summaryrefslogtreecommitdiff
authoralwin <alwin>2004-03-02 12:21:11 (UTC)
committer alwin <alwin>2004-03-02 12:21:11 (UTC)
commitb6b1c97559c0ed9f2e33632272426bf98f289232 (patch) (unidiff)
treed3a9987704770cdf5eb14e1136f6e3ecb2f36a04
parent0d59c780513da78033f4d9040475dee9db0256d4 (diff)
downloadopie-b6b1c97559c0ed9f2e33632272426bf98f289232.zip
opie-b6b1c97559c0ed9f2e33632272426bf98f289232.tar.gz
opie-b6b1c97559c0ed9f2e33632272426bf98f289232.tar.bz2
applied the patch generated by the optimize_connect script from
TT.
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--libqtaux/ocolorbutton.cpp2
-rw-r--r--libqtaux/ocolorpopupmenu.cpp2
-rw-r--r--library/datebookmonth.cpp28
-rw-r--r--library/fileselector.cpp16
-rw-r--r--library/finddialog.cpp12
-rw-r--r--library/findwidget_p.cpp4
-rw-r--r--library/ir.cpp4
-rw-r--r--library/network.cpp4
-rw-r--r--library/qcopenvelope_qws.cpp4
-rw-r--r--library/qpeapplication.cpp12
-rw-r--r--library/qpedialog.cpp4
-rw-r--r--library/storage.cpp4
-rw-r--r--library/timestring.cpp2
-rw-r--r--library/tzselect.cpp8
-rw-r--r--noncore/applets/memoryapplet/swapfile.cpp4
-rw-r--r--noncore/applets/notesapplet/notes.cpp8
-rw-r--r--noncore/applets/wirelessapplet/wireless.cpp8
-rw-r--r--noncore/applets/zkbapplet/zkbwidget.cpp4
-rw-r--r--noncore/apps/advancedfm/advancedfm.cpp4
-rw-r--r--noncore/apps/advancedfm/advancedfmData.cpp28
-rw-r--r--noncore/apps/advancedfm/advancedfmMenu.cpp10
-rw-r--r--noncore/apps/advancedfm/output.cpp18
-rw-r--r--noncore/apps/checkbook/checkbook.cpp18
-rw-r--r--noncore/apps/checkbook/listedit.cpp6
-rw-r--r--noncore/apps/checkbook/mainwindow.cpp2
-rw-r--r--noncore/apps/checkbook/password.cpp2
-rw-r--r--noncore/apps/checkbook/transaction.cpp14
-rw-r--r--noncore/apps/confedit/mainwindow.cpp4
-rw-r--r--noncore/apps/odict/odict.cpp2
-rw-r--r--noncore/apps/opie-bartender/bartender.cpp6
-rw-r--r--noncore/apps/opie-bartender/searchresults.cpp2
-rw-r--r--noncore/apps/opie-console/btconfigwidget.cpp4
-rw-r--r--noncore/apps/opie-console/dialdialog.cpp2
-rw-r--r--noncore/apps/opie-console/emulation_handler.cpp8
-rw-r--r--noncore/apps/opie-console/emulation_layer.cpp24
-rw-r--r--noncore/apps/opie-console/function_keyboard.cpp10
-rw-r--r--noncore/apps/opie-console/io_bt.cpp4
-rw-r--r--noncore/apps/opie-console/io_irda.cpp4
-rw-r--r--noncore/apps/opie-console/mainwindow.cpp8
-rw-r--r--noncore/apps/opie-console/profileeditordialog.cpp6
-rw-r--r--noncore/apps/opie-console/session.cpp4
-rw-r--r--noncore/apps/opie-console/sz_transfer.cpp18
-rw-r--r--noncore/apps/opie-console/test/senderui.cpp2
-rw-r--r--noncore/apps/opie-console/transferdialog.cpp12
-rw-r--r--noncore/apps/opie-reader/QTReaderApp.cpp24
-rw-r--r--noncore/apps/opie-reader/fileBrowser.cpp8
-rw-r--r--noncore/apps/opie-sheet/mainwindow.cpp12
-rw-r--r--noncore/apps/opie-sheet/sheet.cpp4
-rw-r--r--noncore/apps/opie-write/mainwindow.cpp24
-rw-r--r--noncore/apps/opie-write/qtextedit.cpp4
-rwxr-xr-xnoncore/apps/qashmoney/accountdisplay.cpp22
-rwxr-xr-xnoncore/apps/qashmoney/budgetdisplay.cpp20
-rwxr-xr-xnoncore/apps/qashmoney/calculator.cpp24
-rwxr-xr-xnoncore/apps/qashmoney/datepicker.cpp6
-rwxr-xr-xnoncore/apps/qashmoney/memorydialog.cpp6
-rwxr-xr-xnoncore/apps/qashmoney/newaccount.cpp8
-rwxr-xr-xnoncore/apps/qashmoney/newtransaction.cpp8
-rwxr-xr-xnoncore/apps/qashmoney/preferencedialogs.cpp20
-rwxr-xr-xnoncore/apps/qashmoney/qashmoney.cpp20
-rwxr-xr-xnoncore/apps/qashmoney/transactiondisplay.cpp18
-rwxr-xr-xnoncore/apps/qashmoney/transferdialog.cpp2
-rw-r--r--noncore/apps/tableviewer/tableviewer.cpp8
-rw-r--r--noncore/apps/tableviewer/ui/commonwidgets.cpp2
-rw-r--r--noncore/apps/tableviewer/ui/tvbrowseview.cpp4
-rw-r--r--noncore/apps/tableviewer/ui/tvfilterview.cpp2
-rw-r--r--noncore/apps/tableviewer/ui/tvlistview.cpp4
-rw-r--r--noncore/apps/tinykate/libkate/document/katedialogs.cpp6
-rw-r--r--noncore/apps/tinykate/libkate/document/katedocument.cpp2
-rw-r--r--noncore/apps/tinykate/libkate/view/kateviewdialog.cpp6
-rw-r--r--noncore/apps/tinykate/tinykate.cpp2
-rw-r--r--noncore/apps/zsafe/scqtfiledlg.cpp12
-rw-r--r--noncore/apps/zsafe/zsafe.cpp20
-rw-r--r--noncore/comm/keypebble/krfbcanvas.cpp4
-rw-r--r--noncore/comm/keypebble/krfbconnection.cpp6
-rw-r--r--noncore/comm/keypebble/krfblogin.cpp4
-rw-r--r--noncore/comm/keypebble/kvnc.cpp12
-rw-r--r--noncore/games/bounce/game.cpp12
-rw-r--r--noncore/games/buzzword/buzzword.cpp2
-rw-r--r--noncore/games/kpacman/kpacman.cpp4
-rw-r--r--noncore/games/oyatzee/oyatzee.cpp4
-rw-r--r--noncore/multimedia/camera/gui/mainwindow.cpp4
-rw-r--r--noncore/multimedia/opieplayer2/audiowidget.cpp2
-rw-r--r--noncore/multimedia/opieplayer2/mediaplayer.cpp6
-rw-r--r--noncore/multimedia/opieplayer2/mediawidget.cpp12
-rw-r--r--noncore/multimedia/opieplayer2/playlistwidget.cpp88
-rw-r--r--noncore/multimedia/opieplayer2/playlistwidgetgui.cpp2
-rw-r--r--noncore/multimedia/opieplayer2/threadutil.cpp2
-rw-r--r--noncore/multimedia/opieplayer2/videowidget.cpp4
-rw-r--r--noncore/multimedia/opieplayer2/xinecontrol.cpp14
-rw-r--r--noncore/multimedia/opierec/qtrec.cpp30
-rw-r--r--noncore/multimedia/powerchord/powerchordbase.cpp14
-rw-r--r--noncore/multimedia/showimg/ImageFileSelector.cpp14
-rw-r--r--noncore/multimedia/showimg/showimg.cpp4
-rw-r--r--noncore/net/linphone/qlinphone.cpp2
-rw-r--r--noncore/net/mail/accountview.cpp8
-rw-r--r--noncore/net/mail/composemail.cpp2
-rw-r--r--noncore/net/mail/editaccounts.cpp18
-rw-r--r--noncore/net/mail/libmailwrapper/mhwrapper.cpp8
-rw-r--r--noncore/net/mail/libmailwrapper/smtpwrapper.cpp2
-rw-r--r--noncore/net/mail/mainwindow.cpp16
-rw-r--r--noncore/net/mail/viewmail.cpp6
-rw-r--r--noncore/net/opieftp/opieftp.cpp46
-rw-r--r--noncore/net/opieirc/ircchanneltab.cpp2
-rw-r--r--noncore/net/opieirc/ircsession.cpp2
-rw-r--r--noncore/net/opieirc/mainwindow.cpp4
-rw-r--r--noncore/net/opietooth/lib/startdunconnection.cpp8
-rw-r--r--noncore/net/opietooth/lib/startpanconnection.cpp16
-rw-r--r--noncore/net/opietooth/manager/bluebase.cpp32
-rw-r--r--noncore/net/opietooth/manager/obexdialog.cpp2
-rw-r--r--noncore/net/opietooth/manager/pppdialog.cpp6
-rw-r--r--noncore/net/opietooth/manager/scandialog.cpp4
-rw-r--r--noncore/settings/appearance2/appearance.cpp24
-rw-r--r--noncore/settings/appearance2/sample.cpp4
-rw-r--r--noncore/settings/aqpkg/inputdlg.cpp4
-rw-r--r--noncore/settings/aqpkg/installdlgimpl.cpp8
-rw-r--r--noncore/settings/aqpkg/ipkg.cpp10
-rw-r--r--noncore/settings/aqpkg/mainwin.cpp26
-rw-r--r--noncore/settings/aqpkg/settingsimpl.cpp4
-rw-r--r--noncore/settings/backup/backuprestore.cpp4
-rw-r--r--noncore/settings/netsystemtime/mainwindow.cpp14
-rw-r--r--noncore/settings/netsystemtime/settingstabwidget.cpp4
-rw-r--r--noncore/settings/netsystemtime/timetabwidget.cpp2
-rw-r--r--noncore/settings/networksettings/interfaces/interfaceinformationimp.cpp4
-rw-r--r--noncore/settings/networksettings/mainwindowimp.cpp14
-rw-r--r--noncore/settings/networksettings/ppp/edit.cpp8
-rw-r--r--noncore/settings/networksettings/ppp/general.cpp4
-rw-r--r--noncore/settings/networksettings/ppp/kpppwidget.cpp12
-rw-r--r--noncore/settings/networksettings/ppp/pppdargs.cpp4
-rw-r--r--noncore/settings/networksettings/wlan/wlanimp2.cpp2
-rw-r--r--noncore/settings/packagemanager/filterdlg.cpp2
-rw-r--r--noncore/settings/packagemanager/mainwindow.cpp8
-rw-r--r--noncore/settings/packagemanager/oipkg.cpp16
-rw-r--r--noncore/settings/sound/soundsettings.cpp20
-rw-r--r--noncore/settings/sysinfo/benchmarkinfo.cpp2
-rw-r--r--noncore/settings/sysinfo/modulesinfo.cpp4
-rw-r--r--noncore/settings/sysinfo/processinfo.cpp4
-rw-r--r--noncore/settings/tabmanager/tabmanager.cpp4
-rw-r--r--noncore/settings/usermanager/usermanager.cpp2
-rw-r--r--noncore/styles/liquid/liquidset.cpp6
-rw-r--r--noncore/todayplugins/fortune/fortunepluginwidget.cpp4
-rw-r--r--noncore/todayplugins/stockticker/stockticker/helpwindow.cpp16
-rw-r--r--noncore/todayplugins/stockticker/stockticker/inputDialog.cpp2
-rw-r--r--noncore/todayplugins/weather/weatherpluginwidget.cpp2
-rw-r--r--noncore/tools/calc2/calc.cpp4
-rw-r--r--noncore/tools/calculator/calculatorimpl.cpp2
-rw-r--r--noncore/tools/clock/clock.cpp8
-rw-r--r--noncore/tools/formatter/formatter.cpp6
-rw-r--r--noncore/tools/remote/buttondialog.cpp4
-rw-r--r--noncore/tools/remote/recorddialog.cpp6
-rw-r--r--noncore/tools/remote/topgroup.cpp2
-rw-r--r--noncore/tools/remote/topgroupconf.cpp4
-rw-r--r--noncore/unsupported/filebrowser/filebrowser.cpp12
-rw-r--r--noncore/unsupported/gsmtool/gsmtool.cpp4
-rw-r--r--noncore/unsupported/mail2/bend/bend.cpp4
-rw-r--r--noncore/unsupported/mail2/composer.cpp8
-rw-r--r--noncore/unsupported/mail2/folderwidget.cpp24
-rw-r--r--noncore/unsupported/mail2/libmail/imaphandler.cpp6
-rw-r--r--noncore/unsupported/mail2/listviewplus.cpp4
-rw-r--r--noncore/unsupported/mail2/mailtable.cpp12
-rw-r--r--noncore/unsupported/mail2/mainwindow.cpp14
-rw-r--r--noncore/unsupported/mail2/searchdiag.cpp14
-rw-r--r--noncore/unsupported/mail2/viewmail.cpp4
-rw-r--r--noncore/unsupported/mailit/addatt.cpp4
-rw-r--r--noncore/unsupported/mailit/emailclient.cpp32
-rw-r--r--noncore/unsupported/mailit/emailhandler.cpp22
-rw-r--r--noncore/unsupported/mailit/mailitwindow.cpp36
-rw-r--r--noncore/unsupported/oipkg/mainwindow.cpp8
-rw-r--r--noncore/unsupported/oipkg/packagelistitem.cpp8
-rw-r--r--noncore/unsupported/oipkg/packagelistview.cpp8
-rw-r--r--noncore/unsupported/oipkg/pksettings.cpp2
-rw-r--r--noncore/unsupported/qpdf/qbusybar.cpp2
-rw-r--r--noncore/unsupported/qpdf/qpdf.cpp30
-rw-r--r--x11/libqpe-x11/qpe/qpeapplication.cpp8
-rw-r--r--x11/libqpe-x11/qt/qcopchannel_qws.cpp4
174 files changed, 812 insertions, 816 deletions
diff --git a/libqtaux/ocolorbutton.cpp b/libqtaux/ocolorbutton.cpp
index fd3f963..9e41d93 100644
--- a/libqtaux/ocolorbutton.cpp
+++ b/libqtaux/ocolorbutton.cpp
@@ -1,147 +1,147 @@
1/* 1/*
2 This file is part of the Opie Project 2 This file is part of the Opie Project
3 Copyright (C) Robert Griebl <sandman@handhelds.org> 3 Copyright (C) Robert Griebl <sandman@handhelds.org>
4 =. Copyright (C) The Opie Team <opie-devel@handhelds.org> 4 =. Copyright (C) The Opie Team <opie-devel@handhelds.org>
5 .=l. 5 .=l.
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This program is free software; you can 7 _;:,     .>    :=|. This program is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU Library General Public 9:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This program is distributed in the hope that 14    .i_,=:_.      -<s. This program is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
19..}^=.=       =       ; Library General Public License for more 19..}^=.=       =       ; Library General Public License for more
20++=   -.     .`     .: details. 20++=   -.     .`     .: details.
21 :     =  ...= . :.=- 21 :     =  ...= . :.=-
22 -.   .:....=;==+<; You should have received a copy of the GNU 22 -.   .:....=;==+<; You should have received a copy of the GNU
23  -_. . .   )=.  = Library General Public License along with 23  -_. . .   )=.  = Library General Public License along with
24    --        :-=` this library; see the file COPYING.LIB. 24    --        :-=` this library; see the file COPYING.LIB.
25 If not, write to the Free Software Foundation, 25 If not, write to the Free Software Foundation,
26 Inc., 59 Temple Place - Suite 330, 26 Inc., 59 Temple Place - Suite 330,
27 Boston, MA 02111-1307, USA. 27 Boston, MA 02111-1307, USA.
28*/ 28*/
29 29
30#include "ocolorpopupmenu.h" 30#include "ocolorpopupmenu.h"
31#include "ocolorbutton.h" 31#include "ocolorbutton.h"
32 32
33/* OPIE */ 33/* OPIE */
34 34
35/* QT */ 35/* QT */
36#include <qimage.h> 36#include <qimage.h>
37 37
38using namespace Opie; 38using namespace Opie;
39 39
40struct OColorButtonPrivate 40struct OColorButtonPrivate
41{ 41{
42 QPopupMenu *m_menu; 42 QPopupMenu *m_menu;
43 QColor m_color; 43 QColor m_color;
44}; 44};
45 45
46/** 46/**
47 * This concstructs a Color Button with @param color as the start color 47 * This concstructs a Color Button with @param color as the start color
48 * It'll use a OColorPopupMenu internally 48 * It'll use a OColorPopupMenu internally
49 * 49 *
50 * @param parent The parent of the Color Button 50 * @param parent The parent of the Color Button
51 * @param color The color from where to start on 51 * @param color The color from where to start on
52 * @param name @see QObject 52 * @param name @see QObject
53 */ 53 */
54OColorButton::OColorButton ( QWidget *parent, const QColor &color, const char *name ) 54OColorButton::OColorButton ( QWidget *parent, const QColor &color, const char *name )
55 : QPushButton ( parent, name ) 55 : QPushButton ( parent, name )
56{ 56{
57 d = new OColorButtonPrivate; 57 d = new OColorButtonPrivate;
58 58
59 d-> m_menu = new OColorPopupMenu ( color, 0, 0 ); 59 d-> m_menu = new OColorPopupMenu ( color, 0, 0 );
60 setPopup ( d-> m_menu ); 60 setPopup ( d-> m_menu );
61 //setPopupDelay ( 0 ); 61 //setPopupDelay ( 0 );
62 connect ( d-> m_menu, SIGNAL( colorSelected ( const QColor & )), this, SLOT( updateColor ( const QColor & ))); 62 connect ( d-> m_menu, SIGNAL( colorSelected(const QColor&)), this, SLOT( updateColor(const QColor&)));
63 63
64 updateColor ( color ); 64 updateColor ( color );
65 65
66 QSize s = sizeHint ( ) + QSize ( 12, 0 ); 66 QSize s = sizeHint ( ) + QSize ( 12, 0 );
67 setMinimumSize ( s ); 67 setMinimumSize ( s );
68 setMaximumSize ( s. width ( ) * 2, s. height ( )); 68 setMaximumSize ( s. width ( ) * 2, s. height ( ));
69} 69}
70 70
71/** 71/**
72 * This destructs the object 72 * This destructs the object
73 */ 73 */
74OColorButton::~OColorButton ( ) 74OColorButton::~OColorButton ( )
75{ 75{
76 delete d; 76 delete d;
77} 77}
78 78
79/** 79/**
80 * @return Returns the current color of the button 80 * @return Returns the current color of the button
81 */ 81 */
82QColor OColorButton::color ( ) const 82QColor OColorButton::color ( ) const
83{ 83{
84 return d-> m_color; 84 return d-> m_color;
85} 85}
86 86
87/** 87/**
88 * This method sets the color of the button 88 * This method sets the color of the button
89 * @param c The color to be set. 89 * @param c The color to be set.
90 */ 90 */
91void OColorButton::setColor ( const QColor &c ) 91void OColorButton::setColor ( const QColor &c )
92{ 92{
93 updateColor ( c ); 93 updateColor ( c );
94} 94}
95 95
96/** 96/**
97 * @internal 97 * @internal
98 */ 98 */
99void OColorButton::updateColor ( const QColor &c ) 99void OColorButton::updateColor ( const QColor &c )
100{ 100{
101 d-> m_color = c; 101 d-> m_color = c;
102 102
103 QImage img ( 16, 16, 32 ); 103 QImage img ( 16, 16, 32 );
104 img. fill ( 0 ); 104 img. fill ( 0 );
105 105
106 int r, g, b; 106 int r, g, b;
107 c. rgb ( &r, &g, &b ); 107 c. rgb ( &r, &g, &b );
108 108
109 int w = img. width ( ); 109 int w = img. width ( );
110 int h = img. height ( ); 110 int h = img. height ( );
111 111
112 int dx = w * 20 / 100; // 15% 112 int dx = w * 20 / 100; // 15%
113 int dy = h * 20 / 100; 113 int dy = h * 20 / 100;
114 114
115 for ( int y = 0; y < h; y++ ) 115 for ( int y = 0; y < h; y++ )
116 { 116 {
117 for ( int x = 0; x < w; x++ ) 117 for ( int x = 0; x < w; x++ )
118 { 118 {
119 double alpha = 1.0; 119 double alpha = 1.0;
120 120
121 if ( x < dx ) 121 if ( x < dx )
122 alpha *= ( double ( x + 1 ) / dx ); 122 alpha *= ( double ( x + 1 ) / dx );
123 else if ( x >= w - dx ) 123 else if ( x >= w - dx )
124 alpha *= ( double ( w - x ) / dx ); 124 alpha *= ( double ( w - x ) / dx );
125 if ( y < dy ) 125 if ( y < dy )
126 alpha *= ( double ( y + 1 ) / dy ); 126 alpha *= ( double ( y + 1 ) / dy );
127 else if ( y >= h - dy ) 127 else if ( y >= h - dy )
128 alpha *= ( double ( h - y ) / dy ); 128 alpha *= ( double ( h - y ) / dy );
129 129
130 int a = int ( alpha * 255.0 ); 130 int a = int ( alpha * 255.0 );
131 if ( a < 0 ) 131 if ( a < 0 )
132 a = 0; 132 a = 0;
133 if ( a > 255 ) 133 if ( a > 255 )
134 a = 255; 134 a = 255;
135 135
136 img. setPixel ( x, y, qRgba ( r, g, b, a )); 136 img. setPixel ( x, y, qRgba ( r, g, b, a ));
137 } 137 }
138 } 138 }
139 img. setAlphaBuffer ( true ); 139 img. setAlphaBuffer ( true );
140 140
141 QPixmap pix; 141 QPixmap pix;
142 pix. convertFromImage ( img ); 142 pix. convertFromImage ( img );
143 setPixmap ( pix ); 143 setPixmap ( pix );
144 144
145 emit colorSelected ( c ); 145 emit colorSelected ( c );
146} 146}
147 147
diff --git a/libqtaux/ocolorpopupmenu.cpp b/libqtaux/ocolorpopupmenu.cpp
index c5b2b88..4da2a0e 100644
--- a/libqtaux/ocolorpopupmenu.cpp
+++ b/libqtaux/ocolorpopupmenu.cpp
@@ -1,175 +1,175 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002 S. Prud'homme <prudhomme@laposte.net> 4              Copyright (c) 2002 S. Prud'homme <prudhomme@laposte.net>
5              Dan Williams <williamsdr@acm.org> 5              Dan Williams <williamsdr@acm.org>
6 =. 6 =.
7 .=l. 7 .=l.
8           .>+-= 8           .>+-=
9 _;:,     .>    :=|. This program is free software; you can 9 _;:,     .>    :=|. This program is free software; you can
10.> <`_,   >  .   <= redistribute it and/or modify it under 10.> <`_,   >  .   <= redistribute it and/or modify it under
11:`=1 )Y*s>-.--   : the terms of the GNU Library General Public 11:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
12.="- .-=="i,     .._ License as published by the Free Software 12.="- .-=="i,     .._ License as published by the Free Software
13 - .   .-<_>     .<> Foundation; either version 2 of the License, 13 - .   .-<_>     .<> Foundation; either version 2 of the License,
14     ._= =}       : or (at your option) any later version. 14     ._= =}       : or (at your option) any later version.
15    .%`+i>       _;_. 15    .%`+i>       _;_.
16    .i_,=:_.      -<s. This program is distributed in the hope that 16    .i_,=:_.      -<s. This program is distributed in the hope that
17     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 17     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
18    : ..    .:,     . . . without even the implied warranty of 18    : ..    .:,     . . . without even the implied warranty of
19    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 19    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
20  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 20  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
21..}^=.=       =       ; Library General Public License for more 21..}^=.=       =       ; Library General Public License for more
22++=   -.     .`     .: details. 22++=   -.     .`     .: details.
23 :     =  ...= . :.=- 23 :     =  ...= . :.=-
24 -.   .:....=;==+<; You should have received a copy of the GNU 24 -.   .:....=;==+<; You should have received a copy of the GNU
25  -_. . .   )=.  = Library General Public License along with 25  -_. . .   )=.  = Library General Public License along with
26    --        :-=` this library; see the file COPYING.LIB. 26    --        :-=` this library; see the file COPYING.LIB.
27 If not, write to the Free Software Foundation, 27 If not, write to the Free Software Foundation,
28 Inc., 59 Temple Place - Suite 330, 28 Inc., 59 Temple Place - Suite 330,
29 Boston, MA 02111-1307, USA. 29 Boston, MA 02111-1307, USA.
30 30
31*/ 31*/
32 32
33#include "ocolorpopupmenu.h" 33#include "ocolorpopupmenu.h"
34#include "qcolordialog.h" 34#include "qcolordialog.h"
35 35
36/* QT */ 36/* QT */
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qpainter.h> 38#include <qpainter.h>
39 39
40using namespace Opie; 40using namespace Opie;
41 41
42OColorPanelButton::OColorPanelButton( const QColor& color, QWidget* parent, const char* name ) 42OColorPanelButton::OColorPanelButton( const QColor& color, QWidget* parent, const char* name )
43 : QFrame( parent, name ) 43 : QFrame( parent, name )
44{ 44{
45 m_color = color; 45 m_color = color;
46 46
47 setFixedSize( 16, 16 ); 47 setFixedSize( 16, 16 );
48 setActive( FALSE ); 48 setActive( FALSE );
49} 49}
50 50
51OColorPanelButton::~OColorPanelButton() 51OColorPanelButton::~OColorPanelButton()
52{ 52{
53} 53}
54 54
55void OColorPanelButton::setActive( bool active ) 55void OColorPanelButton::setActive( bool active )
56{ 56{
57 m_active = active; 57 m_active = active;
58 58
59 if ( m_active ) { 59 if ( m_active ) {
60 setFrameStyle( Panel | Sunken ); 60 setFrameStyle( Panel | Sunken );
61 } else { 61 } else {
62 setFrameStyle( NoFrame ); 62 setFrameStyle( NoFrame );
63 } 63 }
64} 64}
65 65
66void OColorPanelButton::enterEvent( QEvent* ) 66void OColorPanelButton::enterEvent( QEvent* )
67{ 67{
68 if ( !m_active ) { 68 if ( !m_active ) {
69 setFrameStyle( Panel | Sunken ); 69 setFrameStyle( Panel | Sunken );
70 } 70 }
71} 71}
72 72
73void OColorPanelButton::leaveEvent( QEvent* ) 73void OColorPanelButton::leaveEvent( QEvent* )
74{ 74{
75 if ( !m_active ) { 75 if ( !m_active ) {
76 setFrameStyle( NoFrame ); 76 setFrameStyle( NoFrame );
77 } 77 }
78} 78}
79 79
80void OColorPanelButton::paintEvent( QPaintEvent* e ) 80void OColorPanelButton::paintEvent( QPaintEvent* e )
81{ 81{
82 QFrame::paintEvent( e ); 82 QFrame::paintEvent( e );
83 83
84 QPainter painter; 84 QPainter painter;
85 painter.begin( this ); 85 painter.begin( this );
86 painter.fillRect( 2, 2, 12, 12, m_color ); 86 painter.fillRect( 2, 2, 12, 12, m_color );
87 painter.setPen( Qt::black ); 87 painter.setPen( Qt::black );
88 painter.drawRect( 2, 2, 12, 12 ); 88 painter.drawRect( 2, 2, 12, 12 );
89 painter.end(); 89 painter.end();
90} 90}
91 91
92void OColorPanelButton::mouseReleaseEvent( QMouseEvent* ) 92void OColorPanelButton::mouseReleaseEvent( QMouseEvent* )
93{ 93{
94 emit selected( m_color ); 94 emit selected( m_color );
95} 95}
96 96
97OColorPopupMenu::OColorPopupMenu( const QColor& color, QWidget* parent, const char* name ) 97OColorPopupMenu::OColorPopupMenu( const QColor& color, QWidget* parent, const char* name )
98 : QPopupMenu( parent, name ) 98 : QPopupMenu( parent, name )
99{ 99{
100 m_color = color; 100 m_color = color;
101 101
102 colorPanel = new QWidget( this ); 102 colorPanel = new QWidget( this );
103 103
104 colorLayout = new QGridLayout(colorPanel, 5, 6); 104 colorLayout = new QGridLayout(colorPanel, 5, 6);
105 105
106 addColor(QColor(255, 255, 255), 0, 1); 106 addColor(QColor(255, 255, 255), 0, 1);
107 addColor(QColor(192, 192, 192), 0, 2); 107 addColor(QColor(192, 192, 192), 0, 2);
108 addColor(QColor(128, 128, 128), 0, 3); 108 addColor(QColor(128, 128, 128), 0, 3);
109 addColor(QColor(64, 64, 64), 0, 4); 109 addColor(QColor(64, 64, 64), 0, 4);
110 addColor(QColor(0, 0, 0), 0, 5); 110 addColor(QColor(0, 0, 0), 0, 5);
111 111
112 addColor(QColor(255, 0, 0), 1, 0); 112 addColor(QColor(255, 0, 0), 1, 0);
113 addColor(QColor(255, 128, 0), 1, 1); 113 addColor(QColor(255, 128, 0), 1, 1);
114 addColor(QColor(255, 255, 0), 1, 2); 114 addColor(QColor(255, 255, 0), 1, 2);
115 addColor(QColor(128, 255, 0), 1, 3); 115 addColor(QColor(128, 255, 0), 1, 3);
116 addColor(QColor(0, 255, 0), 1, 4); 116 addColor(QColor(0, 255, 0), 1, 4);
117 addColor(QColor(0, 255, 128), 1, 5); 117 addColor(QColor(0, 255, 128), 1, 5);
118 118
119 addColor(QColor(128, 0, 0), 2, 0); 119 addColor(QColor(128, 0, 0), 2, 0);
120 addColor(QColor(128, 64, 0), 2, 1); 120 addColor(QColor(128, 64, 0), 2, 1);
121 addColor(QColor(128, 128, 0), 2, 2); 121 addColor(QColor(128, 128, 0), 2, 2);
122 addColor(QColor(64, 128, 0), 2, 3); 122 addColor(QColor(64, 128, 0), 2, 3);
123 addColor(QColor(0, 128, 0), 2, 4); 123 addColor(QColor(0, 128, 0), 2, 4);
124 addColor(QColor(0, 128, 64), 2, 5); 124 addColor(QColor(0, 128, 64), 2, 5);
125 125
126 addColor(QColor(0, 255, 255), 3, 0); 126 addColor(QColor(0, 255, 255), 3, 0);
127 addColor(QColor(0, 128, 255), 3, 1); 127 addColor(QColor(0, 128, 255), 3, 1);
128 addColor(QColor(0, 0, 255), 3, 2); 128 addColor(QColor(0, 0, 255), 3, 2);
129 addColor(QColor(128, 0, 255), 3, 3); 129 addColor(QColor(128, 0, 255), 3, 3);
130 addColor(QColor(255, 0, 255), 3, 4); 130 addColor(QColor(255, 0, 255), 3, 4);
131 addColor(QColor(255, 0, 128), 3, 5); 131 addColor(QColor(255, 0, 128), 3, 5);
132 132
133 addColor(QColor(0, 128, 128), 4, 0); 133 addColor(QColor(0, 128, 128), 4, 0);
134 addColor(QColor(0, 64, 128), 4, 1); 134 addColor(QColor(0, 64, 128), 4, 1);
135 addColor(QColor(0, 0, 128), 4, 2); 135 addColor(QColor(0, 0, 128), 4, 2);
136 addColor(QColor(64, 0, 128), 4, 3); 136 addColor(QColor(64, 0, 128), 4, 3);
137 addColor(QColor(128, 0, 128), 4, 4); 137 addColor(QColor(128, 0, 128), 4, 4);
138 addColor(QColor(128, 0, 64), 4, 5); 138 addColor(QColor(128, 0, 64), 4, 5);
139 139
140 insertItem( colorPanel ); 140 insertItem( colorPanel );
141 insertSeparator(); 141 insertSeparator();
142 insertItem(tr("More"),this,SLOT( moreColorClicked())); 142 insertItem(tr("More"),this,SLOT( moreColorClicked()));
143 /* 143 /*
144 QAction* chooseColorAction = new QAction( tr( "More" ), tr( "More..." ), 0, colorPanel, "More" ); 144 QAction* chooseColorAction = new QAction( tr( "More" ), tr( "More..." ), 0, colorPanel, "More" );
145 connect( chooseColorAction, SIGNAL( activated() ), this, SLOT( moreColorClicked() ) ); 145 connect( chooseColorAction, SIGNAL( activated() ), this, SLOT( moreColorClicked() ) );
146 chooseColorAction->addTo( this ); 146 chooseColorAction->addTo( this );
147 */ 147 */
148 activateItemAt( 0 ); 148 activateItemAt( 0 );
149} 149}
150 150
151OColorPopupMenu::~OColorPopupMenu() 151OColorPopupMenu::~OColorPopupMenu()
152{ 152{
153} 153}
154 154
155void OColorPopupMenu::addColor( const QColor& color, int row, int col ) 155void OColorPopupMenu::addColor( const QColor& color, int row, int col )
156{ 156{
157 OColorPanelButton* panelButton = new OColorPanelButton( color, colorPanel ); 157 OColorPanelButton* panelButton = new OColorPanelButton( color, colorPanel );
158 connect( panelButton, SIGNAL( selected( const QColor& ) ), this, SLOT( buttonSelected( const QColor& ) ) ); 158 connect( panelButton, SIGNAL( selected(const QColor&) ), this, SLOT( buttonSelected(const QColor&) ) );
159 colorLayout->addWidget( panelButton, row, col ); 159 colorLayout->addWidget( panelButton, row, col );
160} 160}
161 161
162void OColorPopupMenu::buttonSelected( const QColor& color ) 162void OColorPopupMenu::buttonSelected( const QColor& color )
163{ 163{
164 m_color = color; 164 m_color = color;
165 emit colorSelected( color ); 165 emit colorSelected( color );
166 hide(); 166 hide();
167} 167}
168 168
169void OColorPopupMenu::moreColorClicked() 169void OColorPopupMenu::moreColorClicked()
170{ 170{
171 QColor color = QColorDialog::getColor( m_color ); 171 QColor color = QColorDialog::getColor( m_color );
172 m_color = color; 172 m_color = color;
173 emit colorSelected( color ); 173 emit colorSelected( color );
174 hide(); 174 hide();
175} 175}
diff --git a/library/datebookmonth.cpp b/library/datebookmonth.cpp
index 76e022f..421559e 100644
--- a/library/datebookmonth.cpp
+++ b/library/datebookmonth.cpp
@@ -1,762 +1,762 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include "config.h" 20#include "config.h"
21#include "datebookmonth.h" 21#include "datebookmonth.h"
22#include "datebookdb.h" 22#include "datebookdb.h"
23#include "resource.h" 23#include "resource.h"
24#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25 25
26#include <qtoolbutton.h> 26#include <qtoolbutton.h>
27#include <qspinbox.h> 27#include <qspinbox.h>
28#include <qcombobox.h> 28#include <qcombobox.h>
29#include <qvaluestack.h> 29#include <qvaluestack.h>
30#include <qwhatsthis.h> 30#include <qwhatsthis.h>
31 31
32 32
33DateBookMonthHeader::DateBookMonthHeader( QWidget *parent, const char *name ) 33DateBookMonthHeader::DateBookMonthHeader( QWidget *parent, const char *name )
34 : QHBox( parent, name ) 34 : QHBox( parent, name )
35{ 35{
36 setBackgroundMode( PaletteButton ); 36 setBackgroundMode( PaletteButton );
37 37
38 begin = new QToolButton( this ); 38 begin = new QToolButton( this );
39 begin->setFocusPolicy(NoFocus); 39 begin->setFocusPolicy(NoFocus);
40 begin->setPixmap( Resource::loadPixmap( "start" ) ); 40 begin->setPixmap( Resource::loadPixmap( "start" ) );
41 begin->setAutoRaise( TRUE ); 41 begin->setAutoRaise( TRUE );
42 begin->setFixedSize( begin->sizeHint() ); 42 begin->setFixedSize( begin->sizeHint() );
43 QWhatsThis::add( begin, tr("Show January in the selected year") ); 43 QWhatsThis::add( begin, tr("Show January in the selected year") );
44 44
45 back = new QToolButton( this ); 45 back = new QToolButton( this );
46 back->setFocusPolicy(NoFocus); 46 back->setFocusPolicy(NoFocus);
47 back->setPixmap( Resource::loadPixmap( "back" ) ); 47 back->setPixmap( Resource::loadPixmap( "back" ) );
48 back->setAutoRaise( TRUE ); 48 back->setAutoRaise( TRUE );
49 back->setFixedSize( back->sizeHint() ); 49 back->setFixedSize( back->sizeHint() );
50 QWhatsThis::add( back, tr("Show the previous month") ); 50 QWhatsThis::add( back, tr("Show the previous month") );
51 51
52 month = new QComboBox( FALSE, this ); 52 month = new QComboBox( FALSE, this );
53 for ( int i = 0; i < 12; ++i ) 53 for ( int i = 0; i < 12; ++i )
54 month->insertItem( Calendar::nameOfMonth( i + 1 ) ); 54 month->insertItem( Calendar::nameOfMonth( i + 1 ) );
55 55
56 year = new QSpinBox( 1752, 8000, 1, this ); 56 year = new QSpinBox( 1752, 8000, 1, this );
57 57
58 next = new QToolButton( this ); 58 next = new QToolButton( this );
59 next->setFocusPolicy(NoFocus); 59 next->setFocusPolicy(NoFocus);
60 next->setPixmap( Resource::loadPixmap( "forward" ) ); 60 next->setPixmap( Resource::loadPixmap( "forward" ) );
61 next->setAutoRaise( TRUE ); 61 next->setAutoRaise( TRUE );
62 next->setFixedSize( next->sizeHint() ); 62 next->setFixedSize( next->sizeHint() );
63 QWhatsThis::add( next, tr("Show the next month") ); 63 QWhatsThis::add( next, tr("Show the next month") );
64 64
65 end = new QToolButton( this ); 65 end = new QToolButton( this );
66 end->setFocusPolicy(NoFocus); 66 end->setFocusPolicy(NoFocus);
67 end->setPixmap( Resource::loadPixmap( "finish" ) ); 67 end->setPixmap( Resource::loadPixmap( "finish" ) );
68 end->setAutoRaise( TRUE ); 68 end->setAutoRaise( TRUE );
69 end->setFixedSize( end->sizeHint() ); 69 end->setFixedSize( end->sizeHint() );
70 QWhatsThis::add( end, tr("Show December in the selected year") ); 70 QWhatsThis::add( end, tr("Show December in the selected year") );
71 71
72 connect( month, SIGNAL( activated( int ) ), 72 connect( month, SIGNAL( activated(int) ),
73 this, SLOT( updateDate() ) ); 73 this, SLOT( updateDate() ) );
74 connect( year, SIGNAL( valueChanged( int ) ), 74 connect( year, SIGNAL( valueChanged(int) ),
75 this, SLOT( updateDate() ) ); 75 this, SLOT( updateDate() ) );
76 connect( begin, SIGNAL( clicked() ), 76 connect( begin, SIGNAL( clicked() ),
77 this, SLOT( firstMonth() ) ); 77 this, SLOT( firstMonth() ) );
78 connect( end, SIGNAL( clicked() ), 78 connect( end, SIGNAL( clicked() ),
79 this, SLOT( lastMonth() ) ); 79 this, SLOT( lastMonth() ) );
80 connect( back, SIGNAL( clicked() ), 80 connect( back, SIGNAL( clicked() ),
81 this, SLOT( monthBack() ) ); 81 this, SLOT( monthBack() ) );
82 connect( next, SIGNAL( clicked() ), 82 connect( next, SIGNAL( clicked() ),
83 this, SLOT( monthForward() ) ); 83 this, SLOT( monthForward() ) );
84 back->setAutoRepeat( TRUE ); 84 back->setAutoRepeat( TRUE );
85 next->setAutoRepeat( TRUE ); 85 next->setAutoRepeat( TRUE );
86} 86}
87 87
88 88
89DateBookMonthHeader::~DateBookMonthHeader() 89DateBookMonthHeader::~DateBookMonthHeader()
90{ 90{
91 91
92} 92}
93 93
94void DateBookMonthHeader::updateDate() 94void DateBookMonthHeader::updateDate()
95{ 95{
96 emit dateChanged( year->value(), month->currentItem() + 1 ); 96 emit dateChanged( year->value(), month->currentItem() + 1 );
97} 97}
98 98
99void DateBookMonthHeader::firstMonth() 99void DateBookMonthHeader::firstMonth()
100{ 100{
101 emit dateChanged( year->value(), 1 ); 101 emit dateChanged( year->value(), 1 );
102 month->setCurrentItem( 0 ); 102 month->setCurrentItem( 0 );
103} 103}
104 104
105void DateBookMonthHeader::lastMonth() 105void DateBookMonthHeader::lastMonth()
106{ 106{
107 emit dateChanged( year->value(), 12 ); 107 emit dateChanged( year->value(), 12 );
108 month->setCurrentItem( 11 ); 108 month->setCurrentItem( 11 );
109} 109}
110 110
111void DateBookMonthHeader::monthBack() 111void DateBookMonthHeader::monthBack()
112{ 112{
113 if ( month->currentItem() > 0 ) { 113 if ( month->currentItem() > 0 ) {
114 emit dateChanged( year->value(), month->currentItem() ); 114 emit dateChanged( year->value(), month->currentItem() );
115 month->setCurrentItem( month->currentItem() - 1 ); 115 month->setCurrentItem( month->currentItem() - 1 );
116 } else { 116 } else {
117 emit dateChanged( year->value() - 1, 12 ); 117 emit dateChanged( year->value() - 1, 12 );
118 // we have a signal set to a changed value in year so we only need to change 118 // we have a signal set to a changed value in year so we only need to change
119 // year to get the result... 119 // year to get the result...
120 month->setCurrentItem( 11 ); 120 month->setCurrentItem( 11 );
121 year->setValue( year->value() - 1 ); 121 year->setValue( year->value() - 1 );
122 } 122 }
123} 123}
124 124
125void DateBookMonthHeader::monthForward() 125void DateBookMonthHeader::monthForward()
126{ 126{
127 if ( month->currentItem() < 11 ) { 127 if ( month->currentItem() < 11 ) {
128 emit dateChanged( year->value(), month->currentItem() + 2 ); 128 emit dateChanged( year->value(), month->currentItem() + 2 );
129 month->setCurrentItem( month->currentItem() + 1 ); 129 month->setCurrentItem( month->currentItem() + 1 );
130 } else { 130 } else {
131 // we have a signal set to a changed value in year so we only need to change 131 // we have a signal set to a changed value in year so we only need to change
132 // year to get the result... 132 // year to get the result...
133 month->setCurrentItem( 0 ); 133 month->setCurrentItem( 0 );
134 year->setValue( year->value() + 1 ); 134 year->setValue( year->value() + 1 );
135 } 135 }
136} 136}
137 137
138void DateBookMonthHeader::setDate( int y, int m ) 138void DateBookMonthHeader::setDate( int y, int m )
139{ 139{
140 year->setValue( y ); 140 year->setValue( y );
141 month->setCurrentItem( m - 1 ); 141 month->setCurrentItem( m - 1 );
142} 142}
143 143
144//--------------------------------------------------------------------------- 144//---------------------------------------------------------------------------
145 145
146class DateBookMonthTablePrivate 146class DateBookMonthTablePrivate
147{ 147{
148public: 148public:
149 DateBookMonthTablePrivate() {}; 149 DateBookMonthTablePrivate() {};
150 ~DateBookMonthTablePrivate() { mMonthEvents.clear(); }; 150 ~DateBookMonthTablePrivate() { mMonthEvents.clear(); };
151 151
152 QValueList<EffectiveEvent> mMonthEvents; 152 QValueList<EffectiveEvent> mMonthEvents;
153 bool onMonday; 153 bool onMonday;
154}; 154};
155 155
156DateBookMonthTable::DateBookMonthTable( QWidget *parent, const char *name, 156DateBookMonthTable::DateBookMonthTable( QWidget *parent, const char *name,
157 DateBookDB *newDb ) 157 DateBookDB *newDb )
158 : QTable( 6, 7, parent, name ), 158 : QTable( 6, 7, parent, name ),
159 db( newDb ) 159 db( newDb )
160{ 160{
161 d = new DateBookMonthTablePrivate(); 161 d = new DateBookMonthTablePrivate();
162 selYear = -1; 162 selYear = -1;
163 selMonth = -1; 163 selMonth = -1;
164 selDay = -1; 164 selDay = -1;
165 165
166 /* init these as well make valgrind happy and be consistent with Qtopia1.6 -zecke */ 166 /* init these as well make valgrind happy and be consistent with Qtopia1.6 -zecke */
167 year = -1; 167 year = -1;
168 month = -1; 168 month = -1;
169 day = -1; 169 day = -1;
170 170
171 Config cfg( "qpe" ); 171 Config cfg( "qpe" );
172 cfg.setGroup( "Time" ); 172 cfg.setGroup( "Time" );
173 d->onMonday = cfg.readBoolEntry( "MONDAY" ); 173 d->onMonday = cfg.readBoolEntry( "MONDAY" );
174 174
175 horizontalHeader()->setResizeEnabled( FALSE ); 175 horizontalHeader()->setResizeEnabled( FALSE );
176 // we have to do this here... or suffer the consequences later... 176 // we have to do this here... or suffer the consequences later...
177 for ( int i = 0; i < 7; i++ ){ 177 for ( int i = 0; i < 7; i++ ){
178 horizontalHeader()->resizeSection( i, 30 ); 178 horizontalHeader()->resizeSection( i, 30 );
179 setColumnStretchable( i, TRUE ); 179 setColumnStretchable( i, TRUE );
180 } 180 }
181 setupLabels(); 181 setupLabels();
182 182
183 verticalHeader()->hide(); 183 verticalHeader()->hide();
184 setLeftMargin( 0 ); 184 setLeftMargin( 0 );
185 for ( int i = 0; i < 6; ++i ) 185 for ( int i = 0; i < 6; ++i )
186 setRowStretchable( i, TRUE ); 186 setRowStretchable( i, TRUE );
187 187
188 setSelectionMode( NoSelection ); 188 setSelectionMode( NoSelection );
189 189
190 connect( this, SIGNAL( clicked( int, int, int, const QPoint & ) ), 190 connect( this, SIGNAL( clicked(int,int,int,const QPoint&) ),
191 this, SLOT( dayClicked( int, int ) ) ); 191 this, SLOT( dayClicked(int,int) ) );
192 connect( this, SIGNAL( currentChanged( int, int ) ), 192 connect( this, SIGNAL( currentChanged(int,int) ),
193 this, SLOT( dragDay( int, int ) ) ); 193 this, SLOT( dragDay(int,int) ) );
194 setVScrollBarMode( AlwaysOff ); 194 setVScrollBarMode( AlwaysOff );
195 setHScrollBarMode( AlwaysOff ); 195 setHScrollBarMode( AlwaysOff );
196} 196}
197 197
198DateBookMonthTable::~DateBookMonthTable() 198DateBookMonthTable::~DateBookMonthTable()
199{ 199{
200 monthsEvents.clear(); 200 monthsEvents.clear();
201 delete d; 201 delete d;
202} 202}
203 203
204void DateBookMonthTable::setDate(int y, int m, int d) 204void DateBookMonthTable::setDate(int y, int m, int d)
205{ 205{
206 if (month == m && year == y) { 206 if (month == m && year == y) {
207 if ( selYear == -1 ) 207 if ( selYear == -1 )
208 year = selYear; 208 year = selYear;
209 if ( selMonth == -1 ) 209 if ( selMonth == -1 )
210 month = selMonth; 210 month = selMonth;
211 int r1, c1, r2, c2; 211 int r1, c1, r2, c2;
212 findDay(selDay, r1, c1); 212 findDay(selDay, r1, c1);
213 selDay = day = d; 213 selDay = day = d;
214 findDay(selDay, r2, c2); 214 findDay(selDay, r2, c2);
215 setCurrentCell( r2, c2 ); 215 setCurrentCell( r2, c2 );
216 //updateCell(r1,c1); 216 //updateCell(r1,c1);
217 //updateCell(r2,c2); 217 //updateCell(r2,c2);
218 } else { 218 } else {
219 selYear = year = y; 219 selYear = year = y;
220 selMonth = month = m; 220 selMonth = month = m;
221 selDay = day = d; 221 selDay = day = d;
222 setupTable(); 222 setupTable();
223 } 223 }
224} 224}
225 225
226void DateBookMonthTable::redraw() 226void DateBookMonthTable::redraw()
227{ 227{
228 setupLabels(); 228 setupLabels();
229 setupTable(); 229 setupTable();
230} 230}
231 231
232void DateBookMonthTable::setWeekStart( bool onMonday ) 232void DateBookMonthTable::setWeekStart( bool onMonday )
233{ 233{
234 d->onMonday = onMonday; 234 d->onMonday = onMonday;
235 setupLabels(); 235 setupLabels();
236 setupTable(); 236 setupTable();
237} 237}
238 238
239void DateBookMonthTable::setupTable() 239void DateBookMonthTable::setupTable()
240{ 240{
241 QValueList<Calendar::Day> days = Calendar::daysOfMonth( year, month, d->onMonday ); 241 QValueList<Calendar::Day> days = Calendar::daysOfMonth( year, month, d->onMonday );
242 QValueList<Calendar::Day>::Iterator it = days.begin(); 242 QValueList<Calendar::Day>::Iterator it = days.begin();
243 int row = 0, col = 0; 243 int row = 0, col = 0;
244 int crow = 0; 244 int crow = 0;
245 int ccol = 0; 245 int ccol = 0;
246 for ( ; it != days.end(); ++it ) { 246 for ( ; it != days.end(); ++it ) {
247 DayItemMonth *i = (DayItemMonth *)item( row, col ); 247 DayItemMonth *i = (DayItemMonth *)item( row, col );
248 if ( !i ) { 248 if ( !i ) {
249 i = new DayItemMonth( this, QTableItem::Never, "" ); 249 i = new DayItemMonth( this, QTableItem::Never, "" );
250 setItem( row, col, i ); 250 setItem( row, col, i );
251 } 251 }
252 Calendar::Day calDay = *it; 252 Calendar::Day calDay = *it;
253 i->clearEffEvents(); 253 i->clearEffEvents();
254 i->setDay( calDay.date ); 254 i->setDay( calDay.date );
255 i->setType( calDay.type ); 255 i->setType( calDay.type );
256 if ( i->day() == day && calDay.type == Calendar::Day::ThisMonth ) { 256 if ( i->day() == day && calDay.type == Calendar::Day::ThisMonth ) {
257 crow = row; 257 crow = row;
258 ccol = col; 258 ccol = col;
259 } 259 }
260 260
261 updateCell( row, col ); 261 updateCell( row, col );
262 262
263 if ( col == 6 ) { 263 if ( col == 6 ) {
264 ++row; 264 ++row;
265 col = 0; 265 col = 0;
266 } else { 266 } else {
267 ++col; 267 ++col;
268 } 268 }
269 } 269 }
270 setCurrentCell( crow, ccol ); 270 setCurrentCell( crow, ccol );
271 getEvents(); 271 getEvents();
272} 272}
273 273
274void DateBookMonthTable::findDay( int day, int &row, int &col ) 274void DateBookMonthTable::findDay( int day, int &row, int &col )
275{ 275{
276 QDate dtBegin( year, month, 1 ); 276 QDate dtBegin( year, month, 1 );
277 int skips = dtBegin.dayOfWeek(); 277 int skips = dtBegin.dayOfWeek();
278 int effective_day = day + skips - 1; // row/columns begin at 0 278 int effective_day = day + skips - 1; // row/columns begin at 0
279 // make an extra adjustment if we start on Mondays. 279 // make an extra adjustment if we start on Mondays.
280 if ( d->onMonday ) 280 if ( d->onMonday )
281 effective_day--; 281 effective_day--;
282 row = effective_day / 7; 282 row = effective_day / 7;
283 col = effective_day % 7; 283 col = effective_day % 7;
284} 284}
285 285
286void DateBookMonthTable::dayClicked( int row, int col ) 286void DateBookMonthTable::dayClicked( int row, int col )
287{ 287{
288 changeDaySelection( row, col ); 288 changeDaySelection( row, col );
289 emit dateClicked( selYear, selMonth, selDay ); 289 emit dateClicked( selYear, selMonth, selDay );
290} 290}
291 291
292void DateBookMonthTable::dragDay( int row, int col ) 292void DateBookMonthTable::dragDay( int row, int col )
293{ 293{
294 changeDaySelection( row, col ); 294 changeDaySelection( row, col );
295} 295}
296 296
297void DateBookMonthTable::changeDaySelection( int row, int col ) 297void DateBookMonthTable::changeDaySelection( int row, int col )
298{ 298{
299 DayItemMonth *i = (DayItemMonth*)item( row, col ); 299 DayItemMonth *i = (DayItemMonth*)item( row, col );
300 if ( !i ) 300 if ( !i )
301 return; 301 return;
302 switch ( i->type() ) { 302 switch ( i->type() ) {
303 case Calendar::Day::ThisMonth: 303 case Calendar::Day::ThisMonth:
304 selMonth = month; 304 selMonth = month;
305 break; 305 break;
306 case Calendar::Day::PrevMonth: 306 case Calendar::Day::PrevMonth:
307 selMonth = month-1; 307 selMonth = month-1;
308 break; 308 break;
309 default: 309 default:
310 selMonth = month+1; 310 selMonth = month+1;
311 } 311 }
312 312
313 selYear = year; 313 selYear = year;
314 if ( selMonth <= 0 ) { 314 if ( selMonth <= 0 ) {
315 selMonth = 12; 315 selMonth = 12;
316 selYear--; 316 selYear--;
317 } else if ( selMonth > 12 ) { 317 } else if ( selMonth > 12 ) {
318 selMonth = 1; 318 selMonth = 1;
319 selYear++; 319 selYear++;
320 } 320 }
321 selDay = i->day(); 321 selDay = i->day();
322} 322}
323 323
324 324
325void DateBookMonthTable::viewportMouseReleaseEvent( QMouseEvent * ) 325void DateBookMonthTable::viewportMouseReleaseEvent( QMouseEvent * )
326{ 326{
327 dayClicked( currentRow(), currentColumn() ); 327 dayClicked( currentRow(), currentColumn() );
328} 328}
329 329
330void DateBookMonthTable::getEvents() 330void DateBookMonthTable::getEvents()
331{ 331{
332 if ( !db ) 332 if ( !db )
333 return; 333 return;
334 334
335 QDate dtStart( year, month, 1 ); 335 QDate dtStart( year, month, 1 );
336 d->mMonthEvents = db->getEffectiveEvents( dtStart, 336 d->mMonthEvents = db->getEffectiveEvents( dtStart,
337 QDate( year, month, 337 QDate( year, month,
338 dtStart.daysInMonth() ) ); 338 dtStart.daysInMonth() ) );
339 QValueListIterator<EffectiveEvent> it = d->mMonthEvents.begin(); 339 QValueListIterator<EffectiveEvent> it = d->mMonthEvents.begin();
340 // now that the events are sorted, basically go through the list, make 340 // now that the events are sorted, basically go through the list, make
341 // a small list for every day and set it for each item... 341 // a small list for every day and set it for each item...
342 // clear all the items... 342 // clear all the items...
343 while ( it != d->mMonthEvents.end() ) { 343 while ( it != d->mMonthEvents.end() ) {
344 QValueList<EffectiveEvent> dayEvent; 344 QValueList<EffectiveEvent> dayEvent;
345 EffectiveEvent e = *it; 345 EffectiveEvent e = *it;
346 ++it; 346 ++it;
347 dayEvent.append( e ); 347 dayEvent.append( e );
348 while ( it != d->mMonthEvents.end() 348 while ( it != d->mMonthEvents.end()
349 && e.date() == (*it).date() ) { 349 && e.date() == (*it).date() ) {
350 dayEvent.append( *it ); 350 dayEvent.append( *it );
351 ++it; 351 ++it;
352 } 352 }
353 int row, col; 353 int row, col;
354 findDay( e.date().day(), row, col ); 354 findDay( e.date().day(), row, col );
355 DayItemMonth* w = static_cast<DayItemMonth*>( item( row, col ) ); 355 DayItemMonth* w = static_cast<DayItemMonth*>( item( row, col ) );
356 w->setEvents( dayEvent ); 356 w->setEvents( dayEvent );
357 updateCell( row, col ); 357 updateCell( row, col );
358 dayEvent.clear(); 358 dayEvent.clear();
359 } 359 }
360} 360}
361 361
362 362
363void DateBookMonthTable::setupLabels() 363void DateBookMonthTable::setupLabels()
364{ 364{
365 for ( int i = 0; i < 7; ++i ) { 365 for ( int i = 0; i < 7; ++i ) {
366 // horizontalHeader()->resizeSection( i, 30 ); 366 // horizontalHeader()->resizeSection( i, 30 );
367 // setColumnStretchable( i, TRUE ); 367 // setColumnStretchable( i, TRUE );
368 if ( d->onMonday ) 368 if ( d->onMonday )
369 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i + 1 ) ); 369 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i + 1 ) );
370 else { 370 else {
371 if ( i == 0 ) 371 if ( i == 0 )
372 horizontalHeader()->setLabel( i, Calendar::nameOfDay( 7 ) ); 372 horizontalHeader()->setLabel( i, Calendar::nameOfDay( 7 ) );
373 else 373 else
374 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i ) ); 374 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i ) );
375 } 375 }
376 } 376 }
377} 377}
378 378
379 379
380//--------------------------------------------------------------------------- 380//---------------------------------------------------------------------------
381 381
382DateBookMonth::DateBookMonth( QWidget *parent, const char *name, bool ac, 382DateBookMonth::DateBookMonth( QWidget *parent, const char *name, bool ac,
383 DateBookDB *data ) 383 DateBookDB *data )
384 : QVBox( parent, name ), 384 : QVBox( parent, name ),
385 autoClose( ac ) 385 autoClose( ac )
386{ 386{
387 setFocusPolicy(StrongFocus); 387 setFocusPolicy(StrongFocus);
388 year = QDate::currentDate().year(); 388 year = QDate::currentDate().year();
389 month = QDate::currentDate().month(); 389 month = QDate::currentDate().month();
390 day = QDate::currentDate().day(); 390 day = QDate::currentDate().day();
391 header = new DateBookMonthHeader( this, "DateBookMonthHeader" ); 391 header = new DateBookMonthHeader( this, "DateBookMonthHeader" );
392 table = new DateBookMonthTable( this, "DateBookMonthTable", data ); 392 table = new DateBookMonthTable( this, "DateBookMonthTable", data );
393 header->setDate( year, month ); 393 header->setDate( year, month );
394 table->setDate( year, month, QDate::currentDate().day() ); 394 table->setDate( year, month, QDate::currentDate().day() );
395 header->setFocusPolicy(NoFocus); 395 header->setFocusPolicy(NoFocus);
396 table->setFocusPolicy(NoFocus); 396 table->setFocusPolicy(NoFocus);
397 connect( header, SIGNAL( dateChanged( int, int ) ), 397 connect( header, SIGNAL( dateChanged(int,int) ),
398 this, SLOT( setDate( int, int ) ) ); 398 this, SLOT( setDate(int,int) ) );
399 connect( table, SIGNAL( dateClicked( int, int, int ) ), 399 connect( table, SIGNAL( dateClicked(int,int,int) ),
400 this, SLOT( finalDate(int, int, int) ) ); 400 this, SLOT( finalDate(int,int,int) ) );
401 connect( qApp, SIGNAL(weekChanged(bool)), this, 401 connect( qApp, SIGNAL(weekChanged(bool)), this,
402 SLOT(slotWeekChange(bool)) ); 402 SLOT(slotWeekChange(bool)) );
403 table->setFocus(); 403 table->setFocus();
404} 404}
405 405
406DateBookMonth::~DateBookMonth() 406DateBookMonth::~DateBookMonth()
407{ 407{
408 408
409} 409}
410 410
411void DateBookMonth::setDate( int y, int m ) 411void DateBookMonth::setDate( int y, int m )
412{ 412{
413 /* only change the date if this is a different date, 413 /* only change the date if this is a different date,
414 * other wise we may mistakenly overide the day */ 414 * other wise we may mistakenly overide the day */
415 if ( (y != year) || (m != month) ) { 415 if ( (y != year) || (m != month) ) {
416 year = y; 416 year = y;
417 month = m; 417 month = m;
418 QDate nd( y, m, 1 ); 418 QDate nd( y, m, 1 );
419 if ( nd.daysInMonth() < day ) 419 if ( nd.daysInMonth() < day )
420 day = nd.daysInMonth(); 420 day = nd.daysInMonth();
421 table->setDate( year, month, day ); 421 table->setDate( year, month, day );
422 } 422 }
423} 423}
424 424
425void DateBookMonth::setDate( int y, int m, int d ) 425void DateBookMonth::setDate( int y, int m, int d )
426{ 426{
427 header->setDate( y, m); 427 header->setDate( y, m);
428 table->setDate( y, m, d); 428 table->setDate( y, m, d);
429 year = y; 429 year = y;
430 month = m; 430 month = m;
431 day = d; 431 day = d;
432} 432}
433 433
434/* called when we wish to close or pass back the date */ 434/* called when we wish to close or pass back the date */
435void DateBookMonth::finalDate(int y, int m, int d) 435void DateBookMonth::finalDate(int y, int m, int d)
436{ 436{
437 setDate( y, m, d ); 437 setDate( y, m, d );
438 438
439 emit dateClicked(y, m, d); 439 emit dateClicked(y, m, d);
440 // emit dateClicked(QDate(y, m, d).toString()); 440 // emit dateClicked(QDate(y, m, d).toString());
441 441
442 if ( autoClose && parentWidget() ) 442 if ( autoClose && parentWidget() )
443 parentWidget()->close(); 443 parentWidget()->close();
444} 444}
445 445
446void DateBookMonth::setDate( QDate d) 446void DateBookMonth::setDate( QDate d)
447{ 447{
448 setDate(d.year(), d.month(), d.day()); 448 setDate(d.year(), d.month(), d.day());
449} 449}
450 450
451void DateBookMonth::redraw() 451void DateBookMonth::redraw()
452{ 452{
453 table->setDate( year, month, day ); 453 table->setDate( year, month, day );
454 table->redraw(); 454 table->redraw();
455} 455}
456 456
457QDate DateBookMonth::selectedDate() const 457QDate DateBookMonth::selectedDate() const
458{ 458{
459 if ( !table ) 459 if ( !table )
460 return QDate::currentDate(); 460 return QDate::currentDate();
461 int y, m, d; 461 int y, m, d;
462 table->getDate( y, m, d ); 462 table->getDate( y, m, d );
463 return QDate( y, m, d ); 463 return QDate( y, m, d );
464} 464}
465 465
466void DateBookMonth::slotWeekChange( bool startOnMonday ) 466void DateBookMonth::slotWeekChange( bool startOnMonday )
467{ 467{
468 table->setWeekStart( startOnMonday ); 468 table->setWeekStart( startOnMonday );
469} 469}
470 470
471void DateBookMonth::keyPressEvent( QKeyEvent *e ) 471void DateBookMonth::keyPressEvent( QKeyEvent *e )
472{ 472{
473 switch(e->key()) { 473 switch(e->key()) {
474 case Key_Up: 474 case Key_Up:
475 setDate(QDate(year, month, day).addDays(-7)); 475 setDate(QDate(year, month, day).addDays(-7));
476 break; 476 break;
477 case Key_Down: 477 case Key_Down:
478 setDate(QDate(year, month, day).addDays(7)); 478 setDate(QDate(year, month, day).addDays(7));
479 break; 479 break;
480 case Key_Left: 480 case Key_Left:
481 setDate(QDate(year, month, day).addDays(-1)); 481 setDate(QDate(year, month, day).addDays(-1));
482 break; 482 break;
483 case Key_Right: 483 case Key_Right:
484 setDate(QDate(year, month, day).addDays(1)); 484 setDate(QDate(year, month, day).addDays(1));
485 break; 485 break;
486 case Key_Space: 486 case Key_Space:
487 qWarning("space"); 487 qWarning("space");
488 emit dateClicked(year, month, day); 488 emit dateClicked(year, month, day);
489 if ( autoClose && parentWidget() ) 489 if ( autoClose && parentWidget() )
490 parentWidget()->close(); 490 parentWidget()->close();
491 break; 491 break;
492 default: 492 default:
493 qWarning("ignore"); 493 qWarning("ignore");
494 e->ignore(); 494 e->ignore();
495 break; 495 break;
496 } 496 }
497} 497}
498 498
499//--------------------------------------------------------------------------- 499//---------------------------------------------------------------------------
500class DayItemMonthPrivate 500class DayItemMonthPrivate
501{ 501{
502public: 502public:
503 DayItemMonthPrivate() {}; 503 DayItemMonthPrivate() {};
504 ~DayItemMonthPrivate() { mDayEvents.clear(); }; 504 ~DayItemMonthPrivate() { mDayEvents.clear(); };
505 QValueList<EffectiveEvent> mDayEvents; 505 QValueList<EffectiveEvent> mDayEvents;
506}; 506};
507 507
508DayItemMonth::DayItemMonth( QTable *table, EditType et, const QString &t ) 508DayItemMonth::DayItemMonth( QTable *table, EditType et, const QString &t )
509 : QTableItem( table, et, t ) 509 : QTableItem( table, et, t )
510{ 510{
511 d = new DayItemMonthPrivate(); 511 d = new DayItemMonthPrivate();
512} 512}
513 513
514DayItemMonth::~DayItemMonth() 514DayItemMonth::~DayItemMonth()
515{ 515{
516 daysEvents.clear(); 516 daysEvents.clear();
517 delete d; 517 delete d;
518} 518}
519 519
520void DayItemMonth::setEvents( const QValueList<EffectiveEvent> &effEv ) 520void DayItemMonth::setEvents( const QValueList<EffectiveEvent> &effEv )
521{ 521{
522 d->mDayEvents = effEv; 522 d->mDayEvents = effEv;
523} 523}
524 524
525void DayItemMonth::clearEffEvents() 525void DayItemMonth::clearEffEvents()
526{ 526{
527 d->mDayEvents.clear(); 527 d->mDayEvents.clear();
528} 528}
529 529
530void DayItemMonth::paint( QPainter *p, const QColorGroup &cg, 530void DayItemMonth::paint( QPainter *p, const QColorGroup &cg,
531 const QRect &cr, bool selected ) 531 const QRect &cr, bool selected )
532{ 532{
533 p->save(); 533 p->save();
534 534
535 QColorGroup g( cg ); 535 QColorGroup g( cg );
536 g.setBrush( QColorGroup::Base, back ); 536 g.setBrush( QColorGroup::Base, back );
537 g.setColor( QColorGroup::Text, forg ); 537 g.setColor( QColorGroup::Text, forg );
538 if ( selected ) 538 if ( selected )
539 p->setPen( g.highlightedText() ); 539 p->setPen( g.highlightedText() );
540 else 540 else
541 p->setPen( g.text() ); 541 p->setPen( g.text() );
542 542
543 QValueStack<int> normalLine; 543 QValueStack<int> normalLine;
544 QValueStack<int> repeatLine; 544 QValueStack<int> repeatLine;
545 QValueStack<int> travelLine; 545 QValueStack<int> travelLine;
546 546
547 bool normalAllDay = FALSE; 547 bool normalAllDay = FALSE;
548 bool repeatAllDay = FALSE; 548 bool repeatAllDay = FALSE;
549 bool travelAllDay = FALSE; 549 bool travelAllDay = FALSE;
550 550
551 QValueListIterator<EffectiveEvent> itDays = d->mDayEvents.begin(); 551 QValueListIterator<EffectiveEvent> itDays = d->mDayEvents.begin();
552 552
553 for ( ; itDays != d->mDayEvents.end(); ++itDays ) { 553 for ( ; itDays != d->mDayEvents.end(); ++itDays ) {
554 int w = cr.width(); 554 int w = cr.width();
555 Event ev = (*itDays).event(); 555 Event ev = (*itDays).event();
556 556
557 int f = (*itDays).start().hour(); // assume Effective event 557 int f = (*itDays).start().hour(); // assume Effective event
558 int t = (*itDays).end().hour(); // is truncated. 558 int t = (*itDays).end().hour(); // is truncated.
559 559
560 if (ev.isAllDay()) { 560 if (ev.isAllDay()) {
561 if (!ev.hasRepeat()) 561 if (!ev.hasRepeat())
562 normalAllDay = TRUE; 562 normalAllDay = TRUE;
563 else 563 else
564 repeatAllDay = TRUE; 564 repeatAllDay = TRUE;
565 } else { 565 } else {
566 int sLine, eLine; 566 int sLine, eLine;
567 if (f == 0) 567 if (f == 0)
568 sLine = 0; 568 sLine = 0;
569 else if (f < 8 ) 569 else if (f < 8 )
570 sLine = 1; 570 sLine = 1;
571 else if (f >= 17) 571 else if (f >= 17)
572 sLine = w - 4; 572 sLine = w - 4;
573 else { 573 else {
574 sLine = (f - 8) * (w - 8); 574 sLine = (f - 8) * (w - 8);
575 if (sLine) 575 if (sLine)
576 sLine /= 8; 576 sLine /= 8;
577 sLine += 4; 577 sLine += 4;
578 } 578 }
579 if (t == 23) 579 if (t == 23)
580 eLine = w; 580 eLine = w;
581 else if (t < 8) 581 else if (t < 8)
582 eLine = 4; 582 eLine = 4;
583 else if (t >= 17) 583 else if (t >= 17)
584 eLine = w - 1; 584 eLine = w - 1;
585 else { 585 else {
586 eLine = (t - 8) * (w - 8); 586 eLine = (t - 8) * (w - 8);
587 if (eLine) 587 if (eLine)
588 eLine /= 8; 588 eLine /= 8;
589 eLine += 4; 589 eLine += 4;
590 } 590 }
591 if (!ev.hasRepeat()) { 591 if (!ev.hasRepeat()) {
592 normalLine.push(sLine); 592 normalLine.push(sLine);
593 normalLine.push(eLine); 593 normalLine.push(eLine);
594 } else { 594 } else {
595 repeatLine.push(sLine); 595 repeatLine.push(sLine);
596 repeatLine.push(eLine); 596 repeatLine.push(eLine);
597 } 597 }
598 } 598 }
599 } 599 }
600 600
601 // draw the background 601 // draw the background
602 if (normalAllDay || repeatAllDay || travelAllDay) { 602 if (normalAllDay || repeatAllDay || travelAllDay) {
603 p->save(); 603 p->save();
604 604
605 if (normalAllDay) 605 if (normalAllDay)
606 if (repeatAllDay) { 606 if (repeatAllDay) {
607 p->fillRect( 0, 0, cr.width(), cr.height() / 2, 607 p->fillRect( 0, 0, cr.width(), cr.height() / 2,
608 colorNormalLight ); 608 colorNormalLight );
609 p->fillRect( 0, cr.height() / 2, cr.width(), cr.height() / 2, 609 p->fillRect( 0, cr.height() / 2, cr.width(), cr.height() / 2,
610 colorRepeatLight ); 610 colorRepeatLight );
611 } else 611 } else
612 p->fillRect( 0, 0, cr.width(), cr.height(), 612 p->fillRect( 0, 0, cr.width(), cr.height(),
613 colorNormalLight ); 613 colorNormalLight );
614 else if (repeatAllDay) 614 else if (repeatAllDay)
615 p->fillRect( 0, 0, cr.width(), cr.height(), 615 p->fillRect( 0, 0, cr.width(), cr.height(),
616 colorRepeatLight ); 616 colorRepeatLight );
617 } else { 617 } else {
618 p->fillRect( 0, 0, cr.width(), 618 p->fillRect( 0, 0, cr.width(),
619 cr.height(), selected 619 cr.height(), selected
620 ? g.brush( QColorGroup::Highlight ) 620 ? g.brush( QColorGroup::Highlight )
621 : g.brush( QColorGroup::Base ) ); 621 : g.brush( QColorGroup::Base ) );
622 } 622 }
623 623
624 // The lines 624 // The lines
625 // now for the lines. 625 // now for the lines.
626 int h = 5; 626 int h = 5;
627 int y = cr.height() / 2 - h; 627 int y = cr.height() / 2 - h;
628 628
629 while(normalLine.count() >= 2) { 629 while(normalLine.count() >= 2) {
630 int x2 = normalLine.pop(); 630 int x2 = normalLine.pop();
631 int x1 = normalLine.pop(); 631 int x1 = normalLine.pop();
632 if (x2 < x1 + 2) 632 if (x2 < x1 + 2)
633 x2 = x1 + 2; 633 x2 = x1 + 2;
634 p->fillRect(x1, y, x2 - x1, h, colorNormal); 634 p->fillRect(x1, y, x2 - x1, h, colorNormal);
635 } 635 }
636 636
637 y += h; 637 y += h;
638 638
639 while(repeatLine.count() >= 2) { 639 while(repeatLine.count() >= 2) {
640 int x2 = repeatLine.pop(); 640 int x2 = repeatLine.pop();
641 int x1 = repeatLine.pop(); 641 int x1 = repeatLine.pop();
642 if (x2 < x1 + 2) 642 if (x2 < x1 + 2)
643 x2 = x1 + 2; 643 x2 = x1 + 2;
644 p->fillRect(x1, y, x2 - x1, h, colorRepeat); 644 p->fillRect(x1, y, x2 - x1, h, colorRepeat);
645 } 645 }
646 646
647 647
648 // Finally, draw the number. 648 // Finally, draw the number.
649 QFont f = p->font(); 649 QFont f = p->font();
650 f.setPointSize( ( f.pointSize() / 3 ) * 2 ); 650 f.setPointSize( ( f.pointSize() / 3 ) * 2 );
651 p->setFont( f ); 651 p->setFont( f );
652 QFontMetrics fm( f ); 652 QFontMetrics fm( f );
653 p->drawText( 1, 1 + fm.ascent(), QString::number( day() ) ); 653 p->drawText( 1, 1 + fm.ascent(), QString::number( day() ) );
654 654
655 p->restore(); 655 p->restore();
656} 656}
657 657
658 658
659 659
660void DayItemMonth::setType( Calendar::Day::Type t ) 660void DayItemMonth::setType( Calendar::Day::Type t )
661{ 661{
662 switch ( t ) { 662 switch ( t ) {
663 case Calendar::Day::PrevMonth: 663 case Calendar::Day::PrevMonth:
664 case Calendar::Day::NextMonth: 664 case Calendar::Day::NextMonth:
665 back = QBrush( QColor( 224, 224, 224 ) ); 665 back = QBrush( QColor( 224, 224, 224 ) );
666 forg = black; 666 forg = black;
667 break; 667 break;
668 case Calendar::Day::ThisMonth: 668 case Calendar::Day::ThisMonth:
669 back = QBrush( white ); 669 back = QBrush( white );
670 forg = black; 670 forg = black;
671 break; 671 break;
672 } 672 }
673 typ = t; 673 typ = t;
674} 674}
675 675
676 676
677 677
678DateButton::DateButton( bool longDate, QWidget *parent, const char * name ) 678DateButton::DateButton( bool longDate, QWidget *parent, const char * name )
679 :QPushButton( parent, name ) 679 :QPushButton( parent, name )
680{ 680{
681 longFormat = longDate; 681 longFormat = longDate;
682 df = DateFormat('/', DateFormat::MonthDayYear, DateFormat::MonthDayYear); 682 df = DateFormat('/', DateFormat::MonthDayYear, DateFormat::MonthDayYear);
683 setDate( QDate::currentDate() ); 683 setDate( QDate::currentDate() );
684 684
685 connect(this,SIGNAL(pressed()),this,SLOT(pickDate())); 685 connect(this,SIGNAL(pressed()),this,SLOT(pickDate()));
686 686
687 687
688} 688}
689 689
690 690
691void DateButton::pickDate() 691void DateButton::pickDate()
692{ 692{
693 static QPopupMenu *m1 = 0; 693 static QPopupMenu *m1 = 0;
694 static DateBookMonth *picker = 0; 694 static DateBookMonth *picker = 0;
695 if ( !m1 ) { 695 if ( !m1 ) {
696 m1 = new QPopupMenu( this ); 696 m1 = new QPopupMenu( this );
697 picker = new DateBookMonth( m1, 0, TRUE ); 697 picker = new DateBookMonth( m1, 0, TRUE );
698 m1->insertItem( picker ); 698 m1->insertItem( picker );
699 connect( picker, SIGNAL( dateClicked( int, int, int ) ), 699 connect( picker, SIGNAL( dateClicked(int,int,int) ),
700 this, SLOT( setDate( int, int, int ) ) ); 700 this, SLOT( setDate(int,int,int) ) );
701 connect( picker, SIGNAL( dateClicked( int, int, int ) ), 701 connect( picker, SIGNAL( dateClicked(int,int,int) ),
702 this, SIGNAL( dateSelected( int, int, int ) ) ); 702 this, SIGNAL( dateSelected(int,int,int) ) );
703 connect( m1, SIGNAL( aboutToHide() ), 703 connect( m1, SIGNAL( aboutToHide() ),
704 this, SLOT( gotHide() ) ); 704 this, SLOT( gotHide() ) );
705 } 705 }
706 picker->slotWeekChange( weekStartsMonday ); 706 picker->slotWeekChange( weekStartsMonday );
707 picker->setDate( currDate.year(), currDate.month(), currDate.day() ); 707 picker->setDate( currDate.year(), currDate.month(), currDate.day() );
708 m1->popup(mapToGlobal(QPoint(0,height()))); 708 m1->popup(mapToGlobal(QPoint(0,height())));
709 picker->setFocus(); 709 picker->setFocus();
710} 710}
711 711
712 712
713void DateButton::gotHide() 713void DateButton::gotHide()
714{ 714{
715 // we have to redo the button... 715 // we have to redo the button...
716 setDown( false ); 716 setDown( false );
717} 717}
718 718
719 719
720// void dateSelected( int year, int month, int day ); 720// void dateSelected( int year, int month, int day );
721 721
722void DateButton::setWeekStartsMonday( int b ) 722void DateButton::setWeekStartsMonday( int b )
723{ 723{
724 weekStartsMonday = b; 724 weekStartsMonday = b;
725} 725}
726 726
727void DateButton::setDate( int y, int m, int d ) 727void DateButton::setDate( int y, int m, int d )
728{ 728{
729 setDate( QDate( y,m,d) ); 729 setDate( QDate( y,m,d) );
730} 730}
731 731
732void DateButton::setDate( QDate d ) 732void DateButton::setDate( QDate d )
733{ 733{
734 currDate = d; 734 currDate = d;
735 setText( longFormat ? TimeString::longDateString( d, df ) : 735 setText( longFormat ? TimeString::longDateString( d, df ) :
736 TimeString::shortDate( d, df ) ); 736 TimeString::shortDate( d, df ) );
737 737
738} 738}
739 739
740void DateButton::setDateFormat( DateFormat f ) 740void DateButton::setDateFormat( DateFormat f )
741{ 741{
742 df = f; 742 df = f;
743 setDate( currDate ); 743 setDate( currDate );
744} 744}
745 745
746bool DateButton::customWhatsThis() const 746bool DateButton::customWhatsThis() const
747{ 747{
748 return TRUE; 748 return TRUE;
749} 749}
750 750
751 751
752// this class is only here for Sharp ROM compatibility 752// this class is only here for Sharp ROM compatibility
753// I have reverse engineered this class and it seems to 753// I have reverse engineered this class and it seems to
754// work (only qtmail seems to use it) - sandman 754// work (only qtmail seems to use it) - sandman
755// DO NOT USE IT IN NEW CODE !! 755// DO NOT USE IT IN NEW CODE !!
756 756
757DateBookMonthPopup::DateBookMonthPopup ( QWidget *w ) 757DateBookMonthPopup::DateBookMonthPopup ( QWidget *w )
758 : QPopupMenu ( w ) 758 : QPopupMenu ( w )
759{ 759{
760 m_dbm = new DateBookMonth( this, 0, TRUE ); 760 m_dbm = new DateBookMonth( this, 0, TRUE );
761 insertItem( m_dbm ); 761 insertItem( m_dbm );
762} 762}
diff --git a/library/fileselector.cpp b/library/fileselector.cpp
index 7c29aba..93fb429 100644
--- a/library/fileselector.cpp
+++ b/library/fileselector.cpp
@@ -1,579 +1,579 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21// WARNING: Do *NOT* define this yourself. The SL5xxx from SHARP does NOT 21// WARNING: Do *NOT* define this yourself. The SL5xxx from SHARP does NOT
22// have this class. 22// have this class.
23#define QTOPIA_INTERNAL_FSLP 23#define QTOPIA_INTERNAL_FSLP
24 24
25#include "fileselector.h" 25#include "fileselector.h"
26#include "fileselector_p.h" 26#include "fileselector_p.h"
27#include "global.h" 27#include "global.h"
28#include "resource.h" 28#include "resource.h"
29#include "config.h" 29#include "config.h"
30#include "storage.h" 30#include "storage.h"
31#include "qpemenubar.h" 31#include "qpemenubar.h"
32#include <qcopchannel_qws.h> 32#include <qcopchannel_qws.h>
33#include "lnkproperties.h" 33#include "lnkproperties.h"
34#include <qpe/qpeapplication.h> 34#include <qpe/qpeapplication.h>
35#include "categorymenu.h" 35#include "categorymenu.h"
36#include "categoryselect.h" 36#include "categoryselect.h"
37#include "mimetype.h" 37#include "mimetype.h"
38#include <qpe/categories.h> 38#include <qpe/categories.h>
39 39
40#include <stdlib.h> 40#include <stdlib.h>
41 41
42#include <qdir.h> 42#include <qdir.h>
43#include <qwidget.h> 43#include <qwidget.h>
44#include <qpopupmenu.h> 44#include <qpopupmenu.h>
45#include <qtoolbutton.h> 45#include <qtoolbutton.h>
46#include <qpushbutton.h> 46#include <qpushbutton.h>
47#include <qheader.h> 47#include <qheader.h>
48#include <qtooltip.h> 48#include <qtooltip.h>
49#include <qwhatsthis.h> 49#include <qwhatsthis.h>
50 50
51class TypeCombo : public QComboBox 51class TypeCombo : public QComboBox
52{ 52{
53 Q_OBJECT 53 Q_OBJECT
54public: 54public:
55 TypeCombo( QWidget *parent, const char *name=0 ) 55 TypeCombo( QWidget *parent, const char *name=0 )
56 : QComboBox( parent, name ) 56 : QComboBox( parent, name )
57 { 57 {
58 connect( this, SIGNAL(activated(int)), this, SLOT(selectType(int)) ); 58 connect( this, SIGNAL(activated(int)), this, SLOT(selectType(int)) );
59 } 59 }
60 60
61 void reread( DocLnkSet &files, const QString &filter ); 61 void reread( DocLnkSet &files, const QString &filter );
62 62
63signals: 63signals:
64 void selected( const QString & ); 64 void selected( const QString & );
65 65
66protected slots: 66protected slots:
67 void selectType( int idx ) { 67 void selectType( int idx ) {
68 emit selected( typelist[idx] ); 68 emit selected( typelist[idx] );
69 } 69 }
70 70
71protected: 71protected:
72 QStringList typelist; 72 QStringList typelist;
73 QString prev; 73 QString prev;
74}; 74};
75 75
76void TypeCombo::reread( DocLnkSet &files, const QString &filter ) 76void TypeCombo::reread( DocLnkSet &files, const QString &filter )
77{ 77{
78 typelist.clear(); 78 typelist.clear();
79 QStringList filters = QStringList::split( ';', filter ); 79 QStringList filters = QStringList::split( ';', filter );
80 int pos = filter.find( '/' ); 80 int pos = filter.find( '/' );
81 //### do for each filter 81 //### do for each filter
82 if ( filters.count() == 1 && pos >= 0 && filter[pos+1] != '*' ) { 82 if ( filters.count() == 1 && pos >= 0 && filter[pos+1] != '*' ) {
83 typelist.append( filter ); 83 typelist.append( filter );
84 clear(); 84 clear();
85 QString minor = filter.mid( pos+1 ); 85 QString minor = filter.mid( pos+1 );
86 minor[0] = minor[0].upper(); 86 minor[0] = minor[0].upper();
87 insertItem( tr("%1 files").arg(minor) ); 87 insertItem( tr("%1 files").arg(minor) );
88 setCurrentItem(0); 88 setCurrentItem(0);
89 setEnabled( FALSE ); 89 setEnabled( FALSE );
90 return; 90 return;
91 } 91 }
92 92
93 QListIterator<DocLnk> dit( files.children() ); 93 QListIterator<DocLnk> dit( files.children() );
94 for ( ; dit.current(); ++dit ) { 94 for ( ; dit.current(); ++dit ) {
95 if ( !typelist.contains( (*dit)->type() ) ) 95 if ( !typelist.contains( (*dit)->type() ) )
96 typelist.append( (*dit)->type() ); 96 typelist.append( (*dit)->type() );
97 } 97 }
98 98
99 QStringList types; 99 QStringList types;
100 QStringList::ConstIterator it; 100 QStringList::ConstIterator it;
101 for (it = typelist.begin(); it!=typelist.end(); ++it) { 101 for (it = typelist.begin(); it!=typelist.end(); ++it) {
102 QString t = *it; 102 QString t = *it;
103 if ( t.left(12) == "application/" ) { 103 if ( t.left(12) == "application/" ) {
104 MimeType mt(t); 104 MimeType mt(t);
105 const AppLnk* app = mt.application(); 105 const AppLnk* app = mt.application();
106 if ( app ) 106 if ( app )
107 t = app->name(); 107 t = app->name();
108 else 108 else
109 t = t.mid(12); 109 t = t.mid(12);
110 } else { 110 } else {
111 QString major, minor; 111 QString major, minor;
112 int pos = t.find( '/' ); 112 int pos = t.find( '/' );
113 if ( pos >= 0 ) { 113 if ( pos >= 0 ) {
114 major = t.left( pos ); 114 major = t.left( pos );
115 minor = t.mid( pos+1 ); 115 minor = t.mid( pos+1 );
116 } 116 }
117 if ( minor.find( "x-" ) == 0 ) 117 if ( minor.find( "x-" ) == 0 )
118 minor = minor.mid( 2 ); 118 minor = minor.mid( 2 );
119 minor[0] = minor[0].upper(); 119 minor[0] = minor[0].upper();
120 major[0] = major[0].upper(); 120 major[0] = major[0].upper();
121 if ( filters.count() > 1 ) 121 if ( filters.count() > 1 )
122 t = tr("%1 %2", "minor mimetype / major mimetype").arg(minor).arg(major); 122 t = tr("%1 %2", "minor mimetype / major mimetype").arg(minor).arg(major);
123 else 123 else
124 t = minor; 124 t = minor;
125 } 125 }
126 types += tr("%1 files").arg(t); 126 types += tr("%1 files").arg(t);
127 } 127 }
128 for (it = filters.begin(); it!=filters.end(); ++it) { 128 for (it = filters.begin(); it!=filters.end(); ++it) {
129 typelist.append( *it ); 129 typelist.append( *it );
130 int pos = (*it).find( '/' ); 130 int pos = (*it).find( '/' );
131 if ( pos >= 0 ) { 131 if ( pos >= 0 ) {
132 QString maj = (*it).left( pos ); 132 QString maj = (*it).left( pos );
133 maj[0] = maj[0].upper(); 133 maj[0] = maj[0].upper();
134 types << tr("All %1 files").arg(maj); 134 types << tr("All %1 files").arg(maj);
135 } 135 }
136 } 136 }
137 if ( filters.count() > 1 ) { 137 if ( filters.count() > 1 ) {
138 typelist.append( filter ); 138 typelist.append( filter );
139 types << tr("All files"); 139 types << tr("All files");
140 } 140 }
141 prev = currentText(); 141 prev = currentText();
142 clear(); 142 clear();
143 insertStringList(types); 143 insertStringList(types);
144 for (int i=0; i<count(); i++) { 144 for (int i=0; i<count(); i++) {
145 if ( text(i) == prev ) { 145 if ( text(i) == prev ) {
146 setCurrentItem(i); 146 setCurrentItem(i);
147 break; 147 break;
148 } 148 }
149 } 149 }
150 if ( prev.isNull() ) 150 if ( prev.isNull() )
151 setCurrentItem(count()-1); 151 setCurrentItem(count()-1);
152 setEnabled( TRUE ); 152 setEnabled( TRUE );
153} 153}
154 154
155 155
156//=========================================================================== 156//===========================================================================
157 157
158FileSelectorItem::FileSelectorItem( QListView *parent, const DocLnk &f ) 158FileSelectorItem::FileSelectorItem( QListView *parent, const DocLnk &f )
159 : QListViewItem( parent ), fl( f ) 159 : QListViewItem( parent ), fl( f )
160{ 160{
161 setText( 0, f.name() ); 161 setText( 0, f.name() );
162 setPixmap( 0, f.pixmap() ); 162 setPixmap( 0, f.pixmap() );
163} 163}
164 164
165FileSelectorItem::~FileSelectorItem() 165FileSelectorItem::~FileSelectorItem()
166{ 166{
167} 167}
168 168
169FileSelectorView::FileSelectorView( QWidget *parent, const char *name ) 169FileSelectorView::FileSelectorView( QWidget *parent, const char *name )
170 : QListView( parent, name ) 170 : QListView( parent, name )
171{ 171{
172 setAllColumnsShowFocus( TRUE ); 172 setAllColumnsShowFocus( TRUE );
173 addColumn( tr( "Name" ) ); 173 addColumn( tr( "Name" ) );
174 header()->hide(); 174 header()->hide();
175} 175}
176 176
177FileSelectorView::~FileSelectorView() 177FileSelectorView::~FileSelectorView()
178{ 178{
179} 179}
180 180
181void FileSelectorView::keyPressEvent( QKeyEvent *e ) 181void FileSelectorView::keyPressEvent( QKeyEvent *e )
182{ 182{
183 QString txt = e->text(); 183 QString txt = e->text();
184 if (e->key() == Key_Space) 184 if (e->key() == Key_Space)
185 emit returnPressed( currentItem() ); 185 emit returnPressed( currentItem() );
186 else if ( !txt.isNull() && txt[0] > ' ' && e->key() < 0x1000 ) 186 else if ( !txt.isNull() && txt[0] > ' ' && e->key() < 0x1000 )
187 e->ignore(); 187 e->ignore();
188 else 188 else
189 QListView::keyPressEvent(e); 189 QListView::keyPressEvent(e);
190} 190}
191 191
192class NewDocItem : public FileSelectorItem 192class NewDocItem : public FileSelectorItem
193{ 193{
194public: 194public:
195 NewDocItem( QListView *parent, const DocLnk &f ) 195 NewDocItem( QListView *parent, const DocLnk &f )
196 : FileSelectorItem( parent, f ) { 196 : FileSelectorItem( parent, f ) {
197 setText( 0, QObject::tr("New Document") ); 197 setText( 0, QObject::tr("New Document") );
198 QImage img( Resource::loadImage( "new" ) ); 198 QImage img( Resource::loadImage( "new" ) );
199 QPixmap pm; 199 QPixmap pm;
200 pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); 200 pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() );
201 setPixmap( 0, pm ); 201 setPixmap( 0, pm );
202 } 202 }
203 QString key ( int, bool ) const { 203 QString key ( int, bool ) const {
204 return QString("\n"); 204 return QString("\n");
205 } 205 }
206 206
207 void paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int alignment ) { 207 void paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int alignment ) {
208 QFont oldFont = p->font(); 208 QFont oldFont = p->font();
209 QFont newFont = p->font(); 209 QFont newFont = p->font();
210 newFont.setWeight( QFont::Bold ); 210 newFont.setWeight( QFont::Bold );
211 p->setFont( newFont ); 211 p->setFont( newFont );
212 FileSelectorItem::paintCell( p, cg, column, width, alignment ); 212 FileSelectorItem::paintCell( p, cg, column, width, alignment );
213 p->setFont( oldFont ); 213 p->setFont( oldFont );
214 } 214 }
215 215
216 int width( const QFontMetrics &fm, const QListView *v, int c ) const { 216 int width( const QFontMetrics &fm, const QListView *v, int c ) const {
217 return FileSelectorItem::width( fm, v, c )*4/3; // allow for bold font 217 return FileSelectorItem::width( fm, v, c )*4/3; // allow for bold font
218 } 218 }
219}; 219};
220 220
221//=========================================================================== 221//===========================================================================
222 222
223class FileSelectorPrivate 223class FileSelectorPrivate
224{ 224{
225public: 225public:
226 TypeCombo *typeCombo; 226 TypeCombo *typeCombo;
227 CategorySelect *catSelect; 227 CategorySelect *catSelect;
228 QValueList<QRegExp> mimeFilters; 228 QValueList<QRegExp> mimeFilters;
229 int catId; 229 int catId;
230 bool showNew; 230 bool showNew;
231 NewDocItem *newDocItem; 231 NewDocItem *newDocItem;
232 DocLnkSet files; 232 DocLnkSet files;
233 QHBox *toolbar; 233 QHBox *toolbar;
234}; 234};
235 235
236/*! 236/*!
237 \class FileSelector fileselector.h 237 \class FileSelector fileselector.h
238 \brief The FileSelector widget allows the user to select DocLnk objects. 238 \brief The FileSelector widget allows the user to select DocLnk objects.
239 239
240 This class presents a file selection dialog to the user. This widget 240 This class presents a file selection dialog to the user. This widget
241 is usually the first widget seen in a \link docwidget.html 241 is usually the first widget seen in a \link docwidget.html
242 document-oriented application\endlink. The developer will most often 242 document-oriented application\endlink. The developer will most often
243 create this widget in combination with a <a 243 create this widget in combination with a <a
244 href="../qt/qwidgetstack.html"> QWidgetStack</a> and the appropriate 244 href="../qt/qwidgetstack.html"> QWidgetStack</a> and the appropriate
245 editor and/or viewer widget for their application. This widget 245 editor and/or viewer widget for their application. This widget
246 should be shown first and the user can the select which document 246 should be shown first and the user can the select which document
247 they wish to operate on. Please refer to the implementation of 247 they wish to operate on. Please refer to the implementation of
248 texteditor for an example of how to tie these classes together. 248 texteditor for an example of how to tie these classes together.
249 249
250 Use setNewVisible() depending on whether the application can be used 250 Use setNewVisible() depending on whether the application can be used
251 to create new files or not. Use setCloseVisible() depending on 251 to create new files or not. Use setCloseVisible() depending on
252 whether the user may leave the dialog without creating or selecting 252 whether the user may leave the dialog without creating or selecting
253 a document or not. The number of files in the view is available from 253 a document or not. The number of files in the view is available from
254 fileCount(). To force the view to be updated call reread(). 254 fileCount(). To force the view to be updated call reread().
255 255
256 If the user presses the 'New Document' button the newSelected() 256 If the user presses the 'New Document' button the newSelected()
257 signal is emitted. If the user selects an existing file the 257 signal is emitted. If the user selects an existing file the
258 fileSelected() signal is emitted. The selected file's \link 258 fileSelected() signal is emitted. The selected file's \link
259 doclnk.html DocLnk\endlink is available from the selected() 259 doclnk.html DocLnk\endlink is available from the selected()
260 function. If the file selector is no longer necessary the closeMe() 260 function. If the file selector is no longer necessary the closeMe()
261 signal is emitted. 261 signal is emitted.
262 262
263 \ingroup qtopiaemb 263 \ingroup qtopiaemb
264 \sa FileManager 264 \sa FileManager
265*/ 265*/
266 266
267/*! 267/*!
268 Constructs a FileSelector with mime filter \a f. 268 Constructs a FileSelector with mime filter \a f.
269 The standard Qt \a parent and \a name parameters are passed to the 269 The standard Qt \a parent and \a name parameters are passed to the
270 parent widget. 270 parent widget.
271 271
272 If \a newVisible is TRUE, the widget has a button to allow the user 272 If \a newVisible is TRUE, the widget has a button to allow the user
273 the create "new" documents; this is useful for applications that can 273 the create "new" documents; this is useful for applications that can
274 create and edit documents but not suitable for applications that 274 create and edit documents but not suitable for applications that
275 only provide viewing. 275 only provide viewing.
276 276
277 \a closeVisible is deprecated 277 \a closeVisible is deprecated
278 278
279 \sa DocLnkSet::DocLnkSet() 279 \sa DocLnkSet::DocLnkSet()
280*/ 280*/
281FileSelector::FileSelector( const QString &f, QWidget *parent, const char *name, bool newVisible, bool closeVisible ) 281FileSelector::FileSelector( const QString &f, QWidget *parent, const char *name, bool newVisible, bool closeVisible )
282 : QVBox( parent, name ), filter( f ) 282 : QVBox( parent, name ), filter( f )
283{ 283{
284 setMargin( 0 ); 284 setMargin( 0 );
285 setSpacing( 0 ); 285 setSpacing( 0 );
286 286
287 d = new FileSelectorPrivate(); 287 d = new FileSelectorPrivate();
288 d->newDocItem = 0; 288 d->newDocItem = 0;
289 d->showNew = newVisible; 289 d->showNew = newVisible;
290 d->catId = -2; // All files 290 d->catId = -2; // All files
291 291
292 d->toolbar = new QHBox( this ); 292 d->toolbar = new QHBox( this );
293 d->toolbar->setBackgroundMode( PaletteButton ); // same colour as toolbars 293 d->toolbar->setBackgroundMode( PaletteButton ); // same colour as toolbars
294 d->toolbar->setSpacing( 0 ); 294 d->toolbar->setSpacing( 0 );
295 d->toolbar->hide(); 295 d->toolbar->hide();
296 296
297 QWidget *spacer = new QWidget( d->toolbar ); 297 QWidget *spacer = new QWidget( d->toolbar );
298 spacer->setBackgroundMode( PaletteButton ); 298 spacer->setBackgroundMode( PaletteButton );
299 299
300 QToolButton *tb = new QToolButton( d->toolbar ); 300 QToolButton *tb = new QToolButton( d->toolbar );
301 tb->setPixmap( Resource::loadPixmap( "close" ) ); 301 tb->setPixmap( Resource::loadPixmap( "close" ) );
302 connect( tb, SIGNAL( clicked() ), this, SIGNAL( closeMe() ) ); 302 connect( tb, SIGNAL( clicked() ), this, SIGNAL( closeMe() ) );
303 buttonClose = tb; 303 buttonClose = tb;
304 tb->setFixedSize( 18, 20 ); // tb->sizeHint() ); 304 tb->setFixedSize( 18, 20 ); // tb->sizeHint() );
305 tb->setAutoRaise( TRUE ); 305 tb->setAutoRaise( TRUE );
306 QToolTip::add( tb, tr( "Close the File Selector" ) ); 306 QToolTip::add( tb, tr( "Close the File Selector" ) );
307 QPEMenuToolFocusManager::manager()->addWidget( tb ); 307 QPEMenuToolFocusManager::manager()->addWidget( tb );
308 308
309 view = new FileSelectorView( this, "fileview" ); 309 view = new FileSelectorView( this, "fileview" );
310 QPEApplication::setStylusOperation( view->viewport(), QPEApplication::RightOnHold ); 310 QPEApplication::setStylusOperation( view->viewport(), QPEApplication::RightOnHold );
311 connect( view, SIGNAL( mouseButtonClicked( int, QListViewItem *, const QPoint &, int ) ), 311 connect( view, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),
312 this, SLOT( fileClicked( int, QListViewItem *, const QPoint &, int ) ) ); 312 this, SLOT( fileClicked(int,QListViewItem*,const QPoint&,int) ) );
313 connect( view, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint &, int ) ), 313 connect( view, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
314 this, SLOT( filePressed( int, QListViewItem *, const QPoint &, int ) ) ); 314 this, SLOT( filePressed(int,QListViewItem*,const QPoint&,int) ) );
315 connect( view, SIGNAL( returnPressed( QListViewItem * ) ), 315 connect( view, SIGNAL( returnPressed(QListViewItem*) ),
316 this, SLOT( fileClicked( QListViewItem * ) ) ); 316 this, SLOT( fileClicked(QListViewItem*) ) );
317 317
318 QHBox *hb = new QHBox( this ); 318 QHBox *hb = new QHBox( this );
319 319
320 d->typeCombo = new TypeCombo( hb ); 320 d->typeCombo = new TypeCombo( hb );
321 connect( d->typeCombo, SIGNAL(selected(const QString&)), 321 connect( d->typeCombo, SIGNAL(selected(const QString&)),
322 this, SLOT(typeSelected(const QString&)) ); 322 this, SLOT(typeSelected(const QString&)) );
323 QWhatsThis::add( d->typeCombo, tr("Show documents of this type") ); 323 QWhatsThis::add( d->typeCombo, tr("Show documents of this type") );
324 324
325 Categories c; 325 Categories c;
326 c.load(categoryFileName()); 326 c.load(categoryFileName());
327 QArray<int> vl( 0 ); 327 QArray<int> vl( 0 );
328 d->catSelect = new CategorySelect( hb ); 328 d->catSelect = new CategorySelect( hb );
329 d->catSelect->setRemoveCategoryEdit( TRUE ); 329 d->catSelect->setRemoveCategoryEdit( TRUE );
330 d->catSelect->setCategories( vl, "Document View", tr("Document View") ); 330 d->catSelect->setCategories( vl, "Document View", tr("Document View") );
331 d->catSelect->setAllCategories( TRUE ); 331 d->catSelect->setAllCategories( TRUE );
332 connect( d->catSelect, SIGNAL(signalSelected(int)), this, SLOT(catSelected(int)) ); 332 connect( d->catSelect, SIGNAL(signalSelected(int)), this, SLOT(catSelected(int)) );
333 QWhatsThis::add( d->catSelect, tr("Show documents in this category") ); 333 QWhatsThis::add( d->catSelect, tr("Show documents in this category") );
334 334
335 setCloseVisible( closeVisible ); 335 setCloseVisible( closeVisible );
336 336
337 QCopChannel *channel = new QCopChannel( "QPE/Card", this ); 337 QCopChannel *channel = new QCopChannel( "QPE/Card", this );
338 connect( channel, SIGNAL(received(const QCString &, const QByteArray &)), 338 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
339 this, SLOT(cardMessage( const QCString &, const QByteArray &)) ); 339 this, SLOT(cardMessage(const QCString&,const QByteArray&)) );
340 340
341 reread(); 341 reread();
342 updateWhatsThis(); 342 updateWhatsThis();
343} 343}
344 344
345/*! 345/*!
346 Destroys the widget. 346 Destroys the widget.
347*/ 347*/
348FileSelector::~FileSelector() 348FileSelector::~FileSelector()
349{ 349{
350 delete d; 350 delete d;
351} 351}
352 352
353/*! 353/*!
354 Returns the number of files in the view. If this is zero, an editor 354 Returns the number of files in the view. If this is zero, an editor
355 application might bypass the selector and immediately start with 355 application might bypass the selector and immediately start with
356 a "new" document. 356 a "new" document.
357*/ 357*/
358int FileSelector::fileCount() 358int FileSelector::fileCount()
359{ 359{
360 return d->files.children().count();; 360 return d->files.children().count();;
361} 361}
362 362
363/*! 363/*!
364 Calling this function is the programmatic equivalent of the user 364 Calling this function is the programmatic equivalent of the user
365 pressing the "new" button. 365 pressing the "new" button.
366 366
367 \sa newSelected(), closeMe() 367 \sa newSelected(), closeMe()
368*/ 368*/
369void FileSelector::createNew() 369void FileSelector::createNew()
370{ 370{
371 DocLnk f; 371 DocLnk f;
372 emit newSelected( f ); 372 emit newSelected( f );
373 emit closeMe(); 373 emit closeMe();
374} 374}
375 375
376void FileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int ) 376void FileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int )
377{ 377{
378 if ( !i ) 378 if ( !i )
379 return; 379 return;
380 if ( button == Qt::LeftButton ) { 380 if ( button == Qt::LeftButton ) {
381 fileClicked( i ); 381 fileClicked( i );
382 } 382 }
383} 383}
384 384
385void FileSelector::filePressed( int button, QListViewItem *i, const QPoint &, int ) 385void FileSelector::filePressed( int button, QListViewItem *i, const QPoint &, int )
386{ 386{
387 if ( !i || i == d->newDocItem ) 387 if ( !i || i == d->newDocItem )
388 return; 388 return;
389 if ( button == Qt::RightButton ) { 389 if ( button == Qt::RightButton ) {
390 DocLnk l = ((FileSelectorItem *)i)->file(); 390 DocLnk l = ((FileSelectorItem *)i)->file();
391 LnkProperties prop( &l ); 391 LnkProperties prop( &l );
392 prop.showMaximized(); 392 prop.showMaximized();
393 prop.exec(); 393 prop.exec();
394 reread(); 394 reread();
395 } 395 }
396} 396}
397 397
398void FileSelector::fileClicked( QListViewItem *i ) 398void FileSelector::fileClicked( QListViewItem *i )
399{ 399{
400 if ( !i ) 400 if ( !i )
401 return; 401 return;
402 if ( i == d->newDocItem ) { 402 if ( i == d->newDocItem ) {
403 createNew(); 403 createNew();
404 } else { 404 } else {
405 emit fileSelected( ( (FileSelectorItem*)i )->file() ); 405 emit fileSelected( ( (FileSelectorItem*)i )->file() );
406 emit closeMe(); 406 emit closeMe();
407 } 407 }
408} 408}
409 409
410void FileSelector::typeSelected( const QString &type ) 410void FileSelector::typeSelected( const QString &type )
411{ 411{
412 d->mimeFilters.clear(); 412 d->mimeFilters.clear();
413 QStringList subFilter = QStringList::split(";", type); 413 QStringList subFilter = QStringList::split(";", type);
414 for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++it ) 414 for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++it )
415 d->mimeFilters.append( QRegExp(*it, FALSE, TRUE) ); 415 d->mimeFilters.append( QRegExp(*it, FALSE, TRUE) );
416 updateView(); 416 updateView();
417} 417}
418 418
419void FileSelector::catSelected( int c ) 419void FileSelector::catSelected( int c )
420{ 420{
421 d->catId = c; 421 d->catId = c;
422 updateView(); 422 updateView();
423} 423}
424 424
425void FileSelector::cardMessage( const QCString &msg, const QByteArray &) 425void FileSelector::cardMessage( const QCString &msg, const QByteArray &)
426{ 426{
427 if ( msg == "mtabChanged()" ) 427 if ( msg == "mtabChanged()" )
428 reread(); 428 reread();
429} 429}
430 430
431 431
432/*! 432/*!
433 Returns the selected \link doclnk.html DocLnk\endlink. The caller is 433 Returns the selected \link doclnk.html DocLnk\endlink. The caller is
434 responsible for deleting the returned value. 434 responsible for deleting the returned value.
435*/ 435*/
436const DocLnk *FileSelector::selected() 436const DocLnk *FileSelector::selected()
437{ 437{
438 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem(); 438 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem();
439 if ( item && item != d->newDocItem ) 439 if ( item && item != d->newDocItem )
440 return new DocLnk( item->file() ); 440 return new DocLnk( item->file() );
441 return NULL; 441 return NULL;
442} 442}
443 443
444/*! 444/*!
445 \fn void FileSelector::fileSelected( const DocLnk &f ) 445 \fn void FileSelector::fileSelected( const DocLnk &f )
446 446
447 This signal is emitted when the user selects a document. 447 This signal is emitted when the user selects a document.
448 \a f is the document. 448 \a f is the document.
449*/ 449*/
450 450
451/*! 451/*!
452 \fn void FileSelector::newSelected( const DocLnk &f ) 452 \fn void FileSelector::newSelected( const DocLnk &f )
453 453
454 This signal is emitted when the user selects a "new" document. 454 This signal is emitted when the user selects a "new" document.
455 \a f is a DocLnk for the document. You will need to set the type 455 \a f is a DocLnk for the document. You will need to set the type
456 of the document after copying it. 456 of the document after copying it.
457*/ 457*/
458 458
459/*! 459/*!
460 \fn void FileSelector::closeMe() 460 \fn void FileSelector::closeMe()
461 461
462 This signal is emitted when the user no longer needs to view the widget. 462 This signal is emitted when the user no longer needs to view the widget.
463*/ 463*/
464 464
465 465
466/*! 466/*!
467 If \a b is TRUE a "new document" entry is visible; if \a b is FALSE 467 If \a b is TRUE a "new document" entry is visible; if \a b is FALSE
468 this entry is not visible and the user is unable to create new 468 this entry is not visible and the user is unable to create new
469 documents from the dialog. 469 documents from the dialog.
470*/ 470*/
471void FileSelector::setNewVisible( bool b ) 471void FileSelector::setNewVisible( bool b )
472{ 472{
473 if ( d->showNew != b ) { 473 if ( d->showNew != b ) {
474 d->showNew = b; 474 d->showNew = b;
475 updateView(); 475 updateView();
476 updateWhatsThis(); 476 updateWhatsThis();
477 } 477 }
478} 478}
479 479
480/*! 480/*!
481 If \a b is TRUE a "close" or "no document" button is visible; if \a 481 If \a b is TRUE a "close" or "no document" button is visible; if \a
482 b is FALSE this button is not visible and the user is unable to 482 b is FALSE this button is not visible and the user is unable to
483 leave the dialog without creating or selecting a document. 483 leave the dialog without creating or selecting a document.
484 484
485 This function is deprecated. 485 This function is deprecated.
486*/ 486*/
487void FileSelector::setCloseVisible( bool b ) 487void FileSelector::setCloseVisible( bool b )
488{ 488{
489 if ( b ) 489 if ( b )
490 d->toolbar->show(); 490 d->toolbar->show();
491 else 491 else
492 d->toolbar->hide(); 492 d->toolbar->hide();
493} 493}
494 494
495/*! 495/*!
496 496
497*/ 497*/
498void FileSelector::setTypeComboVisible( bool b ) { 498void FileSelector::setTypeComboVisible( bool b ) {
499 if ( b ) 499 if ( b )
500 d->typeCombo->show(); 500 d->typeCombo->show();
501 else 501 else
502 d->typeCombo->hide(); 502 d->typeCombo->hide();
503} 503}
504/*! 504/*!
505 505
506*/ 506*/
507void FileSelector::setCategorySelectVisible( bool b ) { 507void FileSelector::setCategorySelectVisible( bool b ) {
508 if ( b ) 508 if ( b )
509 d->catSelect->show(); 509 d->catSelect->show();
510 else 510 else
511 d->catSelect->hide(); 511 d->catSelect->hide();
512} 512}
513 513
514/*! 514/*!
515 Rereads the list of documents. 515 Rereads the list of documents.
516*/ 516*/
517void FileSelector::reread() 517void FileSelector::reread()
518{ 518{
519 d->files.clear(); 519 d->files.clear();
520 Global::findDocuments(&d->files, filter); 520 Global::findDocuments(&d->files, filter);
521 d->typeCombo->reread( d->files, filter ); 521 d->typeCombo->reread( d->files, filter );
522 updateView(); 522 updateView();
523} 523}
524 524
525void FileSelector::updateView() 525void FileSelector::updateView()
526{ 526{
527 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem(); 527 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem();
528 if ( item == d->newDocItem ) 528 if ( item == d->newDocItem )
529 item = 0; 529 item = 0;
530 QString oldFile; 530 QString oldFile;
531 if ( item ) 531 if ( item )
532 oldFile = item->file().file(); 532 oldFile = item->file().file();
533 view->clear(); 533 view->clear();
534 QListIterator<DocLnk> dit( d->files.children() ); 534 QListIterator<DocLnk> dit( d->files.children() );
535 for ( ; dit.current(); ++dit ) { 535 for ( ; dit.current(); ++dit ) {
536 bool mimeMatch = FALSE; 536 bool mimeMatch = FALSE;
537 if ( d->mimeFilters.count() ) { 537 if ( d->mimeFilters.count() ) {
538 QValueList<QRegExp>::Iterator it; 538 QValueList<QRegExp>::Iterator it;
539 for ( it = d->mimeFilters.begin(); it != d->mimeFilters.end(); ++it ) { 539 for ( it = d->mimeFilters.begin(); it != d->mimeFilters.end(); ++it ) {
540 if ( (*it).match((*dit)->type()) >= 0 ) { 540 if ( (*it).match((*dit)->type()) >= 0 ) {
541 mimeMatch = TRUE; 541 mimeMatch = TRUE;
542 break; 542 break;
543 } 543 }
544 } 544 }
545 } else { 545 } else {
546 mimeMatch = TRUE; 546 mimeMatch = TRUE;
547 } 547 }
548 if ( mimeMatch && 548 if ( mimeMatch &&
549 (d->catId == -2 || (*dit)->categories().contains(d->catId) || 549 (d->catId == -2 || (*dit)->categories().contains(d->catId) ||
550 (d->catId == -1 && (*dit)->categories().isEmpty())) ) { 550 (d->catId == -1 && (*dit)->categories().isEmpty())) ) {
551 item = new FileSelectorItem( view, **dit ); 551 item = new FileSelectorItem( view, **dit );
552 if ( item->file().file() == oldFile ) 552 if ( item->file().file() == oldFile )
553 view->setCurrentItem( item ); 553 view->setCurrentItem( item );
554 } 554 }
555 } 555 }
556 556
557 if ( d->showNew ) 557 if ( d->showNew )
558 d->newDocItem = new NewDocItem( view, DocLnk() ); 558 d->newDocItem = new NewDocItem( view, DocLnk() );
559 else 559 else
560 d->newDocItem = 0; 560 d->newDocItem = 0;
561 561
562 if ( !view->selectedItem() || view->childCount() == 1 ) { 562 if ( !view->selectedItem() || view->childCount() == 1 ) {
563 view->setCurrentItem( view->firstChild() ); 563 view->setCurrentItem( view->firstChild() );
564 view->setSelected( view->firstChild(), TRUE ); 564 view->setSelected( view->firstChild(), TRUE );
565 } 565 }
566} 566}
567 567
568void FileSelector::updateWhatsThis() 568void FileSelector::updateWhatsThis()
569{ 569{
570 QWhatsThis::remove( this ); 570 QWhatsThis::remove( this );
571 QString text = tr("Click to select a document from the list"); 571 QString text = tr("Click to select a document from the list");
572 if ( d->showNew ) 572 if ( d->showNew )
573 text += tr(", or select <b>New Document</b> to create a new document."); 573 text += tr(", or select <b>New Document</b> to create a new document.");
574 text += tr("<br><br>Click and hold for document properties."); 574 text += tr("<br><br>Click and hold for document properties.");
575 QWhatsThis::add( this, text ); 575 QWhatsThis::add( this, text );
576} 576}
577 577
578#include "fileselector.moc" 578#include "fileselector.moc"
579 579
diff --git a/library/finddialog.cpp b/library/finddialog.cpp
index 64487c9..9417179 100644
--- a/library/finddialog.cpp
+++ b/library/finddialog.cpp
@@ -1,84 +1,80 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21// WARNING: Do *NOT* define this yourself. The SL5xxx from SHARP does NOT 21// WARNING: Do *NOT* define this yourself. The SL5xxx from SHARP does NOT
22// have this class. 22// have this class.
23#define QTOPIA_INTERNAL_FD 23#define QTOPIA_INTERNAL_FD
24 24
25#include "finddialog.h" 25#include "finddialog.h"
26#include "findwidget_p.h" 26#include "findwidget_p.h"
27 27
28#include <qlayout.h> 28#include <qlayout.h>
29 29
30/*! 30/*!
31 \class FindDialog finddialog.h 31 \class FindDialog finddialog.h
32 \brief A simple FindDialog 32 \brief A simple FindDialog
33 33
34 A find dialog. FIXME!!!! 34 A find dialog. FIXME!!!!
35 35
36*/ 36*/
37FindDialog::FindDialog( const QString &appName, QWidget *parent, 37FindDialog::FindDialog( const QString &appName, QWidget *parent,
38 const char *name, bool modal ) 38 const char *name, bool modal )
39 : QDialog( parent, name, modal ) 39 : QDialog( parent, name, modal )
40{ 40{
41 setCaption( tr("Find") ); 41 setCaption( tr("Find") );
42 QVBoxLayout *vb; 42 QVBoxLayout *vb;
43 vb = new QVBoxLayout( this ); 43 vb = new QVBoxLayout( this );
44 fw = new FindWidget( appName, this, "Find Widget" ); 44 fw = new FindWidget( appName, this, "Find Widget" );
45 vb->addWidget( fw ); 45 vb->addWidget( fw );
46 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&, 46 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&,bool,bool,int)),
47 bool,bool,int)), 47 this, SIGNAL(signalFindClicked(const QString&,bool,bool,int)) );
48 this, SIGNAL(signalFindClicked(const QString&, 48 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&,const QDate&,bool,bool,int)),
49 bool,bool,int)) ); 49 this, SIGNAL(signalFindClicked(const QString&,const QDate&,bool,bool,int)) );
50 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&,const QDate&,
51 bool,bool,int)),
52 this, SIGNAL(signalFindClicked(const QString&,
53 const QDate&,bool,bool,int)) );
54 d = 0; 50 d = 0;
55} 51}
56 52
57FindDialog::~FindDialog() 53FindDialog::~FindDialog()
58{ 54{
59} 55}
60 56
61QString FindDialog::findText() const 57QString FindDialog::findText() const
62{ 58{
63 return fw->findText(); 59 return fw->findText();
64} 60}
65 61
66void FindDialog::setUseDate( bool show ) 62void FindDialog::setUseDate( bool show )
67{ 63{
68 fw->setUseDate( show ); 64 fw->setUseDate( show );
69} 65}
70 66
71void FindDialog::setDate( const QDate &dt ) 67void FindDialog::setDate( const QDate &dt )
72{ 68{
73 fw->setDate( dt ); 69 fw->setDate( dt );
74} 70}
75 71
76void FindDialog::slotNotFound() 72void FindDialog::slotNotFound()
77{ 73{
78 fw->slotNotFound(); 74 fw->slotNotFound();
79} 75}
80 76
81void FindDialog::slotWrapAround() 77void FindDialog::slotWrapAround()
82{ 78{
83 fw->slotWrapAround(); 79 fw->slotWrapAround();
84} 80}
diff --git a/library/findwidget_p.cpp b/library/findwidget_p.cpp
index e91d789..0591f07 100644
--- a/library/findwidget_p.cpp
+++ b/library/findwidget_p.cpp
@@ -1,114 +1,114 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "findwidget_p.h" 21#include "findwidget_p.h"
22 22
23#include <qpe/categoryselect.h> 23#include <qpe/categoryselect.h>
24#include <qpe/datebookmonth.h> 24#include <qpe/datebookmonth.h>
25 25
26#include <qcheckbox.h> 26#include <qcheckbox.h>
27#include <qlabel.h> 27#include <qlabel.h>
28#include <qlineedit.h> 28#include <qlineedit.h>
29 29
30FindWidget::FindWidget( const QString &appName, QWidget *parent, 30FindWidget::FindWidget( const QString &appName, QWidget *parent,
31 const char *name ) 31 const char *name )
32 : FindWidgetBase( parent, name ), 32 : FindWidgetBase( parent, name ),
33 mStrApp( appName ), 33 mStrApp( appName ),
34 mDate( QDate::currentDate() ) 34 mDate( QDate::currentDate() )
35{ 35{
36 setMaximumSize( sizeHint() ); 36 setMaximumSize( sizeHint() );
37 QArray<int> vl(0); 37 QArray<int> vl(0);
38 cmbCat->setCategories( vl, mStrApp ); 38 cmbCat->setCategories( vl, mStrApp );
39 cmbCat->setRemoveCategoryEdit( TRUE ); 39 cmbCat->setRemoveCategoryEdit( TRUE );
40 cmbCat->setAllCategories( TRUE ); 40 cmbCat->setAllCategories( TRUE );
41 // hide junk for the moment... 41 // hide junk for the moment...
42 lblStartDate->hide(); 42 lblStartDate->hide();
43 cmdStartDate->hide(); 43 cmdStartDate->hide();
44 QPopupMenu *m1 = new QPopupMenu( this ); 44 QPopupMenu *m1 = new QPopupMenu( this );
45 dtPicker = new DateBookMonth( m1, 0, TRUE ); 45 dtPicker = new DateBookMonth( m1, 0, TRUE );
46 dtPicker->setDate( mDate.year(), mDate.month(), mDate.day() ); 46 dtPicker->setDate( mDate.year(), mDate.month(), mDate.day() );
47 m1->insertItem( dtPicker ); 47 m1->insertItem( dtPicker );
48 cmdStartDate->setPopup( m1 ); 48 cmdStartDate->setPopup( m1 );
49 cmdStartDate->setText( TimeString::shortDate(mDate) ); 49 cmdStartDate->setText( TimeString::shortDate(mDate) );
50 QObject::connect( dtPicker, SIGNAL(dateClicked(int, int, int)), 50 QObject::connect( dtPicker, SIGNAL(dateClicked(int,int,int)),
51 this, SLOT(slotDateChanged(int, int, int)) ); 51 this, SLOT(slotDateChanged(int,int,int)) );
52 52
53 QObject::connect( cmdFind, SIGNAL(clicked()), 53 QObject::connect( cmdFind, SIGNAL(clicked()),
54 this, SLOT(slotFindClicked()) ); 54 this, SLOT(slotFindClicked()) );
55} 55}
56 56
57FindWidget::~FindWidget() 57FindWidget::~FindWidget()
58{ 58{
59} 59}
60 60
61QString FindWidget::findText() const 61QString FindWidget::findText() const
62{ 62{
63 return txtFind->text(); 63 return txtFind->text();
64} 64}
65 65
66void FindWidget::slotFindClicked() 66void FindWidget::slotFindClicked()
67{ 67{
68 lblStatus->setText( "" ); 68 lblStatus->setText( "" );
69 if ( cmdStartDate->isVisible() ) 69 if ( cmdStartDate->isVisible() )
70 emit signalFindClicked( findText(), 70 emit signalFindClicked( findText(),
71 mDate, 71 mDate,
72 chkCase->isChecked(), 72 chkCase->isChecked(),
73 chkBackwards->isChecked(), 73 chkBackwards->isChecked(),
74 cmbCat->currentCategory() ); 74 cmbCat->currentCategory() );
75 else 75 else
76 emit signalFindClicked( findText(), chkCase->isChecked(), 76 emit signalFindClicked( findText(), chkCase->isChecked(),
77 chkBackwards->isChecked(), 77 chkBackwards->isChecked(),
78 cmbCat->currentCategory() ); 78 cmbCat->currentCategory() );
79} 79}
80 80
81void FindWidget::setUseDate( bool show ) 81void FindWidget::setUseDate( bool show )
82{ 82{
83 if ( show ) { 83 if ( show ) {
84 lblStartDate->show(); 84 lblStartDate->show();
85 cmdStartDate->show(); 85 cmdStartDate->show();
86 } else { 86 } else {
87 lblStartDate->hide(); 87 lblStartDate->hide();
88 cmdStartDate->hide(); 88 cmdStartDate->hide();
89 } 89 }
90 chkBackwards->setDisabled( show ); 90 chkBackwards->setDisabled( show );
91} 91}
92 92
93void FindWidget::setDate( const QDate &dt ) 93void FindWidget::setDate( const QDate &dt )
94{ 94{
95 slotDateChanged( dt.year(), dt.month(), dt.day() ); 95 slotDateChanged( dt.year(), dt.month(), dt.day() );
96} 96}
97 97
98void FindWidget::slotNotFound() 98void FindWidget::slotNotFound()
99{ 99{
100 lblStatus->setText( tr("String Not Found.") ); 100 lblStatus->setText( tr("String Not Found.") );
101} 101}
102 102
103void FindWidget::slotWrapAround() 103void FindWidget::slotWrapAround()
104{ 104{
105 lblStatus->setText( tr("End reached, starting at %1", "Date using TimeString::shortDate") 105 lblStatus->setText( tr("End reached, starting at %1", "Date using TimeString::shortDate")
106 .arg(TimeString::shortDate( mDate ) ) ); 106 .arg(TimeString::shortDate( mDate ) ) );
107} 107}
108 108
109void FindWidget::slotDateChanged( int year, int month, int day ) 109void FindWidget::slotDateChanged( int year, int month, int day )
110{ 110{
111 mDate.setYMD( year, month, day ); 111 mDate.setYMD( year, month, day );
112 cmdStartDate->setText( TimeString::shortDate( mDate ) ); 112 cmdStartDate->setText( TimeString::shortDate( mDate ) );
113 dtPicker->setDate( year, month, day ); 113 dtPicker->setDate( year, month, day );
114} 114}
diff --git a/library/ir.cpp b/library/ir.cpp
index 32c0925..c581eb1 100644
--- a/library/ir.cpp
+++ b/library/ir.cpp
@@ -1,116 +1,116 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "ir.h" 21#include "ir.h"
22 22
23#include "qcopenvelope_qws.h" 23#include "qcopenvelope_qws.h"
24#include "applnk.h" 24#include "applnk.h"
25 25
26/*! 26/*!
27 \class Ir ir.h 27 \class Ir ir.h
28 \brief The Ir class implements basic support for sending objects over an 28 \brief The Ir class implements basic support for sending objects over an
29 infrared communication link. 29 infrared communication link.
30 30
31 Both \link doclnk.html DocLnk\endlink objects and files can be 31 Both \link doclnk.html DocLnk\endlink objects and files can be
32 sent to another device via the infrared link using the send() 32 sent to another device via the infrared link using the send()
33 function. When the send has completed the done() signal is 33 function. When the send has completed the done() signal is
34 emitted. 34 emitted.
35 35
36 The supported() function returns whether the device supports 36 The supported() function returns whether the device supports
37 infrared communication or not. 37 infrared communication or not.
38 38
39 \ingroup qtopiaemb 39 \ingroup qtopiaemb
40*/ 40*/
41 41
42/*! 42/*!
43 Constructs an Ir object. The \a parent and \a name classes are the 43 Constructs an Ir object. The \a parent and \a name classes are the
44 standard QObject parameters. 44 standard QObject parameters.
45*/ 45*/
46Ir::Ir( QObject *parent, const char *name ) 46Ir::Ir( QObject *parent, const char *name )
47 : QObject( parent, name ) 47 : QObject( parent, name )
48{ 48{
49#ifndef QT_NO_COP 49#ifndef QT_NO_COP
50 ch = new QCopChannel( "QPE/Obex" ); 50 ch = new QCopChannel( "QPE/Obex" );
51 connect( ch, SIGNAL(received(const QCString &, const QByteArray &)), 51 connect( ch, SIGNAL(received(const QCString&,const QByteArray&)),
52 this, SLOT(obexMessage( const QCString &, const QByteArray &)) ); 52 this, SLOT(obexMessage(const QCString&,const QByteArray&)) );
53#endif 53#endif
54} 54}
55 55
56/*! 56/*!
57 Returns TRUE if the system supports infrared communication; 57 Returns TRUE if the system supports infrared communication;
58 otherwise returns FALSE. 58 otherwise returns FALSE.
59*/ 59*/
60bool Ir::supported() 60bool Ir::supported()
61{ 61{
62#ifndef QT_NO_COP 62#ifndef QT_NO_COP
63 return QCopChannel::isRegistered( "QPE/Obex" ); 63 return QCopChannel::isRegistered( "QPE/Obex" );
64#endif 64#endif
65} 65}
66 66
67/*! 67/*!
68 Sends the object in file \a fn over the infrared link. The \a 68 Sends the object in file \a fn over the infrared link. The \a
69 description is used in the text shown to the user while sending 69 description is used in the text shown to the user while sending
70 is in progress. The optional \a mimetype parameter specifies the 70 is in progress. The optional \a mimetype parameter specifies the
71 mimetype of the object. If this parameter is not set, it is 71 mimetype of the object. If this parameter is not set, it is
72 determined by the the filename's suffix. 72 determined by the the filename's suffix.
73 73
74 \sa done() 74 \sa done()
75*/ 75*/
76void Ir::send( const QString &fn, const QString &description, const QString &mimetype) 76void Ir::send( const QString &fn, const QString &description, const QString &mimetype)
77{ 77{
78 if ( !filename.isEmpty() ) return; 78 if ( !filename.isEmpty() ) return;
79 filename = fn; 79 filename = fn;
80#ifndef QT_NO_COP 80#ifndef QT_NO_COP
81 QCopEnvelope e("QPE/Obex", "send(QString,QString,QString)"); 81 QCopEnvelope e("QPE/Obex", "send(QString,QString,QString)");
82 e << description << filename << mimetype; 82 e << description << filename << mimetype;
83#endif 83#endif
84} 84}
85 85
86/*! 86/*!
87 \overload 87 \overload
88 88
89 Uses the DocLnk::file() and DocLnk::type() of \a doc. 89 Uses the DocLnk::file() and DocLnk::type() of \a doc.
90 90
91 \sa done() 91 \sa done()
92*/ 92*/
93void Ir::send( const DocLnk &doc, const QString &description ) 93void Ir::send( const DocLnk &doc, const QString &description )
94{ 94{
95 send( doc.file(), description, doc.type() ); 95 send( doc.file(), description, doc.type() );
96} 96}
97 97
98/*! 98/*!
99 \fn Ir::done( Ir *ir ); 99 \fn Ir::done( Ir *ir );
100 100
101 This signal is emitted by \a ir, when the send comand has been processed. 101 This signal is emitted by \a ir, when the send comand has been processed.
102*/ 102*/
103 103
104/*!\internal 104/*!\internal
105 */ 105 */
106void Ir::obexMessage( const QCString &msg, const QByteArray &data) 106void Ir::obexMessage( const QCString &msg, const QByteArray &data)
107{ 107{
108 if ( msg == "done(QString)" ) { 108 if ( msg == "done(QString)" ) {
109 QString fn; 109 QString fn;
110 QDataStream stream( data, IO_ReadOnly ); 110 QDataStream stream( data, IO_ReadOnly );
111 stream >> fn; 111 stream >> fn;
112 if ( fn == filename ) 112 if ( fn == filename )
113 emit done( this ); 113 emit done( this );
114 } 114 }
115} 115}
116 116
diff --git a/library/network.cpp b/library/network.cpp
index 991e11a..df28857 100644
--- a/library/network.cpp
+++ b/library/network.cpp
@@ -1,448 +1,448 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#define QTOPIA_INTERNAL_LANGLIST 21#define QTOPIA_INTERNAL_LANGLIST
22#include "qpe/network.h" 22#include "qpe/network.h"
23#include "qpe/networkinterface.h" 23#include "qpe/networkinterface.h"
24#include "qpe/global.h" 24#include "qpe/global.h"
25#include "qpe/config.h" 25#include "qpe/config.h"
26#include "qpe/resource.h" 26#include "qpe/resource.h"
27#include "qpe/qpeapplication.h" 27#include "qpe/qpeapplication.h"
28#include <qpe/qcopenvelope_qws.h> 28#include <qpe/qcopenvelope_qws.h>
29#include <qpe/qlibrary.h> 29#include <qpe/qlibrary.h>
30 30
31#include <qlistbox.h> 31#include <qlistbox.h>
32#include <qdir.h> 32#include <qdir.h>
33#include <qlayout.h> 33#include <qlayout.h>
34#include <qdict.h> 34#include <qdict.h>
35#include <qtranslator.h> 35#include <qtranslator.h>
36 36
37#include <stdlib.h> 37#include <stdlib.h>
38 38
39#ifndef QT_NO_COP 39#ifndef QT_NO_COP
40class NetworkEmitter : public QCopChannel { 40class NetworkEmitter : public QCopChannel {
41 Q_OBJECT 41 Q_OBJECT
42public: 42public:
43 NetworkEmitter() : QCopChannel("QPE/Network",qApp) 43 NetworkEmitter() : QCopChannel("QPE/Network",qApp)
44 { 44 {
45 } 45 }
46 46
47 void receive(const QCString &msg, const QByteArray&) 47 void receive(const QCString &msg, const QByteArray&)
48 { 48 {
49 if ( msg == "choicesChanged()" ) 49 if ( msg == "choicesChanged()" )
50 emit changed(); 50 emit changed();
51 } 51 }
52 52
53signals: 53signals:
54 void changed(); 54 void changed();
55}; 55};
56 56
57/*! 57/*!
58 \internal 58 \internal
59 59
60 Requests that the service \a choice be started. The \a password is 60 Requests that the service \a choice be started. The \a password is
61 the password to use if required. 61 the password to use if required.
62*/ 62*/
63void Network::start(const QString& choice, const QString& password) 63void Network::start(const QString& choice, const QString& password)
64{ 64{
65 QCopEnvelope e("QPE/Network", "start(QString,QString)"); 65 QCopEnvelope e("QPE/Network", "start(QString,QString)");
66 e << choice << password; 66 e << choice << password;
67} 67}
68 68
69/*! 69/*!
70 \class Network network.h 70 \class Network network.h
71 \brief The Network class provides network access functionality. 71 \brief The Network class provides network access functionality.
72 \internal 72 \internal
73*/ 73*/
74 74
75// copy the proxy settings of the active config over to the Proxies.conf file 75// copy the proxy settings of the active config over to the Proxies.conf file
76/*! 76/*!
77 \internal 77 \internal
78*/ 78*/
79void Network::writeProxySettings( Config &cfg ) 79void Network::writeProxySettings( Config &cfg )
80{ 80{
81 Config proxy( Network::settingsDir() + "/Proxies.conf", Config::File ); 81 Config proxy( Network::settingsDir() + "/Proxies.conf", Config::File );
82 proxy.setGroup("Properties"); 82 proxy.setGroup("Properties");
83 cfg.setGroup("Proxy"); 83 cfg.setGroup("Proxy");
84 proxy.writeEntry("type", cfg.readEntry("type") ); 84 proxy.writeEntry("type", cfg.readEntry("type") );
85 proxy.writeEntry("autoconfig", cfg.readEntry("autoconfig") ); 85 proxy.writeEntry("autoconfig", cfg.readEntry("autoconfig") );
86 proxy.writeEntry("httphost", cfg.readEntry("httphost") ); 86 proxy.writeEntry("httphost", cfg.readEntry("httphost") );
87 proxy.writeEntry("httpport", cfg.readEntry("httpport") ); 87 proxy.writeEntry("httpport", cfg.readEntry("httpport") );
88 proxy.writeEntry("ftphost", cfg.readEntry("ftphost") ); 88 proxy.writeEntry("ftphost", cfg.readEntry("ftphost") );
89 proxy.writeEntry("ftpport", cfg.readEntry("ftpport") ); 89 proxy.writeEntry("ftpport", cfg.readEntry("ftpport") );
90 proxy.writeEntry("noproxies", cfg.readEntry("noproxies") ); 90 proxy.writeEntry("noproxies", cfg.readEntry("noproxies") );
91 cfg.setGroup("Properties"); 91 cfg.setGroup("Properties");
92} 92}
93 93
94 94
95 95
96/*! 96/*!
97 \internal 97 \internal
98 98
99 Stops the current network service. 99 Stops the current network service.
100*/ 100*/
101void Network::stop() 101void Network::stop()
102{ 102{
103 QCopEnvelope e("QPE/Network", "stop()"); 103 QCopEnvelope e("QPE/Network", "stop()");
104} 104}
105 105
106static NetworkEmitter *emitter = 0; 106static NetworkEmitter *emitter = 0;
107 107
108/*! 108/*!
109 \internal 109 \internal
110*/ 110*/
111void Network::connectChoiceChange(QObject* receiver, const char* slot) 111void Network::connectChoiceChange(QObject* receiver, const char* slot)
112{ 112{
113 if ( !emitter ) 113 if ( !emitter )
114 emitter = new NetworkEmitter; 114 emitter = new NetworkEmitter;
115 QObject::connect(emitter,SIGNAL(changed()),receiver,slot); 115 QObject::connect(emitter,SIGNAL(changed()),receiver,slot);
116} 116}
117 117
118 #endif// QT_NO_COP 118 #endif// QT_NO_COP
119/*! 119/*!
120 \internal 120 \internal
121*/ 121*/
122QString Network::settingsDir() 122QString Network::settingsDir()
123{ 123{
124 return Global::applicationFileName("Network", "modules"); 124 return Global::applicationFileName("Network", "modules");
125} 125}
126 126
127#ifndef QT_NO_COP 127#ifndef QT_NO_COP
128/*! 128/*!
129 \internal 129 \internal
130*/ 130*/
131QStringList Network::choices(QListBox* lb, const QString& dir) 131QStringList Network::choices(QListBox* lb, const QString& dir)
132{ 132{
133 QStringList list; 133 QStringList list;
134 134
135 if ( lb ) 135 if ( lb )
136 lb->clear(); 136 lb->clear();
137 137
138 QString adir = dir.isEmpty() ? settingsDir() : dir; 138 QString adir = dir.isEmpty() ? settingsDir() : dir;
139 QDir settingsdir(adir); 139 QDir settingsdir(adir);
140 settingsdir.mkdir(adir); 140 settingsdir.mkdir(adir);
141 141
142 QStringList files = settingsdir.entryList("*.conf"); 142 QStringList files = settingsdir.entryList("*.conf");
143 for (QStringList::ConstIterator it=files.begin(); it!=files.end(); ++it ) { 143 for (QStringList::ConstIterator it=files.begin(); it!=files.end(); ++it ) {
144 QString filename = settingsdir.filePath(*it); 144 QString filename = settingsdir.filePath(*it);
145 Config cfg(filename, Config::File); 145 Config cfg(filename, Config::File);
146 cfg.setGroup("Info"); 146 cfg.setGroup("Info");
147 if ( lb ) 147 if ( lb )
148 lb->insertItem(Resource::loadPixmap("Network/" + cfg.readEntry("Type")), 148 lb->insertItem(Resource::loadPixmap("Network/" + cfg.readEntry("Type")),
149 cfg.readEntry("Name")); 149 cfg.readEntry("Name"));
150 list.append(filename); 150 list.append(filename);
151 } 151 }
152 152
153 return list; 153 return list;
154} 154}
155 155
156class NetworkServer : public QCopChannel { 156class NetworkServer : public QCopChannel {
157 Q_OBJECT 157 Q_OBJECT
158public: 158public:
159 NetworkServer(QObject* parent) : QCopChannel("QPE/Network",parent), wait(0) 159 NetworkServer(QObject* parent) : QCopChannel("QPE/Network",parent), wait(0)
160 { 160 {
161 up = FALSE; 161 up = FALSE;
162 examineNetworks( TRUE ); 162 examineNetworks( TRUE );
163 QCopChannel* card = new QCopChannel("QPE/Card",parent); 163 QCopChannel* card = new QCopChannel("QPE/Card",parent);
164 connect(card,SIGNAL(received(const QCString &, const QByteArray&)), 164 connect(card,SIGNAL(received(const QCString&,const QByteArray&)),
165 this,SLOT(cardMessage(const QCString &, const QByteArray&))); 165 this,SLOT(cardMessage(const QCString&,const QByteArray&)));
166 } 166 }
167 167
168 ~NetworkServer() 168 ~NetworkServer()
169 { 169 {
170 stop(); 170 stop();
171 } 171 }
172 172
173 bool networkOnline() const 173 bool networkOnline() const
174 { 174 {
175 return up; 175 return up;
176 } 176 }
177 177
178private: 178private:
179 void receive(const QCString &msg, const QByteArray& data) 179 void receive(const QCString &msg, const QByteArray& data)
180 { 180 {
181 if ( msg == "start(QString,QString)" ) { 181 if ( msg == "start(QString,QString)" ) {
182 QDataStream stream(data,IO_ReadOnly); 182 QDataStream stream(data,IO_ReadOnly);
183 QString file,password; 183 QString file,password;
184 stream >> file >> password; 184 stream >> file >> password;
185 if ( file.isEmpty() ) { 185 if ( file.isEmpty() ) {
186 QStringList l = Network::choices(); 186 QStringList l = Network::choices();
187 for (QStringList::ConstIterator i=l.begin(); i!=l.end(); ++i) { 187 for (QStringList::ConstIterator i=l.begin(); i!=l.end(); ++i) {
188 Config cfg(*i,Config::File); 188 Config cfg(*i,Config::File);
189 cfg.setGroup("Info"); 189 cfg.setGroup("Info");
190 QString type = cfg.readEntry("Type"); 190 QString type = cfg.readEntry("Type");
191 NetworkInterface* plugin = Network::loadPlugin(type); 191 NetworkInterface* plugin = Network::loadPlugin(type);
192 cfg.setGroup("Properties"); 192 cfg.setGroup("Properties");
193 if ( plugin && plugin->isAvailable(cfg) ) { 193 if ( plugin && plugin->isAvailable(cfg) ) {
194 file = *i; 194 file = *i;
195 break; 195 break;
196 } 196 }
197 } 197 }
198 if ( file.isEmpty() ) { 198 if ( file.isEmpty() ) {
199 QCopEnvelope("QPE/Network", "failed()"); 199 QCopEnvelope("QPE/Network", "failed()");
200 return; 200 return;
201 } 201 }
202 } 202 }
203 start(file,password); 203 start(file,password);
204 } else if ( msg == "stop()" ) { 204 } else if ( msg == "stop()" ) {
205 stop(); 205 stop();
206 } else if ( msg == "choicesChanged()" ) { 206 } else if ( msg == "choicesChanged()" ) {
207 examineNetworks(); 207 examineNetworks();
208 } 208 }
209 } 209 }
210 210
211private slots: 211private slots:
212 void cardMessage(const QCString &msg, const QByteArray&) 212 void cardMessage(const QCString &msg, const QByteArray&)
213 { 213 {
214 if ( msg == "stabChanged()" ) 214 if ( msg == "stabChanged()" )
215 examineNetworks(); 215 examineNetworks();
216 } 216 }
217 217
218private: 218private:
219 void examineNetworks( bool firstStart = FALSE ) 219 void examineNetworks( bool firstStart = FALSE )
220 { 220 {
221 QStringList l = Network::choices(); 221 QStringList l = Network::choices();
222 bool wasup = up; up=FALSE; 222 bool wasup = up; up=FALSE;
223 QStringList pavailable = available; 223 QStringList pavailable = available;
224 available.clear(); 224 available.clear();
225 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) { 225 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) {
226 Config cfg(*it,Config::File); 226 Config cfg(*it,Config::File);
227 cfg.setGroup("Info"); 227 cfg.setGroup("Info");
228 QString type = cfg.readEntry("Type"); 228 QString type = cfg.readEntry("Type");
229 NetworkInterface* plugin = Network::loadPlugin(type); 229 NetworkInterface* plugin = Network::loadPlugin(type);
230 cfg.setGroup("Properties"); 230 cfg.setGroup("Properties");
231 if ( plugin ) { 231 if ( plugin ) {
232 if ( plugin->isActive(cfg) ) { 232 if ( plugin->isActive(cfg) ) {
233 up = TRUE; 233 up = TRUE;
234 if ( firstStart ) 234 if ( firstStart )
235 plugin->start( cfg ); 235 plugin->start( cfg );
236 } 236 }
237 if ( plugin->isAvailable(cfg) ) 237 if ( plugin->isAvailable(cfg) )
238 available.append(*it); 238 available.append(*it);
239 } 239 }
240 } 240 }
241 241
242 // Try to work around unreproducible bug whereby 242 // Try to work around unreproducible bug whereby
243 // the netmon applet shows wrong state. 243 // the netmon applet shows wrong state.
244 bool reannounce = wait<0; 244 bool reannounce = wait<0;
245 245
246 if ( available != pavailable || reannounce ) { 246 if ( available != pavailable || reannounce ) {
247 QCopEnvelope e("QPE/Network", "available(QStringList)"); 247 QCopEnvelope e("QPE/Network", "available(QStringList)");
248 e << available; 248 e << available;
249 } 249 }
250 if ( up != wasup || reannounce ) { 250 if ( up != wasup || reannounce ) {
251 QCopEnvelope("QPE/Network", up ? "up()" : "down()"); 251 QCopEnvelope("QPE/Network", up ? "up()" : "down()");
252 } 252 }
253 } 253 }
254 254
255 void start( const QString& file, const QString& password ) 255 void start( const QString& file, const QString& password )
256 { 256 {
257 if ( !current.isEmpty() ) 257 if ( !current.isEmpty() )
258 stop(); 258 stop();
259 current = QString::null; 259 current = QString::null;
260 Config cfg(file, Config::File); 260 Config cfg(file, Config::File);
261 cfg.setGroup("Info"); 261 cfg.setGroup("Info");
262 QString type = cfg.readEntry("Type"); 262 QString type = cfg.readEntry("Type");
263 NetworkInterface* plugin = Network::loadPlugin(type); 263 NetworkInterface* plugin = Network::loadPlugin(type);
264 bool started = FALSE; 264 bool started = FALSE;
265 if ( plugin ) { 265 if ( plugin ) {
266 cfg.setGroup("Properties"); 266 cfg.setGroup("Properties");
267 if ( plugin->start(cfg,password) ) { 267 if ( plugin->start(cfg,password) ) {
268 Network::writeProxySettings( cfg ); 268 Network::writeProxySettings( cfg );
269 current = file; 269 current = file;
270 wait=0; 270 wait=0;
271 startTimer(400); 271 startTimer(400);
272 started = TRUE; 272 started = TRUE;
273 } 273 }
274 } 274 }
275 if ( !started ) { 275 if ( !started ) {
276 QCopEnvelope("QPE/Network", "failed()"); 276 QCopEnvelope("QPE/Network", "failed()");
277 } 277 }
278 } 278 }
279 279
280 void stop() 280 void stop()
281 { 281 {
282 bool stopped = FALSE; 282 bool stopped = FALSE;
283 if ( !current.isEmpty() ) { 283 if ( !current.isEmpty() ) {
284 Config cfg(current, Config::File); 284 Config cfg(current, Config::File);
285 cfg.setGroup("Info"); 285 cfg.setGroup("Info");
286 QString type = cfg.readEntry("Type"); 286 QString type = cfg.readEntry("Type");
287 NetworkInterface* plugin = Network::loadPlugin(type); 287 NetworkInterface* plugin = Network::loadPlugin(type);
288 if ( plugin ) { 288 if ( plugin ) {
289 cfg.setGroup("Properties"); 289 cfg.setGroup("Properties");
290 if ( plugin->stop(cfg) ) { 290 if ( plugin->stop(cfg) ) {
291 current = QString::null; 291 current = QString::null;
292 wait=0; 292 wait=0;
293 startTimer(400); 293 startTimer(400);
294 stopped = TRUE; 294 stopped = TRUE;
295 } 295 }
296 } 296 }
297 } 297 }
298 if ( !stopped ) { 298 if ( !stopped ) {
299 QCopEnvelope("QPE/Network", "failed()"); 299 QCopEnvelope("QPE/Network", "failed()");
300 } 300 }
301 } 301 }
302 302
303 void timerEvent(QTimerEvent*) 303 void timerEvent(QTimerEvent*)
304 { 304 {
305 examineNetworks(); 305 examineNetworks();
306 if ( wait >= 0 ) { 306 if ( wait >= 0 ) {
307 if ( up == !current.isNull() ) { 307 if ( up == !current.isNull() ) {
308 // done 308 // done
309 killTimers(); 309 killTimers();
310 if ( up ) { 310 if ( up ) {
311 startTimer(3000); // monitor link 311 startTimer(3000); // monitor link
312 wait = -1; 312 wait = -1;
313 } 313 }
314 } else { 314 } else {
315 wait++; 315 wait++;
316 if ( wait == 600 ) { 316 if ( wait == 600 ) {
317 killTimers(); // forget about it after 240 s 317 killTimers(); // forget about it after 240 s
318 QCopEnvelope("QPE/Network", "failed()"); 318 QCopEnvelope("QPE/Network", "failed()");
319 up = !current.isNull(); 319 up = !current.isNull();
320 } 320 }
321 } 321 }
322 } else if ( !up ) { 322 } else if ( !up ) {
323 killTimers(); 323 killTimers();
324 } 324 }
325 } 325 }
326 326
327private: 327private:
328 QStringList available; 328 QStringList available;
329 QString current; 329 QString current;
330 bool up; 330 bool up;
331 int wait; 331 int wait;
332}; 332};
333 333
334static NetworkServer* ns=0; 334static NetworkServer* ns=0;
335 335
336/*! 336/*!
337 \internal 337 \internal
338*/ 338*/
339QString Network::serviceName(const QString& service) 339QString Network::serviceName(const QString& service)
340{ 340{
341 Config cfg(service, Config::File); 341 Config cfg(service, Config::File);
342 cfg.setGroup("Info"); 342 cfg.setGroup("Info");
343 return cfg.readEntry("Name"); 343 return cfg.readEntry("Name");
344} 344}
345 345
346/*! 346/*!
347 \internal 347 \internal
348*/ 348*/
349QString Network::serviceType(const QString& service) 349QString Network::serviceType(const QString& service)
350{ 350{
351 Config cfg(service, Config::File); 351 Config cfg(service, Config::File);
352 cfg.setGroup("Info"); 352 cfg.setGroup("Info");
353 return cfg.readEntry("Type"); 353 return cfg.readEntry("Type");
354} 354}
355 355
356/*! 356/*!
357 \internal 357 \internal
358*/ 358*/
359bool Network::serviceNeedsPassword(const QString& service) 359bool Network::serviceNeedsPassword(const QString& service)
360{ 360{
361 Config cfg(service,Config::File); 361 Config cfg(service,Config::File);
362 cfg.setGroup("Info"); 362 cfg.setGroup("Info");
363 QString type = cfg.readEntry("Type"); 363 QString type = cfg.readEntry("Type");
364 NetworkInterface* plugin = Network::loadPlugin(type); 364 NetworkInterface* plugin = Network::loadPlugin(type);
365 cfg.setGroup("Properties"); 365 cfg.setGroup("Properties");
366 return plugin ? plugin->needPassword(cfg) : FALSE; 366 return plugin ? plugin->needPassword(cfg) : FALSE;
367} 367}
368 368
369/*! 369/*!
370 \internal 370 \internal
371*/ 371*/
372bool Network::networkOnline() 372bool Network::networkOnline()
373{ 373{
374 return ns && ns->networkOnline(); 374 return ns && ns->networkOnline();
375} 375}
376 376
377/*! 377/*!
378 \internal 378 \internal
379*/ 379*/
380void Network::createServer(QObject* parent) 380void Network::createServer(QObject* parent)
381{ 381{
382 ns = new NetworkServer(parent); 382 ns = new NetworkServer(parent);
383} 383}
384 384
385/*! 385/*!
386 \internal 386 \internal
387*/ 387*/
388int Network::addStateWidgets(QWidget* parent) 388int Network::addStateWidgets(QWidget* parent)
389{ 389{
390 int n=0; 390 int n=0;
391 QStringList l = Network::choices(); 391 QStringList l = Network::choices();
392 QVBoxLayout* vb = new QVBoxLayout(parent); 392 QVBoxLayout* vb = new QVBoxLayout(parent);
393 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) { 393 for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) {
394 Config cfg(*it,Config::File); 394 Config cfg(*it,Config::File);
395 cfg.setGroup("Info"); 395 cfg.setGroup("Info");
396 QString type = cfg.readEntry("Type"); 396 QString type = cfg.readEntry("Type");
397 NetworkInterface* plugin = Network::loadPlugin(type); 397 NetworkInterface* plugin = Network::loadPlugin(type);
398 cfg.setGroup("Properties"); 398 cfg.setGroup("Properties");
399 if ( plugin ) { 399 if ( plugin ) {
400 QWidget* w; 400 QWidget* w;
401 if ( (w=plugin->addStateWidget(parent,cfg)) ) { 401 if ( (w=plugin->addStateWidget(parent,cfg)) ) {
402 n++; 402 n++;
403 vb->addWidget(w); 403 vb->addWidget(w);
404 } 404 }
405 } 405 }
406 } 406 }
407 return n; 407 return n;
408} 408}
409 409
410static QDict<NetworkInterface> *ifaces; 410static QDict<NetworkInterface> *ifaces;
411 411
412/*! 412/*!
413 \internal 413 \internal
414*/ 414*/
415NetworkInterface* Network::loadPlugin(const QString& type) 415NetworkInterface* Network::loadPlugin(const QString& type)
416{ 416{
417#ifndef QT_NO_COMPONENT 417#ifndef QT_NO_COMPONENT
418 if ( !ifaces ) ifaces = new QDict<NetworkInterface>; 418 if ( !ifaces ) ifaces = new QDict<NetworkInterface>;
419 NetworkInterface *iface = ifaces->find(type); 419 NetworkInterface *iface = ifaces->find(type);
420 if ( !iface ) { 420 if ( !iface ) {
421#ifdef Q_OS_MACX 421#ifdef Q_OS_MACX
422 QString libfile = QPEApplication::qpeDir() + "/plugins/network/lib" + type + ".dylib"; 422 QString libfile = QPEApplication::qpeDir() + "/plugins/network/lib" + type + ".dylib";
423#else 423#else
424 QString libfile = QPEApplication::qpeDir() + "/plugins/network/lib" + type + ".so"; 424 QString libfile = QPEApplication::qpeDir() + "/plugins/network/lib" + type + ".so";
425#endif 425#endif
426 QLibrary lib(libfile); 426 QLibrary lib(libfile);
427 if ( !lib.queryInterface( IID_Network, (QUnknownInterface**)&iface ) == QS_OK ) 427 if ( !lib.queryInterface( IID_Network, (QUnknownInterface**)&iface ) == QS_OK )
428 return 0; 428 return 0;
429 ifaces->insert(type,iface); 429 ifaces->insert(type,iface);
430 QStringList langs = Global::languageList(); 430 QStringList langs = Global::languageList();
431 for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) { 431 for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) {
432 QString lang = *it; 432 QString lang = *it;
433 QTranslator * trans = new QTranslator(qApp); 433 QTranslator * trans = new QTranslator(qApp);
434 QString tfn = QPEApplication::qpeDir()+"/i18n/"+lang+"/lib"+type+".qm"; 434 QString tfn = QPEApplication::qpeDir()+"/i18n/"+lang+"/lib"+type+".qm";
435 if ( trans->load( tfn )) 435 if ( trans->load( tfn ))
436 qApp->installTranslator( trans ); 436 qApp->installTranslator( trans );
437 else 437 else
438 delete trans; 438 delete trans;
439 } 439 }
440 } 440 }
441 return iface; 441 return iface;
442#else 442#else
443 return 0; 443 return 0;
444#endif 444#endif
445} 445}
446 446
447#include "network.moc" 447#include "network.moc"
448 #endif// QT_NO_COP 448 #endif// QT_NO_COP
diff --git a/library/qcopenvelope_qws.cpp b/library/qcopenvelope_qws.cpp
index 8f58787..63efb13 100644
--- a/library/qcopenvelope_qws.cpp
+++ b/library/qcopenvelope_qws.cpp
@@ -1,145 +1,145 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#ifndef QT_NO_COP 21#ifndef QT_NO_COP
22#include "qcopenvelope_qws.h" 22#include "qcopenvelope_qws.h"
23#endif 23#endif
24#include <qbuffer.h> 24#include <qbuffer.h>
25#include <qfile.h> 25#include <qfile.h>
26#include <unistd.h> 26#include <unistd.h>
27#include <errno.h> 27#include <errno.h>
28#include <sys/file.h> 28#include <sys/file.h>
29#include <sys/types.h> 29#include <sys/types.h>
30#include <sys/stat.h> 30#include <sys/stat.h>
31#include <time.h> 31#include <time.h>
32 32
33#ifndef QT_NO_COP 33#ifndef QT_NO_COP
34 34
35/*! 35/*!
36 \class QCopEnvelope qcopenvelope_qws.h 36 \class QCopEnvelope qcopenvelope_qws.h
37 \brief The QCopEnvelope class encapsulates and sends QCop messages 37 \brief The QCopEnvelope class encapsulates and sends QCop messages
38 over QCopChannels. 38 over QCopChannels.
39 39
40 QCop messages allow applications to communicate with each other. 40 QCop messages allow applications to communicate with each other.
41 These messages are sent using QCopEnvelope, and received by connecting 41 These messages are sent using QCopEnvelope, and received by connecting
42 to a QCopChannel. 42 to a QCopChannel.
43 43
44 To send a message, use the following protocol: 44 To send a message, use the following protocol:
45 45
46 \code 46 \code
47 QCopEnvelope e(channelname, messagename); 47 QCopEnvelope e(channelname, messagename);
48 e << parameter1 << parameter2 << ...; 48 e << parameter1 << parameter2 << ...;
49 \endcode 49 \endcode
50 50
51 For messages without parameters, simply use: 51 For messages without parameters, simply use:
52 52
53 \code 53 \code
54 QCopEnvelope e(channelname, messagename); 54 QCopEnvelope e(channelname, messagename);
55 \endcode 55 \endcode
56 56
57 (Do not try to simplify this further as it may confuse some 57 (Do not try to simplify this further as it may confuse some
58 compilers.) 58 compilers.)
59 59
60 The \c{channelname} of channels within Qtopia all start with "QPE/". 60 The \c{channelname} of channels within Qtopia all start with "QPE/".
61 The \c{messagename} is a function identifier followed by a list of types 61 The \c{messagename} is a function identifier followed by a list of types
62 in parentheses. There is no whitespace in the message name. 62 in parentheses. There is no whitespace in the message name.
63 63
64 To receive a message, you will generally just use your application's 64 To receive a message, you will generally just use your application's
65 predefined QPE/Application/\e{appname} channel 65 predefined QPE/Application/\e{appname} channel
66 (see QPEApplication::appMessage()), but you can make another channel 66 (see QPEApplication::appMessage()), but you can make another channel
67 and connect it to a slot like this: 67 and connect it to a slot like this:
68 68
69 \code 69 \code
70 myChannel = new QCopChannel( "QPE/FooBar", this ); 70 myChannel = new QCopChannel( "QPE/FooBar", this );
71 connect( myChannel, SIGNAL(received(const QCString &, const QByteArray &)), 71 connect( myChannel, SIGNAL(received(const QCString&,const QByteArray&)),
72 this, SLOT(fooBarMessage( const QCString &, const QByteArray &)) ); 72 this, SLOT(fooBarMessage(const QCString&,const QByteArray&)) );
73 \endcode 73 \endcode
74 74
75 See also, the \link qcop.html list of Qtopia messages\endlink. 75 See also, the \link qcop.html list of Qtopia messages\endlink.
76*/ 76*/
77 77
78/*! 78/*!
79 Constructs a QCopEnvelope that will write \a message to \a channel. 79 Constructs a QCopEnvelope that will write \a message to \a channel.
80 If \a message has parameters, you must then use operator<<() to 80 If \a message has parameters, you must then use operator<<() to
81 add these parameters to the envelope. 81 add these parameters to the envelope.
82*/ 82*/
83QCopEnvelope::QCopEnvelope( const QCString& channel, const QCString& message ) : 83QCopEnvelope::QCopEnvelope( const QCString& channel, const QCString& message ) :
84 QDataStream(new QBuffer), 84 QDataStream(new QBuffer),
85 ch(channel), msg(message) 85 ch(channel), msg(message)
86{ 86{
87 device()->open(IO_WriteOnly); 87 device()->open(IO_WriteOnly);
88} 88}
89 89
90/*! 90/*!
91 Writes the message and then destroys the QCopEnvelope. 91 Writes the message and then destroys the QCopEnvelope.
92*/ 92*/
93QCopEnvelope::~QCopEnvelope() 93QCopEnvelope::~QCopEnvelope()
94{ 94{
95 QByteArray data = ((QBuffer*)device())->buffer(); 95 QByteArray data = ((QBuffer*)device())->buffer();
96 const int pref=16; 96 const int pref=16;
97 if ( qstrncmp(ch.data(),"QPE/Application/",pref)==0 ) { 97 if ( qstrncmp(ch.data(),"QPE/Application/",pref)==0 ) {
98 QString qcopfn("/tmp/qcop-msg-"); 98 QString qcopfn("/tmp/qcop-msg-");
99 qcopfn += ch.mid(pref); 99 qcopfn += ch.mid(pref);
100 QFile qcopfile(qcopfn); 100 QFile qcopfile(qcopfn);
101 101
102 if ( qcopfile.open(IO_WriteOnly | IO_Append) ) { 102 if ( qcopfile.open(IO_WriteOnly | IO_Append) ) {
103#ifndef Q_OS_WIN32 103#ifndef Q_OS_WIN32
104 if(flock(qcopfile.handle(), LOCK_EX)) { 104 if(flock(qcopfile.handle(), LOCK_EX)) {
105 /* some error occurred */ 105 /* some error occurred */
106 qWarning(QString("Failed to obtain file lock on %1 (%2)") 106 qWarning(QString("Failed to obtain file lock on %1 (%2)")
107 .arg(qcopfn).arg( errno )); 107 .arg(qcopfn).arg( errno ));
108 } 108 }
109#endif 109#endif
110 { 110 {
111 QDataStream ds(&qcopfile); 111 QDataStream ds(&qcopfile);
112 ds << ch << msg << data; 112 ds << ch << msg << data;
113 qcopfile.flush(); 113 qcopfile.flush();
114#ifndef Q_OS_WIN32 114#ifndef Q_OS_WIN32
115 flock(qcopfile.handle(), LOCK_UN); 115 flock(qcopfile.handle(), LOCK_UN);
116#endif 116#endif
117 qcopfile.close(); 117 qcopfile.close();
118 } 118 }
119 119
120 QByteArray b; 120 QByteArray b;
121 QDataStream stream(b, IO_WriteOnly); 121 QDataStream stream(b, IO_WriteOnly);
122 stream << QString(ch.mid(pref)); 122 stream << QString(ch.mid(pref));
123 QCopChannel::send("QPE/Server", "processQCop(QString)", b); 123 QCopChannel::send("QPE/Server", "processQCop(QString)", b);
124 delete device(); 124 delete device();
125 return; 125 return;
126 } else { 126 } else {
127 qWarning(QString("Failed to open file %1") 127 qWarning(QString("Failed to open file %1")
128 .arg(qcopfn)); 128 .arg(qcopfn));
129 } // endif open 129 } // endif open
130 } 130 }
131 else if (qstrncmp(ch.data(), "QPE/SOAP/", 9) == 0) { 131 else if (qstrncmp(ch.data(), "QPE/SOAP/", 9) == 0) {
132 // If this is a message that should go along the SOAP channel, we move the 132 // If this is a message that should go along the SOAP channel, we move the
133 // endpoint URL to the data section. 133 // endpoint URL to the data section.
134 QString endpoint = ch.mid(9); 134 QString endpoint = ch.mid(9);
135 135
136 ch = "QPE/SOAP"; 136 ch = "QPE/SOAP";
137 // Since byte arrays are explicitly shared, this is appended to the data variable.. 137 // Since byte arrays are explicitly shared, this is appended to the data variable..
138 *this << endpoint; 138 *this << endpoint;
139 } 139 }
140 140
141 QCopChannel::send(ch,msg,data); 141 QCopChannel::send(ch,msg,data);
142 delete device(); 142 delete device();
143} 143}
144 144
145#endif 145#endif
diff --git a/library/qpeapplication.cpp b/library/qpeapplication.cpp
index 262221e..c339a78 100644
--- a/library/qpeapplication.cpp
+++ b/library/qpeapplication.cpp
@@ -1,2099 +1,2099 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19*/ 19*/
20#define QTOPIA_INTERNAL_LANGLIST 20#define QTOPIA_INTERNAL_LANGLIST
21#include <stdlib.h> 21#include <stdlib.h>
22#include <unistd.h> 22#include <unistd.h>
23#ifndef Q_OS_MACX 23#ifndef Q_OS_MACX
24#include <linux/limits.h> // needed for some toolchains (PATH_MAX) 24#include <linux/limits.h> // needed for some toolchains (PATH_MAX)
25#endif 25#endif
26#include <qfile.h> 26#include <qfile.h>
27#include <qqueue.h> 27#include <qqueue.h>
28#ifdef Q_WS_QWS 28#ifdef Q_WS_QWS
29#ifndef QT_NO_COP 29#ifndef QT_NO_COP
30#if QT_VERSION <= 231 30#if QT_VERSION <= 231
31#define private public 31#define private public
32#define sendLocally processEvent 32#define sendLocally processEvent
33#include "qcopenvelope_qws.h" 33#include "qcopenvelope_qws.h"
34#undef private 34#undef private
35#else 35#else
36#include "qcopenvelope_qws.h" 36#include "qcopenvelope_qws.h"
37#endif 37#endif
38#endif 38#endif
39#include <qwindowsystem_qws.h> 39#include <qwindowsystem_qws.h>
40#endif 40#endif
41#include <qtextstream.h> 41#include <qtextstream.h>
42#include <qpalette.h> 42#include <qpalette.h>
43#include <qbuffer.h> 43#include <qbuffer.h>
44#include <qptrdict.h> 44#include <qptrdict.h>
45#include <qregexp.h> 45#include <qregexp.h>
46#include <qdir.h> 46#include <qdir.h>
47#include <qlabel.h> 47#include <qlabel.h>
48#include <qdialog.h> 48#include <qdialog.h>
49#include <qdragobject.h> 49#include <qdragobject.h>
50#include <qtextcodec.h> 50#include <qtextcodec.h>
51#include <qevent.h> 51#include <qevent.h>
52#include <qtooltip.h> 52#include <qtooltip.h>
53#include <qsignal.h> 53#include <qsignal.h>
54#include <qmainwindow.h> 54#include <qmainwindow.h>
55#include <qwidgetlist.h> 55#include <qwidgetlist.h>
56#include <qpixmapcache.h> 56#include <qpixmapcache.h>
57 57
58#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 58#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
59#define QTOPIA_INTERNAL_INITAPP 59#define QTOPIA_INTERNAL_INITAPP
60#include "qpeapplication.h" 60#include "qpeapplication.h"
61#include "qpestyle.h" 61#include "qpestyle.h"
62#include "styleinterface.h" 62#include "styleinterface.h"
63#if QT_VERSION >= 300 63#if QT_VERSION >= 300
64#include <qstylefactory.h> 64#include <qstylefactory.h>
65#else 65#else
66#include <qplatinumstyle.h> 66#include <qplatinumstyle.h>
67#include <qwindowsstyle.h> 67#include <qwindowsstyle.h>
68#include <qmotifstyle.h> 68#include <qmotifstyle.h>
69#include <qmotifplusstyle.h> 69#include <qmotifplusstyle.h>
70#include "lightstyle.h" 70#include "lightstyle.h"
71 71
72#include <qpe/qlibrary.h> 72#include <qpe/qlibrary.h>
73#endif 73#endif
74#include "global.h" 74#include "global.h"
75#include "resource.h" 75#include "resource.h"
76#if QT_VERSION <= 230 && defined(QT_NO_CODECS) 76#if QT_VERSION <= 230 && defined(QT_NO_CODECS)
77#include "qutfcodec.h" 77#include "qutfcodec.h"
78#endif 78#endif
79#include "config.h" 79#include "config.h"
80#include "network.h" 80#include "network.h"
81#ifdef QWS 81#ifdef QWS
82#include "fontmanager.h" 82#include "fontmanager.h"
83#endif 83#endif
84 84
85#include "alarmserver.h" 85#include "alarmserver.h"
86#include "applnk.h" 86#include "applnk.h"
87#include "qpemenubar.h" 87#include "qpemenubar.h"
88#include "textcodecinterface.h" 88#include "textcodecinterface.h"
89#include "imagecodecinterface.h" 89#include "imagecodecinterface.h"
90 90
91#include <unistd.h> 91#include <unistd.h>
92#include <sys/file.h> 92#include <sys/file.h>
93#include <sys/ioctl.h> 93#include <sys/ioctl.h>
94#ifndef QT_NO_SOUND 94#ifndef QT_NO_SOUND
95#include <sys/soundcard.h> 95#include <sys/soundcard.h>
96#endif 96#endif
97#include "qt_override_p.h" 97#include "qt_override_p.h"
98 98
99 99
100class QPEApplicationData 100class QPEApplicationData
101{ 101{
102public: 102public:
103 QPEApplicationData ( ) 103 QPEApplicationData ( )
104 : presstimer( 0 ), presswidget( 0 ), rightpressed( false ), kbgrabbed( false ), 104 : presstimer( 0 ), presswidget( 0 ), rightpressed( false ), kbgrabbed( false ),
105 notbusysent( false ), preloaded( false ), forceshow( false ), nomaximize( false ), 105 notbusysent( false ), preloaded( false ), forceshow( false ), nomaximize( false ),
106 keep_running( true ), qcopQok( false ), qpe_main_widget( 0 ) 106 keep_running( true ), qcopQok( false ), qpe_main_widget( 0 )
107 107
108 {} 108 {}
109 109
110 int presstimer; 110 int presstimer;
111 QWidget* presswidget; 111 QWidget* presswidget;
112 QPoint presspos; 112 QPoint presspos;
113 113
114 bool rightpressed : 1; 114 bool rightpressed : 1;
115 bool kbgrabbed : 1; 115 bool kbgrabbed : 1;
116 bool notbusysent : 1; 116 bool notbusysent : 1;
117 bool preloaded : 1; 117 bool preloaded : 1;
118 bool forceshow : 1; 118 bool forceshow : 1;
119 bool nomaximize : 1; 119 bool nomaximize : 1;
120 bool keep_running : 1; 120 bool keep_running : 1;
121 bool qcopQok : 1; 121 bool qcopQok : 1;
122 122
123 123
124 QStringList langs; 124 QStringList langs;
125 QString appName; 125 QString appName;
126 struct QCopRec 126 struct QCopRec
127 { 127 {
128 QCopRec( const QCString &ch, const QCString &msg, 128 QCopRec( const QCString &ch, const QCString &msg,
129 const QByteArray &d ) : 129 const QByteArray &d ) :
130 channel( ch ), message( msg ), data( d ) 130 channel( ch ), message( msg ), data( d )
131 { } 131 { }
132 132
133 QCString channel; 133 QCString channel;
134 QCString message; 134 QCString message;
135 QByteArray data; 135 QByteArray data;
136 }; 136 };
137 QWidget* qpe_main_widget; 137 QWidget* qpe_main_widget;
138 QGuardedPtr<QWidget> lastraised; 138 QGuardedPtr<QWidget> lastraised;
139 QQueue<QCopRec> qcopq; 139 QQueue<QCopRec> qcopq;
140 QString styleName; 140 QString styleName;
141 QString decorationName; 141 QString decorationName;
142 142
143 void enqueueQCop( const QCString &ch, const QCString &msg, 143 void enqueueQCop( const QCString &ch, const QCString &msg,
144 const QByteArray &data ) 144 const QByteArray &data )
145 { 145 {
146 qcopq.enqueue( new QCopRec( ch, msg, data ) ); 146 qcopq.enqueue( new QCopRec( ch, msg, data ) );
147 } 147 }
148 void sendQCopQ() 148 void sendQCopQ()
149 { 149 {
150 if (!qcopQok ) 150 if (!qcopQok )
151 return; 151 return;
152 152
153 QCopRec * r; 153 QCopRec * r;
154 154
155 while((r=qcopq.dequeue())) { 155 while((r=qcopq.dequeue())) {
156 // remove from queue before sending... 156 // remove from queue before sending...
157 // event loop can come around again before getting 157 // event loop can come around again before getting
158 // back from sendLocally 158 // back from sendLocally
159#ifndef QT_NO_COP 159#ifndef QT_NO_COP
160 QCopChannel::sendLocally( r->channel, r->message, r->data ); 160 QCopChannel::sendLocally( r->channel, r->message, r->data );
161#endif 161#endif
162 162
163 delete r; 163 delete r;
164 } 164 }
165 } 165 }
166 static void show_mx(QWidget* mw, bool nomaximize, const QString & = QString::null ) 166 static void show_mx(QWidget* mw, bool nomaximize, const QString & = QString::null )
167 { 167 {
168 168
169 // ugly hack, remove that later after finding a sane solution 169 // ugly hack, remove that later after finding a sane solution
170 // Addendum: Only Sharp currently has models with high resolution but (physically) small displays, 170 // Addendum: Only Sharp currently has models with high resolution but (physically) small displays,
171 // so this is only useful if QT_QWS_SIMPAD is NOT defined. E.g. SIMpad has 800x600 but has 171 // so this is only useful if QT_QWS_SIMPAD is NOT defined. E.g. SIMpad has 800x600 but has
172 // a (physically) large enough display to use the small icons 172 // a (physically) large enough display to use the small icons
173#if defined(OPIE_HIGH_RES_SMALL_PHY) 173#if defined(OPIE_HIGH_RES_SMALL_PHY)
174 if ( QPEApplication::desktop() ->width() >= 600 && ( mw->inherits("QMainWindow") || mw->isA("QMainWindow") ) ) { 174 if ( QPEApplication::desktop() ->width() >= 600 && ( mw->inherits("QMainWindow") || mw->isA("QMainWindow") ) ) {
175 ( ( QMainWindow* ) mw )->setUsesBigPixmaps( true ); 175 ( ( QMainWindow* ) mw )->setUsesBigPixmaps( true );
176 } 176 }
177#endif 177#endif
178 178
179 if ( mw->layout() && mw->inherits("QDialog") ) { 179 if ( mw->layout() && mw->inherits("QDialog") ) {
180 QPEApplication::showDialog((QDialog*)mw, nomaximize); 180 QPEApplication::showDialog((QDialog*)mw, nomaximize);
181 } 181 }
182 else { 182 else {
183#ifdef Q_WS_QWS 183#ifdef Q_WS_QWS
184 if ( !nomaximize ) 184 if ( !nomaximize )
185 mw->showMaximized(); 185 mw->showMaximized();
186 else 186 else
187#endif 187#endif
188 188
189 mw->show(); 189 mw->show();
190 } 190 }
191 } 191 }
192 static bool setWidgetCaptionFromAppName( QWidget* /*mw*/, const QString& /*appName*/, const QString& /*appsPath*/ ) 192 static bool setWidgetCaptionFromAppName( QWidget* /*mw*/, const QString& /*appName*/, const QString& /*appsPath*/ )
193 { 193 {
194 /* 194 /*
195 // This works but disable it for now until it is safe to apply 195 // This works but disable it for now until it is safe to apply
196 // What is does is scan the .desktop files of all the apps for 196 // What is does is scan the .desktop files of all the apps for
197 // the applnk that has the corresponding argv[0] as this program 197 // the applnk that has the corresponding argv[0] as this program
198 // then it uses the name stored in the .desktop file as the caption 198 // then it uses the name stored in the .desktop file as the caption
199 // for the main widget. This saves duplicating translations for 199 // for the main widget. This saves duplicating translations for
200 // the app name in the program and in the .desktop files. 200 // the app name in the program and in the .desktop files.
201 201
202 AppLnkSet apps( appsPath ); 202 AppLnkSet apps( appsPath );
203 203
204 QList<AppLnk> appsList = apps.children(); 204 QList<AppLnk> appsList = apps.children();
205 for ( QListIterator<AppLnk> it(appsList); it.current(); ++it ) { 205 for ( QListIterator<AppLnk> it(appsList); it.current(); ++it ) {
206 if ( (*it)->exec() == appName ) { 206 if ( (*it)->exec() == appName ) {
207 mw->setCaption( (*it)->name() ); 207 mw->setCaption( (*it)->name() );
208 return TRUE; 208 return TRUE;
209 } 209 }
210 } 210 }
211 */ 211 */
212 return FALSE; 212 return FALSE;
213 } 213 }
214 214
215 215
216 void show(QWidget* mw, bool nomax) 216 void show(QWidget* mw, bool nomax)
217 { 217 {
218 setWidgetCaptionFromAppName( mw, appName, QPEApplication::qpeDir() + "apps" ); 218 setWidgetCaptionFromAppName( mw, appName, QPEApplication::qpeDir() + "apps" );
219 nomaximize = nomax; 219 nomaximize = nomax;
220 qpe_main_widget = mw; 220 qpe_main_widget = mw;
221 qcopQok = TRUE; 221 qcopQok = TRUE;
222#ifndef QT_NO_COP 222#ifndef QT_NO_COP
223 223
224 sendQCopQ(); 224 sendQCopQ();
225#endif 225#endif
226 226
227 if ( preloaded ) { 227 if ( preloaded ) {
228 if (forceshow) 228 if (forceshow)
229 show_mx(mw, nomax); 229 show_mx(mw, nomax);
230 } 230 }
231 else if ( keep_running ) { 231 else if ( keep_running ) {
232 show_mx(mw, nomax); 232 show_mx(mw, nomax);
233 } 233 }
234 } 234 }
235 235
236 void loadTextCodecs() 236 void loadTextCodecs()
237 { 237 {
238 QString path = QPEApplication::qpeDir() + "/plugins/textcodecs"; 238 QString path = QPEApplication::qpeDir() + "/plugins/textcodecs";
239#ifdef Q_OS_MACX 239#ifdef Q_OS_MACX
240 QDir dir( path, "lib*.dylib" ); 240 QDir dir( path, "lib*.dylib" );
241#else 241#else
242 QDir dir( path, "lib*.so" ); 242 QDir dir( path, "lib*.so" );
243#endif 243#endif
244 QStringList list; 244 QStringList list;
245 if ( dir. exists ( )) 245 if ( dir. exists ( ))
246 list = dir.entryList(); 246 list = dir.entryList();
247 QStringList::Iterator it; 247 QStringList::Iterator it;
248 for ( it = list.begin(); it != list.end(); ++it ) { 248 for ( it = list.begin(); it != list.end(); ++it ) {
249 TextCodecInterface *iface = 0; 249 TextCodecInterface *iface = 0;
250 QLibrary *lib = new QLibrary( path + "/" + *it ); 250 QLibrary *lib = new QLibrary( path + "/" + *it );
251 if ( lib->queryInterface( IID_QtopiaTextCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) { 251 if ( lib->queryInterface( IID_QtopiaTextCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) {
252 QValueList<int> mibs = iface->mibEnums(); 252 QValueList<int> mibs = iface->mibEnums();
253 for (QValueList<int>::ConstIterator i = mibs.begin(); i != mibs.end(); ++i) { 253 for (QValueList<int>::ConstIterator i = mibs.begin(); i != mibs.end(); ++i) {
254 (void)iface->createForMib(*i); 254 (void)iface->createForMib(*i);
255 // ### it exists now; need to remember if we can delete it 255 // ### it exists now; need to remember if we can delete it
256 } 256 }
257 } 257 }
258 else { 258 else {
259 lib->unload(); 259 lib->unload();
260 delete lib; 260 delete lib;
261 } 261 }
262 } 262 }
263 } 263 }
264 264
265 void loadImageCodecs() 265 void loadImageCodecs()
266 { 266 {
267 QString path = QPEApplication::qpeDir() + "/plugins/imagecodecs"; 267 QString path = QPEApplication::qpeDir() + "/plugins/imagecodecs";
268#ifdef Q_OS_MACX 268#ifdef Q_OS_MACX
269 QDir dir( path, "lib*.dylib" ); 269 QDir dir( path, "lib*.dylib" );
270#else 270#else
271 QDir dir( path, "lib*.so" ); 271 QDir dir( path, "lib*.so" );
272#endif 272#endif
273 QStringList list; 273 QStringList list;
274 if ( dir. exists ( )) 274 if ( dir. exists ( ))
275 list = dir.entryList(); 275 list = dir.entryList();
276 QStringList::Iterator it; 276 QStringList::Iterator it;
277 for ( it = list.begin(); it != list.end(); ++it ) { 277 for ( it = list.begin(); it != list.end(); ++it ) {
278 ImageCodecInterface *iface = 0; 278 ImageCodecInterface *iface = 0;
279 QLibrary *lib = new QLibrary( path + "/" + *it ); 279 QLibrary *lib = new QLibrary( path + "/" + *it );
280 if ( lib->queryInterface( IID_QtopiaImageCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) { 280 if ( lib->queryInterface( IID_QtopiaImageCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) {
281 QStringList formats = iface->keys(); 281 QStringList formats = iface->keys();
282 for (QStringList::ConstIterator i = formats.begin(); i != formats.end(); ++i) { 282 for (QStringList::ConstIterator i = formats.begin(); i != formats.end(); ++i) {
283 (void)iface->installIOHandler(*i); 283 (void)iface->installIOHandler(*i);
284 // ### it exists now; need to remember if we can delete it 284 // ### it exists now; need to remember if we can delete it
285 } 285 }
286 } 286 }
287 else { 287 else {
288 lib->unload(); 288 lib->unload();
289 delete lib; 289 delete lib;
290 } 290 }
291 } 291 }
292 } 292 }
293}; 293};
294 294
295class ResourceMimeFactory : public QMimeSourceFactory 295class ResourceMimeFactory : public QMimeSourceFactory
296{ 296{
297public: 297public:
298 ResourceMimeFactory() : resImage( 0 ) 298 ResourceMimeFactory() : resImage( 0 )
299 { 299 {
300 setFilePath( Global::helpPath() ); 300 setFilePath( Global::helpPath() );
301 setExtensionType( "html", "text/html;charset=UTF-8" ); 301 setExtensionType( "html", "text/html;charset=UTF-8" );
302 } 302 }
303 ~ResourceMimeFactory() { 303 ~ResourceMimeFactory() {
304 delete resImage; 304 delete resImage;
305 } 305 }
306 306
307 const QMimeSource* data( const QString& abs_name ) const 307 const QMimeSource* data( const QString& abs_name ) const
308 { 308 {
309 const QMimeSource * r = QMimeSourceFactory::data( abs_name ); 309 const QMimeSource * r = QMimeSourceFactory::data( abs_name );
310 if ( !r ) { 310 if ( !r ) {
311 int sl = abs_name.length(); 311 int sl = abs_name.length();
312 do { 312 do {
313 sl = abs_name.findRev( '/', sl - 1 ); 313 sl = abs_name.findRev( '/', sl - 1 );
314 QString name = sl >= 0 ? abs_name.mid( sl + 1 ) : abs_name; 314 QString name = sl >= 0 ? abs_name.mid( sl + 1 ) : abs_name;
315 int dot = name.findRev( '.' ); 315 int dot = name.findRev( '.' );
316 if ( dot >= 0 ) 316 if ( dot >= 0 )
317 name = name.left( dot ); 317 name = name.left( dot );
318 QImage img = Resource::loadImage( name ); 318 QImage img = Resource::loadImage( name );
319 if ( !img.isNull() ) { 319 if ( !img.isNull() ) {
320 delete resImage; 320 delete resImage;
321 resImage = new QImageDrag( img ); 321 resImage = new QImageDrag( img );
322 r = resImage; 322 r = resImage;
323 } 323 }
324 } 324 }
325 while ( !r && sl > 0 ); 325 while ( !r && sl > 0 );
326 } 326 }
327 return r; 327 return r;
328 } 328 }
329private: 329private:
330 mutable QImageDrag *resImage; 330 mutable QImageDrag *resImage;
331}; 331};
332 332
333static int& hack(int& i) 333static int& hack(int& i)
334{ 334{
335#if QT_VERSION <= 230 && defined(QT_NO_CODECS) 335#if QT_VERSION <= 230 && defined(QT_NO_CODECS)
336 // These should be created, but aren't in Qt 2.3.0 336 // These should be created, but aren't in Qt 2.3.0
337 (void)new QUtf8Codec; 337 (void)new QUtf8Codec;
338 (void)new QUtf16Codec; 338 (void)new QUtf16Codec;
339#endif 339#endif
340 return i; 340 return i;
341} 341}
342 342
343static int muted = 0; 343static int muted = 0;
344static int micMuted = 0; 344static int micMuted = 0;
345 345
346static void setVolume( int t = 0, int percent = -1 ) 346static void setVolume( int t = 0, int percent = -1 )
347{ 347{
348 switch ( t ) { 348 switch ( t ) {
349 case 0: { 349 case 0: {
350 Config cfg( "qpe" ); 350 Config cfg( "qpe" );
351 cfg.setGroup( "Volume" ); 351 cfg.setGroup( "Volume" );
352 if ( percent < 0 ) 352 if ( percent < 0 )
353 percent = cfg.readNumEntry( "VolumePercent", 50 ); 353 percent = cfg.readNumEntry( "VolumePercent", 50 );
354#ifndef QT_NO_SOUND 354#ifndef QT_NO_SOUND
355 int fd = 0; 355 int fd = 0;
356 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { 356 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) {
357 int vol = muted ? 0 : percent; 357 int vol = muted ? 0 : percent;
358 // set both channels to same volume 358 // set both channels to same volume
359 vol |= vol << 8; 359 vol |= vol << 8;
360 ioctl( fd, MIXER_WRITE( 0 ), &vol ); 360 ioctl( fd, MIXER_WRITE( 0 ), &vol );
361 ::close( fd ); 361 ::close( fd );
362 } 362 }
363#endif 363#endif
364 } 364 }
365 break; 365 break;
366 } 366 }
367} 367}
368 368
369static void setMic( int t = 0, int percent = -1 ) 369static void setMic( int t = 0, int percent = -1 )
370{ 370{
371 switch ( t ) { 371 switch ( t ) {
372 case 0: { 372 case 0: {
373 Config cfg( "qpe" ); 373 Config cfg( "qpe" );
374 cfg.setGroup( "Volume" ); 374 cfg.setGroup( "Volume" );
375 if ( percent < 0 ) 375 if ( percent < 0 )
376 percent = cfg.readNumEntry( "Mic", 50 ); 376 percent = cfg.readNumEntry( "Mic", 50 );
377 377
378#ifndef QT_NO_SOUND 378#ifndef QT_NO_SOUND
379 int fd = 0; 379 int fd = 0;
380 int mic = micMuted ? 0 : percent; 380 int mic = micMuted ? 0 : percent;
381 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { 381 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) {
382 ioctl( fd, MIXER_WRITE( SOUND_MIXER_MIC ), &mic ); 382 ioctl( fd, MIXER_WRITE( SOUND_MIXER_MIC ), &mic );
383 ::close( fd ); 383 ::close( fd );
384 } 384 }
385#endif 385#endif
386 } 386 }
387 break; 387 break;
388 } 388 }
389} 389}
390 390
391 391
392static void setBass( int t = 0, int percent = -1 ) 392static void setBass( int t = 0, int percent = -1 )
393{ 393{
394 switch ( t ) { 394 switch ( t ) {
395 case 0: { 395 case 0: {
396 Config cfg( "qpe" ); 396 Config cfg( "qpe" );
397 cfg.setGroup( "Volume" ); 397 cfg.setGroup( "Volume" );
398 if ( percent < 0 ) 398 if ( percent < 0 )
399 percent = cfg.readNumEntry( "BassPercent", 50 ); 399 percent = cfg.readNumEntry( "BassPercent", 50 );
400 400
401#ifndef QT_NO_SOUND 401#ifndef QT_NO_SOUND
402 int fd = 0; 402 int fd = 0;
403 int bass = percent; 403 int bass = percent;
404 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { 404 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) {
405 ioctl( fd, MIXER_WRITE( SOUND_MIXER_BASS ), &bass ); 405 ioctl( fd, MIXER_WRITE( SOUND_MIXER_BASS ), &bass );
406 ::close( fd ); 406 ::close( fd );
407 } 407 }
408#endif 408#endif
409 } 409 }
410 break; 410 break;
411 } 411 }
412} 412}
413 413
414 414
415static void setTreble( int t = 0, int percent = -1 ) 415static void setTreble( int t = 0, int percent = -1 )
416{ 416{
417 switch ( t ) { 417 switch ( t ) {
418 case 0: { 418 case 0: {
419 Config cfg( "qpe" ); 419 Config cfg( "qpe" );
420 cfg.setGroup( "Volume" ); 420 cfg.setGroup( "Volume" );
421 if ( percent < 0 ) 421 if ( percent < 0 )
422 percent = cfg.readNumEntry( "TreblePercent", 50 ); 422 percent = cfg.readNumEntry( "TreblePercent", 50 );
423 423
424#ifndef QT_NO_SOUND 424#ifndef QT_NO_SOUND
425 int fd = 0; 425 int fd = 0;
426 int treble = percent; 426 int treble = percent;
427 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { 427 if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) {
428 ioctl( fd, MIXER_WRITE( SOUND_MIXER_TREBLE ), &treble ); 428 ioctl( fd, MIXER_WRITE( SOUND_MIXER_TREBLE ), &treble );
429 ::close( fd ); 429 ::close( fd );
430 } 430 }
431#endif 431#endif
432 } 432 }
433 break; 433 break;
434 } 434 }
435} 435}
436 436
437 437
438/** 438/**
439 \class QPEApplication 439 \class QPEApplication
440 \brief The QPEApplication class implements various system services 440 \brief The QPEApplication class implements various system services
441 that are available to all Qtopia applications. 441 that are available to all Qtopia applications.
442 442
443 Simply by using QPEApplication instead of QApplication, a standard Qt 443 Simply by using QPEApplication instead of QApplication, a standard Qt
444 application becomes a Qtopia application. It automatically follows 444 application becomes a Qtopia application. It automatically follows
445 style changes, quits and raises, and in the 445 style changes, quits and raises, and in the
446 case of \link docwidget.html document-oriented\endlink applications, 446 case of \link docwidget.html document-oriented\endlink applications,
447 changes the currently displayed document in response to the environment. 447 changes the currently displayed document in response to the environment.
448 448
449 To create a \link docwidget.html document-oriented\endlink 449 To create a \link docwidget.html document-oriented\endlink
450 application use showMainDocumentWidget(); to create a 450 application use showMainDocumentWidget(); to create a
451 non-document-oriented application use showMainWidget(). The 451 non-document-oriented application use showMainWidget(). The
452 keepRunning() function indicates whether the application will 452 keepRunning() function indicates whether the application will
453 continue running after it's processed the last \link qcop.html 453 continue running after it's processed the last \link qcop.html
454 QCop\endlink message. This can be changed using setKeepRunning(). 454 QCop\endlink message. This can be changed using setKeepRunning().
455 455
456 A variety of signals are emitted when certain events occur, for 456 A variety of signals are emitted when certain events occur, for
457 example, timeChanged(), clockChanged(), weekChanged(), 457 example, timeChanged(), clockChanged(), weekChanged(),
458 dateFormatChanged() and volumeChanged(). If the application receives 458 dateFormatChanged() and volumeChanged(). If the application receives
459 a \link qcop.html QCop\endlink message on the application's 459 a \link qcop.html QCop\endlink message on the application's
460 QPE/Application/\e{appname} channel, the appMessage() signal is 460 QPE/Application/\e{appname} channel, the appMessage() signal is
461 emitted. There are also flush() and reload() signals, which 461 emitted. There are also flush() and reload() signals, which
462 are emitted when synching begins and ends respectively - upon these 462 are emitted when synching begins and ends respectively - upon these
463 signals, the application should save and reload any data 463 signals, the application should save and reload any data
464 files that are involved in synching. Most of these signals will initially 464 files that are involved in synching. Most of these signals will initially
465 be received and unfiltered through the appMessage() signal. 465 be received and unfiltered through the appMessage() signal.
466 466
467 This class also provides a set of useful static functions. The 467 This class also provides a set of useful static functions. The
468 qpeDir() and documentDir() functions return the respective paths. 468 qpeDir() and documentDir() functions return the respective paths.
469 The grabKeyboard() and ungrabKeyboard() functions are used to 469 The grabKeyboard() and ungrabKeyboard() functions are used to
470 control whether the application takes control of the device's 470 control whether the application takes control of the device's
471 physical buttons (e.g. application launch keys). The stylus' mode of 471 physical buttons (e.g. application launch keys). The stylus' mode of
472 operation is set with setStylusOperation() and retrieved with 472 operation is set with setStylusOperation() and retrieved with
473 stylusOperation(). There are also setInputMethodHint() and 473 stylusOperation(). There are also setInputMethodHint() and
474 inputMethodHint() functions. 474 inputMethodHint() functions.
475 475
476 \ingroup qtopiaemb 476 \ingroup qtopiaemb
477*/ 477*/
478 478
479/*! 479/*!
480 \fn void QPEApplication::clientMoused() 480 \fn void QPEApplication::clientMoused()
481 481
482 \internal 482 \internal
483*/ 483*/
484 484
485/*! 485/*!
486 \fn void QPEApplication::timeChanged(); 486 \fn void QPEApplication::timeChanged();
487 This signal is emitted when the time changes outside the normal 487 This signal is emitted when the time changes outside the normal
488 passage of time, i.e. if the time is set backwards or forwards. 488 passage of time, i.e. if the time is set backwards or forwards.
489*/ 489*/
490 490
491/*! 491/*!
492 \fn void QPEApplication::clockChanged( bool ampm ); 492 \fn void QPEApplication::clockChanged( bool ampm );
493 493
494 This signal is emitted when the user changes the clock's style. If 494 This signal is emitted when the user changes the clock's style. If
495 \a ampm is TRUE, the user wants a 12-hour AM/PM clock, otherwise, 495 \a ampm is TRUE, the user wants a 12-hour AM/PM clock, otherwise,
496 they want a 24-hour clock. 496 they want a 24-hour clock.
497*/ 497*/
498 498
499/*! 499/*!
500 \fn void QPEApplication::volumeChanged( bool muted ) 500 \fn void QPEApplication::volumeChanged( bool muted )
501 501
502 This signal is emitted whenever the mute state is changed. If \a 502 This signal is emitted whenever the mute state is changed. If \a
503 muted is TRUE, then sound output has been muted. 503 muted is TRUE, then sound output has been muted.
504*/ 504*/
505 505
506/*! 506/*!
507 \fn void QPEApplication::weekChanged( bool startOnMonday ) 507 \fn void QPEApplication::weekChanged( bool startOnMonday )
508 508
509 This signal is emitted if the week start day is changed. If \a 509 This signal is emitted if the week start day is changed. If \a
510 startOnMonday is TRUE then the first day of the week is Monday; if 510 startOnMonday is TRUE then the first day of the week is Monday; if
511 \a startOnMonday is FALSE then the first day of the week is 511 \a startOnMonday is FALSE then the first day of the week is
512 Sunday. 512 Sunday.
513*/ 513*/
514 514
515/*! 515/*!
516 \fn void QPEApplication::dateFormatChanged(DateFormat) 516 \fn void QPEApplication::dateFormatChanged(DateFormat)
517 517
518 This signal is emitted whenever the date format is changed. 518 This signal is emitted whenever the date format is changed.
519*/ 519*/
520 520
521/*! 521/*!
522 \fn void QPEApplication::flush() 522 \fn void QPEApplication::flush()
523 523
524 ### 524 ###
525*/ 525*/
526 526
527/*! 527/*!
528 \fn void QPEApplication::reload() 528 \fn void QPEApplication::reload()
529 529
530*/ 530*/
531 531
532 532
533 533
534void QPEApplication::processQCopFile() 534void QPEApplication::processQCopFile()
535{ 535{
536 QString qcopfn("/tmp/qcop-msg-"); 536 QString qcopfn("/tmp/qcop-msg-");
537 qcopfn += d->appName; // append command name 537 qcopfn += d->appName; // append command name
538 538
539 QFile f(qcopfn); 539 QFile f(qcopfn);
540 if ( f.open(IO_ReadWrite) ) { 540 if ( f.open(IO_ReadWrite) ) {
541#ifndef Q_OS_WIN32 541#ifndef Q_OS_WIN32
542 flock(f.handle(), LOCK_EX); 542 flock(f.handle(), LOCK_EX);
543#endif 543#endif
544 QDataStream ds(&f); 544 QDataStream ds(&f);
545 QCString channel, message; 545 QCString channel, message;
546 QByteArray data; 546 QByteArray data;
547 while(!ds.atEnd()) { 547 while(!ds.atEnd()) {
548 ds >> channel >> message >> data; 548 ds >> channel >> message >> data;
549 d->enqueueQCop(channel,message,data); 549 d->enqueueQCop(channel,message,data);
550 } 550 }
551 ::ftruncate(f.handle(), 0); 551 ::ftruncate(f.handle(), 0);
552#ifndef Q_OS_WIN32 552#ifndef Q_OS_WIN32
553 f.flush(); 553 f.flush();
554 flock(f.handle(), LOCK_UN); 554 flock(f.handle(), LOCK_UN);
555#endif 555#endif
556 } 556 }
557#endif 557#endif
558} 558}
559 559
560 560
561/*! 561/*!
562 \fn void QPEApplication::appMessage( const QCString& msg, const QByteArray& data ) 562 \fn void QPEApplication::appMessage( const QCString& msg, const QByteArray& data )
563 563
564 This signal is emitted when a message is received on this 564 This signal is emitted when a message is received on this
565 application's QPE/Application/<i>appname</i> \link qcop.html 565 application's QPE/Application/<i>appname</i> \link qcop.html
566 QCop\endlink channel. 566 QCop\endlink channel.
567 567
568 The slot to which you connect this signal uses \a msg and \a data 568 The slot to which you connect this signal uses \a msg and \a data
569 in the following way: 569 in the following way:
570 570
571\code 571\code
572 void MyWidget::receive( const QCString& msg, const QByteArray& data ) 572 void MyWidget::receive( const QCString& msg, const QByteArray& data )
573 { 573 {
574 QDataStream stream( data, IO_ReadOnly ); 574 QDataStream stream( data, IO_ReadOnly );
575 if ( msg == "someMessage(int,int,int)" ) { 575 if ( msg == "someMessage(int,int,int)" ) {
576 int a,b,c; 576 int a,b,c;
577 stream >> a >> b >> c; 577 stream >> a >> b >> c;
578 ... 578 ...
579 } else if ( msg == "otherMessage(QString)" ) { 579 } else if ( msg == "otherMessage(QString)" ) {
580 ... 580 ...
581 } 581 }
582 } 582 }
583\endcode 583\endcode
584 584
585 \sa qcop.html 585 \sa qcop.html
586 Note that messages received here may be processed by qpe application 586 Note that messages received here may be processed by qpe application
587 and emitted as signals, such as flush() and reload(). 587 and emitted as signals, such as flush() and reload().
588*/ 588*/
589 589
590/*! 590/*!
591 Constructs a QPEApplication just as you would construct 591 Constructs a QPEApplication just as you would construct
592 a QApplication, passing \a argc, \a argv, and \a t. 592 a QApplication, passing \a argc, \a argv, and \a t.
593 593
594 For applications, \a t should be the default, GuiClient. Only 594 For applications, \a t should be the default, GuiClient. Only
595 the Qtopia server passes GuiServer. 595 the Qtopia server passes GuiServer.
596*/ 596*/
597QPEApplication::QPEApplication( int & argc, char **argv, Type t ) 597QPEApplication::QPEApplication( int & argc, char **argv, Type t )
598 : QApplication( hack(argc), argv, t ), pidChannel( 0 ) 598 : QApplication( hack(argc), argv, t ), pidChannel( 0 )
599{ 599{
600 QPixmapCache::setCacheLimit(256); // sensible default for smaller devices. 600 QPixmapCache::setCacheLimit(256); // sensible default for smaller devices.
601 601
602 d = new QPEApplicationData; 602 d = new QPEApplicationData;
603 d->loadTextCodecs(); 603 d->loadTextCodecs();
604 d->loadImageCodecs(); 604 d->loadImageCodecs();
605 int dw = desktop() ->width(); 605 int dw = desktop() ->width();
606 606
607 if ( dw < 200 ) { 607 if ( dw < 200 ) {
608 setFont( QFont( "vera", 8 ) ); 608 setFont( QFont( "vera", 8 ) );
609 AppLnk::setSmallIconSize( 10 ); 609 AppLnk::setSmallIconSize( 10 );
610 AppLnk::setBigIconSize( 28 ); 610 AppLnk::setBigIconSize( 28 );
611 } 611 }
612#if defined(OPIE_HIGH_RES_SMALL_PHY) 612#if defined(OPIE_HIGH_RES_SMALL_PHY)
613 else if ( dw > 600 ) { 613 else if ( dw > 600 ) {
614 setFont( QFont( "vera", 16 ) ); 614 setFont( QFont( "vera", 16 ) );
615 AppLnk::setSmallIconSize( 24 ); 615 AppLnk::setSmallIconSize( 24 );
616 AppLnk::setBigIconSize( 48 ); 616 AppLnk::setBigIconSize( 48 );
617 } 617 }
618#endif 618#endif
619 else if ( dw > 200 ) { 619 else if ( dw > 200 ) {
620 setFont( QFont( "vera", 10 ) ); 620 setFont( QFont( "vera", 10 ) );
621 AppLnk::setSmallIconSize( 14 ); 621 AppLnk::setSmallIconSize( 14 );
622 AppLnk::setBigIconSize( 32 ); 622 AppLnk::setBigIconSize( 32 );
623 } 623 }
624 624
625 QMimeSourceFactory::setDefaultFactory( new ResourceMimeFactory ); 625 QMimeSourceFactory::setDefaultFactory( new ResourceMimeFactory );
626 626
627 connect( this, SIGNAL( lastWindowClosed() ), this, SLOT( hideOrQuit() ) ); 627 connect( this, SIGNAL( lastWindowClosed() ), this, SLOT( hideOrQuit() ) );
628 628
629 629
630 sysChannel = new QCopChannel( "QPE/System", this ); 630 sysChannel = new QCopChannel( "QPE/System", this );
631 connect( sysChannel, SIGNAL( received( const QCString &, const QByteArray & ) ), 631 connect( sysChannel, SIGNAL( received(const QCString&,const QByteArray&) ),
632 this, SLOT( systemMessage( const QCString &, const QByteArray & ) ) ); 632 this, SLOT( systemMessage(const QCString&,const QByteArray&) ) );
633 633
634/* COde now in initapp */ 634/* COde now in initapp */
635#if 0 635#if 0
636#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 636#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
637 637
638 QString qcopfn( "/tmp/qcop-msg-" ); 638 QString qcopfn( "/tmp/qcop-msg-" );
639 qcopfn += QString( argv[ 0 ] ); // append command name 639 qcopfn += QString( argv[ 0 ] ); // append command name
640 640
641 QFile f( qcopfn ); 641 QFile f( qcopfn );
642 if ( f.open( IO_ReadOnly ) ) { 642 if ( f.open( IO_ReadOnly ) ) {
643 flock( f.handle(), LOCK_EX ); 643 flock( f.handle(), LOCK_EX );
644 } 644 }
645 645
646 646
647 647
648 QCString channel = QCString( argv[ 0 ] ); 648 QCString channel = QCString( argv[ 0 ] );
649 channel.replace( QRegExp( ".*/" ), "" ); 649 channel.replace( QRegExp( ".*/" ), "" );
650 d->appName = channel; 650 d->appName = channel;
651 channel = "QPE/Application/" + channel; 651 channel = "QPE/Application/" + channel;
652 pidChannel = new QCopChannel( channel, this ); 652 pidChannel = new QCopChannel( channel, this );
653 connect( pidChannel, SIGNAL( received( const QCString &, const QByteArray & ) ), 653 connect( pidChannel, SIGNAL( received(const QCString&,const QByteArray&) ),
654 this, SLOT( pidMessage( const QCString &, const QByteArray & ) ) ); 654 this, SLOT( pidMessage(const QCString&,const QByteArray&) ) );
655 655
656 if ( f.isOpen() ) { 656 if ( f.isOpen() ) {
657 d->keep_running = FALSE; 657 d->keep_running = FALSE;
658 QDataStream ds( &f ); 658 QDataStream ds( &f );
659 QCString channel, message; 659 QCString channel, message;
660 QByteArray data; 660 QByteArray data;
661 while ( !ds.atEnd() ) { 661 while ( !ds.atEnd() ) {
662 ds >> channel >> message >> data; 662 ds >> channel >> message >> data;
663 d->enqueueQCop( channel, message, data ); 663 d->enqueueQCop( channel, message, data );
664 } 664 }
665 665
666 flock( f.handle(), LOCK_UN ); 666 flock( f.handle(), LOCK_UN );
667 f.close(); 667 f.close();
668 f.remove(); 668 f.remove();
669 } 669 }
670 670
671 for ( int a = 0; a < argc; a++ ) { 671 for ( int a = 0; a < argc; a++ ) {
672 if ( qstrcmp( argv[ a ], "-preload" ) == 0 ) { 672 if ( qstrcmp( argv[ a ], "-preload" ) == 0 ) {
673 argv[ a ] = argv[ a + 1 ]; 673 argv[ a ] = argv[ a + 1 ];
674 a++; 674 a++;
675 d->preloaded = TRUE; 675 d->preloaded = TRUE;
676 argc -= 1; 676 argc -= 1;
677 } 677 }
678 else if ( qstrcmp( argv[ a ], "-preload-show" ) == 0 ) { 678 else if ( qstrcmp( argv[ a ], "-preload-show" ) == 0 ) {
679 argv[ a ] = argv[ a + 1 ]; 679 argv[ a ] = argv[ a + 1 ];
680 a++; 680 a++;
681 d->preloaded = TRUE; 681 d->preloaded = TRUE;
682 d->forceshow = TRUE; 682 d->forceshow = TRUE;
683 argc -= 1; 683 argc -= 1;
684 } 684 }
685 } 685 }
686 686
687 /* overide stored arguments */ 687 /* overide stored arguments */
688 setArgs( argc, argv ); 688 setArgs( argc, argv );
689 689
690#endif 690#endif
691#else 691#else
692 initApp( argc, argv ); 692 initApp( argc, argv );
693#endif 693#endif
694 // qwsSetDecoration( new QPEDecoration() ); 694 // qwsSetDecoration( new QPEDecoration() );
695 695
696#ifndef QT_NO_TRANSLATION 696#ifndef QT_NO_TRANSLATION
697 697
698 d->langs = Global::languageList(); 698 d->langs = Global::languageList();
699 for ( QStringList::ConstIterator it = d->langs.begin(); it != d->langs.end(); ++it ) { 699 for ( QStringList::ConstIterator it = d->langs.begin(); it != d->langs.end(); ++it ) {
700 QString lang = *it; 700 QString lang = *it;
701 701
702 installTranslation( lang + "/libopie.qm"); 702 installTranslation( lang + "/libopie.qm");
703 installTranslation( lang + "/libqpe.qm" ); 703 installTranslation( lang + "/libqpe.qm" );
704 installTranslation( lang + "/" + d->appName + ".qm" ); 704 installTranslation( lang + "/" + d->appName + ".qm" );
705 705
706 706
707 //###language/font hack; should look it up somewhere 707 //###language/font hack; should look it up somewhere
708#ifdef QWS 708#ifdef QWS
709 709
710 if ( lang == "ja" || lang == "zh_CN" || lang == "zh_TW" || lang == "ko" ) { 710 if ( lang == "ja" || lang == "zh_CN" || lang == "zh_TW" || lang == "ko" ) {
711 QFont fn = FontManager::unicodeFont( FontManager::Proportional ); 711 QFont fn = FontManager::unicodeFont( FontManager::Proportional );
712 setFont( fn ); 712 setFont( fn );
713 } 713 }
714#endif 714#endif
715 } 715 }
716#endif 716#endif
717 717
718 applyStyle(); 718 applyStyle();
719 719
720 if ( type() == GuiServer ) { 720 if ( type() == GuiServer ) {
721 setVolume(); 721 setVolume();
722 } 722 }
723 723
724 installEventFilter( this ); 724 installEventFilter( this );
725 725
726 QPEMenuToolFocusManager::initialize(); 726 QPEMenuToolFocusManager::initialize();
727 727
728#ifdef QT_NO_QWS_CURSOR 728#ifdef QT_NO_QWS_CURSOR
729 // if we have no cursor, probably don't want tooltips 729 // if we have no cursor, probably don't want tooltips
730 QToolTip::setEnabled( FALSE ); 730 QToolTip::setEnabled( FALSE );
731#endif 731#endif
732} 732}
733 733
734 734
735#ifdef QTOPIA_INTERNAL_INITAPP 735#ifdef QTOPIA_INTERNAL_INITAPP
736void QPEApplication::initApp( int argc, char **argv ) 736void QPEApplication::initApp( int argc, char **argv )
737{ 737{
738 delete pidChannel; 738 delete pidChannel;
739 d->keep_running = TRUE; 739 d->keep_running = TRUE;
740 d->preloaded = FALSE; 740 d->preloaded = FALSE;
741 d->forceshow = FALSE; 741 d->forceshow = FALSE;
742 742
743 QCString channel = QCString(argv[0]); 743 QCString channel = QCString(argv[0]);
744 744
745 channel.replace(QRegExp(".*/"),""); 745 channel.replace(QRegExp(".*/"),"");
746 d->appName = channel; 746 d->appName = channel;
747 747
748 #if QT_VERSION > 235 748 #if QT_VERSION > 235
749 qt_fbdpy->setIdentity( channel ); // In Qt/E 2.3.6 749 qt_fbdpy->setIdentity( channel ); // In Qt/E 2.3.6
750 #endif 750 #endif
751 751
752 channel = "QPE/Application/" + channel; 752 channel = "QPE/Application/" + channel;
753 pidChannel = new QCopChannel( channel, this); 753 pidChannel = new QCopChannel( channel, this);
754 connect( pidChannel, SIGNAL(received(const QCString &, const QByteArray &)), 754 connect( pidChannel, SIGNAL(received(const QCString&,const QByteArray&)),
755 this, SLOT(pidMessage(const QCString &, const QByteArray &))); 755 this, SLOT(pidMessage(const QCString&,const QByteArray&)));
756 756
757 757
758 758
759 processQCopFile(); 759 processQCopFile();
760 d->keep_running = d->qcopq.isEmpty(); 760 d->keep_running = d->qcopq.isEmpty();
761 761
762 for (int a=0; a<argc; a++) { 762 for (int a=0; a<argc; a++) {
763 if ( qstrcmp(argv[a],"-preload")==0 ) { 763 if ( qstrcmp(argv[a],"-preload")==0 ) {
764 argv[a] = argv[a+1]; 764 argv[a] = argv[a+1];
765 a++; 765 a++;
766 d->preloaded = TRUE; 766 d->preloaded = TRUE;
767 argc-=1; 767 argc-=1;
768 } else if ( qstrcmp(argv[a],"-preload-show")==0 ) { 768 } else if ( qstrcmp(argv[a],"-preload-show")==0 ) {
769 argv[a] = argv[a+1]; 769 argv[a] = argv[a+1];
770 a++; 770 a++;
771 d->preloaded = TRUE; 771 d->preloaded = TRUE;
772 d->forceshow = TRUE; 772 d->forceshow = TRUE;
773 argc-=1; 773 argc-=1;
774 } 774 }
775 } 775 }
776 776
777 /* overide stored arguments */ 777 /* overide stored arguments */
778 setArgs(argc, argv); 778 setArgs(argc, argv);
779 779
780 /* install translation here */ 780 /* install translation here */
781 for ( QStringList::ConstIterator it = d->langs.begin(); it != d->langs.end(); ++it ) 781 for ( QStringList::ConstIterator it = d->langs.begin(); it != d->langs.end(); ++it )
782 installTranslation( (*it) + "/" + d->appName + ".qm" ); 782 installTranslation( (*it) + "/" + d->appName + ".qm" );
783} 783}
784#endif 784#endif
785 785
786 786
787static QPtrDict<void>* inputMethodDict = 0; 787static QPtrDict<void>* inputMethodDict = 0;
788static void createInputMethodDict() 788static void createInputMethodDict()
789{ 789{
790 if ( !inputMethodDict ) 790 if ( !inputMethodDict )
791 inputMethodDict = new QPtrDict<void>; 791 inputMethodDict = new QPtrDict<void>;
792} 792}
793 793
794/*! 794/*!
795 Returns the currently set hint to the system as to whether 795 Returns the currently set hint to the system as to whether
796 widget \a w has any use for text input methods. 796 widget \a w has any use for text input methods.
797 797
798 798
799 \sa setInputMethodHint() InputMethodHint 799 \sa setInputMethodHint() InputMethodHint
800*/ 800*/
801QPEApplication::InputMethodHint QPEApplication::inputMethodHint( QWidget * w ) 801QPEApplication::InputMethodHint QPEApplication::inputMethodHint( QWidget * w )
802{ 802{
803 if ( inputMethodDict && w ) 803 if ( inputMethodDict && w )
804 return ( InputMethodHint ) ( int ) inputMethodDict->find( w ); 804 return ( InputMethodHint ) ( int ) inputMethodDict->find( w );
805 return Normal; 805 return Normal;
806} 806}
807 807
808/*! 808/*!
809 \enum QPEApplication::InputMethodHint 809 \enum QPEApplication::InputMethodHint
810 810
811 \value Normal the application sometimes needs text input (the default). 811 \value Normal the application sometimes needs text input (the default).
812 \value AlwaysOff the application never needs text input. 812 \value AlwaysOff the application never needs text input.
813 \value AlwaysOn the application always needs text input. 813 \value AlwaysOn the application always needs text input.
814*/ 814*/
815 815
816/*! 816/*!
817 Hints to the system that widget \a w has use for text input methods 817 Hints to the system that widget \a w has use for text input methods
818 as specified by \a mode. 818 as specified by \a mode.
819 819
820 \sa inputMethodHint() InputMethodHint 820 \sa inputMethodHint() InputMethodHint
821*/ 821*/
822void QPEApplication::setInputMethodHint( QWidget * w, InputMethodHint mode ) 822void QPEApplication::setInputMethodHint( QWidget * w, InputMethodHint mode )
823{ 823{
824 createInputMethodDict(); 824 createInputMethodDict();
825 if ( mode == Normal ) { 825 if ( mode == Normal ) {
826 inputMethodDict->remove 826 inputMethodDict->remove
827 ( w ); 827 ( w );
828 } 828 }
829 else { 829 else {
830 inputMethodDict->insert( w, ( void* ) mode ); 830 inputMethodDict->insert( w, ( void* ) mode );
831 } 831 }
832} 832}
833 833
834class HackDialog : public QDialog 834class HackDialog : public QDialog
835{ 835{
836public: 836public:
837 void acceptIt() 837 void acceptIt()
838 { 838 {
839 accept(); 839 accept();
840 } 840 }
841 void rejectIt() 841 void rejectIt()
842 { 842 {
843 reject(); 843 reject();
844 } 844 }
845}; 845};
846 846
847 847
848void QPEApplication::mapToDefaultAction( QWSKeyEvent * ke, int key ) 848void QPEApplication::mapToDefaultAction( QWSKeyEvent * ke, int key )
849{ 849{
850 // specialised actions for certain widgets. May want to 850 // specialised actions for certain widgets. May want to
851 // add more stuff here. 851 // add more stuff here.
852 if ( activePopupWidget() && activePopupWidget() ->inherits( "QListBox" ) 852 if ( activePopupWidget() && activePopupWidget() ->inherits( "QListBox" )
853 && activePopupWidget() ->parentWidget() 853 && activePopupWidget() ->parentWidget()
854 && activePopupWidget() ->parentWidget() ->inherits( "QComboBox" ) ) 854 && activePopupWidget() ->parentWidget() ->inherits( "QComboBox" ) )
855 key = Qt::Key_Return; 855 key = Qt::Key_Return;
856 856
857 if ( activePopupWidget() && activePopupWidget() ->inherits( "QPopupMenu" ) ) 857 if ( activePopupWidget() && activePopupWidget() ->inherits( "QPopupMenu" ) )
858 key = Qt::Key_Return; 858 key = Qt::Key_Return;
859 859
860#ifdef QWS 860#ifdef QWS
861 861
862 ke->simpleData.keycode = key; 862 ke->simpleData.keycode = key;
863#endif 863#endif
864} 864}
865 865
866class HackWidget : public QWidget 866class HackWidget : public QWidget
867{ 867{
868public: 868public:
869 bool needsOk() 869 bool needsOk()
870 { 870 {
871 return ( getWState() & WState_Reserved1 ); 871 return ( getWState() & WState_Reserved1 );
872 } 872 }
873}; 873};
874 874
875/*! 875/*!
876 \internal 876 \internal
877*/ 877*/
878 878
879#ifdef QWS 879#ifdef QWS
880bool QPEApplication::qwsEventFilter( QWSEvent * e ) 880bool QPEApplication::qwsEventFilter( QWSEvent * e )
881{ 881{
882 if ( !d->notbusysent && e->type == QWSEvent::Focus ) { 882 if ( !d->notbusysent && e->type == QWSEvent::Focus ) {
883 if ( qApp->type() != QApplication::GuiServer ) { 883 if ( qApp->type() != QApplication::GuiServer ) {
884 QCopEnvelope e( "QPE/System", "notBusy(QString)" ); 884 QCopEnvelope e( "QPE/System", "notBusy(QString)" );
885 e << d->appName; 885 e << d->appName;
886 } 886 }
887 d->notbusysent = TRUE; 887 d->notbusysent = TRUE;
888 } 888 }
889 if ( type() == GuiServer ) { 889 if ( type() == GuiServer ) {
890 switch ( e->type ) { 890 switch ( e->type ) {
891 case QWSEvent::Mouse: 891 case QWSEvent::Mouse:
892 if ( e->asMouse() ->simpleData.state && !QWidget::find( e->window() ) ) 892 if ( e->asMouse() ->simpleData.state && !QWidget::find( e->window() ) )
893 emit clientMoused(); 893 emit clientMoused();
894 break; 894 break;
895 default: 895 default:
896 break; 896 break;
897 } 897 }
898 } 898 }
899 if ( e->type == QWSEvent::Key ) { 899 if ( e->type == QWSEvent::Key ) {
900 QWSKeyEvent *ke = ( QWSKeyEvent * ) e; 900 QWSKeyEvent *ke = ( QWSKeyEvent * ) e;
901 if ( ke->simpleData.keycode == Qt::Key_F33 ) { 901 if ( ke->simpleData.keycode == Qt::Key_F33 ) {
902 // Use special "OK" key to press "OK" on top level widgets 902 // Use special "OK" key to press "OK" on top level widgets
903 QWidget * active = activeWindow(); 903 QWidget * active = activeWindow();
904 QWidget *popup = 0; 904 QWidget *popup = 0;
905 if ( active && active->isPopup() ) { 905 if ( active && active->isPopup() ) {
906 popup = active; 906 popup = active;
907 active = active->parentWidget(); 907 active = active->parentWidget();
908 } 908 }
909 if ( active && ( int ) active->winId() == ke->simpleData.window && 909 if ( active && ( int ) active->winId() == ke->simpleData.window &&
910 !active->testWFlags( WStyle_Customize | WType_Popup | WType_Desktop ) ) { 910 !active->testWFlags( WStyle_Customize | WType_Popup | WType_Desktop ) ) {
911 if ( ke->simpleData.is_press ) { 911 if ( ke->simpleData.is_press ) {
912 if ( popup ) 912 if ( popup )
913 popup->close(); 913 popup->close();
914 if ( active->inherits( "QDialog" ) ) { 914 if ( active->inherits( "QDialog" ) ) {
915 HackDialog * d = ( HackDialog * ) active; 915 HackDialog * d = ( HackDialog * ) active;
916 d->acceptIt(); 916 d->acceptIt();
917 return TRUE; 917 return TRUE;
918 } 918 }
919 else if ( ( ( HackWidget * ) active ) ->needsOk() ) { 919 else if ( ( ( HackWidget * ) active ) ->needsOk() ) {
920 QSignal s; 920 QSignal s;
921 s.connect( active, SLOT( accept() ) ); 921 s.connect( active, SLOT( accept() ) );
922 s.activate(); 922 s.activate();
923 } 923 }
924 else { 924 else {
925 // do the same as with the select key: Map to the default action of the widget: 925 // do the same as with the select key: Map to the default action of the widget:
926 mapToDefaultAction( ke, Qt::Key_Return ); 926 mapToDefaultAction( ke, Qt::Key_Return );
927 } 927 }
928 } 928 }
929 } 929 }
930 } 930 }
931 else if ( ke->simpleData.keycode == Qt::Key_F30 ) { 931 else if ( ke->simpleData.keycode == Qt::Key_F30 ) {
932 // Use special "select" key to do whatever default action a widget has 932 // Use special "select" key to do whatever default action a widget has
933 mapToDefaultAction( ke, Qt::Key_Space ); 933 mapToDefaultAction( ke, Qt::Key_Space );
934 } 934 }
935 else if ( ke->simpleData.keycode == Qt::Key_Escape && 935 else if ( ke->simpleData.keycode == Qt::Key_Escape &&
936 ke->simpleData.is_press ) { 936 ke->simpleData.is_press ) {
937 // Escape key closes app if focus on toplevel 937 // Escape key closes app if focus on toplevel
938 QWidget * active = activeWindow(); 938 QWidget * active = activeWindow();
939 if ( active && active->testWFlags( WType_TopLevel ) && 939 if ( active && active->testWFlags( WType_TopLevel ) &&
940 ( int ) active->winId() == ke->simpleData.window && 940 ( int ) active->winId() == ke->simpleData.window &&
941 !active->testWFlags( WStyle_Dialog | WStyle_Customize | WType_Popup | WType_Desktop ) ) { 941 !active->testWFlags( WStyle_Dialog | WStyle_Customize | WType_Popup | WType_Desktop ) ) {
942 if ( active->inherits( "QDialog" ) ) { 942 if ( active->inherits( "QDialog" ) ) {
943 HackDialog * d = ( HackDialog * ) active; 943 HackDialog * d = ( HackDialog * ) active;
944 d->rejectIt(); 944 d->rejectIt();
945 return TRUE; 945 return TRUE;
946 } 946 }
947 else if ( strcmp( argv() [ 0 ], "embeddedkonsole" ) != 0 ) { 947 else if ( strcmp( argv() [ 0 ], "embeddedkonsole" ) != 0 ) {
948 active->close(); 948 active->close();
949 } 949 }
950 } 950 }
951 } 951 }
952 else if ( ke->simpleData.keycode >= Qt::Key_F1 && ke->simpleData.keycode <= Qt::Key_F29 ) { 952 else if ( ke->simpleData.keycode >= Qt::Key_F1 && ke->simpleData.keycode <= Qt::Key_F29 ) {
953 // this should be if ( ODevice::inst ( )-> buttonForKeycode ( ... )) 953 // this should be if ( ODevice::inst ( )-> buttonForKeycode ( ... ))
954 // but we cannot access libopie function within libqpe :( 954 // but we cannot access libopie function within libqpe :(
955 955
956 QWidget * active = activeWindow ( ); 956 QWidget * active = activeWindow ( );
957 if ( active && ((int) active-> winId ( ) == ke-> simpleData.window )) { 957 if ( active && ((int) active-> winId ( ) == ke-> simpleData.window )) {
958 if ( d-> kbgrabbed ) { // we grabbed the keyboard 958 if ( d-> kbgrabbed ) { // we grabbed the keyboard
959 QChar ch ( ke-> simpleData.unicode ); 959 QChar ch ( ke-> simpleData.unicode );
960 QKeyEvent qke ( ke-> simpleData. is_press ? QEvent::KeyPress : QEvent::KeyRelease, 960 QKeyEvent qke ( ke-> simpleData. is_press ? QEvent::KeyPress : QEvent::KeyRelease,
961 ke-> simpleData.keycode, 961 ke-> simpleData.keycode,
962 ch. latin1 ( ), 962 ch. latin1 ( ),
963 ke-> simpleData.modifiers, 963 ke-> simpleData.modifiers,
964 QString ( ch ), 964 QString ( ch ),
965 ke-> simpleData.is_auto_repeat, 1 ); 965 ke-> simpleData.is_auto_repeat, 1 );
966 966
967 QObject *which = QWidget::keyboardGrabber ( ); 967 QObject *which = QWidget::keyboardGrabber ( );
968 if ( !which ) 968 if ( !which )
969 which = QApplication::focusWidget ( ); 969 which = QApplication::focusWidget ( );
970 if ( !which ) 970 if ( !which )
971 which = QApplication::activeWindow ( ); 971 which = QApplication::activeWindow ( );
972 if ( !which ) 972 if ( !which )
973 which = qApp; 973 which = qApp;
974 974
975 QApplication::sendEvent ( which, &qke ); 975 QApplication::sendEvent ( which, &qke );
976 } 976 }
977 else { // we didn't grab the keyboard, so send the event to the launcher 977 else { // we didn't grab the keyboard, so send the event to the launcher
978 QCopEnvelope e ( "QPE/Launcher", "deviceButton(int,int,int)" ); 978 QCopEnvelope e ( "QPE/Launcher", "deviceButton(int,int,int)" );
979 e << int( ke-> simpleData.keycode ) << int( ke-> simpleData. is_press ) << int( ke-> simpleData.is_auto_repeat ); 979 e << int( ke-> simpleData.keycode ) << int( ke-> simpleData. is_press ) << int( ke-> simpleData.is_auto_repeat );
980 } 980 }
981 } 981 }
982 return true; 982 return true;
983 } 983 }
984 } 984 }
985 if ( e->type == QWSEvent::Focus ) { 985 if ( e->type == QWSEvent::Focus ) {
986 QWSFocusEvent * fe = ( QWSFocusEvent* ) e; 986 QWSFocusEvent * fe = ( QWSFocusEvent* ) e;
987 if ( !fe->simpleData.get_focus ) { 987 if ( !fe->simpleData.get_focus ) {
988 QWidget * active = activeWindow(); 988 QWidget * active = activeWindow();
989 while ( active && active->isPopup() ) { 989 while ( active && active->isPopup() ) {
990 active->close(); 990 active->close();
991 active = activeWindow(); 991 active = activeWindow();
992 } 992 }
993 } 993 }
994 else { 994 else {
995 // make sure our modal widget is ALWAYS on top 995 // make sure our modal widget is ALWAYS on top
996 QWidget *topm = activeModalWidget(); 996 QWidget *topm = activeModalWidget();
997 if ( topm ) { 997 if ( topm ) {
998 topm->raise(); 998 topm->raise();
999 } 999 }
1000 } 1000 }
1001 if ( fe->simpleData.get_focus && inputMethodDict ) { 1001 if ( fe->simpleData.get_focus && inputMethodDict ) {
1002 InputMethodHint m = inputMethodHint( QWidget::find( e->window() ) ); 1002 InputMethodHint m = inputMethodHint( QWidget::find( e->window() ) );
1003 if ( m == AlwaysOff ) 1003 if ( m == AlwaysOff )
1004 Global::hideInputMethod(); 1004 Global::hideInputMethod();
1005 if ( m == AlwaysOn ) 1005 if ( m == AlwaysOn )
1006 Global::showInputMethod(); 1006 Global::showInputMethod();
1007 } 1007 }
1008 } 1008 }
1009 1009
1010 1010
1011 return QApplication::qwsEventFilter( e ); 1011 return QApplication::qwsEventFilter( e );
1012} 1012}
1013#endif 1013#endif
1014 1014
1015/*! 1015/*!
1016 Destroys the QPEApplication. 1016 Destroys the QPEApplication.
1017*/ 1017*/
1018QPEApplication::~QPEApplication() 1018QPEApplication::~QPEApplication()
1019{ 1019{
1020 ungrabKeyboard(); 1020 ungrabKeyboard();
1021#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 1021#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
1022 // Need to delete QCopChannels early, since the display will 1022 // Need to delete QCopChannels early, since the display will
1023 // be gone by the time we get to ~QObject(). 1023 // be gone by the time we get to ~QObject().
1024 delete sysChannel; 1024 delete sysChannel;
1025 delete pidChannel; 1025 delete pidChannel;
1026#endif 1026#endif
1027 1027
1028 delete d; 1028 delete d;
1029} 1029}
1030 1030
1031/*! 1031/*!
1032 Returns <tt>$OPIEDIR/</tt>. 1032 Returns <tt>$OPIEDIR/</tt>.
1033*/ 1033*/
1034QString QPEApplication::qpeDir() 1034QString QPEApplication::qpeDir()
1035{ 1035{
1036 const char * base = getenv( "OPIEDIR" ); 1036 const char * base = getenv( "OPIEDIR" );
1037 if ( base ) 1037 if ( base )
1038 return QString( base ) + "/"; 1038 return QString( base ) + "/";
1039 1039
1040 return QString( "../" ); 1040 return QString( "../" );
1041} 1041}
1042 1042
1043/*! 1043/*!
1044 Returns the user's current Document directory. There is a trailing "/". 1044 Returns the user's current Document directory. There is a trailing "/".
1045 .. well, it does now,, and there's no trailing '/' 1045 .. well, it does now,, and there's no trailing '/'
1046*/ 1046*/
1047QString QPEApplication::documentDir() 1047QString QPEApplication::documentDir()
1048{ 1048{
1049 const char* base = getenv( "HOME"); 1049 const char* base = getenv( "HOME");
1050 if ( base ) 1050 if ( base )
1051 return QString( base ) + "/Documents"; 1051 return QString( base ) + "/Documents";
1052 1052
1053 return QString( "../Documents" ); 1053 return QString( "../Documents" );
1054} 1054}
1055 1055
1056static int deforient = -1; 1056static int deforient = -1;
1057 1057
1058/*! 1058/*!
1059 \internal 1059 \internal
1060*/ 1060*/
1061int QPEApplication::defaultRotation() 1061int QPEApplication::defaultRotation()
1062{ 1062{
1063 if ( deforient < 0 ) { 1063 if ( deforient < 0 ) {
1064 QString d = getenv( "QWS_DISPLAY" ); 1064 QString d = getenv( "QWS_DISPLAY" );
1065 if ( d.contains( "Rot90" ) ) { 1065 if ( d.contains( "Rot90" ) ) {
1066 deforient = 90; 1066 deforient = 90;
1067 } 1067 }
1068 else if ( d.contains( "Rot180" ) ) { 1068 else if ( d.contains( "Rot180" ) ) {
1069 deforient = 180; 1069 deforient = 180;
1070 } 1070 }
1071 else if ( d.contains( "Rot270" ) ) { 1071 else if ( d.contains( "Rot270" ) ) {
1072 deforient = 270; 1072 deforient = 270;
1073 } 1073 }
1074 else { 1074 else {
1075 deforient = 0; 1075 deforient = 0;
1076 } 1076 }
1077 } 1077 }
1078 return deforient; 1078 return deforient;
1079} 1079}
1080 1080
1081/*! 1081/*!
1082 \internal 1082 \internal
1083*/ 1083*/
1084void QPEApplication::setDefaultRotation( int r ) 1084void QPEApplication::setDefaultRotation( int r )
1085{ 1085{
1086 if ( qApp->type() == GuiServer ) { 1086 if ( qApp->type() == GuiServer ) {
1087 deforient = r; 1087 deforient = r;
1088 setenv( "QWS_DISPLAY", QString( "Transformed:Rot%1:0" ).arg( r ).latin1(), 1 ); 1088 setenv( "QWS_DISPLAY", QString( "Transformed:Rot%1:0" ).arg( r ).latin1(), 1 );
1089 Config config("qpe"); 1089 Config config("qpe");
1090 config.setGroup( "Rotation" ); 1090 config.setGroup( "Rotation" );
1091 config.writeEntry( "Rot", r ); 1091 config.writeEntry( "Rot", r );
1092 } 1092 }
1093 else { 1093 else {
1094#ifndef QT_NO_COP 1094#ifndef QT_NO_COP
1095 { QCopEnvelope e( "QPE/System", "setDefaultRotation(int)" ); 1095 { QCopEnvelope e( "QPE/System", "setDefaultRotation(int)" );
1096 e << r; 1096 e << r;
1097 } 1097 }
1098#endif 1098#endif
1099 1099
1100 } 1100 }
1101} 1101}
1102 1102
1103#include <qgfx_qws.h> 1103#include <qgfx_qws.h>
1104#include <qwindowsystem_qws.h> 1104#include <qwindowsystem_qws.h>
1105 1105
1106extern void qws_clearLoadedFonts(); 1106extern void qws_clearLoadedFonts();
1107 1107
1108void QPEApplication::setCurrentMode( int x, int y, int depth ) 1108void QPEApplication::setCurrentMode( int x, int y, int depth )
1109{ 1109{
1110 // Reset the caches 1110 // Reset the caches
1111 qws_clearLoadedFonts(); 1111 qws_clearLoadedFonts();
1112 QPixmapCache::clear(); 1112 QPixmapCache::clear();
1113 1113
1114 // Change the screen mode 1114 // Change the screen mode
1115 qt_screen->setMode(x, y, depth); 1115 qt_screen->setMode(x, y, depth);
1116 1116
1117 if ( qApp->type() == GuiServer ) { 1117 if ( qApp->type() == GuiServer ) {
1118 // Reconfigure the GuiServer 1118 // Reconfigure the GuiServer
1119 qwsServer->beginDisplayReconfigure(); 1119 qwsServer->beginDisplayReconfigure();
1120 qwsServer->endDisplayReconfigure(); 1120 qwsServer->endDisplayReconfigure();
1121 1121
1122 // Get all the running apps to reset 1122 // Get all the running apps to reset
1123 QCopEnvelope env( "QPE/System", "reset()" ); 1123 QCopEnvelope env( "QPE/System", "reset()" );
1124 } 1124 }
1125} 1125}
1126 1126
1127void QPEApplication::reset() { 1127void QPEApplication::reset() {
1128 // Reconnect to the screen 1128 // Reconnect to the screen
1129 qt_screen->disconnect(); 1129 qt_screen->disconnect();
1130 qt_screen->connect( QString::null ); 1130 qt_screen->connect( QString::null );
1131 1131
1132 // Redraw everything 1132 // Redraw everything
1133 applyStyle(); 1133 applyStyle();
1134} 1134}
1135 1135
1136/*! 1136/*!
1137 \internal 1137 \internal
1138*/ 1138*/
1139void QPEApplication::applyStyle() 1139void QPEApplication::applyStyle()
1140{ 1140{
1141 Config config( "qpe" ); 1141 Config config( "qpe" );
1142 config.setGroup( "Appearance" ); 1142 config.setGroup( "Appearance" );
1143 1143
1144#if QT_VERSION > 233 1144#if QT_VERSION > 233
1145#if !defined(OPIE_NO_OVERRIDE_QT) 1145#if !defined(OPIE_NO_OVERRIDE_QT)
1146 // don't block ourselves ... 1146 // don't block ourselves ...
1147 Opie::force_appearance = 0; 1147 Opie::force_appearance = 0;
1148 1148
1149 static QString appname = Opie::binaryName ( ); 1149 static QString appname = Opie::binaryName ( );
1150 1150
1151 QStringList ex = config. readListEntry ( "NoStyle", ';' ); 1151 QStringList ex = config. readListEntry ( "NoStyle", ';' );
1152 int nostyle = 0; 1152 int nostyle = 0;
1153 for ( QStringList::Iterator it = ex. begin ( ); it != ex. end ( ); ++it ) { 1153 for ( QStringList::Iterator it = ex. begin ( ); it != ex. end ( ); ++it ) {
1154 if ( QRegExp (( *it ). mid ( 1 ), false, true ). find ( appname, 0 ) >= 0 ) { 1154 if ( QRegExp (( *it ). mid ( 1 ), false, true ). find ( appname, 0 ) >= 0 ) {
1155 nostyle = ( *it ). left ( 1 ). toInt ( 0, 32 ); 1155 nostyle = ( *it ). left ( 1 ). toInt ( 0, 32 );
1156 break; 1156 break;
1157 } 1157 }
1158 } 1158 }
1159#else 1159#else
1160 int nostyle = 0; 1160 int nostyle = 0;
1161#endif 1161#endif
1162 1162
1163 // Widget style 1163 // Widget style
1164 QString style = config.readEntry( "Style", "FlatStyle" ); 1164 QString style = config.readEntry( "Style", "FlatStyle" );
1165 1165
1166 // don't set a custom style 1166 // don't set a custom style
1167 if ( nostyle & Opie::Force_Style ) 1167 if ( nostyle & Opie::Force_Style )
1168 style = "FlatStyle"; 1168 style = "FlatStyle";
1169 1169
1170 internalSetStyle ( style ); 1170 internalSetStyle ( style );
1171 1171
1172 // Colors - from /etc/colors/Liquid.scheme 1172 // Colors - from /etc/colors/Liquid.scheme
1173 QColor bgcolor( config.readEntry( "Background", "#E0E0E0" ) ); 1173 QColor bgcolor( config.readEntry( "Background", "#E0E0E0" ) );
1174 QColor btncolor( config.readEntry( "Button", "#96c8fa" ) ); 1174 QColor btncolor( config.readEntry( "Button", "#96c8fa" ) );
1175 QPalette pal( btncolor, bgcolor ); 1175 QPalette pal( btncolor, bgcolor );
1176 QString color = config.readEntry( "Highlight", "#73adef" ); 1176 QString color = config.readEntry( "Highlight", "#73adef" );
1177 pal.setColor( QColorGroup::Highlight, QColor( color ) ); 1177 pal.setColor( QColorGroup::Highlight, QColor( color ) );
1178 color = config.readEntry( "HighlightedText", "#FFFFFF" ); 1178 color = config.readEntry( "HighlightedText", "#FFFFFF" );
1179 pal.setColor( QColorGroup::HighlightedText, QColor( color ) ); 1179 pal.setColor( QColorGroup::HighlightedText, QColor( color ) );
1180 color = config.readEntry( "Text", "#000000" ); 1180 color = config.readEntry( "Text", "#000000" );
1181 pal.setColor( QColorGroup::Text, QColor( color ) ); 1181 pal.setColor( QColorGroup::Text, QColor( color ) );
1182 color = config.readEntry( "ButtonText", "#000000" ); 1182 color = config.readEntry( "ButtonText", "#000000" );
1183 pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) ); 1183 pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) );
1184 color = config.readEntry( "Base", "#FFFFFF" ); 1184 color = config.readEntry( "Base", "#FFFFFF" );
1185 pal.setColor( QColorGroup::Base, QColor( color ) ); 1185 pal.setColor( QColorGroup::Base, QColor( color ) );
1186 1186
1187 pal.setColor( QPalette::Disabled, QColorGroup::Text, 1187 pal.setColor( QPalette::Disabled, QColorGroup::Text,
1188 pal.color( QPalette::Active, QColorGroup::Background ).dark() ); 1188 pal.color( QPalette::Active, QColorGroup::Background ).dark() );
1189 1189
1190 setPalette( pal, TRUE ); 1190 setPalette( pal, TRUE );
1191 1191
1192 // Window Decoration 1192 // Window Decoration
1193 QString dec = config.readEntry( "Decoration", "Flat" ); 1193 QString dec = config.readEntry( "Decoration", "Flat" );
1194 1194
1195 // don't set a custom deco 1195 // don't set a custom deco
1196 if ( nostyle & Opie::Force_Decoration ) 1196 if ( nostyle & Opie::Force_Decoration )
1197 dec = ""; 1197 dec = "";
1198 1198
1199 //qDebug ( "Setting Deco: %s -- old %s (%d)", dec.latin1(), d-> decorationName.latin1(), nostyle); 1199 //qDebug ( "Setting Deco: %s -- old %s (%d)", dec.latin1(), d-> decorationName.latin1(), nostyle);
1200 1200
1201 if ( dec != d->decorationName ) { 1201 if ( dec != d->decorationName ) {
1202 qwsSetDecoration( new QPEDecoration( dec ) ); 1202 qwsSetDecoration( new QPEDecoration( dec ) );
1203 d->decorationName = dec; 1203 d->decorationName = dec;
1204 } 1204 }
1205 1205
1206 // Font 1206 // Font
1207 QString ff = config.readEntry( "FontFamily", font().family() ); 1207 QString ff = config.readEntry( "FontFamily", font().family() );
1208 int fs = config.readNumEntry( "FontSize", font().pointSize() ); 1208 int fs = config.readNumEntry( "FontSize", font().pointSize() );
1209 1209
1210 // don't set a custom font 1210 // don't set a custom font
1211 if ( nostyle & Opie::Force_Font ) { 1211 if ( nostyle & Opie::Force_Font ) {
1212 ff = "Vera"; 1212 ff = "Vera";
1213 fs = 10; 1213 fs = 10;
1214 } 1214 }
1215 1215
1216 setFont ( QFont ( ff, fs ), true ); 1216 setFont ( QFont ( ff, fs ), true );
1217 1217
1218#if !defined(OPIE_NO_OVERRIDE_QT) 1218#if !defined(OPIE_NO_OVERRIDE_QT)
1219 // revert to global blocking policy ... 1219 // revert to global blocking policy ...
1220 Opie::force_appearance = config. readBoolEntry ( "ForceStyle", false ) ? Opie::Force_All : Opie::Force_None; 1220 Opie::force_appearance = config. readBoolEntry ( "ForceStyle", false ) ? Opie::Force_All : Opie::Force_None;
1221 Opie::force_appearance &= ~nostyle; 1221 Opie::force_appearance &= ~nostyle;
1222#endif 1222#endif
1223#endif 1223#endif
1224} 1224}
1225 1225
1226void QPEApplication::systemMessage( const QCString& msg, const QByteArray& data ) 1226void QPEApplication::systemMessage( const QCString& msg, const QByteArray& data )
1227{ 1227{
1228#ifdef Q_WS_QWS 1228#ifdef Q_WS_QWS
1229 QDataStream stream( data, IO_ReadOnly ); 1229 QDataStream stream( data, IO_ReadOnly );
1230 if ( msg == "applyStyle()" ) { 1230 if ( msg == "applyStyle()" ) {
1231 applyStyle(); 1231 applyStyle();
1232 } 1232 }
1233 else if ( msg == "toggleApplicationMenu()" ) { 1233 else if ( msg == "toggleApplicationMenu()" ) {
1234 QWidget *active = activeWindow ( ); 1234 QWidget *active = activeWindow ( );
1235 1235
1236 if ( active ) { 1236 if ( active ) {
1237 QPEMenuToolFocusManager *man = QPEMenuToolFocusManager::manager ( ); 1237 QPEMenuToolFocusManager *man = QPEMenuToolFocusManager::manager ( );
1238 bool oldactive = man-> isActive ( ); 1238 bool oldactive = man-> isActive ( );
1239 1239
1240 man-> setActive( !man-> isActive() ); 1240 man-> setActive( !man-> isActive() );
1241 1241
1242 if ( !oldactive && !man-> isActive ( )) { // no menubar to toggle -> try O-Menu 1242 if ( !oldactive && !man-> isActive ( )) { // no menubar to toggle -> try O-Menu
1243 QCopEnvelope e ( "QPE/TaskBar", "toggleStartMenu()" ); 1243 QCopEnvelope e ( "QPE/TaskBar", "toggleStartMenu()" );
1244 } 1244 }
1245 } 1245 }
1246 } 1246 }
1247 else if ( msg == "setDefaultRotation(int)" ) { 1247 else if ( msg == "setDefaultRotation(int)" ) {
1248 if ( type() == GuiServer ) { 1248 if ( type() == GuiServer ) {
1249 int r; 1249 int r;
1250 stream >> r; 1250 stream >> r;
1251 setDefaultRotation( r ); 1251 setDefaultRotation( r );
1252 } 1252 }
1253 } 1253 }
1254 else if ( msg == "setCurrentMode(int,int,int)" ) { // Added: 2003-06-11 by Tim Ansell <mithro@mithis.net> 1254 else if ( msg == "setCurrentMode(int,int,int)" ) { // Added: 2003-06-11 by Tim Ansell <mithro@mithis.net>
1255 if ( type() == GuiServer ) { 1255 if ( type() == GuiServer ) {
1256 int x, y, depth; 1256 int x, y, depth;
1257 stream >> x; 1257 stream >> x;
1258 stream >> y; 1258 stream >> y;
1259 stream >> depth; 1259 stream >> depth;
1260 setCurrentMode( x, y, depth ); 1260 setCurrentMode( x, y, depth );
1261 } 1261 }
1262 } 1262 }
1263 else if ( msg == "reset()" ) { 1263 else if ( msg == "reset()" ) {
1264 if ( type() != GuiServer ) 1264 if ( type() != GuiServer )
1265 reset(); 1265 reset();
1266 } 1266 }
1267 else if ( msg == "setCurrentRotation(int)" ) { 1267 else if ( msg == "setCurrentRotation(int)" ) {
1268 int r; 1268 int r;
1269 stream >> r; 1269 stream >> r;
1270 setCurrentRotation( r ); 1270 setCurrentRotation( r );
1271 } 1271 }
1272 else if ( msg == "shutdown()" ) { 1272 else if ( msg == "shutdown()" ) {
1273 if ( type() == GuiServer ) 1273 if ( type() == GuiServer )
1274 shutdown(); 1274 shutdown();
1275 } 1275 }
1276 else if ( msg == "quit()" ) { 1276 else if ( msg == "quit()" ) {
1277 if ( type() != GuiServer ) 1277 if ( type() != GuiServer )
1278 tryQuit(); 1278 tryQuit();
1279 } 1279 }
1280 else if ( msg == "forceQuit()" ) { 1280 else if ( msg == "forceQuit()" ) {
1281 if ( type() != GuiServer ) 1281 if ( type() != GuiServer )
1282 quit(); 1282 quit();
1283 } 1283 }
1284 else if ( msg == "restart()" ) { 1284 else if ( msg == "restart()" ) {
1285 if ( type() == GuiServer ) 1285 if ( type() == GuiServer )
1286 restart(); 1286 restart();
1287 } 1287 }
1288 else if ( msg == "language(QString)" ) { 1288 else if ( msg == "language(QString)" ) {
1289 if ( type() == GuiServer ) { 1289 if ( type() == GuiServer ) {
1290 QString l; 1290 QString l;
1291 stream >> l; 1291 stream >> l;
1292 QString cl = getenv( "LANG" ); 1292 QString cl = getenv( "LANG" );
1293 if ( cl != l ) { 1293 if ( cl != l ) {
1294 if ( l.isNull() ) 1294 if ( l.isNull() )
1295 unsetenv( "LANG" ); 1295 unsetenv( "LANG" );
1296 else 1296 else
1297 setenv( "LANG", l.latin1(), 1 ); 1297 setenv( "LANG", l.latin1(), 1 );
1298 restart(); 1298 restart();
1299 } 1299 }
1300 } 1300 }
1301 } 1301 }
1302 else if ( msg == "timeChange(QString)" ) { 1302 else if ( msg == "timeChange(QString)" ) {
1303 QString t; 1303 QString t;
1304 stream >> t; 1304 stream >> t;
1305 if ( t.isNull() ) 1305 if ( t.isNull() )
1306 unsetenv( "TZ" ); 1306 unsetenv( "TZ" );
1307 else 1307 else
1308 setenv( "TZ", t.latin1(), 1 ); 1308 setenv( "TZ", t.latin1(), 1 );
1309 // emit the signal so everyone else knows... 1309 // emit the signal so everyone else knows...
1310 emit timeChanged(); 1310 emit timeChanged();
1311 } 1311 }
1312 else if ( msg == "addAlarm(QDateTime,QCString,QCString,int)" ) { 1312 else if ( msg == "addAlarm(QDateTime,QCString,QCString,int)" ) {
1313 if ( type() == GuiServer ) { 1313 if ( type() == GuiServer ) {
1314 QDateTime when; 1314 QDateTime when;
1315 QCString channel, message; 1315 QCString channel, message;
1316 int data; 1316 int data;
1317 stream >> when >> channel >> message >> data; 1317 stream >> when >> channel >> message >> data;
1318 AlarmServer::addAlarm( when, channel, message, data ); 1318 AlarmServer::addAlarm( when, channel, message, data );
1319 } 1319 }
1320 } 1320 }
1321 else if ( msg == "deleteAlarm(QDateTime,QCString,QCString,int)" ) { 1321 else if ( msg == "deleteAlarm(QDateTime,QCString,QCString,int)" ) {
1322 if ( type() == GuiServer ) { 1322 if ( type() == GuiServer ) {
1323 QDateTime when; 1323 QDateTime when;
1324 QCString channel, message; 1324 QCString channel, message;
1325 int data; 1325 int data;
1326 stream >> when >> channel >> message >> data; 1326 stream >> when >> channel >> message >> data;
1327 AlarmServer::deleteAlarm( when, channel, message, data ); 1327 AlarmServer::deleteAlarm( when, channel, message, data );
1328 } 1328 }
1329 } 1329 }
1330 else if ( msg == "clockChange(bool)" ) { 1330 else if ( msg == "clockChange(bool)" ) {
1331 int tmp; 1331 int tmp;
1332 stream >> tmp; 1332 stream >> tmp;
1333 emit clockChanged( tmp ); 1333 emit clockChanged( tmp );
1334 } 1334 }
1335 else if ( msg == "weekChange(bool)" ) { 1335 else if ( msg == "weekChange(bool)" ) {
1336 int tmp; 1336 int tmp;
1337 stream >> tmp; 1337 stream >> tmp;
1338 emit weekChanged( tmp ); 1338 emit weekChanged( tmp );
1339 } 1339 }
1340 else if ( msg == "setDateFormat(DateFormat)" ) { 1340 else if ( msg == "setDateFormat(DateFormat)" ) {
1341 DateFormat tmp; 1341 DateFormat tmp;
1342 stream >> tmp; 1342 stream >> tmp;
1343 emit dateFormatChanged( tmp ); 1343 emit dateFormatChanged( tmp );
1344 } 1344 }
1345 else if ( msg == "setVolume(int,int)" ) { 1345 else if ( msg == "setVolume(int,int)" ) {
1346 int t, v; 1346 int t, v;
1347 stream >> t >> v; 1347 stream >> t >> v;
1348 setVolume( t, v ); 1348 setVolume( t, v );
1349 emit volumeChanged( muted ); 1349 emit volumeChanged( muted );
1350 } 1350 }
1351 else if ( msg == "volumeChange(bool)" ) { 1351 else if ( msg == "volumeChange(bool)" ) {
1352 stream >> muted; 1352 stream >> muted;
1353 setVolume(); 1353 setVolume();
1354 emit volumeChanged( muted ); 1354 emit volumeChanged( muted );
1355 } 1355 }
1356 else if ( msg == "setMic(int,int)" ) { // Added: 2002-02-08 by Jeremy Cowgar <jc@cowgar.com> 1356 else if ( msg == "setMic(int,int)" ) { // Added: 2002-02-08 by Jeremy Cowgar <jc@cowgar.com>
1357 int t, v; 1357 int t, v;
1358 stream >> t >> v; 1358 stream >> t >> v;
1359 setMic( t, v ); 1359 setMic( t, v );
1360 emit micChanged( micMuted ); 1360 emit micChanged( micMuted );
1361 } 1361 }
1362 else if ( msg == "micChange(bool)" ) { // Added: 2002-02-08 by Jeremy Cowgar <jc@cowgar.com> 1362 else if ( msg == "micChange(bool)" ) { // Added: 2002-02-08 by Jeremy Cowgar <jc@cowgar.com>
1363 stream >> micMuted; 1363 stream >> micMuted;
1364 setMic(); 1364 setMic();
1365 emit micChanged( micMuted ); 1365 emit micChanged( micMuted );
1366 } 1366 }
1367 else if ( msg == "setBass(int,int)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> 1367 else if ( msg == "setBass(int,int)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org>
1368 int t, v; 1368 int t, v;
1369 stream >> t >> v; 1369 stream >> t >> v;
1370 setBass( t, v ); 1370 setBass( t, v );
1371 } 1371 }
1372 else if ( msg == "bassChange(bool)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> 1372 else if ( msg == "bassChange(bool)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org>
1373 setBass(); 1373 setBass();
1374 } 1374 }
1375 else if ( msg == "setTreble(int,int)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> 1375 else if ( msg == "setTreble(int,int)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org>
1376 int t, v; 1376 int t, v;
1377 stream >> t >> v; 1377 stream >> t >> v;
1378 setTreble( t, v ); 1378 setTreble( t, v );
1379 } 1379 }
1380 else if ( msg == "trebleChange(bool)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> 1380 else if ( msg == "trebleChange(bool)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org>
1381 setTreble(); 1381 setTreble();
1382 } else if ( msg == "getMarkedText()" ) { 1382 } else if ( msg == "getMarkedText()" ) {
1383 if ( type() == GuiServer ) { 1383 if ( type() == GuiServer ) {
1384 const ushort unicode = 'C'-'@'; 1384 const ushort unicode = 'C'-'@';
1385 const int scan = Key_C; 1385 const int scan = Key_C;
1386 qwsServer->processKeyEvent( unicode, scan, ControlButton, TRUE, FALSE ); 1386 qwsServer->processKeyEvent( unicode, scan, ControlButton, TRUE, FALSE );
1387 qwsServer->processKeyEvent( unicode, scan, ControlButton, FALSE, FALSE ); 1387 qwsServer->processKeyEvent( unicode, scan, ControlButton, FALSE, FALSE );
1388 } 1388 }
1389 } else if ( msg == "newChannel(QString)") { 1389 } else if ( msg == "newChannel(QString)") {
1390 QString myChannel = "QPE/Application/" + d->appName; 1390 QString myChannel = "QPE/Application/" + d->appName;
1391 QString channel; 1391 QString channel;
1392 stream >> channel; 1392 stream >> channel;
1393 if (channel == myChannel) { 1393 if (channel == myChannel) {
1394 processQCopFile(); 1394 processQCopFile();
1395 d->sendQCopQ(); 1395 d->sendQCopQ();
1396 } 1396 }
1397 } 1397 }
1398 1398
1399 1399
1400#endif 1400#endif
1401} 1401}
1402 1402
1403 1403
1404 1404
1405 1405
1406 1406
1407/*! 1407/*!
1408 \internal 1408 \internal
1409*/ 1409*/
1410bool QPEApplication::raiseAppropriateWindow() 1410bool QPEApplication::raiseAppropriateWindow()
1411{ 1411{
1412 bool r=FALSE; 1412 bool r=FALSE;
1413 1413
1414 // 1. Raise the main widget 1414 // 1. Raise the main widget
1415 QWidget *top = d->qpe_main_widget; 1415 QWidget *top = d->qpe_main_widget;
1416 if ( !top ) top = mainWidget(); 1416 if ( !top ) top = mainWidget();
1417 1417
1418 if ( top && d->keep_running ) { 1418 if ( top && d->keep_running ) {
1419 if ( top->isVisible() ) 1419 if ( top->isVisible() )
1420 r = TRUE; 1420 r = TRUE;
1421 else if (d->preloaded) { 1421 else if (d->preloaded) {
1422 // We are preloaded and not visible.. pretend we just started.. 1422 // We are preloaded and not visible.. pretend we just started..
1423#ifndef QT_NO_COP 1423#ifndef QT_NO_COP
1424 QCopEnvelope e("QPE/System", "fastAppShowing(QString)"); 1424 QCopEnvelope e("QPE/System", "fastAppShowing(QString)");
1425 e << d->appName; 1425 e << d->appName;
1426#endif 1426#endif
1427 } 1427 }
1428 1428
1429 d->show_mx(top,d->nomaximize, d->appName); 1429 d->show_mx(top,d->nomaximize, d->appName);
1430 top->raise(); 1430 top->raise();
1431 } 1431 }
1432 1432
1433 QWidget *topm = activeModalWidget(); 1433 QWidget *topm = activeModalWidget();
1434 1434
1435 // 2. Raise any parentless widgets (except top and topm, as they 1435 // 2. Raise any parentless widgets (except top and topm, as they
1436 // are raised before and after this loop). Order from most 1436 // are raised before and after this loop). Order from most
1437 // recently raised as deepest to least recently as top, so 1437 // recently raised as deepest to least recently as top, so
1438 // that repeated calls cycle through widgets. 1438 // that repeated calls cycle through widgets.
1439 QWidgetList *list = topLevelWidgets(); 1439 QWidgetList *list = topLevelWidgets();
1440 if ( list ) { 1440 if ( list ) {
1441 bool foundlast = FALSE; 1441 bool foundlast = FALSE;
1442 QWidget* topsub = 0; 1442 QWidget* topsub = 0;
1443 if ( d->lastraised ) { 1443 if ( d->lastraised ) {
1444 for (QWidget* w = list->first(); w; w = list->next()) { 1444 for (QWidget* w = list->first(); w; w = list->next()) {
1445 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) { 1445 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) {
1446 if ( w == d->lastraised ) 1446 if ( w == d->lastraised )
1447 foundlast = TRUE; 1447 foundlast = TRUE;
1448 if ( foundlast ) { 1448 if ( foundlast ) {
1449 w->raise(); 1449 w->raise();
1450 topsub = w; 1450 topsub = w;
1451 } 1451 }
1452 } 1452 }
1453 } 1453 }
1454 } 1454 }
1455 for (QWidget* w = list->first(); w; w = list->next()) { 1455 for (QWidget* w = list->first(); w; w = list->next()) {
1456 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) { 1456 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) {
1457 if ( w == d->lastraised ) 1457 if ( w == d->lastraised )
1458 break; 1458 break;
1459 w->raise(); 1459 w->raise();
1460 topsub = w; 1460 topsub = w;
1461 } 1461 }
1462 } 1462 }
1463 d->lastraised = topsub; 1463 d->lastraised = topsub;
1464 delete list; 1464 delete list;
1465 } 1465 }
1466 1466
1467 // 3. Raise the active modal widget. 1467 // 3. Raise the active modal widget.
1468 if ( topm && topm != top ) { 1468 if ( topm && topm != top ) {
1469 topm->show(); 1469 topm->show();
1470 topm->raise(); 1470 topm->raise();
1471 // If we haven't already handled the fastAppShowing message 1471 // If we haven't already handled the fastAppShowing message
1472 if (!top && d->preloaded) { 1472 if (!top && d->preloaded) {
1473#ifndef QT_NO_COP 1473#ifndef QT_NO_COP
1474 QCopEnvelope e("QPE/System", "fastAppShowing(QString)"); 1474 QCopEnvelope e("QPE/System", "fastAppShowing(QString)");
1475 e << d->appName; 1475 e << d->appName;
1476#endif 1476#endif
1477 } 1477 }
1478 r = FALSE; 1478 r = FALSE;
1479 } 1479 }
1480 1480
1481 return r; 1481 return r;
1482} 1482}
1483 1483
1484 1484
1485void QPEApplication::pidMessage( const QCString& msg, const QByteArray& data) 1485void QPEApplication::pidMessage( const QCString& msg, const QByteArray& data)
1486{ 1486{
1487#ifdef Q_WS_QWS 1487#ifdef Q_WS_QWS
1488 1488
1489 if ( msg == "quit()" ) { 1489 if ( msg == "quit()" ) {
1490 tryQuit(); 1490 tryQuit();
1491 } 1491 }
1492 else if ( msg == "quitIfInvisible()" ) { 1492 else if ( msg == "quitIfInvisible()" ) {
1493 if ( d->qpe_main_widget && !d->qpe_main_widget->isVisible() ) 1493 if ( d->qpe_main_widget && !d->qpe_main_widget->isVisible() )
1494 quit(); 1494 quit();
1495 } 1495 }
1496 else if ( msg == "close()" ) { 1496 else if ( msg == "close()" ) {
1497 hideOrQuit(); 1497 hideOrQuit();
1498 } 1498 }
1499 else if ( msg == "disablePreload()" ) { 1499 else if ( msg == "disablePreload()" ) {
1500 d->preloaded = FALSE; 1500 d->preloaded = FALSE;
1501 d->keep_running = TRUE; 1501 d->keep_running = TRUE;
1502 /* so that quit will quit */ 1502 /* so that quit will quit */
1503 } 1503 }
1504 else if ( msg == "enablePreload()" ) { 1504 else if ( msg == "enablePreload()" ) {
1505 if (d->qpe_main_widget) 1505 if (d->qpe_main_widget)
1506 d->preloaded = TRUE; 1506 d->preloaded = TRUE;
1507 d->keep_running = TRUE; 1507 d->keep_running = TRUE;
1508 /* so next quit won't quit */ 1508 /* so next quit won't quit */
1509 } 1509 }
1510 else if ( msg == "raise()" ) { 1510 else if ( msg == "raise()" ) {
1511 d->keep_running = TRUE; 1511 d->keep_running = TRUE;
1512 d->notbusysent = FALSE; 1512 d->notbusysent = FALSE;
1513 raiseAppropriateWindow(); 1513 raiseAppropriateWindow();
1514 // Tell the system we're still chugging along... 1514 // Tell the system we're still chugging along...
1515 QCopEnvelope e("QPE/System", "appRaised(QString)"); 1515 QCopEnvelope e("QPE/System", "appRaised(QString)");
1516 e << d->appName; 1516 e << d->appName;
1517 } 1517 }
1518 else if ( msg == "flush()" ) { 1518 else if ( msg == "flush()" ) {
1519 emit flush(); 1519 emit flush();
1520 // we need to tell the desktop 1520 // we need to tell the desktop
1521 QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" ); 1521 QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" );
1522 e << d->appName; 1522 e << d->appName;
1523 } 1523 }
1524 else if ( msg == "reload()" ) { 1524 else if ( msg == "reload()" ) {
1525 emit reload(); 1525 emit reload();
1526 } 1526 }
1527 else if ( msg == "setDocument(QString)" ) { 1527 else if ( msg == "setDocument(QString)" ) {
1528 d->keep_running = TRUE; 1528 d->keep_running = TRUE;
1529 QDataStream stream( data, IO_ReadOnly ); 1529 QDataStream stream( data, IO_ReadOnly );
1530 QString doc; 1530 QString doc;
1531 stream >> doc; 1531 stream >> doc;
1532 QWidget *mw = mainWidget(); 1532 QWidget *mw = mainWidget();
1533 if ( !mw ) 1533 if ( !mw )
1534 mw = d->qpe_main_widget; 1534 mw = d->qpe_main_widget;
1535 if ( mw ) 1535 if ( mw )
1536 Global::setDocument( mw, doc ); 1536 Global::setDocument( mw, doc );
1537 1537
1538 } else if ( msg == "QPEProcessQCop()" ) { 1538 } else if ( msg == "QPEProcessQCop()" ) {
1539 processQCopFile(); 1539 processQCopFile();
1540 d->sendQCopQ(); 1540 d->sendQCopQ();
1541 }else 1541 }else
1542 { 1542 {
1543 bool p = d->keep_running; 1543 bool p = d->keep_running;
1544 d->keep_running = FALSE; 1544 d->keep_running = FALSE;
1545 emit appMessage( msg, data); 1545 emit appMessage( msg, data);
1546 if ( d->keep_running ) { 1546 if ( d->keep_running ) {
1547 d->notbusysent = FALSE; 1547 d->notbusysent = FALSE;
1548 raiseAppropriateWindow(); 1548 raiseAppropriateWindow();
1549 if ( !p ) { 1549 if ( !p ) {
1550 // Tell the system we're still chugging along... 1550 // Tell the system we're still chugging along...
1551#ifndef QT_NO_COP 1551#ifndef QT_NO_COP
1552 QCopEnvelope e("QPE/System", "appRaised(QString)"); 1552 QCopEnvelope e("QPE/System", "appRaised(QString)");
1553 e << d->appName; 1553 e << d->appName;
1554#endif 1554#endif
1555 } 1555 }
1556 } 1556 }
1557 if ( p ) 1557 if ( p )
1558 d->keep_running = p; 1558 d->keep_running = p;
1559 } 1559 }
1560#endif 1560#endif
1561} 1561}
1562 1562
1563 1563
1564/*! 1564/*!
1565 Sets widget \a mw as the mainWidget() and shows it. For small windows, 1565 Sets widget \a mw as the mainWidget() and shows it. For small windows,
1566 consider passing TRUE for \a nomaximize rather than the default FALSE. 1566 consider passing TRUE for \a nomaximize rather than the default FALSE.
1567 1567
1568 \sa showMainDocumentWidget() 1568 \sa showMainDocumentWidget()
1569*/ 1569*/
1570void QPEApplication::showMainWidget( QWidget* mw, bool nomaximize ) 1570void QPEApplication::showMainWidget( QWidget* mw, bool nomaximize )
1571{ 1571{
1572 // setMainWidget(mw); this breaks FastLoading because lastWindowClose() would quit 1572 // setMainWidget(mw); this breaks FastLoading because lastWindowClose() would quit
1573 d->show(mw, nomaximize ); 1573 d->show(mw, nomaximize );
1574} 1574}
1575 1575
1576/*! 1576/*!
1577 Sets widget \a mw as the mainWidget() and shows it. For small windows, 1577 Sets widget \a mw as the mainWidget() and shows it. For small windows,
1578 consider passing TRUE for \a nomaximize rather than the default FALSE. 1578 consider passing TRUE for \a nomaximize rather than the default FALSE.
1579 1579
1580 This calls designates the application as 1580 This calls designates the application as
1581 a \link docwidget.html document-oriented\endlink application. 1581 a \link docwidget.html document-oriented\endlink application.
1582 1582
1583 The \a mw widget \e must have this slot: setDocument(const QString&). 1583 The \a mw widget \e must have this slot: setDocument(const QString&).
1584 1584
1585 \sa showMainWidget() 1585 \sa showMainWidget()
1586*/ 1586*/
1587void QPEApplication::showMainDocumentWidget( QWidget* mw, bool nomaximize ) 1587void QPEApplication::showMainDocumentWidget( QWidget* mw, bool nomaximize )
1588{ 1588{
1589 if ( mw && argc() == 2 ) 1589 if ( mw && argc() == 2 )
1590 Global::setDocument( mw, QString::fromUtf8(argv()[1]) ); 1590 Global::setDocument( mw, QString::fromUtf8(argv()[1]) );
1591 1591
1592 1592
1593 //setMainWidget(mw); see above 1593 //setMainWidget(mw); see above
1594 d->show(mw, nomaximize ); 1594 d->show(mw, nomaximize );
1595} 1595}
1596 1596
1597 1597
1598/*! 1598/*!
1599 If an application is started via a \link qcop.html QCop\endlink 1599 If an application is started via a \link qcop.html QCop\endlink
1600 message, the application will process the \link qcop.html 1600 message, the application will process the \link qcop.html
1601 QCop\endlink message and then quit. If the application calls this 1601 QCop\endlink message and then quit. If the application calls this
1602 function while processing a \link qcop.html QCop\endlink message, 1602 function while processing a \link qcop.html QCop\endlink message,
1603 after processing its outstanding \link qcop.html QCop\endlink 1603 after processing its outstanding \link qcop.html QCop\endlink
1604 messages the application will start 'properly' and show itself. 1604 messages the application will start 'properly' and show itself.
1605 1605
1606 \sa keepRunning() 1606 \sa keepRunning()
1607*/ 1607*/
1608void QPEApplication::setKeepRunning() 1608void QPEApplication::setKeepRunning()
1609{ 1609{
1610 if ( qApp && qApp->inherits( "QPEApplication" ) ) { 1610 if ( qApp && qApp->inherits( "QPEApplication" ) ) {
1611 QPEApplication * qpeApp = ( QPEApplication* ) qApp; 1611 QPEApplication * qpeApp = ( QPEApplication* ) qApp;
1612 qpeApp->d->keep_running = TRUE; 1612 qpeApp->d->keep_running = TRUE;
1613 } 1613 }
1614} 1614}
1615 1615
1616/*! 1616/*!
1617 Returns TRUE if the application will quit after processing the 1617 Returns TRUE if the application will quit after processing the
1618 current list of qcop messages; otherwise returns FALSE. 1618 current list of qcop messages; otherwise returns FALSE.
1619 1619
1620 \sa setKeepRunning() 1620 \sa setKeepRunning()
1621*/ 1621*/
1622bool QPEApplication::keepRunning() const 1622bool QPEApplication::keepRunning() const
1623{ 1623{
1624 return d->keep_running; 1624 return d->keep_running;
1625} 1625}
1626 1626
1627/*! 1627/*!
1628 \internal 1628 \internal
1629*/ 1629*/
1630void QPEApplication::internalSetStyle( const QString &style ) 1630void QPEApplication::internalSetStyle( const QString &style )
1631{ 1631{
1632#if QT_VERSION >= 300 1632#if QT_VERSION >= 300
1633 if ( style == "QPE" ) { 1633 if ( style == "QPE" ) {
1634 setStyle( new QPEStyle ); 1634 setStyle( new QPEStyle );
1635 } 1635 }
1636 else { 1636 else {
1637 QStyle *s = QStyleFactory::create( style ); 1637 QStyle *s = QStyleFactory::create( style );
1638 if ( s ) 1638 if ( s )
1639 setStyle( s ); 1639 setStyle( s );
1640 } 1640 }
1641#else 1641#else
1642 if ( style == "Windows" ) { 1642 if ( style == "Windows" ) {
1643 setStyle( new QWindowsStyle ); 1643 setStyle( new QWindowsStyle );
1644 } 1644 }
1645 else if ( style == "QPE" ) { 1645 else if ( style == "QPE" ) {
1646 setStyle( new QPEStyle ); 1646 setStyle( new QPEStyle );
1647 } 1647 }
1648 else if ( style == "Light" ) { 1648 else if ( style == "Light" ) {
1649 setStyle( new LightStyle ); 1649 setStyle( new LightStyle );
1650 } 1650 }
1651#ifndef QT_NO_STYLE_PLATINUM 1651#ifndef QT_NO_STYLE_PLATINUM
1652 else if ( style == "Platinum" ) { 1652 else if ( style == "Platinum" ) {
1653 setStyle( new QPlatinumStyle ); 1653 setStyle( new QPlatinumStyle );
1654 } 1654 }
1655#endif 1655#endif
1656#ifndef QT_NO_STYLE_MOTIF 1656#ifndef QT_NO_STYLE_MOTIF
1657 else if ( style == "Motif" ) { 1657 else if ( style == "Motif" ) {
1658 setStyle( new QMotifStyle ); 1658 setStyle( new QMotifStyle );
1659 } 1659 }
1660#endif 1660#endif
1661#ifndef QT_NO_STYLE_MOTIFPLUS 1661#ifndef QT_NO_STYLE_MOTIFPLUS
1662 else if ( style == "MotifPlus" ) { 1662 else if ( style == "MotifPlus" ) {
1663 setStyle( new QMotifPlusStyle ); 1663 setStyle( new QMotifPlusStyle );
1664 } 1664 }
1665#endif 1665#endif
1666 1666
1667 else { 1667 else {
1668 QStyle *sty = 0; 1668 QStyle *sty = 0;
1669 QString path = QPEApplication::qpeDir ( ) + "/plugins/styles/"; 1669 QString path = QPEApplication::qpeDir ( ) + "/plugins/styles/";
1670 1670
1671#ifdef Q_OS_MACX 1671#ifdef Q_OS_MACX
1672 if ( style. find ( ".dylib" ) > 0 ) 1672 if ( style. find ( ".dylib" ) > 0 )
1673 path += style; 1673 path += style;
1674 else 1674 else
1675 path = path + "lib" + style. lower ( ) + ".dylib"; // compatibility 1675 path = path + "lib" + style. lower ( ) + ".dylib"; // compatibility
1676#else 1676#else
1677 if ( style. find ( ".so" ) > 0 ) 1677 if ( style. find ( ".so" ) > 0 )
1678 path += style; 1678 path += style;
1679 else 1679 else
1680 path = path + "lib" + style. lower ( ) + ".so"; // compatibility 1680 path = path + "lib" + style. lower ( ) + ".so"; // compatibility
1681#endif 1681#endif
1682 static QLibrary *lastlib = 0; 1682 static QLibrary *lastlib = 0;
1683 static StyleInterface *lastiface = 0; 1683 static StyleInterface *lastiface = 0;
1684 1684
1685 QLibrary *lib = new QLibrary ( path ); 1685 QLibrary *lib = new QLibrary ( path );
1686 StyleInterface *iface = 0; 1686 StyleInterface *iface = 0;
1687 1687
1688 if (( lib-> queryInterface ( IID_Style, ( QUnknownInterface ** ) &iface ) == QS_OK ) && iface ) 1688 if (( lib-> queryInterface ( IID_Style, ( QUnknownInterface ** ) &iface ) == QS_OK ) && iface )
1689 sty = iface-> style ( ); 1689 sty = iface-> style ( );
1690 1690
1691 if ( sty ) { 1691 if ( sty ) {
1692 setStyle ( sty ); 1692 setStyle ( sty );
1693 1693
1694 if ( lastiface ) 1694 if ( lastiface )
1695 lastiface-> release ( ); 1695 lastiface-> release ( );
1696 lastiface = iface; 1696 lastiface = iface;
1697 1697
1698 if ( lastlib ) { 1698 if ( lastlib ) {
1699 lastlib-> unload ( ); 1699 lastlib-> unload ( );
1700 delete lastlib; 1700 delete lastlib;
1701 } 1701 }
1702 lastlib = lib; 1702 lastlib = lib;
1703 } 1703 }
1704 else { 1704 else {
1705 if ( iface ) 1705 if ( iface )
1706 iface-> release ( ); 1706 iface-> release ( );
1707 delete lib; 1707 delete lib;
1708 1708
1709 setStyle ( new LightStyle ( )); 1709 setStyle ( new LightStyle ( ));
1710 } 1710 }
1711 } 1711 }
1712#endif 1712#endif
1713} 1713}
1714 1714
1715/*! 1715/*!
1716 \internal 1716 \internal
1717*/ 1717*/
1718void QPEApplication::prepareForTermination( bool willrestart ) 1718void QPEApplication::prepareForTermination( bool willrestart )
1719{ 1719{
1720 if ( willrestart ) { 1720 if ( willrestart ) {
1721 // Draw a big wait icon, the image can be altered in later revisions 1721 // Draw a big wait icon, the image can be altered in later revisions
1722 // QWidget *d = QApplication::desktop(); 1722 // QWidget *d = QApplication::desktop();
1723 QImage img = Resource::loadImage( "launcher/new_wait" ); 1723 QImage img = Resource::loadImage( "launcher/new_wait" );
1724 QPixmap pix; 1724 QPixmap pix;
1725 pix.convertFromImage( img.smoothScale( 1 * img.width(), 1 * img.height() ) ); 1725 pix.convertFromImage( img.smoothScale( 1 * img.width(), 1 * img.height() ) );
1726 QLabel *lblWait = new QLabel( 0, "wait hack!", QWidget::WStyle_Customize | 1726 QLabel *lblWait = new QLabel( 0, "wait hack!", QWidget::WStyle_Customize |
1727 QWidget::WStyle_NoBorder | QWidget::WStyle_Tool ); 1727 QWidget::WStyle_NoBorder | QWidget::WStyle_Tool );
1728 lblWait->setPixmap( pix ); 1728 lblWait->setPixmap( pix );
1729 lblWait->setAlignment( QWidget::AlignCenter ); 1729 lblWait->setAlignment( QWidget::AlignCenter );
1730 lblWait->show(); 1730 lblWait->show();
1731 lblWait->showMaximized(); 1731 lblWait->showMaximized();
1732 } 1732 }
1733#ifndef SINGLE_APP 1733#ifndef SINGLE_APP
1734 { QCopEnvelope envelope( "QPE/System", "forceQuit()" ); 1734 { QCopEnvelope envelope( "QPE/System", "forceQuit()" );
1735 } 1735 }
1736 processEvents(); // ensure the message goes out. 1736 processEvents(); // ensure the message goes out.
1737 sleep( 1 ); // You have 1 second to comply. 1737 sleep( 1 ); // You have 1 second to comply.
1738#endif 1738#endif
1739} 1739}
1740 1740
1741/*! 1741/*!
1742 \internal 1742 \internal
1743*/ 1743*/
1744void QPEApplication::shutdown() 1744void QPEApplication::shutdown()
1745{ 1745{
1746 // Implement in server's QPEApplication subclass 1746 // Implement in server's QPEApplication subclass
1747} 1747}
1748 1748
1749/*! 1749/*!
1750 \internal 1750 \internal
1751*/ 1751*/
1752void QPEApplication::restart() 1752void QPEApplication::restart()
1753{ 1753{
1754 // Implement in server's QPEApplication subclass 1754 // Implement in server's QPEApplication subclass
1755} 1755}
1756 1756
1757static QPtrDict<void>* stylusDict = 0; 1757static QPtrDict<void>* stylusDict = 0;
1758static void createDict() 1758static void createDict()
1759{ 1759{
1760 if ( !stylusDict ) 1760 if ( !stylusDict )
1761 stylusDict = new QPtrDict<void>; 1761 stylusDict = new QPtrDict<void>;
1762} 1762}
1763 1763
1764/*! 1764/*!
1765 Returns the current StylusMode for widget \a w. 1765 Returns the current StylusMode for widget \a w.
1766 1766
1767 \sa setStylusOperation() StylusMode 1767 \sa setStylusOperation() StylusMode
1768*/ 1768*/
1769QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w ) 1769QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w )
1770{ 1770{
1771 if ( stylusDict ) 1771 if ( stylusDict )
1772 return ( StylusMode ) ( int ) stylusDict->find( w ); 1772 return ( StylusMode ) ( int ) stylusDict->find( w );
1773 return LeftOnly; 1773 return LeftOnly;
1774} 1774}
1775 1775
1776/*! 1776/*!
1777 \enum QPEApplication::StylusMode 1777 \enum QPEApplication::StylusMode
1778 1778
1779 \value LeftOnly the stylus only generates LeftButton 1779 \value LeftOnly the stylus only generates LeftButton
1780 events (the default). 1780 events (the default).
1781 \value RightOnHold the stylus generates RightButton events 1781 \value RightOnHold the stylus generates RightButton events
1782 if the user uses the press-and-hold gesture. 1782 if the user uses the press-and-hold gesture.
1783 1783
1784 \sa setStylusOperation() stylusOperation() 1784 \sa setStylusOperation() stylusOperation()
1785*/ 1785*/
1786 1786
1787/*! 1787/*!
1788 Causes widget \a w to receive mouse events according to the stylus 1788 Causes widget \a w to receive mouse events according to the stylus
1789 \a mode. 1789 \a mode.
1790 1790
1791 \sa stylusOperation() StylusMode 1791 \sa stylusOperation() StylusMode
1792*/ 1792*/
1793void QPEApplication::setStylusOperation( QWidget * w, StylusMode mode ) 1793void QPEApplication::setStylusOperation( QWidget * w, StylusMode mode )
1794{ 1794{
1795 createDict(); 1795 createDict();
1796 if ( mode == LeftOnly ) { 1796 if ( mode == LeftOnly ) {
1797 stylusDict->remove 1797 stylusDict->remove
1798 ( w ); 1798 ( w );
1799 w->removeEventFilter( qApp ); 1799 w->removeEventFilter( qApp );
1800 } 1800 }
1801 else { 1801 else {
1802 stylusDict->insert( w, ( void* ) mode ); 1802 stylusDict->insert( w, ( void* ) mode );
1803 connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) ); 1803 connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) );
1804 w->installEventFilter( qApp ); 1804 w->installEventFilter( qApp );
1805 } 1805 }
1806} 1806}
1807 1807
1808 1808
1809/*! 1809/*!
1810 \reimp 1810 \reimp
1811*/ 1811*/
1812bool QPEApplication::eventFilter( QObject *o, QEvent *e ) 1812bool QPEApplication::eventFilter( QObject *o, QEvent *e )
1813{ 1813{
1814 if ( !o->isWidgetType() ) 1814 if ( !o->isWidgetType() )
1815 return FALSE; 1815 return FALSE;
1816 1816
1817 if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) { 1817 if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) {
1818 QMouseEvent * me = ( QMouseEvent* ) e; 1818 QMouseEvent * me = ( QMouseEvent* ) e;
1819 StylusMode mode = (StylusMode)(int)stylusDict->find(o); 1819 StylusMode mode = (StylusMode)(int)stylusDict->find(o);
1820 switch (mode) { 1820 switch (mode) {
1821 case RightOnHold: 1821 case RightOnHold:
1822 switch ( me->type() ) { 1822 switch ( me->type() ) {
1823 case QEvent::MouseButtonPress: 1823 case QEvent::MouseButtonPress:
1824 if ( me->button() == LeftButton ) { 1824 if ( me->button() == LeftButton ) {
1825 if (!d->presstimer ) 1825 if (!d->presstimer )
1826 d->presstimer = startTimer(500); // #### pref. 1826 d->presstimer = startTimer(500); // #### pref.
1827 d->presswidget = (QWidget*)o; 1827 d->presswidget = (QWidget*)o;
1828 d->presspos = me->pos(); 1828 d->presspos = me->pos();
1829 d->rightpressed = FALSE; 1829 d->rightpressed = FALSE;
1830 } 1830 }
1831 break; 1831 break;
1832 case QEvent::MouseMove: 1832 case QEvent::MouseMove:
1833 if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) { 1833 if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) {
1834 killTimer(d->presstimer); 1834 killTimer(d->presstimer);
1835 d->presstimer = 0; 1835 d->presstimer = 0;
1836 } 1836 }
1837 break; 1837 break;
1838 case QEvent::MouseButtonRelease: 1838 case QEvent::MouseButtonRelease:
1839 if ( me->button() == LeftButton ) { 1839 if ( me->button() == LeftButton ) {
1840 if ( d->presstimer ) { 1840 if ( d->presstimer ) {
1841 killTimer(d->presstimer); 1841 killTimer(d->presstimer);
1842 d->presstimer = 0; 1842 d->presstimer = 0;
1843 } 1843 }
1844 if ( d->rightpressed && d->presswidget ) { 1844 if ( d->rightpressed && d->presswidget ) {
1845 // Right released 1845 // Right released
1846 postEvent( d->presswidget, 1846 postEvent( d->presswidget,
1847 new QMouseEvent( QEvent::MouseButtonRelease, me->pos(), 1847 new QMouseEvent( QEvent::MouseButtonRelease, me->pos(),
1848 RightButton, LeftButton + RightButton ) ); 1848 RightButton, LeftButton + RightButton ) );
1849 // Left released, off-widget 1849 // Left released, off-widget
1850 postEvent( d->presswidget, 1850 postEvent( d->presswidget,
1851 new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1), 1851 new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1),
1852 LeftButton, LeftButton ) ); 1852 LeftButton, LeftButton ) );
1853 postEvent( d->presswidget, 1853 postEvent( d->presswidget,
1854 new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1), 1854 new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1),
1855 LeftButton, LeftButton ) ); 1855 LeftButton, LeftButton ) );
1856 d->rightpressed = FALSE; 1856 d->rightpressed = FALSE;
1857 return TRUE; // don't send the real Left release 1857 return TRUE; // don't send the real Left release
1858 } 1858 }
1859 } 1859 }
1860 break; 1860 break;
1861 default: 1861 default:
1862 break; 1862 break;
1863 } 1863 }
1864 break; 1864 break;
1865 default: 1865 default:
1866 ; 1866 ;
1867 } 1867 }
1868 } 1868 }
1869 else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { 1869 else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
1870 QKeyEvent *ke = (QKeyEvent *)e; 1870 QKeyEvent *ke = (QKeyEvent *)e;
1871 if ( ke->key() == Key_Enter ) { 1871 if ( ke->key() == Key_Enter ) {
1872 if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) { 1872 if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) {
1873 postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ', 1873 postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ',
1874 ke->state(), " ", ke->isAutoRepeat(), ke->count() ) ); 1874 ke->state(), " ", ke->isAutoRepeat(), ke->count() ) );
1875 return TRUE; 1875 return TRUE;
1876 } 1876 }
1877 } 1877 }
1878 } 1878 }
1879 return FALSE; 1879 return FALSE;
1880} 1880}
1881 1881
1882/*! 1882/*!
1883 \reimp 1883 \reimp
1884*/ 1884*/
1885void QPEApplication::timerEvent( QTimerEvent *e ) 1885void QPEApplication::timerEvent( QTimerEvent *e )
1886{ 1886{
1887 if ( e->timerId() == d->presstimer && d->presswidget ) { 1887 if ( e->timerId() == d->presstimer && d->presswidget ) {
1888 // Right pressed 1888 // Right pressed
1889 postEvent( d->presswidget, 1889 postEvent( d->presswidget,
1890 new QMouseEvent( QEvent::MouseButtonPress, d->presspos, 1890 new QMouseEvent( QEvent::MouseButtonPress, d->presspos,
1891 RightButton, LeftButton ) ); 1891 RightButton, LeftButton ) );
1892 killTimer( d->presstimer ); 1892 killTimer( d->presstimer );
1893 d->presstimer = 0; 1893 d->presstimer = 0;
1894 d->rightpressed = TRUE; 1894 d->rightpressed = TRUE;
1895 } 1895 }
1896} 1896}
1897 1897
1898void QPEApplication::removeSenderFromStylusDict() 1898void QPEApplication::removeSenderFromStylusDict()
1899{ 1899{
1900 stylusDict->remove 1900 stylusDict->remove
1901 ( ( void* ) sender() ); 1901 ( ( void* ) sender() );
1902 if ( d->presswidget == sender() ) 1902 if ( d->presswidget == sender() )
1903 d->presswidget = 0; 1903 d->presswidget = 0;
1904} 1904}
1905 1905
1906/*! 1906/*!
1907 \internal 1907 \internal
1908*/ 1908*/
1909bool QPEApplication::keyboardGrabbed() const 1909bool QPEApplication::keyboardGrabbed() const
1910{ 1910{
1911 return d->kbgrabbed; 1911 return d->kbgrabbed;
1912} 1912}
1913 1913
1914 1914
1915/*! 1915/*!
1916 Reverses the effect of grabKeyboard(). This is called automatically 1916 Reverses the effect of grabKeyboard(). This is called automatically
1917 on program exit. 1917 on program exit.
1918*/ 1918*/
1919void QPEApplication::ungrabKeyboard() 1919void QPEApplication::ungrabKeyboard()
1920{ 1920{
1921 ((QPEApplication *) qApp )-> d-> kbgrabbed = false; 1921 ((QPEApplication *) qApp )-> d-> kbgrabbed = false;
1922} 1922}
1923 1923
1924/*! 1924/*!
1925 Grabs the physical keyboard keys, e.g. the application's launching 1925 Grabs the physical keyboard keys, e.g. the application's launching
1926 keys. Instead of launching applications when these keys are pressed 1926 keys. Instead of launching applications when these keys are pressed
1927 the signals emitted are sent to this application instead. Some games 1927 the signals emitted are sent to this application instead. Some games
1928 programs take over the launch keys in this way to make interaction 1928 programs take over the launch keys in this way to make interaction
1929 easier. 1929 easier.
1930 1930
1931 \sa ungrabKeyboard() 1931 \sa ungrabKeyboard()
1932*/ 1932*/
1933void QPEApplication::grabKeyboard() 1933void QPEApplication::grabKeyboard()
1934{ 1934{
1935 ((QPEApplication *) qApp )-> d-> kbgrabbed = true; 1935 ((QPEApplication *) qApp )-> d-> kbgrabbed = true;
1936} 1936}
1937 1937
1938/*! 1938/*!
1939 \reimp 1939 \reimp
1940*/ 1940*/
1941int QPEApplication::exec() 1941int QPEApplication::exec()
1942{ 1942{
1943 d->qcopQok = true; 1943 d->qcopQok = true;
1944#ifndef QT_NO_COP 1944#ifndef QT_NO_COP
1945 d->sendQCopQ(); 1945 d->sendQCopQ();
1946 if ( !d->keep_running ) 1946 if ( !d->keep_running )
1947 processEvents(); // we may have received QCop messages in the meantime. 1947 processEvents(); // we may have received QCop messages in the meantime.
1948#endif 1948#endif
1949 1949
1950 if ( d->keep_running ) 1950 if ( d->keep_running )
1951 //|| d->qpe_main_widget && d->qpe_main_widget->isVisible() ) 1951 //|| d->qpe_main_widget && d->qpe_main_widget->isVisible() )
1952 return QApplication::exec(); 1952 return QApplication::exec();
1953 1953
1954#ifndef QT_NO_COP 1954#ifndef QT_NO_COP
1955 1955
1956 { 1956 {
1957 QCopEnvelope e( "QPE/System", "closing(QString)" ); 1957 QCopEnvelope e( "QPE/System", "closing(QString)" );
1958 e << d->appName; 1958 e << d->appName;
1959 } 1959 }
1960#endif 1960#endif
1961 processEvents(); 1961 processEvents();
1962 return 0; 1962 return 0;
1963} 1963}
1964 1964
1965/*! 1965/*!
1966 \internal 1966 \internal
1967 External request for application to quit. Quits if possible without 1967 External request for application to quit. Quits if possible without
1968 loosing state. 1968 loosing state.
1969*/ 1969*/
1970void QPEApplication::tryQuit() 1970void QPEApplication::tryQuit()
1971{ 1971{
1972 if ( activeModalWidget() || strcmp( argv() [ 0 ], "embeddedkonsole" ) == 0 ) 1972 if ( activeModalWidget() || strcmp( argv() [ 0 ], "embeddedkonsole" ) == 0 )
1973 return ; // Inside modal loop or konsole. Too hard to save state. 1973 return ; // Inside modal loop or konsole. Too hard to save state.
1974#ifndef QT_NO_COP 1974#ifndef QT_NO_COP
1975 1975
1976 { 1976 {
1977 QCopEnvelope e( "QPE/System", "closing(QString)" ); 1977 QCopEnvelope e( "QPE/System", "closing(QString)" );
1978 e << d->appName; 1978 e << d->appName;
1979 } 1979 }
1980#endif 1980#endif
1981 processEvents(); 1981 processEvents();
1982 1982
1983 quit(); 1983 quit();
1984} 1984}
1985 1985
1986/*! 1986/*!
1987 \internal 1987 \internal
1988*/ 1988*/
1989void QPEApplication::installTranslation( const QString& baseName ) { 1989void QPEApplication::installTranslation( const QString& baseName ) {
1990 QTranslator* trans = new QTranslator(this); 1990 QTranslator* trans = new QTranslator(this);
1991 QString tfn = qpeDir() + "/i18n/"+baseName; 1991 QString tfn = qpeDir() + "/i18n/"+baseName;
1992 if ( trans->load( tfn ) ) 1992 if ( trans->load( tfn ) )
1993 installTranslator( trans ); 1993 installTranslator( trans );
1994 else 1994 else
1995 delete trans; 1995 delete trans;
1996} 1996}
1997 1997
1998/*! 1998/*!
1999 \internal 1999 \internal
2000 User initiated quit. Makes the window 'Go Away'. If preloaded this means 2000 User initiated quit. Makes the window 'Go Away'. If preloaded this means
2001 hiding the window. If not it means quitting the application. 2001 hiding the window. If not it means quitting the application.
2002 As this is user initiated we don't need to check state. 2002 As this is user initiated we don't need to check state.
2003*/ 2003*/
2004void QPEApplication::hideOrQuit() 2004void QPEApplication::hideOrQuit()
2005{ 2005{
2006 processEvents(); 2006 processEvents();
2007 2007
2008 // If we are a preloaded application we don't actually quit, so emit 2008 // If we are a preloaded application we don't actually quit, so emit
2009 // a System message indicating we're quasi-closing. 2009 // a System message indicating we're quasi-closing.
2010 if ( d->preloaded && d->qpe_main_widget ) 2010 if ( d->preloaded && d->qpe_main_widget )
2011#ifndef QT_NO_COP 2011#ifndef QT_NO_COP
2012 2012
2013 { 2013 {
2014 QCopEnvelope e("QPE/System", "fastAppHiding(QString)" ); 2014 QCopEnvelope e("QPE/System", "fastAppHiding(QString)" );
2015 e << d->appName; 2015 e << d->appName;
2016 d->qpe_main_widget->hide(); 2016 d->qpe_main_widget->hide();
2017 } 2017 }
2018#endif 2018#endif
2019 else 2019 else
2020 quit(); 2020 quit();
2021} 2021}
2022 2022
2023#if (__GNUC__ > 2 ) 2023#if (__GNUC__ > 2 )
2024extern "C" void __cxa_pure_virtual(); 2024extern "C" void __cxa_pure_virtual();
2025 2025
2026void __cxa_pure_virtual() 2026void __cxa_pure_virtual()
2027{ 2027{
2028 fprintf( stderr, "Pure virtual called\n"); 2028 fprintf( stderr, "Pure virtual called\n");
2029 abort(); 2029 abort();
2030 2030
2031} 2031}
2032 2032
2033#endif 2033#endif
2034 2034
2035 2035
2036#if defined(OPIE_NEW_MALLOC) 2036#if defined(OPIE_NEW_MALLOC)
2037 2037
2038// The libraries with the skiff package (and possibly others) have 2038// The libraries with the skiff package (and possibly others) have
2039// completely useless implementations of builtin new and delete that 2039// completely useless implementations of builtin new and delete that
2040// use about 50% of your CPU. Here we revert to the simple libc 2040// use about 50% of your CPU. Here we revert to the simple libc
2041// functions. 2041// functions.
2042 2042
2043void* operator new[]( size_t size ) 2043void* operator new[]( size_t size )
2044{ 2044{
2045 return malloc( size ); 2045 return malloc( size );
2046} 2046}
2047 2047
2048void* operator new( size_t size ) 2048void* operator new( size_t size )
2049{ 2049{
2050 return malloc( size ); 2050 return malloc( size );
2051} 2051}
2052 2052
2053void operator delete[]( void* p ) 2053void operator delete[]( void* p )
2054{ 2054{
2055 free( p ); 2055 free( p );
2056} 2056}
2057 2057
2058void operator delete[]( void* p, size_t /*size*/ ) 2058void operator delete[]( void* p, size_t /*size*/ )
2059{ 2059{
2060 free( p ); 2060 free( p );
2061} 2061}
2062 2062
2063 2063
2064void operator delete( void* p ) 2064void operator delete( void* p )
2065{ 2065{
2066 free( p ); 2066 free( p );
2067} 2067}
2068 2068
2069void operator delete( void* p, size_t /*size*/ ) 2069void operator delete( void* p, size_t /*size*/ )
2070{ 2070{
2071 free( p ); 2071 free( p );
2072} 2072}
2073 2073
2074#endif 2074#endif
2075 2075
2076#if ( QT_VERSION <= 230 ) && !defined(SINGLE_APP) 2076#if ( QT_VERSION <= 230 ) && !defined(SINGLE_APP)
2077#include <qwidgetlist.h> 2077#include <qwidgetlist.h>
2078#ifdef QWS 2078#ifdef QWS
2079#include <qgfx_qws.h> 2079#include <qgfx_qws.h>
2080extern QRect qt_maxWindowRect; 2080extern QRect qt_maxWindowRect;
2081void qt_setMaxWindowRect(const QRect& r ) 2081void qt_setMaxWindowRect(const QRect& r )
2082{ 2082{
2083 qt_maxWindowRect = qt_screen->mapFromDevice( r, 2083 qt_maxWindowRect = qt_screen->mapFromDevice( r,
2084 qt_screen->mapToDevice( QSize( qt_screen->width(), qt_screen->height() ) ) ); 2084 qt_screen->mapToDevice( QSize( qt_screen->width(), qt_screen->height() ) ) );
2085 // Re-resize any maximized windows 2085 // Re-resize any maximized windows
2086 QWidgetList* l = QApplication::topLevelWidgets(); 2086 QWidgetList* l = QApplication::topLevelWidgets();
2087 if ( l ) { 2087 if ( l ) {
2088 QWidget * w = l->first(); 2088 QWidget * w = l->first();
2089 while ( w ) { 2089 while ( w ) {
2090 if ( w->isVisible() && w->isMaximized() ) { 2090 if ( w->isVisible() && w->isMaximized() ) {
2091 w->showMaximized(); 2091 w->showMaximized();
2092 } 2092 }
2093 w = l->next(); 2093 w = l->next();
2094 } 2094 }
2095 delete l; 2095 delete l;
2096 } 2096 }
2097} 2097}
2098#endif 2098#endif
2099#endif 2099#endif
diff --git a/library/qpedialog.cpp b/library/qpedialog.cpp
index ac42972..da461b7 100644
--- a/library/qpedialog.cpp
+++ b/library/qpedialog.cpp
@@ -1,74 +1,74 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#define protected public 21#define protected public
22#include <qdialog.h> 22#include <qdialog.h>
23#undef protected 23#undef protected
24 24
25#include "qpedialog.h" 25#include "qpedialog.h"
26#include <qpe/qpeapplication.h> 26#include <qpe/qpeapplication.h>
27 27
28 28
29/** 29/**
30 * \brief This is the only c'tor. 30 * \brief This is the only c'tor.
31 * 31 *
32 * The parent of this Listener is the Dialog you pass. This means once 32 * The parent of this Listener is the Dialog you pass. This means once
33 * the dialog is deleted this listener will be deleted too. 33 * the dialog is deleted this listener will be deleted too.
34 * This Listener listens on QPEApplication::appMessage signal and implements 34 * This Listener listens on QPEApplication::appMessage signal and implements
35 * accept() and reject(). 35 * accept() and reject().
36 * 36 *
37 * \code 37 * \code
38 *QDialog *dialog = new YourDialog(); 38 *QDialog *dialog = new YourDialog();
39 (void)new QPEDialogListener(dialog); 39 (void)new QPEDialogListener(dialog);
40 if( QPEApplication::execDialog(dialog) == QDialog::Accept ){ 40 if( QPEApplication::execDialog(dialog) == QDialog::Accept ){
41 // do some stuff 41 // do some stuff
42 } 42 }
43 delete dialog; 43 delete dialog;
44 44
45 * \endcode 45 * \endcode
46 * 46 *
47 * @param di The dialog to handle 47 * @param di The dialog to handle
48 */ 48 */
49QPEDialogListener::QPEDialogListener(QDialog *di ) : QObject(di) 49QPEDialogListener::QPEDialogListener(QDialog *di ) : QObject(di)
50{ 50{
51 dialog = di; 51 dialog = di;
52 connect(qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), 52 connect(qApp, SIGNAL(appMessage(const QCString&,const QByteArray&)),
53 this, SLOT(appMessage(const QCString&, const QByteArray&)) ); 53 this, SLOT(appMessage(const QCString&,const QByteArray&)) );
54} 54}
55 55
56 56
57/** 57/**
58 * d'tor 58 * d'tor
59 */ 59 */
60QPEDialogListener::~QPEDialogListener() {} 60QPEDialogListener::~QPEDialogListener() {}
61 61
62/** 62/**
63 * \internal 63 * \internal
64 */ 64 */
65void QPEDialogListener::appMessage( const QCString &msg, const QByteArray & ) 65void QPEDialogListener::appMessage( const QCString &msg, const QByteArray & )
66{ 66{
67 if (!dialog) 67 if (!dialog)
68 return; 68 return;
69 if (msg == "accept()") { 69 if (msg == "accept()") {
70 dialog->accept(); 70 dialog->accept();
71 } else if (msg == "reject()") { 71 } else if (msg == "reject()") {
72 dialog->reject(); 72 dialog->reject();
73 } 73 }
74} 74}
diff --git a/library/storage.cpp b/library/storage.cpp
index 0ea465b..fcee689 100644
--- a/library/storage.cpp
+++ b/library/storage.cpp
@@ -1,401 +1,401 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) Holger 'zecke' Freyther <freyther@kde.org> 2** Copyright (C) Holger 'zecke' Freyther <freyther@kde.org>
3** Copyright (C) Lorn Potter <llornkcor@handhelds.org> 3** Copyright (C) Lorn Potter <llornkcor@handhelds.org>
4** Copyright (C) 2000 Trolltech AS. All rights reserved. 4** Copyright (C) 2000 Trolltech AS. All rights reserved.
5** 5**
6** This file is part of Opie Environment. 6** This file is part of Opie Environment.
7** 7**
8** This file may be distributed and/or modified under the terms of the 8** This file may be distributed and/or modified under the terms of the
9** GNU General Public License version 2 as published by the Free Software 9** GNU General Public License version 2 as published by the Free Software
10** Foundation and appearing in the file LICENSE.GPL included in the 10** Foundation and appearing in the file LICENSE.GPL included in the
11** packaging of this file. 11** packaging of this file.
12** 12**
13** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 13** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
14** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 14** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
15** 15**
16** See http://www.trolltech.com/gpl/ for GPL licensing information. 16** See http://www.trolltech.com/gpl/ for GPL licensing information.
17** 17**
18** Contact info@trolltech.com if any conditions of this licensing are 18** Contact info@trolltech.com if any conditions of this licensing are
19** not clear to you. 19** not clear to you.
20** 20**
21**********************************************************************/ 21**********************************************************************/
22 22
23#include <qpe/storage.h> 23#include <qpe/storage.h>
24 24
25#include <qcopchannel_qws.h> 25#include <qcopchannel_qws.h>
26 26
27#include <stdio.h> 27#include <stdio.h>
28 28
29#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 29#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
30#include <sys/vfs.h> 30#include <sys/vfs.h>
31#include <mntent.h> 31#include <mntent.h>
32#endif 32#endif
33 33
34#ifdef Q_OS_MACX 34#ifdef Q_OS_MACX
35# include <sys/param.h> 35# include <sys/param.h>
36# include <sys/ucred.h> 36# include <sys/ucred.h>
37# include <sys/mount.h> 37# include <sys/mount.h>
38# include <stdio.h> // For strerror() 38# include <stdio.h> // For strerror()
39# include <errno.h> 39# include <errno.h>
40#endif /* Q_OS_MACX */ 40#endif /* Q_OS_MACX */
41 41
42 42
43// Shouldn't be here ! (eilers) 43// Shouldn't be here ! (eilers)
44// #include <sys/vfs.h> 44// #include <sys/vfs.h>
45// #include <mntent.h> 45// #include <mntent.h>
46 46
47 47
48static bool isCF(const QString& m) 48static bool isCF(const QString& m)
49{ 49{
50 50
51#ifndef Q_OS_MACX 51#ifndef Q_OS_MACX
52 FILE* f = fopen("/var/run/stab", "r"); 52 FILE* f = fopen("/var/run/stab", "r");
53 if (!f) f = fopen("/var/state/pcmcia/stab", "r"); 53 if (!f) f = fopen("/var/state/pcmcia/stab", "r");
54 if (!f) f = fopen("/var/lib/pcmcia/stab", "r"); 54 if (!f) f = fopen("/var/lib/pcmcia/stab", "r");
55 if ( f ) 55 if ( f )
56 { 56 {
57 char line[1024]; 57 char line[1024];
58 char devtype[80]; 58 char devtype[80];
59 char devname[80]; 59 char devname[80];
60 while ( fgets( line, 1024, f ) ) 60 while ( fgets( line, 1024, f ) )
61 { 61 {
62 // 0 ide ide-cs 0 hda 3 0 62 // 0 ide ide-cs 0 hda 3 0
63 if ( sscanf(line,"%*d %s %*s %*s %s", devtype, devname )==2 ) 63 if ( sscanf(line,"%*d %s %*s %*s %s", devtype, devname )==2 )
64 { 64 {
65 if ( QString(devtype) == "ide" && m.find(devname)>0 ) 65 if ( QString(devtype) == "ide" && m.find(devname)>0 )
66 { 66 {
67 fclose(f); 67 fclose(f);
68 return TRUE; 68 return TRUE;
69 } 69 }
70 } 70 }
71 } 71 }
72 fclose(f); 72 fclose(f);
73 } 73 }
74#endif /* Q_OS_MACX */ 74#endif /* Q_OS_MACX */
75 return FALSE; 75 return FALSE;
76} 76}
77 77
78/*! \class StorageInfo storage.h 78/*! \class StorageInfo storage.h
79 \brief The StorageInfo class describes the disks mounted on the file system. 79 \brief The StorageInfo class describes the disks mounted on the file system.
80 80
81 This class provides access to the mount information for the Linux 81 This class provides access to the mount information for the Linux
82 filesystem. Each mount point is represented by the FileSystem class. 82 filesystem. Each mount point is represented by the FileSystem class.
83 To ensure this class has the most up to date size information, call 83 To ensure this class has the most up to date size information, call
84 the update() method. Note that this will automatically be signaled 84 the update() method. Note that this will automatically be signaled
85 by the operating system when a disk has been mounted or unmounted. 85 by the operating system when a disk has been mounted or unmounted.
86 86
87 \ingroup qtopiaemb 87 \ingroup qtopiaemb
88*/ 88*/
89 89
90/*! Constructor that determines the current mount points of the filesystem. 90/*! Constructor that determines the current mount points of the filesystem.
91 The standard \a parent parameters is passed on to QObject. 91 The standard \a parent parameters is passed on to QObject.
92 */ 92 */
93StorageInfo::StorageInfo( QObject *parent ) 93StorageInfo::StorageInfo( QObject *parent )
94 : QObject( parent ) 94 : QObject( parent )
95{ 95{
96 mFileSystems.setAutoDelete( TRUE ); 96 mFileSystems.setAutoDelete( TRUE );
97 channel = new QCopChannel( "QPE/Card", this ); 97 channel = new QCopChannel( "QPE/Card", this );
98 connect( channel, SIGNAL(received(const QCString &, const QByteArray &)), 98 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
99 this, SLOT(cardMessage( const QCString &, const QByteArray &)) ); 99 this, SLOT(cardMessage(const QCString&,const QByteArray&)) );
100 update(); 100 update();
101} 101}
102 102
103/*! Returns the longest matching FileSystem that starts with the 103/*! Returns the longest matching FileSystem that starts with the
104 same prefix as \a filename as its mount point. 104 same prefix as \a filename as its mount point.
105*/ 105*/
106const FileSystem *StorageInfo::fileSystemOf( const QString &filename ) 106const FileSystem *StorageInfo::fileSystemOf( const QString &filename )
107{ 107{
108 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i) 108 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i)
109 { 109 {
110 if ( filename.startsWith( (*i)->path() ) ) 110 if ( filename.startsWith( (*i)->path() ) )
111 return (*i); 111 return (*i);
112 } 112 }
113 return 0; 113 return 0;
114} 114}
115 115
116 116
117void StorageInfo::cardMessage( const QCString& msg, const QByteArray& ) 117void StorageInfo::cardMessage( const QCString& msg, const QByteArray& )
118{ 118{
119 if ( msg == "mtabChanged()" ) 119 if ( msg == "mtabChanged()" )
120 update(); 120 update();
121} 121}
122 122
123 123
124/*! Updates the mount and free space available information for each mount 124/*! Updates the mount and free space available information for each mount
125 point. This method is automatically called when a disk is mounted or 125 point. This method is automatically called when a disk is mounted or
126 unmounted. 126 unmounted.
127*/ 127*/
128// cause of the lack of a d pointer we need 128// cause of the lack of a d pointer we need
129// to store informations in a config file :( 129// to store informations in a config file :(
130void StorageInfo::update() 130void StorageInfo::update()
131{ 131{
132 //qDebug("StorageInfo::updating"); 132 //qDebug("StorageInfo::updating");
133#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 133#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
134 struct mntent *me; 134 struct mntent *me;
135 FILE *mntfp = setmntent( "/etc/mtab", "r" ); 135 FILE *mntfp = setmntent( "/etc/mtab", "r" );
136 136
137 QStringList curdisks; 137 QStringList curdisks;
138 QStringList curopts; 138 QStringList curopts;
139 QStringList curfs; 139 QStringList curfs;
140 bool rebuild = FALSE; 140 bool rebuild = FALSE;
141 int n=0; 141 int n=0;
142 if ( mntfp ) 142 if ( mntfp )
143 { 143 {
144 while ( (me = getmntent( mntfp )) != 0 ) 144 while ( (me = getmntent( mntfp )) != 0 )
145 { 145 {
146 QString fs = me->mnt_fsname; 146 QString fs = me->mnt_fsname;
147 if ( fs.left(7)=="/dev/hd" || fs.left(7)=="/dev/sd" 147 if ( fs.left(7)=="/dev/hd" || fs.left(7)=="/dev/sd"
148 || fs.left(8)=="/dev/mtd" || fs.left(9) == "/dev/mmcd" 148 || fs.left(8)=="/dev/mtd" || fs.left(9) == "/dev/mmcd"
149 || fs.left( 14 ) == "/dev/mmc/part1" 149 || fs.left( 14 ) == "/dev/mmc/part1"
150 || fs.left(5)=="tmpfs" || fs.left(9)=="/dev/root" ) 150 || fs.left(5)=="tmpfs" || fs.left(9)=="/dev/root" )
151 { 151 {
152 n++; 152 n++;
153 curdisks.append(fs); 153 curdisks.append(fs);
154 curopts.append( me->mnt_opts ); 154 curopts.append( me->mnt_opts );
155 //qDebug("-->fs %s opts %s", fs.latin1(), me->mnt_opts ); 155 //qDebug("-->fs %s opts %s", fs.latin1(), me->mnt_opts );
156 curfs.append( me->mnt_dir ); 156 curfs.append( me->mnt_dir );
157 bool found = FALSE; 157 bool found = FALSE;
158 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i) 158 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i)
159 { 159 {
160 if ( (*i)->disk() == fs ) 160 if ( (*i)->disk() == fs )
161 { 161 {
162 found = TRUE; 162 found = TRUE;
163 break; 163 break;
164 } 164 }
165 } 165 }
166 if ( !found ) 166 if ( !found )
167 rebuild = TRUE; 167 rebuild = TRUE;
168 } 168 }
169 } 169 }
170 endmntent( mntfp ); 170 endmntent( mntfp );
171 } 171 }
172 if ( rebuild || n != (int)mFileSystems.count() ) 172 if ( rebuild || n != (int)mFileSystems.count() )
173 { 173 {
174 mFileSystems.clear(); 174 mFileSystems.clear();
175 QStringList::ConstIterator it=curdisks.begin(); 175 QStringList::ConstIterator it=curdisks.begin();
176 QStringList::ConstIterator fsit=curfs.begin(); 176 QStringList::ConstIterator fsit=curfs.begin();
177 QStringList::ConstIterator optsIt=curopts.begin(); 177 QStringList::ConstIterator optsIt=curopts.begin();
178 for (; it!=curdisks.end(); ++it, ++fsit, ++optsIt) 178 for (; it!=curdisks.end(); ++it, ++fsit, ++optsIt)
179 { 179 {
180 QString opts = *optsIt; 180 QString opts = *optsIt;
181 181
182 QString disk = *it; 182 QString disk = *it;
183 QString humanname; 183 QString humanname;
184 bool removable = FALSE; 184 bool removable = FALSE;
185 if ( isCF(disk) ) 185 if ( isCF(disk) )
186 { 186 {
187 humanname = tr("CF Card"); 187 humanname = tr("CF Card");
188 removable = TRUE; 188 removable = TRUE;
189 } 189 }
190 else if ( disk == "/dev/hda1" ) 190 else if ( disk == "/dev/hda1" )
191 { 191 {
192 humanname = tr("Hard Disk"); 192 humanname = tr("Hard Disk");
193 } 193 }
194 else if ( disk.left(9) == "/dev/mmcd" ) 194 else if ( disk.left(9) == "/dev/mmcd" )
195 { 195 {
196 humanname = tr("SD Card"); 196 humanname = tr("SD Card");
197 removable = TRUE; 197 removable = TRUE;
198 } 198 }
199 else if ( disk.left( 14 ) == "/dev/mmc/part1" ) 199 else if ( disk.left( 14 ) == "/dev/mmc/part1" )
200 { 200 {
201 humanname = tr("MMC Card"); 201 humanname = tr("MMC Card");
202 removable = TRUE; 202 removable = TRUE;
203 } 203 }
204 else if ( disk.left(7) == "/dev/hd" ) 204 else if ( disk.left(7) == "/dev/hd" )
205 humanname = tr("Hard Disk") + " " + disk; 205 humanname = tr("Hard Disk") + " " + disk;
206 else if ( disk.left(7) == "/dev/sd" ) 206 else if ( disk.left(7) == "/dev/sd" )
207 humanname = tr("SCSI Hard Disk") + " " + disk; 207 humanname = tr("SCSI Hard Disk") + " " + disk;
208 else if ( disk.left(14) == "/dev/mtdblock6" ) //openzaurus ramfs 208 else if ( disk.left(14) == "/dev/mtdblock6" ) //openzaurus ramfs
209 humanname = tr("Internal Memory"); 209 humanname = tr("Internal Memory");
210 else if ( disk == "/dev/mtdblock1" || humanname == "/dev/mtdblock/1" ) 210 else if ( disk == "/dev/mtdblock1" || humanname == "/dev/mtdblock/1" )
211 humanname = tr("Internal Storage"); 211 humanname = tr("Internal Storage");
212 else if ( disk.left(14) == "/dev/mtdblock/" ) 212 else if ( disk.left(14) == "/dev/mtdblock/" )
213 humanname = tr("Internal Storage") + " " + disk; 213 humanname = tr("Internal Storage") + " " + disk;
214 else if ( disk.left(13) == "/dev/mtdblock" ) 214 else if ( disk.left(13) == "/dev/mtdblock" )
215 humanname = tr("Internal Storage") + " " + disk; 215 humanname = tr("Internal Storage") + " " + disk;
216 else if ( disk.left(9) == "/dev/root" ) 216 else if ( disk.left(9) == "/dev/root" )
217 humanname = tr("Internal Storage") + " " + disk; 217 humanname = tr("Internal Storage") + " " + disk;
218 else if ( disk.left(5) == "tmpfs" ) //ipaqs /mnt/ramfs 218 else if ( disk.left(5) == "tmpfs" ) //ipaqs /mnt/ramfs
219 humanname = tr("Internal Memory"); 219 humanname = tr("Internal Memory");
220 FileSystem *fs = new FileSystem( disk, *fsit, humanname, removable, opts ); 220 FileSystem *fs = new FileSystem( disk, *fsit, humanname, removable, opts );
221 mFileSystems.append( fs ); 221 mFileSystems.append( fs );
222 } 222 }
223 emit disksChanged(); 223 emit disksChanged();
224 } 224 }
225 else 225 else
226 { 226 {
227 // just update them 227 // just update them
228 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i) 228 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i)
229 i.current()->update(); 229 i.current()->update();
230 } 230 }
231#endif 231#endif
232} 232}
233 233
234bool deviceTab( const char *device) 234bool deviceTab( const char *device)
235{ 235{
236 QString name = device; 236 QString name = device;
237 bool hasDevice=false; 237 bool hasDevice=false;
238 238
239#ifdef Q_OS_MACX 239#ifdef Q_OS_MACX
240 // Darwin (MacOS X) 240 // Darwin (MacOS X)
241 struct statfs** mntbufp; 241 struct statfs** mntbufp;
242 int count = 0; 242 int count = 0;
243 if ( ( count = getmntinfo( mntbufp, MNT_WAIT ) ) == 0 ) 243 if ( ( count = getmntinfo( mntbufp, MNT_WAIT ) ) == 0 )
244 { 244 {
245 qWarning("deviceTab: Error in getmntinfo(): %s",strerror( errno ) ); 245 qWarning("deviceTab: Error in getmntinfo(): %s",strerror( errno ) );
246 hasDevice = false; 246 hasDevice = false;
247 } 247 }
248 for( int i = 0; i < count; i++ ) 248 for( int i = 0; i < count; i++ )
249 { 249 {
250 QString deviceName = mntbufp[i]->f_mntfromname; 250 QString deviceName = mntbufp[i]->f_mntfromname;
251 qDebug(deviceName); 251 qDebug(deviceName);
252 if( deviceName.left( name.length() ) == name ) 252 if( deviceName.left( name.length() ) == name )
253 hasDevice = true; 253 hasDevice = true;
254 } 254 }
255#else 255#else
256 // Linux 256 // Linux
257 struct mntent *me; 257 struct mntent *me;
258 FILE *mntfp = setmntent( "/etc/mtab", "r" ); 258 FILE *mntfp = setmntent( "/etc/mtab", "r" );
259 if ( mntfp ) 259 if ( mntfp )
260 { 260 {
261 while ( (me = getmntent( mntfp )) != 0 ) 261 while ( (me = getmntent( mntfp )) != 0 )
262 { 262 {
263 QString deviceName = me->mnt_fsname; 263 QString deviceName = me->mnt_fsname;
264 // qDebug(deviceName); 264 // qDebug(deviceName);
265 if( deviceName.left(name.length()) == name) 265 if( deviceName.left(name.length()) == name)
266 { 266 {
267 hasDevice = true; 267 hasDevice = true;
268 } 268 }
269 } 269 }
270 } 270 }
271 endmntent( mntfp ); 271 endmntent( mntfp );
272#endif /* Q_OS_MACX */ 272#endif /* Q_OS_MACX */
273 273
274 274
275 return hasDevice; 275 return hasDevice;
276} 276}
277 277
278/*! 278/*!
279 * @fn static bool StorageInfo::hasCf() 279 * @fn static bool StorageInfo::hasCf()
280 * @brief returns whether device has Cf mounted 280 * @brief returns whether device has Cf mounted
281 * 281 *
282 */ 282 */
283bool StorageInfo::hasCf() 283bool StorageInfo::hasCf()
284{ 284{
285 return deviceTab("/dev/hd"); 285 return deviceTab("/dev/hd");
286} 286}
287 287
288/*! 288/*!
289 * @fn static bool StorageInfo::hasSd() 289 * @fn static bool StorageInfo::hasSd()
290 * @brief returns whether device has SD mounted 290 * @brief returns whether device has SD mounted
291 * 291 *
292 */ 292 */
293bool StorageInfo::hasSd() 293bool StorageInfo::hasSd()
294{ 294{
295 return deviceTab("/dev/mmcd"); 295 return deviceTab("/dev/mmcd");
296} 296}
297 297
298/*! 298/*!
299 * @fn static bool StorageInfo::hasMmc() 299 * @fn static bool StorageInfo::hasMmc()
300 * @brief returns whether device has mmc mounted 300 * @brief returns whether device has mmc mounted
301 * 301 *
302 */ 302 */
303bool StorageInfo::hasMmc() 303bool StorageInfo::hasMmc()
304{ 304{
305 bool hasMmc=false; 305 bool hasMmc=false;
306 if( deviceTab("/dev/mmc/part")) 306 if( deviceTab("/dev/mmc/part"))
307 hasMmc=true; 307 hasMmc=true;
308 if( deviceTab("/dev/mmcd")) 308 if( deviceTab("/dev/mmcd"))
309 hasMmc=true; 309 hasMmc=true;
310 return hasMmc; 310 return hasMmc;
311} 311}
312 312
313/*! \fn const QList<FileSystem> &StorageInfo::fileSystems() const 313/*! \fn const QList<FileSystem> &StorageInfo::fileSystems() const
314 Returns a list of all available mounted file systems. 314 Returns a list of all available mounted file systems.
315 315
316 \warning This may change in Qtopia 3.x to return only relevant Qtopia file systems (and ignore mount points such as /tmp) 316 \warning This may change in Qtopia 3.x to return only relevant Qtopia file systems (and ignore mount points such as /tmp)
317*/ 317*/
318 318
319/*! \fn void StorageInfo::disksChanged() 319/*! \fn void StorageInfo::disksChanged()
320 Gets emitted when a disk has been mounted or unmounted, such as when 320 Gets emitted when a disk has been mounted or unmounted, such as when
321 a CF c 321 a CF c
322*/ 322*/
323//--------------------------------------------------------------------------- 323//---------------------------------------------------------------------------
324 324
325FileSystem::FileSystem( const QString &disk, const QString &path, const QString &name, bool rem, const QString &o ) 325FileSystem::FileSystem( const QString &disk, const QString &path, const QString &name, bool rem, const QString &o )
326 : fsdisk( disk ), fspath( path ), humanname( name ), blkSize(512), totalBlks(0), availBlks(0), removable( rem ), opts( o ) 326 : fsdisk( disk ), fspath( path ), humanname( name ), blkSize(512), totalBlks(0), availBlks(0), removable( rem ), opts( o )
327{ 327{
328 update(); 328 update();
329} 329}
330 330
331void FileSystem::update() 331void FileSystem::update()
332{ 332{
333#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 333#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
334 struct statfs fs; 334 struct statfs fs;
335 if ( !statfs( fspath.latin1(), &fs ) ) 335 if ( !statfs( fspath.latin1(), &fs ) )
336 { 336 {
337 blkSize = fs.f_bsize; 337 blkSize = fs.f_bsize;
338 totalBlks = fs.f_blocks; 338 totalBlks = fs.f_blocks;
339 availBlks = fs.f_bavail; 339 availBlks = fs.f_bavail;
340 } 340 }
341 else 341 else
342 { 342 {
343 blkSize = 0; 343 blkSize = 0;
344 totalBlks = 0; 344 totalBlks = 0;
345 availBlks = 0; 345 availBlks = 0;
346 } 346 }
347#endif 347#endif
348} 348}
349 349
350/*! \class FileSystem storage.h 350/*! \class FileSystem storage.h
351 \brief The FileSystem class describes a single mount point. 351 \brief The FileSystem class describes a single mount point.
352 352
353 This class simply returns information about a mount point, including 353 This class simply returns information about a mount point, including
354 file system name, mount point, human readable name, size information 354 file system name, mount point, human readable name, size information
355 and mount options information. 355 and mount options information.
356 \ingroup qtopiaemb 356 \ingroup qtopiaemb
357 357
358 \sa StorageInfo 358 \sa StorageInfo
359*/ 359*/
360 360
361/*! \fn const QString &FileSystem::disk() const 361/*! \fn const QString &FileSystem::disk() const
362 Returns the file system name, such as /dev/hda3 362 Returns the file system name, such as /dev/hda3
363*/ 363*/
364 364
365/*! \fn const QString &FileSystem::path() const 365/*! \fn const QString &FileSystem::path() const
366 Returns the mount path, such as /home 366 Returns the mount path, such as /home
367*/ 367*/
368 368
369/*! \fn const QString &FileSystem::name() const 369/*! \fn const QString &FileSystem::name() const
370 Returns the translated, human readable name for the mount directory. 370 Returns the translated, human readable name for the mount directory.
371*/ 371*/
372 372
373/*! \fn const QString &FileSystem::options() const 373/*! \fn const QString &FileSystem::options() const
374 Returns the mount options 374 Returns the mount options
375*/ 375*/
376 376
377/*! \fn long FileSystem::blockSize() const 377/*! \fn long FileSystem::blockSize() const
378 Returns the size of each block on the file system. 378 Returns the size of each block on the file system.
379*/ 379*/
380 380
381/*! \fn long FileSystem::totalBlocks() const 381/*! \fn long FileSystem::totalBlocks() const
382 Returns the total number of blocks on the file system 382 Returns the total number of blocks on the file system
383*/ 383*/
384 384
385/*! \fn long FileSystem::availBlocks() const 385/*! \fn long FileSystem::availBlocks() const
386 Returns the number of available blocks on the file system 386 Returns the number of available blocks on the file system
387 */ 387 */
388 388
389/*! \fn bool FileSystem::isRemovable() const 389/*! \fn bool FileSystem::isRemovable() const
390 Returns flag whether the file system can be removed, such as a CF card 390 Returns flag whether the file system can be removed, such as a CF card
391 would be removable, but the internal memory wouldn't 391 would be removable, but the internal memory wouldn't
392*/ 392*/
393 393
394/*! \fn bool FileSystem::isWritable() const 394/*! \fn bool FileSystem::isWritable() const
395 Returns flag whether the file system is mounted as writable or read-only. 395 Returns flag whether the file system is mounted as writable or read-only.
396 Returns FALSE if read-only, TRUE if read and write. 396 Returns FALSE if read-only, TRUE if read and write.
397*/ 397*/
398 398
399/*! \fn QStringList StorageInfo::fileSystemNames() const 399/*! \fn QStringList StorageInfo::fileSystemNames() const
400 Returns a list of filesystem names. 400 Returns a list of filesystem names.
401*/ 401*/
diff --git a/library/timestring.cpp b/library/timestring.cpp
index 2fd0191..91c29ae 100644
--- a/library/timestring.cpp
+++ b/library/timestring.cpp
@@ -1,365 +1,365 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "timestring.h" 21#include "timestring.h"
22#include <qobject.h> 22#include <qobject.h>
23#include <qpe/qpeapplication.h> //for qApp 23#include <qpe/qpeapplication.h> //for qApp
24#include "config.h" 24#include "config.h"
25 25
26 26
27class TimeStringFormatKeeper : public QObject 27class TimeStringFormatKeeper : public QObject
28{ 28{
29 Q_OBJECT 29 Q_OBJECT
30public: 30public:
31 static DateFormat currentFormat() 31 static DateFormat currentFormat()
32 { 32 {
33 if ( !self ) 33 if ( !self )
34 self = new TimeStringFormatKeeper; 34 self = new TimeStringFormatKeeper;
35 return self->format; 35 return self->format;
36 } 36 }
37private slots: 37private slots:
38 void formatChanged( DateFormat f ) 38 void formatChanged( DateFormat f )
39 { 39 {
40 format = f; 40 format = f;
41 } 41 }
42private: 42private:
43 static TimeStringFormatKeeper *self; 43 static TimeStringFormatKeeper *self;
44 DateFormat format; 44 DateFormat format;
45 45
46 TimeStringFormatKeeper() 46 TimeStringFormatKeeper()
47 : QObject( qApp ) 47 : QObject( qApp )
48 { 48 {
49 Config config("qpe"); 49 Config config("qpe");
50 config.setGroup( "Date" ); 50 config.setGroup( "Date" );
51 format = DateFormat(QChar(config.readEntry("Separator", "/")[0]), 51 format = DateFormat(QChar(config.readEntry("Separator", "/")[0]),
52 (DateFormat::Order)config .readNumEntry("ShortOrder", DateFormat::DayMonthYear), 52 (DateFormat::Order)config .readNumEntry("ShortOrder", DateFormat::DayMonthYear),
53 (DateFormat::Order)config.readNumEntry("LongOrder", DateFormat::DayMonthYear)); 53 (DateFormat::Order)config.readNumEntry("LongOrder", DateFormat::DayMonthYear));
54 54
55 connect( qApp, SIGNAL( dateFormatChanged(DateFormat) ), 55 connect( qApp, SIGNAL( dateFormatChanged(DateFormat) ),
56 this, SLOT( formatChanged( DateFormat ) ) ); 56 this, SLOT( formatChanged(DateFormat) ) );
57 } 57 }
58}; 58};
59 59
60TimeStringFormatKeeper *TimeStringFormatKeeper::self = 0; 60TimeStringFormatKeeper *TimeStringFormatKeeper::self = 0;
61 61
62QString DateFormat::toNumberString() const 62QString DateFormat::toNumberString() const
63{ 63{
64 QString buf = ""; 64 QString buf = "";
65 // for each part of the order 65 // for each part of the order
66 for (int i = 0; i < 3; i++) { 66 for (int i = 0; i < 3; i++) {
67 // switch on the relavent 3 bits. 67 // switch on the relavent 3 bits.
68 switch((_shortOrder >> (i * 3)) & 0x0007) { 68 switch((_shortOrder >> (i * 3)) & 0x0007) {
69 case 0x0001: 69 case 0x0001:
70 buf += QObject::tr( "D" , "Shortcut for Day"); 70 buf += QObject::tr( "D" , "Shortcut for Day");
71 break; 71 break;
72 case 0x0002: 72 case 0x0002:
73 buf += QObject::tr( "M", "Shortcur for Month" ); 73 buf += QObject::tr( "M", "Shortcur for Month" );
74 break; 74 break;
75 case 0x0004: 75 case 0x0004:
76 buf += QObject::tr( "Y" ); 76 buf += QObject::tr( "Y" );
77 break; 77 break;
78 } 78 }
79 if (i < 2) 79 if (i < 2)
80 buf += _shortSeparator; 80 buf += _shortSeparator;
81 } 81 }
82 return buf; 82 return buf;
83} 83}
84 84
85QString DateFormat::toWordString() const 85QString DateFormat::toWordString() const
86{ 86{
87 QString buf = ""; 87 QString buf = "";
88 // for each part of the order 88 // for each part of the order
89 for (int i = 0; i < 3; i++) { 89 for (int i = 0; i < 3; i++) {
90 // switch on the relavent 3 bits. 90 // switch on the relavent 3 bits.
91 switch((_longOrder >> (i * 3)) & 0x0007) { 91 switch((_longOrder >> (i * 3)) & 0x0007) {
92 case 0x0001: 92 case 0x0001:
93 buf += QObject::tr( "day" ); 93 buf += QObject::tr( "day" );
94 if (i < 2) { 94 if (i < 2) {
95 if ((_shortOrder << ((i+1) * 3)) & 0x0007) 95 if ((_shortOrder << ((i+1) * 3)) & 0x0007)
96 buf += ", "; 96 buf += ", ";
97 else 97 else
98 buf += " "; 98 buf += " ";
99 } 99 }
100 break; 100 break;
101 case 0x0002: 101 case 0x0002:
102 buf += QObject::tr( "month" ); 102 buf += QObject::tr( "month" );
103 if (i < 2) 103 if (i < 2)
104 buf += " "; 104 buf += " ";
105 break; 105 break;
106 case 0x0004: 106 case 0x0004:
107 buf += QObject::tr( "year" ); 107 buf += QObject::tr( "year" );
108 if (i < 2) 108 if (i < 2)
109 buf += ", "; 109 buf += ", ";
110 break; 110 break;
111 } 111 }
112 } 112 }
113 return buf; 113 return buf;
114} 114}
115 115
116QString DateFormat::numberDate(const QDate &d, int v) const 116QString DateFormat::numberDate(const QDate &d, int v) const
117{ 117{
118 QString buf = ""; 118 QString buf = "";
119 119
120 int pad = 2; 120 int pad = 2;
121 121
122 // for each part of the order 122 // for each part of the order
123 for (int i = 0; i < 3; i++) { 123 for (int i = 0; i < 3; i++) {
124 // switch on the relavent 3 bits. 124 // switch on the relavent 3 bits.
125 switch((_shortOrder >> (i * 3)) & 0x0007) { 125 switch((_shortOrder >> (i * 3)) & 0x0007) {
126 case 0x0001: 126 case 0x0001:
127 if (pad==2) buf += QString().sprintf("%02d",d.day()); 127 if (pad==2) buf += QString().sprintf("%02d",d.day());
128 else buf += QString().sprintf("%d",d.day()); 128 else buf += QString().sprintf("%d",d.day());
129 break; 129 break;
130 case 0x0002: 130 case 0x0002:
131 if (i==0) { // no padding with only MM/DD/YY format 131 if (i==0) { // no padding with only MM/DD/YY format
132 pad=0; 132 pad=0;
133 } 133 }
134 if (pad==2) buf += QString().sprintf("%02d",d.month()); 134 if (pad==2) buf += QString().sprintf("%02d",d.month());
135 else buf += QString().sprintf("%d",d.month()); 135 else buf += QString().sprintf("%d",d.month());
136 break; 136 break;
137 case 0x0004: 137 case 0x0004:
138 { 138 {
139 int year = d.year(); 139 int year = d.year();
140 if (!(v & longNumber)) 140 if (!(v & longNumber))
141 year = year % 100; 141 year = year % 100;
142 buf += QString().sprintf("%02d",year); 142 buf += QString().sprintf("%02d",year);
143 } 143 }
144 break; 144 break;
145 } 145 }
146 if (i < 2) 146 if (i < 2)
147 buf += _shortSeparator; 147 buf += _shortSeparator;
148 } 148 }
149 return buf; 149 return buf;
150} 150}
151 151
152QString DateFormat::wordDate(const QDate &d, int v) const 152QString DateFormat::wordDate(const QDate &d, int v) const
153{ 153{
154 QString buf = ""; 154 QString buf = "";
155 // for each part of the order 155 // for each part of the order
156 if (v & showWeekDay) { 156 if (v & showWeekDay) {
157 QString weekDay = d.dayName(d.dayOfWeek()); 157 QString weekDay = d.dayName(d.dayOfWeek());
158 if (!(v & longWord)) { 158 if (!(v & longWord)) {
159 weekDay = weekDay.left(3); 159 weekDay = weekDay.left(3);
160 } 160 }
161 buf += weekDay; 161 buf += weekDay;
162 if ((_longOrder & 0x0007) == 0x0002) 162 if ((_longOrder & 0x0007) == 0x0002)
163 buf += ' '; 163 buf += ' ';
164 else 164 else
165 buf += ", "; 165 buf += ", ";
166 } 166 }
167 167
168 for (int i = 0; i < 3; i++) { 168 for (int i = 0; i < 3; i++) {
169 // switch on the relavent 3 bits. 169 // switch on the relavent 3 bits.
170 switch((_longOrder >> (i * 3)) & 0x0007) { 170 switch((_longOrder >> (i * 3)) & 0x0007) {
171 case 0x0001: 171 case 0x0001:
172 if (i==1) { 172 if (i==1) {
173 buf += QString().sprintf("%02d, ",d.day()); 173 buf += QString().sprintf("%02d, ",d.day());
174 } else { 174 } else {
175 buf += QString().sprintf("%2d",d.day()); 175 buf += QString().sprintf("%2d",d.day());
176 if (separator()=='.') // 2002/1/11 176 if (separator()=='.') // 2002/1/11
177 buf += ". "; 177 buf += ". ";
178 else 178 else
179 buf += " "; 179 buf += " ";
180 } 180 }
181 break; 181 break;
182 case 0x0002: 182 case 0x0002:
183 { 183 {
184 QString monthName = d.monthName(d.month()); 184 QString monthName = d.monthName(d.month());
185 if (!(v & longWord)) { 185 if (!(v & longWord)) {
186 monthName = monthName.left(3); 186 monthName = monthName.left(3);
187 } 187 }
188 buf += monthName; 188 buf += monthName;
189 } 189 }
190 if (i < 2) 190 if (i < 2)
191 buf += " "; 191 buf += " ";
192 break; 192 break;
193 case 0x0004: 193 case 0x0004:
194 { 194 {
195 int year = d.year(); 195 int year = d.year();
196 if (!(v & longNumber)) 196 if (!(v & longNumber))
197 year = year % 100; 197 year = year % 100;
198 198
199 if (year < 10) 199 if (year < 10)
200 buf += "0"; 200 buf += "0";
201 201
202 buf += QString::number(year); 202 buf += QString::number(year);
203 } 203 }
204 if (i < 2) 204 if (i < 2)
205 buf += ", "; 205 buf += ", ";
206 break; 206 break;
207 } 207 }
208 } 208 }
209 return buf; 209 return buf;
210} 210}
211 211
212#ifndef QT_NO_DATASTREAM 212#ifndef QT_NO_DATASTREAM
213void DateFormat::save(QDataStream &d) const 213void DateFormat::save(QDataStream &d) const
214{ 214{
215 d << _shortSeparator.unicode(); 215 d << _shortSeparator.unicode();
216 uint v= _shortOrder; 216 uint v= _shortOrder;
217 d << v; 217 d << v;
218 v = _longOrder; 218 v = _longOrder;
219 d << v; 219 d << v;
220} 220}
221 221
222void DateFormat::load(QDataStream &d) 222void DateFormat::load(QDataStream &d)
223{ 223{
224 ushort value; 224 ushort value;
225 d >> value; 225 d >> value;
226 _shortSeparator = QChar(value); 226 _shortSeparator = QChar(value);
227 uint v = 0; 227 uint v = 0;
228 d >> v; 228 d >> v;
229 _shortOrder = (Order)v; 229 _shortOrder = (Order)v;
230 v = 0; 230 v = 0;
231 d >> v; 231 d >> v;
232 _longOrder = (Order)v; 232 _longOrder = (Order)v;
233} 233}
234 234
235QDataStream &operator<<(QDataStream &s, const DateFormat&df) 235QDataStream &operator<<(QDataStream &s, const DateFormat&df)
236{ 236{
237 df.save(s); 237 df.save(s);
238 return s; 238 return s;
239} 239}
240QDataStream &operator>>(QDataStream &s, DateFormat&df) 240QDataStream &operator>>(QDataStream &s, DateFormat&df)
241{ 241{
242 df.load(s); 242 df.load(s);
243 return s; 243 return s;
244} 244}
245#endif 245#endif
246 246
247QString TimeString::shortDate( const QDate &d, DateFormat dtf ) 247QString TimeString::shortDate( const QDate &d, DateFormat dtf )
248{ 248{
249 return dtf.wordDate(d); 249 return dtf.wordDate(d);
250} 250}
251 251
252QString TimeString::dateString( const QDate &d, DateFormat dtf ) 252QString TimeString::dateString( const QDate &d, DateFormat dtf )
253{ 253{
254 return QObject::tr( dtf.wordDate(d, DateFormat::longNumber | DateFormat::longWord) ); 254 return QObject::tr( dtf.wordDate(d, DateFormat::longNumber | DateFormat::longWord) );
255} 255}
256 256
257 257
258QString TimeString::longDateString( const QDate &d, DateFormat dtf ) 258QString TimeString::longDateString( const QDate &d, DateFormat dtf )
259{ 259{
260 return QObject::tr( dtf.wordDate(d, DateFormat::showWeekDay | DateFormat::longNumber 260 return QObject::tr( dtf.wordDate(d, DateFormat::showWeekDay | DateFormat::longNumber
261 | DateFormat::longWord) ); 261 | DateFormat::longWord) );
262} 262}
263 263
264DateFormat TimeString::currentDateFormat() 264DateFormat TimeString::currentDateFormat()
265{ 265{
266 return TimeStringFormatKeeper::currentFormat(); 266 return TimeStringFormatKeeper::currentFormat();
267} 267}
268 268
269 269
270QString TimeString::dateString( const QDateTime &dt, bool ampm, bool seconds, DateFormat dtf ) 270QString TimeString::dateString( const QDateTime &dt, bool ampm, bool seconds, DateFormat dtf )
271{ 271{
272 const QDate& d = dt.date(); 272 const QDate& d = dt.date();
273 const QTime& t = dt.time(); 273 const QTime& t = dt.time();
274 274
275 // based on QDateTime::toString() 275 // based on QDateTime::toString()
276 QString buf = timeString(t,ampm,seconds); 276 QString buf = timeString(t,ampm,seconds);
277 buf += " "; 277 buf += " ";
278 buf += longDateString( d, dtf ); 278 buf += longDateString( d, dtf );
279 279
280 return buf; 280 return buf;
281} 281}
282 282
283QString TimeString::timeString( const QTime &t, bool ampm, bool seconds ) 283QString TimeString::timeString( const QTime &t, bool ampm, bool seconds )
284{ 284{
285 if ( !ampm ) { 285 if ( !ampm ) {
286 if ( seconds ) 286 if ( seconds )
287 return t.toString(); 287 return t.toString();
288 QString r = QString::number(t.hour()); 288 QString r = QString::number(t.hour());
289 if ( t.hour() < 10 ) r.prepend( "0" ); 289 if ( t.hour() < 10 ) r.prepend( "0" );
290 r.append( ":" ); 290 r.append( ":" );
291 if ( t.minute() < 10 ) r.append( "0" ); 291 if ( t.minute() < 10 ) r.append( "0" );
292 r.append(QString::number(t.minute())); 292 r.append(QString::number(t.minute()));
293 return r; 293 return r;
294 } 294 }
295 // ### else the hard case that should disappear in Qt 3.0 295 // ### else the hard case that should disappear in Qt 3.0
296 QString argString = seconds ? "%4:%5:%6 %7" : "%4:%5 %7"; 296 QString argString = seconds ? "%4:%5:%6 %7" : "%4:%5 %7";
297 int hour = t.hour(); 297 int hour = t.hour();
298 QString strMin = QString::number( t.minute() ); 298 QString strMin = QString::number( t.minute() );
299 QString strSec = QString::number( t.second() ); 299 QString strSec = QString::number( t.second() );
300 if ( hour > 12 ) 300 if ( hour > 12 )
301 argString = argString.arg( hour - 12, 2 ); 301 argString = argString.arg( hour - 12, 2 );
302 else { 302 else {
303 if ( hour == 0 ) 303 if ( hour == 0 )
304 argString = argString.arg( 12 ); 304 argString = argString.arg( 12 );
305 else 305 else
306 argString = argString.arg( hour, 2 ); 306 argString = argString.arg( hour, 2 );
307 } 307 }
308 if ( t.minute() < 10 ) 308 if ( t.minute() < 10 )
309 strMin.prepend( "0" ); 309 strMin.prepend( "0" );
310 if ( t.second() < 10 ) 310 if ( t.second() < 10 )
311 strSec.prepend( "0" ); 311 strSec.prepend( "0" );
312 argString = argString.arg( strMin ); 312 argString = argString.arg( strMin );
313 if ( seconds ) 313 if ( seconds )
314 argString = argString.arg( strSec ); 314 argString = argString.arg( strSec );
315 if ( hour >= 12 ) 315 if ( hour >= 12 )
316 argString = argString.arg( QObject::tr("PM") ); 316 argString = argString.arg( QObject::tr("PM") );
317 else 317 else
318 argString = argString.arg( QObject::tr("AM") ); 318 argString = argString.arg( QObject::tr("AM") );
319 return argString; 319 return argString;
320} 320}
321 321
322QString TimeString::shortTime( bool ampm, bool seconds ) 322QString TimeString::shortTime( bool ampm, bool seconds )
323{ 323{
324 static const char* const day[] = { 324 static const char* const day[] = {
325 QT_TRANSLATE_NOOP( "QObject", "Mon" ), 325 QT_TRANSLATE_NOOP( "QObject", "Mon" ),
326 QT_TRANSLATE_NOOP( "QObject", "Tue" ), 326 QT_TRANSLATE_NOOP( "QObject", "Tue" ),
327 QT_TRANSLATE_NOOP( "QObject", "Wed" ), 327 QT_TRANSLATE_NOOP( "QObject", "Wed" ),
328 QT_TRANSLATE_NOOP( "QObject", "Thu" ), 328 QT_TRANSLATE_NOOP( "QObject", "Thu" ),
329 QT_TRANSLATE_NOOP( "QObject", "Fri" ), 329 QT_TRANSLATE_NOOP( "QObject", "Fri" ),
330 QT_TRANSLATE_NOOP( "QObject", "Sat" ), 330 QT_TRANSLATE_NOOP( "QObject", "Sat" ),
331 QT_TRANSLATE_NOOP( "QObject", "Sun" ) 331 QT_TRANSLATE_NOOP( "QObject", "Sun" )
332 }; 332 };
333 // just create a shorter time String 333 // just create a shorter time String
334 QDateTime dtTmp = QDateTime::currentDateTime(); 334 QDateTime dtTmp = QDateTime::currentDateTime();
335 QString strTime; 335 QString strTime;
336 strTime = QObject::tr( day[dtTmp.date().dayOfWeek()-1] ) + " " + 336 strTime = QObject::tr( day[dtTmp.date().dayOfWeek()-1] ) + " " +
337 timeString( dtTmp.time(), ampm, seconds ); 337 timeString( dtTmp.time(), ampm, seconds );
338 return strTime; 338 return strTime;
339} 339}
340 340
341QString TimeString::dateString( const QDateTime &t, bool ampm ) 341QString TimeString::dateString( const QDateTime &t, bool ampm )
342{ 342{
343 return dateString(t,ampm,FALSE); 343 return dateString(t,ampm,FALSE);
344} 344}
345 345
346QString TimeString::timeString( const QTime &t, bool ampm) 346QString TimeString::timeString( const QTime &t, bool ampm)
347{ 347{
348 return timeString(t,ampm,FALSE); 348 return timeString(t,ampm,FALSE);
349} 349}
350 350
351QString TimeString::shortTime( bool ampm ) 351QString TimeString::shortTime( bool ampm )
352{ 352{
353 return shortTime(ampm,FALSE); 353 return shortTime(ampm,FALSE);
354} 354}
355 355
356QString TimeString::numberDateString( const QDate &d, DateFormat dtf ) 356QString TimeString::numberDateString( const QDate &d, DateFormat dtf )
357{ 357{
358 return dtf.numberDate(d); 358 return dtf.numberDate(d);
359} 359}
360QString TimeString::longNumberDateString( const QDate &d, DateFormat dtf ) 360QString TimeString::longNumberDateString( const QDate &d, DateFormat dtf )
361{ 361{
362 return dtf.numberDate(d,DateFormat::longNumber); 362 return dtf.numberDate(d,DateFormat::longNumber);
363} 363}
364 364
365#include "timestring.moc" 365#include "timestring.moc"
diff --git a/library/tzselect.cpp b/library/tzselect.cpp
index f28100b..848dfb7 100644
--- a/library/tzselect.cpp
+++ b/library/tzselect.cpp
@@ -1,302 +1,302 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#define QTOPIA_INTERNAL_TZSELECT_INC_LOCAL 21#define QTOPIA_INTERNAL_TZSELECT_INC_LOCAL
22 22
23#include "tzselect.h" 23#include "tzselect.h"
24#include "resource.h" 24#include "resource.h"
25#include "config.h" 25#include "config.h"
26#include <qtoolbutton.h> 26#include <qtoolbutton.h>
27#include <qfile.h> 27#include <qfile.h>
28#include <stdlib.h> 28#include <stdlib.h>
29 29
30#include <qcopchannel_qws.h> 30#include <qcopchannel_qws.h>
31#include <qpe/qpeapplication.h> 31#include <qpe/qpeapplication.h>
32#include <qmessagebox.h> 32#include <qmessagebox.h>
33 33
34/*! 34/*!
35 \class TimeZoneSelector 35 \class TimeZoneSelector
36 36
37 \brief The TimeZoneSelector widget allows users to configure their time zone information. 37 \brief The TimeZoneSelector widget allows users to configure their time zone information.
38 38
39 \ingroup qtopiaemb 39 \ingroup qtopiaemb
40*/ 40*/
41 41
42class TimeZoneSelectorPrivate 42class TimeZoneSelectorPrivate
43{ 43{
44public: 44public:
45 TimeZoneSelectorPrivate() : includeLocal(FALSE) {} 45 TimeZoneSelectorPrivate() : includeLocal(FALSE) {}
46 bool includeLocal; 46 bool includeLocal;
47}; 47};
48 48
49TZCombo::TZCombo( QWidget *p, const char* n ) 49TZCombo::TZCombo( QWidget *p, const char* n )
50 : QComboBox( p, n ) 50 : QComboBox( p, n )
51{ 51{
52 updateZones(); 52 updateZones();
53 // check to see if TZ is set, if it is set the current item to that 53 // check to see if TZ is set, if it is set the current item to that
54 QString tz = getenv("TZ"); 54 QString tz = getenv("TZ");
55 if (parent()->inherits("TimeZoneSelector")) { 55 if (parent()->inherits("TimeZoneSelector")) {
56 if ( ((TimeZoneSelector *)parent())->localIncluded() ) { 56 if ( ((TimeZoneSelector *)parent())->localIncluded() ) {
57 // overide to the 'local' type. 57 // overide to the 'local' type.
58 tz = "None"; 58 tz = "None";
59 } 59 }
60 } 60 }
61 if ( !tz.isNull() ) { 61 if ( !tz.isNull() ) {
62 int n = 0, 62 int n = 0,
63 index = 0; 63 index = 0;
64 for ( QStringList::Iterator it=identifiers.begin(); 64 for ( QStringList::Iterator it=identifiers.begin();
65 it!=identifiers.end(); ++it) { 65 it!=identifiers.end(); ++it) {
66 if ( *it == tz ) 66 if ( *it == tz )
67 index = n; 67 index = n;
68 n++; 68 n++;
69 } 69 }
70 setCurrentItem(index); 70 setCurrentItem(index);
71 } else { 71 } else {
72 setCurrentItem(0); 72 setCurrentItem(0);
73 } 73 }
74 74
75 75
76 76
77 // listen on QPE/System 77 // listen on QPE/System
78#if !defined(QT_NO_COP) 78#if !defined(QT_NO_COP)
79 QCopChannel *channel = new QCopChannel( "QPE/System", this ); 79 QCopChannel *channel = new QCopChannel( "QPE/System", this );
80 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 80 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
81 this, SLOT(handleSystemChannel(const QCString&, const QByteArray&)) ); 81 this, SLOT(handleSystemChannel(const QCString&,const QByteArray&)) );
82#endif 82#endif
83 83
84 84
85} 85}
86 86
87TZCombo::~TZCombo() 87TZCombo::~TZCombo()
88{ 88{
89} 89}
90 90
91void TZCombo::updateZones() 91void TZCombo::updateZones()
92{ 92{
93 QString cur = currentText(); 93 QString cur = currentText();
94 clear(); 94 clear();
95 identifiers.clear(); 95 identifiers.clear();
96 int curix=0; 96 int curix=0;
97 QString tz = getenv("TZ"); 97 QString tz = getenv("TZ");
98 bool tzFound = FALSE; 98 bool tzFound = FALSE;
99 Config cfg("CityTime"); 99 Config cfg("CityTime");
100 cfg.setGroup("TimeZones"); 100 cfg.setGroup("TimeZones");
101 int listIndex = 0; 101 int listIndex = 0;
102 if (parent()->inherits("TimeZoneSelector")) { 102 if (parent()->inherits("TimeZoneSelector")) {
103 if ( ((TimeZoneSelector *)parent())->localIncluded() ) { 103 if ( ((TimeZoneSelector *)parent())->localIncluded() ) {
104 // overide to the 'local' type. 104 // overide to the 'local' type.
105 identifiers.append( "None" ); 105 identifiers.append( "None" );
106 insertItem( tr("None") ); 106 insertItem( tr("None") );
107 if ( cur == tr("None")) 107 if ( cur == tr("None"))
108 curix = 0; 108 curix = 0;
109 listIndex++; 109 listIndex++;
110 } 110 }
111 } 111 }
112 int cfgIndex = 0; 112 int cfgIndex = 0;
113 while (1) { 113 while (1) {
114 QString zn = cfg.readEntry("Zone"+QString::number(cfgIndex), QString::null); 114 QString zn = cfg.readEntry("Zone"+QString::number(cfgIndex), QString::null);
115 if ( zn.isNull() ) 115 if ( zn.isNull() )
116 break; 116 break;
117 if ( zn == tz ) 117 if ( zn == tz )
118 tzFound = TRUE; 118 tzFound = TRUE;
119 QString nm = cfg.readEntry("ZoneName"+QString::number(cfgIndex)); 119 QString nm = cfg.readEntry("ZoneName"+QString::number(cfgIndex));
120 identifiers.append(zn); 120 identifiers.append(zn);
121 insertItem(nm); 121 insertItem(nm);
122 if ( nm == cur ) 122 if ( nm == cur )
123 curix = listIndex; 123 curix = listIndex;
124 ++cfgIndex; 124 ++cfgIndex;
125 ++listIndex; 125 ++listIndex;
126 } 126 }
127 if ( !listIndex ) { 127 if ( !listIndex ) {
128 QStringList list = timezoneDefaults(); 128 QStringList list = timezoneDefaults();
129 for ( QStringList::Iterator it = list.begin(); it!=list.end(); ++it ) { 129 for ( QStringList::Iterator it = list.begin(); it!=list.end(); ++it ) {
130 QString zn = *it; 130 QString zn = *it;
131 QString nm = *++it; 131 QString nm = *++it;
132 if ( zn == tz ) 132 if ( zn == tz )
133 tzFound = TRUE; 133 tzFound = TRUE;
134 if ( nm == cur ) 134 if ( nm == cur )
135 curix = listIndex; 135 curix = listIndex;
136 identifiers.append(zn); 136 identifiers.append(zn);
137 insertItem(nm); 137 insertItem(nm);
138 ++listIndex; 138 ++listIndex;
139 } 139 }
140 } 140 }
141 for (QStringList::Iterator it=extras.begin(); it!=extras.end(); ++it) { 141 for (QStringList::Iterator it=extras.begin(); it!=extras.end(); ++it) {
142 insertItem(*it); 142 insertItem(*it);
143 identifiers.append(*it); 143 identifiers.append(*it);
144 if ( *it == cur ) 144 if ( *it == cur )
145 curix = listIndex; 145 curix = listIndex;
146 ++listIndex; 146 ++listIndex;
147 } 147 }
148 if ( !tzFound && !tz.isEmpty()) { 148 if ( !tzFound && !tz.isEmpty()) {
149 int i = tz.find( '/' ); 149 int i = tz.find( '/' );
150 QString nm = tz.mid( i+1 ).replace(QRegExp("_"), " "); 150 QString nm = tz.mid( i+1 ).replace(QRegExp("_"), " ");
151 identifiers.append(tz); 151 identifiers.append(tz);
152 insertItem(nm); 152 insertItem(nm);
153 if ( nm == cur ) 153 if ( nm == cur )
154 curix = listIndex; 154 curix = listIndex;
155 ++listIndex; 155 ++listIndex;
156 } 156 }
157 setCurrentItem(curix); 157 setCurrentItem(curix);
158} 158}
159 159
160 160
161void TZCombo::keyPressEvent( QKeyEvent *e ) 161void TZCombo::keyPressEvent( QKeyEvent *e )
162{ 162{
163 // ### should popup() in Qt 3.0 (it's virtual there) 163 // ### should popup() in Qt 3.0 (it's virtual there)
164// updateZones(); 164// updateZones();
165 QComboBox::keyPressEvent(e); 165 QComboBox::keyPressEvent(e);
166} 166}
167 167
168void TZCombo::mousePressEvent(QMouseEvent*e) 168void TZCombo::mousePressEvent(QMouseEvent*e)
169{ 169{
170 // ### should popup() in Qt 3.0 (it's virtual there) 170 // ### should popup() in Qt 3.0 (it's virtual there)
171// updateZones(); 171// updateZones();
172 QComboBox::mousePressEvent(e); 172 QComboBox::mousePressEvent(e);
173} 173}
174 174
175QString TZCombo::currZone() const 175QString TZCombo::currZone() const
176{ 176{
177 return identifiers[currentItem()]; 177 return identifiers[currentItem()];
178} 178}
179 179
180void TZCombo::setCurrZone( const QString& id ) 180void TZCombo::setCurrZone( const QString& id )
181{ 181{
182 for (int i=0; i< count(); i++) { 182 for (int i=0; i< count(); i++) {
183 if ( identifiers[i] == id ) { 183 if ( identifiers[i] == id ) {
184 setCurrentItem(i); 184 setCurrentItem(i);
185 return; 185 return;
186} 186}
187 } 187 }
188 insertItem(id); 188 insertItem(id);
189 setCurrentItem( count() - 1); 189 setCurrentItem( count() - 1);
190 identifiers.append(id); 190 identifiers.append(id);
191 extras.append(id); 191 extras.append(id);
192} 192}
193 193
194 194
195 195
196void TZCombo::handleSystemChannel(const QCString&msg, const QByteArray&) 196void TZCombo::handleSystemChannel(const QCString&msg, const QByteArray&)
197{ 197{
198 if ( msg == "timeZoneListChange()" ) { 198 if ( msg == "timeZoneListChange()" ) {
199 updateZones(); 199 updateZones();
200 } 200 }
201} 201}
202 202
203/*! 203/*!
204 Creates a new TimeZoneSelector with parent \a p and name \a n. The combobox will be 204 Creates a new TimeZoneSelector with parent \a p and name \a n. The combobox will be
205 populated with the available timezones. 205 populated with the available timezones.
206*/ 206*/
207 207
208TimeZoneSelector::TimeZoneSelector(QWidget* p, const char* n) : 208TimeZoneSelector::TimeZoneSelector(QWidget* p, const char* n) :
209 QHBox(p,n) 209 QHBox(p,n)
210{ 210{
211 d = new TimeZoneSelectorPrivate(); 211 d = new TimeZoneSelectorPrivate();
212 // build the combobox before we do any updates... 212 // build the combobox before we do any updates...
213 cmbTz = new TZCombo( this, "timezone combo" ); 213 cmbTz = new TZCombo( this, "timezone combo" );
214 214
215 cmdTz = new QToolButton( this, "timezone button" ); 215 cmdTz = new QToolButton( this, "timezone button" );
216 cmdTz->setIconSet( Resource::loadIconSet( "citytime_icon" ) ); 216 cmdTz->setIconSet( Resource::loadIconSet( "citytime_icon" ) );
217 cmdTz->setMaximumSize( cmdTz->sizeHint() ); 217 cmdTz->setMaximumSize( cmdTz->sizeHint() );
218 218
219 // set up a connection to catch a newly selected item and throw our 219 // set up a connection to catch a newly selected item and throw our
220 // signal 220 // signal
221 QObject::connect( cmbTz, SIGNAL( activated( int ) ), 221 QObject::connect( cmbTz, SIGNAL( activated(int) ),
222 this, SLOT( slotTzActive( int ) ) ); 222 this, SLOT( slotTzActive(int) ) );
223 QObject::connect( cmdTz, SIGNAL( clicked() ), 223 QObject::connect( cmdTz, SIGNAL( clicked() ),
224 this, SLOT( slotExecute() ) ); 224 this, SLOT( slotExecute() ) );
225} 225}
226 226
227/*! 227/*!
228 Destroys a TimeZoneSelector. 228 Destroys a TimeZoneSelector.
229*/ 229*/
230TimeZoneSelector::~TimeZoneSelector() 230TimeZoneSelector::~TimeZoneSelector()
231{ 231{
232} 232}
233 233
234void TimeZoneSelector::setLocalIncluded(bool b) 234void TimeZoneSelector::setLocalIncluded(bool b)
235{ 235{
236 d->includeLocal = b; 236 d->includeLocal = b;
237 cmbTz->updateZones(); 237 cmbTz->updateZones();
238} 238}
239 239
240bool TimeZoneSelector::localIncluded() const 240bool TimeZoneSelector::localIncluded() const
241{ 241{
242 return d->includeLocal; 242 return d->includeLocal;
243} 243}
244 244
245/*! 245/*!
246 Returns the currently selected timezone as a string in location format, e.g. 246 Returns the currently selected timezone as a string in location format, e.g.
247 \code Australia/Brisbane \endcode 247 \code Australia/Brisbane \endcode
248*/ 248*/
249QString TimeZoneSelector::currentZone() const 249QString TimeZoneSelector::currentZone() const
250{ 250{
251 return cmbTz->currZone(); 251 return cmbTz->currZone();
252} 252}
253 253
254/*! 254/*!
255 Sets the current timezone to \a id. 255 Sets the current timezone to \a id.
256*/ 256*/
257void TimeZoneSelector::setCurrentZone( const QString& id ) 257void TimeZoneSelector::setCurrentZone( const QString& id )
258{ 258{
259 cmbTz->setCurrZone( id ); 259 cmbTz->setCurrZone( id );
260} 260}
261/*! \fn void TimeZoneSelector::signalNewTz( const QString& id ) 261/*! \fn void TimeZoneSelector::signalNewTz( const QString& id )
262 This signal is emitted when a timezone has been selected by the user. The id 262 This signal is emitted when a timezone has been selected by the user. The id
263 is a \l QString in location format, eg \code Australia/Brisbane \endcode 263 is a \l QString in location format, eg \code Australia/Brisbane \endcode
264*/ 264*/
265 265
266 266
267void TimeZoneSelector::slotTzActive( int ) 267void TimeZoneSelector::slotTzActive( int )
268{ 268{
269 emit signalNewTz( cmbTz->currZone() ); 269 emit signalNewTz( cmbTz->currZone() );
270} 270}
271 271
272void TimeZoneSelector::slotExecute( void ) 272void TimeZoneSelector::slotExecute( void )
273{ 273{
274 // execute the world time application... 274 // execute the world time application...
275 if (QFile::exists(QPEApplication::qpeDir()+"bin/citytime")) 275 if (QFile::exists(QPEApplication::qpeDir()+"bin/citytime"))
276 Global::execute( "citytime" ); 276 Global::execute( "citytime" );
277 else 277 else
278 QMessageBox::warning(this,tr("citytime executable not found"), 278 QMessageBox::warning(this,tr("citytime executable not found"),
279 tr("In order to choose the time zones,\nplease install citytime.")); 279 tr("In order to choose the time zones,\nplease install citytime."));
280} 280}
281 281
282QStringList timezoneDefaults( void ) 282QStringList timezoneDefaults( void )
283{ 283{
284 QStringList tzs; 284 QStringList tzs;
285 // load up the list just like the file format (citytime.cpp) 285 // load up the list just like the file format (citytime.cpp)
286 tzs.append( "America/New_York" ); 286 tzs.append( "America/New_York" );
287 tzs.append( "New York" ); 287 tzs.append( "New York" );
288 tzs.append( "America/Los_Angeles" ); 288 tzs.append( "America/Los_Angeles" );
289 tzs.append( "Los Angeles" ); 289 tzs.append( "Los Angeles" );
290 tzs.append( "Australia/Brisbane" ); 290 tzs.append( "Australia/Brisbane" );
291 tzs.append( "Brisbane" ); 291 tzs.append( "Brisbane" );
292 tzs.append( "Europe/Berlin" ); 292 tzs.append( "Europe/Berlin" );
293 tzs.append( "Berlin" ); 293 tzs.append( "Berlin" );
294 tzs.append( "Asia/Tokyo" ); 294 tzs.append( "Asia/Tokyo" );
295 tzs.append( "Tokyo" ); 295 tzs.append( "Tokyo" );
296 tzs.append( "America/Denver" ); 296 tzs.append( "America/Denver" );
297 tzs.append( "Denver" ); 297 tzs.append( "Denver" );
298 298
299 return tzs; 299 return tzs;
300} 300}
301 301
302 302
diff --git a/noncore/applets/memoryapplet/swapfile.cpp b/noncore/applets/memoryapplet/swapfile.cpp
index 04da8bb..9416db3 100644
--- a/noncore/applets/memoryapplet/swapfile.cpp
+++ b/noncore/applets/memoryapplet/swapfile.cpp
@@ -1,434 +1,434 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include "swapfile.h" 21#include "swapfile.h"
22 22
23#include <qfile.h> 23#include <qfile.h>
24#include <qtextstream.h> 24#include <qtextstream.h>
25#include <qlabel.h> 25#include <qlabel.h>
26#include <qtimer.h> 26#include <qtimer.h>
27#include <qlayout.h> 27#include <qlayout.h>
28#include <qpushbutton.h> 28#include <qpushbutton.h>
29#include <qhbuttongroup.h> 29#include <qhbuttongroup.h>
30#include <qradiobutton.h> 30#include <qradiobutton.h>
31#include <qlineedit.h> 31#include <qlineedit.h>
32#include <qprogressbar.h> 32#include <qprogressbar.h>
33#include <qcombobox.h> 33#include <qcombobox.h>
34#include <qvgroupbox.h> 34#include <qvgroupbox.h>
35#include <qhbox.h> 35#include <qhbox.h>
36#include <qmessagebox.h> 36#include <qmessagebox.h>
37#include <stdio.h> 37#include <stdio.h>
38#include <stdlib.h> 38#include <stdlib.h>
39#include <string.h> 39#include <string.h>
40 40
41#include <qcopchannel_qws.h> 41#include <qcopchannel_qws.h>
42#include <qpe/resource.h> 42#include <qpe/resource.h>
43 43
44#include <unistd.h> 44#include <unistd.h>
45#include <fcntl.h> 45#include <fcntl.h>
46#include <sys/vfs.h> 46#include <sys/vfs.h>
47#include <mntent.h> 47#include <mntent.h>
48#include <unistd.h> 48#include <unistd.h>
49#include <sys/types.h> 49#include <sys/types.h>
50 50
51Swapfile::Swapfile( QWidget *parent, const char *name, WFlags f ) 51Swapfile::Swapfile( QWidget *parent, const char *name, WFlags f )
52 : QWidget( parent, name, f ) 52 : QWidget( parent, name, f )
53{ 53{
54 // are we running as root? 54 // are we running as root?
55 isRoot = geteuid() == 0; 55 isRoot = geteuid() == 0;
56 56
57 QVBoxLayout* vb = new QVBoxLayout(this, 5); 57 QVBoxLayout* vb = new QVBoxLayout(this, 5);
58 58
59 QHButtonGroup* cfsdRBG = new QHButtonGroup(tr("Swapfile location"), this); 59 QHButtonGroup* cfsdRBG = new QHButtonGroup(tr("Swapfile location"), this);
60 cfsdRBG->setRadioButtonExclusive(true); 60 cfsdRBG->setRadioButtonExclusive(true);
61 vb->addWidget(cfsdRBG); 61 vb->addWidget(cfsdRBG);
62 62
63 ramRB = new QRadioButton(tr("RAM"), cfsdRBG); 63 ramRB = new QRadioButton(tr("RAM"), cfsdRBG);
64 cfRB = new QRadioButton(tr("CF Card"), cfsdRBG); 64 cfRB = new QRadioButton(tr("CF Card"), cfsdRBG);
65 sdRB = new QRadioButton(tr("SD Card"), cfsdRBG); 65 sdRB = new QRadioButton(tr("SD Card"), cfsdRBG);
66 66
67 QHBox *hb1 = new QHBox(this); 67 QHBox *hb1 = new QHBox(this);
68 hb1->setSpacing(5); 68 hb1->setSpacing(5);
69 69
70 swapPath1 = new QLineEdit(hb1); 70 swapPath1 = new QLineEdit(hb1);
71 swapPath1->setEnabled(false); 71 swapPath1->setEnabled(false);
72 72
73 QPushButton* swapOn = new QPushButton(tr(" On "), hb1); 73 QPushButton* swapOn = new QPushButton(tr(" On "), hb1);
74 QPushButton* swapOff = new QPushButton(tr(" Off "), hb1); 74 QPushButton* swapOff = new QPushButton(tr(" Off "), hb1);
75 vb->addWidget(hb1); 75 vb->addWidget(hb1);
76 76
77 QVGroupBox* box1 = new QVGroupBox(tr("Manage Swapfile"), this); 77 QVGroupBox* box1 = new QVGroupBox(tr("Manage Swapfile"), this);
78 vb->addWidget(box1); 78 vb->addWidget(box1);
79 79
80 QHBox *hb2 = new QHBox(box1); 80 QHBox *hb2 = new QHBox(box1);
81 hb2->setSpacing(5); 81 hb2->setSpacing(5);
82 QPushButton* mkSwap = new QPushButton(tr("Generate"), hb2); 82 QPushButton* mkSwap = new QPushButton(tr("Generate"), hb2);
83 QPushButton* rmSwap = new QPushButton(tr("Remove"), hb2); 83 QPushButton* rmSwap = new QPushButton(tr("Remove"), hb2);
84 84
85 QHBox *hb3 = new QHBox(box1); 85 QHBox *hb3 = new QHBox(box1);
86 hb3->setSpacing(5); 86 hb3->setSpacing(5);
87 swapSize = new QComboBox(hb3); 87 swapSize = new QComboBox(hb3);
88 swapSize->insertStringList(QStringList::split(",", tr("2 Mb,4 Mb,6 Mb,8 Mb"))); 88 swapSize->insertStringList(QStringList::split(",", tr("2 Mb,4 Mb,6 Mb,8 Mb")));
89 89
90 mkswapProgress = new QProgressBar(3, hb3); 90 mkswapProgress = new QProgressBar(3, hb3);
91 mkswapProgress->setCenterIndicator(true); 91 mkswapProgress->setCenterIndicator(true);
92 92
93 QHBox *hb4 = new QHBox(this); 93 QHBox *hb4 = new QHBox(this);
94 hb4->setSpacing(5); 94 hb4->setSpacing(5);
95 95
96 swapStatusIcon = new QLabel(hb4); 96 swapStatusIcon = new QLabel(hb4);
97 swapStatus = new QLabel(tr(""), hb4); 97 swapStatus = new QLabel(tr(""), hb4);
98 hb4->setStretchFactor(swapStatus, 99); 98 hb4->setStretchFactor(swapStatus, 99);
99 vb->addWidget(hb4); 99 vb->addWidget(hb4);
100 100
101 connect(swapOn, SIGNAL(clicked()), this, SLOT(swapon())); 101 connect(swapOn, SIGNAL(clicked()), this, SLOT(swapon()));
102 connect(swapOff, SIGNAL(clicked()), this, SLOT(swapoff())); 102 connect(swapOff, SIGNAL(clicked()), this, SLOT(swapoff()));
103 connect(cfRB, SIGNAL(clicked()), this, SLOT(cfsdchecked())); 103 connect(cfRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
104 connect(sdRB, SIGNAL(clicked()), this, SLOT(cfsdchecked())); 104 connect(sdRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
105 connect(ramRB, SIGNAL(clicked()), this, SLOT(cfsdchecked())); 105 connect(ramRB, SIGNAL(clicked()), this, SLOT(cfsdchecked()));
106 connect(mkSwap, SIGNAL(clicked()), this, SLOT(makeswapfile())); 106 connect(mkSwap, SIGNAL(clicked()), this, SLOT(makeswapfile()));
107 connect(rmSwap, SIGNAL(clicked()), this, SLOT(removeswapfile())); 107 connect(rmSwap, SIGNAL(clicked()), this, SLOT(removeswapfile()));
108 108
109 cfRB->setEnabled(FALSE); 109 cfRB->setEnabled(FALSE);
110 sdRB->setEnabled(FALSE); 110 sdRB->setEnabled(FALSE);
111 111
112 QCopChannel *pcmciaChannel = new QCopChannel("QPE/Card", this); 112 QCopChannel *pcmciaChannel = new QCopChannel("QPE/Card", this);
113 connect(pcmciaChannel, SIGNAL(received(const QCString &, const QByteArray &)), this, SLOT(cardnotify(const QCString &, const QByteArray &))); 113 connect(pcmciaChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&)));
114 QCopChannel *sdChannel = new QCopChannel("QPE/Card", this); 114 QCopChannel *sdChannel = new QCopChannel("QPE/Card", this);
115 connect(sdChannel, SIGNAL(received(const QCString &, const QByteArray &)), this, SLOT(cardnotify(const QCString &, const QByteArray &))); 115 connect(sdChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(cardnotify(const QCString&,const QByteArray&)));
116 116
117 cardInPcmcia0 = FALSE; 117 cardInPcmcia0 = FALSE;
118 cardInPcmcia1 = FALSE; 118 cardInPcmcia1 = FALSE;
119 cardInSd = FALSE; 119 cardInSd = FALSE;
120 120
121 Swapfile::status(); 121 Swapfile::status();
122 Swapfile::getStatusPcmcia(); 122 Swapfile::getStatusPcmcia();
123 Swapfile::getStatusSd(); 123 Swapfile::getStatusSd();
124} 124}
125 125
126int Swapfile::exec(const QString& arg) 126int Swapfile::exec(const QString& arg)
127{ 127{
128 return system((!isRoot ? "sudo " : "") + arg); 128 return system((!isRoot ? "sudo " : "") + arg);
129} 129}
130 130
131 131
132Swapfile::~Swapfile() 132Swapfile::~Swapfile()
133{ 133{
134} 134}
135 135
136void Swapfile::cardnotify(const QCString & msg, const QByteArray &) 136void Swapfile::cardnotify(const QCString & msg, const QByteArray &)
137{ 137{
138 if (msg == "stabChanged()") 138 if (msg == "stabChanged()")
139 { 139 {
140 getStatusPcmcia(); 140 getStatusPcmcia();
141 } 141 }
142 else if (msg == "mtabChanged()") 142 else if (msg == "mtabChanged()")
143 { 143 {
144 getStatusSd(); 144 getStatusSd();
145 } 145 }
146} 146}
147 147
148void Swapfile::getStatusPcmcia() 148void Swapfile::getStatusPcmcia()
149{ 149{
150 150
151 bool cardWas0 = cardInPcmcia0;// remember last state 151 bool cardWas0 = cardInPcmcia0;// remember last state
152 bool cardWas1 = cardInPcmcia1; 152 bool cardWas1 = cardInPcmcia1;
153 153
154 QString fileName; 154 QString fileName;
155 155
156 // one of these 3 files should exist 156 // one of these 3 files should exist
157 if (QFile::exists("/var/run/stab")) { 157 if (QFile::exists("/var/run/stab")) {
158 fileName = "/var/run/stab"; 158 fileName = "/var/run/stab";
159 } else if (QFile::exists("/var/state/pcmcia/stab")) { 159 } else if (QFile::exists("/var/state/pcmcia/stab")) {
160 fileName = "/var/state/pcmcia/stab"; 160 fileName = "/var/state/pcmcia/stab";
161 } else { 161 } else {
162 fileName = "/var/lib/pcmcia/stab"; 162 fileName = "/var/lib/pcmcia/stab";
163 } 163 }
164 164
165 QFile f(fileName); 165 QFile f(fileName);
166 166
167 if (f.open(IO_ReadOnly)) { 167 if (f.open(IO_ReadOnly)) {
168 QStringList list; 168 QStringList list;
169 QTextStream stream(&f); 169 QTextStream stream(&f);
170 QString streamIn; 170 QString streamIn;
171 streamIn = stream.read(); 171 streamIn = stream.read();
172 list = QStringList::split("\n", streamIn); 172 list = QStringList::split("\n", streamIn);
173 for (QStringList::Iterator line = list.begin(); line != list.end(); 173 for (QStringList::Iterator line = list.begin(); line != list.end();
174 line++) { 174 line++) {
175 if ((*line).startsWith("Socket 0:")) { 175 if ((*line).startsWith("Socket 0:")) {
176 if ((*line).startsWith("Socket 0: empty") && cardInPcmcia0) { 176 if ((*line).startsWith("Socket 0: empty") && cardInPcmcia0) {
177 cardInPcmcia0 = FALSE; 177 cardInPcmcia0 = FALSE;
178 } else if (!(*line).startsWith("Socket 0: empty") 178 } else if (!(*line).startsWith("Socket 0: empty")
179 && !cardInPcmcia0) { 179 && !cardInPcmcia0) {
180 cardInPcmcia0 = TRUE; 180 cardInPcmcia0 = TRUE;
181 } 181 }
182 } else if ((*line).startsWith("Socket 1:")) { 182 } else if ((*line).startsWith("Socket 1:")) {
183 if ((*line).startsWith("Socket 1: empty") && cardInPcmcia1) { 183 if ((*line).startsWith("Socket 1: empty") && cardInPcmcia1) {
184 cardInPcmcia1 = FALSE; 184 cardInPcmcia1 = FALSE;
185 } else if (!(*line).startsWith("Socket 1: empty") 185 } else if (!(*line).startsWith("Socket 1: empty")
186 && !cardInPcmcia1) { 186 && !cardInPcmcia1) {
187 cardInPcmcia1 = TRUE; 187 cardInPcmcia1 = TRUE;
188 } 188 }
189 } 189 }
190 } 190 }
191 f.close(); 191 f.close();
192 192
193 if (cardWas0 != cardInPcmcia0 || cardWas1 != cardInPcmcia1) { 193 if (cardWas0 != cardInPcmcia0 || cardWas1 != cardInPcmcia1) {
194 QString text = QString::null; 194 QString text = QString::null;
195 QString what = QString::null; 195 QString what = QString::null;
196 if (cardWas0 != cardInPcmcia0) { 196 if (cardWas0 != cardInPcmcia0) {
197 if (cardInPcmcia0) { 197 if (cardInPcmcia0) {
198 cfRB->setEnabled(TRUE); 198 cfRB->setEnabled(TRUE);
199 } else { 199 } else {
200 cfRB->setChecked(FALSE); 200 cfRB->setChecked(FALSE);
201 cfRB->setEnabled(FALSE); 201 cfRB->setEnabled(FALSE);
202 } 202 }
203 } 203 }
204 204
205 if (cardWas1 != cardInPcmcia1) { 205 if (cardWas1 != cardInPcmcia1) {
206 if (cardInPcmcia1) { 206 if (cardInPcmcia1) {
207 cfRB->setEnabled(TRUE); 207 cfRB->setEnabled(TRUE);
208 } else { 208 } else {
209 cfRB->setChecked(FALSE); 209 cfRB->setChecked(FALSE);
210 cfRB->setEnabled(FALSE); 210 cfRB->setEnabled(FALSE);
211 } 211 }
212 } 212 }
213 } 213 }
214 } else { 214 } else {
215 // no file found 215 // no file found
216 qDebug("no file found"); 216 qDebug("no file found");
217 cardInPcmcia0 = FALSE; 217 cardInPcmcia0 = FALSE;
218 cardInPcmcia1 = FALSE; 218 cardInPcmcia1 = FALSE;
219 } 219 }
220 Swapfile::cfsdchecked(); 220 Swapfile::cfsdchecked();
221} 221}
222 222
223 223
224void Swapfile::getStatusSd() 224void Swapfile::getStatusSd()
225{ 225{
226 226
227 bool cardWas = cardInSd;// remember last state 227 bool cardWas = cardInSd;// remember last state
228 cardInSd = FALSE; 228 cardInSd = FALSE;
229 229
230#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 230#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
231 struct mntent *me; 231 struct mntent *me;
232 FILE *mntfp = setmntent("/etc/mtab", "r"); 232 FILE *mntfp = setmntent("/etc/mtab", "r");
233 233
234 if (mntfp) { 234 if (mntfp) {
235 while ((me = getmntent(mntfp)) != 0) { 235 while ((me = getmntent(mntfp)) != 0) {
236 QString fs = me->mnt_fsname; 236 QString fs = me->mnt_fsname;
237 if (fs.left(14) == "/dev/mmc/part1" || fs.left(7) == "/dev/sd" 237 if (fs.left(14) == "/dev/mmc/part1" || fs.left(7) == "/dev/sd"
238 || fs.left(9) == "/dev/mmcd") { 238 || fs.left(9) == "/dev/mmcd") {
239 cardInSd = TRUE; 239 cardInSd = TRUE;
240 show(); 240 show();
241 } 241 }
242 } 242 }
243 endmntent(mntfp); 243 endmntent(mntfp);
244 } 244 }
245 245
246 if (cardWas != cardInSd) { 246 if (cardWas != cardInSd) {
247 QString text = QString::null; 247 QString text = QString::null;
248 QString what = QString::null; 248 QString what = QString::null;
249 if (cardInSd) { 249 if (cardInSd) {
250 sdRB->setEnabled(TRUE); 250 sdRB->setEnabled(TRUE);
251 } else { 251 } else {
252 sdRB->setChecked(FALSE); 252 sdRB->setChecked(FALSE);
253 sdRB->setEnabled(FALSE); 253 sdRB->setEnabled(FALSE);
254 } 254 }
255 } 255 }
256#else 256#else
257#error "Not on Linux" 257#error "Not on Linux"
258#endif 258#endif
259 Swapfile::cfsdchecked(); 259 Swapfile::cfsdchecked();
260} 260}
261 261
262int rc=0; 262int rc=0;
263 263
264void Swapfile::swapon() 264void Swapfile::swapon()
265{ 265{
266 char swapcmd[128] ="swapon "; 266 char swapcmd[128] ="swapon ";
267 Swapfile::cfsdchecked(); 267 Swapfile::cfsdchecked();
268 strcat(swapcmd,swapPath1->text()); 268 strcat(swapcmd,swapPath1->text());
269 char *runcmd = swapcmd; 269 char *runcmd = swapcmd;
270 rc = exec(QString("%1").arg(runcmd)); 270 rc = exec(QString("%1").arg(runcmd));
271 if (rc != 0) { 271 if (rc != 0) {
272 setStatusMessage("Failed to attach swapfile.", true); 272 setStatusMessage("Failed to attach swapfile.", true);
273 } 273 }
274 else { 274 else {
275 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 275 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
276 setStatusMessage("Swapfile activated."); 276 setStatusMessage("Swapfile activated.");
277 } 277 }
278 Swapfile::status(); 278 Swapfile::status();
279} 279}
280 280
281 281
282void Swapfile::setStatusMessage(const QString& text, bool error /* = false */) 282void Swapfile::setStatusMessage(const QString& text, bool error /* = false */)
283{ 283{
284 swapStatus->setText("<b>" + text + "</b>"); 284 swapStatus->setText("<b>" + text + "</b>");
285 swapStatusIcon->setPixmap(Resource::loadPixmap(error ? "close" : "done")); 285 swapStatusIcon->setPixmap(Resource::loadPixmap(error ? "close" : "done"));
286} 286}
287 287
288 288
289void Swapfile::swapoff() 289void Swapfile::swapoff()
290{ 290{
291 char swapcmd[128] ="swapoff "; 291 char swapcmd[128] ="swapoff ";
292 if (Swapfile::cfRB->isChecked() == TRUE) 292 if (Swapfile::cfRB->isChecked() == TRUE)
293 Swapfile::cfsdchecked(); 293 Swapfile::cfsdchecked();
294 strcat(swapcmd,swapPath1->text()); 294 strcat(swapcmd,swapPath1->text());
295 char *runcmd = swapcmd; 295 char *runcmd = swapcmd;
296 rc = exec(QString("%1").arg(runcmd)); 296 rc = exec(QString("%1").arg(runcmd));
297 if (rc != 0) { 297 if (rc != 0) {
298 setStatusMessage(tr("Failed to detach swapfile."), true); 298 setStatusMessage(tr("Failed to detach swapfile."), true);
299 } 299 }
300 else { 300 else {
301 /* QMessageBox::information(this, "Information", "Swapfile is inactive!"); */ 301 /* QMessageBox::information(this, "Information", "Swapfile is inactive!"); */
302 setStatusMessage(tr("Swapfile deactivated.")); 302 setStatusMessage(tr("Swapfile deactivated."));
303 /* Swapfile::swapPath->clear();*/ 303 /* Swapfile::swapPath->clear();*/
304 } 304 }
305 Swapfile::status(); 305 Swapfile::status();
306} 306}
307 307
308void Swapfile::cfsdchecked() 308void Swapfile::cfsdchecked()
309{ 309{
310 /* Swapfile::swapPath->clear();*/ 310 /* Swapfile::swapPath->clear();*/
311 Swapfile::swapPath1->clear(); 311 Swapfile::swapPath1->clear();
312 if (Swapfile::ramRB->isChecked() == TRUE) 312 if (Swapfile::ramRB->isChecked() == TRUE)
313 { 313 {
314 Swapfile::swapPath1->insert("/home/swapfile"); 314 Swapfile::swapPath1->insert("/home/swapfile");
315 } 315 }
316 if (Swapfile::sdRB->isChecked() == TRUE) 316 if (Swapfile::sdRB->isChecked() == TRUE)
317 { 317 {
318 Swapfile::swapPath1->insert("/mnt/card/swapfile"); 318 Swapfile::swapPath1->insert("/mnt/card/swapfile");
319 } 319 }
320 if (Swapfile::cfRB->isChecked() == TRUE) 320 if (Swapfile::cfRB->isChecked() == TRUE)
321 { 321 {
322 Swapfile::swapPath1->insert("/mnt/cf/swapfile"); 322 Swapfile::swapPath1->insert("/mnt/cf/swapfile");
323 } 323 }
324 /*Swapfile::swapPath->insert(Swapfile::swapPath1->text());*/ 324 /*Swapfile::swapPath->insert(Swapfile::swapPath1->text());*/
325} 325}
326 326
327void Swapfile::makeswapfile() 327void Swapfile::makeswapfile()
328{ 328{
329 int i = swapSize->currentItem(); 329 int i = swapSize->currentItem();
330 330
331 mkswapProgress->setProgress(1); 331 mkswapProgress->setProgress(1);
332 switch ( i ) { 332 switch ( i ) {
333 case 0: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=2048").arg(swapPath1->text())); 333 case 0: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=2048").arg(swapPath1->text()));
334 break; 334 break;
335 case 1: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=4096").arg(swapPath1->text())); 335 case 1: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=4096").arg(swapPath1->text()));
336 break; 336 break;
337 case 2: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=6144").arg(swapPath1->text())); 337 case 2: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=6144").arg(swapPath1->text()));
338 break; 338 break;
339 case 3: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=8192").arg(swapPath1->text())); 339 case 3: rc=exec(QString("dd if=/dev/zero of=%1 bs=1k count=8192").arg(swapPath1->text()));
340 break; 340 break;
341 } 341 }
342 if (rc != 0) { 342 if (rc != 0) {
343 setStatusMessage(tr("Failed to create swapfile."), true); 343 setStatusMessage(tr("Failed to create swapfile."), true);
344 } 344 }
345 345
346 mkswapProgress->setProgress(2); 346 mkswapProgress->setProgress(2);
347 rc=exec(QString("mkswap %1").arg(swapPath1->text())); 347 rc=exec(QString("mkswap %1").arg(swapPath1->text()));
348 if (rc != 0) { 348 if (rc != 0) {
349 setStatusMessage(tr("Failed to initialize swapfile."), true); 349 setStatusMessage(tr("Failed to initialize swapfile."), true);
350 } 350 }
351 mkswapProgress->setProgress(3); 351 mkswapProgress->setProgress(3);
352 mkswapProgress->reset(); 352 mkswapProgress->reset();
353 setStatusMessage(tr("Swapfile created.")); 353 setStatusMessage(tr("Swapfile created."));
354} 354}
355 355
356void Swapfile::removeswapfile() 356void Swapfile::removeswapfile()
357{ 357{
358 exec(QString("swapoff %1").arg(swapPath1->text())); 358 exec(QString("swapoff %1").arg(swapPath1->text()));
359 rc=exec(QString("rm -rf %1").arg(swapPath1->text())); 359 rc=exec(QString("rm -rf %1").arg(swapPath1->text()));
360 if (rc != 0) { 360 if (rc != 0) {
361 setStatusMessage(tr("Failed to remove swapfile."), true); 361 setStatusMessage(tr("Failed to remove swapfile."), true);
362 } 362 }
363 Swapfile::status(); 363 Swapfile::status();
364 Swapfile::cfsdchecked(); 364 Swapfile::cfsdchecked();
365 setStatusMessage(tr("Swapfile removed.")); 365 setStatusMessage(tr("Swapfile removed."));
366} 366}
367 367
368void Swapfile::status() 368void Swapfile::status()
369{ 369{
370 FILE *fp; 370 FILE *fp;
371 char buffer[128], swapfile[128], temp[128]; 371 char buffer[128], swapfile[128], temp[128];
372 int swapsize=2000, i=1; 372 int swapsize=2000, i=1;
373 373
374 fp=fopen("/proc/swaps", "r"); 374 fp=fopen("/proc/swaps", "r");
375 while ( (fgets(buffer,128,fp)) != NULL ) { 375 while ( (fgets(buffer,128,fp)) != NULL ) {
376 sscanf(buffer, "%s %s %d %s %s\n", swapfile, temp, &swapsize, temp, temp); 376 sscanf(buffer, "%s %s %d %s %s\n", swapfile, temp, &swapsize, temp, temp);
377 } 377 }
378 fclose(fp); 378 fclose(fp);
379 379
380 ramRB->setChecked(FALSE); 380 ramRB->setChecked(FALSE);
381 cfRB->setChecked(FALSE); 381 cfRB->setChecked(FALSE);
382 sdRB->setChecked(FALSE); 382 sdRB->setChecked(FALSE);
383 383
384 i=strcmp(swapfile, "/home/swapfile"); 384 i=strcmp(swapfile, "/home/swapfile");
385 if ( i == 0 ) { 385 if ( i == 0 ) {
386 ramRB->setChecked(TRUE); 386 ramRB->setChecked(TRUE);
387 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 387 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
388 setStatusMessage(tr("Swapfile activated.")); 388 setStatusMessage(tr("Swapfile activated."));
389 } 389 }
390 i=strcmp(swapfile, "/usr/mnt.rom/cf/swapfile"); 390 i=strcmp(swapfile, "/usr/mnt.rom/cf/swapfile");
391 if ( i == 0 ) { 391 if ( i == 0 ) {
392 cfRB->setChecked(TRUE); 392 cfRB->setChecked(TRUE);
393 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 393 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
394 setStatusMessage(tr("Swapfile activated.")); 394 setStatusMessage(tr("Swapfile activated."));
395 } 395 }
396 i=strcmp(swapfile, "/mnt/cf/swapfile"); 396 i=strcmp(swapfile, "/mnt/cf/swapfile");
397 if ( i == 0 ) { 397 if ( i == 0 ) {
398 cfRB->setChecked(TRUE); 398 cfRB->setChecked(TRUE);
399 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 399 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
400 setStatusMessage(tr("Swapfile activated.")); 400 setStatusMessage(tr("Swapfile activated."));
401 } 401 }
402 i=strcmp(swapfile, "/usr/mnt.rom/card/swapfile"); 402 i=strcmp(swapfile, "/usr/mnt.rom/card/swapfile");
403 if ( i == 0 ) { 403 if ( i == 0 ) {
404 sdRB->setChecked(TRUE); 404 sdRB->setChecked(TRUE);
405 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 405 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
406 setStatusMessage(tr("Swapfile activated.")); 406 setStatusMessage(tr("Swapfile activated."));
407 } 407 }
408 i=strcmp(swapfile, "/mnt/card/swapfile"); 408 i=strcmp(swapfile, "/mnt/card/swapfile");
409 if ( i == 0 ) { 409 if ( i == 0 ) {
410 sdRB->setChecked(TRUE); 410 sdRB->setChecked(TRUE);
411 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */ 411 /* QMessageBox::information(this, "Information", "Swapfile is active!"); */
412 setStatusMessage(tr("Swapfile activated.")); 412 setStatusMessage(tr("Swapfile activated."));
413 } 413 }
414 414
415 Swapfile::cfsdchecked(); 415 Swapfile::cfsdchecked();
416 416
417 417
418 swapsize /=1000; 418 swapsize /=1000;
419 419
420 switch ( swapsize ) { 420 switch ( swapsize ) {
421 case 2: swapSize->setCurrentItem(0); 421 case 2: swapSize->setCurrentItem(0);
422 break; 422 break;
423 case 4: swapSize->setCurrentItem(1); 423 case 4: swapSize->setCurrentItem(1);
424 break; 424 break;
425 case 6: swapSize->setCurrentItem(2); 425 case 6: swapSize->setCurrentItem(2);
426 break; 426 break;
427 case 8: swapSize->setCurrentItem(3); 427 case 8: swapSize->setCurrentItem(3);
428 break; 428 break;
429 } 429 }
430 430
431 431
432} 432}
433 433
434 434
diff --git a/noncore/applets/notesapplet/notes.cpp b/noncore/applets/notesapplet/notes.cpp
index 1142028..9b5e475 100644
--- a/noncore/applets/notesapplet/notes.cpp
+++ b/noncore/applets/notesapplet/notes.cpp
@@ -1,514 +1,514 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002 L.J. Potter <llornkcor@handhelds.org> 2** Copyright (C) 2002 L.J. Potter <llornkcor@handhelds.org>
3 3
4** All rights reserved. 4** All rights reserved.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "notes.h" 16#include "notes.h"
17 17
18#include <qapplication.h> 18#include <qapplication.h>
19#include <stdlib.h> 19#include <stdlib.h>
20#include <qstringlist.h> 20#include <qstringlist.h>
21 21
22#include <opie2/otaskbarapplet.h> 22#include <opie2/otaskbarapplet.h>
23#include <qpe/filemanager.h> 23#include <qpe/filemanager.h>
24#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25#include <qpe/timestring.h> 25#include <qpe/timestring.h>
26#include <qpe/applnk.h> 26#include <qpe/applnk.h>
27#include <qpe/ir.h> 27#include <qpe/ir.h>
28#include <qpe/config.h> 28#include <qpe/config.h>
29 29
30// #include <qsocket.h> 30// #include <qsocket.h>
31// #include <qclipboard.h> 31// #include <qclipboard.h>
32#include <qmultilineedit.h> 32#include <qmultilineedit.h>
33#include <qlistbox.h> 33#include <qlistbox.h>
34#include <qpopupmenu.h> 34#include <qpopupmenu.h>
35#include <qmessagebox.h> 35#include <qmessagebox.h>
36 36
37#include <qdir.h> 37#include <qdir.h>
38#include <qfile.h> 38#include <qfile.h>
39#include <qpoint.h> 39#include <qpoint.h>
40#include <qpushbutton.h> 40#include <qpushbutton.h>
41#include <qpainter.h> 41#include <qpainter.h>
42#include <qlayout.h> 42#include <qlayout.h>
43#include <qframe.h> 43#include <qframe.h>
44#include <qpixmap.h> 44#include <qpixmap.h>
45#include <qstring.h> 45#include <qstring.h>
46#include <qtimer.h> 46#include <qtimer.h>
47 47
48/* XPM */ 48/* XPM */
49static char * notes_xpm[] = { 49static char * notes_xpm[] = {
50"16 16 11 1", 50"16 16 11 1",
51" c None", 51" c None",
52". c #000000", 52". c #000000",
53"+ c #7F7F7F", 53"+ c #7F7F7F",
54"@ c #BFBFBF", 54"@ c #BFBFBF",
55"# c #BFC1FF", 55"# c #BFC1FF",
56"$ c #FF0000", 56"$ c #FF0000",
57"% c #FFFFFF", 57"% c #FFFFFF",
58"& c #00037F", 58"& c #00037F",
59"* c #0006FF", 59"* c #0006FF",
60"= c #0005BF", 60"= c #0005BF",
61"- c #7F0000", 61"- c #7F0000",
62" .. ", 62" .. ",
63" .. ", 63" .. ",
64" ... ", 64" ... ",
65" .+ ", 65" .+ ",
66" .@. ", 66" .@. ",
67" . .+ ", 67" . .+ ",
68" ..#.@. ", 68" ..#.@. ",
69" ..###.+.. ", 69" ..###.+.. ",
70" ..###$...##.. ", 70" ..###$...##.. ",
71"..###$$$%+$$##&.", 71"..###$$$%+$$##&.",
72".*=####$-###&=&.", 72".*=####$-###&=&.",
73".=**=###==&=&=..", 73".=**=###==&=&=..",
74" ..=**=#&=&=.. ", 74" ..=**=#&=&=.. ",
75" ..=*=&=.. ", 75" ..=*=&=.. ",
76" ..=.. ", 76" ..=.. ",
77" . "}; 77" . "};
78 78
79 79
80NotesControl::NotesControl( QWidget *, const char * ) 80NotesControl::NotesControl( QWidget *, const char * )
81 : QVBox( 0, "NotesControl",/* WDestructiveClose | */WStyle_StaysOnTop ) 81 : QVBox( 0, "NotesControl",/* WDestructiveClose | */WStyle_StaysOnTop )
82// : QFrame( parent, name, WDestructiveClose | WStyle_StaysOnTop | WType_Popup ) 82// : QFrame( parent, name, WDestructiveClose | WStyle_StaysOnTop | WType_Popup )
83{ 83{
84 QDir d( QDir::homeDirPath()+"/notes"); 84 QDir d( QDir::homeDirPath()+"/notes");
85 if( !d.exists()) { 85 if( !d.exists()) {
86 qDebug("make dir"); 86 qDebug("make dir");
87 if(!d.mkdir( QDir::homeDirPath()+"/notes", true)) 87 if(!d.mkdir( QDir::homeDirPath()+"/notes", true))
88 qDebug("<<<<<<<<<<<<<<<<<<<<<<<<<<<make dir failed"); 88 qDebug("<<<<<<<<<<<<<<<<<<<<<<<<<<<make dir failed");
89 } 89 }
90 Config cfg("Notes"); 90 Config cfg("Notes");
91 cfg.setGroup("Options"); 91 cfg.setGroup("Options");
92 showMax = cfg.readBoolEntry("ShowMax", false); 92 showMax = cfg.readBoolEntry("ShowMax", false);
93 93
94 setFrameStyle( QFrame::PopupPanel | QFrame::Raised ); 94 setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
95 loaded=false; 95 loaded=false;
96 edited=false; 96 edited=false;
97 doPopulate=true; 97 doPopulate=true;
98 isNew=false; 98 isNew=false;
99 QVBox *vbox = new QVBox( this, "Vlayout" ); 99 QVBox *vbox = new QVBox( this, "Vlayout" );
100 QHBox *hbox = new QHBox( this, "HLayout" ); 100 QHBox *hbox = new QHBox( this, "HLayout" );
101 101
102 view = new QMultiLineEdit(vbox, "OpieNotesView"); 102 view = new QMultiLineEdit(vbox, "OpieNotesView");
103 103
104 box = new QListBox(vbox, "OpieNotesBox"); 104 box = new QListBox(vbox, "OpieNotesBox");
105 105
106 QPEApplication::setStylusOperation( box->viewport(),QPEApplication::RightOnHold); 106 QPEApplication::setStylusOperation( box->viewport(),QPEApplication::RightOnHold);
107 107
108 box->setFixedHeight(50); 108 box->setFixedHeight(50);
109 109
110 vbox->setMargin( 6 ); 110 vbox->setMargin( 6 );
111 vbox->setSpacing( 3 ); 111 vbox->setSpacing( 3 );
112 112
113 113
114 114
115 setFocusPolicy(QWidget::StrongFocus); 115 setFocusPolicy(QWidget::StrongFocus);
116 116
117 newButton= new QPushButton( hbox, "newButton" ); 117 newButton= new QPushButton( hbox, "newButton" );
118 newButton->setText(tr("New")); 118 newButton->setText(tr("New"));
119 119
120 120
121 saveButton= new QPushButton( hbox, "saveButton" ); 121 saveButton= new QPushButton( hbox, "saveButton" );
122 saveButton->setText(tr("Save")); 122 saveButton->setText(tr("Save"));
123 123
124 124
125 deleteButton= new QPushButton( hbox, "deleteButton" ); 125 deleteButton= new QPushButton( hbox, "deleteButton" );
126 deleteButton->setText(tr("Delete")); 126 deleteButton->setText(tr("Delete"));
127 127
128 128
129 129
130 connect( box, SIGNAL( mouseButtonPressed( int, QListBoxItem *, const QPoint&)), 130 connect( box, SIGNAL( mouseButtonPressed(int,QListBoxItem*,const QPoint&)),
131 this,SLOT( boxPressed(int, QListBoxItem *, const QPoint&)) ); 131 this,SLOT( boxPressed(int,QListBoxItem*,const QPoint&)) );
132 132
133 connect(box, SIGNAL(highlighted(const QString&)), this, SLOT(slotBoxSelected(const QString &))); 133 connect(box, SIGNAL(highlighted(const QString&)), this, SLOT(slotBoxSelected(const QString&)));
134 134
135 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showMenu() ) ); 135 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showMenu() ) );
136 136
137 connect(view,SIGNAL( textChanged() ), this, SLOT(slotViewEdited() ) ); 137 connect(view,SIGNAL( textChanged() ), this, SLOT(slotViewEdited() ) );
138 138
139 connect(newButton, SIGNAL(clicked()), this, SLOT(slotNewButton())); 139 connect(newButton, SIGNAL(clicked()), this, SLOT(slotNewButton()));
140 connect(saveButton, SIGNAL(clicked()), this, SLOT(slotSaveButton())); 140 connect(saveButton, SIGNAL(clicked()), this, SLOT(slotSaveButton()));
141 connect(deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteButtonClicked())); 141 connect(deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteButtonClicked()));
142 142
143 populateBox(); 143 populateBox();
144 load(); 144 load();
145 setCaption("Notes"); 145 setCaption("Notes");
146 // parent->setFocus(); 146 // parent->setFocus();
147} 147}
148 148
149void NotesControl::slotSaveButton() { 149void NotesControl::slotSaveButton() {
150 slotNewButton(); 150 slotNewButton();
151 populateBox(); 151 populateBox();
152} 152}
153 153
154void NotesControl::slotDeleteButtonClicked() { 154void NotesControl::slotDeleteButtonClicked() {
155 switch ( QMessageBox::warning(this,tr("Delete?") 155 switch ( QMessageBox::warning(this,tr("Delete?")
156 ,tr("Do you really want to<BR><B> delete</B> this note ?") 156 ,tr("Do you really want to<BR><B> delete</B> this note ?")
157 ,tr("Yes"),tr("No"),0,1,1) ) { 157 ,tr("Yes"),tr("No"),0,1,1) ) {
158 case 0: 158 case 0:
159 slotDeleteButton(); 159 slotDeleteButton();
160 break; 160 break;
161 }; 161 };
162} 162}
163 163
164void NotesControl::slotDeleteButton() { 164void NotesControl::slotDeleteButton() {
165 165
166 QString selectedText = box->currentText(); 166 QString selectedText = box->currentText();
167 qDebug("deleting "+selectedText); 167 qDebug("deleting "+selectedText);
168 168
169 if( !selectedText.isEmpty()) { 169 if( !selectedText.isEmpty()) {
170 170
171 Config cfg("Notes"); 171 Config cfg("Notes");
172 cfg.setGroup("Docs"); 172 cfg.setGroup("Docs");
173 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); 173 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
174 QString entryName, entryName2;; 174 QString entryName, entryName2;;
175 for ( int i = 0; i < noOfFiles; i++ ) { 175 for ( int i = 0; i < noOfFiles; i++ ) {
176 entryName.sprintf( "File%i", i + 1 ); 176 entryName.sprintf( "File%i", i + 1 );
177 if(selectedText == cfg.readEntry( entryName )) { 177 if(selectedText == cfg.readEntry( entryName )) {
178 qDebug("removing %s, %d", selectedText.latin1(), i); 178 qDebug("removing %s, %d", selectedText.latin1(), i);
179 for ( int j = i; j < noOfFiles; j++ ) { 179 for ( int j = i; j < noOfFiles; j++ ) {
180 entryName.sprintf( "File%i", i + 1 ); 180 entryName.sprintf( "File%i", i + 1 );
181 entryName2.sprintf( "File%i", i + 2 ); 181 entryName2.sprintf( "File%i", i + 2 );
182 QString temp = cfg.readEntry(entryName2); 182 QString temp = cfg.readEntry(entryName2);
183 qDebug("move "+temp); 183 qDebug("move "+temp);
184 cfg.writeEntry(entryName, temp); 184 cfg.writeEntry(entryName, temp);
185 i++; 185 i++;
186 } 186 }
187 cfg.writeEntry("NumberOfFiles", noOfFiles-1 ); 187 cfg.writeEntry("NumberOfFiles", noOfFiles-1 );
188 entryName.sprintf( "File%i", noOfFiles ); 188 entryName.sprintf( "File%i", noOfFiles );
189 cfg.removeEntry(entryName); 189 cfg.removeEntry(entryName);
190 cfg.write(); 190 cfg.write();
191 DocLnk nf(selectedText); 191 DocLnk nf(selectedText);
192 nf.removeFiles(); 192 nf.removeFiles();
193 QString fi=QPEApplication::documentDir()+"/text/plain/"+selectedText+".desktop"; 193 QString fi=QPEApplication::documentDir()+"/text/plain/"+selectedText+".desktop";
194 qDebug(fi); 194 qDebug(fi);
195 195
196 QFile f( fi); 196 QFile f( fi);
197 if( !f.remove()) qDebug(".desktop file not removed"); 197 if( !f.remove()) qDebug(".desktop file not removed");
198 198
199 } 199 }
200 } 200 }
201 view->clear(); 201 view->clear();
202 202
203 populateBox(); 203 populateBox();
204 } 204 }
205} 205}
206 206
207void NotesControl::slotNewButton() { 207void NotesControl::slotNewButton() {
208 if(edited) save(); 208 if(edited) save();
209 view->clear(); 209 view->clear();
210 view->setFocus(); 210 view->setFocus();
211 edited=false; 211 edited=false;
212 isNew=false; 212 isNew=false;
213} 213}
214 214
215void NotesControl::slotBeamButton() { 215void NotesControl::slotBeamButton() {
216 Ir ir; 216 Ir ir;
217 if(!ir.supported()){ 217 if(!ir.supported()){
218 } else { 218 } else {
219 this->hide(); 219 this->hide();
220 QString selectedText = box->currentText(); 220 QString selectedText = box->currentText();
221 if( !selectedText.isEmpty()) { 221 if( !selectedText.isEmpty()) {
222 QString file = QDir::homeDirPath()+"/"+selectedText; 222 QString file = QDir::homeDirPath()+"/"+selectedText;
223 QFile f(file); 223 QFile f(file);
224 Ir *irFile = new Ir(this, "IR"); 224 Ir *irFile = new Ir(this, "IR");
225 connect( irFile, SIGNAL(done(Ir*)), this, SLOT( slotBeamFinished( Ir * ))); 225 connect( irFile, SIGNAL(done(Ir*)), this, SLOT( slotBeamFinished(Ir*)));
226 irFile->send( file, "Note", "text/plain" ); 226 irFile->send( file, "Note", "text/plain" );
227 } 227 }
228 } 228 }
229} 229}
230 230
231void NotesControl::slotBeamFinished(Ir *) { 231void NotesControl::slotBeamFinished(Ir *) {
232 this->show(); 232 this->show();
233} 233}
234 234
235void NotesControl::boxPressed(int mouse, QListBoxItem *, const QPoint&) { 235void NotesControl::boxPressed(int mouse, QListBoxItem *, const QPoint&) {
236 switch (mouse) { 236 switch (mouse) {
237 case 1:{ 237 case 1:{
238 } 238 }
239 break; 239 break;
240 case 2: 240 case 2:
241 menuTimer.start( 500, TRUE ); 241 menuTimer.start( 500, TRUE );
242 break; 242 break;
243 }; 243 };
244} 244}
245 245
246void NotesControl::slotBoxSelected(const QString &itemString) { 246void NotesControl::slotBoxSelected(const QString &itemString) {
247 if(edited) { 247 if(edited) {
248 save(); 248 save();
249 } 249 }
250 loaded=false; 250 loaded=false;
251 edited=false; 251 edited=false;
252 load(itemString); 252 load(itemString);
253} 253}
254 254
255 255
256void NotesControl::showMenu() { 256void NotesControl::showMenu() {
257 QPopupMenu *m = new QPopupMenu(0); 257 QPopupMenu *m = new QPopupMenu(0);
258 m->insertItem( tr( "Beam Out" ), this, SLOT( slotBeamButton() )); 258 m->insertItem( tr( "Beam Out" ), this, SLOT( slotBeamButton() ));
259 m->insertItem( tr( "Search For..." ), this, SLOT( slotSearch() )); 259 m->insertItem( tr( "Search For..." ), this, SLOT( slotSearch() ));
260 m->insertItem( tr( "Toggle Maximized" ), this, SLOT( slotShowMax() )); 260 m->insertItem( tr( "Toggle Maximized" ), this, SLOT( slotShowMax() ));
261 m->insertSeparator(); 261 m->insertSeparator();
262 m->insertItem( tr( "Delete" ), this, SLOT( slotDeleteButton() )); 262 m->insertItem( tr( "Delete" ), this, SLOT( slotDeleteButton() ));
263 m->setFocus(); 263 m->setFocus();
264 m->exec( QCursor::pos() ); 264 m->exec( QCursor::pos() );
265 265
266 if(m) delete m; 266 if(m) delete m;
267} 267}
268 268
269void NotesControl::focusOutEvent ( QFocusEvent * e) { 269void NotesControl::focusOutEvent ( QFocusEvent * e) {
270 if( e->reason() == QFocusEvent::Popup) 270 if( e->reason() == QFocusEvent::Popup)
271 save(); 271 save();
272 else { 272 else {
273 if(!loaded) { 273 if(!loaded) {
274 populateBox(); 274 populateBox();
275 load(); 275 load();
276 } 276 }
277 } 277 }
278 QWidget::focusOutEvent(e); 278 QWidget::focusOutEvent(e);
279} 279}
280 280
281void NotesControl::save() { 281void NotesControl::save() {
282 Config cfg("Notes"); 282 Config cfg("Notes");
283 cfg.setGroup("Docs"); 283 cfg.setGroup("Docs");
284 if( edited) { 284 if( edited) {
285// qDebug("is edited"); 285// qDebug("is edited");
286 QString rt = view->text(); 286 QString rt = view->text();
287 if( rt.length()>1) { 287 if( rt.length()>1) {
288 QString pt = rt.simplifyWhiteSpace(); 288 QString pt = rt.simplifyWhiteSpace();
289 int i = pt.find( ' ', pt.find( ' ' )+2 ); 289 int i = pt.find( ' ', pt.find( ' ' )+2 );
290 QString docname = pt; 290 QString docname = pt;
291 if ( i > 0 ) 291 if ( i > 0 )
292 docname = pt.left(i); 292 docname = pt.left(i);
293 // remove "." at the beginning 293 // remove "." at the beginning
294 while( docname.startsWith( "." ) ) 294 while( docname.startsWith( "." ) )
295 docname = docname.mid( 1 ); 295 docname = docname.mid( 1 );
296 docname.replace( QRegExp("/"), "_" ); 296 docname.replace( QRegExp("/"), "_" );
297 // cut the length. filenames longer than that don't make sense 297 // cut the length. filenames longer than that don't make sense
298 // and something goes wrong when they get too long. 298 // and something goes wrong when they get too long.
299 if ( docname.length() > 40 ) 299 if ( docname.length() > 40 )
300 docname = docname.left(40); 300 docname = docname.left(40);
301 if ( docname.isEmpty() ) 301 if ( docname.isEmpty() )
302 docname = "Empty Text"; 302 docname = "Empty Text";
303// qDebug(docname); 303// qDebug(docname);
304 304
305 if( oldDocName != docname) { 305 if( oldDocName != docname) {
306 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); 306 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
307 QString entryName; 307 QString entryName;
308 entryName.sprintf( "File%i", noOfFiles + 1 ); 308 entryName.sprintf( "File%i", noOfFiles + 1 );
309 cfg.writeEntry( entryName,docname ); 309 cfg.writeEntry( entryName,docname );
310 cfg.writeEntry("NumberOfFiles", noOfFiles+1 ); 310 cfg.writeEntry("NumberOfFiles", noOfFiles+1 );
311 cfg.write(); 311 cfg.write();
312 } 312 }
313// else 313// else
314// qDebug("oldname equals docname"); 314// qDebug("oldname equals docname");
315 315
316 doc = new DocLnk(docname); 316 doc = new DocLnk(docname);
317 if(QFile(doc->linkFile()).exists()) 317 if(QFile(doc->linkFile()).exists())
318 qDebug("puppie"); 318 qDebug("puppie");
319 doc->setType("text/plain"); 319 doc->setType("text/plain");
320 doc->setName(docname); 320 doc->setName(docname);
321 QString temp = docname.replace( QRegExp(" "), "_" ); 321 QString temp = docname.replace( QRegExp(" "), "_" );
322 doc->setFile( QDir::homeDirPath()+"/notes/"+temp); 322 doc->setFile( QDir::homeDirPath()+"/notes/"+temp);
323 FileManager fm; 323 FileManager fm;
324 if ( !fm.saveFile( *doc, rt ) ) { 324 if ( !fm.saveFile( *doc, rt ) ) {
325 } 325 }
326 326
327 oldDocName=docname; 327 oldDocName=docname;
328 edited=false; 328 edited=false;
329// qDebug("save"); 329// qDebug("save");
330 if (doPopulate) 330 if (doPopulate)
331 populateBox(); 331 populateBox();
332 } 332 }
333 cfg.writeEntry( "LastDoc",oldDocName ); 333 cfg.writeEntry( "LastDoc",oldDocName );
334 cfg.write(); 334 cfg.write();
335 335
336 } 336 }
337} 337}
338 338
339void NotesControl::populateBox() { 339void NotesControl::populateBox() {
340 box->clear(); 340 box->clear();
341// qDebug("populate"); 341// qDebug("populate");
342 Config cfg("Notes"); 342 Config cfg("Notes");
343 cfg.setGroup("Docs"); 343 cfg.setGroup("Docs");
344 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); 344 int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 );
345 QStringList list; 345 QStringList list;
346 QString entryName; 346 QString entryName;
347 for ( int i = 0; i < noOfFiles; i++ ) { 347 for ( int i = 0; i < noOfFiles; i++ ) {
348 entryName.sprintf( "File%i", i + 1 ); 348 entryName.sprintf( "File%i", i + 1 );
349 list.append(cfg.readEntry( entryName )); 349 list.append(cfg.readEntry( entryName ));
350 } 350 }
351 list.sort(); 351 list.sort();
352 box->insertStringList(list,-1); 352 box->insertStringList(list,-1);
353 doPopulate=false; 353 doPopulate=false;
354 update(); 354 update();
355} 355}
356 356
357void NotesControl::load() { 357void NotesControl::load() {
358 358
359 if(!loaded) { 359 if(!loaded) {
360 Config cfg("Notes"); 360 Config cfg("Notes");
361 cfg.setGroup("Docs"); 361 cfg.setGroup("Docs");
362 QString lastDoc=cfg.readEntry( "LastDoc","notes"); 362 QString lastDoc=cfg.readEntry( "LastDoc","notes");
363 DocLnk nf; 363 DocLnk nf;
364 nf.setType("text/plain"); 364 nf.setType("text/plain");
365 nf.setFile(lastDoc); 365 nf.setFile(lastDoc);
366 366
367 loadDoc(nf); 367 loadDoc(nf);
368 loaded=true; 368 loaded=true;
369 oldDocName=lastDoc; 369 oldDocName=lastDoc;
370 cfg.writeEntry( "LastDoc",oldDocName ); 370 cfg.writeEntry( "LastDoc",oldDocName );
371 cfg.write(); 371 cfg.write();
372 } 372 }
373} 373}
374 374
375void NotesControl::load(const QString & file) { 375void NotesControl::load(const QString & file) {
376 qDebug("loading "+file); 376 qDebug("loading "+file);
377 QString name = file; 377 QString name = file;
378 QString temp; 378 QString temp;
379 if( !QFile( QDir::homeDirPath()+"/"+file).exists() ) 379 if( !QFile( QDir::homeDirPath()+"/"+file).exists() )
380 temp = QDir::homeDirPath()+"/notes/"+ name.replace( QRegExp(" "), "_" ); 380 temp = QDir::homeDirPath()+"/notes/"+ name.replace( QRegExp(" "), "_" );
381 else 381 else
382 temp = name; 382 temp = name;
383 if(!loaded) { 383 if(!loaded) {
384 DocLnk nf; 384 DocLnk nf;
385 nf.setType("text/plain"); 385 nf.setType("text/plain");
386 nf.setFile( temp); 386 nf.setFile( temp);
387 if(!temp.isEmpty()) 387 if(!temp.isEmpty())
388 loadDoc(nf); 388 loadDoc(nf);
389 loaded=true; 389 loaded=true;
390 } 390 }
391// view->setFocus(); 391// view->setFocus();
392 oldDocName=file; 392 oldDocName=file;
393 Config cfg("Notes"); 393 Config cfg("Notes");
394 cfg.setGroup("Docs"); 394 cfg.setGroup("Docs");
395 cfg.writeEntry( "LastDoc",oldDocName ); 395 cfg.writeEntry( "LastDoc",oldDocName );
396 cfg.write(); 396 cfg.write();
397} 397}
398 398
399void NotesControl::loadDoc( const DocLnk &f) { 399void NotesControl::loadDoc( const DocLnk &f) {
400 FileManager fm; 400 FileManager fm;
401 QString txt; 401 QString txt;
402 if ( !fm.loadFile( f, txt ) ) { 402 if ( !fm.loadFile( f, txt ) ) {
403 qDebug("could not load file "+f.file()); 403 qDebug("could not load file "+f.file());
404 return; 404 return;
405 } 405 }
406 view->setText(txt); 406 view->setText(txt);
407} 407}
408 408
409void NotesControl::slotViewEdited() { 409void NotesControl::slotViewEdited() {
410 if(loaded) { 410 if(loaded) {
411 edited=true; 411 edited=true;
412 } 412 }
413} 413}
414 414
415 415
416void NotesControl::slotShowMax() { 416void NotesControl::slotShowMax() {
417 Config cfg("Notes"); 417 Config cfg("Notes");
418 cfg.setGroup("Options"); 418 cfg.setGroup("Options");
419 showMax=!showMax; 419 showMax=!showMax;
420 cfg.writeEntry("ShowMax", showMax); 420 cfg.writeEntry("ShowMax", showMax);
421 cfg.write(); 421 cfg.write();
422 hide(); 422 hide();
423} 423}
424 424
425void NotesControl::slotSearch() { 425void NotesControl::slotSearch() {
426 int boxCount = box->count(); 426 int boxCount = box->count();
427 for(int i=0;i< boxCount;i++) { 427 for(int i=0;i< boxCount;i++) {
428 428
429 } 429 }
430} 430}
431 431
432// void NotesControl::keyReleaseEvent( QKeyEvent *e) { 432// void NotesControl::keyReleaseEvent( QKeyEvent *e) {
433 433
434// switch ( e->state() ) { 434// switch ( e->state() ) {
435// case ControlButton: 435// case ControlButton:
436// if(e->key() == Key_C) { //copy 436// if(e->key() == Key_C) { //copy
437// qDebug("copy"); 437// qDebug("copy");
438// QClipboard *cb = QApplication::clipboard(); 438// QClipboard *cb = QApplication::clipboard();
439// QString text; 439// QString text;
440 440
441// // Copy text from the clipboard (paste) 441// // Copy text from the clipboard (paste)
442// text = cb->text(); 442// text = cb->text();
443// } 443// }
444// if(e->key() == Key_X) { //cut 444// if(e->key() == Key_X) { //cut
445// } 445// }
446// if(e->key() == Key_V) { //paste 446// if(e->key() == Key_V) { //paste
447// QClipboard *cb = QApplication::clipboard(); 447// QClipboard *cb = QApplication::clipboard();
448// QString text; 448// QString text;
449// //view 449// //view
450// cb->setText(); 450// cb->setText();
451// } 451// }
452// break; 452// break;
453// }; 453// };
454// QWidget::keyReleaseEvent(e); 454// QWidget::keyReleaseEvent(e);
455// } 455// }
456 456
457//=========================================================================== 457//===========================================================================
458 458
459NotesApplet::NotesApplet( QWidget *parent, const char *name ) 459NotesApplet::NotesApplet( QWidget *parent, const char *name )
460 : QWidget( parent, name ) { 460 : QWidget( parent, name ) {
461 setFixedHeight( 18 ); 461 setFixedHeight( 18 );
462 setFixedWidth( 14 ); 462 setFixedWidth( 14 );
463 vc = new NotesControl; 463 vc = new NotesControl;
464} 464}
465 465
466NotesApplet::~NotesApplet() { 466NotesApplet::~NotesApplet() {
467 delete vc; 467 delete vc;
468} 468}
469 469
470int NotesApplet::position() 470int NotesApplet::position()
471{ 471{
472 return 6; 472 return 6;
473} 473}
474 474
475void NotesApplet::mousePressEvent( QMouseEvent *) { 475void NotesApplet::mousePressEvent( QMouseEvent *) {
476 if( !vc->isHidden()) { 476 if( !vc->isHidden()) {
477 vc->doPopulate=false; 477 vc->doPopulate=false;
478 vc->save(); 478 vc->save();
479 vc->close(); 479 vc->close();
480 } else { 480 } else {
481// vc = new NotesControl; 481// vc = new NotesControl;
482// QPoint curPos = mapToGlobal( rect().topLeft() ); 482// QPoint curPos = mapToGlobal( rect().topLeft() );
483 if(vc->showMax) { 483 if(vc->showMax) {
484 qDebug("show max"); 484 qDebug("show max");
485 vc->showMaximized(); 485 vc->showMaximized();
486 } else { 486 } else {
487 qDebug("no show max"); 487 qDebug("no show max");
488 QWidget *wid = QPEApplication::desktop(); 488 QWidget *wid = QPEApplication::desktop();
489 QRect rect = QApplication::desktop()->geometry(); 489 QRect rect = QApplication::desktop()->geometry();
490 vc->setGeometry( ( wid->width() / 2) - ( vc->width() / 2 ) , 28 , wid->width() -10 , 180); 490 vc->setGeometry( ( wid->width() / 2) - ( vc->width() / 2 ) , 28 , wid->width() -10 , 180);
491 vc->move ( (rect.center()/2) - (vc->rect().center()/2)); 491 vc->move ( (rect.center()/2) - (vc->rect().center()/2));
492// vc->move( (( wid->width() / 2) - ( vc->width() / 2 ))-4, 28); 492// vc->move( (( wid->width() / 2) - ( vc->width() / 2 ))-4, 28);
493 } 493 }
494 vc->show(); 494 vc->show();
495 vc->doPopulate=true; 495 vc->doPopulate=true;
496 vc->populateBox(); 496 vc->populateBox();
497 vc->doPopulate=false; 497 vc->doPopulate=false;
498 vc->loaded=false; 498 vc->loaded=false;
499 499
500 vc->load(); 500 vc->load();
501// this->setFocus(); 501// this->setFocus();
502 vc->view->setFocus(); 502 vc->view->setFocus();
503 } 503 }
504} 504}
505 505
506void NotesApplet::paintEvent( QPaintEvent* ) { 506void NotesApplet::paintEvent( QPaintEvent* ) {
507 QPainter p(this); 507 QPainter p(this);
508 p.drawPixmap( 0, 1, ( const char** ) notes_xpm ); 508 p.drawPixmap( 0, 1, ( const char** ) notes_xpm );
509} 509}
510 510
511Q_EXPORT_INTERFACE() 511Q_EXPORT_INTERFACE()
512{ 512{
513 Q_CREATE_INSTANCE( OTaskbarAppletWrapper<NotesApplet> ); 513 Q_CREATE_INSTANCE( OTaskbarAppletWrapper<NotesApplet> );
514} 514}
diff --git a/noncore/applets/wirelessapplet/wireless.cpp b/noncore/applets/wirelessapplet/wireless.cpp
index 9ce6618..6ef2e44 100644
--- a/noncore/applets/wirelessapplet/wireless.cpp
+++ b/noncore/applets/wirelessapplet/wireless.cpp
@@ -1,558 +1,558 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer <mickey@vanille.de> 2** Copyright (C) 2002-2004 Michael 'Mickey' Lauer <mickey@vanille.de>
3** 3**
4** This file may be distributed and/or modified under the terms of the 4** This file may be distributed and/or modified under the terms of the
5** GNU General Public License version 2 as published by the Free Software 5** GNU General Public License version 2 as published by the Free Software
6** Foundation and appearing in the file LICENSE.GPL included in the 6** Foundation and appearing in the file LICENSE.GPL included in the
7** packaging of this file. 7** packaging of this file.
8** 8**
9** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 9** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
10** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 10** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
11** 11**
12**********************************************************************/ 12**********************************************************************/
13 13
14#include "wireless.h" 14#include "wireless.h"
15#include "mgraph.h" 15#include "mgraph.h"
16#include "advancedconfig.h" 16#include "advancedconfig.h"
17#include "connect0.xpm" 17#include "connect0.xpm"
18#include "connect1.xpm" 18#include "connect1.xpm"
19#include "connect2.xpm" 19#include "connect2.xpm"
20#include "connect3.xpm" 20#include "connect3.xpm"
21#include "connect4.xpm" 21#include "connect4.xpm"
22#include "connect5.xpm" 22#include "connect5.xpm"
23#include "nowireless.xpm" 23#include "nowireless.xpm"
24 24
25/* OPIE */ 25/* OPIE */
26#include <opie2/onetwork.h> 26#include <opie2/onetwork.h>
27#include <opie2/otaskbarapplet.h> 27#include <opie2/otaskbarapplet.h>
28#include <qpe/config.h> 28#include <qpe/config.h>
29 29
30/* QT */ 30/* QT */
31#include <qradiobutton.h> 31#include <qradiobutton.h>
32#include <qpushbutton.h> 32#include <qpushbutton.h>
33#include <qpainter.h> 33#include <qpainter.h>
34#include <qlabel.h> 34#include <qlabel.h>
35#include <qslider.h> 35#include <qslider.h>
36#include <qbuttongroup.h> 36#include <qbuttongroup.h>
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qfile.h> 38#include <qfile.h>
39#include <qtextstream.h> 39#include <qtextstream.h>
40 40
41/* STD */ 41/* STD */
42#include <sys/types.h> 42#include <sys/types.h>
43#include <signal.h> 43#include <signal.h>
44 44
45#define STYLE_BARS 0 45#define STYLE_BARS 0
46#define STYLE_ANTENNA 1 46#define STYLE_ANTENNA 1
47 47
48//#define MDEBUG 48//#define MDEBUG
49#undef MDEBUG 49#undef MDEBUG
50 50
51WirelessControl::WirelessControl( WirelessApplet *applet, QWidget *parent, const char *name ) 51WirelessControl::WirelessControl( WirelessApplet *applet, QWidget *parent, const char *name )
52 : QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), applet( applet ) 52 : QFrame( parent, name, WStyle_StaysOnTop | WType_Popup ), applet( applet )
53{ 53{
54 54
55 readConfig(); 55 readConfig();
56 writeConfigEntry( "UpdateFrequency", updateFrequency ); 56 writeConfigEntry( "UpdateFrequency", updateFrequency );
57 writeConfigEntry( "DisplayStyle", displayStyle ); 57 writeConfigEntry( "DisplayStyle", displayStyle );
58 58
59 setFrameStyle( QFrame::PopupPanel | QFrame::Raised ); 59 setFrameStyle( QFrame::PopupPanel | QFrame::Raised );
60 QGridLayout *grid = new QGridLayout( this, 3, 2, 6, 2, "top layout" ); 60 QGridLayout *grid = new QGridLayout( this, 3, 2, 6, 2, "top layout" );
61 61
62 /* status label */ 62 /* status label */
63 63
64 statusLabel = new QLabel( this, "statuslabel" ); 64 statusLabel = new QLabel( this, "statuslabel" );
65 QString text( "Wireless Status:<br>" 65 QString text( "Wireless Status:<br>"
66 "*** Unknown ***<br>" 66 "*** Unknown ***<br>"
67 "Card not inserted ?<br>" 67 "Card not inserted ?<br>"
68 "Or Sharp ROM ?<br>" 68 "Or Sharp ROM ?<br>"
69 "CELL: 00:00:00:00:00:00" ); 69 "CELL: 00:00:00:00:00:00" );
70 /* QString text( "Station: Unknown<br>" 70 /* QString text( "Station: Unknown<br>"
71 "ESSID: Unknown<br>" 71 "ESSID: Unknown<br>"
72 "MODE: Unknown<br>" 72 "MODE: Unknown<br>"
73 "FREQ: Unknown<br>" 73 "FREQ: Unknown<br>"
74 "CELL: AA:BB:CC:DD:EE:FF" ); */ 74 "CELL: AA:BB:CC:DD:EE:FF" ); */
75 statusLabel->setText( text ); 75 statusLabel->setText( text );
76 statusLabel->setFixedSize( statusLabel->sizeHint() ); 76 statusLabel->setFixedSize( statusLabel->sizeHint() );
77 grid->addWidget( statusLabel, 0, 0 ); 77 grid->addWidget( statusLabel, 0, 0 );
78 78
79 /* visualization group box */ 79 /* visualization group box */
80 80
81 QButtonGroup* group = new QButtonGroup( 1, Qt::Horizontal, "Visualization", this ); 81 QButtonGroup* group = new QButtonGroup( 1, Qt::Horizontal, "Visualization", this );
82 QRadioButton* r1 = new QRadioButton( "Color Bars", group ); 82 QRadioButton* r1 = new QRadioButton( "Color Bars", group );
83 QRadioButton* r2 = new QRadioButton( "Antenna", group ); 83 QRadioButton* r2 = new QRadioButton( "Antenna", group );
84 r1->setFocusPolicy( QWidget::NoFocus ); 84 r1->setFocusPolicy( QWidget::NoFocus );
85 r2->setFocusPolicy( QWidget::NoFocus ); 85 r2->setFocusPolicy( QWidget::NoFocus );
86 group->setFocusPolicy( QWidget::NoFocus ); 86 group->setFocusPolicy( QWidget::NoFocus );
87 group->setButton( displayStyle ); 87 group->setButton( displayStyle );
88 grid->addWidget( group, 0, 1 ); 88 grid->addWidget( group, 0, 1 );
89 89
90 /* quality graph */ 90 /* quality graph */
91 91
92 mgraph = new MGraph( this ); 92 mgraph = new MGraph( this );
93 mgraph->setFrameStyle( QFrame::Panel | QFrame::Sunken ); 93 mgraph->setFrameStyle( QFrame::Panel | QFrame::Sunken );
94 mgraph->setMin( 0 ); 94 mgraph->setMin( 0 );
95 mgraph->setMax( 92 ); 95 mgraph->setMax( 92 );
96 grid->addWidget( mgraph, 1, 0 ); 96 grid->addWidget( mgraph, 1, 0 );
97 mgraph->setFocusPolicy( QWidget::NoFocus ); 97 mgraph->setFocusPolicy( QWidget::NoFocus );
98 98
99 /* advanced configuration Button */ 99 /* advanced configuration Button */
100 100
101 QPushButton* advanced = new QPushButton( "Advanced...", this ); 101 QPushButton* advanced = new QPushButton( "Advanced...", this );
102 advanced->setFocusPolicy( QWidget::NoFocus ); 102 advanced->setFocusPolicy( QWidget::NoFocus );
103 grid->addWidget( advanced, 2, 0, Qt::AlignCenter ); 103 grid->addWidget( advanced, 2, 0, Qt::AlignCenter );
104 connect( advanced, SIGNAL( clicked() ), 104 connect( advanced, SIGNAL( clicked() ),
105 this, SLOT( advancedConfigClicked() ) ); 105 this, SLOT( advancedConfigClicked() ) );
106 106
107 /* update Frequency Label */ 107 /* update Frequency Label */
108 108
109 updateLabel = new QLabel( this ); 109 updateLabel = new QLabel( this );
110 text.sprintf( "Update every %d s", updateFrequency ); 110 text.sprintf( "Update every %d s", updateFrequency );
111 updateLabel->setText( text ); 111 updateLabel->setText( text );
112 grid->addWidget( updateLabel, 2, 1 ); 112 grid->addWidget( updateLabel, 2, 1 );
113 113
114 /* update Frequency Slider */ 114 /* update Frequency Slider */
115 115
116 QSlider* updateSlider = new QSlider( QSlider::Horizontal, this ); 116 QSlider* updateSlider = new QSlider( QSlider::Horizontal, this );
117 updateSlider->setRange( 0, 9 ); 117 updateSlider->setRange( 0, 9 );
118 updateSlider->setValue( updateFrequency ); 118 updateSlider->setValue( updateFrequency );
119 updateSlider->setTickmarks( QSlider::Both ); 119 updateSlider->setTickmarks( QSlider::Both );
120 updateSlider->setTickInterval( 1 ); 120 updateSlider->setTickInterval( 1 );
121 updateSlider->setSteps( 1, 1 ); 121 updateSlider->setSteps( 1, 1 );
122 updateSlider->setFocusPolicy( QWidget::NoFocus ); 122 updateSlider->setFocusPolicy( QWidget::NoFocus );
123 grid->addWidget( updateSlider, 1, 1 ); 123 grid->addWidget( updateSlider, 1, 1 );
124 connect( updateSlider, SIGNAL( valueChanged( int ) ), 124 connect( updateSlider, SIGNAL( valueChanged(int) ),
125 this, SLOT( updateDelayChange( int ) ) ); 125 this, SLOT( updateDelayChange(int) ) );
126 126
127 setFixedSize( sizeHint() ); 127 setFixedSize( sizeHint() );
128 setFocusPolicy( QWidget::NoFocus ); 128 setFocusPolicy( QWidget::NoFocus );
129 129
130 applet->displayStyleChange( displayStyle ); 130 applet->displayStyleChange( displayStyle );
131 applet->updateDelayChange( updateFrequency ); 131 applet->updateDelayChange( updateFrequency );
132 132
133 connect( group, SIGNAL( clicked( int ) ), 133 connect( group, SIGNAL( clicked(int) ),
134 this, SLOT( displayStyleChange( int ) ) ); 134 this, SLOT( displayStyleChange(int) ) );
135 135
136 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE ); 136 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE );
137} 137}
138 138
139void WirelessControl::advancedConfigClicked() 139void WirelessControl::advancedConfigClicked()
140{ 140{
141 AdvancedConfig * a = new AdvancedConfig( this, "dialog", TRUE ); 141 AdvancedConfig * a = new AdvancedConfig( this, "dialog", TRUE );
142 int result = a->exec(); 142 int result = a->exec();
143 a->hide(); 143 a->hide();
144 delete a; 144 delete a;
145 if ( result == QDialog::Accepted ) 145 if ( result == QDialog::Accepted )
146 { 146 {
147 readConfig(); 147 readConfig();
148 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE ); 148 applet->updateDHCPConfig( rocESSID, rocFREQ, rocAP, rocMODE );
149 } 149 }
150} 150}
151 151
152void WirelessControl::updateDelayChange( int delay ) 152void WirelessControl::updateDelayChange( int delay )
153{ 153{
154 QString text; 154 QString text;
155 text.sprintf( "Update every %d s", delay ); 155 text.sprintf( "Update every %d s", delay );
156 updateLabel->setText( text ); 156 updateLabel->setText( text );
157 applet->updateDelayChange( delay ); 157 applet->updateDelayChange( delay );
158 writeConfigEntry( "UpdateFrequency", delay ); 158 writeConfigEntry( "UpdateFrequency", delay );
159} 159}
160 160
161void WirelessControl::displayStyleChange( int style ) 161void WirelessControl::displayStyleChange( int style )
162{ 162{
163 applet->displayStyleChange( style ); 163 applet->displayStyleChange( style );
164 writeConfigEntry( "DisplayStyle", style ); 164 writeConfigEntry( "DisplayStyle", style );
165} 165}
166 166
167void WirelessControl::show ( bool ) 167void WirelessControl::show ( bool )
168{ 168{
169 QPoint curPos = applet->mapToGlobal( QPoint ( 0, 0 ) ); 169 QPoint curPos = applet->mapToGlobal( QPoint ( 0, 0 ) );
170 170
171 int w = sizeHint().width(); 171 int w = sizeHint().width();
172 int x = curPos.x() - ( w / 2 ); 172 int x = curPos.x() - ( w / 2 );
173 173
174 if ( ( x + w ) > QPEApplication::desktop() ->width() ) 174 if ( ( x + w ) > QPEApplication::desktop() ->width() )
175 x = QPEApplication::desktop ( ) -> width ( ) - w; 175 x = QPEApplication::desktop ( ) -> width ( ) - w;
176 176
177 move( x, curPos.y () - sizeHint().height () ); 177 move( x, curPos.y () - sizeHint().height () );
178 QFrame::show(); 178 QFrame::show();
179} 179}
180 180
181void WirelessControl::readConfig() 181void WirelessControl::readConfig()
182{ 182{
183 Config cfg( "qpe" ); 183 Config cfg( "qpe" );
184 cfg.setGroup( "Wireless" ); 184 cfg.setGroup( "Wireless" );
185 185
186 updateFrequency = cfg.readNumEntry( "UpdateFrequency", 2 ); 186 updateFrequency = cfg.readNumEntry( "UpdateFrequency", 2 );
187 displayStyle = cfg.readNumEntry( "DisplayStyle", STYLE_ANTENNA ); 187 displayStyle = cfg.readNumEntry( "DisplayStyle", STYLE_ANTENNA );
188 rocESSID = cfg.readBoolEntry( "renew_dhcp_on_essid_change", false ); 188 rocESSID = cfg.readBoolEntry( "renew_dhcp_on_essid_change", false );
189 rocFREQ = cfg.readBoolEntry( "renew_dhcp_on_freq_change", false ); 189 rocFREQ = cfg.readBoolEntry( "renew_dhcp_on_freq_change", false );
190 rocAP = cfg.readBoolEntry( "renew_dhcp_on_ap_change", false ); 190 rocAP = cfg.readBoolEntry( "renew_dhcp_on_ap_change", false );
191 rocMODE = cfg.readBoolEntry( "renew_dhcp_on_mode_change", false ); 191 rocMODE = cfg.readBoolEntry( "renew_dhcp_on_mode_change", false );
192} 192}
193 193
194void WirelessControl::writeConfigEntry( const char *entry, int val ) 194void WirelessControl::writeConfigEntry( const char *entry, int val )
195{ 195{
196 Config cfg( "qpe" ); 196 Config cfg( "qpe" );
197 cfg.setGroup( "Wireless" ); 197 cfg.setGroup( "Wireless" );
198 cfg.writeEntry( entry, val ); 198 cfg.writeEntry( entry, val );
199} 199}
200 200
201//=========================================================================== 201//===========================================================================
202 202
203WirelessApplet::WirelessApplet( QWidget *parent, const char *name ) 203WirelessApplet::WirelessApplet( QWidget *parent, const char *name )
204 : QWidget( parent, name ), visualStyle( STYLE_ANTENNA ), 204 : QWidget( parent, name ), visualStyle( STYLE_ANTENNA ),
205 timer( 0 ), interface( 0 ), oldiface( 0 ), 205 timer( 0 ), interface( 0 ), oldiface( 0 ),
206 rocESSID( false ), rocFREQ( false ), rocAP( false ), rocMODE( false ) 206 rocESSID( false ), rocFREQ( false ), rocAP( false ), rocMODE( false )
207{ 207{
208 setFixedHeight( 18 ); 208 setFixedHeight( 18 );
209 setFixedWidth( 14 ); 209 setFixedWidth( 14 );
210 status = new WirelessControl( this, this, "wireless status" ); 210 status = new WirelessControl( this, this, "wireless status" );
211} 211}
212 212
213void WirelessApplet::checkInterface() 213void WirelessApplet::checkInterface()
214{ 214{
215 interface = 0L; 215 interface = 0L;
216 ONetwork* net = ONetwork::instance(); 216 ONetwork* net = ONetwork::instance();
217 net->synchronize(); 217 net->synchronize();
218 ONetwork::InterfaceIterator it = net->iterator(); 218 ONetwork::InterfaceIterator it = net->iterator();
219 219
220 while ( it.current() && !it.current()->isWireless() ) ++it; 220 while ( it.current() && !it.current()->isWireless() ) ++it;
221 221
222 if ( it.current() && it.current()->isWireless() ) 222 if ( it.current() && it.current()->isWireless() )
223 interface = static_cast<OWirelessNetworkInterface*>( it.current() ); 223 interface = static_cast<OWirelessNetworkInterface*>( it.current() );
224 224
225 if ( interface ) 225 if ( interface )
226 { 226 {
227#ifdef MDEBUG 227#ifdef MDEBUG
228 qDebug( "WIFIAPPLET: using interface '%s'", ( const char* ) interface->name() ); 228 qDebug( "WIFIAPPLET: using interface '%s'", ( const char* ) interface->name() );
229#endif 229#endif
230 230
231 } 231 }
232 else 232 else
233 { 233 {
234#ifdef MDEBUG 234#ifdef MDEBUG
235 qDebug( "WIFIAPPLET: D'oh! No Wireless interface present... :(" ); 235 qDebug( "WIFIAPPLET: D'oh! No Wireless interface present... :(" );
236#endif 236#endif
237 hide(); 237 hide();
238 } 238 }
239} 239}
240 240
241void WirelessApplet::renewDHCP() 241void WirelessApplet::renewDHCP()
242{ 242{
243#ifdef MDEBUG 243#ifdef MDEBUG
244 qDebug( "WIFIAPPLET: Going to request a DHCP configuration renew." ); 244 qDebug( "WIFIAPPLET: Going to request a DHCP configuration renew." );
245#endif 245#endif
246 246
247 QString pidfile; 247 QString pidfile;
248 if ( !interface ) 248 if ( !interface )
249 return ; 249 return ;
250 QString ifacename( interface->name() ); 250 QString ifacename( interface->name() );
251 251
252 // At first we are trying dhcpcd 252 // At first we are trying dhcpcd
253 253
254 pidfile.sprintf( "/var/run/dhcpcd-%s.pid", ( const char* ) ifacename ); 254 pidfile.sprintf( "/var/run/dhcpcd-%s.pid", ( const char* ) ifacename );
255#ifdef MDEBUG 255#ifdef MDEBUG
256 qDebug( "WIFIAPPLET: dhcpcd pidfile is '%s'", ( const char* ) pidfile ); 256 qDebug( "WIFIAPPLET: dhcpcd pidfile is '%s'", ( const char* ) pidfile );
257#endif 257#endif
258 int pid; 258 int pid;
259 QFile pfile( pidfile ); 259 QFile pfile( pidfile );
260 bool hasFile = pfile.open( IO_ReadOnly ); 260 bool hasFile = pfile.open( IO_ReadOnly );
261 QTextStream s( &pfile ); 261 QTextStream s( &pfile );
262 if ( hasFile ) 262 if ( hasFile )
263 { 263 {
264 s >> pid; 264 s >> pid;
265#ifdef MDEBUG 265#ifdef MDEBUG
266 qDebug( "WIFIAPPLET: sent SIGALARM to pid %d", pid ); 266 qDebug( "WIFIAPPLET: sent SIGALARM to pid %d", pid );
267#endif 267#endif
268 kill( pid, SIGALRM ); 268 kill( pid, SIGALRM );
269 return ; 269 return ;
270 } 270 }
271 271
272 // No dhcpcd, so we are trying udhcpc 272 // No dhcpcd, so we are trying udhcpc
273#ifdef MDEBUG 273#ifdef MDEBUG
274 qDebug( "WIFIAPPLET: dhcpcd not available." ); 274 qDebug( "WIFIAPPLET: dhcpcd not available." );
275#endif 275#endif
276 pidfile.sprintf( "/var/run/udhcpc.%s.pid", ( const char* ) ifacename ); 276 pidfile.sprintf( "/var/run/udhcpc.%s.pid", ( const char* ) ifacename );
277#ifdef MDEBUG 277#ifdef MDEBUG
278 qDebug( "WIFIAPPLET: udhcpc pidfile is '%s'", ( const char* ) pidfile ); 278 qDebug( "WIFIAPPLET: udhcpc pidfile is '%s'", ( const char* ) pidfile );
279#endif 279#endif
280 QFile pfile2( pidfile ); 280 QFile pfile2( pidfile );
281 hasFile = pfile2.open( IO_ReadOnly ); 281 hasFile = pfile2.open( IO_ReadOnly );
282 QTextStream s2( &pfile2 ); 282 QTextStream s2( &pfile2 );
283 if ( hasFile ) 283 if ( hasFile )
284 { 284 {
285 s2 >> pid; 285 s2 >> pid;
286#ifdef MDEBUG 286#ifdef MDEBUG
287 qDebug( "WIFIAPPLET: sent SIGUSR1 to pid %d", pid ); 287 qDebug( "WIFIAPPLET: sent SIGUSR1 to pid %d", pid );
288#endif 288#endif
289 kill( pid, SIGUSR1 ); 289 kill( pid, SIGUSR1 );
290 return ; 290 return ;
291 } 291 }
292} 292}
293 293
294void WirelessApplet::updateDHCPConfig( bool ESSID, bool FREQ, bool AP, bool MODE ) 294void WirelessApplet::updateDHCPConfig( bool ESSID, bool FREQ, bool AP, bool MODE )
295{ 295{
296 rocESSID = ESSID; 296 rocESSID = ESSID;
297 rocFREQ = FREQ; 297 rocFREQ = FREQ;
298 rocAP = AP; 298 rocAP = AP;
299 rocMODE = MODE; 299 rocMODE = MODE;
300} 300}
301 301
302void WirelessApplet::updateDelayChange( int delay ) 302void WirelessApplet::updateDelayChange( int delay )
303{ 303{
304 if ( timer ) 304 if ( timer )
305 killTimer( timer ); 305 killTimer( timer );
306 delay *= 1000; 306 delay *= 1000;
307 if ( delay == 0 ) 307 if ( delay == 0 )
308 delay = 50; 308 delay = 50;
309 timer = startTimer( delay ); 309 timer = startTimer( delay );
310} 310}
311 311
312void WirelessApplet::displayStyleChange( int style ) 312void WirelessApplet::displayStyleChange( int style )
313{ 313{
314 visualStyle = style; 314 visualStyle = style;
315 repaint(); 315 repaint();
316} 316}
317 317
318WirelessApplet::~WirelessApplet() 318WirelessApplet::~WirelessApplet()
319{} 319{}
320 320
321void WirelessApplet::timerEvent( QTimerEvent* ) 321void WirelessApplet::timerEvent( QTimerEvent* )
322{ 322{
323#ifdef MDEBUG 323#ifdef MDEBUG
324 qDebug( "WirelessApplet::timerEvent" ); 324 qDebug( "WirelessApplet::timerEvent" );
325#endif 325#endif
326 if ( interface ) 326 if ( interface )
327 { 327 {
328 if ( !ONetwork::instance()->isPresent( (const char*) interface->name() ) ) 328 if ( !ONetwork::instance()->isPresent( (const char*) interface->name() ) )
329 { 329 {
330#ifdef MDEBUG 330#ifdef MDEBUG
331 qDebug( "WIFIAPPLET: Interface no longer present." ); 331 qDebug( "WIFIAPPLET: Interface no longer present." );
332#endif 332#endif
333 interface = 0L; 333 interface = 0L;
334 mustRepaint(); 334 mustRepaint();
335 return; 335 return;
336 } 336 }
337 337
338 if ( mustRepaint() ) 338 if ( mustRepaint() )
339 { 339 {
340#ifdef MDEBUG 340#ifdef MDEBUG
341 qDebug( "WIFIAPPLET: A value has changed -> repainting." ); 341 qDebug( "WIFIAPPLET: A value has changed -> repainting." );
342#endif 342#endif
343 repaint(); 343 repaint();
344 } 344 }
345 345
346 if ( status->isVisible() ) 346 if ( status->isVisible() )
347 { 347 {
348 updatePopupWindow(); 348 updatePopupWindow();
349 } 349 }
350 } 350 }
351 else 351 else
352 { 352 {
353 checkInterface(); 353 checkInterface();
354 } 354 }
355} 355}
356 356
357void WirelessApplet::mousePressEvent( QMouseEvent * ) 357void WirelessApplet::mousePressEvent( QMouseEvent * )
358{ 358{
359 if ( status->isVisible() ) 359 if ( status->isVisible() )
360 status->hide(); 360 status->hide();
361 else 361 else
362 status->show( true ); 362 status->show( true );
363} 363}
364 364
365bool WirelessApplet::mustRepaint() 365bool WirelessApplet::mustRepaint()
366{ 366{
367 // check if there are enough changes to justify a (flickering) repaint 367 // check if there are enough changes to justify a (flickering) repaint
368 368
369 // has the interface changed? 369 // has the interface changed?
370 370
371 if ( interface != oldiface ) 371 if ( interface != oldiface )
372 { 372 {
373 oldiface = interface; 373 oldiface = interface;
374 if ( interface ) 374 if ( interface )
375 { 375 {
376#ifdef MDEBUG 376#ifdef MDEBUG
377 qDebug( "WIFIAPPLET: We had no interface but now we have one! :-)" ); 377 qDebug( "WIFIAPPLET: We had no interface but now we have one! :-)" );
378#endif 378#endif
379 show(); 379 show();
380 } 380 }
381 else 381 else
382 { 382 {
383#ifdef MDEBUG 383#ifdef MDEBUG
384 qDebug( "WIFIAPPLET: We had a interface but now we don't have one! ;-(" ); 384 qDebug( "WIFIAPPLET: We had a interface but now we don't have one! ;-(" );
385#endif 385#endif
386 hide(); 386 hide();
387 return true; 387 return true;
388 } 388 }
389 } 389 }
390 390
391 const char** pixmap = getQualityPixmap(); 391 const char** pixmap = getQualityPixmap();
392 392
393 if ( pixmap && ( pixmap != oldpixmap ) ) 393 if ( pixmap && ( pixmap != oldpixmap ) )
394 { 394 {
395 oldpixmap = pixmap; 395 oldpixmap = pixmap;
396 return true; 396 return true;
397 } 397 }
398 398
399 int noiseH = 50; // iface->noisePercent() * ( height() - 3 ) / 100; 399 int noiseH = 50; // iface->noisePercent() * ( height() - 3 ) / 100;
400 int signalH = interface->signalStrength() * ( height() - 3 ) / 100; 400 int signalH = interface->signalStrength() * ( height() - 3 ) / 100;
401 int qualityH = 50; // iface->qualityPercent() * ( height() - 3 ) / 100; 401 int qualityH = 50; // iface->qualityPercent() * ( height() - 3 ) / 100;
402 402
403 if ( ( noiseH != oldnoiseH ) 403 if ( ( noiseH != oldnoiseH )
404 || ( signalH != oldsignalH ) 404 || ( signalH != oldsignalH )
405 || ( qualityH != oldqualityH ) ) 405 || ( qualityH != oldqualityH ) )
406 { 406 {
407 oldnoiseH = noiseH; 407 oldnoiseH = noiseH;
408 oldsignalH = signalH; 408 oldsignalH = signalH;
409 oldqualityH = qualityH; 409 oldqualityH = qualityH;
410 return true; 410 return true;
411 } 411 }
412 412
413 if ( rocESSID && ( oldESSID != interface->SSID() ) ) 413 if ( rocESSID && ( oldESSID != interface->SSID() ) )
414 { 414 {
415#ifdef MDEBUG 415#ifdef MDEBUG
416 qDebug( "WIFIAPPLET: ESSID has changed." ); 416 qDebug( "WIFIAPPLET: ESSID has changed." );
417#endif 417#endif
418 renewDHCP(); 418 renewDHCP();
419 } 419 }
420 else if ( rocFREQ && ( oldFREQ != interface->frequency() ) ) 420 else if ( rocFREQ && ( oldFREQ != interface->frequency() ) )
421 { 421 {
422#ifdef MDEBUG 422#ifdef MDEBUG
423 qDebug( "WIFIAPPLET: FREQ has changed." ); 423 qDebug( "WIFIAPPLET: FREQ has changed." );
424#endif 424#endif
425 renewDHCP(); 425 renewDHCP();
426 } 426 }
427 else if ( rocAP && ( oldAP != interface->associatedAP().toString() ) ) 427 else if ( rocAP && ( oldAP != interface->associatedAP().toString() ) )
428 { 428 {
429#ifdef MDEBUG 429#ifdef MDEBUG
430 qDebug( "WIFIAPPLET: AP has changed." ); 430 qDebug( "WIFIAPPLET: AP has changed." );
431#endif 431#endif
432 renewDHCP(); 432 renewDHCP();
433 } 433 }
434 else if ( rocMODE && ( oldMODE != interface->mode() ) ) 434 else if ( rocMODE && ( oldMODE != interface->mode() ) )
435 { 435 {
436#ifdef MDEBUG 436#ifdef MDEBUG
437 qDebug( "WIFIAPPLET: MODE has changed." ); 437 qDebug( "WIFIAPPLET: MODE has changed." );
438#endif 438#endif
439 renewDHCP(); 439 renewDHCP();
440 } 440 }
441 441
442 oldESSID = interface->SSID(); 442 oldESSID = interface->SSID();
443 oldMODE = interface->mode(); 443 oldMODE = interface->mode();
444 oldFREQ = interface->frequency(); 444 oldFREQ = interface->frequency();
445 oldAP = interface->associatedAP().toString(); 445 oldAP = interface->associatedAP().toString();
446 446
447 return false; 447 return false;
448} 448}
449 449
450void WirelessApplet::updatePopupWindow() 450void WirelessApplet::updatePopupWindow()
451{ 451{
452 int qualityH = interface->signalStrength(); 452 int qualityH = interface->signalStrength();
453 453
454 if ( status->mgraph ) 454 if ( status->mgraph )
455 status->mgraph->addValue( qualityH, false ); 455 status->mgraph->addValue( qualityH, false );
456 456
457 QString freqString; 457 QString freqString;
458 QString cell = ( interface->mode() == "Managed" ) ? "AP: " : "Cell: "; 458 QString cell = ( interface->mode() == "Managed" ) ? "AP: " : "Cell: ";
459 freqString.sprintf( "%.3f GHz", interface->frequency() ); 459 freqString.sprintf( "%.3f GHz", interface->frequency() );
460 status->statusLabel->setText( "Station: " + interface->nickName() + "<br>" + 460 status->statusLabel->setText( "Station: " + interface->nickName() + "<br>" +
461 "ESSID: " + interface->SSID() + "<br>" + 461 "ESSID: " + interface->SSID() + "<br>" +
462 "MODE: " + interface->mode() + "<br>" + 462 "MODE: " + interface->mode() + "<br>" +
463 "FREQ: " + freqString + "<br>" + 463 "FREQ: " + freqString + "<br>" +
464 cell + " " + interface->associatedAP().toString() ); 464 cell + " " + interface->associatedAP().toString() );
465} 465}
466 466
467const char** WirelessApplet::getQualityPixmap() 467const char** WirelessApplet::getQualityPixmap()
468{ 468{
469 if ( !interface ) return ( const char** ) nowireless_xpm; 469 if ( !interface ) return ( const char** ) nowireless_xpm;
470 int qualityH = interface->signalStrength(); 470 int qualityH = interface->signalStrength();
471 if ( qualityH < 0 ) return ( const char** ) nowireless_xpm; 471 if ( qualityH < 0 ) return ( const char** ) nowireless_xpm;
472 472
473 if ( visualStyle == STYLE_ANTENNA ) 473 if ( visualStyle == STYLE_ANTENNA )
474 { 474 {
475 if ( qualityH < 1 ) return ( const char** ) connect0_xpm; 475 if ( qualityH < 1 ) return ( const char** ) connect0_xpm;
476 if ( qualityH < 17 ) return ( const char** ) connect1_xpm; 476 if ( qualityH < 17 ) return ( const char** ) connect1_xpm;
477 if ( qualityH < 34 ) return ( const char** ) connect2_xpm; 477 if ( qualityH < 34 ) return ( const char** ) connect2_xpm;
478 if ( qualityH < 50 ) return ( const char** ) connect3_xpm; 478 if ( qualityH < 50 ) return ( const char** ) connect3_xpm;
479 if ( qualityH < 65 ) return ( const char** ) connect4_xpm; 479 if ( qualityH < 65 ) return ( const char** ) connect4_xpm;
480 return ( const char** ) connect5_xpm; 480 return ( const char** ) connect5_xpm;
481 } 481 }
482 482
483 return 0; // please draw your bars 483 return 0; // please draw your bars
484} 484}
485 485
486void WirelessApplet::paintEvent( QPaintEvent* ) 486void WirelessApplet::paintEvent( QPaintEvent* )
487{ 487{
488 QPainter p( this ); 488 QPainter p( this );
489 QColor color; 489 QColor color;
490 490
491 const char** pixmap = getQualityPixmap(); 491 const char** pixmap = getQualityPixmap();
492 492
493 if ( pixmap ) 493 if ( pixmap )
494 p.drawPixmap( 0, 1, pixmap ); 494 p.drawPixmap( 0, 1, pixmap );
495 else 495 else
496 { 496 {
497 497
498 int noiseH = 30; // iface->noisePercent() * ( height() - 3 ) / 100; 498 int noiseH = 30; // iface->noisePercent() * ( height() - 3 ) / 100;
499 int signalH = 50; // iface->signalPercent() * ( height() - 3 ) / 100; 499 int signalH = 50; // iface->signalPercent() * ( height() - 3 ) / 100;
500 int qualityH = interface->signalStrength(); // iface->qualityPercent() * ( height() - 3 ) / 100; 500 int qualityH = interface->signalStrength(); // iface->qualityPercent() * ( height() - 3 ) / 100;
501 501
502 double intensity; 502 double intensity;
503 int pixelHeight; 503 int pixelHeight;
504 int pixelWidth = 2; 504 int pixelWidth = 2;
505 int Hue; 505 int Hue;
506 int barSpace = 3; 506 int barSpace = 3;
507 int leftoffset = 0; 507 int leftoffset = 0;
508 int bottomoffset = 2; 508 int bottomoffset = 2;
509 509
510 // draw noise indicator 510 // draw noise indicator
511 pixelHeight = noiseH; 511 pixelHeight = noiseH;
512 Hue = 50; 512 Hue = 50;
513 for ( int i = 0; i < pixelHeight; ++i ) 513 for ( int i = 0; i < pixelHeight; ++i )
514 { 514 {
515 intensity = 50 + ( ( double ) i / ( double ) pixelHeight ) * 205; 515 intensity = 50 + ( ( double ) i / ( double ) pixelHeight ) * 205;
516 color.setHsv( Hue, 255, intensity ); 516 color.setHsv( Hue, 255, intensity );
517 p.setPen ( color ); 517 p.setPen ( color );
518 p.drawLine( leftoffset, height() - bottomoffset - i, pixelWidth + leftoffset, height() - bottomoffset - i ); 518 p.drawLine( leftoffset, height() - bottomoffset - i, pixelWidth + leftoffset, height() - bottomoffset - i );
519 } 519 }
520 520
521 // draw signal indicator 521 // draw signal indicator
522 pixelHeight = signalH; 522 pixelHeight = signalH;
523 Hue = 100; 523 Hue = 100;
524 leftoffset += pixelWidth + barSpace; 524 leftoffset += pixelWidth + barSpace;
525 for ( int i = 0; i < pixelHeight; ++i ) 525 for ( int i = 0; i < pixelHeight; ++i )
526 { 526 {
527 intensity = 50 + ( ( double ) i / ( double ) pixelHeight ) * 205; 527 intensity = 50 + ( ( double ) i / ( double ) pixelHeight ) * 205;
528 color.setHsv( Hue, 255, intensity ); 528 color.setHsv( Hue, 255, intensity );
529 p.setPen ( color ); 529 p.setPen ( color );
530 p.drawLine( leftoffset, height() - bottomoffset - i, pixelWidth + leftoffset, height() - bottomoffset - i ); 530 p.drawLine( leftoffset, height() - bottomoffset - i, pixelWidth + leftoffset, height() - bottomoffset - i );
531 } 531 }
532 532
533 // draw quality indicator 533 // draw quality indicator
534 pixelHeight = qualityH; 534 pixelHeight = qualityH;
535 Hue = 250; 535 Hue = 250;
536 leftoffset += pixelWidth + barSpace; 536 leftoffset += pixelWidth + barSpace;
537 for ( int i = 0; i < pixelHeight; ++i ) 537 for ( int i = 0; i < pixelHeight; ++i )
538 { 538 {
539 intensity = 50 + ( ( double ) i / ( double ) pixelHeight ) * 205; 539 intensity = 50 + ( ( double ) i / ( double ) pixelHeight ) * 205;
540 color.setHsv( Hue, 255, intensity ); 540 color.setHsv( Hue, 255, intensity );
541 p.setPen ( color ); 541 p.setPen ( color );
542 p.drawLine( leftoffset, height() - bottomoffset - i, pixelWidth + leftoffset, height() - bottomoffset - i ); 542 p.drawLine( leftoffset, height() - bottomoffset - i, pixelWidth + leftoffset, height() - bottomoffset - i );
543 } 543 }
544 } 544 }
545} 545}
546 546
547 547
548int WirelessApplet::position() 548int WirelessApplet::position()
549{ 549{
550 return 6; 550 return 6;
551} 551}
552 552
553 553
554Q_EXPORT_INTERFACE() 554Q_EXPORT_INTERFACE()
555{ 555{
556 Q_CREATE_INSTANCE( OTaskbarAppletWrapper<WirelessApplet> ); 556 Q_CREATE_INSTANCE( OTaskbarAppletWrapper<WirelessApplet> );
557} 557}
558 558
diff --git a/noncore/applets/zkbapplet/zkbwidget.cpp b/noncore/applets/zkbapplet/zkbwidget.cpp
index 0b5ab78..0083e9b 100644
--- a/noncore/applets/zkbapplet/zkbwidget.cpp
+++ b/noncore/applets/zkbapplet/zkbwidget.cpp
@@ -1,162 +1,162 @@
1#include <opie2/otaskbarapplet.h> 1#include <opie2/otaskbarapplet.h>
2#include <qpe/qcopenvelope_qws.h> 2#include <qpe/qcopenvelope_qws.h>
3#include <qpe/applnk.h> 3#include <qpe/applnk.h>
4#include <qpe/qpeapplication.h> 4#include <qpe/qpeapplication.h>
5#include <qpe/resource.h> 5#include <qpe/resource.h>
6#include <stdio.h> 6#include <stdio.h>
7#include <unistd.h> 7#include <unistd.h>
8#include "zkbwidget.h" 8#include "zkbwidget.h"
9#include "zkbcfg.h" 9#include "zkbcfg.h"
10 10
11ZkbWidget::ZkbWidget(QWidget* parent):QLabel(parent),keymap(0), 11ZkbWidget::ZkbWidget(QWidget* parent):QLabel(parent),keymap(0),
12 disabled(Resource::loadPixmap("zkb-disabled")) { 12 disabled(Resource::loadPixmap("zkb-disabled")) {
13 13
14 labels = new QPopupMenu(); 14 labels = new QPopupMenu();
15 connect(labels, SIGNAL(activated(int)), this, 15 connect(labels, SIGNAL(activated(int)), this,
16 SLOT(labelChanged(int))); 16 SLOT(labelChanged(int)));
17 17
18 loadKeymap(); 18 loadKeymap();
19 19
20 channel = new QCopChannel("QPE/zkb", this); 20 channel = new QCopChannel("QPE/zkb", this);
21 connect(channel, SIGNAL(received(const QCString&, const QByteArray&)), 21 connect(channel, SIGNAL(received(const QCString&,const QByteArray&)),
22 this, SLOT(signalReceived(const QCString&, const QByteArray&))); 22 this, SLOT(signalReceived(const QCString&,const QByteArray&)));
23 setFixedWidth ( AppLnk::smallIconSize() ); 23 setFixedWidth ( AppLnk::smallIconSize() );
24 setFixedHeight ( AppLnk::smallIconSize() ); 24 setFixedHeight ( AppLnk::smallIconSize() );
25} 25}
26 26
27ZkbWidget::~ZkbWidget() { 27ZkbWidget::~ZkbWidget() {
28} 28}
29 29
30int ZkbWidget::position() 30int ZkbWidget::position()
31{ 31{
32 return 8; 32 return 8;
33} 33}
34 34
35bool ZkbWidget::loadKeymap() { 35bool ZkbWidget::loadKeymap() {
36 ZkbConfig c(QPEApplication::qpeDir()+"/share/zkb"); 36 ZkbConfig c(QPEApplication::qpeDir()+"/share/zkb");
37 QFontMetrics fm(font()); 37 QFontMetrics fm(font());
38 38
39 if (keymap != 0) { 39 if (keymap != 0) {
40 delete keymap; 40 delete keymap;
41 keymap = 0; 41 keymap = 0;
42 } 42 }
43 43
44 Keymap* km = new Keymap(); 44 Keymap* km = new Keymap();
45 45
46 if (!c.load("zkb.xml", *km, "")) { 46 if (!c.load("zkb.xml", *km, "")) {
47 delete km; 47 delete km;
48 setPixmap(disabled); 48 setPixmap(disabled);
49 return false; 49 return false;
50 } 50 }
51 51
52 connect(km, SIGNAL(stateChanged(const QString&)), 52 connect(km, SIGNAL(stateChanged(const QString&)),
53 this, SLOT(stateChanged(const QString&))); 53 this, SLOT(stateChanged(const QString&)));
54 54
55 qwsServer->setKeyboardFilter(km); 55 qwsServer->setKeyboardFilter(km);
56 56
57 Keymap* oldkm = keymap; 57 Keymap* oldkm = keymap;
58 keymap = km; 58 keymap = km;
59 59
60 if (oldkm != 0) { 60 if (oldkm != 0) {
61 delete oldkm; 61 delete oldkm;
62 } 62 }
63 63
64 setText(keymap->getCurrentLabel()); 64 setText(keymap->getCurrentLabel());
65 65
66 labels->clear(); 66 labels->clear();
67 QStringList l = keymap->listLabels(); 67 QStringList l = keymap->listLabels();
68 labels->insertItem(disabled, 0, 0); 68 labels->insertItem(disabled, 0, 0);
69 int n = 1; 69 int n = 1;
70 w = 0; 70 w = 0;
71 for(QStringList::Iterator it = l.begin(); it != l.end(); 71 for(QStringList::Iterator it = l.begin(); it != l.end();
72 ++it, n++) { 72 ++it, n++) {
73 73
74 // printf("label: %s\n", (const char*) (*it).utf8()); 74 // printf("label: %s\n", (const char*) (*it).utf8());
75 75
76 labels->insertItem(*it, n, n); 76 labels->insertItem(*it, n, n);
77 int lw = fm.width(*it); 77 int lw = fm.width(*it);
78 if (lw > w) { 78 if (lw > w) {
79 w = lw; 79 w = lw;
80 } 80 }
81 } 81 }
82 82
83 if (w == 0) { 83 if (w == 0) {
84 hide(); 84 hide();
85 } else { 85 } else {
86 show(); 86 show();
87 } 87 }
88 return true; 88 return true;
89} 89}
90 90
91QSize ZkbWidget::sizeHint() const { 91QSize ZkbWidget::sizeHint() const {
92 return QSize(AppLnk::smallIconSize(),AppLnk::smallIconSize()); 92 return QSize(AppLnk::smallIconSize(),AppLnk::smallIconSize());
93} 93}
94 94
95void ZkbWidget::stateChanged(const QString& s) { 95void ZkbWidget::stateChanged(const QString& s) {
96 //qDebug("stateChanged: %s\n", (const char*) s.utf8()); 96 //qDebug("stateChanged: %s\n", (const char*) s.utf8());
97 setText(s); 97 setText(s);
98} 98}
99 99
100void ZkbWidget::labelChanged(int id) { 100void ZkbWidget::labelChanged(int id) {
101 if (id == 0) { 101 if (id == 0) {
102 keymap->disable(); 102 keymap->disable();
103 setPixmap(disabled); 103 setPixmap(disabled);
104 return; 104 return;
105 } 105 }
106 106
107 keymap->enable(); 107 keymap->enable();
108 108
109 QStringList l = keymap->listLabels(); 109 QStringList l = keymap->listLabels();
110 QString lbl = l[id-1]; 110 QString lbl = l[id-1];
111 111
112 //printf("labelChanged: %s\n", (const char*) lbl.utf8()); 112 //printf("labelChanged: %s\n", (const char*) lbl.utf8());
113 State* state = keymap->getStateByLabel(lbl); 113 State* state = keymap->getStateByLabel(lbl);
114 if (state != 0) { 114 if (state != 0) {
115 keymap->setCurrentState(state); 115 keymap->setCurrentState(state);
116 setText(lbl); 116 setText(lbl);
117 } 117 }
118} 118}
119 119
120void ZkbWidget::mouseReleaseEvent(QMouseEvent*) { 120void ZkbWidget::mouseReleaseEvent(QMouseEvent*) {
121 QSize sh = labels->sizeHint(); 121 QSize sh = labels->sizeHint();
122 QPoint p = mapToGlobal(QPoint((width()-sh.width())/2,-sh.height())); 122 QPoint p = mapToGlobal(QPoint((width()-sh.width())/2,-sh.height()));
123 labels->exec(p); 123 labels->exec(p);
124} 124}
125 125
126void ZkbWidget::signalReceived(const QCString& msg, const QByteArray& data) { 126void ZkbWidget::signalReceived(const QCString& msg, const QByteArray& data) {
127 QDataStream stream(data, IO_ReadOnly); 127 QDataStream stream(data, IO_ReadOnly);
128 128
129 if (msg == "enable()") { 129 if (msg == "enable()") {
130 keymap->enable(); 130 keymap->enable();
131 } else if (msg == "disable()") { 131 } else if (msg == "disable()") {
132 keymap->disable(); 132 keymap->disable();
133 } else if (msg == "reload()") { 133 } else if (msg == "reload()") {
134 QCopEnvelope("QPE/System", "busy()"); 134 QCopEnvelope("QPE/System", "busy()");
135 QTimer::singleShot(0, this, SLOT(reload())); 135 QTimer::singleShot(0, this, SLOT(reload()));
136 } else if (msg == "switch(QString)") { 136 } else if (msg == "switch(QString)") {
137 QString lbl; 137 QString lbl;
138 stream >> lbl; 138 stream >> lbl;
139 139
140 if (keymap != 0) { 140 if (keymap != 0) {
141 State* state = keymap->getStateByLabel(lbl); 141 State* state = keymap->getStateByLabel(lbl);
142 if (state != 0) { 142 if (state != 0) {
143 keymap->setCurrentState(state); 143 keymap->setCurrentState(state);
144 setText(lbl); 144 setText(lbl);
145 } 145 }
146 } 146 }
147 } else if (msg == "debug(QString)") { 147 } else if (msg == "debug(QString)") {
148 QString flag; 148 QString flag;
149 stream >> flag; 149 stream >> flag;
150 } 150 }
151} 151}
152 152
153void ZkbWidget::reload() { 153void ZkbWidget::reload() {
154 loadKeymap(); 154 loadKeymap();
155 QCopEnvelope("QPE/System", "notBusy()"); 155 QCopEnvelope("QPE/System", "notBusy()");
156} 156}
157 157
158Q_EXPORT_INTERFACE() 158Q_EXPORT_INTERFACE()
159{ 159{
160 Q_CREATE_INSTANCE( OTaskbarAppletWrapper<ZkbWidget> ); 160 Q_CREATE_INSTANCE( OTaskbarAppletWrapper<ZkbWidget> );
161} 161}
162 162
diff --git a/noncore/apps/advancedfm/advancedfm.cpp b/noncore/apps/advancedfm/advancedfm.cpp
index c44d387..2ba3dca 100644
--- a/noncore/apps/advancedfm/advancedfm.cpp
+++ b/noncore/apps/advancedfm/advancedfm.cpp
@@ -1,883 +1,883 @@
1/*************************************************************************** 1/***************************************************************************
2 AdvancedFm.cpp 2 AdvancedFm.cpp
3 ------------------- 3 -------------------
4 ** Created: Sat Mar 9 23:33:09 2002 4 ** Created: Sat Mar 9 23:33:09 2002
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12#define DEVELOPERS_VERSION 12#define DEVELOPERS_VERSION
13#include "advancedfm.h" 13#include "advancedfm.h"
14 14
15#include <qpe/qpeapplication.h> 15#include <qpe/qpeapplication.h>
16#include <qpe/config.h> 16#include <qpe/config.h>
17#include <qpe/mimetype.h> 17#include <qpe/mimetype.h>
18#include <qpe/applnk.h> 18#include <qpe/applnk.h>
19#include <qpe/resource.h> 19#include <qpe/resource.h>
20#include <qpe/menubutton.h> 20#include <qpe/menubutton.h>
21 21
22#include <qcombobox.h> 22#include <qcombobox.h>
23#include <qpopupmenu.h> 23#include <qpopupmenu.h>
24#include <qlistview.h> 24#include <qlistview.h>
25#include <qmessagebox.h> 25#include <qmessagebox.h>
26#include <qlineedit.h> 26#include <qlineedit.h>
27 27
28 28
29#include <sys/stat.h> 29#include <sys/stat.h>
30#include <time.h> 30#include <time.h>
31#include <dirent.h> 31#include <dirent.h>
32#include <fcntl.h> 32#include <fcntl.h>
33#include <sys/vfs.h> 33#include <sys/vfs.h>
34#include <mntent.h> 34#include <mntent.h>
35 35
36#ifdef NOQUICKLAUNCH 36#ifdef NOQUICKLAUNCH
37AdvancedFm::AdvancedFm( ) 37AdvancedFm::AdvancedFm( )
38#else 38#else
39AdvancedFm::AdvancedFm(QWidget *,const char*, WFlags ) 39AdvancedFm::AdvancedFm(QWidget *,const char*, WFlags )
40#endif 40#endif
41 : QMainWindow( ) { 41 : QMainWindow( ) {
42 init(); 42 init();
43 renameBox = 0; 43 renameBox = 0;
44 44
45 unknownXpm = Resource::loadImage( "UnknownDocument" ).smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); 45 unknownXpm = Resource::loadImage( "UnknownDocument" ).smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() );
46 46
47 initConnections(); 47 initConnections();
48 whichTab=1; 48 whichTab=1;
49 rePopulate(); 49 rePopulate();
50 currentPathCombo->setFocus(); 50 currentPathCombo->setFocus();
51 channel = new QCopChannel( "QPE/Application/advancedfm", this ); 51 channel = new QCopChannel( "QPE/Application/advancedfm", this );
52 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 52 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
53 this, SLOT( qcopReceive(const QCString&, const QByteArray&)) ); 53 this, SLOT( qcopReceive(const QCString&,const QByteArray&)) );
54} 54}
55 55
56AdvancedFm::~AdvancedFm() { 56AdvancedFm::~AdvancedFm() {
57} 57}
58 58
59 59
60void AdvancedFm::cleanUp() { 60void AdvancedFm::cleanUp() {
61 QString sfile=QDir::homeDirPath(); 61 QString sfile=QDir::homeDirPath();
62 if(sfile.right(1) != "/") 62 if(sfile.right(1) != "/")
63 sfile+="/._temp"; 63 sfile+="/._temp";
64 else 64 else
65 sfile+="._temp"; 65 sfile+="._temp";
66 QFile file( sfile); 66 QFile file( sfile);
67 if(file.exists()) 67 if(file.exists())
68 file.remove(); 68 file.remove();
69} 69}
70 70
71void AdvancedFm::tabChanged(QWidget *) { 71void AdvancedFm::tabChanged(QWidget *) {
72// qWarning("tab changed"); 72// qWarning("tab changed");
73 QString path = CurrentDir()->canonicalPath(); 73 QString path = CurrentDir()->canonicalPath();
74 currentPathCombo->lineEdit()->setText( path ); 74 currentPathCombo->lineEdit()->setText( path );
75 75
76 if(whichTab == 1) { 76 if(whichTab == 1) {
77 viewMenu->setItemChecked(viewMenu->idAt(0), true); 77 viewMenu->setItemChecked(viewMenu->idAt(0), true);
78 viewMenu->setItemChecked(viewMenu->idAt(1), false); 78 viewMenu->setItemChecked(viewMenu->idAt(1), false);
79 } else { 79 } else {
80 viewMenu->setItemChecked(viewMenu->idAt(0), false); 80 viewMenu->setItemChecked(viewMenu->idAt(0), false);
81 viewMenu->setItemChecked(viewMenu->idAt(1), true); 81 viewMenu->setItemChecked(viewMenu->idAt(1), true);
82 } 82 }
83 83
84 QString fs= getFileSystemType( (const QString &) path); 84 QString fs= getFileSystemType( (const QString &) path);
85 85
86 setCaption(tr("AdvancedFm :: ")+fs+" :: " 86 setCaption(tr("AdvancedFm :: ")+fs+" :: "
87 +checkDiskSpace( (const QString &) path )+ tr(" kB free") ); 87 +checkDiskSpace( (const QString &) path )+ tr(" kB free") );
88 chdir( path.latin1()); 88 chdir( path.latin1());
89} 89}
90 90
91 91
92void AdvancedFm::populateView() { 92void AdvancedFm::populateView() {
93 93
94// qWarning("PopulateView"); 94// qWarning("PopulateView");
95 QPixmap pm; 95 QPixmap pm;
96 QListView *thisView = CurrentView(); 96 QListView *thisView = CurrentView();
97 QDir *thisDir = CurrentDir(); 97 QDir *thisDir = CurrentDir();
98 QString path = thisDir->canonicalPath(); 98 QString path = thisDir->canonicalPath();
99 99
100//qWarning("path is "+path); 100//qWarning("path is "+path);
101 thisView->clear(); 101 thisView->clear();
102 thisDir->setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 102 thisDir->setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
103 thisDir->setMatchAllDirs(TRUE); 103 thisDir->setMatchAllDirs(TRUE);
104 thisDir->setNameFilter(filterStr); 104 thisDir->setNameFilter(filterStr);
105 QString fileL, fileS, fileDate; 105 QString fileL, fileS, fileDate;
106 QString fs= getFileSystemType((const QString &) path); 106 QString fs= getFileSystemType((const QString &) path);
107 setCaption(tr("AdvancedFm :: ")+fs+" :: " 107 setCaption(tr("AdvancedFm :: ")+fs+" :: "
108 +checkDiskSpace((const QString &) path)+ tr(" kB free") ); 108 +checkDiskSpace((const QString &) path)+ tr(" kB free") );
109 bool isDir=FALSE; 109 bool isDir=FALSE;
110 const QFileInfoList *list = thisDir->entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/); 110 const QFileInfoList *list = thisDir->entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/);
111 QFileInfoListIterator it(*list); 111 QFileInfoListIterator it(*list);
112 QFileInfo *fi; 112 QFileInfo *fi;
113 while ( (fi=it.current()) ) { 113 while ( (fi=it.current()) ) {
114 if (fi->isSymLink() ) { 114 if (fi->isSymLink() ) {
115 QString symLink=fi->readLink(); 115 QString symLink=fi->readLink();
116 QFileInfo sym( symLink); 116 QFileInfo sym( symLink);
117 fileS.sprintf( "%10i", sym.size() ); 117 fileS.sprintf( "%10i", sym.size() );
118 fileL = fi->fileName() +" -> " + sym.filePath().data(); 118 fileL = fi->fileName() +" -> " + sym.filePath().data();
119 fileDate = sym.lastModified().toString(); 119 fileDate = sym.lastModified().toString();
120 } else { 120 } else {
121 fileS.sprintf( "%10i", fi->size() ); 121 fileS.sprintf( "%10i", fi->size() );
122 fileL = fi->fileName(); 122 fileL = fi->fileName();
123 fileDate= fi->lastModified().toString(); 123 fileDate= fi->lastModified().toString();
124 if( QDir(QDir::cleanDirPath( path +"/"+fileL)).exists() ) { 124 if( QDir(QDir::cleanDirPath( path +"/"+fileL)).exists() ) {
125// if(fileL == "..") 125// if(fileL == "..")
126 fileL += "/"; 126 fileL += "/";
127 isDir=TRUE; 127 isDir=TRUE;
128 } 128 }
129 } 129 }
130 QFileInfo fileInfo( path + "/" + fileL); 130 QFileInfo fileInfo( path + "/" + fileL);
131 131
132 if(fileL !="./" && fi->exists()) { 132 if(fileL !="./" && fi->exists()) {
133 item = new QListViewItem( thisView, fileL, fileS , fileDate); 133 item = new QListViewItem( thisView, fileL, fileS , fileDate);
134 134
135 if(isDir || fileL.find("/",0,TRUE) != -1) { 135 if(isDir || fileL.find("/",0,TRUE) != -1) {
136 136
137 if( !QDir( fi->filePath() ).isReadable()) //is directory 137 if( !QDir( fi->filePath() ).isReadable()) //is directory
138 pm = Resource::loadPixmap( "lockedfolder" ); 138 pm = Resource::loadPixmap( "lockedfolder" );
139 else 139 else
140 pm= Resource::loadPixmap( "folder" ); 140 pm= Resource::loadPixmap( "folder" );
141 } 141 }
142 else if ( fs == "vfat" && fileInfo.filePath().contains("/bin") ) { 142 else if ( fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
143 pm = Resource::loadPixmap( "exec"); 143 pm = Resource::loadPixmap( "exec");
144 } 144 }
145 else if( (fileInfo.permission( QFileInfo::ExeUser) 145 else if( (fileInfo.permission( QFileInfo::ExeUser)
146 | fileInfo.permission( QFileInfo::ExeGroup) 146 | fileInfo.permission( QFileInfo::ExeGroup)
147 | fileInfo.permission( QFileInfo::ExeOther)) && fs != "vfat" ) { 147 | fileInfo.permission( QFileInfo::ExeOther)) && fs != "vfat" ) {
148 pm = Resource::loadPixmap( "exec"); 148 pm = Resource::loadPixmap( "exec");
149 } 149 }
150 else if( !fi->isReadable() ) { 150 else if( !fi->isReadable() ) {
151 pm = Resource::loadPixmap( "locked" ); 151 pm = Resource::loadPixmap( "locked" );
152 } 152 }
153 else { //everything else goes by mimetype 153 else { //everything else goes by mimetype
154 MimeType mt(fi->filePath()); 154 MimeType mt(fi->filePath());
155 pm=mt.pixmap(); //sets the correct pixmap for mimetype 155 pm=mt.pixmap(); //sets the correct pixmap for mimetype
156 if(pm.isNull()) { 156 if(pm.isNull()) {
157 pm = unknownXpm; 157 pm = unknownXpm;
158 } 158 }
159 } 159 }
160 if( fi->isSymLink() || fileL.find("->",0,TRUE) != -1) { 160 if( fi->isSymLink() || fileL.find("->",0,TRUE) != -1) {
161 // qDebug(" overlay link image"); 161 // qDebug(" overlay link image");
162 pm= Resource::loadPixmap( "advancedfm/symlink" ); 162 pm= Resource::loadPixmap( "advancedfm/symlink" );
163 // pm= Resource::loadPixmap( "folder" ); 163 // pm= Resource::loadPixmap( "folder" );
164// QPixmap lnk = Resource::loadPixmap( "opie/symlink" ); 164// QPixmap lnk = Resource::loadPixmap( "opie/symlink" );
165// QPainter painter( &pm ); 165// QPainter painter( &pm );
166// painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); 166// painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk );
167// pm.setMask( pm.createHeuristicMask( FALSE ) ); 167// pm.setMask( pm.createHeuristicMask( FALSE ) );
168 } 168 }
169 item->setPixmap( 0,pm); 169 item->setPixmap( 0,pm);
170 170
171 } 171 }
172 isDir=FALSE; 172 isDir=FALSE;
173 ++it; 173 ++it;
174 } 174 }
175 175
176 if( path.find("dev",0,TRUE) != -1) { 176 if( path.find("dev",0,TRUE) != -1) {
177 struct stat buf; 177 struct stat buf;
178 dev_t devT; 178 dev_t devT;
179 DIR *dir; 179 DIR *dir;
180 struct dirent *mydirent; 180 struct dirent *mydirent;
181 181
182 if((dir = opendir( path.latin1())) != NULL) 182 if((dir = opendir( path.latin1())) != NULL)
183 while ((mydirent = readdir(dir)) != NULL) { 183 while ((mydirent = readdir(dir)) != NULL) {
184 lstat( mydirent->d_name, &buf); 184 lstat( mydirent->d_name, &buf);
185// qDebug(mydirent->d_name); 185// qDebug(mydirent->d_name);
186 fileL.sprintf("%s", mydirent->d_name); 186 fileL.sprintf("%s", mydirent->d_name);
187 devT = buf.st_dev; 187 devT = buf.st_dev;
188 fileS.sprintf("%d, %d", (int) ( devT >>8) &0xFF, (int)devT &0xFF); 188 fileS.sprintf("%d, %d", (int) ( devT >>8) &0xFF, (int)devT &0xFF);
189 fileDate.sprintf("%s", ctime( &buf.st_mtime)); 189 fileDate.sprintf("%s", ctime( &buf.st_mtime));
190 if( fileL.find(".") == -1 ) { 190 if( fileL.find(".") == -1 ) {
191 item= new QListViewItem( thisView, fileL, fileS, fileDate); 191 item= new QListViewItem( thisView, fileL, fileS, fileDate);
192 pm = unknownXpm; 192 pm = unknownXpm;
193 item->setPixmap( 0,pm); 193 item->setPixmap( 0,pm);
194 } 194 }
195 } 195 }
196 196
197 closedir(dir); 197 closedir(dir);
198 } 198 }
199 199
200 thisView->setSorting( 3,FALSE); 200 thisView->setSorting( 3,FALSE);
201 fillCombo( (const QString &) path ); 201 fillCombo( (const QString &) path );
202} 202}
203 203
204void AdvancedFm::rePopulate() { 204void AdvancedFm::rePopulate() {
205 populateView(); 205 populateView();
206 setOtherTabCurrent(); 206 setOtherTabCurrent();
207 populateView(); 207 populateView();
208 208
209// int tmpTab = whichTab; 209// int tmpTab = whichTab;
210// // qDebug("%d", tmpTab); 210// // qDebug("%d", tmpTab);
211 211
212// for(int i =1; i < 3; i++) { 212// for(int i =1; i < 3; i++) {
213// TabWidget->setCurrentWidget(i - 1); 213// TabWidget->setCurrentWidget(i - 1);
214// populateView(); 214// populateView();
215// } 215// }
216// TabWidget->setCurrentWidget( tmpTab - 1); 216// TabWidget->setCurrentWidget( tmpTab - 1);
217} 217}
218 218
219void AdvancedFm::ListClicked(QListViewItem *selectedItem) { 219void AdvancedFm::ListClicked(QListViewItem *selectedItem) {
220//qWarning("listclicked"); 220//qWarning("listclicked");
221 if(selectedItem) { 221 if(selectedItem) {
222 QString strItem=selectedItem->text(0); 222 QString strItem=selectedItem->text(0);
223// qWarning(strItem); 223// qWarning(strItem);
224 QString strSize=selectedItem->text(1); 224 QString strSize=selectedItem->text(1);
225 strSize=strSize.stripWhiteSpace(); 225 strSize=strSize.stripWhiteSpace();
226 bool isDirectory = false; 226 bool isDirectory = false;
227 QString strItem2; 227 QString strItem2;
228 228
229 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) {//if symlink 229 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) {//if symlink
230 strItem2 = dealWithSymName((const QString&)strItem); 230 strItem2 = dealWithSymName((const QString&)strItem);
231 if(QDir(strItem2).exists() ) 231 if(QDir(strItem2).exists() )
232 strItem = strItem2; 232 strItem = strItem2;
233 } 233 }
234 234
235 if( strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) { 235 if( strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) {
236 236
237 if(QDir(strItem).exists()) 237 if(QDir(strItem).exists())
238 isDirectory = true; 238 isDirectory = true;
239 } 239 }
240 240
241 if( isDirectory ) { 241 if( isDirectory ) {
242 CurrentDir()->cd( strItem, TRUE); 242 CurrentDir()->cd( strItem, TRUE);
243 populateView(); 243 populateView();
244 CurrentView()->ensureItemVisible( CurrentView()->firstChild()); 244 CurrentView()->ensureItemVisible( CurrentView()->firstChild());
245 } 245 }
246 chdir( strItem.latin1()); 246 chdir( strItem.latin1());
247 } 247 }
248} 248}
249 249
250void AdvancedFm::ListPressed( int mouse, QListViewItem *item, const QPoint& , int ) { 250void AdvancedFm::ListPressed( int mouse, QListViewItem *item, const QPoint& , int ) {
251 dealWithSchmooSchmaa( item->listView()); 251 dealWithSchmooSchmaa( item->listView());
252 switch (mouse) { 252 switch (mouse) {
253 case 1: 253 case 1:
254 { 254 {
255 if(renameBox != 0 ) { 255 if(renameBox != 0 ) {
256 cancelRename(); 256 cancelRename();
257 } 257 }
258 } 258 }
259 break; 259 break;
260 case 2: 260 case 2:
261 menuTimer.start( 500, TRUE ); 261 menuTimer.start( 500, TRUE );
262 break; 262 break;
263 }; 263 };
264} 264}
265 265
266 266
267void AdvancedFm::switchToLocalTab() { 267void AdvancedFm::switchToLocalTab() {
268//qWarning("switch to local view"); 268//qWarning("switch to local view");
269 TabWidget->setCurrentWidget(0); 269 TabWidget->setCurrentWidget(0);
270 Local_View->setFocus(); 270 Local_View->setFocus();
271} 271}
272 272
273void AdvancedFm::switchToRemoteTab() { 273void AdvancedFm::switchToRemoteTab() {
274//qWarning("switch to local view"); 274//qWarning("switch to local view");
275 TabWidget->setCurrentWidget(1); 275 TabWidget->setCurrentWidget(1);
276 Remote_View->setFocus(); 276 Remote_View->setFocus();
277} 277}
278 278
279void AdvancedFm::readConfig() { 279void AdvancedFm::readConfig() {
280 Config cfg("AdvancedFm"); 280 Config cfg("AdvancedFm");
281} 281}
282 282
283void AdvancedFm::writeConfig() { 283void AdvancedFm::writeConfig() {
284 Config cfg("AdvancedFm"); 284 Config cfg("AdvancedFm");
285} 285}
286 286
287void AdvancedFm::currentPathComboChanged() { 287void AdvancedFm::currentPathComboChanged() {
288 if(QDir( currentPathCombo->lineEdit()->text()).exists()) { 288 if(QDir( currentPathCombo->lineEdit()->text()).exists()) {
289 CurrentDir()->setPath( currentPathCombo->lineEdit()->text() ); 289 CurrentDir()->setPath( currentPathCombo->lineEdit()->text() );
290 populateView(); 290 populateView();
291 } else { 291 } else {
292 QMessageBox::message(tr("Note"),tr("That directory does not exist")); 292 QMessageBox::message(tr("Note"),tr("That directory does not exist"));
293 } 293 }
294} 294}
295 295
296void AdvancedFm::fillCombo(const QString &currentPath) { 296void AdvancedFm::fillCombo(const QString &currentPath) {
297 297
298 if ( whichTab == 1) { 298 if ( whichTab == 1) {
299 currentPathCombo->lineEdit()->setText( currentPath); 299 currentPathCombo->lineEdit()->setText( currentPath);
300 if( localDirPathStringList.grep( currentPath,TRUE).isEmpty() ) { 300 if( localDirPathStringList.grep( currentPath,TRUE).isEmpty() ) {
301 currentPathCombo->clear(); 301 currentPathCombo->clear();
302 localDirPathStringList.prepend( currentPath ); 302 localDirPathStringList.prepend( currentPath );
303 currentPathCombo->insertStringList( localDirPathStringList,-1); 303 currentPathCombo->insertStringList( localDirPathStringList,-1);
304 } 304 }
305 } else { 305 } else {
306 currentPathCombo->lineEdit()->setText( currentPath); 306 currentPathCombo->lineEdit()->setText( currentPath);
307 if( remoteDirPathStringList.grep( currentPath,TRUE).isEmpty() ) { 307 if( remoteDirPathStringList.grep( currentPath,TRUE).isEmpty() ) {
308 currentPathCombo->clear(); 308 currentPathCombo->clear();
309 remoteDirPathStringList.prepend( currentPath ); 309 remoteDirPathStringList.prepend( currentPath );
310 currentPathCombo->insertStringList( remoteDirPathStringList,-1); 310 currentPathCombo->insertStringList( remoteDirPathStringList,-1);
311 } 311 }
312 } 312 }
313} 313}
314 314
315void AdvancedFm::currentPathComboActivated(const QString & currentPath) { 315void AdvancedFm::currentPathComboActivated(const QString & currentPath) {
316 chdir( currentPath.latin1() ); 316 chdir( currentPath.latin1() );
317 CurrentDir()->cd( currentPath, TRUE); 317 CurrentDir()->cd( currentPath, TRUE);
318 populateView(); 318 populateView();
319 update(); 319 update();
320} 320}
321 321
322QStringList AdvancedFm::getPath() { 322QStringList AdvancedFm::getPath() {
323 QStringList strList; 323 QStringList strList;
324 QListView *thisView=CurrentView(); 324 QListView *thisView=CurrentView();
325 QList<QListViewItem> * getSelectedItems( QListView * thisView ); 325 QList<QListViewItem> * getSelectedItems( QListView * thisView );
326 QListViewItemIterator it( thisView ); 326 QListViewItemIterator it( thisView );
327 for ( ; it.current(); ++it ) { 327 for ( ; it.current(); ++it ) {
328 if ( it.current()->isSelected() ) { 328 if ( it.current()->isSelected() ) {
329 strList << it.current()->text(0); 329 strList << it.current()->text(0);
330// qDebug(it.current()->text(0)); 330// qDebug(it.current()->text(0));
331 } 331 }
332 } 332 }
333 return strList; 333 return strList;
334} 334}
335 335
336void AdvancedFm::homeButtonPushed() { 336void AdvancedFm::homeButtonPushed() {
337 QString current = QDir::homeDirPath(); 337 QString current = QDir::homeDirPath();
338 chdir( current.latin1() ); 338 chdir( current.latin1() );
339 CurrentDir()->cd( current, TRUE); 339 CurrentDir()->cd( current, TRUE);
340 populateView(); 340 populateView();
341 update(); 341 update();
342} 342}
343 343
344void AdvancedFm::docButtonPushed() { 344void AdvancedFm::docButtonPushed() {
345 QString current = QPEApplication::documentDir(); 345 QString current = QPEApplication::documentDir();
346 chdir( current.latin1() ); 346 chdir( current.latin1() );
347 CurrentDir()->cd( current, TRUE); 347 CurrentDir()->cd( current, TRUE);
348 populateView(); 348 populateView();
349 update(); 349 update();
350} 350}
351 351
352void AdvancedFm::SDButtonPushed() { 352void AdvancedFm::SDButtonPushed() {
353 QString current = "/mnt/card";// this can change so fix 353 QString current = "/mnt/card";// this can change so fix
354 chdir( current.latin1() ); 354 chdir( current.latin1() );
355 CurrentDir()->cd( current, TRUE); 355 CurrentDir()->cd( current, TRUE);
356 populateView(); 356 populateView();
357 update(); 357 update();
358} 358}
359 359
360void AdvancedFm::CFButtonPushed() { 360void AdvancedFm::CFButtonPushed() {
361 QString current; 361 QString current;
362 if(zaurusDevice) 362 if(zaurusDevice)
363 current= "/mnt/cf"; //zaurus 363 current= "/mnt/cf"; //zaurus
364 else 364 else
365 current = "/mnt/hda"; //ipaq 365 current = "/mnt/hda"; //ipaq
366 chdir( current.latin1() ); 366 chdir( current.latin1() );
367 CurrentDir()->cd( current, TRUE); 367 CurrentDir()->cd( current, TRUE);
368 populateView(); 368 populateView();
369 update(); 369 update();
370} 370}
371 371
372 372
373void AdvancedFm::doAbout() { 373void AdvancedFm::doAbout() {
374 QMessageBox::message("AdvancedFm",tr("Advanced FileManager\n" 374 QMessageBox::message("AdvancedFm",tr("Advanced FileManager\n"
375 "is copyright 2002-2003 by\n" 375 "is copyright 2002-2003 by\n"
376 "L.J.Potter<llornkcor@handhelds.org>\n" 376 "L.J.Potter<llornkcor@handhelds.org>\n"
377 "and is licensed by the GPL")); 377 "and is licensed by the GPL"));
378} 378}
379 379
380void AdvancedFm::keyPressEvent( QKeyEvent *e) { 380void AdvancedFm::keyPressEvent( QKeyEvent *e) {
381// qWarning("key %d", e->key()); 381// qWarning("key %d", e->key());
382// if( CurrentView()->hasFocus() ) 382// if( CurrentView()->hasFocus() )
383 { 383 {
384 switch ( e->key() ) { 384 switch ( e->key() ) {
385 case Key_Left: 385 case Key_Left:
386 upDir(); 386 upDir();
387 break; 387 break;
388 case Key_Next: 388 case Key_Next:
389 break; 389 break;
390 case Key_Return: 390 case Key_Return:
391 case Key_Enter: 391 case Key_Enter:
392 navigateToSelected(); 392 navigateToSelected();
393 break; 393 break;
394 case Key_Tab: { 394 case Key_Tab: {
395 setOtherTabCurrent(); 395 setOtherTabCurrent();
396 } 396 }
397 break; 397 break;
398 case Key_Delete: 398 case Key_Delete:
399 del(); 399 del();
400 break; 400 break;
401 case Key_A: 401 case Key_A:
402 copyAs(); 402 copyAs();
403 break; 403 break;
404 case Key_C: 404 case Key_C:
405 copy(); 405 copy();
406 break; 406 break;
407 case Key_E: 407 case Key_E:
408 runThis(); 408 runThis();
409 break; 409 break;
410 case Key_G: 410 case Key_G:
411 { 411 {
412 currentPathCombo->lineEdit()->setFocus(); 412 currentPathCombo->lineEdit()->setFocus();
413 } 413 }
414 break; 414 break;
415 415
416 case Key_H: 416 case Key_H:
417 showHidden(); 417 showHidden();
418 break; 418 break;
419 case Key_I: 419 case Key_I:
420 fileStatus(); 420 fileStatus();
421 break; 421 break;
422 case Key_M: 422 case Key_M:
423 move(); 423 move();
424 break; 424 break;
425 case Key_N: 425 case Key_N:
426 mkDir(); 426 mkDir();
427 break; 427 break;
428 case Key_P: 428 case Key_P:
429 filePerms(); 429 filePerms();
430 break; 430 break;
431 case Key_R: 431 case Key_R:
432 rn(); 432 rn();
433 break; 433 break;
434 case Key_U: 434 case Key_U:
435 upDir(); 435 upDir();
436 break; 436 break;
437 case Key_1: 437 case Key_1:
438 switchToLocalTab(); 438 switchToLocalTab();
439 break; 439 break;
440 case Key_2: 440 case Key_2:
441 switchToRemoteTab(); 441 switchToRemoteTab();
442 break; 442 break;
443 case Key_3: 443 case Key_3:
444 CFButtonPushed(); 444 CFButtonPushed();
445 break; 445 break;
446 case Key_4: 446 case Key_4:
447 SDButtonPushed(); 447 SDButtonPushed();
448 break; 448 break;
449 case Key_5: 449 case Key_5:
450 homeButtonPushed(); 450 homeButtonPushed();
451 break; 451 break;
452 case Key_6: 452 case Key_6:
453 docButtonPushed(); 453 docButtonPushed();
454 break; 454 break;
455 case Key_7: 455 case Key_7:
456 break; 456 break;
457 case Key_8: 457 case Key_8:
458 break; 458 break;
459 case Key_9: 459 case Key_9:
460 break; 460 break;
461 case Key_0: 461 case Key_0:
462 break; 462 break;
463 }; 463 };
464 e->accept(); 464 e->accept();
465 } 465 }
466} 466}
467 467
468void AdvancedFm::keyReleaseEvent( QKeyEvent *e) { 468void AdvancedFm::keyReleaseEvent( QKeyEvent *e) {
469 if( CurrentView()->hasFocus() ) 469 if( CurrentView()->hasFocus() )
470 e->ignore(); 470 e->ignore();
471} 471}
472 472
473 473
474void AdvancedFm::QPEButtonPushed() { 474void AdvancedFm::QPEButtonPushed() {
475 QString current = QPEApplication::qpeDir(); 475 QString current = QPEApplication::qpeDir();
476 chdir( current.latin1() ); 476 chdir( current.latin1() );
477 CurrentDir()->cd( current, TRUE); 477 CurrentDir()->cd( current, TRUE);
478 populateView(); 478 populateView();
479 update(); 479 update();
480} 480}
481 481
482void AdvancedFm::parsetab(const QString &fileName) { 482void AdvancedFm::parsetab(const QString &fileName) {
483 483
484 fileSystemTypeList.clear(); 484 fileSystemTypeList.clear();
485 fsList.clear(); 485 fsList.clear();
486 struct mntent *me; 486 struct mntent *me;
487 FILE *mntfp = setmntent( fileName.latin1(), "r" ); 487 FILE *mntfp = setmntent( fileName.latin1(), "r" );
488 if ( mntfp ) { 488 if ( mntfp ) {
489 while ( (me = getmntent( mntfp )) != 0 ) { 489 while ( (me = getmntent( mntfp )) != 0 ) {
490 QString deviceName = me->mnt_fsname; 490 QString deviceName = me->mnt_fsname;
491 QString filesystemType = me->mnt_type; 491 QString filesystemType = me->mnt_type;
492 QString mountDir = me->mnt_dir; 492 QString mountDir = me->mnt_dir;
493 if(deviceName != "none") { 493 if(deviceName != "none") {
494 if( fsList.contains(filesystemType) == 0 494 if( fsList.contains(filesystemType) == 0
495 & filesystemType.find("proc",0,TRUE) == -1 495 & filesystemType.find("proc",0,TRUE) == -1
496 & filesystemType.find("cramfs",0,TRUE) == -1 496 & filesystemType.find("cramfs",0,TRUE) == -1
497 & filesystemType.find("auto",0,TRUE) == -1) 497 & filesystemType.find("auto",0,TRUE) == -1)
498 fsList << filesystemType; 498 fsList << filesystemType;
499 fileSystemTypeList << mountDir+"::"+filesystemType; 499 fileSystemTypeList << mountDir+"::"+filesystemType;
500 } 500 }
501 } 501 }
502 } 502 }
503 endmntent( mntfp ); 503 endmntent( mntfp );
504} 504}
505 505
506QString AdvancedFm::getFileSystemType(const QString &currentText) { 506QString AdvancedFm::getFileSystemType(const QString &currentText) {
507 parsetab("/etc/mtab"); //why did TT forget filesystem type? 507 parsetab("/etc/mtab"); //why did TT forget filesystem type?
508 QString current = currentText;//.right( currentText.length()-1); 508 QString current = currentText;//.right( currentText.length()-1);
509 QString baseFs; 509 QString baseFs;
510 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it ) { 510 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it ) {
511 QString temp = (*it); 511 QString temp = (*it);
512 QString path = temp.left(temp.find("::",0,TRUE) ); 512 QString path = temp.left(temp.find("::",0,TRUE) );
513 path = path.right( path.length()-1); 513 path = path.right( path.length()-1);
514 if(path.isEmpty()) baseFs = temp.right( temp.length() - temp.find("::",0,TRUE) - 2); 514 if(path.isEmpty()) baseFs = temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
515 if( current.find( path,0,TRUE) != -1 && !path.isEmpty()) { 515 if( current.find( path,0,TRUE) != -1 && !path.isEmpty()) {
516 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2); 516 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
517 } 517 }
518 } 518 }
519 return baseFs; 519 return baseFs;
520} 520}
521 521
522QString AdvancedFm::getDiskSpace( const QString &path) { 522QString AdvancedFm::getDiskSpace( const QString &path) {
523 struct statfs fss; 523 struct statfs fss;
524 if ( !statfs( path.latin1(), &fss ) ) { 524 if ( !statfs( path.latin1(), &fss ) ) {
525 int blkSize = fss.f_bsize; 525 int blkSize = fss.f_bsize;
526 // int totalBlks = fs.f_blocks; 526 // int totalBlks = fs.f_blocks;
527 int availBlks = fss.f_bavail; 527 int availBlks = fss.f_bavail;
528 528
529 long mult = blkSize / 1024; 529 long mult = blkSize / 1024;
530 long div = 1024 / blkSize; 530 long div = 1024 / blkSize;
531 if ( !mult ) mult = 1; 531 if ( !mult ) mult = 1;
532 if ( !div ) div = 1; 532 if ( !div ) div = 1;
533 533
534 return QString::number(availBlks * mult / div); 534 return QString::number(availBlks * mult / div);
535 } 535 }
536 return ""; 536 return "";
537} 537}
538 538
539 539
540void AdvancedFm::showFileMenu() { 540void AdvancedFm::showFileMenu() {
541 QString curApp; 541 QString curApp;
542 curApp = CurrentView()->currentItem()->text(0); 542 curApp = CurrentView()->currentItem()->text(0);
543 543
544 MimeType mt( curApp ); 544 MimeType mt( curApp );
545 const AppLnk* app = mt.application(); 545 const AppLnk* app = mt.application();
546 QFile fi(curApp); 546 QFile fi(curApp);
547 QPopupMenu *m = new QPopupMenu(0); 547 QPopupMenu *m = new QPopupMenu(0);
548 QPopupMenu *n = new QPopupMenu(0); 548 QPopupMenu *n = new QPopupMenu(0);
549 // QPopupMenu *o = new QPopupMenu(0); 549 // QPopupMenu *o = new QPopupMenu(0);
550 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); 550 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
551 551
552 if ( QFileInfo(fi).isDir() ) { 552 if ( QFileInfo(fi).isDir() ) {
553 m->insertSeparator(); 553 m->insertSeparator();
554 m->insertItem( tr( "Change Directory" ), this, SLOT( doDirChange() )); 554 m->insertItem( tr( "Change Directory" ), this, SLOT( doDirChange() ));
555 } else { 555 } else {
556 556
557 if ( app ) 557 if ( app )
558 m->insertItem( app->pixmap(), tr( "Open in " 558 m->insertItem( app->pixmap(), tr( "Open in "
559 + app->name() ), this, SLOT( runThis() ) ); 559 + app->name() ), this, SLOT( runThis() ) );
560 else if( QFileInfo(fi).isExecutable() ) //damn opie doesnt like this 560 else if( QFileInfo(fi).isExecutable() ) //damn opie doesnt like this
561 m->insertItem( tr( "Execute" ), this, SLOT( runThis() ) ); 561 m->insertItem( tr( "Execute" ), this, SLOT( runThis() ) );
562 m->insertItem( Resource::loadPixmap( "txt" ), tr( "Open as text" ),this, SLOT( runText() ) ); 562 m->insertItem( Resource::loadPixmap( "txt" ), tr( "Open as text" ),this, SLOT( runText() ) );
563 } 563 }
564 564
565 m->insertItem(tr("Actions"),n); 565 m->insertItem(tr("Actions"),n);
566 n->insertItem( tr( "Make Directory" ), this, SLOT( makeDir() )); 566 n->insertItem( tr( "Make Directory" ), this, SLOT( makeDir() ));
567 567
568 n->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() )); 568 n->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() ));
569 569
570 n->insertSeparator(); 570 n->insertSeparator();
571 n->insertItem( tr( "Rename" ), this, SLOT( renameIt() )); 571 n->insertItem( tr( "Rename" ), this, SLOT( renameIt() ));
572 572
573 n->insertItem( tr( "Copy" ), this, SLOT( copy() )); 573 n->insertItem( tr( "Copy" ), this, SLOT( copy() ));
574 n->insertItem( tr( "Copy As" ), this, SLOT( copyAs() )); 574 n->insertItem( tr( "Copy As" ), this, SLOT( copyAs() ));
575 n->insertItem( tr( "Copy Same Dir" ), this, SLOT( copySameDir() )); 575 n->insertItem( tr( "Copy Same Dir" ), this, SLOT( copySameDir() ));
576 n->insertItem( tr( "Move" ), this, SLOT( move() )); 576 n->insertItem( tr( "Move" ), this, SLOT( move() ));
577 577
578 n->insertSeparator(); 578 n->insertSeparator();
579 n->insertItem( tr( "Delete" ), this, SLOT( doDelete() )); 579 n->insertItem( tr( "Delete" ), this, SLOT( doDelete() ));
580 m->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() )); 580 m->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() ));
581 581
582 m->insertItem( tr( "Run Command" ), this, SLOT( runCommand() )); 582 m->insertItem( tr( "Run Command" ), this, SLOT( runCommand() ));
583 m->insertItem( tr( "File Info" ), this, SLOT( fileStatus() )); 583 m->insertItem( tr( "File Info" ), this, SLOT( fileStatus() ));
584 584
585 m->insertSeparator(); 585 m->insertSeparator();
586 m->insertItem( tr( "Set Permissions" ), this, SLOT( filePerms() )); 586 m->insertItem( tr( "Set Permissions" ), this, SLOT( filePerms() ));
587 587
588#if defined(QT_QWS_OPIE) 588#if defined(QT_QWS_OPIE)
589 m->insertItem( tr( "Properties" ), this, SLOT( doProperties() )); 589 m->insertItem( tr( "Properties" ), this, SLOT( doProperties() ));
590#endif 590#endif
591 m->setCheckable(TRUE); 591 m->setCheckable(TRUE);
592 if (!b) 592 if (!b)
593 m->setItemChecked(m->idAt(0),TRUE); 593 m->setItemChecked(m->idAt(0),TRUE);
594 else 594 else
595 m->setItemChecked(m->idAt(0),FALSE); 595 m->setItemChecked(m->idAt(0),FALSE);
596 596
597 if(Ir::supported()) 597 if(Ir::supported())
598 m->insertItem( tr( "Beam File" ), this, SLOT( doBeam() )); 598 m->insertItem( tr( "Beam File" ), this, SLOT( doBeam() ));
599 m->setFocus(); 599 m->setFocus();
600 600
601 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) ); 601 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
602 602
603 if(m) delete m; 603 if(m) delete m;
604} 604}
605 605
606 606
607void AdvancedFm::cancelMenuTimer() { 607void AdvancedFm::cancelMenuTimer() {
608 608
609 if( menuTimer.isActive() ) 609 if( menuTimer.isActive() )
610 menuTimer.stop(); 610 menuTimer.stop();
611} 611}
612 612
613QString AdvancedFm::checkDiskSpace(const QString &path) { 613QString AdvancedFm::checkDiskSpace(const QString &path) {
614 struct statfs fss; 614 struct statfs fss;
615 if ( !statfs( path.latin1(), &fss ) ) { 615 if ( !statfs( path.latin1(), &fss ) ) {
616 int blkSize = fss.f_bsize; 616 int blkSize = fss.f_bsize;
617// int totalBlks = fs.f_blocks; 617// int totalBlks = fs.f_blocks;
618 int availBlks = fss.f_bavail; 618 int availBlks = fss.f_bavail;
619 619
620 long mult = blkSize / 1024; 620 long mult = blkSize / 1024;
621 long div = 1024 / blkSize; 621 long div = 1024 / blkSize;
622 if ( !mult ) mult = 1; 622 if ( !mult ) mult = 1;
623 if ( !div ) div = 1; 623 if ( !div ) div = 1;
624 624
625 625
626 return QString::number(availBlks * mult / div); 626 return QString::number(availBlks * mult / div);
627 } 627 }
628 return ""; 628 return "";
629} 629}
630 630
631void AdvancedFm::addToDocs() { 631void AdvancedFm::addToDocs() {
632 QStringList strListPaths = getPath(); 632 QStringList strListPaths = getPath();
633 QDir *thisDir = CurrentDir(); 633 QDir *thisDir = CurrentDir();
634 634
635 if( strListPaths.count() > 0) { 635 if( strListPaths.count() > 0) {
636 QString curFile; 636 QString curFile;
637 for ( QStringList::Iterator it = strListPaths.begin(); it != strListPaths.end(); ++it ) { 637 for ( QStringList::Iterator it = strListPaths.begin(); it != strListPaths.end(); ++it ) {
638 curFile = thisDir->canonicalPath()+"/"+(*it); 638 curFile = thisDir->canonicalPath()+"/"+(*it);
639// qDebug(curFile); 639// qDebug(curFile);
640 QFileInfo fi(curFile); 640 QFileInfo fi(curFile);
641 DocLnk f; 641 DocLnk f;
642// curFile.replace(QRegExp("\\..*"),""); 642// curFile.replace(QRegExp("\\..*"),"");
643 f.setName(fi.baseName() ); 643 f.setName(fi.baseName() );
644 f.setFile( curFile); 644 f.setFile( curFile);
645 f.writeLink(); 645 f.writeLink();
646 } 646 }
647 } 647 }
648} 648}
649 649
650 650
651void AdvancedFm::customDirsToMenu() { 651void AdvancedFm::customDirsToMenu() {
652 652
653 Config cfg("AdvancedFm"); 653 Config cfg("AdvancedFm");
654 cfg.setGroup("Menu"); 654 cfg.setGroup("Menu");
655 655
656 QStringList list = cfg.readListEntry( "CustomDir", ','); 656 QStringList list = cfg.readListEntry( "CustomDir", ',');
657 menuButton->insertItems(list ); 657 menuButton->insertItems(list );
658 658
659// for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) 659// for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
660// { 660// {
661// customDirMenu->insertItem(*it ); 661// customDirMenu->insertItem(*it );
662// } 662// }
663} 663}
664 664
665void AdvancedFm::dirMenuSelected(int item) { 665void AdvancedFm::dirMenuSelected(int item) {
666 switch(item) 666 switch(item)
667 { 667 {
668 668
669 case -21: 669 case -21:
670 case 0: 670 case 0:
671 addCustomDir(); 671 addCustomDir();
672 break; 672 break;
673 case -22: 673 case -22:
674 case 1: 674 case 1:
675 removeCustomDir(); 675 removeCustomDir();
676 break; 676 break;
677 default: 677 default:
678 { 678 {
679// gotoCustomDir( menuButton->text(item)); 679// gotoCustomDir( menuButton->text(item));
680// gotoCustomDir( customDirMenu->text(item)); 680// gotoCustomDir( customDirMenu->text(item));
681 } 681 }
682 break; 682 break;
683 683
684 }; 684 };
685} 685}
686 686
687void AdvancedFm::addCustomDir() { 687void AdvancedFm::addCustomDir() {
688 Config cfg("AdvancedFm"); 688 Config cfg("AdvancedFm");
689 cfg.setGroup("Menu"); 689 cfg.setGroup("Menu");
690 QString dir; 690 QString dir;
691 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)','); 691 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)',');
692 692
693 dir = CurrentDir()->canonicalPath(); 693 dir = CurrentDir()->canonicalPath();
694 694
695 bool addIt=true; 695 bool addIt=true;
696 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 696 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
697 if( dir == (*it)) { 697 if( dir == (*it)) {
698 addIt=false; 698 addIt=false;
699 } 699 }
700 } 700 }
701 if(addIt) { 701 if(addIt) {
702 menuButton->insertItem(dir); 702 menuButton->insertItem(dir);
703// customDirMenu->insertItem(dir); 703// customDirMenu->insertItem(dir);
704 list << dir; 704 list << dir;
705 } 705 }
706 706
707 cfg.writeEntry("CustomDir", list, ','); 707 cfg.writeEntry("CustomDir", list, ',');
708 cfg.write(); 708 cfg.write();
709} 709}
710 710
711void AdvancedFm::removeCustomDir() { 711void AdvancedFm::removeCustomDir() {
712// qDebug("remove custom dir"); 712// qDebug("remove custom dir");
713 Config cfg("AdvancedFm"); 713 Config cfg("AdvancedFm");
714 cfg.setGroup("Menu"); 714 cfg.setGroup("Menu");
715 QString dir; 715 QString dir;
716 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)','); 716 QStringList list = cfg.readListEntry( (const QString &)"CustomDir", (const QChar)',');
717 QStringList list2; 717 QStringList list2;
718 dir = CurrentDir()->canonicalPath(); 718 dir = CurrentDir()->canonicalPath();
719 int ramble=2; 719 int ramble=2;
720// int ramble=-24; 720// int ramble=-24;
721//first remove list 721//first remove list
722 if(list.grep(dir,true).isEmpty()) { 722 if(list.grep(dir,true).isEmpty()) {
723 QMessageBox::message(tr( "AdvancedFm" ), 723 QMessageBox::message(tr( "AdvancedFm" ),
724 tr("Cannot remove current directory\nfrom bookmarks.\nIt is not bookmarked!")); 724 tr("Cannot remove current directory\nfrom bookmarks.\nIt is not bookmarked!"));
725 } else { 725 } else {
726 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 726 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
727 if((*it) != dir) { 727 if((*it) != dir) {
728//current item is not our current dir, so add it to temp list 728//current item is not our current dir, so add it to temp list
729 list2 <<(*it); 729 list2 <<(*it);
730 } else { 730 } else {
731// customDirMenu->removeItem( ramble); 731// customDirMenu->removeItem( ramble);
732 menuButton->remove( ramble); 732 menuButton->remove( ramble);
733 733
734 } 734 }
735 ramble++; 735 ramble++;
736// ramble--; 736// ramble--;
737 } 737 }
738 738
739 cfg.writeEntry("CustomDir", list2, ','); 739 cfg.writeEntry("CustomDir", list2, ',');
740 cfg.write(); 740 cfg.write();
741 } 741 }
742// customDirsToMenu(); 742// customDirsToMenu();
743 743
744} 744}
745 745
746void AdvancedFm::gotoCustomDir(const QString &dir) { 746void AdvancedFm::gotoCustomDir(const QString &dir) {
747// qDebug("gotoCustomDir(const QString &dir) " +dir ); 747// qDebug("gotoCustomDir(const QString &dir) " +dir );
748// QString curDir = dir; 748// QString curDir = dir;
749// QDir *thisDir = CurrentDir(); 749// QDir *thisDir = CurrentDir();
750// if( curDir.isEmpty()) { 750// if( curDir.isEmpty()) {
751// } 751// }
752 if( dir == s_addBookmark) { 752 if( dir == s_addBookmark) {
753 addCustomDir(); 753 addCustomDir();
754 } 754 }
755 if( dir == s_removeBookmark) { 755 if( dir == s_removeBookmark) {
756 removeCustomDir( ); 756 removeCustomDir( );
757 } else { 757 } else {
758 gotoDirectory( dir); 758 gotoDirectory( dir);
759// if(QDir( curDir).exists() ) 759// if(QDir( curDir).exists() )
760// { 760// {
761// thisDir->setPath( curDir ); 761// thisDir->setPath( curDir );
762// chdir( curDir.latin1() ); 762// chdir( curDir.latin1() );
763// thisDir->cd( curDir, TRUE); 763// thisDir->cd( curDir, TRUE);
764// populateView(); 764// populateView();
765// } 765// }
766 } 766 }
767} 767}
768 768
769QDir *AdvancedFm::CurrentDir() { 769QDir *AdvancedFm::CurrentDir() {
770 770
771 if ( whichTab == 1) { 771 if ( whichTab == 1) {
772 return &currentDir; 772 return &currentDir;
773 } else { 773 } else {
774 return &currentRemoteDir; 774 return &currentRemoteDir;
775 } 775 }
776} 776}
777 777
778QDir *AdvancedFm::OtherDir() { 778QDir *AdvancedFm::OtherDir() {
779 if ( whichTab == 1) { 779 if ( whichTab == 1) {
780 return &currentRemoteDir; 780 return &currentRemoteDir;
781 } else { 781 } else {
782 return &currentDir; 782 return &currentDir;
783 } 783 }
784} 784}
785 785
786QListView * AdvancedFm::CurrentView() { 786QListView * AdvancedFm::CurrentView() {
787 if ( whichTab == 1) { 787 if ( whichTab == 1) {
788// qWarning("CurrentView Tab 1"); 788// qWarning("CurrentView Tab 1");
789 return Local_View; 789 return Local_View;
790 } else { 790 } else {
791// qWarning("CurrentView Tab 2"); 791// qWarning("CurrentView Tab 2");
792 return Remote_View; 792 return Remote_View;
793 } 793 }
794} 794}
795 795
796QListView * AdvancedFm::OtherView() { 796QListView * AdvancedFm::OtherView() {
797 if ( whichTab == 1) 797 if ( whichTab == 1)
798 return Remote_View; 798 return Remote_View;
799 else 799 else
800 return Local_View; 800 return Local_View;
801} 801}
802 802
803void AdvancedFm::setOtherTabCurrent() { 803void AdvancedFm::setOtherTabCurrent() {
804// qWarning("setOtherTabCurrent() %d", whichTab); 804// qWarning("setOtherTabCurrent() %d", whichTab);
805 if ( whichTab == 1) { 805 if ( whichTab == 1) {
806 TabWidget->setCurrentWidget(1); 806 TabWidget->setCurrentWidget(1);
807 } else { 807 } else {
808 TabWidget->setCurrentWidget(0); 808 TabWidget->setCurrentWidget(0);
809 } 809 }
810 OtherView()->setFocus(); 810 OtherView()->setFocus();
811 OtherView()->setSelected( CurrentView()->firstChild(), true); 811 OtherView()->setSelected( CurrentView()->firstChild(), true);
812} 812}
813 813
814void AdvancedFm::qcopReceive(const QCString &msg, const QByteArray &data) { 814void AdvancedFm::qcopReceive(const QCString &msg, const QByteArray &data) {
815// qDebug("qcop message "+msg ); 815// qDebug("qcop message "+msg );
816 QDataStream stream ( data, IO_ReadOnly ); 816 QDataStream stream ( data, IO_ReadOnly );
817 if ( msg == "openDirectory(QString)" ) { 817 if ( msg == "openDirectory(QString)" ) {
818// qDebug("received"); 818// qDebug("received");
819 QString file; 819 QString file;
820 stream >> file; 820 stream >> file;
821 gotoDirectory( (const QString &) file); 821 gotoDirectory( (const QString &) file);
822 } 822 }
823} 823}
824 824
825void AdvancedFm::setDocument(const QString &file) { 825void AdvancedFm::setDocument(const QString &file) {
826 gotoDirectory( file); 826 gotoDirectory( file);
827 827
828} 828}
829 829
830void AdvancedFm::gotoDirectory(const QString &file) { 830void AdvancedFm::gotoDirectory(const QString &file) {
831// qWarning("goto dir "+file); 831// qWarning("goto dir "+file);
832 QString curDir = file; 832 QString curDir = file;
833 QDir *thisDir = CurrentDir(); 833 QDir *thisDir = CurrentDir();
834 if(QDir( curDir).exists() ) { 834 if(QDir( curDir).exists() ) {
835 thisDir->setPath( curDir ); 835 thisDir->setPath( curDir );
836 chdir( curDir.latin1() ); 836 chdir( curDir.latin1() );
837 thisDir->cd( curDir, TRUE); 837 thisDir->cd( curDir, TRUE);
838 populateView(); 838 populateView();
839 } 839 }
840 else if(QFileInfo(curDir).exists()) { 840 else if(QFileInfo(curDir).exists()) {
841 QFileInfo fileInfo(curDir); 841 QFileInfo fileInfo(curDir);
842 curDir=fileInfo.dirPath(); 842 curDir=fileInfo.dirPath();
843 if(QDir( curDir).exists() ) { 843 if(QDir( curDir).exists() ) {
844 thisDir->setPath( curDir ); 844 thisDir->setPath( curDir );
845 chdir( curDir.latin1() ); 845 chdir( curDir.latin1() );
846 thisDir->cd( curDir, TRUE); 846 thisDir->cd( curDir, TRUE);
847 populateView(); 847 populateView();
848 } 848 }
849 findFile(file); 849 findFile(file);
850 } 850 }
851 851
852} 852}
853 853
854void AdvancedFm::findFile(const QString &fileName) { 854void AdvancedFm::findFile(const QString &fileName) {
855 QFileInfo fi(fileName); 855 QFileInfo fi(fileName);
856 QListView *thisView = CurrentView(); 856 QListView *thisView = CurrentView();
857 QListViewItemIterator it( thisView ); 857 QListViewItemIterator it( thisView );
858 for ( ; it.current(); ++it ) { 858 for ( ; it.current(); ++it ) {
859 if(it.current()->text(0) == fi.fileName()) { 859 if(it.current()->text(0) == fi.fileName()) {
860 it.current()->setSelected(true); 860 it.current()->setSelected(true);
861 thisView->ensureItemVisible(it.current()); 861 thisView->ensureItemVisible(it.current());
862 } 862 }
863 } 863 }
864} 864}
865 865
866void AdvancedFm::slotSwitchMenu(int ) { 866void AdvancedFm::slotSwitchMenu(int ) {
867// qDebug("Switch %d", item); 867// qDebug("Switch %d", item);
868 // viewMenu->setItemChecked(item, true); 868 // viewMenu->setItemChecked(item, true);
869} 869}
870 870
871void AdvancedFm::dealWithSchmooSchmaa(QWidget *w) { 871void AdvancedFm::dealWithSchmooSchmaa(QWidget *w) {
872 tabChanged( w); 872 tabChanged( w);
873 if( w == Local_View) { 873 if( w == Local_View) {
874 Remote_View->clearFocus(); 874 Remote_View->clearFocus();
875 } else { 875 } else {
876 Local_View->clearFocus(); 876 Local_View->clearFocus();
877 } 877 }
878} 878}
879 879
880void AdvancedFm::navigateToSelected() { 880void AdvancedFm::navigateToSelected() {
881 if( !CurrentView()->currentItem()) return; 881 if( !CurrentView()->currentItem()) return;
882 doDirChange(); 882 doDirChange();
883} 883}
diff --git a/noncore/apps/advancedfm/advancedfmData.cpp b/noncore/apps/advancedfm/advancedfmData.cpp
index 763ae34..f791c77 100644
--- a/noncore/apps/advancedfm/advancedfmData.cpp
+++ b/noncore/apps/advancedfm/advancedfmData.cpp
@@ -1,286 +1,286 @@
1/*************************************************************************** 1/***************************************************************************
2 advancedfmData.cpp 2 advancedfmData.cpp
3 ------------------- 3 -------------------
4** Created: Mon 09-23-2002 13:24:11 4** Created: Mon 09-23-2002 13:24:11
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12#include "advancedfm.h" 12#include "advancedfm.h"
13 13
14#include <qpe/storage.h> 14#include <qpe/storage.h>
15#include <qpe/qpeapplication.h> 15#include <qpe/qpeapplication.h>
16#include <qpe/resource.h> 16#include <qpe/resource.h>
17#include <qpe/menubutton.h> 17#include <qpe/menubutton.h>
18 18
19#include <qlayout.h> 19#include <qlayout.h>
20#include <qhbox.h> 20#include <qhbox.h>
21#include <qmenubar.h> 21#include <qmenubar.h>
22#include <qcombobox.h> 22#include <qcombobox.h>
23#include <qtoolbutton.h> 23#include <qtoolbutton.h>
24#include <qlineedit.h> 24#include <qlineedit.h>
25#include <qlistview.h> 25#include <qlistview.h>
26 26
27#include <sys/utsname.h> 27#include <sys/utsname.h>
28 28
29 29
30void AdvancedFm::init() { 30void AdvancedFm::init() {
31#if defined(QT_QWS_OPIE) 31#if defined(QT_QWS_OPIE)
32 qDebug("<<<<<<<<<<<<<<<<<<<<<<<< OPIE!!!"); 32 qDebug("<<<<<<<<<<<<<<<<<<<<<<<< OPIE!!!");
33#endif 33#endif
34 setCaption( tr( "AdvancedFm" ) ); 34 setCaption( tr( "AdvancedFm" ) );
35 35
36 QVBoxLayout *layout = new QVBoxLayout( this ); 36 QVBoxLayout *layout = new QVBoxLayout( this );
37 layout->setSpacing( 2); 37 layout->setSpacing( 2);
38 layout->setMargin( 2); 38 layout->setMargin( 2);
39 39
40 QMenuBar *menuBar = new QMenuBar(this); 40 QMenuBar *menuBar = new QMenuBar(this);
41 fileMenu = new QPopupMenu( this ); 41 fileMenu = new QPopupMenu( this );
42 viewMenu = new QPopupMenu( this ); 42 viewMenu = new QPopupMenu( this );
43// customDirMenu = new QPopupMenu( this ); 43// customDirMenu = new QPopupMenu( this );
44 44
45 layout->addWidget( menuBar ); 45 layout->addWidget( menuBar );
46 46
47 menuBar->insertItem( tr( "File" ), fileMenu); 47 menuBar->insertItem( tr( "File" ), fileMenu);
48 menuBar->insertItem( tr( "View" ), viewMenu); 48 menuBar->insertItem( tr( "View" ), viewMenu);
49 49
50 cdUpButton = new QToolButton( 0,"cdUpButton"); 50 cdUpButton = new QToolButton( 0,"cdUpButton");
51 cdUpButton->setPixmap(Resource::loadPixmap("up")); 51 cdUpButton->setPixmap(Resource::loadPixmap("up"));
52 cdUpButton->setAutoRaise( true ); 52 cdUpButton->setAutoRaise( true );
53 menuBar->insertItem( cdUpButton ); 53 menuBar->insertItem( cdUpButton );
54 54
55 55
56 QHBox *lineBox = new QHBox( this ); 56 QHBox *lineBox = new QHBox( this );
57 57
58 qpeDirButton= new QToolButton( 0,"QPEButton"); 58 qpeDirButton= new QToolButton( 0,"QPEButton");
59 qpeDirButton->setPixmap( Resource::loadPixmap("launcher/opielogo16x16"));//,"",this,"QPEButton"); 59 qpeDirButton->setPixmap( Resource::loadPixmap("launcher/opielogo16x16"));//,"",this,"QPEButton");
60 qpeDirButton->setAutoRaise( true ); 60 qpeDirButton->setAutoRaise( true );
61 menuBar->insertItem( qpeDirButton ); 61 menuBar->insertItem( qpeDirButton );
62 62
63 cfButton = new QToolButton( 0, "CFButton"); 63 cfButton = new QToolButton( 0, "CFButton");
64 cfButton->setPixmap(Resource::loadPixmap("cardmon/pcmcia")); 64 cfButton->setPixmap(Resource::loadPixmap("cardmon/pcmcia"));
65 cfButton->setAutoRaise( true ); 65 cfButton->setAutoRaise( true );
66 menuBar->insertItem( cfButton ); 66 menuBar->insertItem( cfButton );
67 67
68 sdButton = new QToolButton( 0, "SDButton"); 68 sdButton = new QToolButton( 0, "SDButton");
69 sdButton->setPixmap(Resource::loadPixmap("advancedfm/sdcard")); 69 sdButton->setPixmap(Resource::loadPixmap("advancedfm/sdcard"));
70 sdButton->setAutoRaise( true ); 70 sdButton->setAutoRaise( true );
71 menuBar->insertItem( sdButton ); 71 menuBar->insertItem( sdButton );
72 72
73 docButton = new QToolButton( 0,"docsButton"); 73 docButton = new QToolButton( 0,"docsButton");
74 docButton->setPixmap(Resource::loadPixmap("DocsIcon")); 74 docButton->setPixmap(Resource::loadPixmap("DocsIcon"));
75 docButton->setAutoRaise( true ); 75 docButton->setAutoRaise( true );
76 menuBar->insertItem( docButton ); 76 menuBar->insertItem( docButton );
77 77
78 homeButton = new QToolButton( 0, "homeButton"); 78 homeButton = new QToolButton( 0, "homeButton");
79 homeButton->setPixmap(Resource::loadPixmap("home")); 79 homeButton->setPixmap(Resource::loadPixmap("home"));
80 homeButton->setAutoRaise( true ); 80 homeButton->setAutoRaise( true );
81 menuBar->insertItem( homeButton ); 81 menuBar->insertItem( homeButton );
82 82
83 fileMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showMenuHidden() )); 83 fileMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showMenuHidden() ));
84 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE); 84 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
85 fileMenu->insertSeparator(); 85 fileMenu->insertSeparator();
86 fileMenu->insertItem( tr( "File Search" ), this, SLOT( openSearch() )); 86 fileMenu->insertItem( tr( "File Search" ), this, SLOT( openSearch() ));
87 fileMenu->insertSeparator(); 87 fileMenu->insertSeparator();
88 fileMenu->insertItem( tr( "Make Directory" ), this, SLOT( mkDir() )); 88 fileMenu->insertItem( tr( "Make Directory" ), this, SLOT( mkDir() ));
89 fileMenu->insertItem( tr( "Rename" ), this, SLOT( rn() )); 89 fileMenu->insertItem( tr( "Rename" ), this, SLOT( rn() ));
90 fileMenu->insertItem( tr( "Run Command" ), this, SLOT( runCommandStd() )); 90 fileMenu->insertItem( tr( "Run Command" ), this, SLOT( runCommandStd() ));
91 fileMenu->insertItem( tr( "Run Command with Output" ), this, SLOT( runCommand() )); 91 fileMenu->insertItem( tr( "Run Command with Output" ), this, SLOT( runCommand() ));
92 fileMenu->insertSeparator(); 92 fileMenu->insertSeparator();
93 fileMenu->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() )); 93 fileMenu->insertItem( tr( "Make Symlink" ), this, SLOT( mkSym() ));
94 fileMenu->insertItem( tr( "Select All" ), this, SLOT( selectAll() )); 94 fileMenu->insertItem( tr( "Select All" ), this, SLOT( selectAll() ));
95 fileMenu->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() )); 95 fileMenu->insertItem( tr( "Add To Documents" ), this, SLOT( addToDocs() ));
96 fileMenu->insertItem( tr( "Delete" ), this, SLOT( del() )); 96 fileMenu->insertItem( tr( "Delete" ), this, SLOT( del() ));
97 fileMenu->setCheckable(TRUE); 97 fileMenu->setCheckable(TRUE);
98 98
99 viewMenu->insertItem( tr( "Switch to View 1" ), this, SLOT( switchToLocalTab())); 99 viewMenu->insertItem( tr( "Switch to View 1" ), this, SLOT( switchToLocalTab()));
100 viewMenu->insertItem( tr( "Switch to View 2" ), this, SLOT( switchToRemoteTab())); 100 viewMenu->insertItem( tr( "Switch to View 2" ), this, SLOT( switchToRemoteTab()));
101// viewMenu->insertSeparator(); 101// viewMenu->insertSeparator();
102// viewMenu->insertItem( tr( "About" ), this, SLOT( doAbout() )); 102// viewMenu->insertItem( tr( "About" ), this, SLOT( doAbout() ));
103 viewMenu->setCheckable(true); 103 viewMenu->setCheckable(true);
104 viewMenu->setItemChecked( viewMenu->idAt(0), true); 104 viewMenu->setItemChecked( viewMenu->idAt(0), true);
105 viewMenu->setItemChecked( viewMenu->idAt(1), false); 105 viewMenu->setItemChecked( viewMenu->idAt(1), false);
106 106
107 s_addBookmark = tr("Bookmark Directory"); 107 s_addBookmark = tr("Bookmark Directory");
108 s_removeBookmark = tr("Remove Current Directory from Bookmarks"); 108 s_removeBookmark = tr("Remove Current Directory from Bookmarks");
109 109
110// menuButton->insertItem(""); 110// menuButton->insertItem("");
111 111
112// customDirMenu->insertItem(tr("Add This Directory")); 112// customDirMenu->insertItem(tr("Add This Directory"));
113// customDirMenu->insertItem(tr("Remove This Directory")); 113// customDirMenu->insertItem(tr("Remove This Directory"));
114// customDirMenu->insertSeparator(); 114// customDirMenu->insertSeparator();
115 115
116 menuButton = new MenuButton( lineBox ); 116 menuButton = new MenuButton( lineBox );
117 117
118 menuButton->setUseLabel(false); 118 menuButton->setUseLabel(false);
119 menuButton->setMaximumWidth( 20 ); 119 menuButton->setMaximumWidth( 20 );
120 menuButton->insertItem( s_addBookmark); 120 menuButton->insertItem( s_addBookmark);
121 menuButton->insertItem( s_removeBookmark); 121 menuButton->insertItem( s_removeBookmark);
122 menuButton->insertSeparator(); 122 menuButton->insertSeparator();
123 menuButton->setFocusPolicy(NoFocus); 123 menuButton->setFocusPolicy(NoFocus);
124 124
125 customDirsToMenu(); 125 customDirsToMenu();
126 126
127 currentPathCombo = new QComboBox( FALSE, lineBox, "currentPathCombo" ); 127 currentPathCombo = new QComboBox( FALSE, lineBox, "currentPathCombo" );
128 currentPathCombo->setEditable(TRUE); 128 currentPathCombo->setEditable(TRUE);
129 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); 129 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
130 currentPathCombo->setFocusPolicy(NoFocus); 130 currentPathCombo->setFocusPolicy(NoFocus);
131 layout->addWidget( lineBox ); 131 layout->addWidget( lineBox );
132 132
133 133
134 TabWidget = new OSplitter( Horizontal, this, "TabWidget" ); 134 TabWidget = new OSplitter( Horizontal, this, "TabWidget" );
135// TabWidget = new QTabWidget( this, "TabWidget" ); 135// TabWidget = new QTabWidget( this, "TabWidget" );
136 layout->addWidget( TabWidget, 4 ); 136 layout->addWidget( TabWidget, 4 );
137 137
138 tab = new QWidget( TabWidget, "tab" ); 138 tab = new QWidget( TabWidget, "tab" );
139 tabLayout = new QGridLayout( tab ); 139 tabLayout = new QGridLayout( tab );
140 tabLayout->setSpacing( 2); 140 tabLayout->setSpacing( 2);
141 tabLayout->setMargin( 2); 141 tabLayout->setMargin( 2);
142 142
143 Local_View = new QListView( tab, "Local_View" ); 143 Local_View = new QListView( tab, "Local_View" );
144 Local_View->addColumn( tr("File"),130); 144 Local_View->addColumn( tr("File"),130);
145 Local_View->addColumn( tr("Size"),-1); 145 Local_View->addColumn( tr("Size"),-1);
146 Local_View->setColumnAlignment(1,QListView::AlignRight); 146 Local_View->setColumnAlignment(1,QListView::AlignRight);
147 Local_View->addColumn( tr("Date"),-1); 147 Local_View->addColumn( tr("Date"),-1);
148 Local_View->setColumnAlignment(2,QListView::AlignRight); 148 Local_View->setColumnAlignment(2,QListView::AlignRight);
149 Local_View->setAllColumnsShowFocus(TRUE); 149 Local_View->setAllColumnsShowFocus(TRUE);
150 Local_View->setMultiSelection( TRUE ); 150 Local_View->setMultiSelection( TRUE );
151 Local_View->setSelectionMode(QListView::Extended); 151 Local_View->setSelectionMode(QListView::Extended);
152 Local_View->setFocusPolicy(StrongFocus); 152 Local_View->setFocusPolicy(StrongFocus);
153 Local_View->installEventFilter( this ); 153 Local_View->installEventFilter( this );
154 154
155 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold); 155 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold);
156 156
157 tabLayout->addWidget( Local_View, 0, 0 ); 157 tabLayout->addWidget( Local_View, 0, 0 );
158 158
159 TabWidget->addWidget( tab,"advancedfm/smFileBrowser.png", tr("1")); 159 TabWidget->addWidget( tab,"advancedfm/smFileBrowser.png", tr("1"));
160// TabWidget->insertTab( tab, tr("1")); 160// TabWidget->insertTab( tab, tr("1"));
161 161
162 tab_2 = new QWidget( TabWidget, "tab_2" ); 162 tab_2 = new QWidget( TabWidget, "tab_2" );
163 tabLayout_2 = new QGridLayout( tab_2 ); 163 tabLayout_2 = new QGridLayout( tab_2 );
164 tabLayout_2->setSpacing( 2); 164 tabLayout_2->setSpacing( 2);
165 tabLayout_2->setMargin( 2); 165 tabLayout_2->setMargin( 2);
166 166
167 Remote_View = new QListView( tab_2, "Remote_View" ); 167 Remote_View = new QListView( tab_2, "Remote_View" );
168 Remote_View->addColumn( tr("File"),130); 168 Remote_View->addColumn( tr("File"),130);
169 Remote_View->addColumn( tr("Size"),-1); 169 Remote_View->addColumn( tr("Size"),-1);
170 Remote_View->setColumnAlignment(1,QListView::AlignRight); 170 Remote_View->setColumnAlignment(1,QListView::AlignRight);
171 Remote_View->addColumn( tr("Date"),-1); 171 Remote_View->addColumn( tr("Date"),-1);
172 Remote_View->setColumnAlignment(2,QListView::AlignRight); 172 Remote_View->setColumnAlignment(2,QListView::AlignRight);
173 Remote_View->setAllColumnsShowFocus(TRUE); 173 Remote_View->setAllColumnsShowFocus(TRUE);
174 Remote_View->setMultiSelection( TRUE ); 174 Remote_View->setMultiSelection( TRUE );
175 Remote_View->setSelectionMode(QListView::Extended); 175 Remote_View->setSelectionMode(QListView::Extended);
176 Remote_View->setFocusPolicy(StrongFocus); 176 Remote_View->setFocusPolicy(StrongFocus);
177 Remote_View->installEventFilter( this ); 177 Remote_View->installEventFilter( this );
178 178
179 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold); 179 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold);
180 180
181 tabLayout_2->addWidget( Remote_View, 0, 0 ); 181 tabLayout_2->addWidget( Remote_View, 0, 0 );
182 182
183 TabWidget->addWidget( tab_2, "advancedfm/smFileBrowser.png",tr( "2")); 183 TabWidget->addWidget( tab_2, "advancedfm/smFileBrowser.png",tr( "2"));
184 TabWidget->setSizeChange( 370 ); 184 TabWidget->setSizeChange( 370 );
185// TabWidget->insertTab( tab_2, tr( "2")); 185// TabWidget->insertTab( tab_2, tr( "2"));
186 186
187 /* tab_3 = new QWidget( TabWidget, "tab_3" ); 187 /* tab_3 = new QWidget( TabWidget, "tab_3" );
188 tabLayout_3 = new QGridLayout( tab_3 ); 188 tabLayout_3 = new QGridLayout( tab_3 );
189 tabLayout_3->setSpacing( 2); 189 tabLayout_3->setSpacing( 2);
190 tabLayout_3->setMargin( 2); 190 tabLayout_3->setMargin( 2);
191 191
192 192
193 // OFileDialog fileDialog; 193 // OFileDialog fileDialog;
194 // fileDialog; 194 // fileDialog;
195 // fileSelector = new FileSelector( "*",tab_3, "fileselector" , FALSE, FALSE); //buggy 195 // fileSelector = new FileSelector( "*",tab_3, "fileselector" , FALSE, FALSE); //buggy
196 // fileDialog = new OFileDialog("bangalow", tab_3, 4, 2, "Bungalow"); 196 // fileDialog = new OFileDialog("bangalow", tab_3, 4, 2, "Bungalow");
197 // OFileSelector fileDialog = new OFileSelector( tab_3, 4, 2,"/"); 197 // OFileSelector fileDialog = new OFileSelector( tab_3, 4, 2,"/");
198 198
199 QListView *fileTree; 199 QListView *fileTree;
200 fileTree = new QListView( tab_3, "tree" ); 200 fileTree = new QListView( tab_3, "tree" );
201 201
202 202
203 tabLayout_3->addMultiCellWidget( fileTree, 0, 0, 0, 3 ); 203 tabLayout_3->addMultiCellWidget( fileTree, 0, 0, 0, 3 );
204 204
205 TabWidget->insertTab( tab_3, tr( "Remote" ) ); 205 TabWidget->insertTab( tab_3, tr( "Remote" ) );
206 */ 206 */
207 207
208 /////////////// 208 ///////////////
209 209
210 if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" )) 210 if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" ))
211 zaurusDevice=TRUE; 211 zaurusDevice=TRUE;
212 else 212 else
213 zaurusDevice=FALSE; 213 zaurusDevice=FALSE;
214 214
215 215
216 if( !StorageInfo::hasSd() || !StorageInfo::hasMmc()) { 216 if( !StorageInfo::hasSd() || !StorageInfo::hasMmc()) {
217 qDebug("not have sd"); 217 qDebug("not have sd");
218 sdButton->hide(); 218 sdButton->hide();
219 } 219 }
220 if( !StorageInfo::hasCf() ) { 220 if( !StorageInfo::hasCf() ) {
221 qDebug("not have cf"); 221 qDebug("not have cf");
222 cfButton->hide(); 222 cfButton->hide();
223 } 223 }
224 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 224 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
225 currentDir.setPath( QDir::currentDirPath()); 225 currentDir.setPath( QDir::currentDirPath());
226 226
227 currentRemoteDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 227 currentRemoteDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
228 currentRemoteDir.setPath( QDir::currentDirPath()); 228 currentRemoteDir.setPath( QDir::currentDirPath());
229 229
230 // b = TRUE; 230 // b = TRUE;
231 231
232 filterStr="*"; 232 filterStr="*";
233 b=FALSE; 233 b=FALSE;
234 showMenuHidden(); 234 showMenuHidden();
235 TabWidget->setCurrentWidget(0); 235 TabWidget->setCurrentWidget(0);
236 236
237} 237}
238 238
239void AdvancedFm::initConnections() 239void AdvancedFm::initConnections()
240{ 240{
241 241
242 connect( qApp,SIGNAL( aboutToQuit()), 242 connect( qApp,SIGNAL( aboutToQuit()),
243 this, SLOT( cleanUp()) ); 243 this, SLOT( cleanUp()) );
244 connect( qpeDirButton ,SIGNAL(released()), 244 connect( qpeDirButton ,SIGNAL(released()),
245 this,SLOT( QPEButtonPushed()) ); 245 this,SLOT( QPEButtonPushed()) );
246 connect( cfButton ,SIGNAL(released()), 246 connect( cfButton ,SIGNAL(released()),
247 this,SLOT( CFButtonPushed()) ); 247 this,SLOT( CFButtonPushed()) );
248 connect( sdButton ,SIGNAL(released()), 248 connect( sdButton ,SIGNAL(released()),
249 this,SLOT( SDButtonPushed()) ); 249 this,SLOT( SDButtonPushed()) );
250 connect( cdUpButton ,SIGNAL(released()), 250 connect( cdUpButton ,SIGNAL(released()),
251 this,SLOT( upDir()) ); 251 this,SLOT( upDir()) );
252 connect( docButton,SIGNAL(released()), 252 connect( docButton,SIGNAL(released()),
253 this,SLOT( docButtonPushed()) ); 253 this,SLOT( docButtonPushed()) );
254 connect( homeButton,SIGNAL(released()), 254 connect( homeButton,SIGNAL(released()),
255 this,SLOT( homeButtonPushed()) ); 255 this,SLOT( homeButtonPushed()) );
256 connect( currentPathCombo, SIGNAL( activated( const QString & ) ), 256 connect( currentPathCombo, SIGNAL( activated(const QString&) ),
257 this, SLOT( currentPathComboActivated( const QString & ) ) ); 257 this, SLOT( currentPathComboActivated(const QString&) ) );
258 258
259 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()), 259 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()),
260 this,SLOT(currentPathComboChanged())); 260 this,SLOT(currentPathComboChanged()));
261 261
262 connect( Local_View, SIGNAL( clicked( QListViewItem*)), 262 connect( Local_View, SIGNAL( clicked(QListViewItem*)),
263 this,SLOT( ListClicked(QListViewItem *)) ); 263 this,SLOT( ListClicked(QListViewItem*)) );
264 264
265 connect( Local_View, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), 265 connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
266 this,SLOT( ListPressed(int, QListViewItem *, const QPoint&, int)) ); 266 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
267 267
268 connect( Local_View, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) ); 268 connect( Local_View, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) );
269 269
270 connect( Remote_View, SIGNAL( clicked( QListViewItem*)), 270 connect( Remote_View, SIGNAL( clicked(QListViewItem*)),
271 this,SLOT( ListClicked(QListViewItem *)) ); 271 this,SLOT( ListClicked(QListViewItem*)) );
272 connect( Remote_View, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), 272 connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
273 this,SLOT( ListPressed(int, QListViewItem *, const QPoint&, int)) ); 273 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
274 274
275 connect( TabWidget,SIGNAL(currentChanged(QWidget *)), 275 connect( TabWidget,SIGNAL(currentChanged(QWidget*)),
276 this,SLOT(tabChanged(QWidget*))); 276 this,SLOT(tabChanged(QWidget*)));
277 277
278 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) ); 278 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) );
279 279
280 connect( menuButton, SIGNAL( selected(const QString &)), SLOT(gotoCustomDir(const QString&))); 280 connect( menuButton, SIGNAL( selected(const QString&)), SLOT(gotoCustomDir(const QString&)));
281// connect( menuButton, SIGNAL( selected( int)), SLOT( dirMenuSelected(int))); 281// connect( menuButton, SIGNAL( selected(int)), SLOT( dirMenuSelected(int)));
282 connect( viewMenu, SIGNAL( activated(int )), this, SLOT(slotSwitchMenu(int ))); 282 connect( viewMenu, SIGNAL( activated(int)), this, SLOT(slotSwitchMenu(int)));
283// connect( customDirMenu, SIGNAL( activated(int)), this, SLOT( dirMenuSelected(int))); 283// connect( customDirMenu, SIGNAL( activated(int)), this, SLOT( dirMenuSelected(int)));
284 284
285} 285}
286 286
diff --git a/noncore/apps/advancedfm/advancedfmMenu.cpp b/noncore/apps/advancedfm/advancedfmMenu.cpp
index 9ad1146..9e740d0 100644
--- a/noncore/apps/advancedfm/advancedfmMenu.cpp
+++ b/noncore/apps/advancedfm/advancedfmMenu.cpp
@@ -1,836 +1,836 @@
1/*************************************************************************** 1/***************************************************************************
2 AdvancedFm.cpp 2 AdvancedFm.cpp
3 ------------------- 3 -------------------
4 ** Created: Sat Mar 9 23:33:09 2002 4 ** Created: Sat Mar 9 23:33:09 2002
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12#include "advancedfm.h" 12#include "advancedfm.h"
13#include "output.h" 13#include "output.h"
14#include "filePermissions.h" 14#include "filePermissions.h"
15 15
16#include <qpe/lnkproperties.h> 16#include <qpe/lnkproperties.h>
17#include <qpe/qpeapplication.h> 17#include <qpe/qpeapplication.h>
18#include <qpe/applnk.h> 18#include <qpe/applnk.h>
19 19
20#include <qmessagebox.h> 20#include <qmessagebox.h>
21 21
22 22
23#include <qpopupmenu.h> 23#include <qpopupmenu.h>
24#include <qlistview.h> 24#include <qlistview.h>
25 25
26#include <errno.h> 26#include <errno.h>
27#include <stdlib.h> 27#include <stdlib.h>
28#include <unistd.h> 28#include <unistd.h>
29#include <sys/stat.h> 29#include <sys/stat.h>
30#include <dirent.h> 30#include <dirent.h>
31#include <sys/sendfile.h> 31#include <sys/sendfile.h>
32#include <fcntl.h> 32#include <fcntl.h>
33 33
34 34
35void AdvancedFm::doDirChange() { 35void AdvancedFm::doDirChange() {
36 QString pathItem = CurrentView()->currentItem()->text(0); 36 QString pathItem = CurrentView()->currentItem()->text(0);
37 if( pathItem == "../") { 37 if( pathItem == "../") {
38 ListClicked( CurrentView()->currentItem()); 38 ListClicked( CurrentView()->currentItem());
39 } else { 39 } else {
40 if( pathItem.find(" -> ",0,TRUE) != -1) 40 if( pathItem.find(" -> ",0,TRUE) != -1)
41 pathItem = dealWithSymName((const QString&)pathItem)+"/"; 41 pathItem = dealWithSymName((const QString&)pathItem)+"/";
42// qWarning(pathItem); 42// qWarning(pathItem);
43 gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) ); 43 gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) );
44 } 44 }
45} 45}
46 46
47void AdvancedFm::showMenuHidden() { 47void AdvancedFm::showMenuHidden() {
48 if (b) { 48 if (b) {
49 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 49 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
50 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 50 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
51 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE); 51 fileMenu->setItemChecked( fileMenu->idAt(0),TRUE);
52 } else { 52 } else {
53 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 53 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
54 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 54 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
55 fileMenu->setItemChecked( fileMenu->idAt(0),FALSE); 55 fileMenu->setItemChecked( fileMenu->idAt(0),FALSE);
56 } 56 }
57 b = !b; 57 b = !b;
58 populateView(); 58 populateView();
59} 59}
60 60
61void AdvancedFm::showHidden() { 61void AdvancedFm::showHidden() {
62 if (b) { 62 if (b) {
63 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 63 CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
64 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 64 OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
65 } else { 65 } else {
66 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 66 CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
67 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 67 OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
68 } 68 }
69 populateView(); 69 populateView();
70} 70}
71 71
72QString AdvancedFm::dealWithSymName(const QString &fileName) { 72QString AdvancedFm::dealWithSymName(const QString &fileName) {
73 QString strItem = fileName; 73 QString strItem = fileName;
74 return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4); 74 return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4);
75} 75}
76 76
77void AdvancedFm::runThis() { 77void AdvancedFm::runThis() {
78 if( !CurrentView()->currentItem()) return; 78 if( !CurrentView()->currentItem()) return;
79 QString fs; 79 QString fs;
80 QDir *thisDir = CurrentDir(); 80 QDir *thisDir = CurrentDir();
81 81
82 QString curFile = CurrentView()->currentItem()->text(0); 82 QString curFile = CurrentView()->currentItem()->text(0);
83 QString path = thisDir->canonicalPath(); 83 QString path = thisDir->canonicalPath();
84 84
85 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink 85 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
86 86
87 curFile = dealWithSymName((const QString&)curFile); 87 curFile = dealWithSymName((const QString&)curFile);
88 88
89 if(curFile != "../") { 89 if(curFile != "../") {
90 90
91 fs = getFileSystemType((const QString &) path); 91 fs = getFileSystemType((const QString &) path);
92 QFileInfo fileInfo( path + "/" + curFile); 92 QFileInfo fileInfo( path + "/" + curFile);
93// qDebug( fileInfo.owner()); 93// qDebug( fileInfo.owner());
94 94
95 if( (fileInfo.permission( QFileInfo::ExeUser) 95 if( (fileInfo.permission( QFileInfo::ExeUser)
96 | fileInfo.permission( QFileInfo::ExeGroup) 96 | fileInfo.permission( QFileInfo::ExeGroup)
97 | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) { 97 | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) {
98 | fs == "vfat" && fileInfo.filePath().contains("/bin") ) { 98 | fs == "vfat" && fileInfo.filePath().contains("/bin") ) {
99 QCopEnvelope e("QPE/System", "execute(QString)" ); 99 QCopEnvelope e("QPE/System", "execute(QString)" );
100 e << curFile; 100 e << curFile;
101 } else { 101 } else {
102 curFile = path + "/" + curFile; 102 curFile = path + "/" + curFile;
103 DocLnk nf(curFile); 103 DocLnk nf(curFile);
104 QString execStr = nf.exec(); 104 QString execStr = nf.exec();
105// qDebug( execStr); 105// qDebug( execStr);
106 if( execStr.isEmpty() ) { 106 if( execStr.isEmpty() ) {
107 } else { 107 } else {
108 nf.execute(); 108 nf.execute();
109 } 109 }
110 } 110 }
111 } 111 }
112} 112}
113 113
114void AdvancedFm::runText() { 114void AdvancedFm::runText() {
115 if( !CurrentView()->currentItem()) return; 115 if( !CurrentView()->currentItem()) return;
116 QString curFile = CurrentView()->currentItem()->text(0); 116 QString curFile = CurrentView()->currentItem()->text(0);
117 if(curFile != "../") { 117 if(curFile != "../") {
118 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink 118 if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink
119 curFile = dealWithSymName((const QString&)curFile); 119 curFile = dealWithSymName((const QString&)curFile);
120 curFile = CurrentDir()->canonicalPath()+"/"+curFile; 120 curFile = CurrentDir()->canonicalPath()+"/"+curFile;
121 QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" ); 121 QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" );
122 e << curFile; 122 e << curFile;
123 } 123 }
124} 124}
125 125
126void AdvancedFm::makeDir() { 126void AdvancedFm::makeDir() {
127 InputDialog *fileDlg; 127 InputDialog *fileDlg;
128 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); 128 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
129 fileDlg->exec(); 129 fileDlg->exec();
130 if( fileDlg->result() == 1 ) { 130 if( fileDlg->result() == 1 ) {
131 QDir *thisDir = CurrentDir(); 131 QDir *thisDir = CurrentDir();
132 QString filename = fileDlg->LineEdit1->text(); 132 QString filename = fileDlg->LineEdit1->text();
133 thisDir->mkdir( thisDir->canonicalPath()+"/"+filename); 133 thisDir->mkdir( thisDir->canonicalPath()+"/"+filename);
134 } 134 }
135 populateView(); 135 populateView();
136} 136}
137 137
138void AdvancedFm::doDelete() { 138void AdvancedFm::doDelete() {
139 QStringList curFileList = getPath(); 139 QStringList curFileList = getPath();
140 bool doMsg=true; 140 bool doMsg=true;
141 int count = curFileList.count(); 141 int count = curFileList.count();
142 if( count > 0) { 142 if( count > 0) {
143 if(count > 1 ) { 143 if(count > 1 ) {
144 QString msg; 144 QString msg;
145 msg=tr("Really delete\n%1 files?").arg(count); 145 msg=tr("Really delete\n%1 files?").arg(count);
146 switch ( QMessageBox::warning(this,tr("Delete"),msg 146 switch ( QMessageBox::warning(this,tr("Delete"),msg
147 ,tr("Yes"),tr("No"),0,0,1) ) 147 ,tr("Yes"),tr("No"),0,0,1) )
148 { 148 {
149 case 0: 149 case 0:
150 doMsg=false; 150 doMsg=false;
151 break; 151 break;
152 case 1: 152 case 1:
153 return; 153 return;
154 break; 154 break;
155 }; 155 };
156 } 156 }
157 157
158 QString myFile; 158 QString myFile;
159 159
160 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 160 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
161 myFile = (*it); 161 myFile = (*it);
162 if( myFile.find(" -> ",0,TRUE) != -1) 162 if( myFile.find(" -> ",0,TRUE) != -1)
163 myFile = myFile.left( myFile.find(" -> ",0,TRUE)); 163 myFile = myFile.left( myFile.find(" -> ",0,TRUE));
164 164
165 QString f = CurrentDir()->canonicalPath(); 165 QString f = CurrentDir()->canonicalPath();
166 if(f.right(1).find("/",0,TRUE) == -1) 166 if(f.right(1).find("/",0,TRUE) == -1)
167 f += "/"; 167 f += "/";
168 f += myFile; 168 f += myFile;
169 if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) { 169 if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) {
170 //if file is a directory 170 //if file is a directory
171 171
172 switch ( QMessageBox::warning( this, tr("Delete Directory?"), 172 switch ( QMessageBox::warning( this, tr("Delete Directory?"),
173 tr("Really delete %1\nand all it's contents ?" ).arg( f ) , 173 tr("Really delete %1\nand all it's contents ?" ).arg( f ) ,
174 tr("Yes"), tr("No"), 0, 0, 1) ) { 174 tr("Yes"), tr("No"), 0, 0, 1) ) {
175 case 0: 175 case 0:
176 { 176 {
177 f=f.left(f.length()-1); 177 f=f.left(f.length()-1);
178 QString cmd="rm -rf "+f; 178 QString cmd="rm -rf "+f;
179 startProcess( (const QString)cmd.latin1() ); 179 startProcess( (const QString)cmd.latin1() );
180 populateView(); 180 populateView();
181 } 181 }
182 break; 182 break;
183 case 1: 183 case 1:
184 // exit 184 // exit
185 break; 185 break;
186 }; 186 };
187 187
188 } else { 188 } else {
189 if(doMsg) { 189 if(doMsg) {
190 switch ( QMessageBox::warning(this,tr("Delete"), 190 switch ( QMessageBox::warning(this,tr("Delete"),
191 tr("Really delete\n%1?").arg( myFile ), 191 tr("Really delete\n%1?").arg( myFile ),
192 tr("Yes"), tr("No"), 0, 0, 1) ) { 192 tr("Yes"), tr("No"), 0, 0, 1) ) {
193 case 1: 193 case 1:
194 return; 194 return;
195 break; 195 break;
196 }; 196 };
197 } 197 }
198 198
199 QString cmd="rm "+f; 199 QString cmd="rm "+f;
200 QFile file(f); 200 QFile file(f);
201 QFileInfo fi(myFile); 201 QFileInfo fi(myFile);
202 if( fi.fileName().find("../",0,TRUE)==-1) { 202 if( fi.fileName().find("../",0,TRUE)==-1) {
203// qDebug("remove link files "+myFile); 203// qDebug("remove link files "+myFile);
204 204
205// DocLnk lnk(f); 205// DocLnk lnk(f);
206 DocLnk *lnk; 206 DocLnk *lnk;
207 lnk = new DocLnk(f); 207 lnk = new DocLnk(f);
208// qDebug("Deleting doclnk " + lnk->linkFile()); 208// qDebug("Deleting doclnk " + lnk->linkFile());
209 if(lnk->isValid()) 209 if(lnk->isValid())
210 lnk->removeLinkFile(); 210 lnk->removeLinkFile();
211 // delete lnk; 211 // delete lnk;
212 file.remove(); 212 file.remove();
213 } 213 }
214 } 214 }
215 } 215 }
216 } 216 }
217 populateView(); 217 populateView();
218} 218}
219 219
220void AdvancedFm::filePerms() { 220void AdvancedFm::filePerms() {
221 QStringList curFileList = getPath(); 221 QStringList curFileList = getPath();
222 QString filePath; 222 QString filePath;
223 223
224 filePath = CurrentDir()->canonicalPath()+"/"; 224 filePath = CurrentDir()->canonicalPath()+"/";
225 225
226 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 226 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
227 filePermissions *filePerm; 227 filePermissions *filePerm;
228 filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it)); 228 filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it));
229 QPEApplication::execDialog( filePerm ); 229 QPEApplication::execDialog( filePerm );
230 if( filePerm ) 230 if( filePerm )
231 delete filePerm; 231 delete filePerm;
232 } 232 }
233 populateView(); 233 populateView();
234} 234}
235 235
236void AdvancedFm::doProperties() { 236void AdvancedFm::doProperties() {
237#if defined(QT_QWS_OPIE) 237#if defined(QT_QWS_OPIE)
238 238
239 QStringList curFileList = getPath(); 239 QStringList curFileList = getPath();
240 240
241 QString filePath; 241 QString filePath;
242 filePath = CurrentDir()->canonicalPath()+"/"; 242 filePath = CurrentDir()->canonicalPath()+"/";
243 243
244// qDebug("%d",curFileList.count()); 244// qDebug("%d",curFileList.count());
245 245
246 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 246 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
247// qDebug((filePath+*it)); 247// qDebug((filePath+*it));
248 DocLnk lnk( (filePath+*it)); 248 DocLnk lnk( (filePath+*it));
249 LnkProperties prop( &lnk ); 249 LnkProperties prop( &lnk );
250 QPEApplication::execDialog( &prop ); 250 QPEApplication::execDialog( &prop );
251 } 251 }
252#endif 252#endif
253 253
254} 254}
255 255
256void AdvancedFm::upDir() { 256void AdvancedFm::upDir() {
257 QDir *thisDir = CurrentDir(); 257 QDir *thisDir = CurrentDir();
258 QString current = thisDir->canonicalPath(); 258 QString current = thisDir->canonicalPath();
259 QDir dir(current); 259 QDir dir(current);
260 dir.cdUp(); 260 dir.cdUp();
261 current = dir.canonicalPath(); 261 current = dir.canonicalPath();
262 chdir( current.latin1() ); 262 chdir( current.latin1() );
263 thisDir->cd( current, TRUE); 263 thisDir->cd( current, TRUE);
264 264
265 populateView(); 265 populateView();
266 update(); 266 update();
267} 267}
268 268
269void AdvancedFm::copy() { 269void AdvancedFm::copy() {
270 qApp->processEvents(); 270 qApp->processEvents();
271 QStringList curFileList = getPath(); 271 QStringList curFileList = getPath();
272 272
273 QDir *thisDir = CurrentDir(); 273 QDir *thisDir = CurrentDir();
274 QDir *thatDir = OtherDir(); 274 QDir *thatDir = OtherDir();
275 275
276 bool doMsg=true; 276 bool doMsg=true;
277 int count=curFileList.count(); 277 int count=curFileList.count();
278 if( count > 0) { 278 if( count > 0) {
279 if(count > 1 ){ 279 if(count > 1 ){
280 QString msg; 280 QString msg;
281 msg=tr("Really copy\n%1 files?").arg(count); 281 msg=tr("Really copy\n%1 files?").arg(count);
282 switch ( QMessageBox::warning(this,tr("Copy"),msg 282 switch ( QMessageBox::warning(this,tr("Copy"),msg
283 ,tr("Yes"),tr("No"),0,0,1) ) 283 ,tr("Yes"),tr("No"),0,0,1) )
284 { 284 {
285 case 0: 285 case 0:
286 doMsg=false; 286 doMsg=false;
287 break; 287 break;
288 case 1: 288 case 1:
289 return; 289 return;
290 break; 290 break;
291 }; 291 };
292 } 292 }
293 293
294 QString curFile, item, destFile; 294 QString curFile, item, destFile;
295 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 295 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
296 item=(*it); 296 item=(*it);
297 if(item.find("->",0,TRUE)) //symlink 297 if(item.find("->",0,TRUE)) //symlink
298 item = item.left(item.find("->",0,TRUE)); 298 item = item.left(item.find("->",0,TRUE));
299 299
300 curFile = thisDir->canonicalPath()+"/"+ item; 300 curFile = thisDir->canonicalPath()+"/"+ item;
301 destFile = thatDir->canonicalPath()+"/"+ item; 301 destFile = thatDir->canonicalPath()+"/"+ item;
302 302
303// qDebug("Destination file is "+destFile); 303// qDebug("Destination file is "+destFile);
304// qDebug("CurrentFile file is " + curFile); 304// qDebug("CurrentFile file is " + curFile);
305 305
306 QFile f(destFile); 306 QFile f(destFile);
307 if( f.exists()) { 307 if( f.exists()) {
308 if(doMsg) { 308 if(doMsg) {
309 switch ( QMessageBox::warning(this,tr("File Exists!"), 309 switch ( QMessageBox::warning(this,tr("File Exists!"),
310 tr("%1 exists. Ok to overwrite?").arg( item ), 310 tr("%1 exists. Ok to overwrite?").arg( item ),
311 tr("Yes"),tr("No"),0,0,1) ) { 311 tr("Yes"),tr("No"),0,0,1) ) {
312 case 1: 312 case 1:
313 return; 313 return;
314 break; 314 break;
315 }; 315 };
316 } 316 }
317 f.remove(); 317 f.remove();
318 } 318 }
319 319
320 if( !copyFile( curFile, destFile) ) { 320 if( !copyFile( curFile, destFile) ) {
321 QMessageBox::message("AdvancedFm", 321 QMessageBox::message("AdvancedFm",
322 tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) ); 322 tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) );
323 return; 323 return;
324 } 324 }
325 } 325 }
326 setOtherTabCurrent(); 326 setOtherTabCurrent();
327 rePopulate(); 327 rePopulate();
328 } 328 }
329} 329}
330 330
331void AdvancedFm::copyAs() { 331void AdvancedFm::copyAs() {
332 qApp->processEvents(); 332 qApp->processEvents();
333 333
334 QStringList curFileList = getPath(); 334 QStringList curFileList = getPath();
335 QString curFile, item; 335 QString curFile, item;
336 InputDialog *fileDlg; 336 InputDialog *fileDlg;
337 337
338 QDir *thisDir = CurrentDir(); 338 QDir *thisDir = CurrentDir();
339 QDir *thatDir = OtherDir(); 339 QDir *thatDir = OtherDir();
340 340
341 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 341 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
342 QString destFile; 342 QString destFile;
343 item=(*it); 343 item=(*it);
344 curFile = thisDir->canonicalPath()+"/"+(*it); 344 curFile = thisDir->canonicalPath()+"/"+(*it);
345 fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0); 345 fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0);
346 346
347 fileDlg->setInputText((const QString &) destFile ); 347 fileDlg->setInputText((const QString &) destFile );
348 fileDlg->exec(); 348 fileDlg->exec();
349 349
350 if( fileDlg->result() == 1 ) { 350 if( fileDlg->result() == 1 ) {
351 QString filename = fileDlg->LineEdit1->text(); 351 QString filename = fileDlg->LineEdit1->text();
352 destFile = thatDir->canonicalPath()+"/"+filename; 352 destFile = thatDir->canonicalPath()+"/"+filename;
353 353
354 QFile f( destFile); 354 QFile f( destFile);
355 if( f.exists()) { 355 if( f.exists()) {
356 switch (QMessageBox::warning(this,tr("File Exists!"), 356 switch (QMessageBox::warning(this,tr("File Exists!"),
357 item+tr("\nexists. Ok to overwrite?"), 357 item+tr("\nexists. Ok to overwrite?"),
358 tr("Yes"),tr("No"),0,0,1) ) { 358 tr("Yes"),tr("No"),0,0,1) ) {
359 case 0: 359 case 0:
360 f.remove(); 360 f.remove();
361 break; 361 break;
362 case 1: 362 case 1:
363 return; 363 return;
364 break; 364 break;
365 }; 365 };
366 } 366 }
367 if( !copyFile( curFile, destFile) ) { 367 if( !copyFile( curFile, destFile) ) {
368 QMessageBox::message("AdvancedFm",tr("Could not copy\n") 368 QMessageBox::message("AdvancedFm",tr("Could not copy\n")
369 +curFile +tr("to\n")+destFile); 369 +curFile +tr("to\n")+destFile);
370 return; 370 return;
371 } 371 }
372 } 372 }
373 delete fileDlg; 373 delete fileDlg;
374 374
375 } 375 }
376 rePopulate(); 376 rePopulate();
377 setOtherTabCurrent(); 377 setOtherTabCurrent();
378} 378}
379 379
380void AdvancedFm::copySameDir() { 380void AdvancedFm::copySameDir() {
381 qApp->processEvents(); 381 qApp->processEvents();
382 QStringList curFileList = getPath(); 382 QStringList curFileList = getPath();
383 QString curFile, item, destFile; 383 QString curFile, item, destFile;
384 InputDialog *fileDlg; 384 InputDialog *fileDlg;
385 385
386 QDir *thisDir = CurrentDir(); 386 QDir *thisDir = CurrentDir();
387 387
388 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 388 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
389 item=(*it); 389 item=(*it);
390 curFile = thisDir->canonicalPath()+"/"+ item; 390 curFile = thisDir->canonicalPath()+"/"+ item;
391 391
392 fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0); 392 fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0);
393 fileDlg->setInputText((const QString &) destFile ); 393 fileDlg->setInputText((const QString &) destFile );
394 fileDlg->exec(); 394 fileDlg->exec();
395 395
396 if( fileDlg->result() == 1 ) { 396 if( fileDlg->result() == 1 ) {
397 397
398 QString filename = fileDlg->LineEdit1->text(); 398 QString filename = fileDlg->LineEdit1->text();
399 destFile = thisDir->canonicalPath()+"/"+filename; 399 destFile = thisDir->canonicalPath()+"/"+filename;
400 400
401 QFile f(destFile); 401 QFile f(destFile);
402 if( f.exists()) { 402 if( f.exists()) {
403 switch (QMessageBox::warning(this,tr("Delete"), 403 switch (QMessageBox::warning(this,tr("Delete"),
404 destFile+tr(" already exists.\nDo you really want to delete it?"), 404 destFile+tr(" already exists.\nDo you really want to delete it?"),
405 tr("Yes"),tr("No"),0,0,1) ) { 405 tr("Yes"),tr("No"),0,0,1) ) {
406 case 0: 406 case 0:
407 407
408 f.remove(); 408 f.remove();
409 break; 409 break;
410 case 1: 410 case 1:
411 return; 411 return;
412 break; 412 break;
413 }; 413 };
414 } 414 }
415 if(!copyFile( curFile,destFile) ) { 415 if(!copyFile( curFile,destFile) ) {
416 QMessageBox::message("AdvancedFm",tr("Could not copy\n") 416 QMessageBox::message("AdvancedFm",tr("Could not copy\n")
417 +curFile +tr("to\n")+destFile); 417 +curFile +tr("to\n")+destFile);
418 return; 418 return;
419 } 419 }
420 420
421// qDebug("copy "+curFile+" as "+destFile); 421// qDebug("copy "+curFile+" as "+destFile);
422 } 422 }
423 delete fileDlg; 423 delete fileDlg;
424 } 424 }
425 rePopulate(); 425 rePopulate();
426} 426}
427 427
428void AdvancedFm::move() { 428void AdvancedFm::move() {
429 qApp->processEvents(); 429 qApp->processEvents();
430 430
431 QStringList curFileList = getPath(); 431 QStringList curFileList = getPath();
432 if( curFileList.count() > 0) { 432 if( curFileList.count() > 0) {
433 QString curFile, destFile, item; 433 QString curFile, destFile, item;
434 434
435 QDir *thisDir = CurrentDir(); 435 QDir *thisDir = CurrentDir();
436 QDir *thatDir = OtherDir(); 436 QDir *thatDir = OtherDir();
437 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 437 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
438 item=(*it); 438 item=(*it);
439 QString destFile = thatDir->canonicalPath(); 439 QString destFile = thatDir->canonicalPath();
440 440
441 if(destFile.right(1).find("/",0,TRUE) == -1) 441 if(destFile.right(1).find("/",0,TRUE) == -1)
442 destFile+="/"; 442 destFile+="/";
443 destFile += item; 443 destFile += item;
444// qDebug("Destination file is "+destFile); 444// qDebug("Destination file is "+destFile);
445 445
446 curFile = thisDir->canonicalPath(); 446 curFile = thisDir->canonicalPath();
447 if(curFile.right(1).find("/",0,TRUE) == -1) 447 if(curFile.right(1).find("/",0,TRUE) == -1)
448 curFile +="/"; 448 curFile +="/";
449 curFile+= item; 449 curFile+= item;
450// qDebug("CurrentFile file is " + curFile); 450// qDebug("CurrentFile file is " + curFile);
451 451
452 if(QFileInfo(curFile).isDir()) { 452 if(QFileInfo(curFile).isDir()) {
453 moveDirectory( curFile, destFile ); 453 moveDirectory( curFile, destFile );
454 rePopulate(); 454 rePopulate();
455 return; 455 return;
456 } 456 }
457 457
458 QFile f( curFile); 458 QFile f( curFile);
459 if( f.exists()) { 459 if( f.exists()) {
460 if( !copyFile( curFile, destFile) ) { 460 if( !copyFile( curFile, destFile) ) {
461 QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile); 461 QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile);
462 return; 462 return;
463 } else 463 } else
464 QFile::remove(curFile); 464 QFile::remove(curFile);
465 } 465 }
466 } 466 }
467 467
468 } 468 }
469 rePopulate(); 469 rePopulate();
470 setOtherTabCurrent(); 470 setOtherTabCurrent();
471} 471}
472 472
473bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) { 473bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) {
474 int err = 0; 474 int err = 0;
475 if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src; 475 if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src;
476 err = system((const char*)cmd); 476 err = system((const char*)cmd);
477 } else 477 } else
478 err = -1; 478 err = -1;
479 479
480 if(err!=0) { 480 if(err!=0) {
481 QMessageBox::message(tr("Note"),tr("Could not move\n") + src); 481 QMessageBox::message(tr("Note"),tr("Could not move\n") + src);
482 return false; 482 return false;
483 } 483 }
484 return true; 484 return true;
485} 485}
486 486
487bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) { 487bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) {
488 488
489 QString cmd = "/bin/cp -fpR " + src + " " + dest; 489 QString cmd = "/bin/cp -fpR " + src + " " + dest;
490 qWarning(cmd); 490 qWarning(cmd);
491 int err = system( (const char *) cmd ); 491 int err = system( (const char *) cmd );
492 if ( err != 0 ) { 492 if ( err != 0 ) {
493 QMessageBox::message("AdvancedFm", 493 QMessageBox::message("AdvancedFm",
494 tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) ); 494 tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) );
495 return false; 495 return false;
496 } 496 }
497 497
498 return true; 498 return true;
499} 499}
500 500
501 501
502bool AdvancedFm::copyFile( const QString & src, const QString & dest ) { 502bool AdvancedFm::copyFile( const QString & src, const QString & dest ) {
503 503
504 504
505 if(QFileInfo(src).isDir()) { 505 if(QFileInfo(src).isDir()) {
506 if( copyDirectory( src, dest )) { 506 if( copyDirectory( src, dest )) {
507 setOtherTabCurrent(); 507 setOtherTabCurrent();
508 populateView(); 508 populateView();
509 return true; 509 return true;
510 } 510 }
511 else 511 else
512 return false; 512 return false;
513 } 513 }
514 514
515 515
516 bool success = true; 516 bool success = true;
517 struct stat status; 517 struct stat status;
518 QFile srcFile(src); 518 QFile srcFile(src);
519 QFile destFile(dest); 519 QFile destFile(dest);
520 int err=0; 520 int err=0;
521 int read_fd=0; 521 int read_fd=0;
522 int write_fd=0; 522 int write_fd=0;
523 struct stat stat_buf; 523 struct stat stat_buf;
524 off_t offset = 0; 524 off_t offset = 0;
525 if(!srcFile.open( IO_ReadOnly|IO_Raw)) { 525 if(!srcFile.open( IO_ReadOnly|IO_Raw)) {
526// qWarning("open failed"); 526// qWarning("open failed");
527 return success = false; 527 return success = false;
528 } 528 }
529 read_fd = srcFile.handle(); 529 read_fd = srcFile.handle();
530 if(read_fd != -1) { 530 if(read_fd != -1) {
531 fstat (read_fd, &stat_buf); 531 fstat (read_fd, &stat_buf);
532 if( !destFile.open( IO_WriteOnly|IO_Raw ) ) { 532 if( !destFile.open( IO_WriteOnly|IO_Raw ) ) {
533// qWarning("destfile open failed"); 533// qWarning("destfile open failed");
534 return success = false; 534 return success = false;
535 } 535 }
536 write_fd = destFile.handle(); 536 write_fd = destFile.handle();
537 if(write_fd != -1) { 537 if(write_fd != -1) {
538 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size); 538 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
539 if( err == -1) { 539 if( err == -1) {
540 QString msg; 540 QString msg;
541 switch(err) { 541 switch(err) {
542 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. "; 542 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. ";
543 case EINVAL: msg = "Descriptor is not valid or locked. "; 543 case EINVAL: msg = "Descriptor is not valid or locked. ";
544 case ENOMEM: msg = "Insufficient memory to read from in_fd."; 544 case ENOMEM: msg = "Insufficient memory to read from in_fd.";
545 case EIO: msg = "Unspecified error while reading from in_fd."; 545 case EIO: msg = "Unspecified error while reading from in_fd.";
546 }; 546 };
547 success = false; 547 success = false;
548// qWarning(msg); 548// qWarning(msg);
549 } 549 }
550 } else { 550 } else {
551 success = false; 551 success = false;
552 } 552 }
553 } else { 553 } else {
554 success = false; 554 success = false;
555 } 555 }
556 srcFile.close(); 556 srcFile.close();
557 destFile.close(); 557 destFile.close();
558 // Set file permissions 558 // Set file permissions
559 if( stat( (const char *) src, &status ) == 0 ) { 559 if( stat( (const char *) src, &status ) == 0 ) {
560 chmod( (const char *) dest, status.st_mode ); 560 chmod( (const char *) dest, status.st_mode );
561 } 561 }
562 562
563 return success; 563 return success;
564} 564}
565 565
566void AdvancedFm::runCommand() { 566void AdvancedFm::runCommand() {
567 if( !CurrentView()->currentItem()) return; 567 if( !CurrentView()->currentItem()) return;
568 QDir *thisDir = CurrentDir(); 568 QDir *thisDir = CurrentDir();
569 569
570 QString curFile; 570 QString curFile;
571 curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0); 571 curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0);
572 572
573 InputDialog *fileDlg; 573 InputDialog *fileDlg;
574 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0); 574 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
575 fileDlg->setInputText(curFile); 575 fileDlg->setInputText(curFile);
576 fileDlg->exec(); 576 fileDlg->exec();
577 //QString command; 577 //QString command;
578 578
579 if( fileDlg->result() == 1 ) { 579 if( fileDlg->result() == 1 ) {
580// qDebug(fileDlg->LineEdit1->text()); 580// qDebug(fileDlg->LineEdit1->text());
581 QStringList command; 581 QStringList command;
582 582
583 command << "/bin/sh"; 583 command << "/bin/sh";
584 command << "-c"; 584 command << "-c";
585 command << fileDlg->LineEdit1->text(); 585 command << fileDlg->LineEdit1->text();
586 Output *outDlg; 586 Output *outDlg;
587 outDlg = new Output( command, this, tr("AdvancedFm Output"), true); 587 outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
588 QPEApplication::execDialog( outDlg ); 588 QPEApplication::execDialog( outDlg );
589 qApp->processEvents(); 589 qApp->processEvents();
590 590
591 } 591 }
592} 592}
593 593
594void AdvancedFm::runCommandStd() { 594void AdvancedFm::runCommandStd() {
595 if( !CurrentView()->currentItem()) return; 595 if( !CurrentView()->currentItem()) return;
596 QString curFile; 596 QString curFile;
597 QDir *thisDir = CurrentDir(); 597 QDir *thisDir = CurrentDir();
598 QListView *thisView = CurrentView(); 598 QListView *thisView = CurrentView();
599 if( thisView->currentItem()) 599 if( thisView->currentItem())
600 curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0); 600 curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0);
601 601
602 InputDialog *fileDlg; 602 InputDialog *fileDlg;
603 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0); 603 fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0);
604 fileDlg->setInputText(curFile); 604 fileDlg->setInputText(curFile);
605 fileDlg->exec(); 605 fileDlg->exec();
606 606
607 if( fileDlg->result() == 1 ) { 607 if( fileDlg->result() == 1 ) {
608 qApp->processEvents(); 608 qApp->processEvents();
609 startProcess( (const QString)fileDlg->LineEdit1->text().latin1()); 609 startProcess( (const QString)fileDlg->LineEdit1->text().latin1());
610 } 610 }
611} 611}
612 612
613void AdvancedFm::fileStatus() { 613void AdvancedFm::fileStatus() {
614 if( !CurrentView()->currentItem()) return; 614 if( !CurrentView()->currentItem()) return;
615 QString curFile; 615 QString curFile;
616 curFile = CurrentView()->currentItem()->text(0); 616 curFile = CurrentView()->currentItem()->text(0);
617 617
618 QStringList command; 618 QStringList command;
619 command << "/bin/sh"; 619 command << "/bin/sh";
620 command << "-c"; 620 command << "-c";
621 command << "stat -l "+ curFile; 621 command << "stat -l "+ curFile;
622 622
623 Output *outDlg; 623 Output *outDlg;
624 outDlg = new Output( command, this, tr("AdvancedFm Output"), true); 624 outDlg = new Output( command, this, tr("AdvancedFm Output"), true);
625 QPEApplication::execDialog( outDlg ); 625 QPEApplication::execDialog( outDlg );
626 qApp->processEvents(); 626 qApp->processEvents();
627} 627}
628 628
629 629
630void AdvancedFm::mkDir() { 630void AdvancedFm::mkDir() {
631 makeDir(); 631 makeDir();
632} 632}
633 633
634void AdvancedFm::rn() { 634void AdvancedFm::rn() {
635 renameIt(); 635 renameIt();
636} 636}
637 637
638void AdvancedFm::del() { 638void AdvancedFm::del() {
639 doDelete(); 639 doDelete();
640} 640}
641 641
642void AdvancedFm::mkSym() { 642void AdvancedFm::mkSym() {
643 QString cmd; 643 QString cmd;
644 QStringList curFileList = getPath(); 644 QStringList curFileList = getPath();
645 if( curFileList.count() > 0) { 645 if( curFileList.count() > 0) {
646 QDir *thisDir = CurrentDir(); 646 QDir *thisDir = CurrentDir();
647 QDir * thatDir = OtherDir(); 647 QDir * thatDir = OtherDir();
648 648
649 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 649 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
650 650
651 QString destName = thatDir->canonicalPath()+"/"+(*it); 651 QString destName = thatDir->canonicalPath()+"/"+(*it);
652 if(destName.right(1) == "/") { 652 if(destName.right(1) == "/") {
653 destName = destName.left( destName.length() -1); 653 destName = destName.left( destName.length() -1);
654 } 654 }
655 655
656 QString curFile = thisDir->canonicalPath()+"/"+(*it); 656 QString curFile = thisDir->canonicalPath()+"/"+(*it);
657 657
658 if( curFile.right(1) == "/") { 658 if( curFile.right(1) == "/") {
659 curFile = curFile.left( curFile.length() -1); 659 curFile = curFile.left( curFile.length() -1);
660 } 660 }
661 661
662 cmd = "ln -s "+curFile+" "+destName; 662 cmd = "ln -s "+curFile+" "+destName;
663// qDebug(cmd); 663// qDebug(cmd);
664 startProcess( (const QString)cmd ); 664 startProcess( (const QString)cmd );
665 } 665 }
666 rePopulate(); 666 rePopulate();
667 setOtherTabCurrent(); 667 setOtherTabCurrent();
668 } 668 }
669} 669}
670 670
671void AdvancedFm::doBeam() { 671void AdvancedFm::doBeam() {
672 Ir ir; 672 Ir ir;
673 if(!ir.supported()) { 673 if(!ir.supported()) {
674 } else { 674 } else {
675 QStringList curFileList = getPath(); 675 QStringList curFileList = getPath();
676 if( curFileList.count() > 0) { 676 if( curFileList.count() > 0) {
677 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { 677 for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) {
678 QString curFile = (*it); 678 QString curFile = (*it);
679 QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile; 679 QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile;
680 if( curFilePath.right(1) == "/") { 680 if( curFilePath.right(1) == "/") {
681 curFilePath = curFilePath.left( curFilePath.length() -1); 681 curFilePath = curFilePath.left( curFilePath.length() -1);
682 } 682 }
683 Ir *file = new Ir(this, "IR"); 683 Ir *file = new Ir(this, "IR");
684 connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished( Ir * ))); 684 connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished(Ir*)));
685 file->send( curFilePath, curFile ); 685 file->send( curFilePath, curFile );
686 } 686 }
687 } 687 }
688 } 688 }
689} 689}
690 690
691void AdvancedFm::fileBeamFinished( Ir *) { 691void AdvancedFm::fileBeamFinished( Ir *) {
692 QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") ); 692 QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") );
693} 693}
694 694
695void AdvancedFm::selectAll() { 695void AdvancedFm::selectAll() {
696 QListView *thisView = CurrentView(); 696 QListView *thisView = CurrentView();
697 thisView->selectAll(true); 697 thisView->selectAll(true);
698 thisView->setSelected( thisView->firstChild(),false); 698 thisView->setSelected( thisView->firstChild(),false);
699} 699}
700 700
701void AdvancedFm::startProcess(const QString & cmd) { 701void AdvancedFm::startProcess(const QString & cmd) {
702 QStringList command; 702 QStringList command;
703 OProcess *process; 703 OProcess *process;
704 process = new OProcess(); 704 process = new OProcess();
705 connect(process, SIGNAL(processExited(OProcess *)), 705 connect(process, SIGNAL(processExited(OProcess*)),
706 this, SLOT( processEnded(OProcess *))); 706 this, SLOT( processEnded(OProcess*)));
707 707
708 connect(process, SIGNAL( receivedStderr(OProcess *, char *, int)), 708 connect(process, SIGNAL( receivedStderr(OProcess*,char*,int)),
709 this, SLOT( oprocessStderr(OProcess *, char *, int))); 709 this, SLOT( oprocessStderr(OProcess*,char*,int)));
710 710
711 command << "/bin/sh"; 711 command << "/bin/sh";
712 command << "-c"; 712 command << "-c";
713 command << cmd.latin1(); 713 command << cmd.latin1();
714 *process << command; 714 *process << command;
715 if(!process->start(OProcess::NotifyOnExit, OProcess::All) ) 715 if(!process->start(OProcess::NotifyOnExit, OProcess::All) )
716 qDebug("could not start process"); 716 qDebug("could not start process");
717} 717}
718 718
719void AdvancedFm::processEnded(OProcess *) { 719void AdvancedFm::processEnded(OProcess *) {
720 rePopulate(); 720 rePopulate();
721} 721}
722 722
723void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) { 723void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) {
724// qWarning("received stderrt %d bytes", buflen); 724// qWarning("received stderrt %d bytes", buflen);
725 725
726 QString lineStr = buffer; 726 QString lineStr = buffer;
727 QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") ); 727 QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") );
728} 728}
729 729
730bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) { 730bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) {
731 if ( o->inherits( "QLineEdit" ) ) { 731 if ( o->inherits( "QLineEdit" ) ) {
732 if ( e->type() == QEvent::KeyPress ) { 732 if ( e->type() == QEvent::KeyPress ) {
733 QKeyEvent *ke = (QKeyEvent*)e; 733 QKeyEvent *ke = (QKeyEvent*)e;
734 if ( ke->key() == Key_Return || 734 if ( ke->key() == Key_Return ||
735 ke->key() == Key_Enter ) { 735 ke->key() == Key_Enter ) {
736 okRename(); 736 okRename();
737 return true; 737 return true;
738 } 738 }
739 else if ( ke->key() == Key_Escape ) { 739 else if ( ke->key() == Key_Escape ) {
740 cancelRename(); 740 cancelRename();
741 return true; 741 return true;
742 } 742 }
743 } 743 }
744 else if ( e->type() == QEvent::FocusOut ) { 744 else if ( e->type() == QEvent::FocusOut ) {
745 cancelRename(); 745 cancelRename();
746 return true; 746 return true;
747 } 747 }
748 } 748 }
749 if ( o->inherits( "QListView" ) ) { 749 if ( o->inherits( "QListView" ) ) {
750 if ( e->type() == QEvent::FocusIn ) { 750 if ( e->type() == QEvent::FocusIn ) {
751 if( o == Local_View) { //keep track of which view 751 if( o == Local_View) { //keep track of which view
752 whichTab=1; 752 whichTab=1;
753 } 753 }
754 else { 754 else {
755 whichTab=2; 755 whichTab=2;
756 } 756 }
757 } 757 }
758 OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection 758 OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection
759 } 759 }
760 760
761 return QWidget::eventFilter( o, e ); 761 return QWidget::eventFilter( o, e );
762} 762}
763 763
764 764
765void AdvancedFm::cancelRename() { 765void AdvancedFm::cancelRename() {
766// qDebug("cancel rename"); 766// qDebug("cancel rename");
767 QListView * view; 767 QListView * view;
768 view = CurrentView(); 768 view = CurrentView();
769 769
770 bool resetFocus = view->viewport()->focusProxy() == renameBox; 770 bool resetFocus = view->viewport()->focusProxy() == renameBox;
771 delete renameBox; 771 delete renameBox;
772 renameBox = 0; 772 renameBox = 0;
773 if ( resetFocus ) { 773 if ( resetFocus ) {
774 view->viewport()->setFocusProxy( view); 774 view->viewport()->setFocusProxy( view);
775 view->setFocus(); 775 view->setFocus();
776 } 776 }
777} 777}
778 778
779void AdvancedFm::doRename(QListView * view) { 779void AdvancedFm::doRename(QListView * view) {
780 if( !CurrentView()->currentItem()) return; 780 if( !CurrentView()->currentItem()) return;
781 781
782 QRect r = view->itemRect( view->currentItem( )); 782 QRect r = view->itemRect( view->currentItem( ));
783 r = QRect( view->viewportToContents( r.topLeft() ), r.size() ); 783 r = QRect( view->viewportToContents( r.topLeft() ), r.size() );
784 r.setX( view->contentsX() ); 784 r.setX( view->contentsX() );
785 785
786 if ( r.width() > view->visibleWidth() ) 786 if ( r.width() > view->visibleWidth() )
787 r.setWidth( view->visibleWidth() ); 787 r.setWidth( view->visibleWidth() );
788 788
789 renameBox = new QLineEdit( view->viewport(), "qt_renamebox" ); 789 renameBox = new QLineEdit( view->viewport(), "qt_renamebox" );
790 renameBox->setFrame(true); 790 renameBox->setFrame(true);
791 791
792 renameBox->setText( view->currentItem()->text(0) ); 792 renameBox->setText( view->currentItem()->text(0) );
793 793
794 renameBox->selectAll(); 794 renameBox->selectAll();
795 renameBox->installEventFilter( this ); 795 renameBox->installEventFilter( this );
796 796
797 view->addChild( renameBox, r.x(), r.y() ); 797 view->addChild( renameBox, r.x(), r.y() );
798 798
799 renameBox->resize( r.size() ); 799 renameBox->resize( r.size() );
800 800
801 view->viewport()->setFocusProxy( renameBox ); 801 view->viewport()->setFocusProxy( renameBox );
802 802
803 renameBox->setFocus(); 803 renameBox->setFocus();
804 renameBox->show(); 804 renameBox->show();
805} 805}
806 806
807 807
808void AdvancedFm::renameIt() { 808void AdvancedFm::renameIt() {
809 if( !CurrentView()->currentItem()) return; 809 if( !CurrentView()->currentItem()) return;
810 810
811 QListView *thisView = CurrentView(); 811 QListView *thisView = CurrentView();
812 oldName = thisView->currentItem()->text(0); 812 oldName = thisView->currentItem()->text(0);
813 doRename( thisView ); 813 doRename( thisView );
814} 814}
815 815
816void AdvancedFm::okRename() { 816void AdvancedFm::okRename() {
817 if( !CurrentView()->currentItem()) return; 817 if( !CurrentView()->currentItem()) return;
818 818
819 QString newName = renameBox->text(); 819 QString newName = renameBox->text();
820 cancelRename(); 820 cancelRename();
821 QListView * view = CurrentView(); 821 QListView * view = CurrentView();
822 QString path = CurrentDir()->canonicalPath() + "/"; 822 QString path = CurrentDir()->canonicalPath() + "/";
823 oldName = path + oldName; 823 oldName = path + oldName;
824 newName = path + newName; 824 newName = path + newName;
825 if( rename( oldName.latin1(), newName.latin1())== -1) 825 if( rename( oldName.latin1(), newName.latin1())== -1)
826 QMessageBox::message(tr("Note"),tr("Could not rename")); 826 QMessageBox::message(tr("Note"),tr("Could not rename"));
827 else 827 else
828 oldName = ""; 828 oldName = "";
829 view->takeItem( view->currentItem() ); 829 view->takeItem( view->currentItem() );
830 delete view->currentItem(); 830 delete view->currentItem();
831 rePopulate(); 831 rePopulate();
832} 832}
833 833
834void AdvancedFm::openSearch() { 834void AdvancedFm::openSearch() {
835 QMessageBox::message(tr("Note"),tr("Not Yet Implemented")); 835 QMessageBox::message(tr("Note"),tr("Not Yet Implemented"));
836} 836}
diff --git a/noncore/apps/advancedfm/output.cpp b/noncore/apps/advancedfm/output.cpp
index 7dc2416..0bba1d8 100644
--- a/noncore/apps/advancedfm/output.cpp
+++ b/noncore/apps/advancedfm/output.cpp
@@ -1,276 +1,276 @@
1/**************************************************************************** 1/****************************************************************************
2** outputEdit.cpp 2** outputEdit.cpp
3** 3**
4** Copyright: Fri Apr 12 15:12:58 2002 L.J. Potter <ljp@llornkcor.com> 4** Copyright: Fri Apr 12 15:12:58 2002 L.J. Potter <ljp@llornkcor.com>
5****************************************************************************/ 5****************************************************************************/
6#include "output.h" 6#include "output.h"
7 7
8#include <qpe/qpeapplication.h> 8#include <qpe/qpeapplication.h>
9#include <qpe/applnk.h> 9#include <qpe/applnk.h>
10 10
11#include <qfile.h> 11#include <qfile.h>
12#include <qmultilineedit.h> 12#include <qmultilineedit.h>
13#include <qpushbutton.h> 13#include <qpushbutton.h>
14#include <qlayout.h> 14#include <qlayout.h>
15 15
16#include <errno.h> 16#include <errno.h>
17 17
18/* XPM */ 18/* XPM */
19static char * filesave_xpm[] = { 19static char * filesave_xpm[] = {
20"16 16 78 1", 20"16 16 78 1",
21" c None", 21" c None",
22". c #343434", 22". c #343434",
23"+ c #A0A0A0", 23"+ c #A0A0A0",
24"@ c #565656", 24"@ c #565656",
25"# c #9E9E9E", 25"# c #9E9E9E",
26"$ c #525252", 26"$ c #525252",
27"% c #929292", 27"% c #929292",
28"& c #676767", 28"& c #676767",
29"* c #848484", 29"* c #848484",
30"= c #666666", 30"= c #666666",
31"- c #D8D8D8", 31"- c #D8D8D8",
32"; c #FFFFFF", 32"; c #FFFFFF",
33"> c #DBDBDB", 33"> c #DBDBDB",
34", c #636363", 34", c #636363",
35"' c #989898", 35"' c #989898",
36") c #2D2D2D", 36") c #2D2D2D",
37"! c #909090", 37"! c #909090",
38"~ c #AEAEAE", 38"~ c #AEAEAE",
39"{ c #EAEAEA", 39"{ c #EAEAEA",
40"] c #575757", 40"] c #575757",
41"^ c #585858", 41"^ c #585858",
42"/ c #8A8A8A", 42"/ c #8A8A8A",
43"( c #828282", 43"( c #828282",
44"_ c #6F6F6F", 44"_ c #6F6F6F",
45": c #C9C9C9", 45": c #C9C9C9",
46"< c #050505", 46"< c #050505",
47"[ c #292929", 47"[ c #292929",
48"} c #777777", 48"} c #777777",
49"| c #616161", 49"| c #616161",
50"1 c #3A3A3A", 50"1 c #3A3A3A",
51"2 c #BEBEBE", 51"2 c #BEBEBE",
52"3 c #2C2C2C", 52"3 c #2C2C2C",
53"4 c #7C7C7C", 53"4 c #7C7C7C",
54"5 c #F6F6F6", 54"5 c #F6F6F6",
55"6 c #FCFCFC", 55"6 c #FCFCFC",
56"7 c #6B6B6B", 56"7 c #6B6B6B",
57"8 c #959595", 57"8 c #959595",
58"9 c #4F4F4F", 58"9 c #4F4F4F",
59"0 c #808080", 59"0 c #808080",
60"a c #767676", 60"a c #767676",
61"b c #818181", 61"b c #818181",
62"c c #B8B8B8", 62"c c #B8B8B8",
63"d c #FBFBFB", 63"d c #FBFBFB",
64"e c #F9F9F9", 64"e c #F9F9F9",
65"f c #CCCCCC", 65"f c #CCCCCC",
66"g c #030303", 66"g c #030303",
67"h c #737373", 67"h c #737373",
68"i c #7A7A7A", 68"i c #7A7A7A",
69"j c #7E7E7E", 69"j c #7E7E7E",
70"k c #6A6A6A", 70"k c #6A6A6A",
71"l c #FAFAFA", 71"l c #FAFAFA",
72"m c #505050", 72"m c #505050",
73"n c #9D9D9D", 73"n c #9D9D9D",
74"o c #333333", 74"o c #333333",
75"p c #7B7B7B", 75"p c #7B7B7B",
76"q c #787878", 76"q c #787878",
77"r c #696969", 77"r c #696969",
78"s c #494949", 78"s c #494949",
79"t c #555555", 79"t c #555555",
80"u c #949494", 80"u c #949494",
81"v c #E6E6E6", 81"v c #E6E6E6",
82"w c #424242", 82"w c #424242",
83"x c #515151", 83"x c #515151",
84"y c #535353", 84"y c #535353",
85"z c #3E3E3E", 85"z c #3E3E3E",
86"A c #D4D4D4", 86"A c #D4D4D4",
87"B c #0C0C0C", 87"B c #0C0C0C",
88"C c #353535", 88"C c #353535",
89"D c #474747", 89"D c #474747",
90"E c #ECECEC", 90"E c #ECECEC",
91"F c #919191", 91"F c #919191",
92"G c #7D7D7D", 92"G c #7D7D7D",
93"H c #000000", 93"H c #000000",
94"I c #404040", 94"I c #404040",
95"J c #858585", 95"J c #858585",
96"K c #323232", 96"K c #323232",
97"L c #D0D0D0", 97"L c #D0D0D0",
98"M c #1C1C1C", 98"M c #1C1C1C",
99" ...+ ", 99" ...+ ",
100" @#$%&..+ ", 100" @#$%&..+ ",
101" .*=-;;>,..+ ", 101" .*=-;;>,..+ ",
102" ')!~;;;;;;{]..", 102" ')!~;;;;;;{]..",
103" ^/(-;;;;;;;_:<", 103" ^/(-;;;;;;;_:<",
104" [}|;;;;;;;{12$", 104" [}|;;;;;;;{12$",
105" #34-55;;;;678$+", 105" #34-55;;;;678$+",
106" 90ab=c;dd;e1fg ", 106" 90ab=c;dd;e1fg ",
107" [ahij((kbl0mn$ ", 107" [ahij((kbl0mn$ ",
108" op^q^^7r&]s/$+ ", 108" op^q^^7r&]s/$+ ",
109"@btu;vbwxy]zAB ", 109"@btu;vbwxy]zAB ",
110"CzDEvEv;;DssF$ ", 110"CzDEvEv;;DssF$ ",
111"G.H{E{E{IxsJ$+ ", 111"G.H{E{E{IxsJ$+ ",
112" +...vEKxzLM ", 112" +...vEKxzLM ",
113" +...z]n$ ", 113" +...z]n$ ",
114" +... "}; 114" +... "};
115 115
116Output::Output( const QStringList commands, QWidget* parent, const char* name, bool modal, WFlags fl) 116Output::Output( const QStringList commands, QWidget* parent, const char* name, bool modal, WFlags fl)
117 : QDialog( parent, name, modal, fl ) 117 : QDialog( parent, name, modal, fl )
118{ 118{
119 QStringList cmmds; 119 QStringList cmmds;
120// cmmds=QStringList::split( " ", commands, false); 120// cmmds=QStringList::split( " ", commands, false);
121 cmmds=commands; 121 cmmds=commands;
122// qDebug("count %d", cmmds.count()); 122// qDebug("count %d", cmmds.count());
123 if ( !name ) 123 if ( !name )
124 setName( tr("Output")); 124 setName( tr("Output"));
125 resize( 196, 269 ); 125 resize( 196, 269 );
126 setCaption( name ); 126 setCaption( name );
127 127
128 OutputLayout = new QGridLayout( this ); 128 OutputLayout = new QGridLayout( this );
129 OutputLayout->setSpacing( 2); 129 OutputLayout->setSpacing( 2);
130 OutputLayout->setMargin( 2); 130 OutputLayout->setMargin( 2);
131 131
132 QPushButton *docButton; 132 QPushButton *docButton;
133 docButton = new QPushButton( QPixmap(( const char** ) filesave_xpm ) ,"",this,"saveButton"); 133 docButton = new QPushButton( QPixmap(( const char** ) filesave_xpm ) ,"",this,"saveButton");
134 docButton->setFixedSize( QSize( 20, 20 ) ); 134 docButton->setFixedSize( QSize( 20, 20 ) );
135 connect( docButton,SIGNAL(released()),this,SLOT( saveOutput() )); 135 connect( docButton,SIGNAL(released()),this,SLOT( saveOutput() ));
136 // docButton->setFlat(TRUE); 136 // docButton->setFlat(TRUE);
137 OutputLayout->addMultiCellWidget( docButton, 0,0,3,3 ); 137 OutputLayout->addMultiCellWidget( docButton, 0,0,3,3 );
138 138
139 OutputEdit = new QMultiLineEdit( this, "OutputEdit" ); 139 OutputEdit = new QMultiLineEdit( this, "OutputEdit" );
140 OutputLayout->addMultiCellWidget( OutputEdit, 1,1,0,3 ); 140 OutputLayout->addMultiCellWidget( OutputEdit, 1,1,0,3 );
141 141
142 proc = new OProcess(); 142 proc = new OProcess();
143 143
144 connect(proc, SIGNAL(processExited(OProcess *)), 144 connect(proc, SIGNAL(processExited(OProcess*)),
145 this, SLOT( processFinished())); 145 this, SLOT( processFinished()));
146 146
147 connect(proc, SIGNAL(receivedStdout(OProcess *, char *, int)), 147 connect(proc, SIGNAL(receivedStdout(OProcess*,char*,int)),
148 this, SLOT(commandStdout(OProcess *, char *, int))); 148 this, SLOT(commandStdout(OProcess*,char*,int)));
149 149
150 connect(proc, SIGNAL(receivedStderr(OProcess *, char *, int)), 150 connect(proc, SIGNAL(receivedStderr(OProcess*,char*,int)),
151 this, SLOT(commandStderr(OProcess *, char *, int))); 151 this, SLOT(commandStderr(OProcess*,char*,int)));
152 152
153// connect( , SIGNAL(received(const QByteArray &)), 153// connect( , SIGNAL(received(const QByteArray&)),
154// this, SLOT(commandStdin(const QByteArray &))); 154// this, SLOT(commandStdin(const QByteArray&)));
155 155
156// * proc << commands.latin1(); 156// * proc << commands.latin1();
157 for ( QStringList::Iterator it = cmmds.begin(); it != cmmds.end(); ++it ) { 157 for ( QStringList::Iterator it = cmmds.begin(); it != cmmds.end(); ++it ) {
158 qDebug( "%s", (*it).latin1() ); 158 qDebug( "%s", (*it).latin1() );
159 * proc << (*it).latin1(); 159 * proc << (*it).latin1();
160 } 160 }
161 161
162 if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) { 162 if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) {
163 163
164 OutputEdit->append(tr("Process could not start") ); 164 OutputEdit->append(tr("Process could not start") );
165 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 165 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
166 perror("Error: "); 166 perror("Error: ");
167 QString errorMsg=tr("Error\n")+(QString)strerror(errno); 167 QString errorMsg=tr("Error\n")+(QString)strerror(errno);
168 OutputEdit->append( errorMsg); 168 OutputEdit->append( errorMsg);
169 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 169 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
170 } 170 }
171} 171}
172 172
173Output::~Output() { 173Output::~Output() {
174} 174}
175 175
176void Output::saveOutput() { 176void Output::saveOutput() {
177 177
178 InputDialog *fileDlg; 178 InputDialog *fileDlg;
179 fileDlg = new InputDialog(this,tr("Save output to file (name only)"),TRUE, 0); 179 fileDlg = new InputDialog(this,tr("Save output to file (name only)"),TRUE, 0);
180 fileDlg->exec(); 180 fileDlg->exec();
181 if( fileDlg->result() == 1 ) { 181 if( fileDlg->result() == 1 ) {
182 QString filename = QPEApplication::documentDir(); 182 QString filename = QPEApplication::documentDir();
183 if(filename.right(1).find('/') == -1) 183 if(filename.right(1).find('/') == -1)
184 filename+="/"; 184 filename+="/";
185 QString name = fileDlg->LineEdit1->text(); 185 QString name = fileDlg->LineEdit1->text();
186 filename+="text/plain/"+name; 186 filename+="text/plain/"+name;
187 qDebug(filename); 187 qDebug(filename);
188 188
189 QFile f(filename); 189 QFile f(filename);
190 f.open( IO_WriteOnly); 190 f.open( IO_WriteOnly);
191 if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) { 191 if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) {
192 DocLnk lnk; 192 DocLnk lnk;
193 lnk.setName(name); //sets file name 193 lnk.setName(name); //sets file name
194 lnk.setFile(filename); //sets File property 194 lnk.setFile(filename); //sets File property
195 lnk.setType("text/plain"); 195 lnk.setType("text/plain");
196 if(!lnk.writeLink()) { 196 if(!lnk.writeLink()) {
197 qDebug("Writing doclink did not work"); 197 qDebug("Writing doclink did not work");
198 } 198 }
199 } else 199 } else
200 qWarning("Could not write file"); 200 qWarning("Could not write file");
201 f.close(); 201 f.close();
202 } 202 }
203} 203}
204 204
205void Output::commandStdout(OProcess*, char *buffer, int buflen) { 205void Output::commandStdout(OProcess*, char *buffer, int buflen) {
206 qWarning("received stdout %d bytes", buflen); 206 qWarning("received stdout %d bytes", buflen);
207 207
208// QByteArray data(buflen); 208// QByteArray data(buflen);
209// data.fill(*buffer, buflen); 209// data.fill(*buffer, buflen);
210// for (uint i = 0; i < data.count(); i++ ) { 210// for (uint i = 0; i < data.count(); i++ ) {
211// printf("%c", buffer[i] ); 211// printf("%c", buffer[i] );
212// } 212// }
213// printf("\n"); 213// printf("\n");
214 214
215 QString lineStr = buffer; 215 QString lineStr = buffer;
216 lineStr=lineStr.left(lineStr.length()-1); 216 lineStr=lineStr.left(lineStr.length()-1);
217 OutputEdit->append(lineStr); 217 OutputEdit->append(lineStr);
218 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 218 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
219} 219}
220 220
221 221
222void Output::commandStdin( const QByteArray &data) { 222void Output::commandStdin( const QByteArray &data) {
223 qWarning("received stdin %d bytes", data.size()); 223 qWarning("received stdin %d bytes", data.size());
224 // recieved data from the io layer goes to sz 224 // recieved data from the io layer goes to sz
225 proc->writeStdin(data.data(), data.size()); 225 proc->writeStdin(data.data(), data.size());
226} 226}
227 227
228void Output::commandStderr(OProcess*, char *buffer, int buflen) { 228void Output::commandStderr(OProcess*, char *buffer, int buflen) {
229 qWarning("received stderrt %d bytes", buflen); 229 qWarning("received stderrt %d bytes", buflen);
230 230
231 QString lineStr = buffer; 231 QString lineStr = buffer;
232// lineStr=lineStr.left(lineStr.length()-1); 232// lineStr=lineStr.left(lineStr.length()-1);
233 OutputEdit->append(lineStr); 233 OutputEdit->append(lineStr);
234 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 234 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
235} 235}
236 236
237void Output::processFinished() { 237void Output::processFinished() {
238 238
239 delete proc; 239 delete proc;
240 OutputEdit->append( tr("\nFinished\n") ); 240 OutputEdit->append( tr("\nFinished\n") );
241 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); 241 OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE);
242// close(); 242// close();
243// disconnect( layer(), SIGNAL(received(const QByteArray &)), 243// disconnect( layer(), SIGNAL(received(const QByteArray&)),
244// this, SLOT(commandStdin(const QByteArray &))); 244// this, SLOT(commandStdin(const QByteArray&)));
245} 245}
246 246
247//============================== 247//==============================
248 248
249InputDialog::InputDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 249InputDialog::InputDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
250 : QDialog( parent, name, modal, fl ) 250 : QDialog( parent, name, modal, fl )
251{ 251{
252 if ( !name ) 252 if ( !name )
253 setName( "InputDialog" ); 253 setName( "InputDialog" );
254 resize( 234, 50 ); 254 resize( 234, 50 );
255 setMaximumSize( QSize( 240, 50 ) ); 255 setMaximumSize( QSize( 240, 50 ) );
256 setCaption( tr(name ) ); 256 setCaption( tr(name ) );
257 257
258 LineEdit1 = new QLineEdit( this, "LineEdit1" ); 258 LineEdit1 = new QLineEdit( this, "LineEdit1" );
259 LineEdit1->setGeometry( QRect( 10, 10, 216, 22 ) ); 259 LineEdit1->setGeometry( QRect( 10, 10, 216, 22 ) );
260 LineEdit1->setFocus(); 260 LineEdit1->setFocus();
261 LineEdit1->setFocus(); 261 LineEdit1->setFocus();
262 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(returned() )); 262 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(returned() ));
263} 263}
264 264
265InputDialog::~InputDialog() { 265InputDialog::~InputDialog() {
266 inputText = LineEdit1->text(); 266 inputText = LineEdit1->text();
267} 267}
268 268
269void InputDialog::setInputText(const QString &string) { 269void InputDialog::setInputText(const QString &string) {
270 LineEdit1->setText( string); 270 LineEdit1->setText( string);
271} 271}
272 272
273void InputDialog::returned() { 273void InputDialog::returned() {
274 inputText = LineEdit1->text(); 274 inputText = LineEdit1->text();
275 this->accept(); 275 this->accept();
276} 276}
diff --git a/noncore/apps/checkbook/checkbook.cpp b/noncore/apps/checkbook/checkbook.cpp
index 26b2533..1b933f2 100644
--- a/noncore/apps/checkbook/checkbook.cpp
+++ b/noncore/apps/checkbook/checkbook.cpp
@@ -1,785 +1,785 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "checkbook.h" 29#include "checkbook.h"
30#include "cbinfo.h" 30#include "cbinfo.h"
31#include "transaction.h" 31#include "transaction.h"
32#include "traninfo.h" 32#include "traninfo.h"
33#include "graph.h" 33#include "graph.h"
34#include "graphinfo.h" 34#include "graphinfo.h"
35#include "password.h" 35#include "password.h"
36#include "cfg.h" 36#include "cfg.h"
37 37
38#include <qpe/qpeapplication.h> 38#include <qpe/qpeapplication.h>
39#include <qpe/qpemessagebox.h> 39#include <qpe/qpemessagebox.h>
40#include <qpe/resource.h> 40#include <qpe/resource.h>
41 41
42#include <qcheckbox.h> 42#include <qcheckbox.h>
43#include <qcombobox.h> 43#include <qcombobox.h>
44#include <qlabel.h> 44#include <qlabel.h>
45#include <qlayout.h> 45#include <qlayout.h>
46#include <qlineedit.h> 46#include <qlineedit.h>
47#include <qmultilineedit.h> 47#include <qmultilineedit.h>
48#include <qpushbutton.h> 48#include <qpushbutton.h>
49#include <qwhatsthis.h> 49#include <qwhatsthis.h>
50#include <qpopupmenu.h> 50#include <qpopupmenu.h>
51 51
52#define COL_ID 0 52#define COL_ID 0
53#define COL_SORTDATE 1 53#define COL_SORTDATE 1
54#define COL_NUM 2 54#define COL_NUM 2
55#define COL_DATE 3 55#define COL_DATE 3
56#define COL_DESC 4 56#define COL_DESC 4
57#define COL_AMOUNT 5 57#define COL_AMOUNT 5
58#define COL_BAL 6 58#define COL_BAL 6
59 59
60// --- Checkbook -------------------------------------------------------------- 60// --- Checkbook --------------------------------------------------------------
61Checkbook::Checkbook( QWidget *parent, CBInfo *i, Cfg *cfg ) 61Checkbook::Checkbook( QWidget *parent, CBInfo *i, Cfg *cfg )
62 : QDialog( parent, 0, TRUE, WStyle_ContextHelp ) 62 : QDialog( parent, 0, TRUE, WStyle_ContextHelp )
63{ 63{
64 info = i; 64 info = i;
65 _pCfg=cfg; 65 _pCfg=cfg;
66 66
67 // Title bar 67 // Title bar
68 if ( info->name() != "" ) 68 if ( info->name() != "" )
69 { 69 {
70 QString tempstr = info->name(); 70 QString tempstr = info->name();
71 tempstr.append( " - " ); 71 tempstr.append( " - " );
72 tempstr.append( tr( "Checkbook" ) ); 72 tempstr.append( tr( "Checkbook" ) );
73 setCaption( tempstr ); 73 setCaption( tempstr );
74 } 74 }
75 else 75 else
76 { 76 {
77 setCaption( tr( "New checkbook" ) ); 77 setCaption( tr( "New checkbook" ) );
78 } 78 }
79 79
80 80
81 // Setup layout to make everything pretty 81 // Setup layout to make everything pretty
82 QVBoxLayout *layout = new QVBoxLayout( this ); 82 QVBoxLayout *layout = new QVBoxLayout( this );
83 layout->setMargin( 2 ); 83 layout->setMargin( 2 );
84 layout->setSpacing( 4 ); 84 layout->setSpacing( 4 );
85 85
86 // Setup tabs for all info 86 // Setup tabs for all info
87 mainWidget = new OTabWidget( this ); 87 mainWidget = new OTabWidget( this );
88 layout->addWidget( mainWidget ); 88 layout->addWidget( mainWidget );
89 mainWidget->addTab( initInfo(), "checkbook/infotab", tr( "Info" ) ); 89 mainWidget->addTab( initInfo(), "checkbook/infotab", tr( "Info" ) );
90 mainWidget->addTab( initTransactions(), "checkbook/trantab", tr( "Transactions" ) ); 90 mainWidget->addTab( initTransactions(), "checkbook/trantab", tr( "Transactions" ) );
91 mainWidget->addTab( initCharts(), "checkbook/charttab", tr( "Charts" ) ); 91 mainWidget->addTab( initCharts(), "checkbook/charttab", tr( "Charts" ) );
92 if( _pCfg->isShowLastTab() ) 92 if( _pCfg->isShowLastTab() )
93 mainWidget->setCurrentTab( info->getLastTab() ); 93 mainWidget->setCurrentTab( info->getLastTab() );
94 else 94 else
95 mainWidget->setCurrentTab( tr( "Info" ) ); 95 mainWidget->setCurrentTab( tr( "Info" ) );
96 connect( mainWidget, SIGNAL( currentChanged(QWidget *) ), this, SLOT( slotTab(QWidget *) ) ); 96 connect( mainWidget, SIGNAL( currentChanged(QWidget*) ), this, SLOT( slotTab(QWidget*) ) );
97 97
98 // Load checkbook information 98 // Load checkbook information
99 loadCheckbook(); 99 loadCheckbook();
100} 100}
101 101
102Checkbook::~Checkbook() 102Checkbook::~Checkbook()
103{ 103{
104} 104}
105 105
106// --- initInfo --------------------------------------------------------------- 106// --- initInfo ---------------------------------------------------------------
107QWidget *Checkbook::initInfo() 107QWidget *Checkbook::initInfo()
108{ 108{
109 QWidget *control = new QWidget( mainWidget, tr("Info") ); 109 QWidget *control = new QWidget( mainWidget, tr("Info") );
110 110
111 QVBoxLayout *vb = new QVBoxLayout( control ); 111 QVBoxLayout *vb = new QVBoxLayout( control );
112 112
113 QScrollView *sv = new QScrollView( control ); 113 QScrollView *sv = new QScrollView( control );
114 vb->addWidget( sv, 0, 0 ); 114 vb->addWidget( sv, 0, 0 );
115 sv->setResizePolicy( QScrollView::AutoOneFit ); 115 sv->setResizePolicy( QScrollView::AutoOneFit );
116 sv->setFrameStyle( QFrame::NoFrame ); 116 sv->setFrameStyle( QFrame::NoFrame );
117 117
118 QWidget *container = new QWidget( sv->viewport() ); 118 QWidget *container = new QWidget( sv->viewport() );
119 sv->addChild( container ); 119 sv->addChild( container );
120 120
121 QGridLayout *layout = new QGridLayout( container ); 121 QGridLayout *layout = new QGridLayout( container );
122 layout->setSpacing( 2 ); 122 layout->setSpacing( 2 );
123 layout->setMargin( 4 ); 123 layout->setMargin( 4 );
124 124
125 // Password protection 125 // Password protection
126 passwordCB = new QCheckBox( tr( "Password protect" ), container ); 126 passwordCB = new QCheckBox( tr( "Password protect" ), container );
127 QWhatsThis::add( passwordCB, tr( "Click here to enable/disable password protection of this checkbook." ) ); 127 QWhatsThis::add( passwordCB, tr( "Click here to enable/disable password protection of this checkbook." ) );
128 connect( passwordCB, SIGNAL( clicked() ), this, SLOT( slotPasswordClicked() ) ); 128 connect( passwordCB, SIGNAL( clicked() ), this, SLOT( slotPasswordClicked() ) );
129 layout->addMultiCellWidget( passwordCB, 0, 0, 0, 1 ); 129 layout->addMultiCellWidget( passwordCB, 0, 0, 0, 1 );
130 130
131 // Account name 131 // Account name
132 QLabel *label = new QLabel( tr( "Name:" ), container ); 132 QLabel *label = new QLabel( tr( "Name:" ), container );
133 QWhatsThis::add( label, tr( "Enter name of checkbook here." ) ); 133 QWhatsThis::add( label, tr( "Enter name of checkbook here." ) );
134 layout->addWidget( label, 1, 0 ); 134 layout->addWidget( label, 1, 0 );
135 nameEdit = new QLineEdit( container ); 135 nameEdit = new QLineEdit( container );
136 QWhatsThis::add( nameEdit, tr( "Enter name of checkbook here." ) ); 136 QWhatsThis::add( nameEdit, tr( "Enter name of checkbook here." ) );
137 connect( nameEdit, SIGNAL( textChanged( const QString & ) ), 137 connect( nameEdit, SIGNAL( textChanged(const QString&) ),
138 this, SLOT( slotNameChanged( const QString & ) ) ); 138 this, SLOT( slotNameChanged(const QString&) ) );
139 layout->addWidget( nameEdit, 1, 1 ); 139 layout->addWidget( nameEdit, 1, 1 );
140 140
141 // Type of account 141 // Type of account
142 label = new QLabel( tr( "Type:" ), container ); 142 label = new QLabel( tr( "Type:" ), container );
143 QWhatsThis::add( label, tr( "Select type of checkbook here." ) ); 143 QWhatsThis::add( label, tr( "Select type of checkbook here." ) );
144 layout->addWidget( label, 2, 0 ); 144 layout->addWidget( label, 2, 0 );
145 typeList = new QComboBox( container ); 145 typeList = new QComboBox( container );
146 QWhatsThis::add( typeList, tr( "Select type of checkbook here." ) ); 146 QWhatsThis::add( typeList, tr( "Select type of checkbook here." ) );
147 typeList->insertStringList( _pCfg->getAccountTypes() ); 147 typeList->insertStringList( _pCfg->getAccountTypes() );
148 layout->addWidget( typeList, 2, 1 ); 148 layout->addWidget( typeList, 2, 1 );
149 149
150 // Bank/institution name 150 // Bank/institution name
151 label = new QLabel( tr( "Bank:" ), container ); 151 label = new QLabel( tr( "Bank:" ), container );
152 QWhatsThis::add( label, tr( "Enter name of the bank for this checkbook here." ) ); 152 QWhatsThis::add( label, tr( "Enter name of the bank for this checkbook here." ) );
153 layout->addWidget( label, 3, 0 ); 153 layout->addWidget( label, 3, 0 );
154 bankEdit = new QLineEdit( container ); 154 bankEdit = new QLineEdit( container );
155 QWhatsThis::add( bankEdit, tr( "Enter name of the bank for this checkbook here." ) ); 155 QWhatsThis::add( bankEdit, tr( "Enter name of the bank for this checkbook here." ) );
156 layout->addWidget( bankEdit, 3, 1 ); 156 layout->addWidget( bankEdit, 3, 1 );
157 157
158 // Account number 158 // Account number
159 label = new QLabel( tr( "Account number:" ), container ); 159 label = new QLabel( tr( "Account number:" ), container );
160 QWhatsThis::add( label, tr( "Enter account number for this checkbook here." ) ); 160 QWhatsThis::add( label, tr( "Enter account number for this checkbook here." ) );
161 layout->addWidget( label, 4, 0 ); 161 layout->addWidget( label, 4, 0 );
162 acctNumEdit = new QLineEdit( container ); 162 acctNumEdit = new QLineEdit( container );
163 QWhatsThis::add( acctNumEdit, tr( "Enter account number for this checkbook here." ) ); 163 QWhatsThis::add( acctNumEdit, tr( "Enter account number for this checkbook here." ) );
164 layout->addWidget( acctNumEdit, 4, 1 ); 164 layout->addWidget( acctNumEdit, 4, 1 );
165 165
166 // PIN number 166 // PIN number
167 label = new QLabel( tr( "PIN number:" ), container ); 167 label = new QLabel( tr( "PIN number:" ), container );
168 QWhatsThis::add( label, tr( "Enter PIN number for this checkbook here." ) ); 168 QWhatsThis::add( label, tr( "Enter PIN number for this checkbook here." ) );
169 layout->addWidget( label, 5, 0 ); 169 layout->addWidget( label, 5, 0 );
170 pinNumEdit = new QLineEdit( container ); 170 pinNumEdit = new QLineEdit( container );
171 QWhatsThis::add( pinNumEdit, tr( "Enter PIN number for this checkbook here." ) ); 171 QWhatsThis::add( pinNumEdit, tr( "Enter PIN number for this checkbook here." ) );
172 layout->addWidget( pinNumEdit, 5, 1 ); 172 layout->addWidget( pinNumEdit, 5, 1 );
173 173
174 // Starting balance 174 // Starting balance
175 label = new QLabel( tr( "Starting balance:" ), container ); 175 label = new QLabel( tr( "Starting balance:" ), container );
176 QWhatsThis::add( label, tr( "Enter the initial balance for this checkbook here." ) ); 176 QWhatsThis::add( label, tr( "Enter the initial balance for this checkbook here." ) );
177 layout->addWidget( label, 6, 0 ); 177 layout->addWidget( label, 6, 0 );
178 balanceEdit = new QLineEdit( container ); 178 balanceEdit = new QLineEdit( container );
179 QWhatsThis::add( balanceEdit, tr( "Enter the initial balance for this checkbook here." ) ); 179 QWhatsThis::add( balanceEdit, tr( "Enter the initial balance for this checkbook here." ) );
180 connect( balanceEdit, SIGNAL( textChanged( const QString & ) ), 180 connect( balanceEdit, SIGNAL( textChanged(const QString&) ),
181 this, SLOT( slotStartingBalanceChanged( const QString & ) ) ); 181 this, SLOT( slotStartingBalanceChanged(const QString&) ) );
182 layout->addWidget( balanceEdit, 6, 1 ); 182 layout->addWidget( balanceEdit, 6, 1 );
183 183
184 // Notes 184 // Notes
185 label = new QLabel( tr( "Notes:" ), container ); 185 label = new QLabel( tr( "Notes:" ), container );
186 QWhatsThis::add( label, tr( "Enter any additional information for this checkbook here." ) ); 186 QWhatsThis::add( label, tr( "Enter any additional information for this checkbook here." ) );
187 layout->addWidget( label, 7, 0 ); 187 layout->addWidget( label, 7, 0 );
188 notesEdit = new QMultiLineEdit( container ); 188 notesEdit = new QMultiLineEdit( container );
189 QWhatsThis::add( notesEdit, tr( "Enter any additional information for this checkbook here." ) ); 189 QWhatsThis::add( notesEdit, tr( "Enter any additional information for this checkbook here." ) );
190 notesEdit->setMinimumHeight( 25 ); 190 notesEdit->setMinimumHeight( 25 );
191 notesEdit->setMaximumHeight( 65 ); 191 notesEdit->setMaximumHeight( 65 );
192 layout->addMultiCellWidget( notesEdit, 8, 8, 0, 1 ); 192 layout->addMultiCellWidget( notesEdit, 8, 8, 0, 1 );
193 193
194 return control; 194 return control;
195} 195}
196 196
197 197
198// --- initTransactions ------------------------------------------------------- 198// --- initTransactions -------------------------------------------------------
199QWidget *Checkbook::initTransactions() 199QWidget *Checkbook::initTransactions()
200{ 200{
201 QWidget *control = new QWidget( mainWidget, tr("Transactions") ); 201 QWidget *control = new QWidget( mainWidget, tr("Transactions") );
202 202
203 QGridLayout *layout = new QGridLayout( control ); 203 QGridLayout *layout = new QGridLayout( control );
204 layout->setSpacing( 2 ); 204 layout->setSpacing( 2 );
205 layout->setMargin( 4 ); 205 layout->setMargin( 4 );
206 206
207 // Sort selector 207 // Sort selector
208 QLabel *label = new QLabel( tr( "Sort by:" ), control ); 208 QLabel *label = new QLabel( tr( "Sort by:" ), control );
209 QWhatsThis::add( label, tr( "Select checkbook sorting here." ) ); 209 QWhatsThis::add( label, tr( "Select checkbook sorting here." ) );
210 layout->addMultiCellWidget( label, 0, 0, 0, 1 ); 210 layout->addMultiCellWidget( label, 0, 0, 0, 1 );
211 _cbSortType=new QComboBox( control ); 211 _cbSortType=new QComboBox( control );
212 _cbSortType->insertItem( tr("Entry Order") ); 212 _cbSortType->insertItem( tr("Entry Order") );
213 _cbSortType->insertItem( tr("Date") ); 213 _cbSortType->insertItem( tr("Date") );
214 _cbSortType->insertItem( tr("Number") ); 214 _cbSortType->insertItem( tr("Number") );
215 layout->addMultiCellWidget( _cbSortType, 0, 0, 1, 2 ); 215 layout->addMultiCellWidget( _cbSortType, 0, 0, 1, 2 );
216 connect( _cbSortType, SIGNAL( activated(const QString &) ), this, SLOT( slotSortChanged( const QString & ) ) ); 216 connect( _cbSortType, SIGNAL( activated(const QString&) ), this, SLOT( slotSortChanged(const QString&) ) );
217 217
218 // Table 218 // Table
219 tranTable = new QListView( control ); 219 tranTable = new QListView( control );
220 QFont fnt(QPEApplication::font()); 220 QFont fnt(QPEApplication::font());
221 fnt.setPointSize( fnt.pointSize()-1 ); 221 fnt.setPointSize( fnt.pointSize()-1 );
222 tranTable->setFont( fnt ); 222 tranTable->setFont( fnt );
223 QWhatsThis::add( tranTable, tr( "This is a listing of all transactions entered for this checkbook.\n\nTo sort entries by a specific field, click on the column name." ) ); 223 QWhatsThis::add( tranTable, tr( "This is a listing of all transactions entered for this checkbook.\n\nTo sort entries by a specific field, click on the column name." ) );
224 tranTable->addColumn( tr( "Id" ) ); 224 tranTable->addColumn( tr( "Id" ) );
225 tranTable->setColumnWidthMode( COL_ID, QListView::Manual ); 225 tranTable->setColumnWidthMode( COL_ID, QListView::Manual );
226 tranTable->setColumnWidth( COL_ID, 0); 226 tranTable->setColumnWidth( COL_ID, 0);
227 tranTable->addColumn( tr( "SortDate" ) ); 227 tranTable->addColumn( tr( "SortDate" ) );
228 tranTable->setColumnWidthMode( COL_SORTDATE, QListView::Manual ); 228 tranTable->setColumnWidthMode( COL_SORTDATE, QListView::Manual );
229 tranTable->setColumnWidth( COL_SORTDATE, 0); 229 tranTable->setColumnWidth( COL_SORTDATE, 0);
230 tranTable->addColumn( tr( "Num" ) ); 230 tranTable->addColumn( tr( "Num" ) );
231 tranTable->addColumn( tr( "Date" ) ); 231 tranTable->addColumn( tr( "Date" ) );
232 //tranTable->addColumn( tr( "Cleared" ) ); 232 //tranTable->addColumn( tr( "Cleared" ) );
233 tranTable->addColumn( tr( "Description" ) ); 233 tranTable->addColumn( tr( "Description" ) );
234 int column = tranTable->addColumn( tr( "Amount" ) ); 234 int column = tranTable->addColumn( tr( "Amount" ) );
235 tranTable->setColumnAlignment( column, Qt::AlignRight ); 235 tranTable->setColumnAlignment( column, Qt::AlignRight );
236 column=tranTable->addColumn( tr("Balance") ); 236 column=tranTable->addColumn( tr("Balance") );
237 tranTable->setColumnAlignment( column, Qt::AlignRight ); 237 tranTable->setColumnAlignment( column, Qt::AlignRight );
238 tranTable->setAllColumnsShowFocus( TRUE ); 238 tranTable->setAllColumnsShowFocus( TRUE );
239 tranTable->setSorting( -1 ); 239 tranTable->setSorting( -1 );
240 layout->addMultiCellWidget( tranTable, 1, 1, 0, 2 ); 240 layout->addMultiCellWidget( tranTable, 1, 1, 0, 2 );
241 QPEApplication::setStylusOperation( tranTable->viewport(), QPEApplication::RightOnHold ); 241 QPEApplication::setStylusOperation( tranTable->viewport(), QPEApplication::RightOnHold );
242 connect( tranTable, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), 242 connect( tranTable, SIGNAL( rightButtonPressed(QListViewItem*,const QPoint&,int) ),
243 this, SLOT( slotMenuTran(QListViewItem *, const QPoint &) ) ); 243 this, SLOT( slotMenuTran(QListViewItem*,const QPoint&) ) );
244 connect( tranTable, SIGNAL( doubleClicked( QListViewItem * ) ), 244 connect( tranTable, SIGNAL( doubleClicked(QListViewItem*) ),
245 this, SLOT( slotEditTran() ) ); 245 this, SLOT( slotEditTran() ) );
246 _sortCol=COL_ID; 246 _sortCol=COL_ID;
247 247
248 // Buttons 248 // Buttons
249 QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), control ); 249 QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), control );
250 QWhatsThis::add( btn, tr( "Click here to add a new transaction." ) ); 250 QWhatsThis::add( btn, tr( "Click here to add a new transaction." ) );
251 connect( btn, SIGNAL( clicked() ), this, SLOT( slotNewTran() ) ); 251 connect( btn, SIGNAL( clicked() ), this, SLOT( slotNewTran() ) );
252 layout->addWidget( btn, 2, 0 ); 252 layout->addWidget( btn, 2, 0 );
253 253
254 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Edit" ), control ); 254 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Edit" ), control );
255 QWhatsThis::add( btn, tr( "Select a transaction and then click here to edit it." ) ); 255 QWhatsThis::add( btn, tr( "Select a transaction and then click here to edit it." ) );
256 connect( btn, SIGNAL( clicked() ), this, SLOT( slotEditTran() ) ); 256 connect( btn, SIGNAL( clicked() ), this, SLOT( slotEditTran() ) );
257 layout->addWidget( btn, 2, 1 ); 257 layout->addWidget( btn, 2, 1 );
258 258
259 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), control ); 259 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), control );
260 QWhatsThis::add( btn, tr( "Select a checkbook and then click here to delete it." ) ); 260 QWhatsThis::add( btn, tr( "Select a checkbook and then click here to delete it." ) );
261 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDeleteTran() ) ); 261 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDeleteTran() ) );
262 layout->addWidget( btn, 2, 2 ); 262 layout->addWidget( btn, 2, 2 );
263 263
264 return( control ); 264 return( control );
265} 265}
266 266
267 267
268// --- initCharts ------------------------------------------------------------- 268// --- initCharts -------------------------------------------------------------
269QWidget *Checkbook::initCharts() 269QWidget *Checkbook::initCharts()
270{ 270{
271 graphInfo = 0x0; 271 graphInfo = 0x0;
272 272
273 QWidget *control = new QWidget( mainWidget, tr("Charts") ); 273 QWidget *control = new QWidget( mainWidget, tr("Charts") );
274 274
275 QGridLayout *layout = new QGridLayout( control ); 275 QGridLayout *layout = new QGridLayout( control );
276 layout->setSpacing( 2 ); 276 layout->setSpacing( 2 );
277 layout->setMargin( 4 ); 277 layout->setMargin( 4 );
278 278
279 graphWidget = new Graph( control ); 279 graphWidget = new Graph( control );
280 QWhatsThis::add( graphWidget, tr( "Select the desired chart below and then click on the Draw button." ) ); 280 QWhatsThis::add( graphWidget, tr( "Select the desired chart below and then click on the Draw button." ) );
281 layout->addMultiCellWidget( graphWidget, 0, 0, 0, 2 ); 281 layout->addMultiCellWidget( graphWidget, 0, 0, 0, 2 );
282 282
283 graphList = new QComboBox( control ); 283 graphList = new QComboBox( control );
284 QWhatsThis::add( graphList, tr( "Click here to select the desired chart type." ) ); 284 QWhatsThis::add( graphList, tr( "Click here to select the desired chart type." ) );
285 graphList->insertItem( tr( "Account balance" ) ); 285 graphList->insertItem( tr( "Account balance" ) );
286 graphList->insertItem( tr( "Withdrawals by category" ) ); 286 graphList->insertItem( tr( "Withdrawals by category" ) );
287 graphList->insertItem( tr( "Deposits by category" ) ); 287 graphList->insertItem( tr( "Deposits by category" ) );
288 288
289 layout->addMultiCellWidget( graphList, 1, 1, 0, 1 ); 289 layout->addMultiCellWidget( graphList, 1, 1, 0, 1 );
290 290
291 QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/drawbtn" ), tr( "Draw" ), control ); 291 QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/drawbtn" ), tr( "Draw" ), control );
292 QWhatsThis::add( btn, tr( "Click here to draw the selected chart." ) ); 292 QWhatsThis::add( btn, tr( "Click here to draw the selected chart." ) );
293 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDrawGraph() ) ); 293 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDrawGraph() ) );
294 layout->addWidget( btn, 1, 2 ); 294 layout->addWidget( btn, 1, 2 );
295 295
296 return control; 296 return control;
297} 297}
298 298
299// --- loadCheckbook ---------------------------------------------------------- 299// --- loadCheckbook ----------------------------------------------------------
300void Checkbook::loadCheckbook() 300void Checkbook::loadCheckbook()
301{ 301{
302 if ( !info ) 302 if ( !info )
303 { 303 {
304 return; 304 return;
305 } 305 }
306 306
307 tranList = info->transactions(); 307 tranList = info->transactions();
308 308
309 passwordCB->setChecked( !info->password().isNull() ); 309 passwordCB->setChecked( !info->password().isNull() );
310 nameEdit->setText( info->name() ); 310 nameEdit->setText( info->name() );
311 QString temptext = info->type(); 311 QString temptext = info->type();
312 int i = typeList->count(); 312 int i = typeList->count();
313 while ( i > 0 ) 313 while ( i > 0 )
314 { 314 {
315 i--; 315 i--;
316 typeList->setCurrentItem( i ); 316 typeList->setCurrentItem( i );
317 if ( typeList->currentText() == temptext ) 317 if ( typeList->currentText() == temptext )
318 { 318 {
319 break; 319 break;
320 } 320 }
321 } 321 }
322 if( i<=0 ) { 322 if( i<=0 ) {
323 typeList->insertItem( temptext, 0 ); 323 typeList->insertItem( temptext, 0 );
324 typeList->setCurrentItem(0); 324 typeList->setCurrentItem(0);
325 } 325 }
326 bankEdit->setText( info->bank() ); 326 bankEdit->setText( info->bank() );
327 acctNumEdit->setText( info->account() ); 327 acctNumEdit->setText( info->account() );
328 pinNumEdit->setText( info->pin() ); 328 pinNumEdit->setText( info->pin() );
329 temptext.setNum( info->startingBalance(), 'f', 2 ); 329 temptext.setNum( info->startingBalance(), 'f', 2 );
330 balanceEdit->setText( temptext ); 330 balanceEdit->setText( temptext );
331 notesEdit->setText( info->notes() ); 331 notesEdit->setText( info->notes() );
332 332
333 // Load transactions 333 // Load transactions
334 float amount; 334 float amount;
335 QString stramount; 335 QString stramount;
336 for ( TranInfo *tran = tranList->first(); tran; tran = tranList->next() ) 336 for ( TranInfo *tran = tranList->first(); tran; tran = tranList->next() )
337 { 337 {
338 amount = tran->amount(); 338 amount = tran->amount();
339 if ( tran->withdrawal() ) 339 if ( tran->withdrawal() )
340 { 340 {
341 amount *= -1; 341 amount *= -1;
342 } 342 }
343 stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount ); 343 stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount );
344 ( void ) new CBListItem( tran, tranTable, tran->getIdStr(), tran->datestr(false), tran->number(), tran->datestr(true), tran->desc(), stramount ); 344 ( void ) new CBListItem( tran, tranTable, tran->getIdStr(), tran->datestr(false), tran->number(), tran->datestr(true), tran->desc(), stramount );
345 } 345 }
346 346
347 // set sort order 347 // set sort order
348 bool bOk=false; 348 bool bOk=false;
349 for(int i=0; i<_cbSortType->count(); i++) { 349 for(int i=0; i<_cbSortType->count(); i++) {
350 if( _cbSortType->text(i)==info->getSortOrder() ) { 350 if( _cbSortType->text(i)==info->getSortOrder() ) {
351 _cbSortType->setCurrentItem(i); 351 _cbSortType->setCurrentItem(i);
352 slotSortChanged( info->getSortOrder() ); 352 slotSortChanged( info->getSortOrder() );
353 bOk=true; 353 bOk=true;
354 break; 354 break;
355 } 355 }
356 } 356 }
357 if( !bOk ) { 357 if( !bOk ) {
358 _cbSortType->setCurrentItem(0); 358 _cbSortType->setCurrentItem(0);
359 slotSortChanged( _cbSortType->currentText() ); 359 slotSortChanged( _cbSortType->currentText() );
360 } 360 }
361 361
362 // calc running balance 362 // calc running balance
363 adjustBalance(); 363 adjustBalance();
364} 364}
365 365
366 366
367// --- adjustBalance ---------------------------------------------------------- 367// --- adjustBalance ----------------------------------------------------------
368void Checkbook::adjustBalance() 368void Checkbook::adjustBalance()
369{ 369{
370 // update running balance in register 370 // update running balance in register
371 QString sRunning; 371 QString sRunning;
372 float bal=info->startingBalance(); 372 float bal=info->startingBalance();
373 for(CBListItem *item=(CBListItem *)tranTable->firstChild(); item; item=(CBListItem *)item->nextSibling() ) { 373 for(CBListItem *item=(CBListItem *)tranTable->firstChild(); item; item=(CBListItem *)item->nextSibling() ) {
374 TranInfo *tran=item->getTranInfo(); 374 TranInfo *tran=item->getTranInfo();
375 bal=bal + (tran->withdrawal() ? -1 : 1)*tran->amount() - tran->fee(); 375 bal=bal + (tran->withdrawal() ? -1 : 1)*tran->amount() - tran->fee();
376 sRunning.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), bal ); 376 sRunning.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), bal );
377 item->setText( COL_BAL, sRunning); 377 item->setText( COL_BAL, sRunning);
378 } 378 }
379} 379}
380 380
381// --- resort ----------------------------------------------------------------- 381// --- resort -----------------------------------------------------------------
382void Checkbook::resort() 382void Checkbook::resort()
383{ 383{
384 tranTable->setSorting(_sortCol); 384 tranTable->setSorting(_sortCol);
385 tranTable->sort(); 385 tranTable->sort();
386 tranTable->setSorting(-1); 386 tranTable->setSorting(-1);
387} 387}
388 388
389 389
390// --- accept ----------------------------------------------------------------- 390// --- accept -----------------------------------------------------------------
391void Checkbook::accept() 391void Checkbook::accept()
392{ 392{
393 info->setName( nameEdit->text() ); 393 info->setName( nameEdit->text() );
394 info->setType( typeList->currentText() ); 394 info->setType( typeList->currentText() );
395 info->setBank( bankEdit->text() ); 395 info->setBank( bankEdit->text() );
396 info->setAccount( acctNumEdit->text() ); 396 info->setAccount( acctNumEdit->text() );
397 info->setPin( pinNumEdit->text() ); 397 info->setPin( pinNumEdit->text() );
398 bool ok; 398 bool ok;
399 info->setStartingBalance( balanceEdit->text().toFloat( &ok ) ); 399 info->setStartingBalance( balanceEdit->text().toFloat( &ok ) );
400 info->setNotes( notesEdit->text() ); 400 info->setNotes( notesEdit->text() );
401 401
402 QDialog::accept(); 402 QDialog::accept();
403} 403}
404 404
405// --- slotPasswordClicked ---------------------------------------------------- 405// --- slotPasswordClicked ----------------------------------------------------
406void Checkbook::slotPasswordClicked() 406void Checkbook::slotPasswordClicked()
407{ 407{
408 if ( info->password().isNull() && passwordCB->isChecked() ) 408 if ( info->password().isNull() && passwordCB->isChecked() )
409 { 409 {
410 Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) ); 410 Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) );
411 if ( pw->exec() != QDialog::Accepted ) 411 if ( pw->exec() != QDialog::Accepted )
412 { 412 {
413 passwordCB->setChecked( FALSE ); 413 passwordCB->setChecked( FALSE );
414 delete pw; 414 delete pw;
415 return; 415 return;
416 } 416 }
417 info->setPassword( pw->password ); 417 info->setPassword( pw->password );
418 delete pw; 418 delete pw;
419 419
420 pw = new Password( this, tr( "Confirm password" ), tr( "Please confirm your password:" ) ); 420 pw = new Password( this, tr( "Confirm password" ), tr( "Please confirm your password:" ) );
421 if ( pw->exec() != QDialog::Accepted || pw->password != info->password() ) 421 if ( pw->exec() != QDialog::Accepted || pw->password != info->password() )
422 { 422 {
423 passwordCB->setChecked( FALSE ); 423 passwordCB->setChecked( FALSE );
424 info->setPassword( QString::null ); 424 info->setPassword( QString::null );
425 } 425 }
426 426
427 delete pw; 427 delete pw;
428 } 428 }
429 else if ( !info->password().isNull() && !passwordCB->isChecked() ) 429 else if ( !info->password().isNull() && !passwordCB->isChecked() )
430 { 430 {
431 Password *pw = new Password( this, tr( "Enter password" ), 431 Password *pw = new Password( this, tr( "Enter password" ),
432 tr( "Please enter your password to confirm removal of password protection:" ) ); 432 tr( "Please enter your password to confirm removal of password protection:" ) );
433 if ( pw->exec() == QDialog::Accepted && pw->password == info->password() ) 433 if ( pw->exec() == QDialog::Accepted && pw->password == info->password() )
434 { 434 {
435 info->setPassword( QString::null ); 435 info->setPassword( QString::null );
436 delete pw; 436 delete pw;
437 return; 437 return;
438 } 438 }
439 else 439 else
440 { 440 {
441 passwordCB->setChecked( TRUE ); 441 passwordCB->setChecked( TRUE );
442 } 442 }
443 443
444 delete pw; 444 delete pw;
445 } 445 }
446} 446}
447 447
448void Checkbook::slotNameChanged( const QString &newname ) 448void Checkbook::slotNameChanged( const QString &newname )
449{ 449{
450 info->setName( newname ); 450 info->setName( newname );
451 451
452 // TODO - need filedir 452 // TODO - need filedir
453// QString namestr = filedir; 453// QString namestr = filedir;
454// namestr.append( newname ); 454// namestr.append( newname );
455// namestr.append( ".qcb" ); 455// namestr.append( ".qcb" );
456// info->setFilename( namestr ); 456// info->setFilename( namestr );
457 457
458 QString namestr = newname; 458 QString namestr = newname;
459 namestr.append( " - " ); 459 namestr.append( " - " );
460 namestr.append( tr( "Checkbook" ) ); 460 namestr.append( tr( "Checkbook" ) );
461 setCaption( namestr ); 461 setCaption( namestr );
462} 462}
463 463
464 464
465// ---slotStartingBalanceChanged ---------------------------------------------- 465// ---slotStartingBalanceChanged ----------------------------------------------
466void Checkbook::slotStartingBalanceChanged( const QString &newbalance ) 466void Checkbook::slotStartingBalanceChanged( const QString &newbalance )
467{ 467{
468 bool ok; 468 bool ok;
469 info->setStartingBalance( newbalance.toFloat( &ok ) ); 469 info->setStartingBalance( newbalance.toFloat( &ok ) );
470 adjustBalance(); 470 adjustBalance();
471} 471}
472 472
473 473
474// --- slotNewTran ------------------------------------------------------------ 474// --- slotNewTran ------------------------------------------------------------
475void Checkbook::slotNewTran() 475void Checkbook::slotNewTran()
476{ 476{
477 TranInfo *traninfo = new TranInfo( info->getNextNumber() ); 477 TranInfo *traninfo = new TranInfo( info->getNextNumber() );
478 if( !_dLastNew.isNull() ) 478 if( !_dLastNew.isNull() )
479 traninfo->setDate(_dLastNew); 479 traninfo->setDate(_dLastNew);
480 480
481 Transaction *currtran = new Transaction( this, true, info->name(), 481 Transaction *currtran = new Transaction( this, true, info->name(),
482 traninfo, 482 traninfo,
483 _pCfg ); 483 _pCfg );
484 if ( QPEApplication::execDialog( currtran ) == QDialog::Accepted ) 484 if ( QPEApplication::execDialog( currtran ) == QDialog::Accepted )
485 { 485 {
486 // Add to transaction list 486 // Add to transaction list
487 info->addTransaction( traninfo ); 487 info->addTransaction( traninfo );
488 488
489 // Add to transaction table 489 // Add to transaction table
490 float amount; 490 float amount;
491 QString stramount; 491 QString stramount;
492 amount = (traninfo->withdrawal() ? -1 : 1)*traninfo->amount(); 492 amount = (traninfo->withdrawal() ? -1 : 1)*traninfo->amount();
493 stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount ); 493 stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount );
494 ( void ) new CBListItem( traninfo, tranTable, traninfo->getIdStr(), traninfo->datestr(false), 494 ( void ) new CBListItem( traninfo, tranTable, traninfo->getIdStr(), traninfo->datestr(false),
495 traninfo->number(), traninfo->datestr(true), traninfo->desc(), 495 traninfo->number(), traninfo->datestr(true), traninfo->desc(),
496 stramount ); 496 stramount );
497 resort(); 497 resort();
498 adjustBalance(); 498 adjustBalance();
499 499
500 // save last date 500 // save last date
501 _dLastNew = traninfo->date(); 501 _dLastNew = traninfo->date();
502 502
503 // save description in list of payees, if not in there 503 // save description in list of payees, if not in there
504 QStringList *pLst=&_pCfg->getPayees(); 504 QStringList *pLst=&_pCfg->getPayees();
505 if( _pCfg->getSavePayees() && pLst->contains(traninfo->desc())==0 ) { 505 if( _pCfg->getSavePayees() && pLst->contains(traninfo->desc())==0 ) {
506 pLst->append( traninfo->desc() ); 506 pLst->append( traninfo->desc() );
507 pLst->sort(); 507 pLst->sort();
508 _pCfg->setDirty(true); 508 _pCfg->setDirty(true);
509 } 509 }
510 } 510 }
511 else 511 else
512 { 512 {
513 delete traninfo; 513 delete traninfo;
514 } 514 }
515} 515}
516 516
517 517
518// --- slotEditTran ----------------------------------------------------------- 518// --- slotEditTran -----------------------------------------------------------
519void Checkbook::slotEditTran() 519void Checkbook::slotEditTran()
520{ 520{
521 QListViewItem *curritem = tranTable->currentItem(); 521 QListViewItem *curritem = tranTable->currentItem();
522 if ( !curritem ) 522 if ( !curritem )
523 return; 523 return;
524 524
525 TranInfo *traninfo=info->findTransaction( curritem->text(COL_ID) ); 525 TranInfo *traninfo=info->findTransaction( curritem->text(COL_ID) );
526 526
527 Transaction *currtran = new Transaction( this, false, info->name(), 527 Transaction *currtran = new Transaction( this, false, info->name(),
528 traninfo, 528 traninfo,
529 _pCfg ); 529 _pCfg );
530 if ( QPEApplication::execDialog( currtran ) == QDialog::Accepted ) 530 if ( QPEApplication::execDialog( currtran ) == QDialog::Accepted )
531 { 531 {
532 curritem->setText( COL_NUM, traninfo->number() ); 532 curritem->setText( COL_NUM, traninfo->number() );
533 curritem->setText( COL_SORTDATE, traninfo->datestr(false) ); 533 curritem->setText( COL_SORTDATE, traninfo->datestr(false) );
534 curritem->setText( COL_DATE, traninfo->datestr(true) ); 534 curritem->setText( COL_DATE, traninfo->datestr(true) );
535 curritem->setText( COL_DESC, traninfo->desc() ); 535 curritem->setText( COL_DESC, traninfo->desc() );
536 536
537 float amount = traninfo->amount(); 537 float amount = traninfo->amount();
538 if ( traninfo->withdrawal() ) 538 if ( traninfo->withdrawal() )
539 { 539 {
540 amount *= -1; 540 amount *= -1;
541 } 541 }
542 QString stramount; 542 QString stramount;
543 stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount ); 543 stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount );
544 curritem->setText( COL_AMOUNT, stramount ); 544 curritem->setText( COL_AMOUNT, stramount );
545 resort(); 545 resort();
546 adjustBalance(); 546 adjustBalance();
547 547
548 // save description in list of payees, if not in there 548 // save description in list of payees, if not in there
549 QStringList *pLst=&_pCfg->getPayees(); 549 QStringList *pLst=&_pCfg->getPayees();
550 if( _pCfg->getSavePayees() && pLst->contains(traninfo->desc())==0 ) { 550 if( _pCfg->getSavePayees() && pLst->contains(traninfo->desc())==0 ) {
551 pLst->append( traninfo->desc() ); 551 pLst->append( traninfo->desc() );
552 pLst->sort(); 552 pLst->sort();
553 _pCfg->setDirty(true); 553 _pCfg->setDirty(true);
554 } 554 }
555 } 555 }
556 556
557 delete currtran; 557 delete currtran;
558} 558}
559 559
560// --- slotMenuTran ----------------------------------------------------------- 560// --- slotMenuTran -----------------------------------------------------------
561void Checkbook::slotMenuTran(QListViewItem *item, const QPoint &pnt) 561void Checkbook::slotMenuTran(QListViewItem *item, const QPoint &pnt)
562{ 562{
563 // active item? 563 // active item?
564 if( !item ) 564 if( !item )
565 return; 565 return;
566 566
567 // Display menu 567 // Display menu
568 QPopupMenu m; 568 QPopupMenu m;
569 m.insertItem( QWidget::tr( "Edit" ), 1 ); 569 m.insertItem( QWidget::tr( "Edit" ), 1 );
570 m.insertItem( QWidget::tr( "New" ), 2 ); 570 m.insertItem( QWidget::tr( "New" ), 2 );
571 m.insertItem( QWidget::tr( "Delete" ), 3 ); 571 m.insertItem( QWidget::tr( "Delete" ), 3 );
572 int r = m.exec( pnt ); 572 int r = m.exec( pnt );
573 switch(r) { 573 switch(r) {
574 case 1: 574 case 1:
575 slotEditTran(); 575 slotEditTran();
576 break; 576 break;
577 case 2: 577 case 2:
578 slotNewTran(); 578 slotNewTran();
579 break; 579 break;
580 case 3: 580 case 3:
581 slotDeleteTran(); 581 slotDeleteTran();
582 break; 582 break;
583 } 583 }
584} 584}
585 585
586 586
587// --- slotDeleteTran --------------------------------------------------------- 587// --- slotDeleteTran ---------------------------------------------------------
588void Checkbook::slotDeleteTran() 588void Checkbook::slotDeleteTran()
589{ 589{
590 QListViewItem *curritem = tranTable->currentItem(); 590 QListViewItem *curritem = tranTable->currentItem();
591 if ( !curritem ) 591 if ( !curritem )
592 return; 592 return;
593 593
594 TranInfo *traninfo = info->findTransaction( curritem->text(COL_ID) ); 594 TranInfo *traninfo = info->findTransaction( curritem->text(COL_ID) );
595 595
596 if ( QPEMessageBox::confirmDelete ( this, tr( "Delete transaction" ), traninfo->desc() ) ) 596 if ( QPEMessageBox::confirmDelete ( this, tr( "Delete transaction" ), traninfo->desc() ) )
597 { 597 {
598 info->removeTransaction( traninfo ); 598 info->removeTransaction( traninfo );
599 delete curritem; 599 delete curritem;
600 adjustBalance(); 600 adjustBalance();
601 } 601 }
602} 602}
603 603
604void Checkbook::slotDrawGraph() 604void Checkbook::slotDrawGraph()
605{ 605{
606 if ( graphInfo ) 606 if ( graphInfo )
607 { 607 {
608 delete graphInfo; 608 delete graphInfo;
609 } 609 }
610 610
611 switch ( graphList->currentItem() ) 611 switch ( graphList->currentItem() )
612 { 612 {
613 case 0 : drawBalanceChart(); 613 case 0 : drawBalanceChart();
614 break; 614 break;
615 case 1 : drawCategoryChart( TRUE ); 615 case 1 : drawCategoryChart( TRUE );
616 break; 616 break;
617 case 2 : drawCategoryChart( FALSE ); 617 case 2 : drawCategoryChart( FALSE );
618 break; 618 break;
619 }; 619 };
620 620
621 graphWidget->setGraphInfo( graphInfo ); 621 graphWidget->setGraphInfo( graphInfo );
622 graphWidget->drawGraph( TRUE ); 622 graphWidget->drawGraph( TRUE );
623} 623}
624 624
625void Checkbook::drawBalanceChart() 625void Checkbook::drawBalanceChart()
626{ 626{
627 DataPointList *list = new DataPointList(); 627 DataPointList *list = new DataPointList();
628 628
629 float balance = info->startingBalance(); 629 float balance = info->startingBalance();
630 float amount; 630 float amount;
631 QString label; 631 QString label;
632 int i = 0; 632 int i = 0;
633 int count = tranList->count(); 633 int count = tranList->count();
634 634
635 for ( TranInfo *tran = tranList->first(); tran; tran = tranList->next() ) 635 for ( TranInfo *tran = tranList->first(); tran; tran = tranList->next() )
636 { 636 {
637 i++; 637 i++;
638 balance -= tran->fee(); 638 balance -= tran->fee();
639 amount = tran->amount(); 639 amount = tran->amount();
640 if ( tran->withdrawal() ) 640 if ( tran->withdrawal() )
641 { 641 {
642 amount *= -1; 642 amount *= -1;
643 } 643 }
644 balance += amount; 644 balance += amount;
645 if ( i == 1 || i == count / 2 || i == count ) 645 if ( i == 1 || i == count / 2 || i == count )
646 { 646 {
647 label = tran->datestr(true); 647 label = tran->datestr(true);
648 } 648 }
649 else 649 else
650 { 650 {
651 label = ""; 651 label = "";
652 } 652 }
653 list->append( new DataPointInfo( label, balance ) ); 653 list->append( new DataPointInfo( label, balance ) );
654 } 654 }
655 655
656 graphInfo = new GraphInfo( GraphInfo::BarChart, list ); 656 graphInfo = new GraphInfo( GraphInfo::BarChart, list );
657} 657}
658 658
659void Checkbook::drawCategoryChart( bool withdrawals ) 659void Checkbook::drawCategoryChart( bool withdrawals )
660{ 660{
661 DataPointList *list = new DataPointList(); 661 DataPointList *list = new DataPointList();
662 662
663 TranInfo *tran = tranList->first(); 663 TranInfo *tran = tranList->first();
664 if ( tran && tran->withdrawal() == withdrawals ) 664 if ( tran && tran->withdrawal() == withdrawals )
665 { 665 {
666 list->append( new DataPointInfo( tran->category(), tran->amount() ) ); 666 list->append( new DataPointInfo( tran->category(), tran->amount() ) );
667 } 667 }
668 tran = tranList->next(); 668 tran = tranList->next();
669 669
670 DataPointInfo *cat; 670 DataPointInfo *cat;
671 for ( ; tran; tran = tranList->next() ) 671 for ( ; tran; tran = tranList->next() )
672 { 672 {
673 if ( tran->withdrawal() == withdrawals ) 673 if ( tran->withdrawal() == withdrawals )
674 { 674 {
675 // Find category in list 675 // Find category in list
676 for ( cat = list->first(); cat; cat = list->next() ) 676 for ( cat = list->first(); cat; cat = list->next() )
677 { 677 {
678 if ( cat->label() == tran->category() ) 678 if ( cat->label() == tran->category() )
679 { 679 {
680 break; 680 break;
681 } 681 }
682 } 682 }
683 if ( cat && cat->label() == tran->category() ) 683 if ( cat && cat->label() == tran->category() )
684 { // Found category, add to transaction to category total 684 { // Found category, add to transaction to category total
685 cat->addToValue( tran->amount() ); 685 cat->addToValue( tran->amount() );
686 } 686 }
687 else 687 else
688 { // Didn't find category, add category to list 688 { // Didn't find category, add category to list
689 list->append( new DataPointInfo( tran->category(), tran->amount() ) ); 689 list->append( new DataPointInfo( tran->category(), tran->amount() ) );
690 } 690 }
691 } 691 }
692 } 692 }
693 693
694 graphInfo = new GraphInfo( GraphInfo::PieChart, list ); 694 graphInfo = new GraphInfo( GraphInfo::PieChart, list );
695} 695}
696 696
697CBListItem::CBListItem( TranInfo *pTran, QListView *parent, QString label1, QString label2, 697CBListItem::CBListItem( TranInfo *pTran, QListView *parent, QString label1, QString label2,
698 QString label3, QString label4, QString label5, QString label6, QString label7, 698 QString label3, QString label4, QString label5, QString label6, QString label7,
699 QString label8 ) 699 QString label8 )
700 : QListViewItem( parent, label1, label2, label3, label4, label5, label6, label7, label8 ) 700 : QListViewItem( parent, label1, label2, label3, label4, label5, label6, label7, label8 )
701{ 701{
702 _pTran=pTran; 702 _pTran=pTran;
703 m_known = FALSE; 703 m_known = FALSE;
704 owner = parent; 704 owner = parent;
705} 705}
706 706
707void CBListItem::paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int align ) 707void CBListItem::paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int align )
708{ 708{
709 QColorGroup _cg = cg; 709 QColorGroup _cg = cg;
710 const QPixmap *pm = listView()->viewport()->backgroundPixmap(); 710 const QPixmap *pm = listView()->viewport()->backgroundPixmap();
711 if ( pm && !pm->isNull() ) 711 if ( pm && !pm->isNull() )
712 { 712 {
713 _cg.setBrush( QColorGroup::Base, QBrush( cg.base(), *pm ) ); 713 _cg.setBrush( QColorGroup::Base, QBrush( cg.base(), *pm ) );
714 p->setBrushOrigin( -listView()->contentsX(), -listView()->contentsY() ); 714 p->setBrushOrigin( -listView()->contentsX(), -listView()->contentsY() );
715 } 715 }
716 else if ( isAltBackground() ) 716 else if ( isAltBackground() )
717 _cg.setColor(QColorGroup::Base, cg.background() ); 717 _cg.setColor(QColorGroup::Base, cg.background() );
718 718
719 QListViewItem::paintCell(p, _cg, column, width, align); 719 QListViewItem::paintCell(p, _cg, column, width, align);
720} 720}
721 721
722// --- CBListItem::isAltBackground -------------------------------------------- 722// --- CBListItem::isAltBackground --------------------------------------------
723bool CBListItem::isAltBackground() 723bool CBListItem::isAltBackground()
724{ 724{
725 QListView *lv = static_cast<QListView *>( listView() ); 725 QListView *lv = static_cast<QListView *>( listView() );
726 if ( lv ) 726 if ( lv )
727 { 727 {
728 CBListItem *above = 0; 728 CBListItem *above = 0;
729 above = (CBListItem *)( itemAbove() ); 729 above = (CBListItem *)( itemAbove() );
730 m_known = above ? above->m_known : true; 730 m_known = above ? above->m_known : true;
731 if ( m_known ) 731 if ( m_known )
732 { 732 {
733 m_odd = above ? !above->m_odd : false; 733 m_odd = above ? !above->m_odd : false;
734 } 734 }
735 else 735 else
736 { 736 {
737 CBListItem *item; 737 CBListItem *item;
738 bool previous = true; 738 bool previous = true;
739 if ( parent() ) 739 if ( parent() )
740 { 740 {
741 item = (CBListItem *)( parent() ); 741 item = (CBListItem *)( parent() );
742 if ( item ) 742 if ( item )
743 previous = item->m_odd; 743 previous = item->m_odd;
744 item = (CBListItem *)( parent()->firstChild() ); 744 item = (CBListItem *)( parent()->firstChild() );
745 } 745 }
746 else 746 else
747 { 747 {
748 item = (CBListItem *)( lv->firstChild() ); 748 item = (CBListItem *)( lv->firstChild() );
749 } 749 }
750 750
751 while(item) 751 while(item)
752 { 752 {
753 item->m_odd = previous = !previous; 753 item->m_odd = previous = !previous;
754 item->m_known = true; 754 item->m_known = true;
755 item = (CBListItem *)( item->nextSibling() ); 755 item = (CBListItem *)( item->nextSibling() );
756 } 756 }
757 } 757 }
758 return m_odd; 758 return m_odd;
759 } 759 }
760 return false; 760 return false;
761} 761}
762 762
763 763
764// --- slotTab ---------------------------------------------------------------- 764// --- slotTab ----------------------------------------------------------------
765void Checkbook::slotTab(QWidget *tab) 765void Checkbook::slotTab(QWidget *tab)
766{ 766{
767 if( !tab || !info ) return; 767 if( !tab || !info ) return;
768 info->setLastTab( tab->name() ); 768 info->setLastTab( tab->name() );
769} 769}
770 770
771 771
772// --- slotSortChanged --------------------------------------------------------- 772// --- slotSortChanged ---------------------------------------------------------
773void Checkbook::slotSortChanged( const QString &selc ) 773void Checkbook::slotSortChanged( const QString &selc )
774{ 774{
775 if( selc==tr("Entry Order") ) { 775 if( selc==tr("Entry Order") ) {
776 _sortCol=COL_ID; 776 _sortCol=COL_ID;
777 } else if( selc==tr("Number") ) { 777 } else if( selc==tr("Number") ) {
778 _sortCol=COL_NUM; 778 _sortCol=COL_NUM;
779 } else if( selc==tr("Date") ) { 779 } else if( selc==tr("Date") ) {
780 _sortCol=COL_SORTDATE; 780 _sortCol=COL_SORTDATE;
781 } 781 }
782 info->setSortOrder( selc ); 782 info->setSortOrder( selc );
783 resort(); 783 resort();
784} 784}
785 785
diff --git a/noncore/apps/checkbook/listedit.cpp b/noncore/apps/checkbook/listedit.cpp
index 37f05f0..d00e305 100644
--- a/noncore/apps/checkbook/listedit.cpp
+++ b/noncore/apps/checkbook/listedit.cpp
@@ -1,344 +1,344 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "listedit.h" 29#include "listedit.h"
30#include <qlayout.h> 30#include <qlayout.h>
31#include <qlineedit.h> 31#include <qlineedit.h>
32#include <qlistview.h> 32#include <qlistview.h>
33#include <qwidgetstack.h> 33#include <qwidgetstack.h>
34#include <qcombobox.h> 34#include <qcombobox.h>
35#include <qpushbutton.h> 35#include <qpushbutton.h>
36#include <qpe/resource.h> 36#include <qpe/resource.h>
37 37
38 38
39// --- ListEdit --------------------------------------------------------------- 39// --- ListEdit ---------------------------------------------------------------
40ListEdit::ListEdit( QWidget *parent, const char *sName ) 40ListEdit::ListEdit( QWidget *parent, const char *sName )
41 : QWidget(parent, sName), TableDef(sName) 41 : QWidget(parent, sName), TableDef(sName)
42{ 42{
43 // get font height 43 // get font height
44 int fh = fontMetrics().height(); 44 int fh = fontMetrics().height();
45 45
46 // create layout 46 // create layout
47 QGridLayout *layout=new QGridLayout(this); 47 QGridLayout *layout=new QGridLayout(this);
48 layout->setSpacing( 2 ); 48 layout->setSpacing( 2 );
49 layout->setMargin( 4 ); 49 layout->setMargin( 4 );
50 50
51 // type table 51 // type table
52 _typeTable = new QListView( this ); 52 _typeTable = new QListView( this );
53 ColumnDef *def=first(); 53 ColumnDef *def=first();
54 while( def ) { 54 while( def ) {
55 _typeTable->addColumn( def->getName() ); 55 _typeTable->addColumn( def->getName() );
56 def=next(); 56 def=next();
57 } 57 }
58 connect( _typeTable, SIGNAL( clicked(QListViewItem *, const QPoint &, int) ), this, SLOT( slotClick(QListViewItem *, const QPoint &, int ) ) ); 58 connect( _typeTable, SIGNAL( clicked(QListViewItem*,const QPoint&,int) ), this, SLOT( slotClick(QListViewItem*,const QPoint&,int) ) );
59 layout->addMultiCellWidget(_typeTable, 0,4,0,4); 59 layout->addMultiCellWidget(_typeTable, 0,4,0,4);
60 _currentItem=NULL; 60 _currentItem=NULL;
61 61
62 // edit field 62 // edit field
63 _stack=new QWidgetStack( this ); 63 _stack=new QWidgetStack( this );
64 _stack->setMaximumHeight(fh+5); 64 _stack->setMaximumHeight(fh+5);
65 layout->addMultiCellWidget(_stack, 5,5,0,2); 65 layout->addMultiCellWidget(_stack, 5,5,0,2);
66 _typeEdit = new QLineEdit( _stack ); 66 _typeEdit = new QLineEdit( _stack );
67 _stack->raiseWidget(_typeEdit ); 67 _stack->raiseWidget(_typeEdit );
68 connect( _typeEdit, SIGNAL( textChanged(const QString &) ), this, SLOT( slotEditChanged(const QString &) ) ); 68 connect( _typeEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotEditChanged(const QString&) ) );
69 69
70 // combo box 70 // combo box
71 _box=new QComboBox( _stack ); 71 _box=new QComboBox( _stack );
72 connect( _box, SIGNAL( activated(const QString &) ), this, SLOT( slotActivated(const QString &) ) ); 72 connect( _box, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) );
73 73
74 74
75 // add button 75 // add button
76 QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/add" ), tr( "Add" ), this ); 76 QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/add" ), tr( "Add" ), this );
77 connect( btn, SIGNAL( clicked() ), this, SLOT( slotAdd() ) ); 77 connect( btn, SIGNAL( clicked() ), this, SLOT( slotAdd() ) );
78 layout->addWidget( btn, 5, 3 ); 78 layout->addWidget( btn, 5, 3 );
79 79
80 // delete button 80 // delete button
81 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), this ); 81 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), this );
82 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDel() ) ); 82 connect( btn, SIGNAL( clicked() ), this, SLOT( slotDel() ) );
83 layout->addWidget( btn, 5, 4 ); 83 layout->addWidget( btn, 5, 4 );
84} 84}
85 85
86// --- ~ListEdit -------------------------------------------------------------- 86// --- ~ListEdit --------------------------------------------------------------
87ListEdit::~ListEdit() 87ListEdit::~ListEdit()
88{ 88{
89} 89}
90 90
91 91
92// --- slotEditTypeChanged ---------------------------------------------------- 92// --- slotEditTypeChanged ----------------------------------------------------
93void ListEdit::slotEditChanged(const QString &str) 93void ListEdit::slotEditChanged(const QString &str)
94{ 94{
95 if( !_currentItem || _currentColumn<0 ) return; 95 if( !_currentItem || _currentColumn<0 ) return;
96 _currentItem->setText(_currentColumn, str); 96 _currentItem->setText(_currentColumn, str);
97} 97}
98 98
99// --- slotAddType ------------------------------------------------------------ 99// --- slotAddType ------------------------------------------------------------
100void ListEdit::slotAdd() 100void ListEdit::slotAdd()
101{ 101{
102 // construct new row 102 // construct new row
103 QString args[8]; 103 QString args[8];
104 ColumnDef *pCol=this->first(); 104 ColumnDef *pCol=this->first();
105 int i=0; 105 int i=0;
106 while( pCol && i<8 ) { 106 while( pCol && i<8 ) {
107 args[i++]=pCol->getNewValue(); 107 args[i++]=pCol->getNewValue();
108 pCol=this->next(); 108 pCol=this->next();
109 } 109 }
110 _currentItem=new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] ); 110 _currentItem=new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] );
111 111
112 // fix uniques 112 // fix uniques
113 fixTypes(); 113 fixTypes();
114 114
115 // display col 0 of new value 115 // display col 0 of new value
116 QPoint pnt; 116 QPoint pnt;
117 slotClick(_currentItem, pnt, 0); 117 slotClick(_currentItem, pnt, 0);
118 _typeTable->setSelected( _currentItem, true ); 118 _typeTable->setSelected( _currentItem, true );
119 119
120 // make it selected 120 // make it selected
121 _typeEdit->setCursorPosition(0); 121 _typeEdit->setCursorPosition(0);
122 _typeEdit->setSelection(0, _typeEdit->text().length() ); 122 _typeEdit->setSelection(0, _typeEdit->text().length() );
123} 123}
124 124
125// --- slotDel ------------------------------------------------------------- 125// --- slotDel -------------------------------------------------------------
126void ListEdit::slotDel() 126void ListEdit::slotDel()
127{ 127{
128 if( !_currentItem ) return; 128 if( !_currentItem ) return;
129 delete _currentItem; 129 delete _currentItem;
130 _currentItem=NULL; 130 _currentItem=NULL;
131 _typeEdit->setText(""); 131 _typeEdit->setText("");
132 _stack->raiseWidget(_typeEdit); 132 _stack->raiseWidget(_typeEdit);
133} 133}
134 134
135 135
136// --- fixTypes ---------------------------------------------------------------- 136// --- fixTypes ----------------------------------------------------------------
137// Makes sure all entries have a unique name and empty entries are replaced 137// Makes sure all entries have a unique name and empty entries are replaced
138// by a generic string. The first version performs the operation on a particular 138// by a generic string. The first version performs the operation on a particular
139// column, whereas the 2nd does it for all unique columns. 139// column, whereas the 2nd does it for all unique columns.
140class ColMap { 140class ColMap {
141 public: 141 public:
142 ColMap(QString sValue, QListViewItem *pEntry) { 142 ColMap(QString sValue, QListViewItem *pEntry) {
143 _sValue=sValue; 143 _sValue=sValue;
144 _pEntry=pEntry; 144 _pEntry=pEntry;
145 } 145 }
146 QString &getValue() { return(_sValue); } 146 QString &getValue() { return(_sValue); }
147 QListViewItem *getItem() { return(_pEntry); } 147 QListViewItem *getItem() { return(_pEntry); }
148 148
149 protected: 149 protected:
150 QString _sValue; 150 QString _sValue;
151 QListViewItem *_pEntry; 151 QListViewItem *_pEntry;
152}; 152};
153 153
154class ColList : public QList<QString> 154class ColList : public QList<QString>
155{ 155{
156 public: 156 public:
157 ColList() : QList<QString>() { } 157 ColList() : QList<QString>() { }
158 158
159 protected: 159 protected:
160 int compareItems(QCollection::Item, QCollection::Item); 160 int compareItems(QCollection::Item, QCollection::Item);
161}; 161};
162 162
163int ColList::compareItems(QCollection::Item i1, QCollection::Item i2) { 163int ColList::compareItems(QCollection::Item i1, QCollection::Item i2) {
164 return( ((QString *)i1)->compare(*(QString *)i2) ); 164 return( ((QString *)i1)->compare(*(QString *)i2) );
165} 165}
166 166
167void ListEdit::fixTypes(int iColumn) 167void ListEdit::fixTypes(int iColumn)
168{ 168{
169 // get column def 169 // get column def
170 ColumnDef *pDef=this->at(iColumn); 170 ColumnDef *pDef=this->at(iColumn);
171 171
172 // create map of entries 172 // create map of entries
173 if( !_typeTable->childCount() ) return; 173 if( !_typeTable->childCount() ) return;
174 ColMap **colMap=new (ColMap *)[_typeTable->childCount()]; 174 ColMap **colMap=new (ColMap *)[_typeTable->childCount()];
175 QListViewItem *cur=_typeTable->firstChild(); 175 QListViewItem *cur=_typeTable->firstChild();
176 ColList lst; 176 ColList lst;
177 for(int i=0; i<_typeTable->childCount(); i++) { 177 for(int i=0; i<_typeTable->childCount(); i++) {
178 colMap[i]=new ColMap(cur->text(iColumn), cur); 178 colMap[i]=new ColMap(cur->text(iColumn), cur);
179 lst.append( &(colMap[i]->getValue()) ); 179 lst.append( &(colMap[i]->getValue()) );
180 cur=cur->nextSibling(); 180 cur=cur->nextSibling();
181 } 181 }
182 182
183 // fix empty entries 183 // fix empty entries
184 int i=0; 184 int i=0;
185 for(QString *ptr=lst.first(); ptr; ptr=lst.next()) { 185 for(QString *ptr=lst.first(); ptr; ptr=lst.next()) {
186 *ptr=ptr->stripWhiteSpace(); 186 *ptr=ptr->stripWhiteSpace();
187 if( ptr->isEmpty() ) { 187 if( ptr->isEmpty() ) {
188 i++; 188 i++;
189 if( i==1 ) *ptr=pDef->getNewValue(); 189 if( i==1 ) *ptr=pDef->getNewValue();
190 else ptr->sprintf("%s %d", (const char *)pDef->getNewValue(), i); 190 else ptr->sprintf("%s %d", (const char *)pDef->getNewValue(), i);
191 } 191 }
192 } 192 }
193 193
194 // fix dups 194 // fix dups
195 lst.sort(); 195 lst.sort();
196 QString repl; 196 QString repl;
197 for(uint iCur=0; iCur<lst.count()-1; iCur++) { 197 for(uint iCur=0; iCur<lst.count()-1; iCur++) {
198 QString *current=lst.at(iCur); 198 QString *current=lst.at(iCur);
199 for(uint iNext=iCur+1; iNext<lst.count(); iNext++ ) { 199 for(uint iNext=iCur+1; iNext<lst.count(); iNext++ ) {
200 if( *current!=*lst.at(iNext) ) continue; 200 if( *current!=*lst.at(iNext) ) continue;
201 for(int i=2; ; i++) { 201 for(int i=2; ; i++) {
202 repl.sprintf("%s %d", (const char *)*current, i); 202 repl.sprintf("%s %d", (const char *)*current, i);
203 bool bDup=false; 203 bool bDup=false;
204 uint iChk=iNext+1; 204 uint iChk=iNext+1;
205 while( iChk<lst.count() ) { 205 while( iChk<lst.count() ) {
206 QString *chk=lst.at(iChk); 206 QString *chk=lst.at(iChk);
207 if( !chk->startsWith(*current) ) break; 207 if( !chk->startsWith(*current) ) break;
208 if( *chk==repl ) { 208 if( *chk==repl ) {
209 bDup=true; 209 bDup=true;
210 break; 210 break;
211 } 211 }
212 iChk++; 212 iChk++;
213 } 213 }
214 if( !bDup ) { 214 if( !bDup ) {
215 *lst.at(iNext)=repl; 215 *lst.at(iNext)=repl;
216 break; 216 break;
217 } 217 }
218 } 218 }
219 } 219 }
220 } 220 }
221 lst.sort(); 221 lst.sort();
222 222
223 // copy back clean up col map 223 // copy back clean up col map
224 for(int i=0; i<_typeTable->childCount(); i++) { 224 for(int i=0; i<_typeTable->childCount(); i++) {
225 colMap[i]->getItem()->setText(iColumn, colMap[i]->getValue()); 225 colMap[i]->getItem()->setText(iColumn, colMap[i]->getValue());
226 delete colMap[i]; 226 delete colMap[i];
227 } 227 }
228 delete colMap; 228 delete colMap;
229} 229}
230 230
231void ListEdit::fixTypes() 231void ListEdit::fixTypes()
232{ 232{
233 int i; 233 int i;
234 ColumnDef *pDef; 234 ColumnDef *pDef;
235 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) { 235 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) {
236 if( pDef->hasFlag(ColumnDef::typeUnique) ) 236 if( pDef->hasFlag(ColumnDef::typeUnique) )
237 fixTypes(i); 237 fixTypes(i);
238 } 238 }
239 _typeTable->sort(); 239 _typeTable->sort();
240} 240}
241 241
242 242
243// --- storeInList ------------------------------------------------------------ 243// --- storeInList ------------------------------------------------------------
244void ListEdit::storeInList(QStringList &lst) 244void ListEdit::storeInList(QStringList &lst)
245{ 245{
246 // delete old content 246 // delete old content
247 lst.clear(); 247 lst.clear();
248 248
249 // add new one 249 // add new one
250 fixTypes(); 250 fixTypes();
251 QListViewItem *itm=_typeTable->firstChild(); 251 QListViewItem *itm=_typeTable->firstChild();
252 while( itm ) { 252 while( itm ) {
253 int i=0; 253 int i=0;
254 QString sAdd; 254 QString sAdd;
255 ColumnDef *pDef; 255 ColumnDef *pDef;
256 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) { 256 for(pDef=this->first(), i=0; pDef; pDef=this->next(), i++) {
257 if( i>=1 ) sAdd+=";"; 257 if( i>=1 ) sAdd+=";";
258 sAdd += itm->text(i); 258 sAdd += itm->text(i);
259 } 259 }
260 lst.append( sAdd ); 260 lst.append( sAdd );
261 itm=itm->nextSibling(); 261 itm=itm->nextSibling();
262 } 262 }
263} 263}
264 264
265 265
266// --- slotClicked ------------------------------------------------------------ 266// --- slotClicked ------------------------------------------------------------
267void ListEdit::slotClick(QListViewItem *itm, const QPoint &pnt, int col) 267void ListEdit::slotClick(QListViewItem *itm, const QPoint &pnt, int col)
268{ 268{
269 (void)pnt; // get rid of unused warning; 269 (void)pnt; // get rid of unused warning;
270 270
271 // save values 271 // save values
272 _currentItem=itm; 272 _currentItem=itm;
273 _currentColumn=col; 273 _currentColumn=col;
274 if( itm==NULL ) { 274 if( itm==NULL ) {
275 _typeEdit->setText(""); 275 _typeEdit->setText("");
276 _stack->raiseWidget(_typeEdit); 276 _stack->raiseWidget(_typeEdit);
277 return; 277 return;
278 } 278 }
279 279
280 // display value 280 // display value
281 if( _currentColumn<0 ) _currentColumn=0; 281 if( _currentColumn<0 ) _currentColumn=0;
282 ColumnDef *pDef=this->at(_currentColumn); 282 ColumnDef *pDef=this->at(_currentColumn);
283 if( pDef->isType(ColumnDef::typeString) ) { 283 if( pDef->isType(ColumnDef::typeString) ) {
284 _typeEdit->setText( _currentItem->text(_currentColumn) ); 284 _typeEdit->setText( _currentItem->text(_currentColumn) );
285 _stack->raiseWidget(_typeEdit); 285 _stack->raiseWidget(_typeEdit);
286 } else if( pDef->isType(ColumnDef::typeList) ){ 286 } else if( pDef->isType(ColumnDef::typeList) ){
287 _box->clear(); 287 _box->clear();
288 _box->insertStringList( pDef->getValueList() ); 288 _box->insertStringList( pDef->getValueList() );
289 QStringList::Iterator itr; 289 QStringList::Iterator itr;
290 int i=0; 290 int i=0;
291 for(itr=pDef->getValueList().begin(); itr!=pDef->getValueList().end(); itr++) { 291 for(itr=pDef->getValueList().begin(); itr!=pDef->getValueList().end(); itr++) {
292 if( (*itr)==_currentItem->text(_currentColumn) ) { 292 if( (*itr)==_currentItem->text(_currentColumn) ) {
293 _box->setCurrentItem(i); 293 _box->setCurrentItem(i);
294 i=-1; 294 i=-1;
295 break; 295 break;
296 } 296 }
297 i++; 297 i++;
298 } 298 }
299 if( i>=0 ) { 299 if( i>=0 ) {
300 _box->insertItem( _currentItem->text(_currentColumn) ); 300 _box->insertItem( _currentItem->text(_currentColumn) );
301 _box->setCurrentItem(i); 301 _box->setCurrentItem(i);
302 } 302 }
303 _stack->raiseWidget(_box); 303 _stack->raiseWidget(_box);
304 } else { 304 } else {
305 qDebug( "Unsupported column type for column %s", (const char *)pDef->getName() ); 305 qDebug( "Unsupported column type for column %s", (const char *)pDef->getName() );
306 _typeEdit->setText(""); 306 _typeEdit->setText("");
307 _stack->raiseWidget(_typeEdit); 307 _stack->raiseWidget(_typeEdit);
308 } 308 }
309} 309}
310 310
311 311
312// --- addColumnDef ----------------------------------------------------------- 312// --- addColumnDef -----------------------------------------------------------
313void ListEdit::addColumnDef(ColumnDef *pDef) 313void ListEdit::addColumnDef(ColumnDef *pDef)
314{ 314{
315 _typeTable->addColumn( pDef->getName() ); 315 _typeTable->addColumn( pDef->getName() );
316 _vColumns.append(pDef); 316 _vColumns.append(pDef);
317} 317}
318 318
319// --- addData ---------------------------------------------------------------- 319// --- addData ----------------------------------------------------------------
320void ListEdit::addData(QStringList &lst) 320void ListEdit::addData(QStringList &lst)
321{ 321{
322 // run through list 322 // run through list
323 QStringList::Iterator itr; 323 QStringList::Iterator itr;
324 for(itr=lst.begin(); itr!=lst.end(); itr++) { 324 for(itr=lst.begin(); itr!=lst.end(); itr++) {
325 QStringList split=QStringList::split(";", *itr, true); 325 QStringList split=QStringList::split(";", *itr, true);
326 QStringList::Iterator entry; 326 QStringList::Iterator entry;
327 QString args[8]; 327 QString args[8];
328 int i=0; 328 int i=0;
329 for(entry=split.begin(); entry!=split.end() && i<8; entry++, i++) { 329 for(entry=split.begin(); entry!=split.end() && i<8; entry++, i++) {
330 args[i]= (*entry); 330 args[i]= (*entry);
331 } 331 }
332 while(i<8) { 332 while(i<8) {
333 args[i++]=""; 333 args[i++]="";
334 } 334 }
335 new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); 335 new QListViewItem(_typeTable, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
336 } 336 }
337} 337}
338 338
339// --- slotActivated ---------------------------------------------------------- 339// --- slotActivated ----------------------------------------------------------
340void ListEdit::slotActivated(const QString &str) 340void ListEdit::slotActivated(const QString &str)
341{ 341{
342 if( _currentItem==NULL || _currentColumn<0 ) return; 342 if( _currentItem==NULL || _currentColumn<0 ) return;
343 _currentItem->setText(_currentColumn, str); 343 _currentItem->setText(_currentColumn, str);
344} 344}
diff --git a/noncore/apps/checkbook/mainwindow.cpp b/noncore/apps/checkbook/mainwindow.cpp
index d0fac3b..254ce6a 100644
--- a/noncore/apps/checkbook/mainwindow.cpp
+++ b/noncore/apps/checkbook/mainwindow.cpp
@@ -1,358 +1,358 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "mainwindow.h" 29#include "mainwindow.h"
30#include "cbinfo.h" 30#include "cbinfo.h"
31#include "configuration.h" 31#include "configuration.h"
32#include "password.h" 32#include "password.h"
33#include "checkbook.h" 33#include "checkbook.h"
34 34
35#include <qpe/config.h> 35#include <qpe/config.h>
36#include <qpe/qpeapplication.h> 36#include <qpe/qpeapplication.h>
37#include <qpe/qpemessagebox.h> 37#include <qpe/qpemessagebox.h>
38#include <qpe/qpetoolbar.h> 38#include <qpe/qpetoolbar.h>
39#include <qpe/resource.h> 39#include <qpe/resource.h>
40 40
41#include <qmenubar.h> 41#include <qmenubar.h>
42#include <qaction.h> 42#include <qaction.h>
43#include <qdir.h> 43#include <qdir.h>
44#include <qwhatsthis.h> 44#include <qwhatsthis.h>
45 45
46 46
47MainWindow::MainWindow( QWidget* parent, const char* name, WFlags /*fl*/ ) 47MainWindow::MainWindow( QWidget* parent, const char* name, WFlags /*fl*/ )
48 : QMainWindow( parent, name, WStyle_ContextHelp ) 48 : QMainWindow( parent, name, WStyle_ContextHelp )
49{ 49{
50 setCaption( tr( "Checkbook" ) ); 50 setCaption( tr( "Checkbook" ) );
51 51
52 cbDir = Global::applicationFileName( "checkbook", "" ); 52 cbDir = Global::applicationFileName( "checkbook", "" );
53 lockIcon = Resource::loadPixmap( "locked" ); 53 lockIcon = Resource::loadPixmap( "locked" );
54 54
55 // Load configuration options 55 // Load configuration options
56 Config config( "checkbook" ); 56 Config config( "checkbook" );
57 _cfg.readConfig( config ); 57 _cfg.readConfig( config );
58 58
59 59
60 // Build menu and tool bars 60 // Build menu and tool bars
61 setToolBarsMovable( FALSE ); 61 setToolBarsMovable( FALSE );
62 62
63 QToolBar *bar = new QToolBar( this ); 63 QToolBar *bar = new QToolBar( this );
64 bar->setHorizontalStretchable( TRUE ); 64 bar->setHorizontalStretchable( TRUE );
65 QMenuBar *mb = new QMenuBar( bar ); 65 QMenuBar *mb = new QMenuBar( bar );
66 mb->setMargin( 0 ); 66 mb->setMargin( 0 );
67 QPopupMenu *popup = new QPopupMenu( this ); 67 QPopupMenu *popup = new QPopupMenu( this );
68 68
69 bar = new QToolBar( this ); 69 bar = new QToolBar( this );
70 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); 70 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 );
71 a->setWhatsThis( tr( "Click here to create a new checkbook.\n\nYou also can select New from the Checkbook menu." ) ); 71 a->setWhatsThis( tr( "Click here to create a new checkbook.\n\nYou also can select New from the Checkbook menu." ) );
72 connect( a, SIGNAL( activated() ), this, SLOT( slotNew() ) ); 72 connect( a, SIGNAL( activated() ), this, SLOT( slotNew() ) );
73 a->addTo( popup ); 73 a->addTo( popup );
74 a->addTo( bar ); 74 a->addTo( bar );
75 75
76 actionOpen = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ), QString::null, 76 actionOpen = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ), QString::null,
77 0, this, 0 ); 77 0, this, 0 );
78 actionOpen->setWhatsThis( tr( "Select a checkbook and then click here to edit it.\n\nYou also can select Edit from the Checkbook menu, or click and hold on a checkbook name." ) ); 78 actionOpen->setWhatsThis( tr( "Select a checkbook and then click here to edit it.\n\nYou also can select Edit from the Checkbook menu, or click and hold on a checkbook name." ) );
79 connect( actionOpen, SIGNAL( activated() ), this, SLOT( slotEdit() ) ); 79 connect( actionOpen, SIGNAL( activated() ), this, SLOT( slotEdit() ) );
80 actionOpen->addTo( popup ); 80 actionOpen->addTo( popup );
81 actionOpen->addTo( bar ); 81 actionOpen->addTo( bar );
82 82
83 actionDelete = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 83 actionDelete = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null,
84 0, this, 0 ); 84 0, this, 0 );
85 actionDelete->setWhatsThis( tr( "Select a checkbook and then click here delete it.\n\nYou also can select Delete from the Checkbook menu." ) ); 85 actionDelete->setWhatsThis( tr( "Select a checkbook and then click here delete it.\n\nYou also can select Delete from the Checkbook menu." ) );
86 connect( actionDelete, SIGNAL( activated() ), this, SLOT( slotDelete() ) ); 86 connect( actionDelete, SIGNAL( activated() ), this, SLOT( slotDelete() ) );
87 actionDelete->addTo( popup ); 87 actionDelete->addTo( popup );
88 actionDelete->addTo( bar ); 88 actionDelete->addTo( bar );
89 89
90 popup->insertSeparator(); 90 popup->insertSeparator();
91 91
92 a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); 92 a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 );
93 a->setWhatsThis( tr( "Click here to configure this app." ) ); 93 a->setWhatsThis( tr( "Click here to configure this app." ) );
94 connect( a, SIGNAL( activated() ), this, SLOT( slotConfigure() ) ); 94 connect( a, SIGNAL( activated() ), this, SLOT( slotConfigure() ) );
95 a->addTo( popup ); 95 a->addTo( popup );
96 a->addTo( bar ); 96 a->addTo( bar );
97 97
98 mb->insertItem( tr( "Checkbook" ), popup ); 98 mb->insertItem( tr( "Checkbook" ), popup );
99 99
100 // Load Checkbook selection list 100 // Load Checkbook selection list
101 checkbooks = new CBInfoList(); 101 checkbooks = new CBInfoList();
102 102
103 QDir checkdir( cbDir ); 103 QDir checkdir( cbDir );
104 if (checkdir.exists() == true) 104 if (checkdir.exists() == true)
105 { 105 {
106 QStringList cblist = checkdir.entryList( "*.qcb", QDir::Files|QDir::Readable|QDir::Writable, 106 QStringList cblist = checkdir.entryList( "*.qcb", QDir::Files|QDir::Readable|QDir::Writable,
107 QDir::Time ); 107 QDir::Time );
108 CBInfo *cb = 0x0; 108 CBInfo *cb = 0x0;
109 QString filename; 109 QString filename;
110 110
111 for ( QStringList::Iterator it = cblist.begin(); it != cblist.end(); it++ ) 111 for ( QStringList::Iterator it = cblist.begin(); it != cblist.end(); it++ )
112 { 112 {
113 filename = cbDir; 113 filename = cbDir;
114 filename.append( (*it) ); 114 filename.append( (*it) );
115 115
116 cb = new CBInfo( (*it).remove( (*it).find('.'), (*it).length() ), filename ); 116 cb = new CBInfo( (*it).remove( (*it).find('.'), (*it).length() ), filename );
117 checkbooks->inSort( cb ); 117 checkbooks->inSort( cb );
118 } 118 }
119 } 119 }
120 120
121 // Build Checkbook selection list control 121 // Build Checkbook selection list control
122 cbList = 0x0; 122 cbList = 0x0;
123 buildList(); 123 buildList();
124 124
125 // open last book? 125 // open last book?
126 if( _cfg.isOpenLastBook() ) { 126 if( _cfg.isOpenLastBook() ) {
127 this->show(); 127 this->show();
128 this->showMaximized(); 128 this->showMaximized();
129 QListViewItem *itm=cbList->firstChild(); 129 QListViewItem *itm=cbList->firstChild();
130 while( itm ) { 130 while( itm ) {
131 if( itm->text(posName)==_cfg.getLastBook() ) { 131 if( itm->text(posName)==_cfg.getLastBook() ) {
132 openBook( itm ); 132 openBook( itm );
133 break; 133 break;
134 } 134 }
135 itm=itm->nextSibling(); 135 itm=itm->nextSibling();
136 } 136 }
137 } 137 }
138} 138}
139 139
140 140
141// --- ~MainWindow ------------------------------------------------------------ 141// --- ~MainWindow ------------------------------------------------------------
142MainWindow::~MainWindow() 142MainWindow::~MainWindow()
143{ 143{
144 writeConfig(); 144 writeConfig();
145} 145}
146 146
147 147
148// --- buildList -------------------------------------------------------------- 148// --- buildList --------------------------------------------------------------
149void MainWindow::buildList() 149void MainWindow::buildList()
150{ 150{
151 if ( cbList ) 151 if ( cbList )
152 delete cbList; 152 delete cbList;
153 153
154 cbList = new QListView( this ); 154 cbList = new QListView( this );
155 QWhatsThis::add( cbList, tr( "This is a listing of all checkbooks currently available." ) ); 155 QWhatsThis::add( cbList, tr( "This is a listing of all checkbooks currently available." ) );
156 156
157 if ( _cfg.getShowLocks() ) 157 if ( _cfg.getShowLocks() )
158 { 158 {
159 cbList->addColumn( Resource::loadIconSet( "locked" ), "", 24 ); 159 cbList->addColumn( Resource::loadIconSet( "locked" ), "", 24 );
160 posName = 1; 160 posName = 1;
161 } 161 }
162 else 162 else
163 { 163 {
164 posName = 0; 164 posName = 0;
165 } 165 }
166 cbList->addColumn( tr( "Checkbook Name" ) ); 166 cbList->addColumn( tr( "Checkbook Name" ) );
167 if ( _cfg.getShowBalances() ) 167 if ( _cfg.getShowBalances() )
168 { 168 {
169 int colnum = cbList->addColumn( tr( "Balance" ) ); 169 int colnum = cbList->addColumn( tr( "Balance" ) );
170 cbList->setColumnAlignment( colnum, Qt::AlignRight ); 170 cbList->setColumnAlignment( colnum, Qt::AlignRight );
171 } 171 }
172 cbList->setAllColumnsShowFocus( TRUE ); 172 cbList->setAllColumnsShowFocus( TRUE );
173 cbList->setSorting( posName ); 173 cbList->setSorting( posName );
174 QPEApplication::setStylusOperation( cbList->viewport(), QPEApplication::RightOnHold ); 174 QPEApplication::setStylusOperation( cbList->viewport(), QPEApplication::RightOnHold );
175 connect( cbList, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), 175 connect( cbList, SIGNAL( rightButtonPressed(QListViewItem*,const QPoint&,int) ),
176 this, SLOT( slotEdit() ) ); 176 this, SLOT( slotEdit() ) );
177 setCentralWidget( cbList ); 177 setCentralWidget( cbList );
178 178
179 for ( CBInfo *cb = checkbooks->first(); cb; cb = checkbooks->next() ) 179 for ( CBInfo *cb = checkbooks->first(); cb; cb = checkbooks->next() )
180 { 180 {
181 addCheckbook( cb ); 181 addCheckbook( cb );
182 } 182 }
183} 183}
184 184
185void MainWindow::addCheckbook( CBInfo *cb ) 185void MainWindow::addCheckbook( CBInfo *cb )
186{ 186{
187 QListViewItem *lvi = new QListViewItem( cbList ); 187 QListViewItem *lvi = new QListViewItem( cbList );
188 if ( _cfg.getShowLocks() && !cb->password().isNull() ) 188 if ( _cfg.getShowLocks() && !cb->password().isNull() )
189 { 189 {
190 lvi->setPixmap( 0, lockIcon ); 190 lvi->setPixmap( 0, lockIcon );
191 } 191 }
192 lvi->setText( posName, cb->name() ); 192 lvi->setText( posName, cb->name() );
193 if ( _cfg.getShowBalances() ) 193 if ( _cfg.getShowBalances() )
194 { 194 {
195 QString balance; 195 QString balance;
196 balance.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() ); 196 balance.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() );
197 lvi->setText( posName + 1, balance ); 197 lvi->setText( posName + 1, balance );
198 } 198 }
199} 199}
200 200
201void MainWindow::buildFilename( const QString &name ) 201void MainWindow::buildFilename( const QString &name )
202{ 202{
203 tempFilename = cbDir; 203 tempFilename = cbDir;
204 tempFilename.append( name ); 204 tempFilename.append( name );
205 tempFilename.append( ".qcb" ); 205 tempFilename.append( ".qcb" );
206} 206}
207 207
208void MainWindow::slotNew() 208void MainWindow::slotNew()
209{ 209{
210 CBInfo *cb = new CBInfo(); 210 CBInfo *cb = new CBInfo();
211 211
212 Checkbook *currcb = new Checkbook( this, cb, &_cfg ); 212 Checkbook *currcb = new Checkbook( this, cb, &_cfg );
213 if ( QPEApplication::execDialog( currcb ) == QDialog::Accepted ) 213 if ( QPEApplication::execDialog( currcb ) == QDialog::Accepted )
214 { 214 {
215 // Save new checkbook 215 // Save new checkbook
216 buildFilename( cb->name() ); 216 buildFilename( cb->name() );
217 _cfg.setLastBook( cb->name() ); 217 _cfg.setLastBook( cb->name() );
218 cb->setFilename( tempFilename ); 218 cb->setFilename( tempFilename );
219 cb->write(); 219 cb->write();
220 220
221 // Add to listbox 221 // Add to listbox
222 checkbooks->inSort( cb ); 222 checkbooks->inSort( cb );
223 addCheckbook( cb ); 223 addCheckbook( cb );
224 } 224 }
225 delete currcb; 225 delete currcb;
226} 226}
227 227
228// --- slotEdit --------------------------------------------------------------- 228// --- slotEdit ---------------------------------------------------------------
229void MainWindow::slotEdit() 229void MainWindow::slotEdit()
230{ 230{
231 // get name and open it 231 // get name and open it
232 QListViewItem *curritem = cbList->currentItem(); 232 QListViewItem *curritem = cbList->currentItem();
233 if ( !curritem ) 233 if ( !curritem )
234 return; 234 return;
235 openBook( curritem ); 235 openBook( curritem );
236} 236}
237 237
238 238
239// --- openBook --------------------------------------------------------------- 239// --- openBook ---------------------------------------------------------------
240void MainWindow::openBook(QListViewItem *curritem) 240void MainWindow::openBook(QListViewItem *curritem)
241{ 241{
242 // find book in List 242 // find book in List
243 QString currname=curritem->text(posName); 243 QString currname=curritem->text(posName);
244 CBInfo *cb = checkbooks->first(); 244 CBInfo *cb = checkbooks->first();
245 while ( cb ) { 245 while ( cb ) {
246 if ( cb->name() == currname ) 246 if ( cb->name() == currname )
247 break; 247 break;
248 cb = checkbooks->next(); 248 cb = checkbooks->next();
249 } 249 }
250 if ( !cb ) return; 250 if ( !cb ) return;
251 251
252 // 252 //
253 buildFilename( currname ); 253 buildFilename( currname );
254 float currbalance = cb->balance(); 254 float currbalance = cb->balance();
255 bool currlock = !cb->password().isNull(); 255 bool currlock = !cb->password().isNull();
256 256
257 if ( currlock ) 257 if ( currlock )
258 { 258 {
259 Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) ); 259 Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) );
260 if ( pw->exec() != QDialog::Accepted || pw->password != cb->password() ) 260 if ( pw->exec() != QDialog::Accepted || pw->password != cb->password() )
261 { 261 {
262 delete pw; 262 delete pw;
263 return; 263 return;
264 } 264 }
265 delete pw; 265 delete pw;
266 } 266 }
267 267
268 _cfg.setLastBook( currname ); 268 _cfg.setLastBook( currname );
269 Checkbook *currcb = new Checkbook( this, cb, &_cfg ); 269 Checkbook *currcb = new Checkbook( this, cb, &_cfg );
270 if ( QPEApplication::execDialog( currcb ) == QDialog::Accepted ) 270 if ( QPEApplication::execDialog( currcb ) == QDialog::Accepted )
271 { 271 {
272 QString newname = cb->name(); 272 QString newname = cb->name();
273 if ( currname != newname ) 273 if ( currname != newname )
274 { 274 {
275 // Update name if changed 275 // Update name if changed
276 if( curritem ) { 276 if( curritem ) {
277 curritem->setText( posName, newname ); 277 curritem->setText( posName, newname );
278 cbList->sort(); 278 cbList->sort();
279 } 279 }
280 _cfg.setLastBook( newname ); 280 _cfg.setLastBook( newname );
281 281
282 // Remove old file 282 // Remove old file
283 QFile f( tempFilename ); 283 QFile f( tempFilename );
284 if ( f.exists() ) 284 if ( f.exists() )
285 f.remove(); 285 f.remove();
286 286
287 // Get new filename 287 // Get new filename
288 buildFilename( newname ); 288 buildFilename( newname );
289 cb->setFilename( tempFilename ); 289 cb->setFilename( tempFilename );
290 } 290 }
291 291
292 cb->write(); 292 cb->write();
293 293
294 // Update lock if changed 294 // Update lock if changed
295 if ( _cfg.getShowLocks() && !cb->password().isNull() != currlock ) 295 if ( _cfg.getShowLocks() && !cb->password().isNull() != currlock )
296 { 296 {
297 if ( !cb->password().isNull() ) 297 if ( !cb->password().isNull() )
298 curritem->setPixmap( 0, lockIcon ); 298 curritem->setPixmap( 0, lockIcon );
299 else 299 else
300 curritem->setPixmap( 0, nullIcon ); 300 curritem->setPixmap( 0, nullIcon );
301 } 301 }
302 302
303 // Update balance if changed 303 // Update balance if changed
304 if ( _cfg.getShowBalances() && cb->balance() != currbalance ) 304 if ( _cfg.getShowBalances() && cb->balance() != currbalance )
305 { 305 {
306 QString tempstr; 306 QString tempstr;
307 tempstr.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() ); 307 tempstr.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() );
308 curritem->setText( posName + 1, tempstr ); 308 curritem->setText( posName + 1, tempstr );
309 } 309 }
310 310
311 // write config, if needed 311 // write config, if needed
312 if( _cfg.isDirty() ) { 312 if( _cfg.isDirty() ) {
313 Config config("checkbook"); 313 Config config("checkbook");
314 _cfg.writeConfig( config ); 314 _cfg.writeConfig( config );
315 } 315 }
316 } 316 }
317 delete currcb; 317 delete currcb;
318} 318}
319 319
320// --- slotDelete ------------------------------------------------------------- 320// --- slotDelete -------------------------------------------------------------
321void MainWindow::slotDelete() 321void MainWindow::slotDelete()
322{ 322{
323 QString currname = cbList->currentItem()->text( posName ); 323 QString currname = cbList->currentItem()->text( posName );
324 324
325 if ( QPEMessageBox::confirmDelete ( this, tr( "Delete checkbook" ), currname ) ) 325 if ( QPEMessageBox::confirmDelete ( this, tr( "Delete checkbook" ), currname ) )
326 { 326 {
327 buildFilename( currname ); 327 buildFilename( currname );
328 QFile f( tempFilename ); 328 QFile f( tempFilename );
329 if ( f.exists() ) 329 if ( f.exists() )
330 { 330 {
331 f.remove(); 331 f.remove();
332 } 332 }
333 333
334 delete cbList->currentItem(); 334 delete cbList->currentItem();
335 } 335 }
336} 336}
337 337
338// --- slotConfigure ---------------------------------------------------------- 338// --- slotConfigure ----------------------------------------------------------
339void MainWindow::slotConfigure() 339void MainWindow::slotConfigure()
340{ 340{
341 Configuration *cfgdlg = new Configuration( this, _cfg ); 341 Configuration *cfgdlg = new Configuration( this, _cfg );
342 if ( QPEApplication::execDialog( cfgdlg ) == QDialog::Accepted ) 342 if ( QPEApplication::execDialog( cfgdlg ) == QDialog::Accepted )
343 { 343 {
344 // read data from config dialog & save it 344 // read data from config dialog & save it
345 cfgdlg->saveConfig( _cfg ); 345 cfgdlg->saveConfig( _cfg );
346 writeConfig(); 346 writeConfig();
347 buildList(); 347 buildList();
348 } 348 }
349 delete cfgdlg; 349 delete cfgdlg;
350} 350}
351 351
352 352
353// --- writeConfig -------------------------------------------------------------- 353// --- writeConfig --------------------------------------------------------------
354void MainWindow::writeConfig() 354void MainWindow::writeConfig()
355{ 355{
356 Config config("checkbook"); 356 Config config("checkbook");
357 _cfg.writeConfig( config ); 357 _cfg.writeConfig( config );
358} 358}
diff --git a/noncore/apps/checkbook/password.cpp b/noncore/apps/checkbook/password.cpp
index f381271..89a6bc6 100644
--- a/noncore/apps/checkbook/password.cpp
+++ b/noncore/apps/checkbook/password.cpp
@@ -1,97 +1,97 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "password.h" 29#include "password.h"
30 30
31#include <qlabel.h> 31#include <qlabel.h>
32#include <qlayout.h> 32#include <qlayout.h>
33#include <qlineedit.h> 33#include <qlineedit.h>
34#include <qpushbutton.h> 34#include <qpushbutton.h>
35 35
36static const char* const showhideimage_data[] = { 36static const char* const showhideimage_data[] = {
37"16 16 2 1", 37"16 16 2 1",
38". c None", 38". c None",
39"# c #000000", 39"# c #000000",
40"................", 40"................",
41"...#...###...##.", 41"...#...###...##.",
42"..#.#..#..#.##..", 42"..#.#..#..#.##..",
43"..###..###.##...", 43"..###..###.##...",
44".#...#.#..##....", 44".#...#.#..##....",
45".#...#.#.##.....", 45".#...#.#.##.....",
46"........##.#..#.", 46"........##.#..#.",
47"..##...##...##..", 47"..##...##...##..",
48".#..#.###...##..", 48".#..#.###...##..",
49".#...##..#.#..#.", 49".#...##..#.#..#.",
50".#..##..........", 50".#..##..........",
51".#.##.#..#.#..#.", 51".#.##.#..#.#..#.",
52"..##...##...##..", 52"..##...##...##..",
53".##....##...##..", 53".##....##...##..",
54".#....#..#.#..#.", 54".#....#..#.#..#.",
55"................"}; 55"................"};
56 56
57Password::Password( QWidget *parent, const char *caption, const char *prompt ) 57Password::Password( QWidget *parent, const char *caption, const char *prompt )
58 : QDialog( parent, 0x0, TRUE, 0x0 ) 58 : QDialog( parent, 0x0, TRUE, 0x0 )
59{ 59{
60 setCaption( caption ); 60 setCaption( caption );
61 61
62 QGridLayout *layout = new QGridLayout( this ); 62 QGridLayout *layout = new QGridLayout( this );
63 layout->setSpacing( 2 ); 63 layout->setSpacing( 2 );
64 layout->setMargin( 4 ); 64 layout->setMargin( 4 );
65 65
66 QLabel *label = new QLabel( prompt, this ); 66 QLabel *label = new QLabel( prompt, this );
67 label->setAlignment( AlignLeft | AlignTop | WordBreak ); 67 label->setAlignment( AlignLeft | AlignTop | WordBreak );
68 layout->addMultiCellWidget( label, 0, 0, 0, 1 ); 68 layout->addMultiCellWidget( label, 0, 0, 0, 1 );
69 69
70 pw = new QLineEdit( this ); 70 pw = new QLineEdit( this );
71 pw->setEchoMode( QLineEdit::Password ); 71 pw->setEchoMode( QLineEdit::Password );
72 layout->addWidget( pw, 1, 0 ); 72 layout->addWidget( pw, 1, 0 );
73 73
74 QPixmap *pic = new QPixmap( ( const char** ) showhideimage_data ); 74 QPixmap *pic = new QPixmap( ( const char** ) showhideimage_data );
75 QPushButton *btn = new QPushButton( ( QIconSet ) *pic, QString::null, this ); 75 QPushButton *btn = new QPushButton( ( QIconSet ) *pic, QString::null, this );
76 btn->setMaximumSize( pic->width() + 10, pic->height() + 10 ); 76 btn->setMaximumSize( pic->width() + 10, pic->height() + 10 );
77 btn->setToggleButton( TRUE ); 77 btn->setToggleButton( TRUE );
78 connect( btn, SIGNAL( toggled( bool ) ), this, SLOT( slotTogglePassword( bool ) ) ); 78 connect( btn, SIGNAL( toggled(bool) ), this, SLOT( slotTogglePassword(bool) ) );
79 layout->addWidget( btn, 1, 1 ); 79 layout->addWidget( btn, 1, 1 );
80 80
81 password == ""; 81 password == "";
82} 82}
83 83
84Password::~Password() 84Password::~Password()
85{ 85{
86} 86}
87 87
88void Password::accept() 88void Password::accept()
89{ 89{
90 password = pw->text(); 90 password = pw->text();
91 QDialog::accept(); 91 QDialog::accept();
92} 92}
93 93
94void Password::slotTogglePassword( bool showPW ) 94void Password::slotTogglePassword( bool showPW )
95{ 95{
96 showPW ? pw->setEchoMode( QLineEdit::Normal ) : pw->setEchoMode( QLineEdit::Password ); 96 showPW ? pw->setEchoMode( QLineEdit::Normal ) : pw->setEchoMode( QLineEdit::Password );
97} 97}
diff --git a/noncore/apps/checkbook/transaction.cpp b/noncore/apps/checkbook/transaction.cpp
index a72a48b..1b08b24 100644
--- a/noncore/apps/checkbook/transaction.cpp
+++ b/noncore/apps/checkbook/transaction.cpp
@@ -1,337 +1,337 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> 4             .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "transaction.h" 29#include "transaction.h"
30#include "traninfo.h" 30#include "traninfo.h"
31#include "cfg.h" 31#include "cfg.h"
32#include "checkbook.h" 32#include "checkbook.h"
33 33
34#include <qpe/datebookmonth.h> 34#include <qpe/datebookmonth.h>
35 35
36#include <qbuttongroup.h> 36#include <qbuttongroup.h>
37#include <qcombobox.h> 37#include <qcombobox.h>
38#include <qlabel.h> 38#include <qlabel.h>
39#include <qlayout.h> 39#include <qlayout.h>
40#include <qlineedit.h> 40#include <qlineedit.h>
41#include <qmultilineedit.h> 41#include <qmultilineedit.h>
42#include <qradiobutton.h> 42#include <qradiobutton.h>
43#include <qwhatsthis.h> 43#include <qwhatsthis.h>
44 44
45Transaction::Transaction( QWidget *parent, bool bNew, const QString &acctname, 45Transaction::Transaction( QWidget *parent, bool bNew, const QString &acctname,
46 TranInfo *info, Cfg *pCfg ) 46 TranInfo *info, Cfg *pCfg )
47 : QDialog( parent, 0, TRUE, WStyle_ContextHelp ) 47 : QDialog( parent, 0, TRUE, WStyle_ContextHelp )
48{ 48{
49 QString tempstr = tr( "Transaction for " ); 49 QString tempstr = tr( "Transaction for " );
50 tempstr.append( acctname ); 50 tempstr.append( acctname );
51 setCaption( tempstr ); 51 setCaption( tempstr );
52 52
53 _bNew=bNew; 53 _bNew=bNew;
54 tran = info; 54 tran = info;
55 _pCfg=pCfg; 55 _pCfg=pCfg;
56 56
57 QVBoxLayout *vb = new QVBoxLayout( this ); 57 QVBoxLayout *vb = new QVBoxLayout( this );
58 58
59 QScrollView *sv = new QScrollView( this ); 59 QScrollView *sv = new QScrollView( this );
60 vb->addWidget( sv, 0, 0 ); 60 vb->addWidget( sv, 0, 0 );
61 sv->setResizePolicy( QScrollView::AutoOneFit ); 61 sv->setResizePolicy( QScrollView::AutoOneFit );
62 sv->setFrameStyle( QFrame::NoFrame ); 62 sv->setFrameStyle( QFrame::NoFrame );
63 63
64 QWidget *container = new QWidget( sv->viewport() ); 64 QWidget *container = new QWidget( sv->viewport() );
65 sv->addChild( container ); 65 sv->addChild( container );
66 66
67 QGridLayout *layout = new QGridLayout( container ); 67 QGridLayout *layout = new QGridLayout( container );
68 layout->setSpacing( 2 ); 68 layout->setSpacing( 2 );
69 layout->setMargin( 4 ); 69 layout->setMargin( 4 );
70 70
71 // Withdrawal/Deposit 71 // Withdrawal/Deposit
72 QButtonGroup *btngrp = new QButtonGroup( container ); 72 QButtonGroup *btngrp = new QButtonGroup( container );
73 btngrp->setColumnLayout(0, Qt::Vertical ); 73 btngrp->setColumnLayout(0, Qt::Vertical );
74 btngrp->layout()->setSpacing( 0 ); 74 btngrp->layout()->setSpacing( 0 );
75 btngrp->layout()->setMargin( 0 ); 75 btngrp->layout()->setMargin( 0 );
76 btngrp->setMaximumWidth( 220 ); 76 btngrp->setMaximumWidth( 220 );
77 QGridLayout *layout2 = new QGridLayout( btngrp->layout() ); 77 QGridLayout *layout2 = new QGridLayout( btngrp->layout() );
78 layout2->setSpacing( 2 ); 78 layout2->setSpacing( 2 );
79 layout2->setMargin( 2 ); 79 layout2->setMargin( 2 );
80 withBtn = new QRadioButton( tr( "Withdrawal" ), btngrp ); 80 withBtn = new QRadioButton( tr( "Withdrawal" ), btngrp );
81 QWhatsThis::add( withBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) ); 81 QWhatsThis::add( withBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) );
82 layout2->addWidget( withBtn, 0, 0 ); 82 layout2->addWidget( withBtn, 0, 0 );
83 connect( withBtn, SIGNAL( clicked() ), this, SLOT( slotWithdrawalClicked() ) ); 83 connect( withBtn, SIGNAL( clicked() ), this, SLOT( slotWithdrawalClicked() ) );
84 depBtn = new QRadioButton( tr( "Deposit" ), btngrp ); 84 depBtn = new QRadioButton( tr( "Deposit" ), btngrp );
85 QWhatsThis::add( depBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) ); 85 QWhatsThis::add( depBtn, tr( "Select whether the transaction is a withdrawal or deposit here." ) );
86 layout2->addWidget( depBtn, 0, 1 ); 86 layout2->addWidget( depBtn, 0, 1 );
87 btngrp->setMaximumSize( 320, withBtn->height() ); 87 btngrp->setMaximumSize( 320, withBtn->height() );
88 connect( depBtn, SIGNAL( clicked() ), this, SLOT( slotDepositClicked() ) ); 88 connect( depBtn, SIGNAL( clicked() ), this, SLOT( slotDepositClicked() ) );
89 layout->addMultiCellWidget( btngrp, 0, 0, 0, 3 ); 89 layout->addMultiCellWidget( btngrp, 0, 0, 0, 3 );
90 90
91 // Date 91 // Date
92 QLabel *label = new QLabel( tr( "Date:" ), container ); 92 QLabel *label = new QLabel( tr( "Date:" ), container );
93 QWhatsThis::add( label, tr( "Select date of transaction here." ) ); 93 QWhatsThis::add( label, tr( "Select date of transaction here." ) );
94 layout->addWidget( label, 1, 0 ); 94 layout->addWidget( label, 1, 0 );
95 dateBtn = new QPushButton( TimeString::shortDate( QDate::currentDate() ), 95 dateBtn = new QPushButton( TimeString::shortDate( QDate::currentDate() ),
96 container ); 96 container );
97 QWhatsThis::add( dateBtn, tr( "Select date of transaction here." ) ); 97 QWhatsThis::add( dateBtn, tr( "Select date of transaction here." ) );
98 QPopupMenu *m1 = new QPopupMenu( container ); 98 QPopupMenu *m1 = new QPopupMenu( container );
99 datePicker = new DateBookMonth( m1, 0, TRUE ); 99 datePicker = new DateBookMonth( m1, 0, TRUE );
100 m1->insertItem( datePicker ); 100 m1->insertItem( datePicker );
101 dateBtn->setPopup( m1 ); 101 dateBtn->setPopup( m1 );
102 connect( datePicker, SIGNAL( dateClicked( int, int, int ) ), 102 connect( datePicker, SIGNAL( dateClicked(int,int,int) ),
103 this, SLOT( slotDateChanged( int, int, int ) ) ); 103 this, SLOT( slotDateChanged(int,int,int) ) );
104 layout->addWidget( dateBtn, 1, 1 ); 104 layout->addWidget( dateBtn, 1, 1 );
105 105
106 // Check number 106 // Check number
107 label = new QLabel( tr( "Number:" ), container ); 107 label = new QLabel( tr( "Number:" ), container );
108 QWhatsThis::add( label, tr( "Enter check number here." ) ); 108 QWhatsThis::add( label, tr( "Enter check number here." ) );
109 layout->addWidget( label, 1, 2 ); 109 layout->addWidget( label, 1, 2 );
110 numEdit = new QLineEdit( container ); 110 numEdit = new QLineEdit( container );
111 QWhatsThis::add( numEdit, tr( "Enter check number here." ) ); 111 QWhatsThis::add( numEdit, tr( "Enter check number here." ) );
112 numEdit->setMaximumWidth( 40 ); 112 numEdit->setMaximumWidth( 40 );
113 layout->addWidget( numEdit, 1, 3 ); 113 layout->addWidget( numEdit, 1, 3 );
114 114
115 // Description 115 // Description
116 label = new QLabel( tr( "Description:" ), container ); 116 label = new QLabel( tr( "Description:" ), container );
117 QWhatsThis::add( label, tr( "Enter description of transaction here." ) ); 117 QWhatsThis::add( label, tr( "Enter description of transaction here." ) );
118 layout->addWidget( label, 2, 0 ); 118 layout->addWidget( label, 2, 0 );
119 _cbDesc=new QComboBox( true, container ); 119 _cbDesc=new QComboBox( true, container );
120 _cbDesc->insertStringList( _pCfg->getPayees() ); 120 _cbDesc->insertStringList( _pCfg->getPayees() );
121 QWhatsThis::add( _cbDesc, tr( "Enter description of transaction here." ) ); 121 QWhatsThis::add( _cbDesc, tr( "Enter description of transaction here." ) );
122 layout->addMultiCellWidget( _cbDesc, 2, 2, 1, 3 ); 122 layout->addMultiCellWidget( _cbDesc, 2, 2, 1, 3 );
123 connect( _cbDesc, SIGNAL( activated(const QString &) ), this, SLOT( slotActivated(const QString &) ) ); 123 connect( _cbDesc, SIGNAL( activated(const QString&) ), this, SLOT( slotActivated(const QString&) ) );
124 124
125 125
126 // Category 126 // Category
127 label = new QLabel( tr( "Category:" ), container ); 127 label = new QLabel( tr( "Category:" ), container );
128 QWhatsThis::add( label, tr( "Select transaction category here." ) ); 128 QWhatsThis::add( label, tr( "Select transaction category here." ) );
129 layout->addWidget( label, 3, 0 ); 129 layout->addWidget( label, 3, 0 );
130 catList = new QComboBox( container ); 130 catList = new QComboBox( container );
131 QWhatsThis::add( catList, tr( "Select transaction category here." ) ); 131 QWhatsThis::add( catList, tr( "Select transaction category here." ) );
132 layout->addMultiCellWidget( catList, 3, 3, 1, 3 ); 132 layout->addMultiCellWidget( catList, 3, 3, 1, 3 );
133 133
134 // Type 134 // Type
135 label = new QLabel( tr( "Type:" ), container ); 135 label = new QLabel( tr( "Type:" ), container );
136 QWhatsThis::add( label, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) ); 136 QWhatsThis::add( label, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) );
137 layout->addWidget( label, 4, 0 ); 137 layout->addWidget( label, 4, 0 );
138 typeList = new QComboBox( container ); 138 typeList = new QComboBox( container );
139 QWhatsThis::add( typeList, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) ); 139 QWhatsThis::add( typeList, tr( "Select transaction type here.\n\nThe options available vary based on whether the transaction is a deposit or withdrawal." ) );
140 layout->addMultiCellWidget( typeList, 4, 4, 1, 3 ); 140 layout->addMultiCellWidget( typeList, 4, 4, 1, 3 );
141 141
142 142
143 // Amount 143 // Amount
144 label = new QLabel( tr( "Amount:" ), container ); 144 label = new QLabel( tr( "Amount:" ), container );
145 QWhatsThis::add( label, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) ); 145 QWhatsThis::add( label, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) );
146 layout->addWidget( label, 5, 0 ); 146 layout->addWidget( label, 5, 0 );
147 amtEdit = new QLineEdit( container ); 147 amtEdit = new QLineEdit( container );
148 QWhatsThis::add( amtEdit, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) ); 148 QWhatsThis::add( amtEdit, tr( "Enter the amount of transaction here.\n\nThe value entered should always be positive." ) );
149 layout->addMultiCellWidget( amtEdit, 5, 5, 1, 3 ); 149 layout->addMultiCellWidget( amtEdit, 5, 5, 1, 3 );
150 150
151 // Fee 151 // Fee
152 label = new QLabel( tr( "Fee:" ), container ); 152 label = new QLabel( tr( "Fee:" ), container );
153 QWhatsThis::add( label, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) ); 153 QWhatsThis::add( label, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) );
154 layout->addWidget( label, 6, 0 ); 154 layout->addWidget( label, 6, 0 );
155 feeEdit = new QLineEdit( container ); 155 feeEdit = new QLineEdit( container );
156 QWhatsThis::add( feeEdit, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) ); 156 QWhatsThis::add( feeEdit, tr( "Enter any fee amount assoiciated with this transaction.\n\nThe value entered should always be positive." ) );
157 layout->addMultiCellWidget( feeEdit, 6, 6, 1, 3 ); 157 layout->addMultiCellWidget( feeEdit, 6, 6, 1, 3 );
158 158
159 // Notes 159 // Notes
160 label = new QLabel( tr( "Notes:" ), container ); 160 label = new QLabel( tr( "Notes:" ), container );
161 QWhatsThis::add( label, tr( "Enter any additional information for this transaction here." ) ); 161 QWhatsThis::add( label, tr( "Enter any additional information for this transaction here." ) );
162 layout->addWidget( label, 7, 0 ); 162 layout->addWidget( label, 7, 0 );
163 noteEdit = new QMultiLineEdit( container ); 163 noteEdit = new QMultiLineEdit( container );
164 QWhatsThis::add( noteEdit, tr( "Enter any additional information for this transaction here." ) ); 164 QWhatsThis::add( noteEdit, tr( "Enter any additional information for this transaction here." ) );
165 layout->addMultiCellWidget( noteEdit, 8, 8, 0, 3 ); 165 layout->addMultiCellWidget( noteEdit, 8, 8, 0, 3 );
166 166
167 // init date 167 // init date
168 initFromInfo( info ); 168 initFromInfo( info );
169 169
170 // not new handlers 170 // not new handlers
171 connect( withBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) ); 171 connect( withBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) );
172 connect( depBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) ); 172 connect( depBtn, SIGNAL( toggled(bool) ), this, SLOT( slotNotNew() ) );
173 connect( catList, SIGNAL(activated(const QString &)), this, SLOT( slotNotNew() ) ); 173 connect( catList, SIGNAL(activated(const QString&)), this, SLOT( slotNotNew() ) );
174 connect( typeList, SIGNAL(activated(const QString &)), this, SLOT( slotNotNew() ) ); 174 connect( typeList, SIGNAL(activated(const QString&)), this, SLOT( slotNotNew() ) );
175 connect( amtEdit, SIGNAL(textChanged(const QString &)), this, SLOT( slotNotNew() ) ); 175 connect( amtEdit, SIGNAL(textChanged(const QString&)), this, SLOT( slotNotNew() ) );
176 connect( feeEdit, SIGNAL(textChanged(const QString &)), this, SLOT( slotNotNew() ) ); 176 connect( feeEdit, SIGNAL(textChanged(const QString&)), this, SLOT( slotNotNew() ) );
177 connect( noteEdit, SIGNAL(textChanged()), this, SLOT( slotNotNew() ) ); 177 connect( noteEdit, SIGNAL(textChanged()), this, SLOT( slotNotNew() ) );
178} 178}
179 179
180// --- initFromInfo ----------------------------------------------------------- 180// --- initFromInfo -----------------------------------------------------------
181void Transaction::initFromInfo(TranInfo *info, bool bPopulateOld) 181void Transaction::initFromInfo(TranInfo *info, bool bPopulateOld)
182{ 182{
183 // Populate current values if provided 183 // Populate current values if provided
184 if ( info ) 184 if ( info )
185 { 185 {
186 if ( info->withdrawal() ) 186 if ( info->withdrawal() )
187 { 187 {
188 withBtn->setChecked( TRUE ); 188 withBtn->setChecked( TRUE );
189 slotWithdrawalClicked(); 189 slotWithdrawalClicked();
190 } 190 }
191 else 191 else
192 { 192 {
193 depBtn->setChecked( TRUE ); 193 depBtn->setChecked( TRUE );
194 slotDepositClicked(); 194 slotDepositClicked();
195 } 195 }
196 196
197 if( !bPopulateOld ) { 197 if( !bPopulateOld ) {
198 QDate dt = info->date(); 198 QDate dt = info->date();
199 slotDateChanged( dt.year(), dt.month(), dt.day() ); 199 slotDateChanged( dt.year(), dt.month(), dt.day() );
200 datePicker->setDate( dt ); 200 datePicker->setDate( dt );
201 numEdit->setText( info->number() ); 201 numEdit->setText( info->number() );
202 } 202 }
203 QString temptext = info->category(); 203 QString temptext = info->category();
204 204
205 // set description field 205 // set description field
206 int i; 206 int i;
207 for(i=_cbDesc->count()-1; i>=0; i--) { 207 for(i=_cbDesc->count()-1; i>=0; i--) {
208 if( _cbDesc->text(i)==info->desc() ) { 208 if( _cbDesc->text(i)==info->desc() ) {
209 _cbDesc->setCurrentItem(i); 209 _cbDesc->setCurrentItem(i);
210 break; 210 break;
211 } 211 }
212 } 212 }
213 if( i<=0 ) 213 if( i<=0 )
214 _cbDesc->setEditText( info->desc() ); 214 _cbDesc->setEditText( info->desc() );
215 215
216 i = catList->count(); 216 i = catList->count();
217 while ( i > 0 ) 217 while ( i > 0 )
218 { 218 {
219 i--; 219 i--;
220 catList->setCurrentItem( i ); 220 catList->setCurrentItem( i );
221 if ( catList->currentText() == temptext ) 221 if ( catList->currentText() == temptext )
222 { 222 {
223 break; 223 break;
224 } 224 }
225 } 225 }
226 temptext = info->type(); 226 temptext = info->type();
227 i = typeList->count(); 227 i = typeList->count();
228 while ( i > 0 ) 228 while ( i > 0 )
229 { 229 {
230 i--; 230 i--;
231 typeList->setCurrentItem( i ); 231 typeList->setCurrentItem( i );
232 if ( typeList->currentText() == temptext ) 232 if ( typeList->currentText() == temptext )
233 { 233 {
234 break; 234 break;
235 } 235 }
236 } 236 }
237 amtEdit->setText( QString( "%1" ).arg( info->amount(), 0, 'f', 2 ) ); 237 amtEdit->setText( QString( "%1" ).arg( info->amount(), 0, 'f', 2 ) );
238 feeEdit->setText( QString( "%1" ).arg( info->fee(), 0, 'f', 2 ) ); 238 feeEdit->setText( QString( "%1" ).arg( info->fee(), 0, 'f', 2 ) );
239 noteEdit->setText( info->notes() ); 239 noteEdit->setText( info->notes() );
240 } 240 }
241 else 241 else
242 { 242 {
243 withBtn->setChecked( TRUE ); 243 withBtn->setChecked( TRUE );
244 } 244 }
245} 245}
246 246
247 247
248// --- ~Transaction ----------------------------------------------------------- 248// --- ~Transaction -----------------------------------------------------------
249Transaction::~Transaction() 249Transaction::~Transaction()
250{ 250{
251} 251}
252 252
253// --- accept ----------------------------------------------------------------- 253// --- accept -----------------------------------------------------------------
254void Transaction::accept() 254void Transaction::accept()
255{ 255{
256 tran->setDesc( _cbDesc->currentText() ); 256 tran->setDesc( _cbDesc->currentText() );
257 tran->setDate( datePicker->selectedDate() ); 257 tran->setDate( datePicker->selectedDate() );
258 tran->setWithdrawal( withBtn->isChecked() ); 258 tran->setWithdrawal( withBtn->isChecked() );
259 tran->setType( typeList->currentText() ); 259 tran->setType( typeList->currentText() );
260 tran->setCategory( catList->currentText() ); 260 tran->setCategory( catList->currentText() );
261 bool ok; 261 bool ok;
262 tran->setAmount( amtEdit->text().toFloat( &ok ) ); 262 tran->setAmount( amtEdit->text().toFloat( &ok ) );
263 tran->setFee( feeEdit->text().toFloat( &ok ) ); 263 tran->setFee( feeEdit->text().toFloat( &ok ) );
264 tran->setNumber( numEdit->text() ); 264 tran->setNumber( numEdit->text() );
265 tran->setNotes( noteEdit->text() ); 265 tran->setNotes( noteEdit->text() );
266 266
267 QDialog::accept(); 267 QDialog::accept();
268} 268}
269 269
270void Transaction::slotWithdrawalClicked() 270void Transaction::slotWithdrawalClicked()
271{ 271{
272 catList->clear(); 272 catList->clear();
273 CategoryList *pCatList=_pCfg->getCategoryList(); 273 CategoryList *pCatList=_pCfg->getCategoryList();
274 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) { 274 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) {
275 if( !pCat->isIncome() ) 275 if( !pCat->isIncome() )
276 catList->insertItem( pCat->getName() ); 276 catList->insertItem( pCat->getName() );
277 } 277 }
278 catList->setCurrentItem(0); 278 catList->setCurrentItem(0);
279 279
280 typeList->clear(); 280 typeList->clear();
281 typeList->insertItem( tr( "Debit Charge" ) ); 281 typeList->insertItem( tr( "Debit Charge" ) );
282 typeList->insertItem( tr( "Written Check" ) ); 282 typeList->insertItem( tr( "Written Check" ) );
283 typeList->insertItem( tr( "Transfer" ) ); 283 typeList->insertItem( tr( "Transfer" ) );
284 typeList->insertItem( tr( "Credit Card" ) ); 284 typeList->insertItem( tr( "Credit Card" ) );
285} 285}
286 286
287void Transaction::slotDepositClicked() 287void Transaction::slotDepositClicked()
288{ 288{
289 catList->clear(); 289 catList->clear();
290 CategoryList *pCatList=_pCfg->getCategoryList(); 290 CategoryList *pCatList=_pCfg->getCategoryList();
291 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) { 291 for(Category *pCat=pCatList->first(); pCat; pCat=pCatList->next()) {
292 if( pCat->isIncome() ) 292 if( pCat->isIncome() )
293 catList->insertItem( pCat->getName() ); 293 catList->insertItem( pCat->getName() );
294 } 294 }
295 catList->setCurrentItem( 0 ); 295 catList->setCurrentItem( 0 );
296 296
297 typeList->clear(); 297 typeList->clear();
298 typeList->insertItem( tr( "Written Check" ) ); 298 typeList->insertItem( tr( "Written Check" ) );
299 typeList->insertItem( tr( "Automatic Payment" ) ); 299 typeList->insertItem( tr( "Automatic Payment" ) );
300 typeList->insertItem( tr( "Transfer" ) ); 300 typeList->insertItem( tr( "Transfer" ) );
301 typeList->insertItem( tr( "Cash" ) ); 301 typeList->insertItem( tr( "Cash" ) );
302} 302}
303 303
304// --- slotDateChanged -------------------------------------------------------- 304// --- slotDateChanged --------------------------------------------------------
305void Transaction::slotDateChanged( int y, int m, int d ) 305void Transaction::slotDateChanged( int y, int m, int d )
306{ 306{
307 QDate date; 307 QDate date;
308 date.setYMD( y, m, d ); 308 date.setYMD( y, m, d );
309 dateBtn->setText( TimeString::shortDate( date ) ); 309 dateBtn->setText( TimeString::shortDate( date ) );
310} 310}
311 311
312 312
313 313
314// --- slotActivated ---------------------------------------------------------- 314// --- slotActivated ----------------------------------------------------------
315// Search for the most recent transaction with this description/payee and 315// Search for the most recent transaction with this description/payee and
316// fill amount etc here, as long the new flag is set 316// fill amount etc here, as long the new flag is set
317void Transaction::slotActivated(const QString &arg ) 317void Transaction::slotActivated(const QString &arg )
318{ 318{
319 if( !_bNew ) return; 319 if( !_bNew ) return;
320 TranInfoList *pTl=((Checkbook *)parentWidget())->getTranList(); 320 TranInfoList *pTl=((Checkbook *)parentWidget())->getTranList();
321 if( pTl ) { 321 if( pTl ) {
322 TranInfo *pTi=pTl->findMostRecentByDesc( arg ); 322 TranInfo *pTi=pTl->findMostRecentByDesc( arg );
323 if( pTi ) { 323 if( pTi ) {
324 initFromInfo( pTi, true ); 324 initFromInfo( pTi, true );
325 amtEdit->setFocus(); 325 amtEdit->setFocus();
326 amtEdit->setSelection(0, amtEdit->text().length() ); 326 amtEdit->setSelection(0, amtEdit->text().length() );
327 amtEdit->setCursorPosition(0); 327 amtEdit->setCursorPosition(0);
328 } 328 }
329 } 329 }
330} 330}
331 331
332// slotNotNew ----------------------------------------------------------------- 332// slotNotNew -----------------------------------------------------------------
333void Transaction::slotNotNew() 333void Transaction::slotNotNew()
334{ 334{
335 qDebug("Not new"); 335 qDebug("Not new");
336 _bNew=false; 336 _bNew=false;
337} 337}
diff --git a/noncore/apps/confedit/mainwindow.cpp b/noncore/apps/confedit/mainwindow.cpp
index 5f7ad50..6ef1043 100644
--- a/noncore/apps/confedit/mainwindow.cpp
+++ b/noncore/apps/confedit/mainwindow.cpp
@@ -1,189 +1,189 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10// (c) 2002 Patrick S. Vogt <tille@handhelds.org> 10// (c) 2002 Patrick S. Vogt <tille@handhelds.org>
11 11
12 12
13#include "mainwindow.h" 13#include "mainwindow.h"
14 14
15#include <qlabel.h> 15#include <qlabel.h>
16#include <qlayout.h> 16#include <qlayout.h>
17#include <qlineedit.h> 17#include <qlineedit.h>
18 18
19#include "listviewconfdir.h" 19#include "listviewconfdir.h"
20#include "listviewitemconfigentry.h" 20#include "listviewitemconfigentry.h"
21 21
22 22
23MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : 23MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) :
24 QMainWindow( parent, name, f ), _currentItem(0), _fileItem(0) 24 QMainWindow( parent, name, f ), _currentItem(0), _fileItem(0)
25{ 25{
26 setCaption( tr("Conf File Editor") ); 26 setCaption( tr("Conf File Editor") );
27 27
28 //setBaseSize( qApp->globalStrut() ); 28 //setBaseSize( qApp->globalStrut() );
29 setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) ); 29 setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) );
30 30
31 mainLayout = new QVBoxLayout( this ); 31 mainLayout = new QVBoxLayout( this );
32 mainLayout->setSpacing( 0 ); 32 mainLayout->setSpacing( 0 );
33 mainLayout->setMargin( 0 ); 33 mainLayout->setMargin( 0 );
34 34
35 35
36 qDebug("creating settingList"); 36 qDebug("creating settingList");
37 settingList = new ListViewConfDir( QDir::homeDirPath() + "/Settings", this, "settingslist"); 37 settingList = new ListViewConfDir( QDir::homeDirPath() + "/Settings", this, "settingslist");
38 settingList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) ); 38 settingList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) );
39 mainLayout->addWidget( settingList, 0); 39 mainLayout->addWidget( settingList, 0);
40 40
41 qDebug("creating editor"); 41 qDebug("creating editor");
42 editor = new EditWidget(this); 42 editor = new EditWidget(this);
43 editor->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Maximum));//, sizePolicy().hasHeightForWidth() ) ); 43 editor->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Maximum));//, sizePolicy().hasHeightForWidth() ) );
44 mainLayout->addWidget( editor, 1 ); 44 mainLayout->addWidget( editor, 1 );
45 editor->layoutType( ListViewItemConf::File ); 45 editor->layoutType( ListViewItemConf::File );
46 46
47 makeMenu(); 47 makeMenu();
48 48
49 connect(settingList, SIGNAL( pressed(QListViewItem*) ), 49 connect(settingList, SIGNAL( pressed(QListViewItem*) ),
50 this, SLOT(setCurrent(QListViewItem*))); 50 this, SLOT(setCurrent(QListViewItem*)));
51 connect( settingList, SIGNAL( clicked( QListViewItem* ) ), 51 connect( settingList, SIGNAL( clicked(QListViewItem*) ),
52 this, SLOT( stopTimer( QListViewItem* ) ) ); 52 this, SLOT( stopTimer(QListViewItem*) ) );
53 53
54 connect( editor->LineEditGroup, SIGNAL( textChanged(const QString&) ), 54 connect( editor->LineEditGroup, SIGNAL( textChanged(const QString&) ),
55 SLOT( groupChanged(const QString&) ) ); 55 SLOT( groupChanged(const QString&) ) );
56 connect( editor->LineEditKey, SIGNAL( textChanged(const QString&) ), 56 connect( editor->LineEditKey, SIGNAL( textChanged(const QString&) ),
57 SLOT( keyChanged(const QString&) ) ); 57 SLOT( keyChanged(const QString&) ) );
58 connect( editor->LineEditValue, SIGNAL( textChanged(const QString&) ), 58 connect( editor->LineEditValue, SIGNAL( textChanged(const QString&) ),
59 SLOT( valueChanged(const QString&) ) ); 59 SLOT( valueChanged(const QString&) ) );
60 60
61 setCurrent(0); 61 setCurrent(0);
62 editor->layoutType(EditWidget::File); 62 editor->layoutType(EditWidget::File);
63} 63}
64 64
65void MainWindow::makeMenu() 65void MainWindow::makeMenu()
66{ 66{
67 popupTimer = new QTimer(this); 67 popupTimer = new QTimer(this);
68 popupMenuFile = new QPopupMenu(this); 68 popupMenuFile = new QPopupMenu(this);
69 popupMenuEntry = new QPopupMenu(this); 69 popupMenuEntry = new QPopupMenu(this);
70 70
71 popupActionSave = new QAction( tr("Save"),QString::null, 0, this, 0 ); 71 popupActionSave = new QAction( tr("Save"),QString::null, 0, this, 0 );
72 popupActionSave->addTo( popupMenuFile ); 72 popupActionSave->addTo( popupMenuFile );
73 // popupActionSave->addTo( popupMenuEntry ); 73 // popupActionSave->addTo( popupMenuEntry );
74 connect( popupActionSave, SIGNAL( activated() ), 74 connect( popupActionSave, SIGNAL( activated() ),
75 this , SLOT( saveConfFile() ) ); 75 this , SLOT( saveConfFile() ) );
76 76
77 popupActionRevert = new QAction( tr("Revert"),QString::null, 0, this, 0 ); 77 popupActionRevert = new QAction( tr("Revert"),QString::null, 0, this, 0 );
78 popupActionRevert->addTo( popupMenuFile ); 78 popupActionRevert->addTo( popupMenuFile );
79 popupActionRevert->addTo( popupMenuEntry ); 79 popupActionRevert->addTo( popupMenuEntry );
80 connect( popupActionRevert, SIGNAL( activated() ), 80 connect( popupActionRevert, SIGNAL( activated() ),
81 this , SLOT( revertConfFile() ) ); 81 this , SLOT( revertConfFile() ) );
82 82
83 popupActionDelete = new QAction( tr("Delete"),QString::null, 0, this, 0 ); 83 popupActionDelete = new QAction( tr("Delete"),QString::null, 0, this, 0 );
84 popupActionDelete->addTo( popupMenuFile ); 84 popupActionDelete->addTo( popupMenuFile );
85 popupActionDelete->addTo( popupMenuEntry ); 85 popupActionDelete->addTo( popupMenuEntry );
86 connect( popupActionDelete, SIGNAL( activated() ), 86 connect( popupActionDelete, SIGNAL( activated() ),
87 this , SLOT( removeConfFile() ) ); 87 this , SLOT( removeConfFile() ) );
88 88
89 connect( popupTimer, SIGNAL(timeout()), 89 connect( popupTimer, SIGNAL(timeout()),
90 this, SLOT(showPopup()) ); 90 this, SLOT(showPopup()) );
91} 91}
92 92
93MainWindow::~MainWindow() 93MainWindow::~MainWindow()
94{ 94{
95} 95}
96 96
97 97
98 98
99void MainWindow::setCurrent(QListViewItem *item) 99void MainWindow::setCurrent(QListViewItem *item)
100{ 100{
101 //qDebug("MainWindow::setCurrent"); 101 //qDebug("MainWindow::setCurrent");
102 if (!item) return; 102 if (!item) return;
103 _item = (ListViewItemConf*) item; 103 _item = (ListViewItemConf*) item;
104 if (!_item) return; 104 if (!_item) return;
105 popupTimer->start( 750, true ); 105 popupTimer->start( 750, true );
106 if (_item->getType() == ListViewItemConf::File) 106 if (_item->getType() == ListViewItemConf::File)
107 { 107 {
108 editor->layoutType(EditWidget::File); 108 editor->layoutType(EditWidget::File);
109 _currentItem=0; 109 _currentItem=0;
110 _fileItem = (ListViewItemConfFile*)item; 110 _fileItem = (ListViewItemConfFile*)item;
111 return; 111 return;
112 } 112 }
113 _fileItem = 0; 113 _fileItem = 0;
114 _currentItem = (ListViewItemConfigEntry*)item; 114 _currentItem = (ListViewItemConfigEntry*)item;
115 if (!_currentItem) return; 115 if (!_currentItem) return;
116 QString file = _currentItem->getFile(); 116 QString file = _currentItem->getFile();
117 QString group = _currentItem->getGroup(); 117 QString group = _currentItem->getGroup();
118 QString key = _currentItem->getKey(); 118 QString key = _currentItem->getKey();
119 QString val = _currentItem->getValue(); 119 QString val = _currentItem->getValue();
120 editor->TextFileName->setText(file); 120 editor->TextFileName->setText(file);
121 editor->LineEditGroup->setText(group); 121 editor->LineEditGroup->setText(group);
122 if (!key.isEmpty()) 122 if (!key.isEmpty())
123 { 123 {
124 editor->layoutType(EditWidget::Entry); 124 editor->layoutType(EditWidget::Entry);
125 editor->LineEditKey->setText(key); 125 editor->LineEditKey->setText(key);
126 editor->LineEditValue->setText(val); 126 editor->LineEditValue->setText(val);
127 }else{ 127 }else{
128 editor->layoutType(EditWidget::Group); 128 editor->layoutType(EditWidget::Group);
129 } 129 }
130} 130}
131 131
132 132
133void MainWindow::groupChanged(const QString &g) 133void MainWindow::groupChanged(const QString &g)
134{ 134{
135 if (!_currentItem) return; 135 if (!_currentItem) return;
136 _currentItem->setGroup(g); 136 _currentItem->setGroup(g);
137} 137}
138 138
139void MainWindow::keyChanged(const QString &k) 139void MainWindow::keyChanged(const QString &k)
140{ 140{
141 if (!_currentItem) return; 141 if (!_currentItem) return;
142 _currentItem->keyChanged(k); 142 _currentItem->keyChanged(k);
143} 143}
144 144
145void MainWindow::valueChanged(const QString &v) 145void MainWindow::valueChanged(const QString &v)
146{ 146{
147 if (!_currentItem) return; 147 if (!_currentItem) return;
148 _currentItem->valueChanged(v); 148 _currentItem->valueChanged(v);
149} 149}
150 150
151 151
152void MainWindow::stopTimer( QListViewItem* ) 152void MainWindow::stopTimer( QListViewItem* )
153{ 153{
154 popupTimer->stop(); 154 popupTimer->stop();
155} 155}
156 156
157void MainWindow::saveConfFile() 157void MainWindow::saveConfFile()
158{ 158{
159 if (!_fileItem) return; 159 if (!_fileItem) return;
160 _fileItem->save(); 160 _fileItem->save();
161} 161}
162 162
163void MainWindow::revertConfFile() 163void MainWindow::revertConfFile()
164{ 164{
165 if (!_item) return; 165 if (!_item) return;
166 _item->revert(); 166 _item->revert();
167} 167}
168 168
169void MainWindow::removeConfFile() 169void MainWindow::removeConfFile()
170{ 170{
171 if (!_item) return; 171 if (!_item) return;
172 _item->remove(); 172 _item->remove();
173} 173}
174 174
175void MainWindow::showPopup() 175void MainWindow::showPopup()
176{ 176{
177qDebug("showPopup"); 177qDebug("showPopup");
178 if (!_item) return; 178 if (!_item) return;
179 popupActionRevert->setEnabled(_item->revertable()); 179 popupActionRevert->setEnabled(_item->revertable());
180 popupActionSave->setEnabled(_item->isChanged()); 180 popupActionSave->setEnabled(_item->isChanged());
181 if (_fileItem) 181 if (_fileItem)
182 { 182 {
183 popupActionSave->setEnabled(_fileItem->isChanged()); 183 popupActionSave->setEnabled(_fileItem->isChanged());
184 popupMenuFile->popup( QCursor::pos() ); 184 popupMenuFile->popup( QCursor::pos() );
185 }else if(_currentItem) 185 }else if(_currentItem)
186 { 186 {
187 popupMenuEntry->popup( QCursor::pos() ); 187 popupMenuEntry->popup( QCursor::pos() );
188 } 188 }
189} 189}
diff --git a/noncore/apps/odict/odict.cpp b/noncore/apps/odict/odict.cpp
index d5c6d75..4c99964 100644
--- a/noncore/apps/odict/odict.cpp
+++ b/noncore/apps/odict/odict.cpp
@@ -1,215 +1,215 @@
1/*************************************************************************** 1/***************************************************************************
2 application: : ODict 2 application: : ODict
3 3
4 begin : December 2002 4 begin : December 2002
5 copyright : ( C ) 2002, 2003 by Carsten Niehaus 5 copyright : ( C ) 2002, 2003 by Carsten Niehaus
6 email : cniehaus@handhelds.org 6 email : cniehaus@handhelds.org
7 **************************************************************************/ 7 **************************************************************************/
8 8
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free software; you can redistribute it and/or modify * 11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or * 13 * the Free Software Foundation; either version 2 of the License, or *
14 * ( at your option ) any later version. * 14 * ( at your option ) any later version. *
15 * * 15 * *
16 **************************************************************************/ 16 **************************************************************************/
17#include "odict.h" 17#include "odict.h"
18#include "configdlg.h" 18#include "configdlg.h"
19#include "dingwidget.h" 19#include "dingwidget.h"
20 20
21#include <qmenubar.h> 21#include <qmenubar.h>
22#include <qmessagebox.h> 22#include <qmessagebox.h>
23#include <qvbox.h> 23#include <qvbox.h>
24#include <qlabel.h> 24#include <qlabel.h>
25#include <qpushbutton.h> 25#include <qpushbutton.h>
26#include <qlineedit.h> 26#include <qlineedit.h>
27#include <qaction.h> 27#include <qaction.h>
28#include <qtextbrowser.h> 28#include <qtextbrowser.h>
29#include <qcombobox.h> 29#include <qcombobox.h>
30 30
31#include <qpe/resource.h> 31#include <qpe/resource.h>
32#include <qpe/config.h> 32#include <qpe/config.h>
33 33
34ODict::ODict(QWidget* parent, const char* name, WFlags fl ) : QMainWindow(parent, name, fl ) 34ODict::ODict(QWidget* parent, const char* name, WFlags fl ) : QMainWindow(parent, name, fl )
35{ 35{
36 activated_name = QString::null; 36 activated_name = QString::null;
37 37
38 vbox = new QVBox( this ); 38 vbox = new QVBox( this );
39 setCaption( tr( "Opie-Dictionary" ) ); 39 setCaption( tr( "Opie-Dictionary" ) );
40 setupMenus(); 40 setupMenus();
41 41
42 QHBox *hbox = new QHBox( vbox ); 42 QHBox *hbox = new QHBox( vbox );
43 QLabel* query_label = new QLabel( tr( "Query:" ) , hbox ); 43 QLabel* query_label = new QLabel( tr( "Query:" ) , hbox );
44 query_label->show(); 44 query_label->show();
45 query_le = new QLineEdit( hbox ); 45 query_le = new QLineEdit( hbox );
46 query_co = new QComboBox( hbox ); 46 query_co = new QComboBox( hbox );
47 connect( query_co , SIGNAL( activated(const QString&) ), this, SLOT( slotMethodChanged(const QString&) ) ); 47 connect( query_co , SIGNAL( activated(const QString&) ), this, SLOT( slotMethodChanged(const QString&) ) );
48 ok_button = new QPushButton( tr( "&Ok" ), hbox ); 48 ok_button = new QPushButton( tr( "&Ok" ), hbox );
49 connect( ok_button, SIGNAL( released() ), this, SLOT( slotStartQuery() ) ); 49 connect( ok_button, SIGNAL( released() ), this, SLOT( slotStartQuery() ) );
50 50
51 top_name = new QLabel( vbox ); 51 top_name = new QLabel( vbox );
52 top_name->setAlignment( AlignHCenter ); 52 top_name->setAlignment( AlignHCenter );
53 browser_top = new QTextBrowser( vbox ); 53 browser_top = new QTextBrowser( vbox );
54 bottom_name = new QLabel( vbox ); 54 bottom_name = new QLabel( vbox );
55 bottom_name->setAlignment( AlignHCenter ); 55 bottom_name->setAlignment( AlignHCenter );
56 browser_bottom = new QTextBrowser( vbox ); 56 browser_bottom = new QTextBrowser( vbox );
57 57
58 ding = new DingWidget(); 58 ding = new DingWidget();
59 59
60 loadConfig(); 60 loadConfig();
61 setCentralWidget( vbox ); 61 setCentralWidget( vbox );
62} 62}
63 63
64void ODict::loadConfig() 64void ODict::loadConfig()
65{ 65{
66 /* 66 /*
67 * the name of the last used dictionary 67 * the name of the last used dictionary
68 */ 68 */
69 QString lastname; 69 QString lastname;
70 70
71 Config cfg ( "odict" ); 71 Config cfg ( "odict" );
72 cfg.setGroup( "generalsettings" ); 72 cfg.setGroup( "generalsettings" );
73 casesens = cfg.readEntry( "casesens" ).toInt(); 73 casesens = cfg.readEntry( "casesens" ).toInt();
74 74
75 QString lastDict = cfg.readEntry( "lastdict" ); 75 QString lastDict = cfg.readEntry( "lastdict" );
76 int i = 0, e = 0; 76 int i = 0, e = 0;
77 77
78 QStringList groupListCfg = cfg.groupList().grep( "Method_" ); 78 QStringList groupListCfg = cfg.groupList().grep( "Method_" );
79 query_co->clear(); 79 query_co->clear();
80 for ( QStringList::Iterator it = groupListCfg.begin() ; it != groupListCfg.end() ; ++it ) 80 for ( QStringList::Iterator it = groupListCfg.begin() ; it != groupListCfg.end() ; ++it )
81 { 81 {
82 QString name; 82 QString name;
83 cfg.setGroup( *it ); 83 cfg.setGroup( *it );
84 name = cfg.readEntry( "Name" ); 84 name = cfg.readEntry( "Name" );
85 query_co->insertItem( name ); 85 query_co->insertItem( name );
86 86
87 /* 87 /*
88 * this check is to look up what dictionary has been used the 88 * this check is to look up what dictionary has been used the
89 * last time 89 * last time
90 */ 90 */
91 if ( lastDict == name ) 91 if ( lastDict == name )
92 { 92 {
93 e = i; 93 e = i;
94 lastname = name; 94 lastname = name;
95 } 95 }
96 i++; 96 i++;
97 } 97 }
98 /* 98 /*
99 * now set the two names of the dictionary and the correct QComboBox-Entry 99 * now set the two names of the dictionary and the correct QComboBox-Entry
100 */ 100 */
101 101
102 lookupLanguageNames( lastname ); 102 lookupLanguageNames( lastname );
103 ding->loadDict( lastname ); 103 ding->loadDict( lastname );
104 ding->loadValues(); 104 ding->loadValues();
105 105
106 query_co->setCurrentItem( e ); 106 query_co->setCurrentItem( e );
107 top_name->setText( top_name_content ); 107 top_name->setText( top_name_content );
108 bottom_name->setText( bottom_name_content ); 108 bottom_name->setText( bottom_name_content );
109} 109}
110 110
111void ODict::lookupLanguageNames( QString dictname ) 111void ODict::lookupLanguageNames( QString dictname )
112{ 112{
113 Config cfg ( "odict" ); 113 Config cfg ( "odict" );
114 cfg.setGroup( "Method_"+dictname ); 114 cfg.setGroup( "Method_"+dictname );
115 top_name_content = cfg.readEntry( "Lang1" ); 115 top_name_content = cfg.readEntry( "Lang1" );
116 bottom_name_content = cfg.readEntry( "Lang2" ); 116 bottom_name_content = cfg.readEntry( "Lang2" );
117} 117}
118 118
119void ODict::saveConfig() 119void ODict::saveConfig()
120{ 120{
121 Config cfg ( "odict" ); 121 Config cfg ( "odict" );
122 cfg.setGroup( "generalsettings" ); 122 cfg.setGroup( "generalsettings" );
123 cfg.writeEntry( "casesens" , casesens ); 123 cfg.writeEntry( "casesens" , casesens );
124 cfg.writeEntry( "lastdict" , query_co->currentText() ); 124 cfg.writeEntry( "lastdict" , query_co->currentText() );
125} 125}
126 126
127void ODict::slotStartQuery() 127void ODict::slotStartQuery()
128{ 128{
129 QString querystring = query_le->text(); 129 QString querystring = query_le->text();
130 if ( !querystring.isEmpty() ) 130 if ( !querystring.isEmpty() )
131 { 131 {
132 /* 132 /*
133 * if the user has not yet defined a dictionary 133 * if the user has not yet defined a dictionary
134 */ 134 */
135 if ( !query_co->currentText() ) 135 if ( !query_co->currentText() )
136 { 136 {
137 switch ( QMessageBox::information( this, tr( "OPIE-Dictionary" ), 137 switch ( QMessageBox::information( this, tr( "OPIE-Dictionary" ),
138 tr( "No dictionary defined" ), 138 tr( "No dictionary defined" ),
139 tr( "&Define one" ), 139 tr( "&Define one" ),
140 tr( "&Cancel" ), 140 tr( "&Cancel" ),
141 0, // Define a dict 141 0, // Define a dict
142 1 ) ) // Cancel choosen 142 1 ) ) // Cancel choosen
143 { 143 {
144 case 0: 144 case 0:
145 slotSettings(); 145 slotSettings();
146 break; 146 break;
147 case 1: // stop here 147 case 1: // stop here
148 return; 148 return;
149 } 149 }
150 } 150 }
151 151
152 /* 152 /*
153 * ok, the user has defined a dict 153 * ok, the user has defined a dict
154 */ 154 */
155 ding->setCaseSensitive( casesens ); 155 ding->setCaseSensitive( casesens );
156 156
157 BroswerContent test = ding->setText( querystring ); 157 BroswerContent test = ding->setText( querystring );
158 158
159 browser_top->setText( test.top ); 159 browser_top->setText( test.top );
160 browser_bottom->setText( test.bottom ); 160 browser_bottom->setText( test.bottom );
161 } 161 }
162} 162}
163 163
164void ODict::slotSettings() 164void ODict::slotSettings()
165{ 165{
166 ConfigDlg dlg( this, "Config" , true); 166 ConfigDlg dlg( this, "Config" , true);
167 if ( dlg.exec() == QDialog::Accepted ) 167 if ( dlg.exec() == QDialog::Accepted )
168 saveConfig(); 168 saveConfig();
169} 169}
170 170
171void ODict::slotSetParameter( int count ) 171void ODict::slotSetParameter( int count )
172{ 172{
173 if ( count == 0 ) 173 if ( count == 0 )
174 { 174 {
175 if ( casesens ) 175 if ( casesens )
176 casesens = false; 176 casesens = false;
177 else 177 else
178 casesens = true; 178 casesens = true;
179 } 179 }
180 180
181 saveConfig(); 181 saveConfig();
182} 182}
183 183
184void ODict::slotMethodChanged( const QString& methodnumber ) 184void ODict::slotMethodChanged( const QString& methodnumber )
185{ 185{
186 activated_name = methodnumber; 186 activated_name = methodnumber;
187 187
188 if ( activated_name != ding->loadedDict() ) 188 if ( activated_name != ding->loadedDict() )
189 { 189 {
190 ding->loadDict(activated_name); 190 ding->loadDict(activated_name);
191 191
192 lookupLanguageNames( activated_name ); 192 lookupLanguageNames( activated_name );
193 top_name->setText( top_name_content ); 193 top_name->setText( top_name_content );
194 bottom_name->setText( bottom_name_content ); 194 bottom_name->setText( bottom_name_content );
195 } 195 }
196} 196}
197 197
198void ODict::setupMenus() 198void ODict::setupMenus()
199{ 199{
200 menu = new QMenuBar( this ); 200 menu = new QMenuBar( this );
201 201
202 settings = new QPopupMenu( menu ); 202 settings = new QPopupMenu( menu );
203 setting_a = new QAction(tr( "Configuration" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); 203 setting_a = new QAction(tr( "Configuration" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 );
204 connect( setting_a, SIGNAL( activated() ), this, SLOT( slotSettings() ) ); 204 connect( setting_a, SIGNAL( activated() ), this, SLOT( slotSettings() ) );
205 setting_a->addTo( settings ); 205 setting_a->addTo( settings );
206 setting_b = new QAction(tr( "Searchmethods" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 ); 206 setting_b = new QAction(tr( "Searchmethods" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 );
207 207
208 parameter = new QPopupMenu( menu ); 208 parameter = new QPopupMenu( menu );
209 connect( parameter, SIGNAL( activated( int ) ), this, SLOT( slotSetParameter( int ) ) ); 209 connect( parameter, SIGNAL( activated(int) ), this, SLOT( slotSetParameter(int) ) );
210 parameter->insertItem( tr( "C&ase sensitive" ), 0 ,0 ); 210 parameter->insertItem( tr( "C&ase sensitive" ), 0 ,0 );
211 parameter->insertSeparator(); 211 parameter->insertSeparator();
212 212
213 menu->insertItem( tr( "Settings" ) , settings ); 213 menu->insertItem( tr( "Settings" ) , settings );
214 menu->insertItem( tr( "Parameter" ) , parameter ); 214 menu->insertItem( tr( "Parameter" ) , parameter );
215} 215}
diff --git a/noncore/apps/opie-bartender/bartender.cpp b/noncore/apps/opie-bartender/bartender.cpp
index 3c010e9..b6401ed 100644
--- a/noncore/apps/opie-bartender/bartender.cpp
+++ b/noncore/apps/opie-bartender/bartender.cpp
@@ -1,432 +1,432 @@
1/**************************************************************************** 1/****************************************************************************
2** 2**
3** Created: Sat Jul 20 08:10:53 2002 3** Created: Sat Jul 20 08:10:53 2002
4** by: L.J. Potter <ljp@llornkcor.com> 4** by: L.J. Potter <ljp@llornkcor.com>
5** copyright : (C) 2002 by ljp 5** copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12 12
13#include "bartender.h" 13#include "bartender.h"
14#include "showdrinks.h" 14#include "showdrinks.h"
15#include "inputDialog.h" 15#include "inputDialog.h"
16#include "searchresults.h" 16#include "searchresults.h"
17#include "bac.h" 17#include "bac.h"
18 18
19#include <qpe/qpetoolbar.h> 19#include <qpe/qpetoolbar.h>
20#include <qmenubar.h> 20#include <qmenubar.h>
21//#include <opie2/colorpopupmenu.h> 21//#include <opie2/colorpopupmenu.h>
22#include <qpe/qpeapplication.h> 22#include <qpe/qpeapplication.h>
23#include <qpe/resource.h> 23#include <qpe/resource.h>
24 24
25#include <qlineedit.h> 25#include <qlineedit.h>
26#include <qdir.h> 26#include <qdir.h>
27#include <qpushbutton.h> 27#include <qpushbutton.h>
28#include <qlistbox.h> 28#include <qlistbox.h>
29#include <qmultilineedit.h> 29#include <qmultilineedit.h>
30#include <qmessagebox.h> 30#include <qmessagebox.h>
31#include <qtextstream.h> 31#include <qtextstream.h>
32#include <qaction.h> 32#include <qaction.h>
33#include <qheader.h> 33#include <qheader.h>
34#include <qlistview.h> 34#include <qlistview.h>
35#include <qlayout.h> 35#include <qlayout.h>
36 36
37#include <fcntl.h> 37#include <fcntl.h>
38#include <unistd.h> 38#include <unistd.h>
39#include <stdlib.h> 39#include <stdlib.h>
40#include <stdio.h> 40#include <stdio.h>
41#include <errno.h> 41#include <errno.h>
42 42
43 43
44Bartender::Bartender( QWidget* parent, const char* name, WFlags fl ) 44Bartender::Bartender( QWidget* parent, const char* name, WFlags fl )
45 : QMainWindow( parent, name, fl ) { 45 : QMainWindow( parent, name, fl ) {
46 if ( !name ) 46 if ( !name )
47 setName( "Bartender" ); 47 setName( "Bartender" );
48 QGridLayout *layout = new QGridLayout( this ); 48 QGridLayout *layout = new QGridLayout( this );
49 layout->setSpacing( 2); 49 layout->setSpacing( 2);
50 layout->setMargin( 2); 50 layout->setMargin( 2);
51 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 51 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
52 52
53 setCaption( tr( "Bartender" ) ); 53 setCaption( tr( "Bartender" ) );
54 54
55 ToolBar1 = new QToolBar( this, "ToolBar1" ); 55 ToolBar1 = new QToolBar( this, "ToolBar1" );
56 ToolBar1->setFixedHeight(22); 56 ToolBar1->setFixedHeight(22);
57 layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 ); 57 layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 );
58 58
59 QMenuBar *menuBar = new QMenuBar( ToolBar1 ); 59 QMenuBar *menuBar = new QMenuBar( ToolBar1 );
60 QPopupMenu *fileMenu; 60 QPopupMenu *fileMenu;
61 fileMenu = new QPopupMenu( this); 61 fileMenu = new QPopupMenu( this);
62 menuBar->insertItem( tr("File"), fileMenu ); 62 menuBar->insertItem( tr("File"), fileMenu );
63 63
64 fileMenu->insertItem(tr("New Drink")); 64 fileMenu->insertItem(tr("New Drink"));
65 fileMenu->insertItem(tr("Open Drink")); 65 fileMenu->insertItem(tr("Open Drink"));
66 fileMenu->insertItem(tr("Find by Drink Name")); 66 fileMenu->insertItem(tr("Find by Drink Name"));
67 fileMenu->insertItem(tr("Find by Alcohol")); 67 fileMenu->insertItem(tr("Find by Alcohol"));
68 68
69 QPopupMenu *editMenu; 69 QPopupMenu *editMenu;
70 editMenu = new QPopupMenu( this); 70 editMenu = new QPopupMenu( this);
71 menuBar->insertItem( tr("Edit"), editMenu ); 71 menuBar->insertItem( tr("Edit"), editMenu );
72 editMenu->insertItem(tr("edit")); 72 editMenu->insertItem(tr("edit"));
73 73
74 connect( fileMenu, SIGNAL( activated(int) ), this, SLOT( fileMenuActivated(int) )); 74 connect( fileMenu, SIGNAL( activated(int) ), this, SLOT( fileMenuActivated(int) ));
75 connect( editMenu, SIGNAL( activated(int) ), this, SLOT( editMenuActivated(int) )); 75 connect( editMenu, SIGNAL( activated(int) ), this, SLOT( editMenuActivated(int) ));
76 76
77 77
78 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), "New", 0, this, 0 ); 78 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), "New", 0, this, 0 );
79 connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); 79 connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) );
80 a->addTo( ToolBar1 ); 80 a->addTo( ToolBar1 );
81 81
82 a = new QAction( tr( "Open" ), Resource::loadPixmap( "bartender/bartender_sm" ), "open", 0, this, 0 ); 82 a = new QAction( tr( "Open" ), Resource::loadPixmap( "bartender/bartender_sm" ), "open", 0, this, 0 );
83 connect( a, SIGNAL( activated() ), this, SLOT( openCurrentDrink() ) ); 83 connect( a, SIGNAL( activated() ), this, SLOT( openCurrentDrink() ) );
84 a->addTo( ToolBar1 ); 84 a->addTo( ToolBar1 );
85 85
86 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), "Find", 0, this, 0 ); 86 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), "Find", 0, this, 0 );
87 connect( a, SIGNAL( activated() ), this, SLOT( askSearch() ) ); 87 connect( a, SIGNAL( activated() ), this, SLOT( askSearch() ) );
88 a->addTo( ToolBar1 ); 88 a->addTo( ToolBar1 );
89 89
90 a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ),"Edit", 0, this, 0 ); 90 a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ),"Edit", 0, this, 0 );
91 connect( a, SIGNAL( activated() ), this, SLOT( doEdit() ) ); 91 connect( a, SIGNAL( activated() ), this, SLOT( doEdit() ) );
92 a->addTo( ToolBar1 ); 92 a->addTo( ToolBar1 );
93 93
94 QPushButton *t; 94 QPushButton *t;
95 t= new QPushButton( "BAC", ToolBar1, "bacButtin"); 95 t= new QPushButton( "BAC", ToolBar1, "bacButtin");
96 connect( t, SIGNAL( clicked() ), this, SLOT( doBac() ) ); 96 connect( t, SIGNAL( clicked() ), this, SLOT( doBac() ) );
97 97
98 DrinkView = new QListView( this, "DrinkView" ); 98 DrinkView = new QListView( this, "DrinkView" );
99 DrinkView->addColumn( tr( "Name of Drink" ) ); 99 DrinkView->addColumn( tr( "Name of Drink" ) );
100// DrinkView->setRootIsDecorated( TRUE ); 100// DrinkView->setRootIsDecorated( TRUE );
101 DrinkView->header()->hide(); 101 DrinkView->header()->hide();
102 102
103 QPEApplication::setStylusOperation( DrinkView->viewport(),QPEApplication::RightOnHold); 103 QPEApplication::setStylusOperation( DrinkView->viewport(),QPEApplication::RightOnHold);
104 104
105 connect(DrinkView, SIGNAL( doubleClicked(QListViewItem*)),this,SLOT(showDrink( QListViewItem*))); 105 connect(DrinkView, SIGNAL( doubleClicked(QListViewItem*)),this,SLOT(showDrink(QListViewItem*)));
106 connect(DrinkView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), 106 connect(DrinkView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
107 this,SLOT( showDrink(int, QListViewItem *, const QPoint&, int))); 107 this,SLOT( showDrink(int,QListViewItem*,const QPoint&,int)));
108 108
109 layout->addMultiCellWidget( DrinkView, 1, 2, 0, 4 ); 109 layout->addMultiCellWidget( DrinkView, 1, 2, 0, 4 );
110 if(QDir("db").exists()) { 110 if(QDir("db").exists()) {
111 dbFile.setName( "db/drinkdb.txt"); 111 dbFile.setName( "db/drinkdb.txt");
112 } else 112 } else
113 dbFile.setName( QPEApplication::qpeDir()+"/etc/bartender/drinkdb.txt"); 113 dbFile.setName( QPEApplication::qpeDir()+"/etc/bartender/drinkdb.txt");
114 initDrinkDb(); 114 initDrinkDb();
115} 115}
116 116
117Bartender::~Bartender() { 117Bartender::~Bartender() {
118} 118}
119 119
120/* 120/*
121this happens right before exit */ 121this happens right before exit */
122void Bartender::cleanUp() { 122void Bartender::cleanUp() {
123 dbFile.close(); 123 dbFile.close();
124 124
125} 125}
126 126
127void Bartender::initDrinkDb() { 127void Bartender::initDrinkDb() {
128 128
129 if(!dbFile.isOpen()) 129 if(!dbFile.isOpen())
130 if ( !dbFile.open( IO_ReadOnly)) { 130 if ( !dbFile.open( IO_ReadOnly)) {
131 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); 131 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) );
132 return; 132 return;
133 } 133 }
134 fillList(); 134 fillList();
135} 135}
136 136
137void Bartender::fillList() { 137void Bartender::fillList() {
138 dbFile.at(1); 138 dbFile.at(1);
139 DrinkView->clear(); 139 DrinkView->clear();
140 int i=0; 140 int i=0;
141 QListViewItem * item ; 141 QListViewItem * item ;
142 QTextStream t( &dbFile); 142 QTextStream t( &dbFile);
143 QString s; 143 QString s;
144 while ( !t.eof()) { 144 while ( !t.eof()) {
145 s = t.readLine(); 145 s = t.readLine();
146 if(s.find("#",0,TRUE) != -1) { 146 if(s.find("#",0,TRUE) != -1) {
147// qDebug(s.right(s.length()-2)); 147// qDebug(s.right(s.length()-2));
148 item= new QListViewItem( DrinkView, 0 ); 148 item= new QListViewItem( DrinkView, 0 );
149 item->setText( 0, s.right(s.length()-2)); 149 item->setText( 0, s.right(s.length()-2));
150 i++; 150 i++;
151 } 151 }
152 } 152 }
153 qDebug("there are currently %d of drinks", i); 153 qDebug("there are currently %d of drinks", i);
154} 154}
155 155
156void Bartender::fileNew() { 156void Bartender::fileNew() {
157 157
158 New_Drink *newDrinks; 158 New_Drink *newDrinks;
159 newDrinks = new New_Drink(this,"New Drink....", TRUE); 159 newDrinks = new New_Drink(this,"New Drink....", TRUE);
160 QString newName, newIng; 160 QString newName, newIng;
161 QPEApplication::execDialog( newDrinks ); 161 QPEApplication::execDialog( newDrinks );
162 newName = newDrinks->LineEdit1->text(); 162 newName = newDrinks->LineEdit1->text();
163 newIng= newDrinks->MultiLineEdit1->text(); 163 newIng= newDrinks->MultiLineEdit1->text();
164 164
165 if(dbFile.isOpen()) 165 if(dbFile.isOpen())
166 dbFile.close(); 166 dbFile.close();
167 if ( !dbFile.open( IO_WriteOnly| IO_Append)) { 167 if ( !dbFile.open( IO_WriteOnly| IO_Append)) {
168 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); 168 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) );
169 return; 169 return;
170 } 170 }
171 if(newDrinks ->result() == 1 ) { 171 if(newDrinks ->result() == 1 ) {
172 QString newDrink="\n# "+newName+"\n"; 172 QString newDrink="\n# "+newName+"\n";
173 newDrink.append(newIng+"\n"); 173 newDrink.append(newIng+"\n");
174 qDebug("writing "+newDrink); 174 qDebug("writing "+newDrink);
175 dbFile.writeBlock( newDrink.latin1(), newDrink.length()); 175 dbFile.writeBlock( newDrink.latin1(), newDrink.length());
176 clearList(); 176 clearList();
177 dbFile.close(); 177 dbFile.close();
178 178
179 initDrinkDb(); 179 initDrinkDb();
180 } 180 }
181 delete newDrinks; 181 delete newDrinks;
182} 182}
183 183
184void Bartender::showDrink(int mouse, QListViewItem * item, const QPoint&, int) { 184void Bartender::showDrink(int mouse, QListViewItem * item, const QPoint&, int) {
185 switch (mouse) { 185 switch (mouse) {
186 case 1: 186 case 1:
187// showDrink(item); 187// showDrink(item);
188 break; 188 break;
189 case 2: 189 case 2:
190 showDrink(item); 190 showDrink(item);
191 break; 191 break;
192 } 192 }
193} 193}
194 194
195void Bartender::showDrink( QListViewItem *item) { 195void Bartender::showDrink( QListViewItem *item) {
196 if(item==NULL) return; 196 if(item==NULL) return;
197 dbFile.at(0); 197 dbFile.at(0);
198 Show_Drink *showDrinks; 198 Show_Drink *showDrinks;
199 QString myDrink=item->text(0); 199 QString myDrink=item->text(0);
200 showDrinks = new Show_Drink(this, myDrink, TRUE); 200 showDrinks = new Show_Drink(this, myDrink, TRUE);
201 QTextStream t( &dbFile); 201 QTextStream t( &dbFile);
202 202
203 QString s, s2; 203 QString s, s2;
204 while ( !t.eof()) { 204 while ( !t.eof()) {
205 s = t.readLine(); 205 s = t.readLine();
206 if(s.find( myDrink, 0, TRUE) != -1) { 206 if(s.find( myDrink, 0, TRUE) != -1) {
207 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { 207 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) {
208 s2 = t.readLine(); 208 s2 = t.readLine();
209 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { 209 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) {
210// qDebug(s2); 210// qDebug(s2);
211 showDrinks->MultiLineEdit1->append(s2); 211 showDrinks->MultiLineEdit1->append(s2);
212 } 212 }
213 if( dbFile.atEnd() ) break; 213 if( dbFile.atEnd() ) break;
214 } 214 }
215 } 215 }
216 } 216 }
217 QPEApplication::execDialog( showDrinks ); 217 QPEApplication::execDialog( showDrinks );
218 218
219 if(showDrinks ->result() ==0) { 219 if(showDrinks ->result() ==0) {
220 doEdit(); 220 doEdit();
221 } 221 }
222 delete showDrinks; 222 delete showDrinks;
223} 223}
224 224
225void Bartender::askSearch() { 225void Bartender::askSearch() {
226 switch ( QMessageBox::warning(this,tr("Find"),tr("Search by drink name\n")+ 226 switch ( QMessageBox::warning(this,tr("Find"),tr("Search by drink name\n")+
227 "\nor alcohol ?" 227 "\nor alcohol ?"
228 ,tr("Drink Name"),tr("Alcohol"),0,0,1) ) { 228 ,tr("Drink Name"),tr("Alcohol"),0,0,1) ) {
229 case 0: 229 case 0:
230 doSearchByName(); 230 doSearchByName();
231 break; 231 break;
232 case 1: 232 case 1:
233 doSearchByDrink(); 233 doSearchByDrink();
234 break; 234 break;
235 }; 235 };
236} 236}
237 237
238/* search by name */ 238/* search by name */
239void Bartender::doSearchByName() { 239void Bartender::doSearchByName() {
240// if( DrinkView->currentItem() == NULL) return; 240// if( DrinkView->currentItem() == NULL) return;
241 QStringList searchList; 241 QStringList searchList;
242 QString searchForDrinkName; 242 QString searchForDrinkName;
243 InputDialog *fileDlg; 243 InputDialog *fileDlg;
244 fileDlg = new InputDialog(this,tr("Find by Drink Name"),TRUE, 0); 244 fileDlg = new InputDialog(this,tr("Find by Drink Name"),TRUE, 0);
245 fileDlg->exec(); 245 fileDlg->exec();
246 if( fileDlg->result() == 1 ) { 246 if( fileDlg->result() == 1 ) {
247 searchForDrinkName = fileDlg->LineEdit1->text(); 247 searchForDrinkName = fileDlg->LineEdit1->text();
248 QListViewItemIterator it( DrinkView ); 248 QListViewItemIterator it( DrinkView );
249 for ( ; it.current(); ++it ) { 249 for ( ; it.current(); ++it ) {
250 if ( it.current()->text(0).find( searchForDrinkName, 0, TRUE) != -1 ) { 250 if ( it.current()->text(0).find( searchForDrinkName, 0, TRUE) != -1 ) {
251// qDebug( it.current()->text(0)); 251// qDebug( it.current()->text(0));
252 searchList.append(it.current()->text(0)); 252 searchList.append(it.current()->text(0));
253 } 253 }
254 } 254 }
255 if(searchList.count() >0) 255 if(searchList.count() >0)
256 showSearchResult(searchList); 256 showSearchResult(searchList);
257 else 257 else
258 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+searchForDrinkName); 258 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+searchForDrinkName);
259 }//end Inputdialog 259 }//end Inputdialog
260 delete fileDlg; 260 delete fileDlg;
261} 261}
262 262
263void Bartender::doSearchByDrink() { 263void Bartender::doSearchByDrink() {
264// if( DrinkView->currentItem() == NULL) return; 264// if( DrinkView->currentItem() == NULL) return;
265 QStringList searchList; 265 QStringList searchList;
266 QString searchForDrinkName, lastDrinkName, tempName; 266 QString searchForDrinkName, lastDrinkName, tempName;
267 267
268 InputDialog *fileDlg; 268 InputDialog *fileDlg;
269 fileDlg = new InputDialog(this,tr("Find by Alcohol"),TRUE, 0); 269 fileDlg = new InputDialog(this,tr("Find by Alcohol"),TRUE, 0);
270 fileDlg->exec(); 270 fileDlg->exec();
271 if( fileDlg->result() == 1 ) { 271 if( fileDlg->result() == 1 ) {
272 searchForDrinkName = fileDlg->LineEdit1->text(); 272 searchForDrinkName = fileDlg->LineEdit1->text();
273 273
274 dbFile.at(0); 274 dbFile.at(0);
275 QTextStream t( &dbFile); 275 QTextStream t( &dbFile);
276 276
277 QString s, s2; 277 QString s, s2;
278 while ( !t.eof()) { 278 while ( !t.eof()) {
279 s = t.readLine(); 279 s = t.readLine();
280 if(s.find("#",0,TRUE) != -1) { 280 if(s.find("#",0,TRUE) != -1) {
281 lastDrinkName=s.right(s.length()-2); 281 lastDrinkName=s.right(s.length()-2);
282// qDebug("last drink name "+lastDrinkName); 282// qDebug("last drink name "+lastDrinkName);
283 } 283 }
284 else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) { 284 else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) {
285// qDebug("appending "+lastDrinkName); 285// qDebug("appending "+lastDrinkName);
286 searchList.append( lastDrinkName); 286 searchList.append( lastDrinkName);
287 tempName=lastDrinkName; 287 tempName=lastDrinkName;
288 } 288 }
289// if( dbFile.atEnd() ) break; 289// if( dbFile.atEnd() ) break;
290 290
291 } //oef 291 } //oef
292 if(searchList.count() >0) 292 if(searchList.count() >0)
293 showSearchResult(searchList); 293 showSearchResult(searchList);
294 else 294 else
295 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+ searchForDrinkName); 295 QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+ searchForDrinkName);
296 } 296 }
297 delete fileDlg; 297 delete fileDlg;
298} 298}
299 299
300void Bartender::showSearchResult(QStringList &searchList) { 300void Bartender::showSearchResult(QStringList &searchList) {
301 QString result; 301 QString result;
302 Search_Results *searchDlg; 302 Search_Results *searchDlg;
303 303
304 searchList.sort(); 304 searchList.sort();
305 305
306 searchDlg = new Search_Results(this, "Search Results", TRUE); 306 searchDlg = new Search_Results(this, "Search Results", TRUE);
307 searchDlg->ListBox1->insertStringList( searchList,-1); 307 searchDlg->ListBox1->insertStringList( searchList,-1);
308 QPEApplication::execDialog( searchDlg ); 308 QPEApplication::execDialog( searchDlg );
309 309
310 if( searchDlg->result() == 1 ) { 310 if( searchDlg->result() == 1 ) {
311 result= searchDlg->ListBox1->currentText(); 311 result= searchDlg->ListBox1->currentText();
312 } 312 }
313 QListViewItemIterator it2( DrinkView ); 313 QListViewItemIterator it2( DrinkView );
314 for ( ; it2.current(); ++it2 ) { 314 for ( ; it2.current(); ++it2 ) {
315 if ( it2.current()->text(0)== result ) { 315 if ( it2.current()->text(0)== result ) {
316// qDebug( it2.current()->text(0)); 316// qDebug( it2.current()->text(0));
317 showDrink(it2.current()); 317 showDrink(it2.current());
318 } 318 }
319 } 319 }
320delete searchDlg; 320delete searchDlg;
321} 321}
322 322
323void Bartender::doEdit() { 323void Bartender::doEdit() {
324 if(DrinkView->currentItem() == NULL) { 324 if(DrinkView->currentItem() == NULL) {
325 fileNew(); 325 fileNew();
326 } 326 }
327 327
328 QString myDrink; 328 QString myDrink;
329 myDrink= DrinkView->currentItem()->text(0); 329 myDrink= DrinkView->currentItem()->text(0);
330 dbFile.at(0); 330 dbFile.at(0);
331 int foundAt=0; 331 int foundAt=0;
332 New_Drink *newDrinks; 332 New_Drink *newDrinks;
333 newDrinks = new New_Drink(this,"Edit Drink....", TRUE); 333 newDrinks = new New_Drink(this,"Edit Drink....", TRUE);
334 QString newName, newIng; 334 QString newName, newIng;
335 QPEApplication::showDialog( newDrinks ); 335 QPEApplication::showDialog( newDrinks );
336 QTextStream t( &dbFile); 336 QTextStream t( &dbFile);
337 337
338 QString s, s2; 338 QString s, s2;
339 while ( !t.eof()) { 339 while ( !t.eof()) {
340 s = t.readLine(); 340 s = t.readLine();
341 if(s.find( myDrink, 0, TRUE) != -1) { 341 if(s.find( myDrink, 0, TRUE) != -1) {
342 foundAt = dbFile.at() - (s.length()+1); 342 foundAt = dbFile.at() - (s.length()+1);
343 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { 343 for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) {
344 s2 = t.readLine(); 344 s2 = t.readLine();
345 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { 345 if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) {
346// qDebug(s2); 346// qDebug(s2);
347 newDrinks->MultiLineEdit1->append(s2); 347 newDrinks->MultiLineEdit1->append(s2);
348 newDrinks->LineEdit1->setText(myDrink); 348 newDrinks->LineEdit1->setText(myDrink);
349 } 349 }
350 if( dbFile.atEnd() ) break; 350 if( dbFile.atEnd() ) break;
351 } 351 }
352 } 352 }
353 } 353 }
354 newDrinks->exec(); 354 newDrinks->exec();
355 newName = newDrinks->LineEdit1->text(); 355 newName = newDrinks->LineEdit1->text();
356 newIng= newDrinks->MultiLineEdit1->text(); 356 newIng= newDrinks->MultiLineEdit1->text();
357 357
358 if( newDrinks ->result() == 1 ) { 358 if( newDrinks ->result() == 1 ) {
359 if(dbFile.isOpen()) 359 if(dbFile.isOpen())
360 dbFile.close(); 360 dbFile.close();
361 if ( !dbFile.open( IO_ReadWrite )) { 361 if ( !dbFile.open( IO_ReadWrite )) {
362 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); 362 QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) );
363 return; 363 return;
364 } 364 }
365 int fd = dbFile.handle(); 365 int fd = dbFile.handle();
366 lseek( fd, foundAt, SEEK_SET); 366 lseek( fd, foundAt, SEEK_SET);
367 367
368// dbFile.at( foundAt); 368// dbFile.at( foundAt);
369#warning FIXME problems with editing drinks db 369#warning FIXME problems with editing drinks db
370 ////////// FIXME write to user file 370 ////////// FIXME write to user file
371 QString newDrink="# "+newName+"\n"; 371 QString newDrink="# "+newName+"\n";
372 newDrink.append(newIng+"\n"); 372 newDrink.append(newIng+"\n");
373 qDebug("writing "+newDrink); 373 qDebug("writing "+newDrink);
374 dbFile.writeBlock( newDrink.latin1(), newDrink.length()); 374 dbFile.writeBlock( newDrink.latin1(), newDrink.length());
375 clearList(); 375 clearList();
376 376
377 dbFile.flush(); 377 dbFile.flush();
378 378
379 initDrinkDb(); 379 initDrinkDb();
380 } 380 }
381} 381}
382 382
383void Bartender::clearList() { 383void Bartender::clearList() {
384 DrinkView->clear(); 384 DrinkView->clear();
385} 385}
386 386
387void Bartender::doBac() { 387void Bartender::doBac() {
388 BacDialog *bacDlg; 388 BacDialog *bacDlg;
389 bacDlg = new BacDialog(this,"BAC",TRUE); 389 bacDlg = new BacDialog(this,"BAC",TRUE);
390 QPEApplication::execDialog( bacDlg ); 390 QPEApplication::execDialog( bacDlg );
391 delete bacDlg; 391 delete bacDlg;
392} 392}
393 393
394void Bartender::openCurrentDrink() { 394void Bartender::openCurrentDrink() {
395 if(DrinkView->currentItem() == NULL) return; 395 if(DrinkView->currentItem() == NULL) return;
396 showDrink(DrinkView->currentItem()); 396 showDrink(DrinkView->currentItem());
397} 397}
398 398
399void Bartender::fileMenuActivated( int item) { 399void Bartender::fileMenuActivated( int item) {
400 qDebug("Item %d", item); 400 qDebug("Item %d", item);
401 switch(item) { 401 switch(item) {
402 case -3: // new -3 402 case -3: // new -3
403 fileNew(); 403 fileNew();
404 break; 404 break;
405 case -4:// open -4 405 case -4:// open -4
406 openCurrentDrink(); 406 openCurrentDrink();
407 break; 407 break;
408 case -5:// drink -5 408 case -5:// drink -5
409 doSearchByName(); 409 doSearchByName();
410 410
411 break; 411 break;
412 case -6:// alcohol -6 412 case -6:// alcohol -6
413 doSearchByDrink(); 413 doSearchByDrink();
414 414
415 break; 415 break;
416 416
417 } 417 }
418} 418}
419 419
420void Bartender::editMenuActivated(int item) { 420void Bartender::editMenuActivated(int item) {
421 qDebug("Item %d", item); 421 qDebug("Item %d", item);
422 /* 422 /*
423 edit -8 423 edit -8
424 */ 424 */
425 switch(item) { 425 switch(item) {
426 case -8: 426 case -8:
427 doEdit() ; 427 doEdit() ;
428 break; 428 break;
429 429
430 } 430 }
431} 431}
432 432
diff --git a/noncore/apps/opie-bartender/searchresults.cpp b/noncore/apps/opie-bartender/searchresults.cpp
index 4900d1f..a511a57 100644
--- a/noncore/apps/opie-bartender/searchresults.cpp
+++ b/noncore/apps/opie-bartender/searchresults.cpp
@@ -1,43 +1,43 @@
1/**************************************************************************** 1/****************************************************************************
2** Created: Sat Jul 20 08:23:27 2002 2** Created: Sat Jul 20 08:23:27 2002
3** by: L.J. Potter <ljp@llornkcor.com> 3** by: L.J. Potter <ljp@llornkcor.com>
4** copyright : (C) 2002 by ljp 4** copyright : (C) 2002 by ljp
5 email : ljp@llornkcor.com 5 email : ljp@llornkcor.com
6 * This program is free software; you can redistribute it and/or modify * 6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by * 7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or * 8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. * 9 * (at your option) any later version. *
10 ***************************************************************************/ 10 ***************************************************************************/
11#include "searchresults.h" 11#include "searchresults.h"
12 12
13 13
14#include <qlistbox.h> 14#include <qlistbox.h>
15#include <qlayout.h> 15#include <qlayout.h>
16 16
17Search_Results::Search_Results( QWidget* parent, const char* name, bool modal, WFlags fl ) 17Search_Results::Search_Results( QWidget* parent, const char* name, bool modal, WFlags fl )
18 : QDialog( parent, name, modal, fl ) { 18 : QDialog( parent, name, modal, fl ) {
19 if ( !name ) 19 if ( !name )
20 setName( drinkName); 20 setName( drinkName);
21 21
22 drinkName = name; 22 drinkName = name;
23 setCaption( drinkName ); 23 setCaption( drinkName );
24 24
25 Layout5 = new QGridLayout( this ); 25 Layout5 = new QGridLayout( this );
26 Layout5->setSpacing( 6 ); 26 Layout5->setSpacing( 6 );
27 Layout5->setMargin( 4 ); 27 Layout5->setMargin( 4 );
28 28
29 ListBox1 = new QListBox( this, "ListBox1" ); 29 ListBox1 = new QListBox( this, "ListBox1" );
30 30
31 Layout5->addMultiCellWidget( ListBox1, 0, 1, 0, 3 ); 31 Layout5->addMultiCellWidget( ListBox1, 0, 1, 0, 3 );
32 connect( ListBox1, SIGNAL( clicked( QListBoxItem *)), SLOT( listSelected( QListBoxItem *)) ); 32 connect( ListBox1, SIGNAL( clicked(QListBoxItem*)), SLOT( listSelected(QListBoxItem*)) );
33} 33}
34 34
35Search_Results::~Search_Results() { 35Search_Results::~Search_Results() {
36} 36}
37 37
38 38
39void Search_Results::listSelected(QListBoxItem *) { 39void Search_Results::listSelected(QListBoxItem *) {
40 40
41 QDialog::accept(); 41 QDialog::accept();
42} 42}
43 43
diff --git a/noncore/apps/opie-console/btconfigwidget.cpp b/noncore/apps/opie-console/btconfigwidget.cpp
index 64046d8..0ac337f 100644
--- a/noncore/apps/opie-console/btconfigwidget.cpp
+++ b/noncore/apps/opie-console/btconfigwidget.cpp
@@ -1,190 +1,190 @@
1#include <qlabel.h> 1#include <qlabel.h>
2#include <qlayout.h> 2#include <qlayout.h>
3#include <qlineedit.h> 3#include <qlineedit.h>
4#include <qcombobox.h> 4#include <qcombobox.h>
5#include <qhbox.h> 5#include <qhbox.h>
6#include <qradiobutton.h> 6#include <qradiobutton.h>
7 7
8#include "iolayerbase.h" 8#include "iolayerbase.h"
9#include "btconfigwidget.h" 9#include "btconfigwidget.h"
10 10
11namespace { 11namespace {
12 void setCurrent( const QString& str, QComboBox* bo ) { 12 void setCurrent( const QString& str, QComboBox* bo ) {
13 uint b = bo->count(); 13 uint b = bo->count();
14 for (int i = 0; i < bo->count(); i++ ) { 14 for (int i = 0; i < bo->count(); i++ ) {
15 if ( bo->text(i) == str ) { 15 if ( bo->text(i) == str ) {
16 bo->setCurrentItem( i ); 16 bo->setCurrentItem( i );
17 return; 17 return;
18 } 18 }
19 } 19 }
20 bo->insertItem( str ); 20 bo->insertItem( str );
21 bo->setCurrentItem( b ); 21 bo->setCurrentItem( b );
22 } 22 }
23} 23}
24 24
25BTConfigWidget::BTConfigWidget( const QString& name, 25BTConfigWidget::BTConfigWidget( const QString& name,
26 QWidget* parent, 26 QWidget* parent,
27 const char* na ) 27 const char* na )
28 : ProfileDialogConnectionWidget( name, parent, na ) { 28 : ProfileDialogConnectionWidget( name, parent, na ) {
29 29
30 m_lay = new QVBoxLayout( this ); 30 m_lay = new QVBoxLayout( this );
31 31
32 m_device = new QLabel( tr( "Device" ), this ); 32 m_device = new QLabel( tr( "Device" ), this );
33 QHBox *deviceBox = new QHBox( this ); 33 QHBox *deviceBox = new QHBox( this );
34 m_devRadio = new QRadioButton( deviceBox ); 34 m_devRadio = new QRadioButton( deviceBox );
35 connect( m_devRadio, SIGNAL( toggled( bool ) ), this, SLOT( slotDevRadio( bool ) ) ); 35 connect( m_devRadio, SIGNAL( toggled(bool) ), this, SLOT( slotDevRadio(bool) ) );
36 m_deviceCmb = new QComboBox( deviceBox ); 36 m_deviceCmb = new QComboBox( deviceBox );
37 m_deviceCmb->setEditable( TRUE ); 37 m_deviceCmb->setEditable( TRUE );
38 38
39 QLabel *macLabel = new QLabel( this ); 39 QLabel *macLabel = new QLabel( this );
40 macLabel->setText( tr( "Or peer mac address" ) ); 40 macLabel->setText( tr( "Or peer mac address" ) );
41 QHBox *macBox = new QHBox( this ); 41 QHBox *macBox = new QHBox( this );
42 m_macRadio = new QRadioButton( macBox ); 42 m_macRadio = new QRadioButton( macBox );
43 connect( m_macRadio, SIGNAL( toggled( bool ) ), this, SLOT( slotMacRadio( bool ) ) ); 43 connect( m_macRadio, SIGNAL( toggled(bool) ), this, SLOT( slotMacRadio(bool) ) );
44 m_mac = new QLineEdit( macBox ); 44 m_mac = new QLineEdit( macBox );
45 45
46 m_base = new IOLayerBase(this, "base"); 46 m_base = new IOLayerBase(this, "base");
47 47
48 m_lay->addWidget( m_device ); 48 m_lay->addWidget( m_device );
49 m_lay->addWidget( deviceBox ); 49 m_lay->addWidget( deviceBox );
50 m_lay->addWidget( macLabel ); 50 m_lay->addWidget( macLabel );
51 m_lay->addWidget( macBox ); 51 m_lay->addWidget( macBox );
52 m_lay->addWidget( m_base ); 52 m_lay->addWidget( m_base );
53 53
54 m_deviceCmb->insertItem( "/dev/ttyU0" ); 54 m_deviceCmb->insertItem( "/dev/ttyU0" );
55 m_deviceCmb->insertItem( "/dev/ttyU1" ); 55 m_deviceCmb->insertItem( "/dev/ttyU1" );
56} 56}
57 57
58BTConfigWidget::~BTConfigWidget() { 58BTConfigWidget::~BTConfigWidget() {
59 59
60} 60}
61void BTConfigWidget::load( const Profile& prof ) { 61void BTConfigWidget::load( const Profile& prof ) {
62 int rad_flow = prof.readNumEntry("Flow"); 62 int rad_flow = prof.readNumEntry("Flow");
63 int rad_parity = prof.readNumEntry("Parity"); 63 int rad_parity = prof.readNumEntry("Parity");
64 int speed = prof.readNumEntry("Speed"); 64 int speed = prof.readNumEntry("Speed");
65 QString mac = prof.readEntry("Mac"); 65 QString mac = prof.readEntry("Mac");
66 66
67 if (!mac.isEmpty() ) { 67 if (!mac.isEmpty() ) {
68 m_mac->setText( mac ); 68 m_mac->setText( mac );
69 } else { 69 } else {
70 m_devRadio->setChecked( true ); 70 m_devRadio->setChecked( true );
71 } 71 }
72 72
73 if (rad_flow == 1) { 73 if (rad_flow == 1) {
74 m_base->setFlow( IOLayerBase::Hardware ); 74 m_base->setFlow( IOLayerBase::Hardware );
75 } else if (rad_flow == 2) { 75 } else if (rad_flow == 2) {
76 m_base->setFlow( IOLayerBase::Software ); 76 m_base->setFlow( IOLayerBase::Software );
77 } else if (rad_flow == 0) { 77 } else if (rad_flow == 0) {
78 m_base->setFlow( IOLayerBase::None ); 78 m_base->setFlow( IOLayerBase::None );
79 } 79 }
80 80
81 if (rad_parity == 1) { 81 if (rad_parity == 1) {
82 m_base->setParity( IOLayerBase::Even ); 82 m_base->setParity( IOLayerBase::Even );
83 } else if ( rad_parity == 2 ) { 83 } else if ( rad_parity == 2 ) {
84 m_base->setParity( IOLayerBase::Odd ); 84 m_base->setParity( IOLayerBase::Odd );
85 } else { 85 } else {
86 m_base->setParity( IOLayerBase::NonePar ); 86 m_base->setParity( IOLayerBase::NonePar );
87 } 87 }
88 88
89 switch( speed ) { 89 switch( speed ) {
90 case 115200: 90 case 115200:
91 m_base->setSpeed(IOLayerBase::Baud_115200 ); 91 m_base->setSpeed(IOLayerBase::Baud_115200 );
92 break; 92 break;
93 case 57600: 93 case 57600:
94 m_base->setSpeed( IOLayerBase::Baud_57600 ); 94 m_base->setSpeed( IOLayerBase::Baud_57600 );
95 break; 95 break;
96 case 38400: 96 case 38400:
97 m_base->setSpeed(IOLayerBase::Baud_38400 ); 97 m_base->setSpeed(IOLayerBase::Baud_38400 );
98 break; 98 break;
99 case 19200: 99 case 19200:
100 m_base->setSpeed( IOLayerBase::Baud_19200 ); 100 m_base->setSpeed( IOLayerBase::Baud_19200 );
101 break; 101 break;
102 case 9600: 102 case 9600:
103 default: 103 default:
104 m_base->setSpeed(IOLayerBase::Baud_9600 ); 104 m_base->setSpeed(IOLayerBase::Baud_9600 );
105 break; 105 break;
106 } 106 }
107 107
108 if ( prof.readEntry("Device").isEmpty() ) return; 108 if ( prof.readEntry("Device").isEmpty() ) return;
109 setCurrent( prof.readEntry("Device"), m_deviceCmb ); 109 setCurrent( prof.readEntry("Device"), m_deviceCmb );
110 110
111} 111}
112/* 112/*
113 * save speed, 113 * save speed,
114 * flow, 114 * flow,
115 * parity 115 * parity
116 */ 116 */
117void BTConfigWidget::save( Profile& prof ) { 117void BTConfigWidget::save( Profile& prof ) {
118 int flow, parity, speed; 118 int flow, parity, speed;
119 flow = parity = speed = 0; 119 flow = parity = speed = 0;
120 prof.writeEntry("Device", m_deviceCmb->currentText() ); 120 prof.writeEntry("Device", m_deviceCmb->currentText() );
121 121
122 122
123 switch( m_base->flow() ) { 123 switch( m_base->flow() ) {
124 case IOLayerBase::None: 124 case IOLayerBase::None:
125 flow = 0; 125 flow = 0;
126 break; 126 break;
127 case IOLayerBase::Software: 127 case IOLayerBase::Software:
128 flow = 2; 128 flow = 2;
129 break; 129 break;
130 case IOLayerBase::Hardware: 130 case IOLayerBase::Hardware:
131 flow = 1; 131 flow = 1;
132 break; 132 break;
133 } 133 }
134 134
135 switch( m_base->parity() ) { 135 switch( m_base->parity() ) {
136 case IOLayerBase::Odd: 136 case IOLayerBase::Odd:
137 parity = 2; 137 parity = 2;
138 break; 138 break;
139 case IOLayerBase::Even: 139 case IOLayerBase::Even:
140 parity = 1; 140 parity = 1;
141 break; 141 break;
142 case IOLayerBase::NonePar: 142 case IOLayerBase::NonePar:
143 parity = 0; 143 parity = 0;
144 break; 144 break;
145 } 145 }
146 146
147 switch( m_base->speed() ) { 147 switch( m_base->speed() ) {
148 case IOLayerBase::Baud_115200: 148 case IOLayerBase::Baud_115200:
149 speed = 115200; 149 speed = 115200;
150 break; 150 break;
151 case IOLayerBase::Baud_57600: 151 case IOLayerBase::Baud_57600:
152 speed = 57600; 152 speed = 57600;
153 break; 153 break;
154 case IOLayerBase::Baud_38400: 154 case IOLayerBase::Baud_38400:
155 speed = 38400; 155 speed = 38400;
156 break; 156 break;
157 case IOLayerBase::Baud_19200: 157 case IOLayerBase::Baud_19200:
158 speed = 19200; 158 speed = 19200;
159 break; 159 break;
160 default: 160 default:
161 case IOLayerBase::Baud_9600: 161 case IOLayerBase::Baud_9600:
162 speed = 9600; 162 speed = 9600;
163 break; 163 break;
164 } 164 }
165 165
166 prof.writeEntry("Flow", flow); 166 prof.writeEntry("Flow", flow);
167 prof.writeEntry("Parity", parity); 167 prof.writeEntry("Parity", parity);
168 prof.writeEntry("Speed", speed); 168 prof.writeEntry("Speed", speed);
169 prof.writeEntry("Mac", m_mac->text() ); 169 prof.writeEntry("Mac", m_mac->text() );
170} 170}
171 171
172void BTConfigWidget::slotMacRadio( bool on ) { 172void BTConfigWidget::slotMacRadio( bool on ) {
173 if ( on ) { 173 if ( on ) {
174 m_devRadio->setChecked( false ); 174 m_devRadio->setChecked( false );
175 m_deviceCmb->setEnabled( false ); 175 m_deviceCmb->setEnabled( false );
176 m_mac->setEnabled( true ); 176 m_mac->setEnabled( true );
177 } else { 177 } else {
178 m_devRadio->setChecked( true ); 178 m_devRadio->setChecked( true );
179 } 179 }
180} 180}
181 181
182void BTConfigWidget::slotDevRadio( bool on ) { 182void BTConfigWidget::slotDevRadio( bool on ) {
183 if ( on ) { 183 if ( on ) {
184 m_macRadio->setChecked( false ); 184 m_macRadio->setChecked( false );
185 m_deviceCmb->setEnabled( true ); 185 m_deviceCmb->setEnabled( true );
186 m_mac->setEnabled( false ); 186 m_mac->setEnabled( false );
187 } else { 187 } else {
188 m_macRadio->setChecked( true ); 188 m_macRadio->setChecked( true );
189 } 189 }
190} 190}
diff --git a/noncore/apps/opie-console/dialdialog.cpp b/noncore/apps/opie-console/dialdialog.cpp
index 6bc1240..526d55e 100644
--- a/noncore/apps/opie-console/dialdialog.cpp
+++ b/noncore/apps/opie-console/dialdialog.cpp
@@ -1,98 +1,98 @@
1 1
2 2
3#include <qlayout.h> 3#include <qlayout.h>
4#include <qlabel.h> 4#include <qlabel.h>
5#include <qpushbutton.h> 5#include <qpushbutton.h>
6#include <qbuttongroup.h> 6#include <qbuttongroup.h>
7 7
8#include "dialdialog.h" 8#include "dialdialog.h"
9 9
10 10
11 11
12DialDialog::DialDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 12DialDialog::DialDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
13 : QDialog( parent, name, modal, fl ) { 13 : QDialog( parent, name, modal, fl ) {
14 14
15 setCaption( tr( "Enter number" ) ); 15 setCaption( tr( "Enter number" ) );
16 16
17 QVBoxLayout *mainLayout = new QVBoxLayout( this ); 17 QVBoxLayout *mainLayout = new QVBoxLayout( this );
18 18
19 QLabel *textLabel = new QLabel( this ); 19 QLabel *textLabel = new QLabel( this );
20 textLabel->setTextFormat( QLabel::RichText ); 20 textLabel->setTextFormat( QLabel::RichText );
21 textLabel->setText( tr("Enter the number you want to dial. When finished, press ok") ); 21 textLabel->setText( tr("Enter the number you want to dial. When finished, press ok") );
22 22
23 m_dialLine = new QLineEdit( this ); 23 m_dialLine = new QLineEdit( this );
24 m_dialLine->setReadOnly( true ); 24 m_dialLine->setReadOnly( true );
25 m_dialLine->setFrame( false ); 25 m_dialLine->setFrame( false );
26 m_dialLine->setAlignment( Qt::AlignLeft ); 26 m_dialLine->setAlignment( Qt::AlignLeft );
27 QFont dialLine_font( m_dialLine->font() ); 27 QFont dialLine_font( m_dialLine->font() );
28 dialLine_font.setBold( TRUE ); 28 dialLine_font.setBold( TRUE );
29 dialLine_font.setPointSize( 18 ); 29 dialLine_font.setPointSize( 18 );
30 m_dialLine->setFont( dialLine_font ); 30 m_dialLine->setFont( dialLine_font );
31 31
32 QWidget* dialWidget = new QWidget( this ); 32 QWidget* dialWidget = new QWidget( this );
33 QGridLayout *layout = new QGridLayout( dialWidget , 4, 3 ); 33 QGridLayout *layout = new QGridLayout( dialWidget , 4, 3 );
34 34
35 QButtonGroup *dialButtons = new QButtonGroup( ); 35 QButtonGroup *dialButtons = new QButtonGroup( );
36 36
37 QPushButton *number0 = new QPushButton( dialWidget ); 37 QPushButton *number0 = new QPushButton( dialWidget );
38 number0->setText( QString( "0" ) ); 38 number0->setText( QString( "0" ) );
39 QFont number0_font( number0->font() ); 39 QFont number0_font( number0->font() );
40 number0_font.setBold( TRUE ); 40 number0_font.setBold( TRUE );
41 number0->setFont( number0_font ); 41 number0->setFont( number0_font );
42 layout->addWidget( number0, 4, 1 ); 42 layout->addWidget( number0, 4, 1 );
43 dialButtons->insert( number0 ); 43 dialButtons->insert( number0 );
44 44
45 int x = 0, y = 0; 45 int x = 0, y = 0;
46 for ( int i = 0 ; i < 9; i++ ) { 46 for ( int i = 0 ; i < 9; i++ ) {
47 QPushButton *number = new QPushButton( dialWidget ); 47 QPushButton *number = new QPushButton( dialWidget );
48 number->setText( QString( "%1" ).arg( i + 1 ) ); 48 number->setText( QString( "%1" ).arg( i + 1 ) );
49 QFont number_font( number->font() ); 49 QFont number_font( number->font() );
50 number_font.setBold( TRUE ); 50 number_font.setBold( TRUE );
51 number->setFont( number_font ); 51 number->setFont( number_font );
52 52
53 dialButtons->insert( number ); 53 dialButtons->insert( number );
54 54
55 layout->addWidget( number, x, y ); 55 layout->addWidget( number, x, y );
56 56
57 if ( y < 2 ) { 57 if ( y < 2 ) {
58 y++; 58 y++;
59 } else { 59 } else {
60 x++; 60 x++;
61 y = 0; 61 y = 0;
62 } 62 }
63 } 63 }
64 64
65 connect( dialButtons, SIGNAL( clicked( int ) ), this, SLOT( slotEnterNumber( int ) ) ); 65 connect( dialButtons, SIGNAL( clicked(int) ), this, SLOT( slotEnterNumber(int) ) );
66 66
67 mainLayout->addStretch( 2 ); 67 mainLayout->addStretch( 2 );
68 mainLayout->addWidget( textLabel ); 68 mainLayout->addWidget( textLabel );
69 mainLayout->addStretch( 1 ); 69 mainLayout->addStretch( 1 );
70 mainLayout->addWidget( m_dialLine ); 70 mainLayout->addWidget( m_dialLine );
71 mainLayout->addStretch( 2 ); 71 mainLayout->addStretch( 2 );
72 mainLayout->addWidget( dialWidget ); 72 mainLayout->addWidget( dialWidget );
73 mainLayout->addStretch( 4 ); 73 mainLayout->addStretch( 4 );
74} 74}
75 75
76 76
77void DialDialog::slotEnterNumber( int number ) { 77void DialDialog::slotEnterNumber( int number ) {
78 78
79 // pretty stupid, just for testing .-) 79 // pretty stupid, just for testing .-)
80 80
81 m_number.append(QString("%1").arg(number)); 81 m_number.append(QString("%1").arg(number));
82 82
83 setNumber(m_number); 83 setNumber(m_number);
84} 84}
85 85
86DialDialog::~DialDialog() { 86DialDialog::~DialDialog() {
87} 87}
88 88
89QString DialDialog::number() { 89QString DialDialog::number() {
90 return m_number; 90 return m_number;
91 91
92} 92}
93 93
94void DialDialog::setNumber( QString number ) 94void DialDialog::setNumber( QString number )
95{ 95{
96 m_dialLine->setText( QString("%1").arg( number ) ); 96 m_dialLine->setText( QString("%1").arg( number ) );
97} 97}
98 98
diff --git a/noncore/apps/opie-console/emulation_handler.cpp b/noncore/apps/opie-console/emulation_handler.cpp
index 2c1d888..99d069f 100644
--- a/noncore/apps/opie-console/emulation_handler.cpp
+++ b/noncore/apps/opie-console/emulation_handler.cpp
@@ -1,206 +1,206 @@
1 1
2#include "TEmuVt102.h" 2#include "TEmuVt102.h"
3 3
4#include "profile.h" 4#include "profile.h"
5#include "emulation_handler.h" 5#include "emulation_handler.h"
6#include "script.h" 6#include "script.h"
7 7
8EmulationHandler::EmulationHandler( const Profile& prof, QWidget* parent,const char* name ) 8EmulationHandler::EmulationHandler( const Profile& prof, QWidget* parent,const char* name )
9 : QObject(0, name ) 9 : QObject(0, name )
10{ 10{
11 m_teWid = new TEWidget( parent, "TerminalMain"); 11 m_teWid = new TEWidget( parent, "TerminalMain");
12 // use setWrapAt(0) for classic behaviour (wrap at screen width, no scrollbar) 12 // use setWrapAt(0) for classic behaviour (wrap at screen width, no scrollbar)
13 // use setWrapAt(80) for normal console with scrollbar 13 // use setWrapAt(80) for normal console with scrollbar
14 setWrap(prof.readNumEntry("Wrap", 0) ? 0 : 80); 14 setWrap(prof.readNumEntry("Wrap", 0) ? 0 : 80);
15 m_teWid->setMinimumSize(150, 70 ); 15 m_teWid->setMinimumSize(150, 70 );
16 m_script = 0; 16 m_script = 0;
17 parent->resize( m_teWid->calcSize(80, 24 ) ); 17 parent->resize( m_teWid->calcSize(80, 24 ) );
18 m_teEmu = new TEmuVt102(m_teWid ); 18 m_teEmu = new TEmuVt102(m_teWid );
19 19
20 connect(m_teEmu,SIGNAL(ImageSizeChanged(int, int) ), 20 connect(m_teEmu,SIGNAL(ImageSizeChanged(int,int) ),
21 this, SIGNAL(changeSize(int, int) ) ); 21 this, SIGNAL(changeSize(int,int) ) );
22 connect(m_teEmu, SIGNAL(sndBlock(const char*, int) ), 22 connect(m_teEmu, SIGNAL(sndBlock(const char*,int) ),
23 this, SLOT(recvEmulation(const char*, int) ) ); 23 this, SLOT(recvEmulation(const char*,int) ) );
24 m_teEmu->setConnect( true ); 24 m_teEmu->setConnect( true );
25 m_teEmu->setHistory( TRUE ); 25 m_teEmu->setHistory( TRUE );
26 load( prof ); 26 load( prof );
27 27
28 28
29 29
30} 30}
31TEmulation* EmulationHandler::emulation() { 31TEmulation* EmulationHandler::emulation() {
32 return m_teEmu; 32 return m_teEmu;
33} 33}
34EmulationHandler::~EmulationHandler() { 34EmulationHandler::~EmulationHandler() {
35 if (isRecording()) 35 if (isRecording())
36 clearScript(); 36 clearScript();
37 delete m_teEmu; 37 delete m_teEmu;
38 delete m_teWid; 38 delete m_teWid;
39} 39}
40 40
41void EmulationHandler::load( const Profile& prof) { 41void EmulationHandler::load( const Profile& prof) {
42 m_teWid->setVTFont( font( prof.readNumEntry("Font") ) ); 42 m_teWid->setVTFont( font( prof.readNumEntry("Font") ) );
43 int num = prof.readNumEntry("Color"); 43 int num = prof.readNumEntry("Color");
44 setColor( foreColor(num), backColor(num) ); 44 setColor( foreColor(num), backColor(num) );
45 m_teWid->setBackgroundColor(backColor(num) ); 45 m_teWid->setBackgroundColor(backColor(num) );
46 46
47 int term = prof.readNumEntry("Terminal", 0) ; 47 int term = prof.readNumEntry("Terminal", 0) ;
48 switch(term) { 48 switch(term) {
49 default: 49 default:
50 case Profile::VT102: 50 case Profile::VT102:
51 case Profile::VT100: 51 case Profile::VT100:
52 m_teEmu->setKeytrans("vt100.keytab"); 52 m_teEmu->setKeytrans("vt100.keytab");
53 break; 53 break;
54 case Profile::Linux: 54 case Profile::Linux:
55 m_teEmu->setKeytrans("linux.keytab"); 55 m_teEmu->setKeytrans("linux.keytab");
56 break; 56 break;
57 case Profile::XTerm: 57 case Profile::XTerm:
58 m_teEmu->setKeytrans("default.Keytab"); 58 m_teEmu->setKeytrans("default.Keytab");
59 break; 59 break;
60 } 60 }
61} 61}
62void EmulationHandler::recv( const QByteArray& ar) { 62void EmulationHandler::recv( const QByteArray& ar) {
63 m_teEmu->onRcvBlock(ar.data(), ar.count() ); 63 m_teEmu->onRcvBlock(ar.data(), ar.count() );
64} 64}
65void EmulationHandler::recvEmulation(const char* src, int len ) { 65void EmulationHandler::recvEmulation(const char* src, int len ) {
66 QByteArray ar(len); 66 QByteArray ar(len);
67 67
68 memcpy(ar.data(), src, sizeof(char) * len ); 68 memcpy(ar.data(), src, sizeof(char) * len );
69 if (isRecording()) 69 if (isRecording())
70 m_script->append(ar); 70 m_script->append(ar);
71 emit send(ar); 71 emit send(ar);
72} 72}
73QWidget* EmulationHandler::widget() { 73QWidget* EmulationHandler::widget() {
74 return m_teWid; 74 return m_teWid;
75} 75}
76/* 76/*
77 * allocate a new table of colors 77 * allocate a new table of colors
78 */ 78 */
79void EmulationHandler::setColor( const QColor& fore, const QColor& back ) { 79void EmulationHandler::setColor( const QColor& fore, const QColor& back ) {
80 ColorEntry table[TABLE_COLORS]; 80 ColorEntry table[TABLE_COLORS];
81 const ColorEntry *defaultCt = m_teWid->getdefaultColorTable(); 81 const ColorEntry *defaultCt = m_teWid->getdefaultColorTable();
82 82
83 for (int i = 0; i < TABLE_COLORS; i++ ) { 83 for (int i = 0; i < TABLE_COLORS; i++ ) {
84 if ( i == 0 || i == 10 ) { 84 if ( i == 0 || i == 10 ) {
85 table[i].color = fore; 85 table[i].color = fore;
86 }else if ( i == 1 || i == 11 ) { 86 }else if ( i == 1 || i == 11 ) {
87 table[i].color = back; 87 table[i].color = back;
88 table[i].transparent = 0; 88 table[i].transparent = 0;
89 }else { 89 }else {
90 table[i].color = defaultCt[i].color; 90 table[i].color = defaultCt[i].color;
91 } 91 }
92 } 92 }
93 m_teWid->setColorTable(table ); 93 m_teWid->setColorTable(table );
94 m_teWid->update(); 94 m_teWid->update();
95} 95}
96QFont EmulationHandler::font( int id ) { 96QFont EmulationHandler::font( int id ) {
97 QString name; 97 QString name;
98 int size = 0; 98 int size = 0;
99 switch(id ) { 99 switch(id ) {
100 default: // fall through 100 default: // fall through
101 case 0: 101 case 0:
102 name = QString::fromLatin1("Micro"); 102 name = QString::fromLatin1("Micro");
103 size = 4; 103 size = 4;
104 break; 104 break;
105 case 1: 105 case 1:
106 name = QString::fromLatin1("Fixed"); 106 name = QString::fromLatin1("Fixed");
107 size = 7; 107 size = 7;
108 break; 108 break;
109 case 2: 109 case 2:
110 name = QString::fromLatin1("Fixed"); 110 name = QString::fromLatin1("Fixed");
111 size = 12; 111 size = 12;
112 break; 112 break;
113 } 113 }
114 QFont font(name, size, QFont::Normal ); 114 QFont font(name, size, QFont::Normal );
115 font.setFixedPitch(TRUE ); 115 font.setFixedPitch(TRUE );
116 return font; 116 return font;
117} 117}
118QColor EmulationHandler::foreColor(int col) { 118QColor EmulationHandler::foreColor(int col) {
119 QColor co; 119 QColor co;
120 /* we need to switch it */ 120 /* we need to switch it */
121 switch( col ) { 121 switch( col ) {
122 default: 122 default:
123 case Profile::White: 123 case Profile::White:
124 /* color is black */ 124 /* color is black */
125 co = Qt::white; 125 co = Qt::white;
126 break; 126 break;
127 case Profile::Black: 127 case Profile::Black:
128 co = Qt::black; 128 co = Qt::black;
129 break; 129 break;
130 case Profile::Green: 130 case Profile::Green:
131 qWarning("Foreground green"); 131 qWarning("Foreground green");
132 co = Qt::green; 132 co = Qt::green;
133 break; 133 break;
134 case Profile::Orange: 134 case Profile::Orange:
135 qWarning("Foreground orange"); 135 qWarning("Foreground orange");
136 co.setRgb( 231, 184, 98 ); 136 co.setRgb( 231, 184, 98 );
137 break; 137 break;
138 } 138 }
139 139
140 return co; 140 return co;
141} 141}
142QColor EmulationHandler::backColor(int col ) { 142QColor EmulationHandler::backColor(int col ) {
143 QColor co; 143 QColor co;
144 /* we need to switch it */ 144 /* we need to switch it */
145 switch( col ) { 145 switch( col ) {
146 default: 146 default:
147 case Profile::White: 147 case Profile::White:
148 /* color is white */ 148 /* color is white */
149 co = Qt::black; 149 co = Qt::black;
150 break; 150 break;
151 case Profile::Black: 151 case Profile::Black:
152 co = Qt::white; 152 co = Qt::white;
153 break; 153 break;
154 case Profile::Green: 154 case Profile::Green:
155 qWarning("Background black"); 155 qWarning("Background black");
156 co = Qt::black; 156 co = Qt::black;
157 break; 157 break;
158 case Profile::Orange: 158 case Profile::Orange:
159 qWarning("Background black"); 159 qWarning("Background black");
160 co = Qt::black; 160 co = Qt::black;
161 break; 161 break;
162 } 162 }
163 163
164 return co; 164 return co;
165} 165}
166 166
167QPushButton* EmulationHandler::cornerButton() { 167QPushButton* EmulationHandler::cornerButton() {
168 return m_teWid->cornerButton(); 168 return m_teWid->cornerButton();
169} 169}
170 170
171 171
172Script *EmulationHandler::script() { 172Script *EmulationHandler::script() {
173 return m_script; 173 return m_script;
174} 174}
175 175
176bool EmulationHandler::isRecording() { 176bool EmulationHandler::isRecording() {
177 return (m_script != 0); 177 return (m_script != 0);
178} 178}
179 179
180void EmulationHandler::startRecording() { 180void EmulationHandler::startRecording() {
181 if (!isRecording()) 181 if (!isRecording())
182 m_script = new Script(); 182 m_script = new Script();
183} 183}
184 184
185void EmulationHandler::clearScript() { 185void EmulationHandler::clearScript() {
186 if (isRecording()) { 186 if (isRecording()) {
187 delete m_script; 187 delete m_script;
188 m_script = 0; 188 m_script = 0;
189 } 189 }
190} 190}
191 191
192void EmulationHandler::runScript(const Script *script) { 192void EmulationHandler::runScript(const Script *script) {
193 emit send(script->script()); 193 emit send(script->script());
194} 194}
195 195
196void EmulationHandler::copy() { 196void EmulationHandler::copy() {
197 m_teWid->emitSelection(); 197 m_teWid->emitSelection();
198} 198}
199void EmulationHandler::paste() { 199void EmulationHandler::paste() {
200 m_teWid->pasteClipboard(); 200 m_teWid->pasteClipboard();
201} 201}
202 202
203void EmulationHandler::setWrap(int columns) { 203void EmulationHandler::setWrap(int columns) {
204 m_teWid->setWrapAt(columns); 204 m_teWid->setWrapAt(columns);
205} 205}
206 206
diff --git a/noncore/apps/opie-console/emulation_layer.cpp b/noncore/apps/opie-console/emulation_layer.cpp
index 2bef801..fd30ad7 100644
--- a/noncore/apps/opie-console/emulation_layer.cpp
+++ b/noncore/apps/opie-console/emulation_layer.cpp
@@ -1,371 +1,371 @@
1/* -------------------------------------------------------------------------- */ 1/* -------------------------------------------------------------------------- */
2/* */ 2/* */
3/* [emulation_layer.cpp] Terminal Emulation Decoder */ 3/* [emulation_layer.cpp] Terminal Emulation Decoder */
4/* */ 4/* */
5/* -------------------------------------------------------------------------- */ 5/* -------------------------------------------------------------------------- */
6/* */ 6/* */
7/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */ 7/* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */
8/* */ 8/* */
9/* This file is part of Konsole - an X terminal for KDE */ 9/* This file is part of Konsole - an X terminal for KDE */
10/* */ 10/* */
11/* -------------------------------------------------------------------------- */ 11/* -------------------------------------------------------------------------- */
12 /* */ 12 /* */
13/* Ported Konsole to Qt/Embedded */ 13/* Ported Konsole to Qt/Embedded */
14 /* */ 14 /* */
15/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ 15/* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */
16 /* */ 16 /* */
17/* -------------------------------------------------------------------------- */ 17/* -------------------------------------------------------------------------- */
18 /* */ 18 /* */
19/* Modified to suit opie-console */ 19/* Modified to suit opie-console */
20 /* */ 20 /* */
21/* Copyright (C) 2002 by opie developers <opie@handhelds.org> */ 21/* Copyright (C) 2002 by opie developers <opie@handhelds.org> */
22 /* */ 22 /* */
23/* -------------------------------------------------------------------------- */ 23/* -------------------------------------------------------------------------- */
24 24
25/*! \class EmulationLayer 25/*! \class EmulationLayer
26 26
27 \brief Mediator between Widget and Screen. 27 \brief Mediator between Widget and Screen.
28 28
29 This class is responsible to scan the escapes sequences of the terminal 29 This class is responsible to scan the escapes sequences of the terminal
30 emulation and to map it to their corresponding semantic complements. 30 emulation and to map it to their corresponding semantic complements.
31 Thus this module knows mainly about decoding escapes sequences and 31 Thus this module knows mainly about decoding escapes sequences and
32 is a stateless device w.r.t. the semantics. 32 is a stateless device w.r.t. the semantics.
33 33
34 It is also responsible to refresh the Widget by certain rules. 34 It is also responsible to refresh the Widget by certain rules.
35 35
36 \sa Widget \sa Screen 36 \sa Widget \sa Screen
37 37
38 \par A note on refreshing 38 \par A note on refreshing
39 39
40 Although the modifications to the current screen image could immediately 40 Although the modifications to the current screen image could immediately
41 be propagated via `Widget' to the graphical surface, we have chosen 41 be propagated via `Widget' to the graphical surface, we have chosen
42 another way here. 42 another way here.
43 43
44 The reason for doing so is twofold. 44 The reason for doing so is twofold.
45 45
46 First, experiments show that directly displaying the operation results 46 First, experiments show that directly displaying the operation results
47 in slowing down the overall performance of emulations. Displaying 47 in slowing down the overall performance of emulations. Displaying
48 individual characters using X11 creates a lot of overhead. 48 individual characters using X11 creates a lot of overhead.
49 49
50 Second, by using the following refreshing method, the screen operations 50 Second, by using the following refreshing method, the screen operations
51 can be completely separated from the displaying. This greatly simplifies 51 can be completely separated from the displaying. This greatly simplifies
52 the programmer's task of coding and maintaining the screen operations, 52 the programmer's task of coding and maintaining the screen operations,
53 since one need not worry about differential modifications on the 53 since one need not worry about differential modifications on the
54 display affecting the operation of concern. 54 display affecting the operation of concern.
55 55
56 We use a refreshing algorithm here that has been adoped from rxvt/kvt. 56 We use a refreshing algorithm here that has been adoped from rxvt/kvt.
57 57
58 By this, refreshing is driven by a timer, which is (re)started whenever 58 By this, refreshing is driven by a timer, which is (re)started whenever
59 a new bunch of data to be interpreted by the emulation arives at `onRcvBlock'. 59 a new bunch of data to be interpreted by the emulation arives at `onRcvBlock'.
60 As soon as no more data arrive for `BULK_TIMEOUT' milliseconds, we trigger 60 As soon as no more data arrive for `BULK_TIMEOUT' milliseconds, we trigger
61 refresh. This rule suits both bulk display operation as done by curses as 61 refresh. This rule suits both bulk display operation as done by curses as
62 well as individual characters typed. 62 well as individual characters typed.
63 (BULK_TIMEOUT < 1000 / max characters received from keyboard per second). 63 (BULK_TIMEOUT < 1000 / max characters received from keyboard per second).
64 64
65 Additionally, we trigger refreshing by newlines comming in to make visual 65 Additionally, we trigger refreshing by newlines comming in to make visual
66 snapshots of lists as produced by `cat', `ls' and likely programs, thereby 66 snapshots of lists as produced by `cat', `ls' and likely programs, thereby
67 producing the illusion of a permanent and immediate display operation. 67 producing the illusion of a permanent and immediate display operation.
68 68
69 As a sort of catch-all needed for cases where none of the above 69 As a sort of catch-all needed for cases where none of the above
70 conditions catch, the screen refresh is also triggered by a count 70 conditions catch, the screen refresh is also triggered by a count
71 of incoming bulks (`bulk_incnt'). 71 of incoming bulks (`bulk_incnt').
72*/ 72*/
73 73
74/* FIXME 74/* FIXME
75 - evtl. the bulk operations could be made more transparent. 75 - evtl. the bulk operations could be made more transparent.
76*/ 76*/
77 77
78#include "emulation_layer.h" 78#include "emulation_layer.h"
79#include <stdio.h> 79#include <stdio.h>
80#include <stdlib.h> 80#include <stdlib.h>
81#include <unistd.h> 81#include <unistd.h>
82 82
83 83
84/* ------------------------------------------------------------------------- */ 84/* ------------------------------------------------------------------------- */
85/* */ 85/* */
86/* EmulationLayer */ 86/* EmulationLayer */
87/* */ 87/* */
88/* ------------------------------------------------------------------------- */ 88/* ------------------------------------------------------------------------- */
89 89
90#define CNTL(c) ((c)-'@') 90#define CNTL(c) ((c)-'@')
91 91
92/*! 92/*!
93*/ 93*/
94 94
95EmulationLayer::EmulationLayer( WidgetLayer* gui ) 95EmulationLayer::EmulationLayer( WidgetLayer* gui )
96: decoder((QTextDecoder*)NULL) 96: decoder((QTextDecoder*)NULL)
97{ 97{
98 this->gui = gui; 98 this->gui = gui;
99 99
100 screen[0] = new Screen(gui->lines(),gui->columns()); 100 screen[0] = new Screen(gui->lines(),gui->columns());
101 screen[1] = new Screen(gui->lines(),gui->columns()); 101 screen[1] = new Screen(gui->lines(),gui->columns());
102 scr = screen[0]; 102 scr = screen[0];
103 103
104 bulk_nlcnt = 0; // reset bulk newline counter 104 bulk_nlcnt = 0; // reset bulk newline counter
105 bulk_incnt = 0; // reset bulk counter 105 bulk_incnt = 0; // reset bulk counter
106 connected = FALSE; 106 connected = FALSE;
107 107
108 QObject::connect(&bulk_timer, SIGNAL( timeout() ), this, SLOT( showBulk() ) ); 108 QObject::connect(&bulk_timer, SIGNAL( timeout() ), this, SLOT( showBulk() ) );
109 QObject::connect(gui,SIGNAL( imageSizeChanged( int, int ) ), 109 QObject::connect(gui,SIGNAL( imageSizeChanged(int,int) ),
110 this,SLOT( onImageSizeChange( int, int ) ) ); 110 this,SLOT( onImageSizeChange(int,int) ) );
111 QObject::connect(gui,SIGNAL( changedHistoryCursor( int ) ), 111 QObject::connect(gui,SIGNAL( changedHistoryCursor(int) ),
112 this,SLOT( historyCursorChange( int ) ) ); 112 this,SLOT( historyCursorChange(int) ) );
113 QObject::connect(gui,SIGNAL( keyPressed( QKeyEvent* ) ), 113 QObject::connect(gui,SIGNAL( keyPressed(QKeyEvent*) ),
114 this,SLOT( onKeyPress( QKeyEvent* ) ) ); 114 this,SLOT( onKeyPress(QKeyEvent*) ) );
115 QObject::connect(gui,SIGNAL( selectionBegin( const int, const int) ), 115 QObject::connect(gui,SIGNAL( selectionBegin(const int,const int) ),
116 this,SLOT( onSelectionBegin( const int, const int ) ) ); 116 this,SLOT( onSelectionBegin(const int,const int) ) );
117 QObject::connect(gui,SIGNAL( selectionExtended( const int, const int ) ), 117 QObject::connect(gui,SIGNAL( selectionExtended(const int,const int) ),
118 this,SLOT( onSelectionExtend( const int,const int ) ) ); 118 this,SLOT( onSelectionExtend(const int,const int) ) );
119 QObject::connect(gui,SIGNAL( selectionEnd( const bool ) ), 119 QObject::connect(gui,SIGNAL( selectionEnd(const bool) ),
120 this,SLOT( setSelection( const bool ) ) ); 120 this,SLOT( setSelection(const bool) ) );
121 QObject::connect(gui,SIGNAL( selectionCleared() ), 121 QObject::connect(gui,SIGNAL( selectionCleared() ),
122 this,SLOT( clearSelection() ) ); 122 this,SLOT( clearSelection() ) );
123} 123}
124 124
125/*! 125/*!
126*/ 126*/
127 127
128EmulationLayer::~EmulationLayer() 128EmulationLayer::~EmulationLayer()
129{ 129{
130 delete screen[0]; 130 delete screen[0];
131 delete screen[1]; 131 delete screen[1];
132 bulk_timer.stop(); 132 bulk_timer.stop();
133} 133}
134 134
135/*! change between primary and alternate screen 135/*! change between primary and alternate screen
136*/ 136*/
137 137
138void EmulationLayer::setScreen(int n) 138void EmulationLayer::setScreen(int n)
139{ 139{
140 scr = screen[n&1]; 140 scr = screen[n&1];
141} 141}
142 142
143void EmulationLayer::setHistory(bool on) 143void EmulationLayer::setHistory(bool on)
144{ 144{
145 screen[0]->setScroll(on); 145 screen[0]->setScroll(on);
146 if (!connected) return; 146 if (!connected) return;
147 showBulk(); 147 showBulk();
148} 148}
149 149
150bool EmulationLayer::history() 150bool EmulationLayer::history()
151{ 151{
152 return screen[0]->hasScroll(); 152 return screen[0]->hasScroll();
153} 153}
154 154
155void EmulationLayer::setCodec(int c) 155void EmulationLayer::setCodec(int c)
156{ 156{
157 //FIXME: check whether we have to free codec 157 //FIXME: check whether we have to free codec
158 codec = c ? QTextCodec::codecForName("utf8") 158 codec = c ? QTextCodec::codecForName("utf8")
159 : QTextCodec::codecForLocale(); 159 : QTextCodec::codecForLocale();
160 if (decoder) delete decoder; 160 if (decoder) delete decoder;
161 decoder = codec->makeDecoder(); 161 decoder = codec->makeDecoder();
162} 162}
163 163
164void EmulationLayer::setKeytrans(int no) 164void EmulationLayer::setKeytrans(int no)
165{ 165{
166 keytrans = KeyTrans::find(no); 166 keytrans = KeyTrans::find(no);
167} 167}
168 168
169void EmulationLayer::setKeytrans(const char * no) 169void EmulationLayer::setKeytrans(const char * no)
170{ 170{
171 keytrans = KeyTrans::find(no); 171 keytrans = KeyTrans::find(no);
172} 172}
173 173
174// Interpreting Codes --------------------------------------------------------- 174// Interpreting Codes ---------------------------------------------------------
175 175
176/* 176/*
177 This section deals with decoding the incoming character stream. 177 This section deals with decoding the incoming character stream.
178 Decoding means here, that the stream is first seperated into `tokens' 178 Decoding means here, that the stream is first seperated into `tokens'
179 which are then mapped to a `meaning' provided as operations by the 179 which are then mapped to a `meaning' provided as operations by the
180 `Screen' class. 180 `Screen' class.
181*/ 181*/
182 182
183/*! 183/*!
184*/ 184*/
185 185
186void EmulationLayer::onRcvChar(int c) 186void EmulationLayer::onRcvChar(int c)
187// process application unicode input to terminal 187// process application unicode input to terminal
188// this is a trivial scanner 188// this is a trivial scanner
189{ 189{
190 c &= 0xff; 190 c &= 0xff;
191 switch (c) 191 switch (c)
192 { 192 {
193 case '\b' : scr->BackSpace(); break; 193 case '\b' : scr->BackSpace(); break;
194 case '\t' : scr->Tabulate(); break; 194 case '\t' : scr->Tabulate(); break;
195 case '\n' : scr->NewLine(); break; 195 case '\n' : scr->NewLine(); break;
196 case '\r' : scr->Return(); break; 196 case '\r' : scr->Return(); break;
197 case 0x07 : gui->bell(); break; 197 case 0x07 : gui->bell(); break;
198 default : scr->ShowCharacter(c); break; 198 default : scr->ShowCharacter(c); break;
199 }; 199 };
200} 200}
201 201
202/* ------------------------------------------------------------------------- */ 202/* ------------------------------------------------------------------------- */
203/* */ 203/* */
204/* Keyboard Handling */ 204/* Keyboard Handling */
205/* */ 205/* */
206/* ------------------------------------------------------------------------- */ 206/* ------------------------------------------------------------------------- */
207 207
208/*! 208/*!
209*/ 209*/
210 210
211void EmulationLayer::onKeyPress( QKeyEvent* ev ) 211void EmulationLayer::onKeyPress( QKeyEvent* ev )
212{ 212{
213 if (!connected) return; // someone else gets the keys 213 if (!connected) return; // someone else gets the keys
214 if (scr->getHistCursor() != scr->getHistLines()); 214 if (scr->getHistCursor() != scr->getHistLines());
215 scr->setHistCursor(scr->getHistLines()); 215 scr->setHistCursor(scr->getHistLines());
216 if (!ev->text().isEmpty()) 216 if (!ev->text().isEmpty())
217 { // A block of text 217 { // A block of text
218 // Note that the text is proper unicode. 218 // Note that the text is proper unicode.
219 // We should do a conversion here, but since this 219 // We should do a conversion here, but since this
220 // routine will never be used, we simply emit plain ascii. 220 // routine will never be used, we simply emit plain ascii.
221 sendString( ev->text().ascii() ); //,ev->text().length()); 221 sendString( ev->text().ascii() ); //,ev->text().length());
222 } 222 }
223 else if (ev->ascii()>0) 223 else if (ev->ascii()>0)
224 { 224 {
225 QByteArray c = QByteArray( 1 ); 225 QByteArray c = QByteArray( 1 );
226 c.at( 0 ) = ev->ascii(); 226 c.at( 0 ) = ev->ascii();
227 // ibot: qbytearray is emited not char* 227 // ibot: qbytearray is emited not char*
228 228
229 emit sndBlock( (QByteArray) c ); 229 emit sndBlock( (QByteArray) c );
230 } 230 }
231} 231}
232 232
233// Unblocking, Byte to Unicode translation --------------------------------- -- 233// Unblocking, Byte to Unicode translation --------------------------------- --
234 234
235/* 235/*
236 We are doing code conversion from locale to unicode first. 236 We are doing code conversion from locale to unicode first.
237*/ 237*/
238 238
239void EmulationLayer::onRcvBlock(const QByteArray &s ) 239void EmulationLayer::onRcvBlock(const QByteArray &s )
240{ 240{
241 bulkStart(); 241 bulkStart();
242 bulk_incnt += 1; 242 bulk_incnt += 1;
243 for (int i = 0; i < s.size(); i++) 243 for (int i = 0; i < s.size(); i++)
244 { 244 {
245 //TODO: ibot: maybe decoding qbytearray to unicode in io_layer? 245 //TODO: ibot: maybe decoding qbytearray to unicode in io_layer?
246 QString result = decoder->toUnicode(&s[i],1); 246 QString result = decoder->toUnicode(&s[i],1);
247 int reslen = result.length(); 247 int reslen = result.length();
248 for (int j = 0; j < reslen; j++) 248 for (int j = 0; j < reslen; j++)
249 onRcvChar(result[j].unicode()); 249 onRcvChar(result[j].unicode());
250 if (s[i] == '\n') bulkNewline(); 250 if (s[i] == '\n') bulkNewline();
251 } 251 }
252 bulkEnd(); 252 bulkEnd();
253} 253}
254 254
255// Selection --------------------------------------------------------------- -- 255// Selection --------------------------------------------------------------- --
256 256
257void EmulationLayer::onSelectionBegin(const int x, const int y) { 257void EmulationLayer::onSelectionBegin(const int x, const int y) {
258 if (!connected) return; 258 if (!connected) return;
259 scr->setSelBeginXY(x,y); 259 scr->setSelBeginXY(x,y);
260 showBulk(); 260 showBulk();
261} 261}
262 262
263void EmulationLayer::onSelectionExtend(const int x, const int y) { 263void EmulationLayer::onSelectionExtend(const int x, const int y) {
264 if (!connected) return; 264 if (!connected) return;
265 scr->setSelExtentXY(x,y); 265 scr->setSelExtentXY(x,y);
266 showBulk(); 266 showBulk();
267} 267}
268 268
269void EmulationLayer::setSelection(const BOOL preserve_line_breaks) { 269void EmulationLayer::setSelection(const BOOL preserve_line_breaks) {
270 if (!connected) return; 270 if (!connected) return;
271 QString t = scr->getSelText(preserve_line_breaks); 271 QString t = scr->getSelText(preserve_line_breaks);
272 if (!t.isNull()) gui->setSelection(t); 272 if (!t.isNull()) gui->setSelection(t);
273} 273}
274 274
275void EmulationLayer::clearSelection() { 275void EmulationLayer::clearSelection() {
276 if (!connected) return; 276 if (!connected) return;
277 scr->clearSelection(); 277 scr->clearSelection();
278 showBulk(); 278 showBulk();
279} 279}
280 280
281// Refreshing -------------------------------------------------------------- -- 281// Refreshing -------------------------------------------------------------- --
282 282
283#define BULK_TIMEOUT 20 283#define BULK_TIMEOUT 20
284 284
285/*! 285/*!
286 called when \n comes in. Evtl. triggers showBulk at endBulk 286 called when \n comes in. Evtl. triggers showBulk at endBulk
287*/ 287*/
288 288
289void EmulationLayer::bulkNewline() 289void EmulationLayer::bulkNewline()
290{ 290{
291 bulk_nlcnt += 1; 291 bulk_nlcnt += 1;
292 bulk_incnt = 0; // reset bulk counter since `nl' rule applies 292 bulk_incnt = 0; // reset bulk counter since `nl' rule applies
293} 293}
294 294
295/*! 295/*!
296*/ 296*/
297 297
298void EmulationLayer::showBulk() 298void EmulationLayer::showBulk()
299{ 299{
300 bulk_nlcnt = 0; // reset bulk newline counter 300 bulk_nlcnt = 0; // reset bulk newline counter
301 bulk_incnt = 0; // reset bulk counter 301 bulk_incnt = 0; // reset bulk counter
302 if (connected) 302 if (connected)
303 { 303 {
304 QArray<Character> image = scr->getCookedImage(); // get the image 304 QArray<Character> image = scr->getCookedImage(); // get the image
305 gui->setImage(image, 305 gui->setImage(image,
306 scr->getLines(), 306 scr->getLines(),
307 scr->getColumns()); // actual refresh 307 scr->getColumns()); // actual refresh
308 delete image; 308 delete image;
309 //FIXME: check that we do not trigger other draw event here. 309 //FIXME: check that we do not trigger other draw event here.
310 gui->setScroll(scr->getHistCursor(),scr->getHistLines()); 310 gui->setScroll(scr->getHistCursor(),scr->getHistLines());
311 } 311 }
312} 312}
313 313
314void EmulationLayer::bulkStart() 314void EmulationLayer::bulkStart()
315{ 315{
316 if (bulk_timer.isActive()) bulk_timer.stop(); 316 if (bulk_timer.isActive()) bulk_timer.stop();
317} 317}
318 318
319void EmulationLayer::bulkEnd() 319void EmulationLayer::bulkEnd()
320{ 320{
321 if ( bulk_nlcnt > gui->lines() || bulk_incnt > 20 ) 321 if ( bulk_nlcnt > gui->lines() || bulk_incnt > 20 )
322 showBulk(); // resets bulk_??cnt to 0, too. 322 showBulk(); // resets bulk_??cnt to 0, too.
323 else 323 else
324 bulk_timer.start(BULK_TIMEOUT,TRUE); 324 bulk_timer.start(BULK_TIMEOUT,TRUE);
325} 325}
326 326
327void EmulationLayer::setConnect(bool c) 327void EmulationLayer::setConnect(bool c)
328{ 328{
329 connected = c; 329 connected = c;
330 if ( connected) 330 if ( connected)
331 { 331 {
332 onImageSizeChange(gui->lines(), gui->columns()); 332 onImageSizeChange(gui->lines(), gui->columns());
333 showBulk(); 333 showBulk();
334 } 334 }
335 else 335 else
336 { 336 {
337 scr->clearSelection(); 337 scr->clearSelection();
338 } 338 }
339} 339}
340 340
341// --------------------------------------------------------------------------- 341// ---------------------------------------------------------------------------
342 342
343/*! triggered by image size change of the Widget `gui'. 343/*! triggered by image size change of the Widget `gui'.
344 344
345 This event is simply propagated to the attached screens 345 This event is simply propagated to the attached screens
346 and to the related serial line. 346 and to the related serial line.
347*/ 347*/
348 348
349void EmulationLayer::onImageSizeChange(int lines, int columns) 349void EmulationLayer::onImageSizeChange(int lines, int columns)
350{ 350{
351 if (!connected) return; 351 if (!connected) return;
352 screen[0]->resizeImage(lines,columns); 352 screen[0]->resizeImage(lines,columns);
353 screen[1]->resizeImage(lines,columns); 353 screen[1]->resizeImage(lines,columns);
354 showBulk(); 354 showBulk();
355 emit ImageSizeChanged(lines,columns); // propagate event to serial line 355 emit ImageSizeChanged(lines,columns); // propagate event to serial line
356} 356}
357 357
358void EmulationLayer::onHistoryCursorChange(int cursor) 358void EmulationLayer::onHistoryCursorChange(int cursor)
359{ 359{
360 if (!connected) return; 360 if (!connected) return;
361 scr->setHistCursor(cursor); 361 scr->setHistCursor(cursor);
362 showBulk(); 362 showBulk();
363} 363}
364 364
365void EmulationLayer::setColumns(int columns) 365void EmulationLayer::setColumns(int columns)
366{ 366{
367 //FIXME: this goes strange ways. 367 //FIXME: this goes strange ways.
368 // Can we put this straight or explain it at least? 368 // Can we put this straight or explain it at least?
369 emit changeColumns(columns); 369 emit changeColumns(columns);
370} 370}
371 371
diff --git a/noncore/apps/opie-console/function_keyboard.cpp b/noncore/apps/opie-console/function_keyboard.cpp
index c232d89..eb32551 100644
--- a/noncore/apps/opie-console/function_keyboard.cpp
+++ b/noncore/apps/opie-console/function_keyboard.cpp
@@ -1,426 +1,426 @@
1#include "function_keyboard.h" 1#include "function_keyboard.h"
2 2
3#include <qlayout.h> 3#include <qlayout.h>
4#include <qlistbox.h> 4#include <qlistbox.h>
5#include <qlabel.h> 5#include <qlabel.h>
6#include <qdir.h> 6#include <qdir.h>
7 7
8#define DEFAULT_ROWS 2 8#define DEFAULT_ROWS 2
9#define DEFAULT_COLS 12 9#define DEFAULT_COLS 12
10 10
11/* FunctionKeyboard {{{1 */ 11/* FunctionKeyboard {{{1 */
12 12
13FunctionKeyboard::FunctionKeyboard(QWidget *parent) : 13FunctionKeyboard::FunctionKeyboard(QWidget *parent) :
14 QFrame(parent), numRows(DEFAULT_ROWS), numCols(DEFAULT_COLS), 14 QFrame(parent), numRows(DEFAULT_ROWS), numCols(DEFAULT_COLS),
15 pressedRow(0), pressedCol(0) { 15 pressedRow(0), pressedCol(0) {
16 16
17 setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed)); 17 setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed));
18 18
19 /* 19 /*
20 * all the saving/loading is now done in a profile. downside is that you cant modify 20 * all the saving/loading is now done in a profile. downside is that you cant modify
21 * the keyboard for all profiles, but must do it on a profile-basis 21 * the keyboard for all profiles, but must do it on a profile-basis
22 * 22 *
23 23
24 Config conf("opie-console-keys"); 24 Config conf("opie-console-keys");
25 conf.setGroup("keys"); 25 conf.setGroup("keys");
26 for (uint r = 0; r < numRows; r++) 26 for (uint r = 0; r < numRows; r++)
27 for (uint c = 0; c < numCols; c++) { 27 for (uint c = 0; c < numCols; c++) {
28 28
29 QString handle = "r" + QString::number(r) + "c" + QString::number(c); 29 QString handle = "r" + QString::number(r) + "c" + QString::number(c);
30 QStringList value_list = conf.readListEntry( handle, '|'); 30 QStringList value_list = conf.readListEntry( handle, '|');
31 31
32 if (value_list.isEmpty()) continue; 32 if (value_list.isEmpty()) continue;
33 33
34 keys.insert( 34 keys.insert(
35 35
36 handle, 36 handle,
37 FKey (value_list[0], value_list[1], value_list[2].toUShort(), value_list[3].toUShort()) 37 FKey (value_list[0], value_list[1], value_list[2].toUShort(), value_list[3].toUShort())
38 ); 38 );
39 } 39 }
40 //qWarning("loaded %d keys", keys.count()); 40 //qWarning("loaded %d keys", keys.count());
41 */ 41 */
42 if (keys.isEmpty()) loadDefaults(); 42 if (keys.isEmpty()) loadDefaults();
43 43
44 44
45 45
46} 46}
47 47
48FunctionKeyboard::~FunctionKeyboard() {} 48FunctionKeyboard::~FunctionKeyboard() {}
49 49
50void FunctionKeyboard::changeRows(int r) { 50void FunctionKeyboard::changeRows(int r) {
51 51
52 numRows = r; 52 numRows = r;
53 53
54 // have to do this so the whole thing gets redrawn 54 // have to do this so the whole thing gets redrawn
55 hide(); show(); 55 hide(); show();
56} 56}
57void FunctionKeyboard::changeCols(int c) { 57void FunctionKeyboard::changeCols(int c) {
58 58
59 numCols = c; 59 numCols = c;
60 keyWidth = (double)width()/numCols; // have to reset this thing too 60 keyWidth = (double)width()/numCols; // have to reset this thing too
61 repaint(false); 61 repaint(false);
62} 62}
63void FunctionKeyboard::load (const Profile& prof) { 63void FunctionKeyboard::load (const Profile& prof) {
64 64
65 keys.clear(); 65 keys.clear();
66 66
67 numRows = prof.readNumEntry("keb_rows", 2); 67 numRows = prof.readNumEntry("keb_rows", 2);
68 numCols = prof.readNumEntry("keb_cols", 10); 68 numCols = prof.readNumEntry("keb_cols", 10);
69 keyWidth = (double)width()/numCols; // have to reset this thing too 69 keyWidth = (double)width()/numCols; // have to reset this thing too
70 70
71 /* load all the keys to the keyboard */ 71 /* load all the keys to the keyboard */
72 for (ushort i = 0; i <= numRows - 1; i++) 72 for (ushort i = 0; i <= numRows - 1; i++)
73 for (ushort j = 0; j <= numCols - 1; j++) { 73 for (ushort j = 0; j <= numCols - 1; j++) {
74 74
75 QString h = "r" + QString::number(i) + "c" + QString::number(j); 75 QString h = "r" + QString::number(i) + "c" + QString::number(j);
76 QString values = prof.readEntry("keb_" + h); 76 QString values = prof.readEntry("keb_" + h);
77 77
78 if (!values.isEmpty()) { 78 if (!values.isEmpty()) {
79 79
80 QStringList l = QStringList::split(QChar('|'), values, TRUE); 80 QStringList l = QStringList::split(QChar('|'), values, TRUE);
81 keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt()); 81 keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt());
82 82
83 // load pixmap if used 83 // load pixmap if used
84 if (!l[1].isEmpty()) { 84 if (!l[1].isEmpty()) {
85 85
86 keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) ); 86 keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) );
87 } 87 }
88 } 88 }
89 } 89 }
90 90
91 if (keys.isEmpty()) loadDefaults(); 91 if (keys.isEmpty()) loadDefaults();
92 92
93 hide(); 93 hide();
94 show(); 94 show();
95 95
96} 96}
97 97
98void FunctionKeyboard::paintEvent(QPaintEvent *e) { 98void FunctionKeyboard::paintEvent(QPaintEvent *e) {
99 99
100 QPainter p(this); 100 QPainter p(this);
101 p.setClipRect(e->rect()); 101 p.setClipRect(e->rect());
102 p.fillRect(0, 0, width(), height(), QColor(255,255,255)); 102 p.fillRect(0, 0, width(), height(), QColor(255,255,255));
103 103
104 p.setPen(QColor(0,0,0)); 104 p.setPen(QColor(0,0,0));
105 105
106 /* those decimals do count! becomes short if use plain int */ 106 /* those decimals do count! becomes short if use plain int */
107 for (double i = 0; i <= width(); i += keyWidth) { 107 for (double i = 0; i <= width(); i += keyWidth) {
108 108
109 p.drawLine((int)i, 0, (int)i, height()); 109 p.drawLine((int)i, 0, (int)i, height());
110 } 110 }
111 111
112 // sometimes the last line doesnt get drawn 112 // sometimes the last line doesnt get drawn
113 p.drawLine(width() -1, 0, width() -1, height()); 113 p.drawLine(width() -1, 0, width() -1, height());
114 114
115 for (int i = 0; i <= height(); i += keyHeight) { 115 for (int i = 0; i <= height(); i += keyHeight) {
116 116
117 p.drawLine(0, i, width(), i); 117 p.drawLine(0, i, width(), i);
118 } 118 }
119 119
120 for (uint r = 0; r < numRows; r++) { 120 for (uint r = 0; r < numRows; r++) {
121 for (uint c = 0; c < numCols; c++) { 121 for (uint c = 0; c < numCols; c++) {
122 122
123 QString handle = "r" + QString::number(r) + "c" + QString::number(c); 123 QString handle = "r" + QString::number(r) + "c" + QString::number(c);
124 if (keys.contains(handle)) { 124 if (keys.contains(handle)) {
125 125
126 if (keys[handle].pixFile.isEmpty()) 126 if (keys[handle].pixFile.isEmpty())
127 p.drawText( c * keyWidth + 1, r * keyHeight + 1, 127 p.drawText( c * keyWidth + 1, r * keyHeight + 1,
128 keyWidth, keyHeight, 128 keyWidth, keyHeight,
129 Qt::AlignHCenter | Qt::AlignVCenter, 129 Qt::AlignHCenter | Qt::AlignVCenter,
130 keys[handle].label 130 keys[handle].label
131 ); 131 );
132 else { 132 else {
133 133
134 ushort centerX = (ushort)(c *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2; 134 ushort centerX = (ushort)(c *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2;
135 ushort centerY = r * keyHeight + (keyHeight - keys[handle].pix->height()) / 2; 135 ushort centerY = r * keyHeight + (keyHeight - keys[handle].pix->height()) / 2;
136 p.drawPixmap(centerX, centerY, *keys[handle].pix); 136 p.drawPixmap(centerX, centerY, *keys[handle].pix);
137 } 137 }
138 } 138 }
139 } 139 }
140 } 140 }
141} 141}
142 142
143void FunctionKeyboard::paintKey(uint row, uint col) { 143void FunctionKeyboard::paintKey(uint row, uint col) {
144 144
145 QPainter p(this); 145 QPainter p(this);
146 146
147 p.fillRect(QRect(QPoint(col * keyWidth + 1, row * keyHeight + 1), 147 p.fillRect(QRect(QPoint(col * keyWidth + 1, row * keyHeight + 1),
148 QPoint((col + 1) * keyWidth - 1, row * keyHeight + keyHeight- 1)), 148 QPoint((col + 1) * keyWidth - 1, row * keyHeight + keyHeight- 1)),
149 (pressedRow != -1 && pressedCol != -1 ) ? QColor(97,119,155) : QColor(255,255,255)); 149 (pressedRow != -1 && pressedCol != -1 ) ? QColor(97,119,155) : QColor(255,255,255));
150 150
151 QString handle ("r" + QString::number(row) + "c" + QString::number(col)); 151 QString handle ("r" + QString::number(row) + "c" + QString::number(col));
152 if (keys[handle].pixFile.isEmpty()) 152 if (keys[handle].pixFile.isEmpty())
153 p.drawText( 153 p.drawText(
154 col * keyWidth + 1, row * keyHeight + 1, 154 col * keyWidth + 1, row * keyHeight + 1,
155 keyWidth, keyHeight, 155 keyWidth, keyHeight,
156 Qt::AlignHCenter | Qt::AlignVCenter, 156 Qt::AlignHCenter | Qt::AlignVCenter,
157 keys[handle].label 157 keys[handle].label
158 ); 158 );
159 else { 159 else {
160 160
161 ushort centerX = (ushort)(col *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2; 161 ushort centerX = (ushort)(col *keyWidth) + (ushort)(keyWidth - keys[handle].pix->width()) / 2;
162 ushort centerY = row * keyHeight + (keyHeight - keys[handle].pix->height()) / 2; 162 ushort centerY = row * keyHeight + (keyHeight - keys[handle].pix->height()) / 2;
163 p.drawPixmap(centerX, centerY, *keys[handle].pix); 163 p.drawPixmap(centerX, centerY, *keys[handle].pix);
164 } 164 }
165 165
166 if (col == numCols - 1) { 166 if (col == numCols - 1) {
167 167
168 // sometimes it doesnt draw the last line 168 // sometimes it doesnt draw the last line
169 169
170 p.drawLine((col+1) * keyWidth -1, row * keyHeight, 170 p.drawLine((col+1) * keyWidth -1, row * keyHeight,
171 (col+1) * keyWidth -1, (row + 1) * keyHeight 171 (col+1) * keyWidth -1, (row + 1) * keyHeight
172 ); 172 );
173 } 173 }
174 174
175} 175}
176 176
177void FunctionKeyboard::mousePressEvent(QMouseEvent *e) { 177void FunctionKeyboard::mousePressEvent(QMouseEvent *e) {
178 178
179 pressedRow = e->y() / keyHeight; 179 pressedRow = e->y() / keyHeight;
180 pressedCol = (int) (e->x() / keyWidth); 180 pressedCol = (int) (e->x() / keyWidth);
181 181
182 paintKey(pressedRow, pressedCol); 182 paintKey(pressedRow, pressedCol);
183 183
184 // emit that sucker! 184 // emit that sucker!
185 FKey k = keys["r" + QString::number(pressedRow) + "c" + QString::number(pressedCol)]; 185 FKey k = keys["r" + QString::number(pressedRow) + "c" + QString::number(pressedCol)];
186 emit keyPressed(k, pressedRow, pressedCol, 1); 186 emit keyPressed(k, pressedRow, pressedCol, 1);
187 187
188} 188}
189 189
190void FunctionKeyboard::mouseReleaseEvent(QMouseEvent *) { 190void FunctionKeyboard::mouseReleaseEvent(QMouseEvent *) {
191 191
192 if (pressedRow != -1 && pressedRow != -1) { 192 if (pressedRow != -1 && pressedRow != -1) {
193 193
194 int row = pressedRow; pressedRow = -1; 194 int row = pressedRow; pressedRow = -1;
195 int col = pressedCol; pressedCol = -1; 195 int col = pressedCol; pressedCol = -1;
196 paintKey(row, col); 196 paintKey(row, col);
197 197
198 FKey k = keys["r" + QString::number(row) + "c" + QString::number(col)]; 198 FKey k = keys["r" + QString::number(row) + "c" + QString::number(col)];
199 emit keyPressed(k, row, col, 0); 199 emit keyPressed(k, row, col, 0);
200 } 200 }
201 201
202} 202}
203 203
204 204
205void FunctionKeyboard::resizeEvent(QResizeEvent*) { 205void FunctionKeyboard::resizeEvent(QResizeEvent*) {
206 206
207 /* set he default font height/width */ 207 /* set he default font height/width */
208 QFontMetrics fm=fontMetrics(); 208 QFontMetrics fm=fontMetrics();
209 keyHeight = fm.lineSpacing() + 2; 209 keyHeight = fm.lineSpacing() + 2;
210 keyWidth = (double)width()/numCols; 210 keyWidth = (double)width()/numCols;
211 211
212} 212}
213 213
214QSize FunctionKeyboard::sizeHint() const { 214QSize FunctionKeyboard::sizeHint() const {
215 215
216 return QSize(width(), keyHeight * numRows + 1); 216 return QSize(width(), keyHeight * numRows + 1);
217} 217}
218 218
219void FunctionKeyboard::loadDefaults() { 219void FunctionKeyboard::loadDefaults() {
220 220
221 numRows = DEFAULT_ROWS; 221 numRows = DEFAULT_ROWS;
222 numCols = DEFAULT_COLS; 222 numCols = DEFAULT_COLS;
223 keyWidth = (double)width()/numCols; // have to reset this thing too 223 keyWidth = (double)width()/numCols; // have to reset this thing too
224 224
225 keys.insert( "r0c0", FKey ("Enter", "enter", Qt::Key_Enter, 0)); 225 keys.insert( "r0c0", FKey ("Enter", "enter", Qt::Key_Enter, 0));
226 keys.insert( "r0c1", FKey ("Space", "space", Qt::Key_Space, Qt::Key_Space)); 226 keys.insert( "r0c1", FKey ("Space", "space", Qt::Key_Space, Qt::Key_Space));
227 keys.insert( "r0c2", FKey ("Tab", "tab", Qt::Key_Tab, 0)); 227 keys.insert( "r0c2", FKey ("Tab", "tab", Qt::Key_Tab, 0));
228 keys.insert( "r0c3", FKey ("Up", "up", Qt::Key_Up, 0)); 228 keys.insert( "r0c3", FKey ("Up", "up", Qt::Key_Up, 0));
229 keys.insert( "r0c4", FKey ("Down", "down", Qt::Key_Down, 0)); 229 keys.insert( "r0c4", FKey ("Down", "down", Qt::Key_Down, 0));
230 230
231 keys.insert( "r0c7", FKey ("Ho", 0, 4112, 0)); 231 keys.insert( "r0c7", FKey ("Ho", 0, 4112, 0));
232 keys.insert( "r0c8", FKey ("End", 0, 4113, 0)); 232 keys.insert( "r0c8", FKey ("End", 0, 4113, 0));
233 keys.insert( "r0c9", FKey ("Pu", 0, 4118, 0)); 233 keys.insert( "r0c9", FKey ("Pu", 0, 4118, 0));
234 keys.insert( "r0c10", FKey ("Pd", 0, 4119, 0)); 234 keys.insert( "r0c10", FKey ("Pd", 0, 4119, 0));
235 keys.insert( "r0c11", FKey ("Esc", 0, Qt::Key_Escape, 0xfff)); 235 keys.insert( "r0c11", FKey ("Esc", 0, Qt::Key_Escape, 0xfff));
236 236
237 keys.insert( "r1c0", FKey ("F1", 0, 4144, 0)); 237 keys.insert( "r1c0", FKey ("F1", 0, 4144, 0));
238 keys.insert( "r1c1", FKey ("F2", 0, 4145, 0)); 238 keys.insert( "r1c1", FKey ("F2", 0, 4145, 0));
239 keys.insert( "r1c2", FKey ("F3", 0, 4146, 0)); 239 keys.insert( "r1c2", FKey ("F3", 0, 4146, 0));
240 keys.insert( "r1c3", FKey ("F4", 0, 4147, 0)); 240 keys.insert( "r1c3", FKey ("F4", 0, 4147, 0));
241 keys.insert( "r1c4", FKey ("F5", 0, 4148, 0)); 241 keys.insert( "r1c4", FKey ("F5", 0, 4148, 0));
242 keys.insert( "r1c5", FKey ("F6", 0, 4149, 0)); 242 keys.insert( "r1c5", FKey ("F6", 0, 4149, 0));
243 keys.insert( "r1c6", FKey ("F7", 0, 4150, 0)); 243 keys.insert( "r1c6", FKey ("F7", 0, 4150, 0));
244 keys.insert( "r1c7", FKey ("F8", 0, 4151, 0)); 244 keys.insert( "r1c7", FKey ("F8", 0, 4151, 0));
245 keys.insert( "r1c8", FKey ("F9", 0, 4152, 0)); 245 keys.insert( "r1c8", FKey ("F9", 0, 4152, 0));
246 keys.insert( "r1c9", FKey ("F10", 0, 4153, 0)); 246 keys.insert( "r1c9", FKey ("F10", 0, 4153, 0));
247 keys.insert( "r1c10", FKey ("F11", 0, 4154, 0)); 247 keys.insert( "r1c10", FKey ("F11", 0, 4154, 0));
248 keys.insert( "r1c11", FKey ("F12", 0, 4155, 0)); 248 keys.insert( "r1c11", FKey ("F12", 0, 4155, 0));
249 249
250 250
251} 251}
252 252
253/* FunctionKeyboardConfig {{{1 */ 253/* FunctionKeyboardConfig {{{1 */
254 254
255FunctionKeyboardConfig::FunctionKeyboardConfig(const QString& name, QWidget* parent, const char* na ) 255FunctionKeyboardConfig::FunctionKeyboardConfig(const QString& name, QWidget* parent, const char* na )
256 : ProfileDialogKeyWidget(name, parent, na), 256 : ProfileDialogKeyWidget(name, parent, na),
257 selectedRow(0), selectedCol(0) 257 selectedRow(0), selectedCol(0)
258{ 258{
259 qWarning("FunctionKeyboardConfig"); 259 qWarning("FunctionKeyboardConfig");
260 260
261 261
262 kb = new FunctionKeyboard(this); 262 kb = new FunctionKeyboard(this);
263 connect (kb, SIGNAL(keyPressed(FKey, ushort, ushort, bool)), 263 connect (kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)),
264 this, SLOT(slotKeyPressed(FKey, ushort, ushort, bool))); 264 this, SLOT(slotKeyPressed(FKey,ushort,ushort,bool)));
265 265
266 QGroupBox *dimentions = new QGroupBox(2, Qt::Horizontal, tr("Dimensions"), this); 266 QGroupBox *dimentions = new QGroupBox(2, Qt::Horizontal, tr("Dimensions"), this);
267 QLabel *l = new QLabel("Rows", dimentions); 267 QLabel *l = new QLabel("Rows", dimentions);
268 m_rowBox = new QSpinBox(1, 15, 1, dimentions); 268 m_rowBox = new QSpinBox(1, 15, 1, dimentions);
269 connect (m_rowBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeRows(int))); 269 connect (m_rowBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeRows(int)));
270 l = new QLabel("Columns", dimentions); 270 l = new QLabel("Columns", dimentions);
271 m_colBox = new QSpinBox(1, 15, 1, dimentions); 271 m_colBox = new QSpinBox(1, 15, 1, dimentions);
272 connect (m_colBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeCols(int))); 272 connect (m_colBox, SIGNAL(valueChanged(int)), this, SLOT(slotChangeCols(int)));
273 273
274 QGroupBox *editKey = new QGroupBox(2, Qt::Horizontal, tr("Edit Key"), this); 274 QGroupBox *editKey = new QGroupBox(2, Qt::Horizontal, tr("Edit Key"), this);
275 l = new QLabel("Label", editKey); 275 l = new QLabel("Label", editKey);
276 m_labels = new QComboBox(true, editKey); 276 m_labels = new QComboBox(true, editKey);
277 m_labels->setInsertionPolicy(QComboBox::AtCurrent); 277 m_labels->setInsertionPolicy(QComboBox::AtCurrent);
278 m_labels->insertItem(""); 278 m_labels->insertItem("");
279 279
280 QStringList files = QDir( QPEApplication::qpeDir() + "pics/console/keys/", "*.png").entryList(); 280 QStringList files = QDir( QPEApplication::qpeDir() + "pics/console/keys/", "*.png").entryList();
281 281
282 for (uint i = 0; i < files.count(); i++) { 282 for (uint i = 0; i < files.count(); i++) {
283 283
284 m_labels->insertItem( Resource::loadPixmap("console/keys/" + files[i]), files[i]); 284 m_labels->insertItem( Resource::loadPixmap("console/keys/" + files[i]), files[i]);
285 } 285 }
286 connect (m_labels, SIGNAL(activated(int)), this, SLOT(slotChangeIcon(int))); 286 connect (m_labels, SIGNAL(activated(int)), this, SLOT(slotChangeIcon(int)));
287 connect (m_labels, SIGNAL(textChanged(const QString &)), this, SLOT(slotChangeLabelText(const QString&))); 287 connect (m_labels, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeLabelText(const QString&)));
288 288
289 l = new QLabel("Q Keycode", editKey); 289 l = new QLabel("Q Keycode", editKey);
290 m_qvalues = new QComboBox(true, editKey); 290 m_qvalues = new QComboBox(true, editKey);
291 m_qvalues->setInsertionPolicy(QComboBox::AtTop); 291 m_qvalues->setInsertionPolicy(QComboBox::AtTop);
292 m_qvalues->setDuplicatesEnabled(false); 292 m_qvalues->setDuplicatesEnabled(false);
293 m_qvalues->insertItem(""); 293 m_qvalues->insertItem("");
294 connect (m_qvalues, SIGNAL(textChanged(const QString &)), this, SLOT(slotChangeQCode(const QString&))); 294 connect (m_qvalues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeQCode(const QString&)));
295 295
296 l = new QLabel("Unicode Value", editKey); 296 l = new QLabel("Unicode Value", editKey);
297 m_uniValues = new QComboBox(true, editKey); 297 m_uniValues = new QComboBox(true, editKey);
298 m_uniValues->setInsertionPolicy(QComboBox::AtTop); 298 m_uniValues->setInsertionPolicy(QComboBox::AtTop);
299 m_uniValues->setDuplicatesEnabled(false); 299 m_uniValues->setDuplicatesEnabled(false);
300 m_uniValues->insertItem(""); 300 m_uniValues->insertItem("");
301 connect (m_uniValues, SIGNAL(textChanged(const QString &)), this, SLOT(slotChangeUnicode(const QString&))); 301 connect (m_uniValues, SIGNAL(textChanged(const QString&)), this, SLOT(slotChangeUnicode(const QString&)));
302 302
303 QVBoxLayout *root = new QVBoxLayout(this, 2); 303 QVBoxLayout *root = new QVBoxLayout(this, 2);
304 root->addWidget(kb); 304 root->addWidget(kb);
305 root->addWidget(dimentions); 305 root->addWidget(dimentions);
306 root->addWidget(editKey); 306 root->addWidget(editKey);
307} 307}
308FunctionKeyboardConfig::~FunctionKeyboardConfig() { 308FunctionKeyboardConfig::~FunctionKeyboardConfig() {
309 309
310} 310}
311void FunctionKeyboardConfig::load (const Profile& prof) { 311void FunctionKeyboardConfig::load (const Profile& prof) {
312 312
313 kb->keys.clear(); 313 kb->keys.clear();
314 kb->loadDefaults(); 314 kb->loadDefaults();
315 315
316 m_rowBox->setValue(prof.readNumEntry("keb_rows", 2)); 316 m_rowBox->setValue(prof.readNumEntry("keb_rows", 2));
317 m_colBox->setValue(prof.readNumEntry("keb_cols", 10)); 317 m_colBox->setValue(prof.readNumEntry("keb_cols", 10));
318 318
319 /* load all the keys to the keyboard */ 319 /* load all the keys to the keyboard */
320 for (int i = 0; i <= m_rowBox->value() -1; i++) 320 for (int i = 0; i <= m_rowBox->value() -1; i++)
321 for (int j = 0; j <= m_colBox->value() -1; j++) { 321 for (int j = 0; j <= m_colBox->value() -1; j++) {
322 322
323 QString h = "r" + QString::number(i) + "c" + QString::number(j); 323 QString h = "r" + QString::number(i) + "c" + QString::number(j);
324 QString values = prof.readEntry("keb_" + h); 324 QString values = prof.readEntry("keb_" + h);
325 325
326 if (!values.isEmpty()) { 326 if (!values.isEmpty()) {
327 327
328 QStringList l = QStringList::split(QChar('|'), values, TRUE); 328 QStringList l = QStringList::split(QChar('|'), values, TRUE);
329 kb->keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt()); 329 kb->keys[h] = FKey(l[0], l[1], l[2].toInt(), l[3].toInt());
330 330
331 // load pixmap if used 331 // load pixmap if used
332 if (!l[1].isEmpty()) { 332 if (!l[1].isEmpty()) {
333 333
334 kb->keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) ); 334 kb->keys[h].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + l[1] ) );
335 } 335 }
336 } 336 }
337 } 337 }
338 338
339} 339}
340void FunctionKeyboardConfig::save (Profile& prof) { 340void FunctionKeyboardConfig::save (Profile& prof) {
341 341
342 prof.writeEntry("keb_rows", m_rowBox->value()); 342 prof.writeEntry("keb_rows", m_rowBox->value());
343 prof.writeEntry("keb_cols", m_colBox->value()); 343 prof.writeEntry("keb_cols", m_colBox->value());
344 344
345 QMap<QString, FKey>::Iterator it; 345 QMap<QString, FKey>::Iterator it;
346 for ( it = kb->keys.begin(); it != kb->keys.end(); it++) { 346 for ( it = kb->keys.begin(); it != kb->keys.end(); it++) {
347 347
348 FKey k = it.data(); 348 FKey k = it.data();
349 QString entry = k.label + "|" 349 QString entry = k.label + "|"
350 + k.pixFile + "|" 350 + k.pixFile + "|"
351 + QString::number(k.qcode) + "|" 351 + QString::number(k.qcode) + "|"
352 + QString::number(k.unicode); 352 + QString::number(k.unicode);
353 353
354 prof.writeEntry("keb_" + it.key(), entry); 354 prof.writeEntry("keb_" + it.key(), entry);
355 355
356 } 356 }
357 357
358} 358}
359void FunctionKeyboardConfig::slotChangeRows(int r) { 359void FunctionKeyboardConfig::slotChangeRows(int r) {
360 360
361 kb->changeRows(r); 361 kb->changeRows(r);
362 362
363} 363}
364void FunctionKeyboardConfig::slotChangeCols(int c) { 364void FunctionKeyboardConfig::slotChangeCols(int c) {
365 365
366 kb->changeCols(c); 366 kb->changeCols(c);
367} 367}
368void FunctionKeyboardConfig::slotKeyPressed(FKey k, ushort r, ushort c, bool pressed) { 368void FunctionKeyboardConfig::slotKeyPressed(FKey k, ushort r, ushort c, bool pressed) {
369 369
370 if (!pressed) return; 370 if (!pressed) return;
371 371
372 selectedHandle = "r" + QString::number(r) + 372 selectedHandle = "r" + QString::number(r) +
373 "c" + QString::number(c); 373 "c" + QString::number(c);
374 selectedRow = r; 374 selectedRow = r;
375 selectedCol = c; 375 selectedCol = c;
376 376
377 if (k.pixFile.isEmpty()) { 377 if (k.pixFile.isEmpty()) {
378 378
379 m_labels->setEditable(true); 379 m_labels->setEditable(true);
380 m_labels->setCurrentItem(0); 380 m_labels->setCurrentItem(0);
381 m_labels->changeItem(k.label, 0); 381 m_labels->changeItem(k.label, 0);
382 382
383 } else { 383 } else {
384 384
385 // any better way to select the pixmap? 385 // any better way to select the pixmap?
386 m_labels->setCurrentItem((m_labels->listBox())->index((m_labels->listBox())->findItem(kb->keys[selectedHandle].pixFile))); 386 m_labels->setCurrentItem((m_labels->listBox())->index((m_labels->listBox())->findItem(kb->keys[selectedHandle].pixFile)));
387 m_labels->setEditable(false); 387 m_labels->setEditable(false);
388 } 388 }
389 m_qvalues->changeItem(QString::number(k.qcode), 0); 389 m_qvalues->changeItem(QString::number(k.qcode), 0);
390 m_uniValues->changeItem(QString::number(k.unicode), 0); 390 m_uniValues->changeItem(QString::number(k.unicode), 0);
391} 391}
392void FunctionKeyboardConfig::slotChangeIcon(int index) { 392void FunctionKeyboardConfig::slotChangeIcon(int index) {
393 393
394 if (index == 0) { 394 if (index == 0) {
395 395
396 // is text 396 // is text
397 m_labels->setEditable(true); 397 m_labels->setEditable(true);
398 // why tf does the text get erased unless i do this? 398 // why tf does the text get erased unless i do this?
399 m_labels->changeItem(m_labels->text(0), 0); 399 m_labels->changeItem(m_labels->text(0), 0);
400 400
401 kb->keys[selectedHandle].pixFile = ""; 401 kb->keys[selectedHandle].pixFile = "";
402 delete kb->keys[selectedHandle].pix; 402 delete kb->keys[selectedHandle].pix;
403 403
404 } else { 404 } else {
405 405
406 // is a pixmap 406 // is a pixmap
407 m_labels->setEditable(false); 407 m_labels->setEditable(false);
408 kb->keys[selectedHandle].pixFile = m_labels->currentText(); 408 kb->keys[selectedHandle].pixFile = m_labels->currentText();
409 kb->keys[selectedHandle].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + m_labels->currentText() ) ); 409 kb->keys[selectedHandle].pix = new QPixmap( Resource::loadPixmap( "console/keys/" + m_labels->currentText() ) );
410 } 410 }
411 kb->paintKey(selectedRow, selectedCol); 411 kb->paintKey(selectedRow, selectedCol);
412} 412}
413void FunctionKeyboardConfig::slotChangeLabelText(const QString &label) { 413void FunctionKeyboardConfig::slotChangeLabelText(const QString &label) {
414 414
415 kb->keys[selectedHandle].label = label; 415 kb->keys[selectedHandle].label = label;
416 416
417 kb->paintKey(selectedRow, selectedCol); 417 kb->paintKey(selectedRow, selectedCol);
418} 418}
419void FunctionKeyboardConfig::slotChangeQCode(const QString& qcode) { 419void FunctionKeyboardConfig::slotChangeQCode(const QString& qcode) {
420 420
421 kb->keys[selectedHandle].qcode = qcode.toUInt(); 421 kb->keys[selectedHandle].qcode = qcode.toUInt();
422} 422}
423void FunctionKeyboardConfig::slotChangeUnicode(const QString& uni) { 423void FunctionKeyboardConfig::slotChangeUnicode(const QString& uni) {
424 424
425 kb->keys[selectedHandle].unicode = uni.toUInt(); 425 kb->keys[selectedHandle].unicode = uni.toUInt();
426} 426}
diff --git a/noncore/apps/opie-console/io_bt.cpp b/noncore/apps/opie-console/io_bt.cpp
index 37bf797..1a8c979 100644
--- a/noncore/apps/opie-console/io_bt.cpp
+++ b/noncore/apps/opie-console/io_bt.cpp
@@ -1,92 +1,92 @@
1 1
2#include "io_bt.h" 2#include "io_bt.h"
3 3
4IOBt::IOBt( const Profile &config ) : IOSerial( config ) { 4IOBt::IOBt( const Profile &config ) : IOSerial( config ) {
5 m_attach = 0; 5 m_attach = 0;
6} 6}
7 7
8 8
9IOBt::~IOBt() { 9IOBt::~IOBt() {
10 if ( m_attach ) { 10 if ( m_attach ) {
11 delete m_attach; 11 delete m_attach;
12 } 12 }
13} 13}
14 14
15 15
16void IOBt::close() { 16void IOBt::close() {
17 17
18 IOSerial::close(); 18 IOSerial::close();
19 // still need error handling 19 // still need error handling
20 if ( m_attach ) { 20 if ( m_attach ) {
21 delete m_attach; 21 delete m_attach;
22 m_attach = 0; 22 m_attach = 0;
23 } 23 }
24} 24}
25 25
26bool IOBt::open() { 26bool IOBt::open() {
27 bool ret = false; 27 bool ret = false;
28 28
29 // only set up bt stuff if mac address was set, otherwise use the device set 29 // only set up bt stuff if mac address was set, otherwise use the device set
30 if ( !m_mac.isEmpty() ) { 30 if ( !m_mac.isEmpty() ) {
31 31
32 // now it should also be checked, if there is a connection to the device with that mac allready 32 // now it should also be checked, if there is a connection to the device with that mac allready
33 // hciattach here 33 // hciattach here
34 m_attach = new OProcess(); 34 m_attach = new OProcess();
35 *m_attach << "hciattach /dev/ttyS2 any 57600"; 35 *m_attach << "hciattach /dev/ttyS2 any 57600";
36 36
37 // then start hcid, then rcfomm handling (m_mac) 37 // then start hcid, then rcfomm handling (m_mac)
38 38
39 connect( m_attach, SIGNAL( processExited( OProcess* ) ), 39 connect( m_attach, SIGNAL( processExited(OProcess*) ),
40 this, SLOT( slotExited( OProcess* ) ) ); 40 this, SLOT( slotExited(OProcess*) ) );
41 41
42 if ( m_attach->start() ) { 42 if ( m_attach->start() ) {
43 ret = IOSerial::open(); 43 ret = IOSerial::open();
44 } else { 44 } else {
45 qWarning("could not attach to device"); 45 qWarning("could not attach to device");
46 delete m_attach; 46 delete m_attach;
47 m_attach = 0; 47 m_attach = 0;
48 } 48 }
49 } else { 49 } else {
50 // directly to the normal serial 50 // directly to the normal serial
51 // TODO: look first if the connection really exists. ( is set up ) 51 // TODO: look first if the connection really exists. ( is set up )
52 52
53 ret =IOSerial::open(); 53 ret =IOSerial::open();
54 } 54 }
55 return ret; 55 return ret;
56} 56}
57 57
58void IOBt::reload( const Profile &config ) { 58void IOBt::reload( const Profile &config ) {
59 m_device = config.readEntry("Device", BT_DEFAULT_DEVICE); 59 m_device = config.readEntry("Device", BT_DEFAULT_DEVICE);
60 m_mac = config.readEntry("Mac", BT_DEFAULT_MAC); 60 m_mac = config.readEntry("Mac", BT_DEFAULT_MAC);
61 m_baud = config.readNumEntry("Baud", BT_DEFAULT_BAUD); 61 m_baud = config.readNumEntry("Baud", BT_DEFAULT_BAUD);
62 m_parity = config.readNumEntry("Parity", BT_DEFAULT_PARITY); 62 m_parity = config.readNumEntry("Parity", BT_DEFAULT_PARITY);
63 m_dbits = config.readNumEntry("DataBits", BT_DEFAULT_DBITS); 63 m_dbits = config.readNumEntry("DataBits", BT_DEFAULT_DBITS);
64 m_sbits = config.readNumEntry("StopBits", BT_DEFAULT_SBITS); 64 m_sbits = config.readNumEntry("StopBits", BT_DEFAULT_SBITS);
65 m_flow = config.readNumEntry("Flow", BT_DEFAULT_FLOW); 65 m_flow = config.readNumEntry("Flow", BT_DEFAULT_FLOW);
66} 66}
67 67
68 68
69QString IOBt::identifier() const { 69QString IOBt::identifier() const {
70 return "bluetooth"; 70 return "bluetooth";
71} 71}
72 72
73QString IOBt::name() const { 73QString IOBt::name() const {
74 return "BLuetooth IO Layer"; 74 return "BLuetooth IO Layer";
75} 75}
76 76
77void IOBt::slotExited( OProcess* proc ){ 77void IOBt::slotExited( OProcess* proc ){
78 close(); 78 close();
79 delete proc; 79 delete proc;
80} 80}
81 81
82QBitArray IOBt::supports() const { 82QBitArray IOBt::supports() const {
83 return QBitArray( 3 ); 83 return QBitArray( 3 );
84} 84}
85 85
86bool IOBt::isConnected() { 86bool IOBt::isConnected() {
87 return false; 87 return false;
88} 88}
89 89
90void IOBt::send(const QByteArray &data) { 90void IOBt::send(const QByteArray &data) {
91 qDebug( "Please overload me..." ); 91 qDebug( "Please overload me..." );
92} 92}
diff --git a/noncore/apps/opie-console/io_irda.cpp b/noncore/apps/opie-console/io_irda.cpp
index e360fb4..b281b7d 100644
--- a/noncore/apps/opie-console/io_irda.cpp
+++ b/noncore/apps/opie-console/io_irda.cpp
@@ -1,77 +1,77 @@
1 1
2#include "io_irda.h" 2#include "io_irda.h"
3 3
4IOIrda::IOIrda( const Profile &config ) : IOSerial( config ) { 4IOIrda::IOIrda( const Profile &config ) : IOSerial( config ) {
5 m_attach = 0; 5 m_attach = 0;
6} 6}
7 7
8 8
9IOIrda::~IOIrda() { 9IOIrda::~IOIrda() {
10 if ( m_attach ) { 10 if ( m_attach ) {
11 delete m_attach; 11 delete m_attach;
12 } 12 }
13} 13}
14 14
15 15
16void IOIrda::close() { 16void IOIrda::close() {
17 17
18 IOSerial::close(); 18 IOSerial::close();
19 // still need error handling 19 // still need error handling
20 delete m_attach; 20 delete m_attach;
21} 21}
22 22
23bool IOIrda::open() { 23bool IOIrda::open() {
24 bool ret; 24 bool ret;
25 25
26 // irdaattach here 26 // irdaattach here
27 m_attach = new OProcess(); 27 m_attach = new OProcess();
28 *m_attach << "irattach /dev/ttyS2 -s"; 28 *m_attach << "irattach /dev/ttyS2 -s";
29 29
30 connect( m_attach, SIGNAL( processExited( OProcess* ) ), 30 connect( m_attach, SIGNAL( processExited(OProcess*) ),
31 this, SLOT( slotExited( OProcess* ) ) ); 31 this, SLOT( slotExited(OProcess*) ) );
32 32
33 if ( m_attach->start() ) { 33 if ( m_attach->start() ) {
34 ret= IOSerial::open(); 34 ret= IOSerial::open();
35 } else { 35 } else {
36 // emit error!!! 36 // emit error!!!
37 qWarning("could not attach to device"); 37 qWarning("could not attach to device");
38 delete m_attach; 38 delete m_attach;
39 m_attach = 0l; 39 m_attach = 0l;
40 } 40 }
41 return ret; 41 return ret;
42} 42}
43 43
44void IOIrda::reload( const Profile &config ) { 44void IOIrda::reload( const Profile &config ) {
45 m_device = config.readEntry("Device", IRDA_DEFAULT_DEVICE); 45 m_device = config.readEntry("Device", IRDA_DEFAULT_DEVICE);
46 m_baud = config.readNumEntry("Baud", IRDA_DEFAULT_BAUD); 46 m_baud = config.readNumEntry("Baud", IRDA_DEFAULT_BAUD);
47 m_parity = config.readNumEntry("Parity", IRDA_DEFAULT_PARITY); 47 m_parity = config.readNumEntry("Parity", IRDA_DEFAULT_PARITY);
48 m_dbits = config.readNumEntry("DataBits", IRDA_DEFAULT_DBITS); 48 m_dbits = config.readNumEntry("DataBits", IRDA_DEFAULT_DBITS);
49 m_sbits = config.readNumEntry("StopBits", IRDA_DEFAULT_SBITS); 49 m_sbits = config.readNumEntry("StopBits", IRDA_DEFAULT_SBITS);
50 m_flow = config.readNumEntry("Flow", IRDA_DEFAULT_FLOW); 50 m_flow = config.readNumEntry("Flow", IRDA_DEFAULT_FLOW);
51} 51}
52 52
53 53
54QString IOIrda::identifier() const { 54QString IOIrda::identifier() const {
55 return "irda"; 55 return "irda";
56} 56}
57 57
58QString IOIrda::name() const { 58QString IOIrda::name() const {
59 return "Irda IO Layer"; 59 return "Irda IO Layer";
60} 60}
61 61
62void IOIrda::slotExited(OProcess* proc ){ 62void IOIrda::slotExited(OProcess* proc ){
63 close(); 63 close();
64 delete proc; 64 delete proc;
65} 65}
66 66
67QBitArray IOIrda::supports()const { 67QBitArray IOIrda::supports()const {
68 return QBitArray( 3 ); 68 return QBitArray( 3 );
69} 69}
70 70
71bool IOIrda::isConnected() { 71bool IOIrda::isConnected() {
72 return false; 72 return false;
73} 73}
74 74
75void IOIrda::send(const QByteArray &data) { 75void IOIrda::send(const QByteArray &data) {
76 qDebug( "Please overload me..." ); 76 qDebug( "Please overload me..." );
77} 77}
diff --git a/noncore/apps/opie-console/mainwindow.cpp b/noncore/apps/opie-console/mainwindow.cpp
index 1d2385f..197f799 100644
--- a/noncore/apps/opie-console/mainwindow.cpp
+++ b/noncore/apps/opie-console/mainwindow.cpp
@@ -1,727 +1,727 @@
1#include <assert.h> 1#include <assert.h>
2 2
3#include <qaction.h> 3#include <qaction.h>
4#include <qmenubar.h> 4#include <qmenubar.h>
5#include <qtoolbar.h> 5#include <qtoolbar.h>
6#include <qmessagebox.h> 6#include <qmessagebox.h>
7#include <qwhatsthis.h> 7#include <qwhatsthis.h>
8#include <qfileinfo.h> 8#include <qfileinfo.h>
9 9
10#include <qpe/filemanager.h> 10#include <qpe/filemanager.h>
11 11
12#include <opie2/ofiledialog.h> 12#include <opie2/ofiledialog.h>
13 13
14#include "TEmulation.h" 14#include "TEmulation.h"
15#include "profileeditordialog.h" 15#include "profileeditordialog.h"
16#include "configdialog.h" 16#include "configdialog.h"
17#include "default.h" 17#include "default.h"
18#include "profilemanager.h" 18#include "profilemanager.h"
19#include "mainwindow.h" 19#include "mainwindow.h"
20#include "tabwidget.h" 20#include "tabwidget.h"
21#include "transferdialog.h" 21#include "transferdialog.h"
22#include "function_keyboard.h" 22#include "function_keyboard.h"
23#include "emulation_handler.h" 23#include "emulation_handler.h"
24#include "script.h" 24#include "script.h"
25 25
26 26
27MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) { 27MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) {
28 KeyTrans::loadAll(); 28 KeyTrans::loadAll();
29 for (int i = 0; i < KeyTrans::count(); i++ ) { 29 for (int i = 0; i < KeyTrans::count(); i++ ) {
30 KeyTrans* s = KeyTrans::find(i ); 30 KeyTrans* s = KeyTrans::find(i );
31 assert( s ); 31 assert( s );
32 } 32 }
33 m_factory = new MetaFactory(); 33 m_factory = new MetaFactory();
34 Default def(m_factory); 34 Default def(m_factory);
35 m_sessions.setAutoDelete( TRUE ); 35 m_sessions.setAutoDelete( TRUE );
36 m_curSession = 0; 36 m_curSession = 0;
37 m_manager = new ProfileManager( m_factory ); 37 m_manager = new ProfileManager( m_factory );
38 m_manager->load(); 38 m_manager->load();
39 m_scriptsData.setAutoDelete(TRUE); 39 m_scriptsData.setAutoDelete(TRUE);
40 40
41 initUI(); 41 initUI();
42 populateProfiles(); 42 populateProfiles();
43 populateScripts(); 43 populateScripts();
44} 44}
45 45
46void MainWindow::initUI() { 46void MainWindow::initUI() {
47 47
48 setToolBarsMovable( FALSE ); 48 setToolBarsMovable( FALSE );
49 49
50 /* tool bar for the menu */ 50 /* tool bar for the menu */
51 m_tool = new QToolBar( this ); 51 m_tool = new QToolBar( this );
52 m_tool->setHorizontalStretchable( TRUE ); 52 m_tool->setHorizontalStretchable( TRUE );
53 53
54 m_bar = new QMenuBar( m_tool ); 54 m_bar = new QMenuBar( m_tool );
55 m_console = new QPopupMenu( this ); 55 m_console = new QPopupMenu( this );
56 m_scripts = new QPopupMenu( this ); 56 m_scripts = new QPopupMenu( this );
57 m_sessionsPop= new QPopupMenu( this ); 57 m_sessionsPop= new QPopupMenu( this );
58 m_scriptsPop = new QPopupMenu( this ); 58 m_scriptsPop = new QPopupMenu( this );
59 59
60 /* add a toolbar for icons */ 60 /* add a toolbar for icons */
61 m_icons = new QToolBar(this); 61 m_icons = new QToolBar(this);
62 62
63 /* 63 /*
64 * the settings action 64 * the settings action
65 */ 65 */
66 m_setProfiles = new QAction(tr("Configure Profiles"), 66 m_setProfiles = new QAction(tr("Configure Profiles"),
67 Resource::loadPixmap( "SettingsIcon" ), 67 Resource::loadPixmap( "SettingsIcon" ),
68 QString::null, 0, this, 0); 68 QString::null, 0, this, 0);
69 m_setProfiles->addTo( m_console ); 69 m_setProfiles->addTo( m_console );
70 connect( m_setProfiles, SIGNAL(activated() ), 70 connect( m_setProfiles, SIGNAL(activated() ),
71 this, SLOT(slotConfigure() ) ); 71 this, SLOT(slotConfigure() ) );
72 72
73 m_console->insertSeparator(); 73 m_console->insertSeparator();
74 /* 74 /*
75 * new Action for new sessions 75 * new Action for new sessions
76 */ 76 */
77 QAction* newCon = new QAction(tr("New Profile"), 77 QAction* newCon = new QAction(tr("New Profile"),
78 Resource::loadPixmap( "new" ), 78 Resource::loadPixmap( "new" ),
79 QString::null, 0, this, 0); 79 QString::null, 0, this, 0);
80 newCon->addTo( m_console ); 80 newCon->addTo( m_console );
81 connect( newCon, SIGNAL(activated() ), 81 connect( newCon, SIGNAL(activated() ),
82 this, SLOT(slotNew() ) ); 82 this, SLOT(slotNew() ) );
83 83
84 m_console->insertSeparator(); 84 m_console->insertSeparator();
85 85
86 QAction *saveCon = new QAction( tr("Save Profile" ), 86 QAction *saveCon = new QAction( tr("Save Profile" ),
87 Resource::loadPixmap( "save" ), QString::null, 87 Resource::loadPixmap( "save" ), QString::null,
88 0, this, 0 ); 88 0, this, 0 );
89 saveCon->addTo( m_console ); 89 saveCon->addTo( m_console );
90 connect( saveCon, SIGNAL(activated() ), 90 connect( saveCon, SIGNAL(activated() ),
91 this, SLOT(slotSaveSession() ) ); 91 this, SLOT(slotSaveSession() ) );
92 m_console->insertSeparator(); 92 m_console->insertSeparator();
93 93
94 /* 94 /*
95 * connect action 95 * connect action
96 */ 96 */
97 m_connect = new QAction( tr("Connect"), Resource::loadPixmap("console/connected"), 97 m_connect = new QAction( tr("Connect"), Resource::loadPixmap("console/connected"),
98 QString::null, 0, this, 0 ); 98 QString::null, 0, this, 0 );
99 m_connect->addTo( m_console ); 99 m_connect->addTo( m_console );
100 connect(m_connect, SIGNAL(activated() ), 100 connect(m_connect, SIGNAL(activated() ),
101 this, SLOT(slotConnect() ) ); 101 this, SLOT(slotConnect() ) );
102 102
103 /* 103 /*
104 * disconnect action 104 * disconnect action
105 */ 105 */
106 m_disconnect = new QAction( tr("Disconnect"), Resource::loadPixmap("console/notconnected"), 106 m_disconnect = new QAction( tr("Disconnect"), Resource::loadPixmap("console/notconnected"),
107 QString::null, 0, this, 0 ); 107 QString::null, 0, this, 0 );
108 m_disconnect->addTo( m_console ); 108 m_disconnect->addTo( m_console );
109 connect(m_disconnect, SIGNAL(activated() ), 109 connect(m_disconnect, SIGNAL(activated() ),
110 this, SLOT(slotDisconnect() ) ); 110 this, SLOT(slotDisconnect() ) );
111 111
112 m_console->insertSeparator(); 112 m_console->insertSeparator();
113 113
114 114
115 m_quickLaunch = new QAction( tr("QuickLaunch"), Resource::loadPixmap("console/konsole_mini"), QString::null, 0, this, 0 ); 115 m_quickLaunch = new QAction( tr("QuickLaunch"), Resource::loadPixmap("console/konsole_mini"), QString::null, 0, this, 0 );
116 m_quickLaunch->addTo( m_icons ); 116 m_quickLaunch->addTo( m_icons );
117 connect( m_quickLaunch, SIGNAL( activated() ), 117 connect( m_quickLaunch, SIGNAL( activated() ),
118 this, SLOT( slotQuickLaunch() ) ); 118 this, SLOT( slotQuickLaunch() ) );
119 119
120 QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) ); 120 QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) );
121 121
122 m_transfer = new QAction( tr("Transfer file..."), Resource::loadPixmap("pass") , QString::null, 122 m_transfer = new QAction( tr("Transfer file..."), Resource::loadPixmap("pass") , QString::null,
123 0, this, 0 ); 123 0, this, 0 );
124 m_transfer->addTo( m_console ); 124 m_transfer->addTo( m_console );
125 connect(m_transfer, SIGNAL(activated() ), 125 connect(m_transfer, SIGNAL(activated() ),
126 this, SLOT(slotTransfer() ) ); 126 this, SLOT(slotTransfer() ) );
127 127
128 128
129 129
130 /* 130 /*
131 * immediate change of line wrap policy 131 * immediate change of line wrap policy
132 */ 132 */
133 m_isWrapped = false; 133 m_isWrapped = false;
134 m_wrap = new QAction( tr("Line wrap"), Resource::loadPixmap( "linewrap" ), QString::null, 0, this, 0 ); 134 m_wrap = new QAction( tr("Line wrap"), Resource::loadPixmap( "linewrap" ), QString::null, 0, this, 0 );
135 m_wrap->addTo( m_console ); 135 m_wrap->addTo( m_console );
136 connect( m_wrap, SIGNAL( activated() ), SLOT( slotWrap() ) ); 136 connect( m_wrap, SIGNAL( activated() ), SLOT( slotWrap() ) );
137 137
138 /* 138 /*
139 * fullscreen 139 * fullscreen
140 */ 140 */
141 m_isFullscreen = false; 141 m_isFullscreen = false;
142 142
143 m_fullscreen = new QAction( tr("Full screen"), Resource::loadPixmap( "fullscreen" ) 143 m_fullscreen = new QAction( tr("Full screen"), Resource::loadPixmap( "fullscreen" )
144 , QString::null, 0, this, 0); 144 , QString::null, 0, this, 0);
145 m_fullscreen->addTo( m_console ); 145 m_fullscreen->addTo( m_console );
146 connect( m_fullscreen, SIGNAL( activated() ), 146 connect( m_fullscreen, SIGNAL( activated() ),
147 this, SLOT( slotFullscreen() ) ); 147 this, SLOT( slotFullscreen() ) );
148 148
149 m_console->insertSeparator(); 149 m_console->insertSeparator();
150 150
151 QAction *a = new QAction(); 151 QAction *a = new QAction();
152 a->setText( tr("Save history") ); 152 a->setText( tr("Save history") );
153 a->addTo( m_console ); 153 a->addTo( m_console );
154 connect(a, SIGNAL(activated() ), 154 connect(a, SIGNAL(activated() ),
155 this, SLOT(slotSaveHistory() ) ); 155 this, SLOT(slotSaveHistory() ) );
156 /* 156 /*
157 * terminate action 157 * terminate action
158 */ 158 */
159 m_terminate = new QAction(); 159 m_terminate = new QAction();
160 m_terminate->setText( tr("Terminate") ); 160 m_terminate->setText( tr("Terminate") );
161 m_terminate->addTo( m_console ); 161 m_terminate->addTo( m_console );
162 connect(m_terminate, SIGNAL(activated() ), 162 connect(m_terminate, SIGNAL(activated() ),
163 this, SLOT(slotTerminate() ) ); 163 this, SLOT(slotTerminate() ) );
164 164
165 m_closewindow = new QAction(); 165 m_closewindow = new QAction();
166 m_closewindow->setText( tr("Close Window") ); 166 m_closewindow->setText( tr("Close Window") );
167 m_closewindow->addTo( m_console ); 167 m_closewindow->addTo( m_console );
168 connect( m_closewindow, SIGNAL(activated() ), 168 connect( m_closewindow, SIGNAL(activated() ),
169 this, SLOT(slotClose() ) ); 169 this, SLOT(slotClose() ) );
170 170
171 171
172 /* 172 /*
173 * script actions 173 * script actions
174 */ 174 */
175 m_runScript_id = m_scripts->insertItem(tr("Run Script"), m_scriptsPop, -1, 0); 175 m_runScript_id = m_scripts->insertItem(tr("Run Script"), m_scriptsPop, -1, 0);
176 connect(m_scriptsPop, SIGNAL(activated(int)), this, SLOT(slotRunScript(int))); 176 connect(m_scriptsPop, SIGNAL(activated(int)), this, SLOT(slotRunScript(int)));
177 177
178 m_recordScript = new QAction(tr("Record Script"), QString::null, 0, this, 0); 178 m_recordScript = new QAction(tr("Record Script"), QString::null, 0, this, 0);
179 m_recordScript->addTo(m_scripts); 179 m_recordScript->addTo(m_scripts);
180 connect(m_recordScript, SIGNAL(activated()), this, SLOT(slotRecordScript())); 180 connect(m_recordScript, SIGNAL(activated()), this, SLOT(slotRecordScript()));
181 181
182 m_saveScript = new QAction(tr("Save Script"), QString::null, 0, this, 0); 182 m_saveScript = new QAction(tr("Save Script"), QString::null, 0, this, 0);
183 m_saveScript->addTo(m_scripts); 183 m_saveScript->addTo(m_scripts);
184 connect(m_saveScript, SIGNAL(activated()), this, SLOT(slotSaveScript())); 184 connect(m_saveScript, SIGNAL(activated()), this, SLOT(slotSaveScript()));
185 185
186 186
187 /* 187 /*
188 * action that open/closes the keyboard 188 * action that open/closes the keyboard
189 */ 189 */
190 m_openKeys = new QAction (tr("Open Keyboard..."), 190 m_openKeys = new QAction (tr("Open Keyboard..."),
191 Resource::loadPixmap( "console/keys/keyboard_icon" ), 191 Resource::loadPixmap( "console/keys/keyboard_icon" ),
192 QString::null, 0, this, 0); 192 QString::null, 0, this, 0);
193 m_openKeys->setToggleAction(true); 193 m_openKeys->setToggleAction(true);
194 connect (m_openKeys, SIGNAL(toggled(bool)), this, SLOT(slotOpenKeb(bool))); 194 connect (m_openKeys, SIGNAL(toggled(bool)), this, SLOT(slotOpenKeb(bool)));
195 195
196 /* insert the submenu */ 196 /* insert the submenu */
197 m_console->insertItem(tr("New from Profile"), m_sessionsPop, 197 m_console->insertItem(tr("New from Profile"), m_sessionsPop,
198 -1, 0); 198 -1, 0);
199 199
200 /* insert the connection menu */ 200 /* insert the connection menu */
201 m_bar->insertItem( tr("Connection"), m_console ); 201 m_bar->insertItem( tr("Connection"), m_console );
202 202
203 /* the scripts menu */ 203 /* the scripts menu */
204 m_bar->insertItem( tr("Scripts"), m_scripts ); 204 m_bar->insertItem( tr("Scripts"), m_scripts );
205 205
206 /* and the keyboard */ 206 /* and the keyboard */
207 m_keyBar = new QToolBar(this); 207 m_keyBar = new QToolBar(this);
208 addToolBar( m_keyBar, "Keyboard", QMainWindow::Top, TRUE ); 208 addToolBar( m_keyBar, "Keyboard", QMainWindow::Top, TRUE );
209 m_keyBar->setHorizontalStretchable( TRUE ); 209 m_keyBar->setHorizontalStretchable( TRUE );
210 m_keyBar->hide(); 210 m_keyBar->hide();
211 211
212 m_kb = new FunctionKeyboard(m_keyBar); 212 m_kb = new FunctionKeyboard(m_keyBar);
213 connect(m_kb, SIGNAL(keyPressed(FKey, ushort, ushort, bool)), 213 connect(m_kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)),
214 this, SLOT(slotKeyReceived(FKey, ushort, ushort, bool))); 214 this, SLOT(slotKeyReceived(FKey,ushort,ushort,bool)));
215 215
216 216
217 a = new QAction(tr("Copy"), 217 a = new QAction(tr("Copy"),
218 Resource::loadPixmap("copy"), QString::null, 218 Resource::loadPixmap("copy"), QString::null,
219 0, this, 0 ); 219 0, this, 0 );
220 //a->addTo( m_icons ); 220 //a->addTo( m_icons );
221 connect( a, SIGNAL(activated() ), 221 connect( a, SIGNAL(activated() ),
222 this, SLOT(slotCopy() ) ); 222 this, SLOT(slotCopy() ) );
223 223
224 QAction *paste = new QAction(tr("Paste"), 224 QAction *paste = new QAction(tr("Paste"),
225 Resource::loadPixmap("paste"), QString::null, 225 Resource::loadPixmap("paste"), QString::null,
226 0, this, 0 ); 226 0, this, 0 );
227 connect( paste, SIGNAL(activated() ), 227 connect( paste, SIGNAL(activated() ),
228 this, SLOT(slotPaste() ) ); 228 this, SLOT(slotPaste() ) );
229 229
230 230
231 newCon->addTo( m_icons ); 231 newCon->addTo( m_icons );
232 //m_setProfiles->addTo( m_icons ); 232 //m_setProfiles->addTo( m_icons );
233 paste->addTo( m_icons ); 233 paste->addTo( m_icons );
234 m_openKeys->addTo(m_icons); 234 m_openKeys->addTo(m_icons);
235 m_fullscreen->addTo( m_icons ); 235 m_fullscreen->addTo( m_icons );
236 236
237 m_connect->setEnabled( false ); 237 m_connect->setEnabled( false );
238 m_disconnect->setEnabled( false ); 238 m_disconnect->setEnabled( false );
239 m_terminate->setEnabled( false ); 239 m_terminate->setEnabled( false );
240 m_transfer->setEnabled( false ); 240 m_transfer->setEnabled( false );
241 m_scripts->setItemEnabled(m_runScript_id, false); 241 m_scripts->setItemEnabled(m_runScript_id, false);
242 m_recordScript->setEnabled( false ); 242 m_recordScript->setEnabled( false );
243 m_saveScript->setEnabled( false ); 243 m_saveScript->setEnabled( false );
244 m_fullscreen->setEnabled( false ); 244 m_fullscreen->setEnabled( false );
245 m_closewindow->setEnabled( false ); 245 m_closewindow->setEnabled( false );
246 m_wrap->setEnabled( false ); 246 m_wrap->setEnabled( false );
247 247
248 /* 248 /*
249 * connect to the menu activation 249 * connect to the menu activation
250 */ 250 */
251 connect( m_sessionsPop, SIGNAL(activated( int ) ), 251 connect( m_sessionsPop, SIGNAL(activated(int) ),
252 this, SLOT(slotProfile( int ) ) ); 252 this, SLOT(slotProfile(int) ) );
253 253
254 m_consoleWindow = new TabWidget( this, "blah"); 254 m_consoleWindow = new TabWidget( this, "blah");
255 connect(m_consoleWindow, SIGNAL(activated(Session*) ), 255 connect(m_consoleWindow, SIGNAL(activated(Session*) ),
256 this, SLOT(slotSessionChanged(Session*) ) ); 256 this, SLOT(slotSessionChanged(Session*) ) );
257 setCentralWidget( m_consoleWindow ); 257 setCentralWidget( m_consoleWindow );
258 258
259 slotQuickLaunch(); 259 slotQuickLaunch();
260} 260}
261 261
262ProfileManager* MainWindow::manager() { 262ProfileManager* MainWindow::manager() {
263 return m_manager; 263 return m_manager;
264} 264}
265TabWidget* MainWindow::tabWidget() { 265TabWidget* MainWindow::tabWidget() {
266 return m_consoleWindow; 266 return m_consoleWindow;
267} 267}
268void MainWindow::populateProfiles() { 268void MainWindow::populateProfiles() {
269 m_sessionsPop->clear(); 269 m_sessionsPop->clear();
270 Profile::ValueList list = manager()->all(); 270 Profile::ValueList list = manager()->all();
271 for (Profile::ValueList::Iterator it = list.begin(); it != list.end(); ++it ) { 271 for (Profile::ValueList::Iterator it = list.begin(); it != list.end(); ++it ) {
272 m_sessionsPop->insertItem( (*it).name() ); 272 m_sessionsPop->insertItem( (*it).name() );
273 } 273 }
274 274
275} 275}
276 276
277void MainWindow::populateScripts() { 277void MainWindow::populateScripts() {
278 m_scriptsPop->clear(); 278 m_scriptsPop->clear();
279 m_scriptsData.clear(); 279 m_scriptsData.clear();
280 DocLnkSet files(QPEApplication::documentDir(), "text/plain"); 280 DocLnkSet files(QPEApplication::documentDir(), "text/plain");
281 QListIterator<DocLnk> dit(files.children()); 281 QListIterator<DocLnk> dit(files.children());
282 for (; dit.current(); ++dit) { 282 for (; dit.current(); ++dit) {
283 if (*dit && (*dit)->name().length()>0) { 283 if (*dit && (*dit)->name().length()>0) {
284 QFileInfo info((*dit)->file()); 284 QFileInfo info((*dit)->file());
285 if (info.extension(false) == "script") { 285 if (info.extension(false) == "script") {
286 m_scriptsData.append(new DocLnk(**dit)); 286 m_scriptsData.append(new DocLnk(**dit));
287 m_scriptsPop->insertItem((*dit)->name()); 287 m_scriptsPop->insertItem((*dit)->name());
288 } 288 }
289 } 289 }
290 } 290 }
291 291
292} 292}
293 293
294MainWindow::~MainWindow() { 294MainWindow::~MainWindow() {
295 delete m_factory; 295 delete m_factory;
296 manager()->save(); 296 manager()->save();
297} 297}
298 298
299MetaFactory* MainWindow::factory() { 299MetaFactory* MainWindow::factory() {
300 return m_factory; 300 return m_factory;
301} 301}
302 302
303Session* MainWindow::currentSession() { 303Session* MainWindow::currentSession() {
304 return m_curSession; 304 return m_curSession;
305} 305}
306 306
307QList<Session> MainWindow::sessions() { 307QList<Session> MainWindow::sessions() {
308 return m_sessions; 308 return m_sessions;
309} 309}
310 310
311void MainWindow::slotNew() { 311void MainWindow::slotNew() {
312 ProfileEditorDialog dlg(factory() ); 312 ProfileEditorDialog dlg(factory() );
313 dlg.setCaption( tr("New Connection") ); 313 dlg.setCaption( tr("New Connection") );
314 int ret = QPEApplication::execDialog( &dlg ); 314 int ret = QPEApplication::execDialog( &dlg );
315 315
316 if ( ret == QDialog::Accepted ) { 316 if ( ret == QDialog::Accepted ) {
317 create( dlg.profile() ); 317 create( dlg.profile() );
318 } 318 }
319} 319}
320 320
321void MainWindow::slotRecordScript() { 321void MainWindow::slotRecordScript() {
322 if (currentSession()) { 322 if (currentSession()) {
323 currentSession()->emulationHandler()->startRecording(); 323 currentSession()->emulationHandler()->startRecording();
324 m_saveScript->setEnabled(true); 324 m_saveScript->setEnabled(true);
325 m_recordScript->setEnabled(false); 325 m_recordScript->setEnabled(false);
326 } 326 }
327} 327}
328 328
329void MainWindow::slotSaveScript() { 329void MainWindow::slotSaveScript() {
330 if (currentSession() && currentSession()->emulationHandler()->isRecording()) { 330 if (currentSession() && currentSession()->emulationHandler()->isRecording()) {
331 QMap<QString, QStringList> map; 331 QMap<QString, QStringList> map;
332 QStringList text; 332 QStringList text;
333 text << "text/plain"; 333 text << "text/plain";
334 map.insert(tr("Script"), text ); 334 map.insert(tr("Script"), text );
335 QString filename = Opie::OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); 335 QString filename = Opie::OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map);
336 if (!filename.isEmpty()) { 336 if (!filename.isEmpty()) {
337 QFileInfo info(filename); 337 QFileInfo info(filename);
338 if (info.extension(FALSE) != "script") 338 if (info.extension(FALSE) != "script")
339 filename += ".script"; 339 filename += ".script";
340 DocLnk nf; 340 DocLnk nf;
341 nf.setType("text/plain"); 341 nf.setType("text/plain");
342 nf.setFile(filename); 342 nf.setFile(filename);
343 nf.setName(info.fileName()); 343 nf.setName(info.fileName());
344 FileManager fm; 344 FileManager fm;
345 fm.saveFile(nf, currentSession()->emulationHandler()->script()->script()); 345 fm.saveFile(nf, currentSession()->emulationHandler()->script()->script());
346 currentSession()->emulationHandler()->clearScript(); 346 currentSession()->emulationHandler()->clearScript();
347 m_saveScript->setEnabled(false); 347 m_saveScript->setEnabled(false);
348 m_recordScript->setEnabled(true); 348 m_recordScript->setEnabled(true);
349 populateScripts(); 349 populateScripts();
350 } 350 }
351 } 351 }
352} 352}
353 353
354void MainWindow::slotRunScript(int id) { 354void MainWindow::slotRunScript(int id) {
355 if (currentSession()) { 355 if (currentSession()) {
356 int index = m_scriptsPop->indexOf(id); 356 int index = m_scriptsPop->indexOf(id);
357 DocLnk *lnk = m_scriptsData.at(index); 357 DocLnk *lnk = m_scriptsData.at(index);
358 QString filePath = lnk->file(); 358 QString filePath = lnk->file();
359 Script script(filePath); 359 Script script(filePath);
360 currentSession()->emulationHandler()->runScript(&script); 360 currentSession()->emulationHandler()->runScript(&script);
361 } 361 }
362} 362}
363 363
364void MainWindow::slotConnect() { 364void MainWindow::slotConnect() {
365 if ( currentSession() ) { 365 if ( currentSession() ) {
366 bool ret = currentSession()->layer()->open(); 366 bool ret = currentSession()->layer()->open();
367 if(!ret) QMessageBox::warning(currentSession()->widgetStack(), 367 if(!ret) QMessageBox::warning(currentSession()->widgetStack(),
368 QObject::tr("Failed"), 368 QObject::tr("Failed"),
369 QObject::tr("Connecting failed for this session.")); 369 QObject::tr("Connecting failed for this session."));
370 else { 370 else {
371 m_connect->setEnabled( false ); 371 m_connect->setEnabled( false );
372 m_disconnect->setEnabled( true ); 372 m_disconnect->setEnabled( true );
373 373
374 // if it does not support file transfer, disable the menu entry 374 // if it does not support file transfer, disable the menu entry
375 if ( ( m_curSession->layer() )->supports()[1] == 0 ) { 375 if ( ( m_curSession->layer() )->supports()[1] == 0 ) {
376 m_transfer->setEnabled( false ); 376 m_transfer->setEnabled( false );
377 } else { 377 } else {
378 m_transfer->setEnabled( true ); 378 m_transfer->setEnabled( true );
379 } 379 }
380 380
381 m_recordScript->setEnabled( true ); 381 m_recordScript->setEnabled( true );
382 m_scripts->setItemEnabled(m_runScript_id, true); 382 m_scripts->setItemEnabled(m_runScript_id, true);
383 } 383 }
384 } 384 }
385} 385}
386 386
387void MainWindow::slotDisconnect() { 387void MainWindow::slotDisconnect() {
388 if ( currentSession() ) { 388 if ( currentSession() ) {
389 currentSession()->layer()->close(); 389 currentSession()->layer()->close();
390 m_connect->setEnabled( true ); 390 m_connect->setEnabled( true );
391 m_disconnect->setEnabled( false ); 391 m_disconnect->setEnabled( false );
392 m_transfer->setEnabled( false ); 392 m_transfer->setEnabled( false );
393 m_recordScript->setEnabled( false); 393 m_recordScript->setEnabled( false);
394 m_saveScript->setEnabled( false ); 394 m_saveScript->setEnabled( false );
395 m_scripts->setItemEnabled(m_runScript_id, false); 395 m_scripts->setItemEnabled(m_runScript_id, false);
396 } 396 }
397} 397}
398 398
399void MainWindow::slotTerminate() { 399void MainWindow::slotTerminate() {
400 if ( currentSession() ) 400 if ( currentSession() )
401 currentSession()->layer()->close(); 401 currentSession()->layer()->close();
402 402
403 slotClose(); 403 slotClose();
404 /* FIXME move to the next session */ 404 /* FIXME move to the next session */
405} 405}
406 406
407 407
408 408
409 409
410 410
411 411
412void MainWindow::slotQuickLaunch() { 412void MainWindow::slotQuickLaunch() {
413 Profile prof = manager()->profile( "default" ); 413 Profile prof = manager()->profile( "default" );
414 if ( prof.name() == "default" ) { 414 if ( prof.name() == "default" ) {
415 create( prof ); 415 create( prof );
416 } else { 416 } else {
417 Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 ); 417 Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 );
418 newProf.setAutoConnect( true ); 418 newProf.setAutoConnect( true );
419 create( newProf ); 419 create( newProf );
420 slotSaveSession(); 420 slotSaveSession();
421 } 421 }
422 422
423} 423}
424 424
425void MainWindow::slotConfigure() { 425void MainWindow::slotConfigure() {
426 ConfigDialog conf( manager()->all(), factory() ); 426 ConfigDialog conf( manager()->all(), factory() );
427 427
428 int ret = QPEApplication::execDialog( &conf ); 428 int ret = QPEApplication::execDialog( &conf );
429 429
430 if ( QDialog::Accepted == ret ) { 430 if ( QDialog::Accepted == ret ) {
431 manager()->setProfiles( conf.list() ); 431 manager()->setProfiles( conf.list() );
432 manager()->save(); 432 manager()->save();
433 populateProfiles(); 433 populateProfiles();
434 } 434 }
435} 435}
436/* 436/*
437 * we will remove 437 * we will remove
438 * this window from the tabwidget 438 * this window from the tabwidget
439 * remove it from the list 439 * remove it from the list
440 * delete it 440 * delete it
441 * and set the currentSession() 441 * and set the currentSession()
442 */ 442 */
443void MainWindow::slotClose() { 443void MainWindow::slotClose() {
444 if (!currentSession() ) 444 if (!currentSession() )
445 return; 445 return;
446 446
447 Session* ses = currentSession(); 447 Session* ses = currentSession();
448 qWarning("removing! currentSession %s", currentSession()->name().latin1() ); 448 qWarning("removing! currentSession %s", currentSession()->name().latin1() );
449 /* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */ 449 /* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */
450 m_curSession = NULL; 450 m_curSession = NULL;
451 tabWidget()->remove( /*currentSession()*/ses ); 451 tabWidget()->remove( /*currentSession()*/ses );
452 /*it's autodelete */ 452 /*it's autodelete */
453 m_sessions.remove( ses ); 453 m_sessions.remove( ses );
454 qWarning("after remove!!"); 454 qWarning("after remove!!");
455 455
456 if (!currentSession() ) { 456 if (!currentSession() ) {
457 m_connect->setEnabled( false ); 457 m_connect->setEnabled( false );
458 m_disconnect->setEnabled( false ); 458 m_disconnect->setEnabled( false );
459 m_terminate->setEnabled( false ); 459 m_terminate->setEnabled( false );
460 m_transfer->setEnabled( false ); 460 m_transfer->setEnabled( false );
461 m_recordScript->setEnabled( false ); 461 m_recordScript->setEnabled( false );
462 m_saveScript->setEnabled( false ); 462 m_saveScript->setEnabled( false );
463 m_scripts->setItemEnabled(m_runScript_id, false); 463 m_scripts->setItemEnabled(m_runScript_id, false);
464 m_fullscreen->setEnabled( false ); 464 m_fullscreen->setEnabled( false );
465 m_wrap->setEnabled( false ); 465 m_wrap->setEnabled( false );
466 m_closewindow->setEnabled( false ); 466 m_closewindow->setEnabled( false );
467 } 467 }
468 468
469 m_kb->loadDefaults(); 469 m_kb->loadDefaults();
470} 470}
471 471
472/* 472/*
473 * We will get the name 473 * We will get the name
474 * Then the profile 474 * Then the profile
475 * and then we will make a profile 475 * and then we will make a profile
476 */ 476 */
477void MainWindow::slotProfile( int id) { 477void MainWindow::slotProfile( int id) {
478 Profile prof = manager()->profile( m_sessionsPop->text( id) ); 478 Profile prof = manager()->profile( m_sessionsPop->text( id) );
479 create( prof ); 479 create( prof );
480} 480}
481 481
482 482
483 483
484void MainWindow::create( const Profile& prof ) { 484void MainWindow::create( const Profile& prof ) {
485 if(m_curSession) 485 if(m_curSession)
486 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); 486 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide();
487 487
488 Session *ses = manager()->fromProfile( prof, tabWidget() ); 488 Session *ses = manager()->fromProfile( prof, tabWidget() );
489 489
490 if((!ses) || (!ses->layer()) || (!ses->widgetStack())) 490 if((!ses) || (!ses->layer()) || (!ses->widgetStack()))
491 { 491 {
492 QMessageBox::warning(this, 492 QMessageBox::warning(this,
493 QObject::tr("Session failed"), 493 QObject::tr("Session failed"),
494 QObject::tr("<qt>Cannot open session: Not all components were found.</qt>")); 494 QObject::tr("<qt>Cannot open session: Not all components were found.</qt>"));
495 //if(ses) delete ses; 495 //if(ses) delete ses;
496 return; 496 return;
497 } 497 }
498 498
499 m_sessions.append( ses ); 499 m_sessions.append( ses );
500 tabWidget()->add( ses ); 500 tabWidget()->add( ses );
501 tabWidget()->repaint(); 501 tabWidget()->repaint();
502 m_curSession = ses; 502 m_curSession = ses;
503 503
504 // dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it 504 // dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it
505 m_connect->setEnabled( true ); 505 m_connect->setEnabled( true );
506 m_disconnect->setEnabled( false ); 506 m_disconnect->setEnabled( false );
507 m_terminate->setEnabled( true ); 507 m_terminate->setEnabled( true );
508 m_fullscreen->setEnabled( true ); 508 m_fullscreen->setEnabled( true );
509 m_wrap->setEnabled( true ); 509 m_wrap->setEnabled( true );
510 m_closewindow->setEnabled( true ); 510 m_closewindow->setEnabled( true );
511 m_transfer->setEnabled( false ); 511 m_transfer->setEnabled( false );
512 m_recordScript->setEnabled( false ); 512 m_recordScript->setEnabled( false );
513 m_saveScript->setEnabled( false ); 513 m_saveScript->setEnabled( false );
514 m_scripts->setItemEnabled(m_runScript_id, false); 514 m_scripts->setItemEnabled(m_runScript_id, false);
515 515
516 // is io_layer wants direct connection, then autoconnect 516 // is io_layer wants direct connection, then autoconnect
517 //if ( ( m_curSession->layer() )->supports()[0] == 1 ) { 517 //if ( ( m_curSession->layer() )->supports()[0] == 1 ) {
518 if (prof.autoConnect()) { 518 if (prof.autoConnect()) {
519 slotConnect(); 519 slotConnect();
520 } 520 }
521 521
522 522
523 QWidget *w = currentSession()->widget(); 523 QWidget *w = currentSession()->widget();
524 if(w) w->setFocus(); 524 if(w) w->setFocus();
525 525
526 if(currentSession()->profile().readNumEntry("Wrap", 80)){ 526 if(currentSession()->profile().readNumEntry("Wrap", 80)){
527 m_isWrapped = true; 527 m_isWrapped = true;
528 } else { 528 } else {
529 m_isWrapped = false; 529 m_isWrapped = false;
530 } 530 }
531 531
532 m_kb->load(currentSession()->profile()); 532 m_kb->load(currentSession()->profile());
533} 533}
534 534
535void MainWindow::slotTransfer() 535void MainWindow::slotTransfer()
536{ 536{
537 if ( currentSession() ) { 537 if ( currentSession() ) {
538 Session *mysession = currentSession(); 538 Session *mysession = currentSession();
539 TransferDialog dlg(/*mysession->widgetStack()*/this, this); 539 TransferDialog dlg(/*mysession->widgetStack()*/this, this);
540 mysession->setTransferDialog(&dlg); 540 mysession->setTransferDialog(&dlg);
541 //dlg.reparent(mysession->widgetStack(), QPoint(0, 0)); 541 //dlg.reparent(mysession->widgetStack(), QPoint(0, 0));
542 //dlg.showMaximized(); 542 //dlg.showMaximized();
543 currentSession()->widgetStack()->addWidget(&dlg, -1); 543 currentSession()->widgetStack()->addWidget(&dlg, -1);
544 dlg.show(); 544 dlg.show();
545 //dlg.exec(); 545 //dlg.exec();
546 while(dlg.isRunning()) qApp->processEvents(); 546 while(dlg.isRunning()) qApp->processEvents();
547 mysession->setTransferDialog(0l); 547 mysession->setTransferDialog(0l);
548 } 548 }
549} 549}
550 550
551 551
552void MainWindow::slotOpenKeb(bool state) { 552void MainWindow::slotOpenKeb(bool state) {
553 553
554 if (state) m_keyBar->show(); 554 if (state) m_keyBar->show();
555 else m_keyBar->hide(); 555 else m_keyBar->hide();
556 556
557} 557}
558 558
559 559
560void MainWindow::slotOpenButtons( bool state ) { 560void MainWindow::slotOpenButtons( bool state ) {
561 561
562 if ( state ) { 562 if ( state ) {
563 m_buttonBar->show(); 563 m_buttonBar->show();
564 } else { 564 } else {
565 m_buttonBar->hide(); 565 m_buttonBar->hide();
566 } 566 }
567} 567}
568 568
569 569
570 570
571void MainWindow::slotSessionChanged( Session* ses ) { 571void MainWindow::slotSessionChanged( Session* ses ) {
572 qWarning("changed!"); 572 qWarning("changed!");
573 573
574 if(m_curSession) 574 if(m_curSession)
575 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); 575 if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide();
576 if(ses) 576 if(ses)
577 if(ses->transferDialog()) ses->transferDialog()->show(); 577 if(ses->transferDialog()) ses->transferDialog()->show();
578 578
579 if ( ses ) { 579 if ( ses ) {
580 m_curSession = ses; 580 m_curSession = ses;
581 qDebug(QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) ); 581 qDebug(QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) );
582 if ( m_curSession->layer()->isConnected() ) { 582 if ( m_curSession->layer()->isConnected() ) {
583 m_connect->setEnabled( false ); 583 m_connect->setEnabled( false );
584 m_disconnect->setEnabled( true ); 584 m_disconnect->setEnabled( true );
585 m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording()); 585 m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording());
586 m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording()); 586 m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording());
587 m_scripts->setItemEnabled(m_runScript_id, true); 587 m_scripts->setItemEnabled(m_runScript_id, true);
588 } else { 588 } else {
589 m_connect->setEnabled( true ); 589 m_connect->setEnabled( true );
590 m_disconnect->setEnabled( false ); 590 m_disconnect->setEnabled( false );
591 m_recordScript->setEnabled( false ); 591 m_recordScript->setEnabled( false );
592 m_saveScript->setEnabled( false ); 592 m_saveScript->setEnabled( false );
593 m_scripts->setItemEnabled(m_runScript_id, false); 593 m_scripts->setItemEnabled(m_runScript_id, false);
594 } 594 }
595 595
596 if ( ( m_curSession->layer() )->supports()[1] == 0 ) { 596 if ( ( m_curSession->layer() )->supports()[1] == 0 ) {
597 m_transfer->setEnabled( false ); 597 m_transfer->setEnabled( false );
598 } else { 598 } else {
599 m_transfer->setEnabled( true ); 599 m_transfer->setEnabled( true );
600 } 600 }
601 601
602 QWidget *w = m_curSession->widget(); 602 QWidget *w = m_curSession->widget();
603 if(w) w->setFocus(); 603 if(w) w->setFocus();
604 604
605 if(currentSession()->profile().readNumEntry("Wrap", 80)){ 605 if(currentSession()->profile().readNumEntry("Wrap", 80)){
606 m_isWrapped = true; 606 m_isWrapped = true;
607 } else { 607 } else {
608 m_isWrapped = false; 608 m_isWrapped = false;
609 } 609 }
610 610
611 m_kb->load(currentSession()->profile()); 611 m_kb->load(currentSession()->profile());
612 } 612 }
613} 613}
614 614
615void MainWindow::slotWrap() 615void MainWindow::slotWrap()
616{ 616{
617 if(m_curSession) 617 if(m_curSession)
618 { 618 {
619 EmulationHandler *e = m_curSession->emulationHandler(); 619 EmulationHandler *e = m_curSession->emulationHandler();
620 if(e) 620 if(e)
621 { 621 {
622 if(m_isWrapped) 622 if(m_isWrapped)
623 { 623 {
624 e->setWrap(80); 624 e->setWrap(80);
625 m_isWrapped = false; 625 m_isWrapped = false;
626 } 626 }
627 else 627 else
628 { 628 {
629 e->setWrap(0); 629 e->setWrap(0);
630 m_isWrapped = true; 630 m_isWrapped = true;
631 } 631 }
632 } 632 }
633 } 633 }
634} 634}
635 635
636void MainWindow::slotFullscreen() { 636void MainWindow::slotFullscreen() {
637 637
638 638
639 639
640 if ( m_isFullscreen ) { 640 if ( m_isFullscreen ) {
641 ( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true ); 641 ( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true );
642 ( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() ); 642 ( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() );
643 ( m_curSession->emulationHandler() )->cornerButton()->hide(); 643 ( m_curSession->emulationHandler() )->cornerButton()->hide();
644 disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); 644 disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) );
645 645
646 } else { 646 } else {
647 savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget(); 647 savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget();
648 ( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame ); 648 ( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame );
649 ( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop 649 ( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop
650 , QPoint(0,0), false ); 650 , QPoint(0,0), false );
651 ( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() ); 651 ( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() );
652 ( m_curSession->widgetStack() )->setFocus(); 652 ( m_curSession->widgetStack() )->setFocus();
653 ( m_curSession->widgetStack() )->show(); 653 ( m_curSession->widgetStack() )->show();
654 654
655 ( ( m_curSession->emulationHandler() )->cornerButton() )->show(); 655 ( ( m_curSession->emulationHandler() )->cornerButton() )->show();
656 656
657 connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); 657 connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) );
658 } 658 }
659 659
660 m_isFullscreen = !m_isFullscreen; 660 m_isFullscreen = !m_isFullscreen;
661} 661}
662 662
663 663
664void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) { 664void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) {
665 665
666 if ( m_curSession ) { 666 if ( m_curSession ) {
667 667
668 QEvent::Type state; 668 QEvent::Type state;
669 669
670 if (pressed) state = QEvent::KeyPress; 670 if (pressed) state = QEvent::KeyPress;
671 else state = QEvent::KeyRelease; 671 else state = QEvent::KeyRelease;
672 672
673 QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode))); 673 QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode)));
674 674
675 // is this the best way to do this? cant figure out any other way to work 675 // is this the best way to do this? cant figure out any other way to work
676 QApplication::sendEvent((QObject *)m_curSession->widget(), &ke); 676 QApplication::sendEvent((QObject *)m_curSession->widget(), &ke);
677 ke.ignore(); 677 ke.ignore();
678 } 678 }
679} 679}
680void MainWindow::slotCopy() { 680void MainWindow::slotCopy() {
681 if (!currentSession() ) return; 681 if (!currentSession() ) return;
682 currentSession()->emulationHandler()->copy(); 682 currentSession()->emulationHandler()->copy();
683} 683}
684void MainWindow::slotPaste() { 684void MainWindow::slotPaste() {
685 if (!currentSession() ) return; 685 if (!currentSession() ) return;
686 currentSession()->emulationHandler()->paste(); 686 currentSession()->emulationHandler()->paste();
687} 687}
688 688
689/* 689/*
690 * Save the session 690 * Save the session
691 */ 691 */
692 692
693void MainWindow::slotSaveSession() { 693void MainWindow::slotSaveSession() {
694 if (!currentSession() ) { 694 if (!currentSession() ) {
695 QMessageBox::information(this, tr("Save Connection"), 695 QMessageBox::information(this, tr("Save Connection"),
696 tr("<qt>There is no Connection.</qt>"), 1 ); 696 tr("<qt>There is no Connection.</qt>"), 1 );
697 return; 697 return;
698 } 698 }
699 manager()->add( currentSession()->profile() ); 699 manager()->add( currentSession()->profile() );
700 manager()->save(); 700 manager()->save();
701 populateProfiles(); 701 populateProfiles();
702} 702}
703void MainWindow::slotSaveHistory() { 703void MainWindow::slotSaveHistory() {
704 QMap<QString, QStringList> map; 704 QMap<QString, QStringList> map;
705 QStringList text; 705 QStringList text;
706 text << "text/plain"; 706 text << "text/plain";
707 map.insert(tr("History"), text ); 707 map.insert(tr("History"), text );
708 QString filename = Opie::OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); 708 QString filename = Opie::OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map);
709 if (filename.isEmpty() ) return; 709 if (filename.isEmpty() ) return;
710 710
711 QFileInfo info(filename); 711 QFileInfo info(filename);
712 712
713 DocLnk nf; 713 DocLnk nf;
714 nf.setType("text/plain"); 714 nf.setType("text/plain");
715 nf.setFile(filename); 715 nf.setFile(filename);
716 nf.setName(info.fileName()); 716 nf.setName(info.fileName());
717 717
718 718
719 QFile file(filename); 719 QFile file(filename);
720 file.open(IO_WriteOnly ); 720 file.open(IO_WriteOnly );
721 QTextStream str(&file ); 721 QTextStream str(&file );
722 if ( currentSession() ) 722 if ( currentSession() )
723 currentSession()->emulationHandler()->emulation()->streamHistory(&str); 723 currentSession()->emulationHandler()->emulation()->streamHistory(&str);
724 724
725 file.close(); 725 file.close();
726 nf.writeLink(); 726 nf.writeLink();
727} 727}
diff --git a/noncore/apps/opie-console/profileeditordialog.cpp b/noncore/apps/opie-console/profileeditordialog.cpp
index 979e89d..6e1e23e 100644
--- a/noncore/apps/opie-console/profileeditordialog.cpp
+++ b/noncore/apps/opie-console/profileeditordialog.cpp
@@ -1,241 +1,241 @@
1#include <qlayout.h> 1#include <qlayout.h>
2#include <qlineedit.h> 2#include <qlineedit.h>
3#include <qlabel.h> 3#include <qlabel.h>
4#include <qmessagebox.h> 4#include <qmessagebox.h>
5#include <qcombobox.h> 5#include <qcombobox.h>
6#include <qcheckbox.h> 6#include <qcheckbox.h>
7#include <qscrollview.h> 7#include <qscrollview.h>
8 8
9#include "metafactory.h" 9#include "metafactory.h"
10#include "profileeditordialog.h" 10#include "profileeditordialog.h"
11 11
12namespace { 12namespace {
13 void setCurrent( const QString& str, QComboBox* bo ) { 13 void setCurrent( const QString& str, QComboBox* bo ) {
14 for (int i = 0; i < bo->count(); i++ ) { 14 for (int i = 0; i < bo->count(); i++ ) {
15 if ( bo->text(i) == str ) { 15 if ( bo->text(i) == str ) {
16 bo->setCurrentItem( i ); 16 bo->setCurrentItem( i );
17 } 17 }
18 } 18 }
19 }; 19 };
20} 20}
21 21
22ProfileEditorDialog::ProfileEditorDialog( MetaFactory* fact, 22ProfileEditorDialog::ProfileEditorDialog( MetaFactory* fact,
23 const Profile& prof ) 23 const Profile& prof )
24 : QDialog(0, 0, TRUE), m_fact( fact ), m_prof( prof ) 24 : QDialog(0, 0, TRUE), m_fact( fact ), m_prof( prof )
25{ 25{
26 initUI(); 26 initUI();
27 27
28 // Apply current profile 28 // Apply current profile
29 // plugin_plugin->load(profile); 29 // plugin_plugin->load(profile);
30 // ... (reset profile name line edit etc.) 30 // ... (reset profile name line edit etc.)
31} 31}
32 32
33ProfileEditorDialog::ProfileEditorDialog( MetaFactory* fact ) 33ProfileEditorDialog::ProfileEditorDialog( MetaFactory* fact )
34 : QDialog(0, 0, TRUE), m_fact( fact ) 34 : QDialog(0, 0, TRUE), m_fact( fact )
35{ 35{
36 // Default profile 36 // Default profile
37 m_prof = Profile(tr("New Profile"), "serial", "default", Profile::Black, Profile::White, Profile::VT102); 37 m_prof = Profile(tr("New Profile"), "serial", "default", Profile::Black, Profile::White, Profile::VT102);
38 38
39 initUI(); 39 initUI();
40 40
41 // Apply current profile 41 // Apply current profile
42 // plugin_plugin->load(profile); 42 // plugin_plugin->load(profile);
43} 43}
44 44
45Profile ProfileEditorDialog::profile() const 45Profile ProfileEditorDialog::profile() const
46{ 46{
47 return m_prof; 47 return m_prof;
48} 48}
49 49
50void ProfileEditorDialog::initUI() 50void ProfileEditorDialog::initUI()
51{ 51{
52 m_con = m_term = m_key = 0l; 52 m_con = m_term = m_key = 0l;
53 53
54 54
55 QVBoxLayout *mainLayout = new QVBoxLayout( this ); 55 QVBoxLayout *mainLayout = new QVBoxLayout( this );
56 tabWidget = new OTabWidget( this ); 56 tabWidget = new OTabWidget( this );
57 tabWidget->setTabStyle(OTabWidget::TextTab); 57 tabWidget->setTabStyle(OTabWidget::TextTab);
58 mainLayout->add(tabWidget); 58 mainLayout->add(tabWidget);
59 59
60 /* base tabs */ 60 /* base tabs */
61 tabprof = new QWidget(this); 61 tabprof = new QWidget(this);
62 m_tabTerm = new QWidget(this); 62 m_tabTerm = new QWidget(this);
63 m_tabCon = new QWidget(this); 63 m_tabCon = new QWidget(this);
64 m_tabKey = new QWidget(this); 64 m_tabKey = new QWidget(this);
65 65
66 m_svCon = new QScrollView( m_tabCon ); 66 m_svCon = new QScrollView( m_tabCon );
67 m_svCon->setResizePolicy( QScrollView::AutoOneFit ); 67 m_svCon->setResizePolicy( QScrollView::AutoOneFit );
68 //m_svCon->setHScrollBarMode( QScrollView::AlwaysOff ); 68 //m_svCon->setHScrollBarMode( QScrollView::AlwaysOff );
69 m_svCon->setFrameShape( QFrame::NoFrame ); 69 m_svCon->setFrameShape( QFrame::NoFrame );
70 m_svTerm = new QScrollView( m_tabTerm ); 70 m_svTerm = new QScrollView( m_tabTerm );
71 m_svTerm->setResizePolicy( QScrollView::AutoOneFit ); 71 m_svTerm->setResizePolicy( QScrollView::AutoOneFit );
72 //m_svTerm->setHScrollBarMode( QScrollView::AlwaysOff ); 72 //m_svTerm->setHScrollBarMode( QScrollView::AlwaysOff );
73 m_svTerm->setFrameShape( QFrame::NoFrame ); 73 m_svTerm->setFrameShape( QFrame::NoFrame );
74 74
75 /* base layout for tabs */ 75 /* base layout for tabs */
76 m_layCon = new QHBoxLayout( m_tabCon , 2 ); 76 m_layCon = new QHBoxLayout( m_tabCon , 2 );
77 m_layTerm = new QHBoxLayout( m_tabTerm, 2 ); 77 m_layTerm = new QHBoxLayout( m_tabTerm, 2 );
78 m_layKey = new QHBoxLayout( m_tabKey, 2 ); 78 m_layKey = new QHBoxLayout( m_tabKey, 2 );
79 79
80 m_layCon->addWidget( m_svCon ); 80 m_layCon->addWidget( m_svCon );
81 m_layTerm->addWidget( m_svTerm ); 81 m_layTerm->addWidget( m_svTerm );
82 82
83 // profile tab 83 // profile tab
84 84
85 QLabel *name = new QLabel(QObject::tr("Profile name"), tabprof); 85 QLabel *name = new QLabel(QObject::tr("Profile name"), tabprof);
86 m_name = new QLineEdit(tabprof); 86 m_name = new QLineEdit(tabprof);
87 QLabel *con = new QLabel(tr("Connection"), tabprof ); 87 QLabel *con = new QLabel(tr("Connection"), tabprof );
88 QLabel *term = new QLabel(tr("Terminal"), tabprof ); 88 QLabel *term = new QLabel(tr("Terminal"), tabprof );
89 m_conCmb = new QComboBox( tabprof ); 89 m_conCmb = new QComboBox( tabprof );
90 m_termCmb = new QComboBox( tabprof ); 90 m_termCmb = new QComboBox( tabprof );
91 m_autoConnect = new QCheckBox(tr("Auto connect after load"), tabprof); 91 m_autoConnect = new QCheckBox(tr("Auto connect after load"), tabprof);
92 92
93 // layouting 93 // layouting
94 QVBoxLayout *vbox3 = new QVBoxLayout(tabprof, 2); 94 QVBoxLayout *vbox3 = new QVBoxLayout(tabprof, 2);
95 vbox3->add(name); 95 vbox3->add(name);
96 vbox3->add(m_name); 96 vbox3->add(m_name);
97 vbox3->add(con ); 97 vbox3->add(con );
98 vbox3->add(m_conCmb ); 98 vbox3->add(m_conCmb );
99 vbox3->add(term ); 99 vbox3->add(term );
100 vbox3->add(m_termCmb ); 100 vbox3->add(m_termCmb );
101 vbox3->add(m_autoConnect); 101 vbox3->add(m_autoConnect);
102 vbox3->addStretch(1); 102 vbox3->addStretch(1);
103 103
104 m_showconntab = 0; 104 m_showconntab = 0;
105 tabWidget->addTab(tabprof, "", QObject::tr("Profile")); 105 tabWidget->addTab(tabprof, "", QObject::tr("Profile"));
106 tabWidget->addTab(m_tabCon, "", QObject::tr("Connection")); 106 tabWidget->addTab(m_tabCon, "", QObject::tr("Connection"));
107 tabWidget->addTab(m_tabTerm, "", QObject::tr("Terminal")); 107 tabWidget->addTab(m_tabTerm, "", QObject::tr("Terminal"));
108 tabWidget->addTab(m_tabKey, "", QObject::tr("Special Keys")); 108 tabWidget->addTab(m_tabKey, "", QObject::tr("Special Keys"));
109 tabWidget->setCurrentTab( tabprof ); 109 tabWidget->setCurrentTab( tabprof );
110 110
111 111
112 // fill the comboboxes 112 // fill the comboboxes
113 QStringList list = m_fact->connectionWidgets(); 113 QStringList list = m_fact->connectionWidgets();
114 QStringList::Iterator it; 114 QStringList::Iterator it;
115 for (it =list.begin(); it != list.end(); ++it ) { 115 for (it =list.begin(); it != list.end(); ++it ) {
116 m_conCmb->insertItem( (*it) ); 116 m_conCmb->insertItem( (*it) );
117 } 117 }
118 list = m_fact->terminalWidgets(); 118 list = m_fact->terminalWidgets();
119 for (it =list.begin(); it != list.end(); ++it ) { 119 for (it =list.begin(); it != list.end(); ++it ) {
120 m_termCmb->insertItem( (*it) ); 120 m_termCmb->insertItem( (*it) );
121 } 121 }
122 122
123 // load profile values 123 // load profile values
124 m_name->setText(m_prof.name()); 124 m_name->setText(m_prof.name());
125 slotKeyActivated( "Default Keyboard" ); 125 slotKeyActivated( "Default Keyboard" );
126 setCurrent( m_fact->external(m_prof.ioLayerName() ), m_conCmb ); 126 setCurrent( m_fact->external(m_prof.ioLayerName() ), m_conCmb );
127 setCurrent( m_fact->external(m_prof.terminalName() ), m_termCmb ); 127 setCurrent( m_fact->external(m_prof.terminalName() ), m_termCmb );
128 slotConActivated( m_fact->external(m_prof.ioLayerName() ) ); 128 slotConActivated( m_fact->external(m_prof.ioLayerName() ) );
129 slotTermActivated( m_fact->external(m_prof.terminalName() ) ); 129 slotTermActivated( m_fact->external(m_prof.terminalName() ) );
130 m_autoConnect->setChecked(m_prof.autoConnect()); 130 m_autoConnect->setChecked(m_prof.autoConnect());
131 131
132 132
133 // signal and slots 133 // signal and slots
134 connect(m_conCmb, SIGNAL(activated(const QString& ) ), 134 connect(m_conCmb, SIGNAL(activated(const QString&) ),
135 this, SLOT(slotConActivated(const QString&) ) ); 135 this, SLOT(slotConActivated(const QString&) ) );
136 connect(m_termCmb, SIGNAL(activated(const QString& ) ), 136 connect(m_termCmb, SIGNAL(activated(const QString&) ),
137 this, SLOT(slotTermActivated(const QString& ) ) ); 137 this, SLOT(slotTermActivated(const QString&) ) );
138 138
139} 139}
140 140
141ProfileEditorDialog::~ProfileEditorDialog() { 141ProfileEditorDialog::~ProfileEditorDialog() {
142 142
143} 143}
144void ProfileEditorDialog::accept() 144void ProfileEditorDialog::accept()
145{ 145{
146 if(profName().isEmpty()) 146 if(profName().isEmpty())
147 { 147 {
148 QMessageBox::information(this, 148 QMessageBox::information(this,
149 QObject::tr("Invalid profile"), 149 QObject::tr("Invalid profile"),
150 QObject::tr("Please enter a profile name.")); 150 QObject::tr("Please enter a profile name."));
151 return; 151 return;
152 } 152 }
153 // Save profile and plugin profile 153 // Save profile and plugin profile
154 //if(plugin_plugin) plugin_plugin->save(); 154 //if(plugin_plugin) plugin_plugin->save();
155 155
156 // Save general values 156 // Save general values
157 m_prof.setName( profName() ); 157 m_prof.setName( profName() );
158 m_prof.setIOLayer( m_fact->internal(m_conCmb ->currentText() ) ); 158 m_prof.setIOLayer( m_fact->internal(m_conCmb ->currentText() ) );
159 m_prof.setTerminalName( m_fact->internal(m_termCmb->currentText() ) ); 159 m_prof.setTerminalName( m_fact->internal(m_termCmb->currentText() ) );
160 m_prof.setAutoConnect( m_autoConnect->isChecked() ); 160 m_prof.setAutoConnect( m_autoConnect->isChecked() );
161 161
162 if (m_con ) 162 if (m_con )
163 m_con->save( m_prof ); 163 m_con->save( m_prof );
164 if (m_term ) 164 if (m_term )
165 m_term->save( m_prof ); 165 m_term->save( m_prof );
166 if (m_key) 166 if (m_key)
167 m_key->save( m_prof ); 167 m_key->save( m_prof );
168 168
169 QDialog::accept(); 169 QDialog::accept();
170} 170}
171 171
172 172
173QString ProfileEditorDialog::profName()const 173QString ProfileEditorDialog::profName()const
174{ 174{
175 return m_name->text(); 175 return m_name->text();
176} 176}
177 177
178QCString ProfileEditorDialog::profType()const 178QCString ProfileEditorDialog::profType()const
179{ 179{
180 /*QStringList w = m_fact->configWidgets(); 180 /*QStringList w = m_fact->configWidgets();
181 for(QStringList::Iterator it = w.begin(); it != w.end(); it++) 181 for(QStringList::Iterator it = w.begin(); it != w.end(); it++)
182 if(device_box->currentText() == m_fact->name((*it))) return (*it); 182 if(device_box->currentText() == m_fact->name((*it))) return (*it);
183 */ 183 */
184 return QCString(); 184 return QCString();
185} 185}
186/* 186/*
187 * we need to switch the widget 187 * we need to switch the widget
188 */ 188 */
189void ProfileEditorDialog::slotConActivated( const QString& str ) { 189void ProfileEditorDialog::slotConActivated( const QString& str ) {
190 190
191 delete m_con; 191 delete m_con;
192 192
193 m_con = m_fact->newConnectionPlugin( str, m_svCon->viewport() ); 193 m_con = m_fact->newConnectionPlugin( str, m_svCon->viewport() );
194 194
195 if ( !m_con ) { 195 if ( !m_con ) {
196 m_con = new NoOptions( str, m_svCon->viewport(), "name"); 196 m_con = new NoOptions( str, m_svCon->viewport(), "name");
197 } 197 }
198 198
199 // FIXME ugly hack right. Right solution would be to look into the layer and see if it 199 // FIXME ugly hack right. Right solution would be to look into the layer and see if it
200 // supports auto connect and then set it as prefered 200 // supports auto connect and then set it as prefered
201 if ( m_conCmb ->currentText() == tr("Local Console") ) { 201 if ( m_conCmb ->currentText() == tr("Local Console") ) {
202 m_autoConnect->setChecked( true ); 202 m_autoConnect->setChecked( true );
203 m_prof.writeEntry("Terminal", Profile::Linux ); 203 m_prof.writeEntry("Terminal", Profile::Linux );
204 slotTermActivated( m_fact->external (m_prof.terminalName() ) ); 204 slotTermActivated( m_fact->external (m_prof.terminalName() ) );
205 } else { 205 } else {
206 m_prof.writeEntry("Terminal", Profile::VT102 ); 206 m_prof.writeEntry("Terminal", Profile::VT102 );
207 slotTermActivated( m_fact->external (m_prof.terminalName() ) ); 207 slotTermActivated( m_fact->external (m_prof.terminalName() ) );
208 m_autoConnect->setChecked( false ); 208 m_autoConnect->setChecked( false );
209 } 209 }
210 210
211 m_con->load( m_prof ); 211 m_con->load( m_prof );
212 m_svCon->addChild( m_con ); 212 m_svCon->addChild( m_con );
213} 213}
214 214
215 215
216/* 216/*
217 * we need to switch the widget 217 * we need to switch the widget
218 */ 218 */
219void ProfileEditorDialog::slotTermActivated( const QString& str ) { 219void ProfileEditorDialog::slotTermActivated( const QString& str ) {
220 220
221 delete m_term; 221 delete m_term;
222 222
223 m_term = m_fact->newTerminalPlugin( str, m_svTerm->viewport() ); 223 m_term = m_fact->newTerminalPlugin( str, m_svTerm->viewport() );
224 224
225 if ( m_term ) { 225 if ( m_term ) {
226 m_term->load( m_prof ); 226 m_term->load( m_prof );
227 m_svTerm->addChild( m_term ); 227 m_svTerm->addChild( m_term );
228 } 228 }
229} 229}
230 230
231void ProfileEditorDialog::slotKeyActivated(const QString &str) { 231void ProfileEditorDialog::slotKeyActivated(const QString &str) {
232 delete m_key; 232 delete m_key;
233 m_key = m_fact->newKeyboardPlugin( str, m_tabKey ); 233 m_key = m_fact->newKeyboardPlugin( str, m_tabKey );
234 234
235 if (m_key) { 235 if (m_key) {
236 236
237 m_key->load(m_prof); 237 m_key->load(m_prof);
238 m_layKey->addWidget(m_key); 238 m_layKey->addWidget(m_key);
239 } 239 }
240 240
241} 241}
diff --git a/noncore/apps/opie-console/session.cpp b/noncore/apps/opie-console/session.cpp
index 1034ede..b7f14c5 100644
--- a/noncore/apps/opie-console/session.cpp
+++ b/noncore/apps/opie-console/session.cpp
@@ -1,115 +1,115 @@
1 1
2 2
3#include "file_layer.h" 3#include "file_layer.h"
4#include "emulation_handler.h" 4#include "emulation_handler.h"
5#include "session.h" 5#include "session.h"
6 6
7 7
8Session::Session() { 8Session::Session() {
9 m_widget = 0l; 9 m_widget = 0l;
10 m_layer = 0l; 10 m_layer = 0l;
11 m_emu = 0l; 11 m_emu = 0l;
12 m_transfer = 0l; 12 m_transfer = 0l;
13} 13}
14Session::Session( const QString& na, QWidgetStack* widget, IOLayer* lay) 14Session::Session( const QString& na, QWidgetStack* widget, IOLayer* lay)
15 : m_name( na ), m_widget( widget ), m_layer( lay ) 15 : m_name( na ), m_widget( widget ), m_layer( lay )
16{ 16{
17// m_widLay = 0l; 17// m_widLay = 0l;
18// m_emLay = 0l; 18// m_emLay = 0l;
19 m_emu = 0l; 19 m_emu = 0l;
20} 20}
21Session::~Session() { 21Session::~Session() {
22 delete m_layer; 22 delete m_layer;
23 delete m_emu; 23 delete m_emu;
24 delete m_widget; 24 delete m_widget;
25 /* the widget layer should be deleted by the m_widget */ 25 /* the widget layer should be deleted by the m_widget */
26} 26}
27QString Session::name()const { 27QString Session::name()const {
28 return m_name; 28 return m_name;
29} 29}
30QWidgetStack* Session::widgetStack() { 30QWidgetStack* Session::widgetStack() {
31 return m_widget; 31 return m_widget;
32} 32}
33IOLayer* Session::layer() { 33IOLayer* Session::layer() {
34 return m_layer; 34 return m_layer;
35} 35}
36EmulationHandler* Session::emulationHandler() { 36EmulationHandler* Session::emulationHandler() {
37 return m_emu; 37 return m_emu;
38} 38}
39QWidget* Session::widget() { 39QWidget* Session::widget() {
40 if (!m_emu ) 40 if (!m_emu )
41 return 0l; 41 return 0l;
42 42
43 return m_emu->widget(); 43 return m_emu->widget();
44} 44}
45Profile Session::profile()const { 45Profile Session::profile()const {
46 return m_prof; 46 return m_prof;
47} 47}
48/* 48/*
49WidgetLayer* Session::emulationWidget() { 49WidgetLayer* Session::emulationWidget() {
50 return m_widLay; 50 return m_widLay;
51} 51}
52*/ 52*/
53void Session::connect() { 53void Session::connect() {
54 if ( !m_layer || !m_emu ) 54 if ( !m_layer || !m_emu )
55 return; 55 return;
56 56
57 QObject::connect(m_layer, SIGNAL(received(const QByteArray&) ), 57 QObject::connect(m_layer, SIGNAL(received(const QByteArray&) ),
58 m_emu, SLOT(recv(const QByteArray&) ) ); 58 m_emu, SLOT(recv(const QByteArray&) ) );
59 QObject::connect(m_emu, SIGNAL(send(const QByteArray&) ), 59 QObject::connect(m_emu, SIGNAL(send(const QByteArray&) ),
60 m_layer, SLOT(send(const QByteArray&) ) ); 60 m_layer, SLOT(send(const QByteArray&) ) );
61 QObject::connect(m_emu, SIGNAL(changeSize(int, int) ), 61 QObject::connect(m_emu, SIGNAL(changeSize(int,int) ),
62 m_layer, SLOT(setSize(int, int) ) ); 62 m_layer, SLOT(setSize(int,int) ) );
63} 63}
64 64
65void Session::disconnect() { 65void Session::disconnect() {
66 66
67 if ( !m_layer || !m_emu ) 67 if ( !m_layer || !m_emu )
68 return; 68 return;
69 69
70 QObject::disconnect(m_layer, SIGNAL(received(const QByteArray&) ), 70 QObject::disconnect(m_layer, SIGNAL(received(const QByteArray&) ),
71 m_emu, SLOT(recv(const QByteArray&) ) ); 71 m_emu, SLOT(recv(const QByteArray&) ) );
72 QObject::disconnect(m_emu, SIGNAL(send(const QByteArray&) ), 72 QObject::disconnect(m_emu, SIGNAL(send(const QByteArray&) ),
73 m_layer, SLOT(send(const QByteArray&) ) ); 73 m_layer, SLOT(send(const QByteArray&) ) );
74} 74}
75 75
76void Session::setName( const QString& na){ 76void Session::setName( const QString& na){
77 m_name = na; 77 m_name = na;
78} 78}
79 79
80void Session::setWidgetStack( QWidgetStack* wid ) { 80void Session::setWidgetStack( QWidgetStack* wid ) {
81 delete m_emu; 81 delete m_emu;
82 m_emu = 0l; 82 m_emu = 0l;
83 delete m_widget; 83 delete m_widget;
84 /* the EmulationLayer was destroyed... */ 84 /* the EmulationLayer was destroyed... */
85 85
86 m_widget = wid; 86 m_widget = wid;
87} 87}
88void Session::setIOLayer( IOLayer* lay ) { 88void Session::setIOLayer( IOLayer* lay ) {
89 delete m_layer; 89 delete m_layer;
90 m_layer = lay; 90 m_layer = lay;
91} 91}
92 92
93void Session::setEmulationHandler( EmulationHandler* lay ) { 93void Session::setEmulationHandler( EmulationHandler* lay ) {
94 delete m_emu; 94 delete m_emu;
95 m_emu = lay; 95 m_emu = lay;
96} 96}
97void Session::setProfile( const Profile& prof ) { 97void Session::setProfile( const Profile& prof ) {
98 m_prof = prof; 98 m_prof = prof;
99} 99}
100/* 100/*
101void Session::setEmulationWidget( WidgetLayer* lay ) { 101void Session::setEmulationWidget( WidgetLayer* lay ) {
102 delete m_widLay; 102 delete m_widLay;
103 m_widLay = lay; 103 m_widLay = lay;
104} 104}
105*/ 105*/
106void Session::setTransferDialog(QWidget *d) 106void Session::setTransferDialog(QWidget *d)
107{ 107{
108 m_transfer = d; 108 m_transfer = d;
109} 109}
110 110
111QWidget *Session::transferDialog() 111QWidget *Session::transferDialog()
112{ 112{
113 return m_transfer; 113 return m_transfer;
114} 114}
115 115
diff --git a/noncore/apps/opie-console/sz_transfer.cpp b/noncore/apps/opie-console/sz_transfer.cpp
index c47e73e..2f82417 100644
--- a/noncore/apps/opie-console/sz_transfer.cpp
+++ b/noncore/apps/opie-console/sz_transfer.cpp
@@ -1,84 +1,84 @@
1 1
2#include "sz_transfer.h" 2#include "sz_transfer.h"
3#include <qfile.h> 3#include <qfile.h>
4#include <stdio.h> 4#include <stdio.h>
5#include <sys/termios.h> 5#include <sys/termios.h>
6 6
7 7
8 8
9SzTransfer::SzTransfer(Type t, IOLayer *layer) : FileTransferLayer(layer), m_t(t) 9SzTransfer::SzTransfer(Type t, IOLayer *layer) : FileTransferLayer(layer), m_t(t)
10{ 10{
11} 11}
12 12
13SzTransfer::~SzTransfer() { 13SzTransfer::~SzTransfer() {
14} 14}
15 15
16void SzTransfer::sendFile(const QFile& file) { 16void SzTransfer::sendFile(const QFile& file) {
17 17
18 sendFile(file.name()); 18 sendFile(file.name());
19} 19}
20 20
21void SzTransfer::sendFile(const QString& file) { 21void SzTransfer::sendFile(const QString& file) {
22 22
23 //setcbreak(2); /* raw no echo */ 23 //setcbreak(2); /* raw no echo */
24 24
25 proc = new OProcess; 25 proc = new OProcess;
26 *proc << "sz"; 26 *proc << "sz";
27 *proc << "-v" << "-v" << "-b" << file; 27 *proc << "-v" << "-v" << "-b" << file;
28 connect(proc, SIGNAL(processExited(OProcess *)), 28 connect(proc, SIGNAL(processExited(OProcess*)),
29 this, SLOT(sent())); 29 this, SLOT(sent()));
30 connect(proc, SIGNAL(receivedStdout(OProcess *, char *, int)), 30 connect(proc, SIGNAL(receivedStdout(OProcess*,char*,int)),
31 this, SLOT(SzReceivedStdout(OProcess *, char *, int))); 31 this, SLOT(SzReceivedStdout(OProcess*,char*,int)));
32 connect(proc, SIGNAL(receivedStderr(OProcess *, char *, int)), 32 connect(proc, SIGNAL(receivedStderr(OProcess*,char*,int)),
33 this, SLOT(SzReceivedStderr(OProcess *, char *, int))); 33 this, SLOT(SzReceivedStderr(OProcess*,char*,int)));
34 connect(layer(), SIGNAL(received(const QByteArray &)), 34 connect(layer(), SIGNAL(received(const QByteArray&)),
35 this, SLOT(receivedStdin(const QByteArray &))); 35 this, SLOT(receivedStdin(const QByteArray&)));
36 proc->start(OProcess::NotifyOnExit, OProcess::All); 36 proc->start(OProcess::NotifyOnExit, OProcess::All);
37 37
38} 38}
39 39
40void SzTransfer::SzReceivedStdout(OProcess *, char *buffer, int buflen) { 40void SzTransfer::SzReceivedStdout(OProcess *, char *buffer, int buflen) {
41 41
42 qWarning("recieved from sz on stdout %d bytes", buflen); 42 qWarning("recieved from sz on stdout %d bytes", buflen);
43 43
44 QByteArray data(buflen); 44 QByteArray data(buflen);
45 data.fill(*buffer, buflen); 45 data.fill(*buffer, buflen);
46 for (uint i = 0; i < data.count(); i++ ) { 46 for (uint i = 0; i < data.count(); i++ ) {
47 printf("%c", buffer[i] ); 47 printf("%c", buffer[i] );
48 } 48 }
49 printf("\n"); 49 printf("\n");
50 50
51 // send out through the io layer 51 // send out through the io layer
52 layer()->send(data); 52 layer()->send(data);
53} 53}
54 54
55void SzTransfer::SzReceivedStderr(OProcess *, char *buffer, int length) { 55void SzTransfer::SzReceivedStderr(OProcess *, char *buffer, int length) {
56 56
57 // parse and show data in a progress dialog/widget 57 // parse and show data in a progress dialog/widget
58 printf("stderr:\n"); 58 printf("stderr:\n");
59 //for (int i = 0; i < length; i++) 59 //for (int i = 0; i < length; i++)
60 // printf("%c", buffer[i]); 60 // printf("%c", buffer[i]);
61 //printf("\n"); 61 //printf("\n");
62} 62}
63 63
64void SzTransfer::receivedStdin(const QByteArray &data) { 64void SzTransfer::receivedStdin(const QByteArray &data) {
65 65
66 qWarning("recieved from io_serial %d bytes", data.size()); 66 qWarning("recieved from io_serial %d bytes", data.size());
67 67
68 // recieved data from the io layer goes to sz 68 // recieved data from the io layer goes to sz
69 proc->writeStdin(data.data(), data.size()); 69 proc->writeStdin(data.data(), data.size());
70 70
71} 71}
72 72
73void SzTransfer::sent() { 73void SzTransfer::sent() {
74 74
75 qWarning("sent file"); 75 qWarning("sent file");
76 76
77 //setcbreak(0); /* default */ 77 //setcbreak(0); /* default */
78 78
79 79
80 delete proc; 80 delete proc;
81 disconnect(layer(), SIGNAL(received(const QByteArray &)), 81 disconnect(layer(), SIGNAL(received(const QByteArray&)),
82 this, SLOT(receivedStdin(const QByteArray &))); 82 this, SLOT(receivedStdin(const QByteArray&)));
83 83
84} 84}
diff --git a/noncore/apps/opie-console/test/senderui.cpp b/noncore/apps/opie-console/test/senderui.cpp
index 4a7202d..b1725db 100644
--- a/noncore/apps/opie-console/test/senderui.cpp
+++ b/noncore/apps/opie-console/test/senderui.cpp
@@ -1,77 +1,77 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include <stdio.h> 2#include <stdio.h>
3#include <fcntl.h> 3#include <fcntl.h>
4#include <sys/termios.h> 4#include <sys/termios.h>
5 5
6#include <qmultilineedit.h> 6#include <qmultilineedit.h>
7#include <qsocketnotifier.h> 7#include <qsocketnotifier.h>
8 8
9#include "../profile.h" 9#include "../profile.h"
10#include "../io_serial.h" 10#include "../io_serial.h"
11#include "../filetransfer.h" 11#include "../filetransfer.h"
12#include "../filereceive.h" 12#include "../filereceive.h"
13 13
14#include <opie2/oprocess.h> 14#include <opie2/oprocess.h>
15 15
16#include "senderui.h" 16#include "senderui.h"
17 17
18SenderUI::SenderUI() 18SenderUI::SenderUI()
19 : Sender() { 19 : Sender() {
20 20
21 /* we do that manually */ 21 /* we do that manually */
22 Profile prof; 22 Profile prof;
23 QString str = "/dev/bty0"; 23 QString str = "/dev/bty0";
24 prof.writeEntry("Device",str ); 24 prof.writeEntry("Device",str );
25 prof.writeEntry("Baud", 19200 ); 25 prof.writeEntry("Baud", 19200 );
26 26
27 qWarning("prof " + prof.readEntry("Device") + " " + str); 27 qWarning("prof " + prof.readEntry("Device") + " " + str);
28 ser = new IOSerial(prof); 28 ser = new IOSerial(prof);
29 connect(ser, SIGNAL(received(const QByteArray& ) ), 29 connect(ser, SIGNAL(received(const QByteArray&) ),
30 this, SLOT(got(const QByteArray&) ) ); 30 this, SLOT(got(const QByteArray&) ) );
31 31
32 if ( ser->open() ) 32 if ( ser->open() )
33 qWarning("opened!!!"); 33 qWarning("opened!!!");
34 else 34 else
35 qWarning("could not open"); 35 qWarning("could not open");
36 36
37 37
38} 38}
39SenderUI::~SenderUI() { 39SenderUI::~SenderUI() {
40 40
41} 41}
42void SenderUI::slotSendFile() { 42void SenderUI::slotSendFile() {
43 43
44 sz = new FileTransfer(FileTransfer::SY, ser); 44 sz = new FileTransfer(FileTransfer::SY, ser);
45 sz->sendFile("/home/ich/bootopie-v06-13.jffs2"); 45 sz->sendFile("/home/ich/bootopie-v06-13.jffs2");
46 46
47 connect (sz, SIGNAL(sent()), 47 connect (sz, SIGNAL(sent()),
48 this, SLOT(fileTransComplete())); 48 this, SLOT(fileTransComplete()));
49} 49}
50 50
51void SenderUI::slotSend() { 51void SenderUI::slotSend() {
52 QCString str = MultiLineEdit1->text().utf8(); 52 QCString str = MultiLineEdit1->text().utf8();
53 qWarning("sending: %s", str.data() ); 53 qWarning("sending: %s", str.data() );
54 str = str.replace( QRegExp("\n"), "\r"); 54 str = str.replace( QRegExp("\n"), "\r");
55 ser->send( str ); 55 ser->send( str );
56} 56}
57void SenderUI::got(const QByteArray& ar) { 57void SenderUI::got(const QByteArray& ar) {
58 qWarning("got:"); 58 qWarning("got:");
59 for ( uint i = 0; i < ar.count(); i++ ) { 59 for ( uint i = 0; i < ar.count(); i++ ) {
60 printf("%c", ar[i] ); 60 printf("%c", ar[i] );
61 } 61 }
62 printf("\n"); 62 printf("\n");
63} 63}
64 64
65void SenderUI::fileTransComplete() { 65void SenderUI::fileTransComplete() {
66 66
67 qWarning("file transfer complete"); 67 qWarning("file transfer complete");
68} 68}
69void SenderUI::send() { 69void SenderUI::send() {
70 70
71} 71}
72void SenderUI::slotRev(){ 72void SenderUI::slotRev(){
73qWarning("Going to receive!"); 73qWarning("Going to receive!");
74FileReceive *rev = new FileReceive( FileReceive::SZ, ser ); 74FileReceive *rev = new FileReceive( FileReceive::SZ, ser );
75rev->receive(); 75rev->receive();
76 76
77} 77}
diff --git a/noncore/apps/opie-console/transferdialog.cpp b/noncore/apps/opie-console/transferdialog.cpp
index 30e7caf..d494a6c 100644
--- a/noncore/apps/opie-console/transferdialog.cpp
+++ b/noncore/apps/opie-console/transferdialog.cpp
@@ -1,275 +1,275 @@
1#include <qlayout.h> 1#include <qlayout.h>
2#include <qcombobox.h> 2#include <qcombobox.h>
3#include <qlabel.h> 3#include <qlabel.h>
4#include <qlineedit.h> 4#include <qlineedit.h>
5#include <qpushbutton.h> 5#include <qpushbutton.h>
6#include <qmessagebox.h> 6#include <qmessagebox.h>
7#include <qprogressbar.h> 7#include <qprogressbar.h>
8#include <qradiobutton.h> 8#include <qradiobutton.h>
9#include <qbuttongroup.h> 9#include <qbuttongroup.h>
10 10
11#include <opie2/ofiledialog.h> 11#include <opie2/ofiledialog.h>
12 12
13#include "metafactory.h" 13#include "metafactory.h"
14#include "mainwindow.h" 14#include "mainwindow.h"
15 15
16#include "transferdialog.h" 16#include "transferdialog.h"
17 17
18TransferDialog::TransferDialog(QWidget *parent, MainWindow *mainwindow, const char *) 18TransferDialog::TransferDialog(QWidget *parent, MainWindow *mainwindow, const char *)
19: QDialog(parent, 0l, false), m_win(mainwindow) 19: QDialog(parent, 0l, false), m_win(mainwindow)
20{ 20{
21 m_lay = 0l; 21 m_lay = 0l;
22 m_recvlay = 0l; 22 m_recvlay = 0l;
23 QVBoxLayout *vbox, *vbox2; 23 QVBoxLayout *vbox, *vbox2;
24 QHBoxLayout *hbox, *hbox2, *hbox3; 24 QHBoxLayout *hbox, *hbox2, *hbox3;
25 QLabel *file, *mode, *progress, *status; 25 QLabel *file, *mode, *progress, *status;
26 QButtonGroup *group; 26 QButtonGroup *group;
27 QRadioButton *mode_send, *mode_receive; 27 QRadioButton *mode_send, *mode_receive;
28 28
29 m_autocleanup = 0; 29 m_autocleanup = 0;
30 m_running = true; 30 m_running = true;
31 31
32 group = new QButtonGroup(QObject::tr("Transfer mode"), this); 32 group = new QButtonGroup(QObject::tr("Transfer mode"), this);
33 mode_send = new QRadioButton(QObject::tr("Send"), group); 33 mode_send = new QRadioButton(QObject::tr("Send"), group);
34 mode_receive = new QRadioButton(QObject::tr("Receive"), group); 34 mode_receive = new QRadioButton(QObject::tr("Receive"), group);
35 group->insert(mode_send, id_send); 35 group->insert(mode_send, id_send);
36 group->insert(mode_receive, id_receive); 36 group->insert(mode_receive, id_receive);
37 vbox2 = new QVBoxLayout(group, 2); 37 vbox2 = new QVBoxLayout(group, 2);
38 vbox2->addSpacing(10); 38 vbox2->addSpacing(10);
39 hbox3 = new QHBoxLayout(vbox2, 2); 39 hbox3 = new QHBoxLayout(vbox2, 2);
40 hbox3->add(mode_send); 40 hbox3->add(mode_send);
41 hbox3->add(mode_receive); 41 hbox3->add(mode_receive);
42 mode_send->setChecked(true); 42 mode_send->setChecked(true);
43 m_transfermode = id_send; 43 m_transfermode = id_send;
44 44
45 file = new QLabel(QObject::tr("Send file"), this); 45 file = new QLabel(QObject::tr("Send file"), this);
46 mode = new QLabel(QObject::tr("Transfer protocol"), this); 46 mode = new QLabel(QObject::tr("Transfer protocol"), this);
47 progress = new QLabel(QObject::tr("Progress"), this); 47 progress = new QLabel(QObject::tr("Progress"), this);
48 status = new QLabel(QObject::tr("Status"), this); 48 status = new QLabel(QObject::tr("Status"), this);
49 49
50 statusbar = new QLabel(QObject::tr("Ready"), this); 50 statusbar = new QLabel(QObject::tr("Ready"), this);
51 statusbar->setFrameStyle(QFrame::Panel | QFrame::Sunken); 51 statusbar->setFrameStyle(QFrame::Panel | QFrame::Sunken);
52 52
53 protocol = new QComboBox(this); 53 protocol = new QComboBox(this);
54 QStringList list = m_win->factory()->fileTransferLayers(); 54 QStringList list = m_win->factory()->fileTransferLayers();
55 for (QStringList::Iterator it = list.begin(); it != list.end(); ++it) 55 for (QStringList::Iterator it = list.begin(); it != list.end(); ++it)
56 protocol->insertItem((*it)); 56 protocol->insertItem((*it));
57 57
58 filename = new QLineEdit(this); 58 filename = new QLineEdit(this);
59 59
60 progressbar = new QProgressBar(this); 60 progressbar = new QProgressBar(this);
61 progressbar->setProgress(0); 61 progressbar->setProgress(0);
62 62
63 selector = new QPushButton("...", this); 63 selector = new QPushButton("...", this);
64 ok = new QPushButton(QObject::tr("Start transfer"), this); 64 ok = new QPushButton(QObject::tr("Start transfer"), this);
65 cancel = new QPushButton(QObject::tr("Cancel"), this); 65 cancel = new QPushButton(QObject::tr("Cancel"), this);
66 66
67 vbox = new QVBoxLayout(this, 2); 67 vbox = new QVBoxLayout(this, 2);
68 vbox->add(group); 68 vbox->add(group);
69 vbox->add(file); 69 vbox->add(file);
70 hbox = new QHBoxLayout(vbox, 0); 70 hbox = new QHBoxLayout(vbox, 0);
71 hbox->add(filename); 71 hbox->add(filename);
72 hbox->add(selector); 72 hbox->add(selector);
73 vbox->add(mode); 73 vbox->add(mode);
74 vbox->add(protocol); 74 vbox->add(protocol);
75 vbox->add(progress); 75 vbox->add(progress);
76 vbox->add(progressbar); 76 vbox->add(progressbar);
77 vbox->add(status); 77 vbox->add(status);
78 vbox->add(statusbar); 78 vbox->add(statusbar);
79 vbox->addStretch(1); 79 vbox->addStretch(1);
80 hbox2 = new QHBoxLayout(vbox, 2); 80 hbox2 = new QHBoxLayout(vbox, 2);
81 hbox2->add(ok); 81 hbox2->add(ok);
82 hbox2->add(cancel); 82 hbox2->add(cancel);
83 83
84 setCaption(QObject::tr("File transfer")); 84 setCaption(QObject::tr("File transfer"));
85 show(); 85 show();
86 86
87 connect(selector, SIGNAL(clicked()), SLOT(slotFilename())); 87 connect(selector, SIGNAL(clicked()), SLOT(slotFilename()));
88 connect(ok, SIGNAL(clicked()), SLOT(slotTransfer())); 88 connect(ok, SIGNAL(clicked()), SLOT(slotTransfer()));
89 connect(cancel, SIGNAL(clicked()), SLOT(slotCancel())); 89 connect(cancel, SIGNAL(clicked()), SLOT(slotCancel()));
90 connect(group, SIGNAL(clicked(int)), SLOT(slotMode(int))); 90 connect(group, SIGNAL(clicked(int)), SLOT(slotMode(int)));
91} 91}
92 92
93TransferDialog::~TransferDialog() 93TransferDialog::~TransferDialog()
94{ 94{
95} 95}
96 96
97void TransferDialog::slotFilename() 97void TransferDialog::slotFilename()
98{ 98{
99 QString f; 99 QString f;
100 100
101 f = Opie::OFileDialog::getOpenFileName(0); 101 f = Opie::OFileDialog::getOpenFileName(0);
102 if(!f.isNull()) filename->setText(f); 102 if(!f.isNull()) filename->setText(f);
103} 103}
104 104
105void TransferDialog::slotTransfer() 105void TransferDialog::slotTransfer()
106{ 106{
107 if((m_transfermode == id_send) && (filename->text().isEmpty())) 107 if((m_transfermode == id_send) && (filename->text().isEmpty()))
108 { 108 {
109 QMessageBox::information(this, 109 QMessageBox::information(this,
110 QObject::tr("Attention"), 110 QObject::tr("Attention"),
111 QObject::tr("No file has been specified.")); 111 QObject::tr("No file has been specified."));
112 return; 112 return;
113 } 113 }
114 114
115 ok->setEnabled(false); 115 ok->setEnabled(false);
116 116
117 cleanup(); 117 cleanup();
118 m_autocleanup = 0; 118 m_autocleanup = 0;
119 119
120 if(m_transfermode == id_send) statusbar->setText(QObject::tr("Sending...")); 120 if(m_transfermode == id_send) statusbar->setText(QObject::tr("Sending..."));
121 else statusbar->setText(QObject::tr("Receiving...")); 121 else statusbar->setText(QObject::tr("Receiving..."));
122 122
123 if(m_transfermode == id_send) 123 if(m_transfermode == id_send)
124 { 124 {
125 m_lay = m_win->factory()->newFileTransfer(protocol->currentText(), m_win->currentSession()->layer()); 125 m_lay = m_win->factory()->newFileTransfer(protocol->currentText(), m_win->currentSession()->layer());
126 m_lay->sendFile(filename->text()); 126 m_lay->sendFile(filename->text());
127 127
128 connect(m_lay, SIGNAL(progress(const QString&, int, int, int, int, int)), 128 connect(m_lay, SIGNAL(progress(const QString&,int,int,int,int,int)),
129 SLOT(slotProgress(const QString&, int, int, int, int, int))); 129 SLOT(slotProgress(const QString&,int,int,int,int,int)));
130 connect(m_lay, SIGNAL(error(int, const QString&)), SLOT(slotError(int, const QString&))); 130 connect(m_lay, SIGNAL(error(int,const QString&)), SLOT(slotError(int,const QString&)));
131 connect(m_lay, SIGNAL(sent()), SLOT(slotSent())); 131 connect(m_lay, SIGNAL(sent()), SLOT(slotSent()));
132 } 132 }
133 else 133 else
134 { 134 {
135 m_recvlay = m_win->factory()->newReceive(protocol->currentText(), m_win->currentSession()->layer()); 135 m_recvlay = m_win->factory()->newReceive(protocol->currentText(), m_win->currentSession()->layer());
136 m_recvlay->receive(); 136 m_recvlay->receive();
137 137
138 connect(m_recvlay, SIGNAL(progress(const QString&, int, int, int, int, int)), 138 connect(m_recvlay, SIGNAL(progress(const QString&,int,int,int,int,int)),
139 SLOT(slotProgress(const QString&, int, int, int, int, int))); 139 SLOT(slotProgress(const QString&,int,int,int,int,int)));
140 connect(m_recvlay, SIGNAL(error(int, const QString&)), SLOT(slotError(int, const QString&))); 140 connect(m_recvlay, SIGNAL(error(int,const QString&)), SLOT(slotError(int,const QString&)));
141 connect(m_recvlay, SIGNAL(received(const QString&)), SLOT(slotReceived(const QString&))); 141 connect(m_recvlay, SIGNAL(received(const QString&)), SLOT(slotReceived(const QString&)));
142 } 142 }
143} 143}
144 144
145void TransferDialog::cleanup() 145void TransferDialog::cleanup()
146{ 146{
147 if(m_lay) 147 if(m_lay)
148 { 148 {
149 m_lay->cancel(); 149 m_lay->cancel();
150 delete m_lay; 150 delete m_lay;
151 m_lay = 0l; 151 m_lay = 0l;
152 } 152 }
153 if(m_recvlay) 153 if(m_recvlay)
154 { 154 {
155 m_recvlay->cancel(); 155 m_recvlay->cancel();
156 delete m_recvlay; 156 delete m_recvlay;
157 m_recvlay = 0l; 157 m_recvlay = 0l;
158 } 158 }
159} 159}
160 160
161void TransferDialog::slotCancel() 161void TransferDialog::slotCancel()
162{ 162{
163 ok->setEnabled(true); 163 ok->setEnabled(true);
164 statusbar->setText(QObject::tr("Ready")); 164 statusbar->setText(QObject::tr("Ready"));
165 165
166 if((m_lay) || (m_recvlay)) 166 if((m_lay) || (m_recvlay))
167 { 167 {
168 cleanup(); 168 cleanup();
169 if(m_autocleanup) 169 if(m_autocleanup)
170 { 170 {
171 m_running = false; 171 m_running = false;
172 close(); 172 close();
173 } 173 }
174 else 174 else
175 { 175 {
176 QMessageBox::information(this, 176 QMessageBox::information(this,
177 QObject::tr("Cancelled"), 177 QObject::tr("Cancelled"),
178 QObject::tr("The file transfer has been cancelled.")); 178 QObject::tr("The file transfer has been cancelled."));
179 } 179 }
180 } 180 }
181 else 181 else
182 { 182 {
183 m_running = false; 183 m_running = false;
184 close(); 184 close();
185 } 185 }
186} 186}
187 187
188void TransferDialog::slotProgress(const QString& , int progress, int , int , int, int ) 188void TransferDialog::slotProgress(const QString& , int progress, int , int , int, int )
189{ 189{
190 progressbar->setProgress(progress); 190 progressbar->setProgress(progress);
191} 191}
192 192
193void TransferDialog::slotError(int error, const QString& ) 193void TransferDialog::slotError(int error, const QString& )
194{ 194{
195 statusbar->setText(QObject::tr("Ready")); 195 statusbar->setText(QObject::tr("Ready"));
196 196
197 switch(error) 197 switch(error)
198 { 198 {
199 case FileTransferLayer::NotSupported: 199 case FileTransferLayer::NotSupported:
200 QMessageBox::critical(this, 200 QMessageBox::critical(this,
201 QObject::tr("Error"), 201 QObject::tr("Error"),
202 QObject::tr("Operation not supported.")); 202 QObject::tr("Operation not supported."));
203 break; 203 break;
204 case FileTransferLayer::StartError: 204 case FileTransferLayer::StartError:
205 QMessageBox::critical(this, 205 QMessageBox::critical(this,
206 QObject::tr("Error"), 206 QObject::tr("Error"),
207 QObject::tr("Transfer could not be started.")); 207 QObject::tr("Transfer could not be started."));
208 break; 208 break;
209 case FileTransferLayer::NoError: 209 case FileTransferLayer::NoError:
210 QMessageBox::critical(this, 210 QMessageBox::critical(this,
211 QObject::tr("Error"), 211 QObject::tr("Error"),
212 QObject::tr("No error.")); 212 QObject::tr("No error."));
213 break; 213 break;
214 case FileTransferLayer::Undefined: 214 case FileTransferLayer::Undefined:
215 QMessageBox::critical(this, 215 QMessageBox::critical(this,
216 QObject::tr("Error"), 216 QObject::tr("Error"),
217 QObject::tr("Undefined error occured.")); 217 QObject::tr("Undefined error occured."));
218 break; 218 break;
219 case FileTransferLayer::Incomplete: 219 case FileTransferLayer::Incomplete:
220 QMessageBox::critical(this, 220 QMessageBox::critical(this,
221 QObject::tr("Error"), 221 QObject::tr("Error"),
222 QObject::tr("Incomplete transfer.")); 222 QObject::tr("Incomplete transfer."));
223 break; 223 break;
224 case FileTransferLayer::Unknown: 224 case FileTransferLayer::Unknown:
225 default: 225 default:
226 QMessageBox::critical(this, 226 QMessageBox::critical(this,
227 QObject::tr("Error"), 227 QObject::tr("Error"),
228 QObject::tr("Unknown error occured.")); 228 QObject::tr("Unknown error occured."));
229 break; 229 break;
230 } 230 }
231 231
232 m_autocleanup = 1; 232 m_autocleanup = 1;
233} 233}
234 234
235void TransferDialog::slotSent() 235void TransferDialog::slotSent()
236{ 236{
237 progressbar->setProgress(100); 237 progressbar->setProgress(100);
238 QMessageBox::information(this, QObject::tr("Sent"), QObject::tr("File has been sent.")); 238 QMessageBox::information(this, QObject::tr("Sent"), QObject::tr("File has been sent."));
239 ok->setEnabled(true); 239 ok->setEnabled(true);
240 progressbar->setProgress(0); 240 progressbar->setProgress(0);
241 statusbar->setText(QObject::tr("Ready")); 241 statusbar->setText(QObject::tr("Ready"));
242 m_autocleanup = 1; 242 m_autocleanup = 1;
243} 243}
244 244
245void TransferDialog::slotReceived(const QString& ) 245void TransferDialog::slotReceived(const QString& )
246{ 246{
247 progressbar->setProgress(100); 247 progressbar->setProgress(100);
248 QMessageBox::information(this, QObject::tr("Received"), QObject::tr("File has been received.")); 248 QMessageBox::information(this, QObject::tr("Received"), QObject::tr("File has been received."));
249 //QMessageBox::information(this, QObject::tr("Sent"), QObject::tr("File has been received as %1.").arg(file)); 249 //QMessageBox::information(this, QObject::tr("Sent"), QObject::tr("File has been received as %1.").arg(file));
250 ok->setEnabled(true); 250 ok->setEnabled(true);
251 progressbar->setProgress(0); 251 progressbar->setProgress(0);
252 statusbar->setText(QObject::tr("Ready")); 252 statusbar->setText(QObject::tr("Ready"));
253 m_autocleanup = 1; 253 m_autocleanup = 1;
254} 254}
255 255
256void TransferDialog::slotMode(int id) 256void TransferDialog::slotMode(int id)
257{ 257{
258 if(id == id_send) 258 if(id == id_send)
259 { 259 {
260 selector->setEnabled(true); 260 selector->setEnabled(true);
261 filename->setEnabled(true); 261 filename->setEnabled(true);
262 } 262 }
263 else 263 else
264 { 264 {
265 selector->setEnabled(false); 265 selector->setEnabled(false);
266 filename->setEnabled(false); 266 filename->setEnabled(false);
267 } 267 }
268 m_transfermode = id; 268 m_transfermode = id;
269} 269}
270 270
271bool TransferDialog::isRunning() 271bool TransferDialog::isRunning()
272{ 272{
273 return m_running; 273 return m_running;
274} 274}
275 275
diff --git a/noncore/apps/opie-reader/QTReaderApp.cpp b/noncore/apps/opie-reader/QTReaderApp.cpp
index e759249..b0d589e 100644
--- a/noncore/apps/opie-reader/QTReaderApp.cpp
+++ b/noncore/apps/opie-reader/QTReaderApp.cpp
@@ -1,4221 +1,4221 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. Allrights reserved. 2** Copyright (C) 2000 Trolltech AS. Allrights reserved.
3** 3**
4** This file is part of Qt Palmtop Environment. 4** This file is part of Qt Palmtop Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include "useqpe.h" 20#include "useqpe.h"
21#include <qregexp.h> 21#include <qregexp.h>
22#include <qclipboard.h> 22#include <qclipboard.h>
23#include <qwidgetstack.h> 23#include <qwidgetstack.h>
24#ifdef USEQPE 24#ifdef USEQPE
25#include <qmenubar.h> 25#include <qmenubar.h>
26#include <qpe/qpetoolbar.h> 26#include <qpe/qpetoolbar.h>
27#endif 27#endif
28#include <qmenubar.h> 28#include <qmenubar.h>
29#include <qtoolbar.h> 29#include <qtoolbar.h>
30#ifdef USEQPE 30#ifdef USEQPE
31#include <qpe/menubutton.h> 31#include <qpe/menubutton.h>
32#include <qpe/fontdatabase.h> 32#include <qpe/fontdatabase.h>
33#endif 33#endif
34#include <qcombobox.h> 34#include <qcombobox.h>
35#include <qpopupmenu.h> 35#include <qpopupmenu.h>
36#include <qaction.h> 36#include <qaction.h>
37#include <qapplication.h> 37#include <qapplication.h>
38#include <qlineedit.h> 38#include <qlineedit.h>
39#include <qtoolbutton.h> 39#include <qtoolbutton.h>
40#include <qspinbox.h> 40#include <qspinbox.h>
41#include <qobjectlist.h> 41#include <qobjectlist.h>
42#ifdef USEQPE 42#ifdef USEQPE
43#include <qpe/global.h> 43#include <qpe/global.h>
44#include <qpe/applnk.h> 44#include <qpe/applnk.h>
45#endif 45#endif
46#include <qfileinfo.h> 46#include <qfileinfo.h>
47#include <stdlib.h> //getenv 47#include <stdlib.h> //getenv
48#include <qprogressbar.h> 48#include <qprogressbar.h>
49#ifdef USEQPE 49#ifdef USEQPE
50#include <qpe/config.h> 50#include <qpe/config.h>
51#endif 51#endif
52#include <qbuttongroup.h> 52#include <qbuttongroup.h>
53#include <qradiobutton.h> 53#include <qradiobutton.h>
54#ifdef USEQPE 54#ifdef USEQPE
55#include <qpe/qcopenvelope_qws.h> 55#include <qpe/qcopenvelope_qws.h>
56#endif 56#endif
57#include "QTReader.h" 57#include "QTReader.h"
58#include "GraphicWin.h" 58#include "GraphicWin.h"
59#include "Bkmks.h" 59#include "Bkmks.h"
60#include "cbkmkselector.h" 60#include "cbkmkselector.h"
61#include "infowin.h" 61#include "infowin.h"
62#include "ToolbarPrefs.h" 62#include "ToolbarPrefs.h"
63#include "Prefs.h" 63#include "Prefs.h"
64#include "CAnnoEdit.h" 64#include "CAnnoEdit.h"
65#include "QFloatBar.h" 65#include "QFloatBar.h"
66#include "FixedFont.h" 66#include "FixedFont.h"
67#include "URLDialog.h" 67#include "URLDialog.h"
68//#include <qpe/fontdatabase.h> 68//#include <qpe/fontdatabase.h>
69 69
70#ifdef USEQPE 70#ifdef USEQPE
71#include <qpe/resource.h> 71#include <qpe/resource.h>
72#include <qpe/qpeapplication.h> 72#include <qpe/qpeapplication.h>
73#include "fileBrowser.h" 73#include "fileBrowser.h"
74#else 74#else
75#include "qfiledialog.h" 75#include "qfiledialog.h"
76#endif 76#endif
77 77
78#include "QTReaderApp.h" 78#include "QTReaderApp.h"
79#include "CDrawBuffer.h" 79#include "CDrawBuffer.h"
80#include "Filedata.h" 80#include "Filedata.h"
81#include "opie.h" 81#include "opie.h"
82#include "names.h" 82#include "names.h"
83#include "CEncoding_tables.h" 83#include "CEncoding_tables.h"
84#include "CloseDialog.h" 84#include "CloseDialog.h"
85 85
86bool CheckVersion(int&, int&, char&); 86bool CheckVersion(int&, int&, char&);
87 87
88#ifdef _WINDOWS 88#ifdef _WINDOWS
89#define PICDIR "c:\\uqtreader\\pics\\" 89#define PICDIR "c:\\uqtreader\\pics\\"
90#else 90#else
91#ifdef USEQPE 91#ifdef USEQPE
92#define PICDIR "opie-reader/" 92#define PICDIR "opie-reader/"
93#else 93#else
94#define PICDIR "/home/tim/uqtreader/pics/" 94#define PICDIR "/home/tim/uqtreader/pics/"
95#endif 95#endif
96#endif 96#endif
97 97
98unsigned long QTReaderApp::m_uid = 0; 98unsigned long QTReaderApp::m_uid = 0;
99 99
100void QTReaderApp::setScrollState(bool _b) { m_scrollButton->setOn(_b); } 100void QTReaderApp::setScrollState(bool _b) { m_scrollButton->setOn(_b); }
101 101
102#ifdef USEQPE 102#ifdef USEQPE
103#define geticon(iconname) Resource::loadPixmap( iconname ) 103#define geticon(iconname) Resource::loadPixmap( iconname )
104#define getmyicon(iconname) Resource::loadPixmap( PICDIR iconname ) 104#define getmyicon(iconname) Resource::loadPixmap( PICDIR iconname )
105#else 105#else
106#define geticon(iconname) QPixmap(PICDIR iconname ".png") 106#define geticon(iconname) QPixmap(PICDIR iconname ".png")
107#define getmyicon(iconname) geticon(iconname) 107#define getmyicon(iconname) geticon(iconname)
108//#define geticon(iconname) QIconSet( QPixmap(PICDIR iconname) ) 108//#define geticon(iconname) QIconSet( QPixmap(PICDIR iconname) )
109#endif 109#endif
110 110
111#ifndef _WINDOWS 111#ifndef _WINDOWS
112#include <unistd.h> 112#include <unistd.h>
113#endif 113#endif
114#include <stddef.h> 114#include <stddef.h>
115#ifndef _WINDOWS 115#ifndef _WINDOWS
116#include <dirent.h> 116#include <dirent.h>
117#endif 117#endif
118 118
119void QTReaderApp::listBkmkFiles() 119void QTReaderApp::listBkmkFiles()
120{ 120{
121 bkmkselector->clear(); 121 bkmkselector->clear();
122 bkmkselector->setText("Cancel"); 122 bkmkselector->setText("Cancel");
123#ifndef USEQPE 123#ifndef USEQPE
124 int cnt = 0; 124 int cnt = 0;
125 125
126 QDir d = QDir::home(); // "/" 126 QDir d = QDir::home(); // "/"
127 if ( !d.cd(APPDIR) ) { // "/tmp" 127 if ( !d.cd(APPDIR) ) { // "/tmp"
128 qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); 128 qWarning( "Cannot find the \"~/" APPDIR "\" directory" );
129 d = QDir::home(); 129 d = QDir::home();
130 d.mkdir(APPDIR); 130 d.mkdir(APPDIR);
131 d.cd(APPDIR); 131 d.cd(APPDIR);
132 } 132 }
133 133
134 134
135 135
136 136
137 d.setFilter( QDir::Files | QDir::NoSymLinks ); 137 d.setFilter( QDir::Files | QDir::NoSymLinks );
138// d.setSorting( QDir::Size | QDir::Reversed ); 138// d.setSorting( QDir::Size | QDir::Reversed );
139 139
140 const QFileInfoList *list = d.entryInfoList(); 140 const QFileInfoList *list = d.entryInfoList();
141 QFileInfoListIterator it( *list ); // create list iterator 141 QFileInfoListIterator it( *list ); // create list iterator
142 QFileInfo *fi; // pointer for traversing 142 QFileInfo *fi; // pointer for traversing
143 143
144 while ( (fi=it.current()) ) { // for each file... 144 while ( (fi=it.current()) ) { // for each file...
145 145
146 bkmkselector->insertItem(fi->fileName()); 146 bkmkselector->insertItem(fi->fileName());
147 cnt++; 147 cnt++;
148 148
149 //qDebug( "%10li %s", fi->size(), fi->fileName().data() ); 149 //qDebug( "%10li %s", fi->size(), fi->fileName().data() );
150 ++it; // goto next list element 150 ++it; // goto next list element
151 } 151 }
152 152
153#else /* USEQPE */ 153#else /* USEQPE */
154 int cnt = 0; 154 int cnt = 0;
155 DIR *d; 155 DIR *d;
156 d = opendir((const char *)Global::applicationFileName(APPDIR,"")); 156 d = opendir((const char *)Global::applicationFileName(APPDIR,""));
157 157
158 while(1) 158 while(1)
159 { 159 {
160 struct dirent* de; 160 struct dirent* de;
161 struct stat buf; 161 struct stat buf;
162 de = readdir(d); 162 de = readdir(d);
163 if (de == NULL) break; 163 if (de == NULL) break;
164 164
165 if (lstat((const char *)Global::applicationFileName(APPDIR,de->d_name),&buf) == 0 && S_ISREG(buf.st_mode)) 165 if (lstat((const char *)Global::applicationFileName(APPDIR,de->d_name),&buf) == 0 && S_ISREG(buf.st_mode))
166 { 166 {
167 bkmkselector->insertItem(de->d_name); 167 bkmkselector->insertItem(de->d_name);
168 cnt++; 168 cnt++;
169 } 169 }
170 } 170 }
171 171
172 closedir(d); 172 closedir(d);
173#endif 173#endif
174 if (cnt > 0) 174 if (cnt > 0)
175 { 175 {
176//tjw menu->hide(); 176//tjw menu->hide();
177 editorStack->raiseWidget( bkmkselector ); 177 editorStack->raiseWidget( bkmkselector );
178 hidetoolbars(); 178 hidetoolbars();
179 m_nBkmkAction = cRmBkmkFile; 179 m_nBkmkAction = cRmBkmkFile;
180 } 180 }
181 else 181 else
182 QMessageBox::information(this, PROGNAME, "No bookmark files"); 182 QMessageBox::information(this, PROGNAME, "No bookmark files");
183} 183}
184 184
185void QTReaderApp::hidetoolbars() 185void QTReaderApp::hidetoolbars()
186{ 186{
187 menubar->hide(); 187 menubar->hide();
188 if (fileBar != NULL) fileBar->hide(); 188 if (fileBar != NULL) fileBar->hide();
189 if (viewBar != NULL) viewBar->hide(); 189 if (viewBar != NULL) viewBar->hide();
190 if (navBar != NULL) navBar->hide(); 190 if (navBar != NULL) navBar->hide();
191 if (markBar != NULL) markBar->hide(); 191 if (markBar != NULL) markBar->hide();
192 if (m_fontVisible) m_fontBar->hide(); 192 if (m_fontVisible) m_fontBar->hide();
193 if (regVisible) 193 if (regVisible)
194 { 194 {
195#ifdef USEQPE 195#ifdef USEQPE
196 Global::hideInputMethod(); 196 Global::hideInputMethod();
197#endif 197#endif
198 regBar->hide(); 198 regBar->hide();
199 } 199 }
200 if (searchVisible) 200 if (searchVisible)
201 { 201 {
202#ifdef USEQPE 202#ifdef USEQPE
203 Global::hideInputMethod(); 203 Global::hideInputMethod();
204#endif 204#endif
205 searchBar->hide(); 205 searchBar->hide();
206 } 206 }
207} 207}
208 208
209QTReaderApp::QTReaderApp( QWidget *parent, const char *name, WFlags f ) 209QTReaderApp::QTReaderApp( QWidget *parent, const char *name, WFlags f )
210 : QMainWindow( parent, name, f ), bFromDocView( FALSE ), m_dontSave(false), 210 : QMainWindow( parent, name, f ), bFromDocView( FALSE ), m_dontSave(false),
211 fileBar(NULL), navBar(NULL), viewBar(NULL), markBar(NULL) 211 fileBar(NULL), navBar(NULL), viewBar(NULL), markBar(NULL)
212{ 212{
213 m_url_clipboard = false; 213 m_url_clipboard = false;
214 m_url_localfile = false; 214 m_url_localfile = false;
215 m_url_globalfile = false; 215 m_url_globalfile = false;
216 ftime(&m_lastkeytime); 216 ftime(&m_lastkeytime);
217//// qDebug("Application directory = %s", (const tchar *)QPEApplication::documentDir()); 217//// qDebug("Application directory = %s", (const tchar *)QPEApplication::documentDir());
218//// qDebug("Application directory = %s", (const tchar *)Global::applicationFileName("uqtreader","bkmks.xml")); 218//// qDebug("Application directory = %s", (const tchar *)Global::applicationFileName("uqtreader","bkmks.xml"));
219 219
220 m_bcloseDisabled = true; 220 m_bcloseDisabled = true;
221 m_disableesckey = false; 221 m_disableesckey = false;
222 pBkmklist = NULL; 222 pBkmklist = NULL;
223 pOpenlist = NULL; 223 pOpenlist = NULL;
224// doc = 0; 224// doc = 0;
225 225
226 m_fBkmksChanged = false; 226 m_fBkmksChanged = false;
227 227
228 QString lang = getenv( "LANG" ); 228 QString lang = getenv( "LANG" );
229 QString rot = getenv( "QWS_DISPLAY" ); 229 QString rot = getenv( "QWS_DISPLAY" );
230 230
231/* 231/*
232 int m_rot = 0; 232 int m_rot = 0;
233 if (rot.contains("Rot90")) 233 if (rot.contains("Rot90"))
234 { 234 {
235 m_rot = 90; 235 m_rot = 90;
236 } 236 }
237 else if (rot.contains("Rot180")) 237 else if (rot.contains("Rot180"))
238 { 238 {
239 m_rot = 180; 239 m_rot = 180;
240 } 240 }
241 else if (rot.contains("Rot270")) 241 else if (rot.contains("Rot270"))
242 { 242 {
243 m_rot = 270; 243 m_rot = 270;
244 } 244 }
245 245
246// qDebug("Initial Rotation(%d):%s", m_rot, (const char*)rot); 246// qDebug("Initial Rotation(%d):%s", m_rot, (const char*)rot);
247*/ 247*/
248 m_autogenstr = "^ *[A-Z].*[a-z] *$"; 248 m_autogenstr = "^ *[A-Z].*[a-z] *$";
249 249
250#ifdef USEQPE 250#ifdef USEQPE
251 setIcon( Resource::loadPixmap( PICDIR "uqtreader") ); 251 setIcon( Resource::loadPixmap( PICDIR "uqtreader") );
252#else 252#else
253 setIcon( QPixmap (PICDIR "uqtreader.png") ); 253 setIcon( QPixmap (PICDIR "uqtreader.png") );
254#endif /* USEQPE */ 254#endif /* USEQPE */
255 255
256// QToolBar *bar = new QToolBar( this ); 256// QToolBar *bar = new QToolBar( this );
257// menubar = new QToolBar( this ); 257// menubar = new QToolBar( this );
258#ifdef USEQPE 258#ifdef USEQPE
259 Config config( APPDIR ); 259 Config config( APPDIR );
260#else 260#else
261 QDir d = QDir::home(); // "/" 261 QDir d = QDir::home(); // "/"
262 if ( !d.cd(APPDIR) ) { // "/tmp" 262 if ( !d.cd(APPDIR) ) { // "/tmp"
263 qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); 263 qWarning( "Cannot find the \"~/" APPDIR "\" directory" );
264 d = QDir::home(); 264 d = QDir::home();
265 d.mkdir(APPDIR); 265 d.mkdir(APPDIR);
266 d.cd(APPDIR); 266 d.cd(APPDIR);
267 } 267 }
268 QFileInfo fi(d, INIFILE); 268 QFileInfo fi(d, INIFILE);
269// qDebug("Path:%s", (const char*)fi.absFilePath()); 269// qDebug("Path:%s", (const char*)fi.absFilePath());
270 Config config(fi.absFilePath()); 270 Config config(fi.absFilePath());
271#endif 271#endif
272 config.setGroup("Toolbar"); 272 config.setGroup("Toolbar");
273 m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", false); 273 m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", false);
274 m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", 1); 274 m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", 1);
275 m_tbposition = (ToolBarDock)config.readNumEntry("Position", 2); 275 m_tbposition = (ToolBarDock)config.readNumEntry("Position", 2);
276 menubar = new QToolBar("Menus", this, m_tbposition); 276 menubar = new QToolBar("Menus", this, m_tbposition);
277 277
278// fileBar = new QToolBar("File", this); 278// fileBar = new QToolBar("File", this);
279// QToolBar* viewBar = new QToolBar("File", this); 279// QToolBar* viewBar = new QToolBar("File", this);
280// QToolBar* navBar = new QToolBar("File", this); 280// QToolBar* navBar = new QToolBar("File", this);
281// QToolBar* markBar = new QToolBar("File", this); 281// QToolBar* markBar = new QToolBar("File", this);
282 282
283#ifdef USEQPE 283#ifdef USEQPE
284 mb = new QMenuBar( menubar ); 284 mb = new QMenuBar( menubar );
285#else 285#else
286 mb = new QMenuBar( menubar ); 286 mb = new QMenuBar( menubar );
287#endif 287#endif
288 288
289//#ifdef USEQPE 289//#ifdef USEQPE
290 QPopupMenu* tmp = new QPopupMenu(mb); 290 QPopupMenu* tmp = new QPopupMenu(mb);
291 mb->insertItem( geticon( "AppsIcon" ), tmp ); 291 mb->insertItem( geticon( "AppsIcon" ), tmp );
292//#else 292//#else
293// QMenuBar* tmp = mb; 293// QMenuBar* tmp = mb;
294//#endif 294//#endif
295 295
296 QPopupMenu *file = new QPopupMenu( mb ); 296 QPopupMenu *file = new QPopupMenu( mb );
297 tmp->insertItem( tr( "File" ), file ); 297 tmp->insertItem( tr( "File" ), file );
298 298
299 QPopupMenu *navigation = new QPopupMenu(mb); 299 QPopupMenu *navigation = new QPopupMenu(mb);
300 tmp->insertItem( tr( "Navigation" ), navigation ); 300 tmp->insertItem( tr( "Navigation" ), navigation );
301 301
302 QPopupMenu *view = new QPopupMenu( mb ); 302 QPopupMenu *view = new QPopupMenu( mb );
303 tmp->insertItem( tr( "View" ), view ); 303 tmp->insertItem( tr( "View" ), view );
304 304
305 QPopupMenu *marks = new QPopupMenu( this ); 305 QPopupMenu *marks = new QPopupMenu( this );
306 tmp->insertItem( tr( "Marks" ), marks ); 306 tmp->insertItem( tr( "Marks" ), marks );
307 307
308 QPopupMenu *settings = new QPopupMenu( this ); 308 QPopupMenu *settings = new QPopupMenu( this );
309 tmp->insertItem( tr( "Settings" ), settings ); 309 tmp->insertItem( tr( "Settings" ), settings );
310 310
311// addToolBar(menubar, "Menus",QMainWindow::Top); 311// addToolBar(menubar, "Menus",QMainWindow::Top);
312// addToolBar(fileBar, "Toolbar",QMainWindow::Top); 312// addToolBar(fileBar, "Toolbar",QMainWindow::Top);
313 313
314 // QPopupMenu *edit = new QPopupMenu( this ); 314 // QPopupMenu *edit = new QPopupMenu( this );
315 315
316 /* 316 /*
317 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); 317 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 );
318 connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); 318 connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) );
319 a->addTo( bar ); 319 a->addTo( bar );
320 a->addTo( file ); 320 a->addTo( file );
321 */ 321 */
322 322
323 editorStack = new QWidgetStack( this ); 323 editorStack = new QWidgetStack( this );
324 setCentralWidget( editorStack ); 324 setCentralWidget( editorStack );
325 325
326 searchVisible = FALSE; 326 searchVisible = FALSE;
327 regVisible = FALSE; 327 regVisible = FALSE;
328 m_fontVisible = false; 328 m_fontVisible = false;
329 329
330 m_annoWin = new CAnnoEdit(editorStack); 330 m_annoWin = new CAnnoEdit(editorStack);
331 editorStack->addWidget(m_annoWin, get_unique_id()); 331 editorStack->addWidget(m_annoWin, get_unique_id());
332 connect( m_annoWin, SIGNAL( finished(const QString&, const QString&) ), this, SLOT( addAnno(const QString&, const QString&) ) ); 332 connect( m_annoWin, SIGNAL( finished(const QString&,const QString&) ), this, SLOT( addAnno(const QString&,const QString&) ) );
333 connect( m_annoWin, SIGNAL( cancelled() ), this, SLOT( infoClose() ) ); 333 connect( m_annoWin, SIGNAL( cancelled() ), this, SLOT( infoClose() ) );
334 334
335 m_infoWin = new infowin(editorStack); 335 m_infoWin = new infowin(editorStack);
336 editorStack->addWidget(m_infoWin, get_unique_id()); 336 editorStack->addWidget(m_infoWin, get_unique_id());
337 connect( m_infoWin, SIGNAL( Close() ), this, SLOT( infoClose() ) ); 337 connect( m_infoWin, SIGNAL( Close() ), this, SLOT( infoClose() ) );
338 338
339 m_graphicwin = new GraphicWin(editorStack); 339 m_graphicwin = new GraphicWin(editorStack);
340 editorStack->addWidget(m_graphicwin, get_unique_id()); 340 editorStack->addWidget(m_graphicwin, get_unique_id());
341 connect( m_graphicwin, SIGNAL( Closed() ), this, SLOT( infoClose() ) ); 341 connect( m_graphicwin, SIGNAL( Closed() ), this, SLOT( infoClose() ) );
342 342
343// bkmkselector = new QListBox(editorStack, "Bookmarks"); 343// bkmkselector = new QListBox(editorStack, "Bookmarks");
344 bkmkselector = new CBkmkSelector(editorStack, "Bookmarks"); 344 bkmkselector = new CBkmkSelector(editorStack, "Bookmarks");
345 // connect(bkmkselector, SIGNAL( selected(const QString&) ), this, SLOT( gotobkmk(const QString&) ) ); 345 // connect(bkmkselector, SIGNAL( selected(const QString&) ), this, SLOT( gotobkmk(const QString&) ) );
346 connect(bkmkselector, SIGNAL( selected(int) ), this, SLOT( gotobkmk(int) ) ); 346 connect(bkmkselector, SIGNAL( selected(int) ), this, SLOT( gotobkmk(int) ) );
347 connect(bkmkselector, SIGNAL( cancelled() ), this, SLOT( cancelbkmk() ) ); 347 connect(bkmkselector, SIGNAL( cancelled() ), this, SLOT( cancelbkmk() ) );
348 editorStack->addWidget( bkmkselector, get_unique_id() ); 348 editorStack->addWidget( bkmkselector, get_unique_id() );
349 349
350/* 350/*
351 importSelector = new FileSelector( "*", editorStack, "importselector", false ); 351 importSelector = new FileSelector( "*", editorStack, "importselector", false );
352 connect( importSelector, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( importFile( const DocLnk & ) ) ); 352 connect( importSelector, SIGNAL( fileSelected(const DocLnk&) ), this, SLOT( importFile(const DocLnk&) ) );
353 353
354 editorStack->addWidget( importSelector, get_unique_id() ); 354 editorStack->addWidget( importSelector, get_unique_id() );
355 355
356 // don't need the close visible, it is redundant... 356 // don't need the close visible, it is redundant...
357 importSelector->setCloseVisible( FALSE ); 357 importSelector->setCloseVisible( FALSE );
358*/ 358*/
359// qDebug("Reading file list"); 359// qDebug("Reading file list");
360 readfilelist(); 360 readfilelist();
361 361
362 reader = new QTReader( editorStack ); 362 reader = new QTReader( editorStack );
363 363
364 reader->bDoUpdates = false; 364 reader->bDoUpdates = false;
365 365
366#ifdef USEQPE 366#ifdef USEQPE
367 ((QPEApplication*)qApp)->setStylusOperation(reader, QPEApplication::RightOnHold); 367 ((QPEApplication*)qApp)->setStylusOperation(reader, QPEApplication::RightOnHold);
368#endif 368#endif
369 369
370// qDebug("Reading config"); 370// qDebug("Reading config");
371// Config config( APPDIR ); 371// Config config( APPDIR );
372 config.setGroup( "View" ); 372 config.setGroup( "View" );
373 m_debounce = config.readNumEntry("Debounce", 0); 373 m_debounce = config.readNumEntry("Debounce", 0);
374#ifdef USEQPE 374#ifdef USEQPE
375 m_bFloatingDialog = config.readBoolEntry("FloatDialogs", false); 375 m_bFloatingDialog = config.readBoolEntry("FloatDialogs", false);
376#else 376#else
377 m_bFloatingDialog = config.readBoolEntry("FloatDialogs", true); 377 m_bFloatingDialog = config.readBoolEntry("FloatDialogs", true);
378#endif 378#endif
379 reader->bstripcr = config.readBoolEntry( "StripCr", true ); 379 reader->bstripcr = config.readBoolEntry( "StripCr", true );
380 reader->bfulljust = config.readBoolEntry( "FullJust", false ); 380 reader->bfulljust = config.readBoolEntry( "FullJust", false );
381 reader->setextraspace(config.readNumEntry( "ExtraSpace", 0 )); 381 reader->setextraspace(config.readNumEntry( "ExtraSpace", 0 ));
382 reader->setlead(config.readNumEntry( "ExtraLead", 0 )); 382 reader->setlead(config.readNumEntry( "ExtraLead", 0 ));
383 reader->btextfmt = config.readBoolEntry( "TextFmt", false ); 383 reader->btextfmt = config.readBoolEntry( "TextFmt", false );
384 reader->bautofmt = config.readBoolEntry( "AutoFmt", true ); 384 reader->bautofmt = config.readBoolEntry( "AutoFmt", true );
385 reader->bstriphtml = config.readBoolEntry( "StripHtml", false ); 385 reader->bstriphtml = config.readBoolEntry( "StripHtml", false );
386 reader->bpeanut = config.readBoolEntry( "Peanut", false ); 386 reader->bpeanut = config.readBoolEntry( "Peanut", false );
387 reader->bdehyphen = config.readBoolEntry( "Dehyphen", false ); 387 reader->bdehyphen = config.readBoolEntry( "Dehyphen", false );
388 reader->bdepluck = config.readBoolEntry( "Depluck", false ); 388 reader->bdepluck = config.readBoolEntry( "Depluck", false );
389 reader->bdejpluck = config.readBoolEntry( "Dejpluck", false ); 389 reader->bdejpluck = config.readBoolEntry( "Dejpluck", false );
390 reader->bonespace = config.readBoolEntry( "OneSpace", false ); 390 reader->bonespace = config.readBoolEntry( "OneSpace", false );
391 reader->bunindent = config.readBoolEntry( "Unindent", false ); 391 reader->bunindent = config.readBoolEntry( "Unindent", false );
392 reader->brepara = config.readBoolEntry( "Repara", false ); 392 reader->brepara = config.readBoolEntry( "Repara", false );
393 reader->bdblspce = config.readBoolEntry( "DoubleSpace", false ); 393 reader->bdblspce = config.readBoolEntry( "DoubleSpace", false );
394 reader->bindenter = config.readNumEntry( "Indent", 0 ); 394 reader->bindenter = config.readNumEntry( "Indent", 0 );
395 reader->m_textsize = config.readNumEntry( "FontSize", 12 ); 395 reader->m_textsize = config.readNumEntry( "FontSize", 12 );
396 reader->m_delay = config.readNumEntry( "ScrollDelay", 5184); 396 reader->m_delay = config.readNumEntry( "ScrollDelay", 5184);
397 reader->m_lastfile = config.readEntry( "LastFile", QString::null ); 397 reader->m_lastfile = config.readEntry( "LastFile", QString::null );
398 reader->m_lastposn = config.readNumEntry( "LastPosn", 0 ); 398 reader->m_lastposn = config.readNumEntry( "LastPosn", 0 );
399 reader->m_bpagemode = config.readBoolEntry( "PageMode", true ); 399 reader->m_bpagemode = config.readBoolEntry( "PageMode", true );
400 reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", false); 400 reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", false);
401 reader->m_swapmouse = config.readBoolEntry( "SwapMouse", false); 401 reader->m_swapmouse = config.readBoolEntry( "SwapMouse", false);
402 reader->m_fontname = config.readEntry( "Fontname", "helvetica" ); 402 reader->m_fontname = config.readEntry( "Fontname", "helvetica" );
403 reader->m_encd = config.readNumEntry( "Encoding", 0 ); 403 reader->m_encd = config.readNumEntry( "Encoding", 0 );
404 reader->m_charpc = config.readNumEntry( "CharSpacing", 100 ); 404 reader->m_charpc = config.readNumEntry( "CharSpacing", 100 );
405 reader->m_overlap = config.readNumEntry( "Overlap", 0 ); 405 reader->m_overlap = config.readNumEntry( "Overlap", 0 );
406 reader->m_border = config.readNumEntry( "Margin", 6 ); 406 reader->m_border = config.readNumEntry( "Margin", 6 );
407#ifdef REPALM 407#ifdef REPALM
408 reader->brepalm = config.readBoolEntry( "Repalm", true ); 408 reader->brepalm = config.readBoolEntry( "Repalm", true );
409#endif 409#endif
410 reader->bremap = config.readBoolEntry( "Remap", true ); 410 reader->bremap = config.readBoolEntry( "Remap", true );
411 reader->bmakebold = config.readBoolEntry( "MakeBold", false ); 411 reader->bmakebold = config.readBoolEntry( "MakeBold", false );
412 reader->setContinuous(config.readBoolEntry( "Continuous", true )); 412 reader->setContinuous(config.readBoolEntry( "Continuous", true ));
413 m_targetapp = config.readEntry( "TargetApp", QString::null ); 413 m_targetapp = config.readEntry( "TargetApp", QString::null );
414 m_targetmsg = config.readEntry( "TargetMsg", QString::null ); 414 m_targetmsg = config.readEntry( "TargetMsg", QString::null );
415#ifdef _SCROLLPIPE 415#ifdef _SCROLLPIPE
416 reader->m_pipetarget = config.readEntry( "PipeTarget", QString::null ); 416 reader->m_pipetarget = config.readEntry( "PipeTarget", QString::null );
417 reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", true ); 417 reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", true );
418#endif 418#endif
419 m_twoTouch = config.readBoolEntry( "TwoTouch", false); 419 m_twoTouch = config.readBoolEntry( "TwoTouch", false);
420 m_doAnnotation = config.readBoolEntry( "Annotation", false); 420 m_doAnnotation = config.readBoolEntry( "Annotation", false);
421 m_doDictionary = config.readBoolEntry( "Dictionary", false); 421 m_doDictionary = config.readBoolEntry( "Dictionary", false);
422 m_doClipboard = config.readBoolEntry( "Clipboard", false); 422 m_doClipboard = config.readBoolEntry( "Clipboard", false);
423 m_spaceTarget = (ActionTypes)config.readNumEntry("SpaceTarget", cesAutoScroll); 423 m_spaceTarget = (ActionTypes)config.readNumEntry("SpaceTarget", cesAutoScroll);
424 m_escapeTarget = (ActionTypes)config.readNumEntry("EscapeTarget", cesNone); 424 m_escapeTarget = (ActionTypes)config.readNumEntry("EscapeTarget", cesNone);
425 m_returnTarget = (ActionTypes)config.readNumEntry("ReturnTarget", cesFullScreen); 425 m_returnTarget = (ActionTypes)config.readNumEntry("ReturnTarget", cesFullScreen);
426 m_leftTarget = (ActionTypes)config.readNumEntry("LeftTarget", cesZoomOut); 426 m_leftTarget = (ActionTypes)config.readNumEntry("LeftTarget", cesZoomOut);
427 m_rightTarget = (ActionTypes)config.readNumEntry("RightTarget", cesZoomIn); 427 m_rightTarget = (ActionTypes)config.readNumEntry("RightTarget", cesZoomIn);
428 m_upTarget = (ActionTypes)config.readNumEntry("UpTarget", cesPageUp); 428 m_upTarget = (ActionTypes)config.readNumEntry("UpTarget", cesPageUp);
429 m_downTarget = (ActionTypes)config.readNumEntry("DownTarget", cesPageDown); 429 m_downTarget = (ActionTypes)config.readNumEntry("DownTarget", cesPageDown);
430 430
431 m_leftScroll = config.readBoolEntry("LeftScroll", false); 431 m_leftScroll = config.readBoolEntry("LeftScroll", false);
432 m_rightScroll = config.readBoolEntry("RightScroll", false); 432 m_rightScroll = config.readBoolEntry("RightScroll", false);
433 m_upScroll = config.readBoolEntry("UpScroll", true); 433 m_upScroll = config.readBoolEntry("UpScroll", true);
434 m_downScroll = config.readBoolEntry("DownScroll", true); 434 m_downScroll = config.readBoolEntry("DownScroll", true);
435 435
436 m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", false); 436 m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", false);
437 reader->setBaseSize(config.readNumEntry( "Basesize", 10 )); 437 reader->setBaseSize(config.readNumEntry( "Basesize", 10 ));
438 438
439#ifndef USEQPE 439#ifndef USEQPE
440 config.setGroup( "Geometry" ); 440 config.setGroup( "Geometry" );
441 setGeometry(0,0, 441 setGeometry(0,0,
442 config.readNumEntry( "width", QApplication::desktop()->width()/2 ), 442 config.readNumEntry( "width", QApplication::desktop()->width()/2 ),
443 config.readNumEntry( "height", QApplication::desktop()->height()/2 )); 443 config.readNumEntry( "height", QApplication::desktop()->height()/2 ));
444 move( 444 move(
445 config.readNumEntry( "x", 20 ), 445 config.readNumEntry( "x", 20 ),
446 config.readNumEntry( "y", 20 )); 446 config.readNumEntry( "y", 20 ));
447#endif 447#endif
448 448
449 449
450 450
451 setTwoTouch(m_twoTouch); 451 setTwoTouch(m_twoTouch);
452 452
453 connect( reader, SIGNAL( OnShowPicture(QImage&) ), this, SLOT( showgraphic(QImage&) ) ); 453 connect( reader, SIGNAL( OnShowPicture(QImage&) ), this, SLOT( showgraphic(QImage&) ) );
454 454
455 connect( reader, SIGNAL( OnRedraw() ), this, SLOT( OnRedraw() ) ); 455 connect( reader, SIGNAL( OnRedraw() ), this, SLOT( OnRedraw() ) );
456 connect( reader, SIGNAL( OnWordSelected(const QString&, size_t, const QString&) ), this, SLOT( OnWordSelected(const QString&, size_t, const QString&) ) ); 456 connect( reader, SIGNAL( OnWordSelected(const QString&,size_t,const QString&) ), this, SLOT( OnWordSelected(const QString&,size_t,const QString&) ) );
457 connect( reader, SIGNAL( OnURLSelected(const QString&) ), this, SLOT( OnURLSelected(const QString&) ) ); 457 connect( reader, SIGNAL( OnURLSelected(const QString&) ), this, SLOT( OnURLSelected(const QString&) ) );
458 editorStack->addWidget( reader, get_unique_id() ); 458 editorStack->addWidget( reader, get_unique_id() );
459 459
460 m_preferences_action = new QAction( tr( "Configuration" ), geticon( "SettingsIcon" ), QString::null, 0, this, NULL); 460 m_preferences_action = new QAction( tr( "Configuration" ), geticon( "SettingsIcon" ), QString::null, 0, this, NULL);
461 connect( m_preferences_action, SIGNAL( activated() ), this, SLOT( showprefs() ) ); 461 connect( m_preferences_action, SIGNAL( activated() ), this, SLOT( showprefs() ) );
462 m_preferences_action->addTo( settings ); 462 m_preferences_action->addTo( settings );
463 463
464 m_saveconfig_action = new QAction( tr( "Save Config" ), QString::null, 0, this, NULL); 464 m_saveconfig_action = new QAction( tr( "Save Config" ), QString::null, 0, this, NULL);
465 connect( m_saveconfig_action, SIGNAL( activated() ), this, SLOT( SaveConfig() ) ); 465 connect( m_saveconfig_action, SIGNAL( activated() ), this, SLOT( SaveConfig() ) );
466 m_saveconfig_action->addTo( settings ); 466 m_saveconfig_action->addTo( settings );
467 467
468 m_loadconfig_action = new QAction( tr( "Load Config" ), QString::null, 0, this, NULL); 468 m_loadconfig_action = new QAction( tr( "Load Config" ), QString::null, 0, this, NULL);
469 connect( m_loadconfig_action, SIGNAL( activated() ), this, SLOT( LoadConfig() ) ); 469 connect( m_loadconfig_action, SIGNAL( activated() ), this, SLOT( LoadConfig() ) );
470 m_loadconfig_action->addTo( settings ); 470 m_loadconfig_action->addTo( settings );
471 471
472 m_tidyconfig_action = new QAction( tr( "Delete Config" ), QString::null, 0, this, NULL); 472 m_tidyconfig_action = new QAction( tr( "Delete Config" ), QString::null, 0, this, NULL);
473 connect( m_tidyconfig_action, SIGNAL( activated() ), this, SLOT( TidyConfig() ) ); 473 connect( m_tidyconfig_action, SIGNAL( activated() ), this, SLOT( TidyConfig() ) );
474 m_tidyconfig_action->addTo( settings ); 474 m_tidyconfig_action->addTo( settings );
475 475
476 settings->insertSeparator(); 476 settings->insertSeparator();
477 m_toolbarprefs_action = new QAction( tr( "Toolbars" ), QString::null, 0, this, NULL); 477 m_toolbarprefs_action = new QAction( tr( "Toolbars" ), QString::null, 0, this, NULL);
478 connect( m_toolbarprefs_action, SIGNAL( activated() ), this, SLOT( showtoolbarprefs() ) ); 478 connect( m_toolbarprefs_action, SIGNAL( activated() ), this, SLOT( showtoolbarprefs() ) );
479 m_toolbarprefs_action->addTo( settings ); 479 m_toolbarprefs_action->addTo( settings );
480 480
481 m_open_action = new QAction( tr( "Open" ), geticon( "fileopen" ), QString::null, 0, this, 0 ); 481 m_open_action = new QAction( tr( "Open" ), geticon( "fileopen" ), QString::null, 0, this, 0 );
482 connect( m_open_action, SIGNAL( activated() ), this, SLOT( fileOpen() ) ); 482 connect( m_open_action, SIGNAL( activated() ), this, SLOT( fileOpen() ) );
483 m_open_action->addTo( file ); 483 m_open_action->addTo( file );
484 484
485 m_close_action = new QAction( tr( "Close" ), geticon( "close" ), QString::null, 0, this, 0 ); 485 m_close_action = new QAction( tr( "Close" ), geticon( "close" ), QString::null, 0, this, 0 );
486 connect( m_close_action, SIGNAL( activated() ), this, SLOT( fileClose() ) ); 486 connect( m_close_action, SIGNAL( activated() ), this, SLOT( fileClose() ) );
487 m_close_action->addTo( file ); 487 m_close_action->addTo( file );
488 488
489#ifdef _SCRIPT 489#ifdef _SCRIPT
490 a = new QAction( tr( "Run Script" ), QString::null, 0, this, NULL); 490 a = new QAction( tr( "Run Script" ), QString::null, 0, this, NULL);
491 connect( a, SIGNAL( activated() ), this, SLOT( RunScript() ) ); 491 connect( a, SIGNAL( activated() ), this, SLOT( RunScript() ) );
492 a->addTo( file ); 492 a->addTo( file );
493#endif 493#endif
494 /* 494 /*
495 a = new QAction( tr( "Revert" ), geticon( "close" ), QString::null, 0, this, 0 ); 495 a = new QAction( tr( "Revert" ), geticon( "close" ), QString::null, 0, this, 0 );
496 connect( a, SIGNAL( activated() ), this, SLOT( fileRevert() ) ); 496 connect( a, SIGNAL( activated() ), this, SLOT( fileRevert() ) );
497 a->addTo( file ); 497 a->addTo( file );
498 498
499 a = new QAction( tr( "Cut" ), geticon( "cut" ), QString::null, 0, this, 0 ); 499 a = new QAction( tr( "Cut" ), geticon( "cut" ), QString::null, 0, this, 0 );
500 connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); 500 connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) );
501 a->addTo( filebar() ); 501 a->addTo( filebar() );
502 a->addTo( edit ); 502 a->addTo( edit );
503 */ 503 */
504 504
505 m_info_action = new QAction( tr( "Info" ), geticon( "UtilsIcon" ), QString::null, 0, this, NULL); 505 m_info_action = new QAction( tr( "Info" ), geticon( "UtilsIcon" ), QString::null, 0, this, NULL);
506 connect( m_info_action, SIGNAL( activated() ), this, SLOT( showinfo() ) ); 506 connect( m_info_action, SIGNAL( activated() ), this, SLOT( showinfo() ) );
507 m_info_action->addTo( file ); 507 m_info_action->addTo( file );
508 508
509 m_touch_action = new QAction( tr( "Two/One Touch" ), geticon( "1to1" ), QString::null, 0, this, NULL, true ); 509 m_touch_action = new QAction( tr( "Two/One Touch" ), geticon( "1to1" ), QString::null, 0, this, NULL, true );
510 connect( m_touch_action, SIGNAL( toggled(bool) ), this, SLOT( setTwoTouch(bool) ) ); 510 connect( m_touch_action, SIGNAL( toggled(bool) ), this, SLOT( setTwoTouch(bool) ) );
511 m_touch_action->setOn(m_twoTouch); 511 m_touch_action->setOn(m_twoTouch);
512 m_touch_action->addTo( file ); 512 m_touch_action->addTo( file );
513 513
514 m_find_action = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, NULL); 514 m_find_action = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, NULL);
515 connect( m_find_action, SIGNAL( activated() ), this, SLOT( editFind() ) ); 515 connect( m_find_action, SIGNAL( activated() ), this, SLOT( editFind() ) );
516 file->insertSeparator(); 516 file->insertSeparator();
517// a->addTo( bar ); 517// a->addTo( bar );
518 m_find_action->addTo( file ); 518 m_find_action->addTo( file );
519 519
520 m_exportlinks_action = new QAction( tr( "Export Links" ), QString::null, 0, this, NULL); 520 m_exportlinks_action = new QAction( tr( "Export Links" ), QString::null, 0, this, NULL);
521 connect( m_exportlinks_action, SIGNAL( activated() ), this, SLOT( ExportLinks() ) ); 521 connect( m_exportlinks_action, SIGNAL( activated() ), this, SLOT( ExportLinks() ) );
522 m_exportlinks_action->addTo( file ); 522 m_exportlinks_action->addTo( file );
523 523
524 m_scrollButton = new QAction( tr( "Scroll" ), getmyicon( "panel-arrow-down" ), QString::null, 0, this, 0, true ); 524 m_scrollButton = new QAction( tr( "Scroll" ), getmyicon( "panel-arrow-down" ), QString::null, 0, this, 0, true );
525 connect( m_scrollButton, SIGNAL( toggled(bool) ), this, SLOT( autoScroll(bool) ) ); 525 connect( m_scrollButton, SIGNAL( toggled(bool) ), this, SLOT( autoScroll(bool) ) );
526 m_scrollButton->addTo(navigation); 526 m_scrollButton->addTo(navigation);
527 m_scrollButton->setOn(false); 527 m_scrollButton->setOn(false);
528 528
529 m_start_action = new QAction( tr( "Goto Start" ), geticon( "start" ), QString::null, 0, this, NULL); 529 m_start_action = new QAction( tr( "Goto Start" ), geticon( "start" ), QString::null, 0, this, NULL);
530 connect( m_start_action, SIGNAL( activated() ), this, SLOT( gotoStart() ) ); 530 connect( m_start_action, SIGNAL( activated() ), this, SLOT( gotoStart() ) );
531 m_start_action->addTo(navigation); 531 m_start_action->addTo(navigation);
532 532
533 m_end_action = new QAction( tr( "Goto End" ), geticon( "finish" ), QString::null, 0, this, NULL); 533 m_end_action = new QAction( tr( "Goto End" ), geticon( "finish" ), QString::null, 0, this, NULL);
534 connect( m_end_action, SIGNAL( activated() ), this, SLOT( gotoEnd() ) ); 534 connect( m_end_action, SIGNAL( activated() ), this, SLOT( gotoEnd() ) );
535 m_end_action->addTo(navigation); 535 m_end_action->addTo(navigation);
536 536
537 m_jump_action = new QAction( tr( "Jump" ), geticon( "rotate" ), QString::null, 0, this, NULL); 537 m_jump_action = new QAction( tr( "Jump" ), geticon( "rotate" ), QString::null, 0, this, NULL);
538 connect( m_jump_action, SIGNAL( activated() ), this, SLOT( jump() ) ); 538 connect( m_jump_action, SIGNAL( activated() ), this, SLOT( jump() ) );
539 m_jump_action->addTo(navigation); 539 m_jump_action->addTo(navigation);
540 540
541 m_pageline_action = new QAction( tr( "Page/Line Scroll" ), geticon( "pass" ), QString::null, 0, this, NULL, true ); 541 m_pageline_action = new QAction( tr( "Page/Line Scroll" ), geticon( "pass" ), QString::null, 0, this, NULL, true );
542 connect( m_pageline_action, SIGNAL( toggled(bool) ), this, SLOT( pagemode(bool) ) ); 542 connect( m_pageline_action, SIGNAL( toggled(bool) ), this, SLOT( pagemode(bool) ) );
543 m_pageline_action->addTo(navigation); 543 m_pageline_action->addTo(navigation);
544 m_pageline_action->setOn(reader->m_bpagemode); 544 m_pageline_action->setOn(reader->m_bpagemode);
545 545
546 m_pageup_action = new QAction( tr( "Up" ), geticon( "up" ), QString::null, 0, this, 0 ); 546 m_pageup_action = new QAction( tr( "Up" ), geticon( "up" ), QString::null, 0, this, 0 );
547 connect( m_pageup_action, SIGNAL( activated() ), this, SLOT( pageup() ) ); 547 connect( m_pageup_action, SIGNAL( activated() ), this, SLOT( pageup() ) );
548 m_pageup_action->addTo( navigation ); 548 m_pageup_action->addTo( navigation );
549 549
550 m_pagedn_action = new QAction( tr( "Down" ), geticon( "down" ), QString::null, 0, this, 0 ); 550 m_pagedn_action = new QAction( tr( "Down" ), geticon( "down" ), QString::null, 0, this, 0 );
551 connect( m_pagedn_action, SIGNAL( activated() ), this, SLOT( pagedn() ) ); 551 connect( m_pagedn_action, SIGNAL( activated() ), this, SLOT( pagedn() ) );
552 m_pagedn_action->addTo( navigation ); 552 m_pagedn_action->addTo( navigation );
553 553
554 m_back_action = new QAction( tr( "Back" ), geticon( "back" ), QString::null, 0, this, 0 ); 554 m_back_action = new QAction( tr( "Back" ), geticon( "back" ), QString::null, 0, this, 0 );
555 connect( m_back_action, SIGNAL( activated() ), reader, SLOT( goBack() ) ); 555 connect( m_back_action, SIGNAL( activated() ), reader, SLOT( goBack() ) );
556 m_back_action->addTo( navigation ); 556 m_back_action->addTo( navigation );
557 557
558 m_home_action = new QAction( tr( "Home" ), geticon( "home" ), QString::null, 0, this, 0 ); 558 m_home_action = new QAction( tr( "Home" ), geticon( "home" ), QString::null, 0, this, 0 );
559 connect( m_home_action, SIGNAL( activated() ), reader, SLOT( goHome() ) ); 559 connect( m_home_action, SIGNAL( activated() ), reader, SLOT( goHome() ) );
560 m_home_action->addTo( navigation ); 560 m_home_action->addTo( navigation );
561 561
562 m_forward_action = new QAction( tr( "Forward" ), geticon( "forward" ), QString::null, 0, this, 0 ); 562 m_forward_action = new QAction( tr( "Forward" ), geticon( "forward" ), QString::null, 0, this, 0 );
563 connect( m_forward_action, SIGNAL( activated() ), reader, SLOT( goForward() ) ); 563 connect( m_forward_action, SIGNAL( activated() ), reader, SLOT( goForward() ) );
564 m_forward_action->addTo( navigation ); 564 m_forward_action->addTo( navigation );
565 565
566 /* 566 /*
567 a = new QAction( tr( "Find" ), QString::null, 0, this, NULL, true ); 567 a = new QAction( tr( "Find" ), QString::null, 0, this, NULL, true );
568 // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) ); 568 // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) );
569 a->addTo( file ); 569 a->addTo( file );
570 570
571 a = new QAction( tr( "Find Again" ), QString::null, 0, this, NULL, true ); 571 a = new QAction( tr( "Find Again" ), QString::null, 0, this, NULL, true );
572 // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) ); 572 // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) );
573 a->addTo( file ); 573 a->addTo( file );
574 */ 574 */
575 575
576// file->insertSeparator(); 576// file->insertSeparator();
577 577
578#ifdef _SCROLLPIPE 578#ifdef _SCROLLPIPE
579 579
580 QActionGroup* ag = new QActionGroup(this); 580 QActionGroup* ag = new QActionGroup(this);
581 ag->setExclusive(false); 581 ag->setExclusive(false);
582 spacemenu = new QPopupMenu(this); 582 spacemenu = new QPopupMenu(this);
583 file->insertItem( tr( "Scrolling" ), spacemenu ); 583 file->insertItem( tr( "Scrolling" ), spacemenu );
584 584
585 a = new QAction( tr( "Set Target" ), QString::null, 0, ag, NULL); 585 a = new QAction( tr( "Set Target" ), QString::null, 0, ag, NULL);
586 connect( a, SIGNAL( activated() ), this, SLOT( setpipetarget() ) ); 586 connect( a, SIGNAL( activated() ), this, SLOT( setpipetarget() ) );
587 587
588 a = new QAction( tr( "Pause Paras" ), QString::null, 0, ag, NULL, true ); 588 a = new QAction( tr( "Pause Paras" ), QString::null, 0, ag, NULL, true );
589 connect( a, SIGNAL( toggled(bool) ), this, SLOT( setpause(bool) ) ); 589 connect( a, SIGNAL( toggled(bool) ), this, SLOT( setpause(bool) ) );
590 a->setOn(reader->m_pauseAfterEachPara); 590 a->setOn(reader->m_pauseAfterEachPara);
591 591
592 ag->addTo(spacemenu); 592 ag->addTo(spacemenu);
593// file->insertSeparator(); 593// file->insertSeparator();
594 594
595#endif 595#endif
596 596
597/* 597/*
598 a = new QAction( tr( "Import" ), QString::null, 0, this, NULL ); 598 a = new QAction( tr( "Import" ), QString::null, 0, this, NULL );
599 connect( a, SIGNAL( activated() ), this, SLOT( importFiles() ) ); 599 connect( a, SIGNAL( activated() ), this, SLOT( importFiles() ) );
600 a->addTo( file ); 600 a->addTo( file );
601*/ 601*/
602 602
603 /* 603 /*
604 a = new QAction( tr( "Paste" ), geticon( "paste" ), QString::null, 0, this, 0 ); 604 a = new QAction( tr( "Paste" ), geticon( "paste" ), QString::null, 0, this, 0 );
605 connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); 605 connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) );
606 a->addTo( fileBar ); 606 a->addTo( fileBar );
607 a->addTo( edit ); 607 a->addTo( edit );
608 */ 608 */
609 609
610// a = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, 0 ); 610// a = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, 0 );
611 611
612 m_fullscreen = false; 612 m_fullscreen = false;
613 m_actFullscreen = new QAction( tr( "Fullscreen" ), geticon( "fullscreen" ), QString::null, 0, this, NULL, true ); 613 m_actFullscreen = new QAction( tr( "Fullscreen" ), geticon( "fullscreen" ), QString::null, 0, this, NULL, true );
614 connect( m_actFullscreen, SIGNAL( toggled(bool) ), this, SLOT( setfullscreen(bool) ) ); 614 connect( m_actFullscreen, SIGNAL( toggled(bool) ), this, SLOT( setfullscreen(bool) ) );
615 m_actFullscreen->setOn(m_fullscreen); 615 m_actFullscreen->setOn(m_fullscreen);
616 m_actFullscreen->addTo( view ); 616 m_actFullscreen->addTo( view );
617 617
618 view->insertSeparator(); 618 view->insertSeparator();
619 619
620 m_zoomin_action = new QAction( tr( "Zoom In" ), geticon( "zoom" ), QString::null, 0, this); 620 m_zoomin_action = new QAction( tr( "Zoom In" ), geticon( "zoom" ), QString::null, 0, this);
621 connect( m_zoomin_action, SIGNAL( activated() ), this, SLOT( zoomin() ) ); 621 connect( m_zoomin_action, SIGNAL( activated() ), this, SLOT( zoomin() ) );
622 m_zoomin_action->addTo( view ); 622 m_zoomin_action->addTo( view );
623 623
624 m_zoomout_action = new QAction( tr( "Zoom Out" ), geticon( "mag" ), QString::null, 0, this); 624 m_zoomout_action = new QAction( tr( "Zoom Out" ), geticon( "mag" ), QString::null, 0, this);
625 connect( m_zoomout_action, SIGNAL( activated() ), this, SLOT( zoomout() ) ); 625 connect( m_zoomout_action, SIGNAL( activated() ), this, SLOT( zoomout() ) );
626 m_zoomout_action->addTo( view ); 626 m_zoomout_action->addTo( view );
627 627
628 view->insertSeparator(); 628 view->insertSeparator();
629 m_setfont_action = new QAction( tr( "Set Font" ), getmyicon( "font" ), QString::null, 0, this); 629 m_setfont_action = new QAction( tr( "Set Font" ), getmyicon( "font" ), QString::null, 0, this);
630 connect( m_setfont_action, SIGNAL( activated() ), this, SLOT( setfont() ) ); 630 connect( m_setfont_action, SIGNAL( activated() ), this, SLOT( setfont() ) );
631 m_setfont_action->addTo( view ); 631 m_setfont_action->addTo( view );
632 632
633 view->insertSeparator(); 633 view->insertSeparator();
634 m_setenc_action = new QAction( tr( "Set Encoding" ), getmyicon( "charset" ), QString::null, 0, this); 634 m_setenc_action = new QAction( tr( "Set Encoding" ), getmyicon( "charset" ), QString::null, 0, this);
635 connect( m_setenc_action, SIGNAL( activated() ), this, SLOT( chooseencoding() ) ); 635 connect( m_setenc_action, SIGNAL( activated() ), this, SLOT( chooseencoding() ) );
636 m_setenc_action->addTo( view ); 636 m_setenc_action->addTo( view );
637 637
638 m_setmono_action = new QAction( tr( "Ideogram" ), getmyicon( "ideogram" ), QString::null, 0, this, NULL, true); 638 m_setmono_action = new QAction( tr( "Ideogram" ), getmyicon( "ideogram" ), QString::null, 0, this, NULL, true);
639 connect( m_setmono_action, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) ); 639 connect( m_setmono_action, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) );
640 m_setmono_action->addTo( view ); 640 m_setmono_action->addTo( view );
641 m_setmono_action->setOn(reader->m_bMonoSpaced); 641 m_setmono_action->setOn(reader->m_bMonoSpaced);
642 642
643 643
644 // a = new QAction( tr( "Zoom" ), QString::null, 0, this, NULL, true ); 644 // a = new QAction( tr( "Zoom" ), QString::null, 0, this, NULL, true );
645 // a = new QAction( tr( "Zoom" ), geticon( "mag" ), QString::null, 0, this, 0 ); 645 // a = new QAction( tr( "Zoom" ), geticon( "mag" ), QString::null, 0, this, 0 );
646 646
647 647
648 648
649 // a->addTo( filebar() ); 649 // a->addTo( filebar() );
650// view->insertSeparator(); 650// view->insertSeparator();
651 651
652/* 652/*
653 a = new QAction( tr( "Ideogram/Word" ), QString::null, 0, this, NULL, true ); 653 a = new QAction( tr( "Ideogram/Word" ), QString::null, 0, this, NULL, true );
654 connect( a, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) ); 654 connect( a, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) );
655 a->setOn(reader->m_bMonoSpaced); 655 a->setOn(reader->m_bMonoSpaced);
656 a->addTo( view ); 656 a->addTo( view );
657*/ 657*/
658/* 658/*
659 a = new QAction( tr( "Set Width" ), QString::null, 0, this, NULL); 659 a = new QAction( tr( "Set Width" ), QString::null, 0, this, NULL);
660 connect( a, SIGNAL( activated() ), this, SLOT( setspacing() ) ); 660 connect( a, SIGNAL( activated() ), this, SLOT( setspacing() ) );
661 a->addTo( view ); 661 a->addTo( view );
662*/ 662*/
663 663
664 m_mark_action = new QAction( tr( "Bookmark" ), getmyicon( "bookmark" ), QString::null, 0, this, NULL); 664 m_mark_action = new QAction( tr( "Bookmark" ), getmyicon( "bookmark" ), QString::null, 0, this, NULL);
665 connect( m_mark_action, SIGNAL( activated() ), this, SLOT( addbkmk() ) ); 665 connect( m_mark_action, SIGNAL( activated() ), this, SLOT( addbkmk() ) );
666 m_mark_action->addTo( marks ); 666 m_mark_action->addTo( marks );
667 667
668 m_annotate_action = new QAction( tr( "Annotate" ), getmyicon( "annotate" ), QString::null, 0, this, NULL); 668 m_annotate_action = new QAction( tr( "Annotate" ), getmyicon( "annotate" ), QString::null, 0, this, NULL);
669 connect( m_annotate_action, SIGNAL( activated() ), this, SLOT( addanno() ) ); 669 connect( m_annotate_action, SIGNAL( activated() ), this, SLOT( addanno() ) );
670 m_annotate_action->addTo( marks ); 670 m_annotate_action->addTo( marks );
671 671
672 m_goto_action = new QAction( tr( "Goto" ), getmyicon( "bookmark_goto" ), QString::null, 0, this, NULL, false ); 672 m_goto_action = new QAction( tr( "Goto" ), getmyicon( "bookmark_goto" ), QString::null, 0, this, NULL, false );
673 connect( m_goto_action, SIGNAL( activated() ), this, SLOT( do_gotomark() ) ); 673 connect( m_goto_action, SIGNAL( activated() ), this, SLOT( do_gotomark() ) );
674 m_goto_action->addTo( marks ); 674 m_goto_action->addTo( marks );
675 675
676 m_delete_action = new QAction( tr( "Delete" ), getmyicon( "bookmark_delete" ), QString::null, 0, this, NULL); 676 m_delete_action = new QAction( tr( "Delete" ), getmyicon( "bookmark_delete" ), QString::null, 0, this, NULL);
677 connect( m_delete_action, SIGNAL( activated() ), this, SLOT( do_delmark() ) ); 677 connect( m_delete_action, SIGNAL( activated() ), this, SLOT( do_delmark() ) );
678 m_delete_action->addTo( marks ); 678 m_delete_action->addTo( marks );
679 679
680 m_autogen_action = new QAction( tr( "Autogen" ), geticon( "exec" ), QString::null, 0, this, NULL, false ); 680 m_autogen_action = new QAction( tr( "Autogen" ), geticon( "exec" ), QString::null, 0, this, NULL, false );
681 connect( m_autogen_action, SIGNAL( activated() ), this, SLOT( do_autogen() ) ); 681 connect( m_autogen_action, SIGNAL( activated() ), this, SLOT( do_autogen() ) );
682 marks->insertSeparator(); 682 marks->insertSeparator();
683 m_autogen_action->addTo( marks ); 683 m_autogen_action->addTo( marks );
684 684
685 m_clear_action = new QAction( tr( "Clear" ), getmyicon( "bookmark_clear" ), QString::null, 0, this, NULL); 685 m_clear_action = new QAction( tr( "Clear" ), getmyicon( "bookmark_clear" ), QString::null, 0, this, NULL);
686 connect( m_clear_action, SIGNAL( activated() ), this, SLOT( clearBkmkList() ) ); 686 connect( m_clear_action, SIGNAL( activated() ), this, SLOT( clearBkmkList() ) );
687 m_clear_action->addTo( marks ); 687 m_clear_action->addTo( marks );
688 688
689 m_save_action = new QAction( tr( "Save" ), getmyicon( "bookmark_save" ), QString::null, 0, this, NULL ); 689 m_save_action = new QAction( tr( "Save" ), getmyicon( "bookmark_save" ), QString::null, 0, this, NULL );
690 connect( m_save_action, SIGNAL( activated() ), this, SLOT( savebkmks() ) ); 690 connect( m_save_action, SIGNAL( activated() ), this, SLOT( savebkmks() ) );
691 m_save_action->addTo( marks ); 691 m_save_action->addTo( marks );
692 692
693 m_tidy_action = new QAction( tr( "Tidy" ), getmyicon( "bookmark_tidy" ), QString::null, 0, this, NULL); 693 m_tidy_action = new QAction( tr( "Tidy" ), getmyicon( "bookmark_tidy" ), QString::null, 0, this, NULL);
694 connect( m_tidy_action, SIGNAL( activated() ), this, SLOT( listBkmkFiles() ) ); 694 connect( m_tidy_action, SIGNAL( activated() ), this, SLOT( listBkmkFiles() ) );
695 marks->insertSeparator(); 695 marks->insertSeparator();
696 m_tidy_action->addTo( marks ); 696 m_tidy_action->addTo( marks );
697 697
698 m_startBlock_action = new QAction( tr( "Start Block" ), geticon( "new" ), QString::null, 0, this, NULL); 698 m_startBlock_action = new QAction( tr( "Start Block" ), geticon( "new" ), QString::null, 0, this, NULL);
699 connect( m_startBlock_action, SIGNAL( activated() ), this, SLOT( editMark() ) ); 699 connect( m_startBlock_action, SIGNAL( activated() ), this, SLOT( editMark() ) );
700 marks->insertSeparator(); 700 marks->insertSeparator();
701 m_startBlock_action->addTo( marks ); 701 m_startBlock_action->addTo( marks );
702 702
703 m_endBlock_action = new QAction( tr( "Copy Block" ), geticon( "copy" ), QString::null, 0, this, NULL); 703 m_endBlock_action = new QAction( tr( "Copy Block" ), geticon( "copy" ), QString::null, 0, this, NULL);
704 connect( m_endBlock_action, SIGNAL( activated() ), this, SLOT( editCopy() ) ); 704 connect( m_endBlock_action, SIGNAL( activated() ), this, SLOT( editCopy() ) );
705 m_endBlock_action->addTo( marks ); 705 m_endBlock_action->addTo( marks );
706 706
707 m_bkmkAvail = NULL; 707 m_bkmkAvail = NULL;
708 708
709 709
710 setToolBarsMovable(m_tbmove); 710 setToolBarsMovable(m_tbmove);
711 addtoolbars(&config); 711 addtoolbars(&config);
712 712
713 pbar = new QProgressBar(this); 713 pbar = new QProgressBar(this);
714 pbar->hide(); 714 pbar->hide();
715 715
716 searchBar = new QFloatBar( "Search", this, QMainWindow::Top, TRUE ); 716 searchBar = new QFloatBar( "Search", this, QMainWindow::Top, TRUE );
717 717
718 searchBar->setHorizontalStretchable( TRUE ); 718 searchBar->setHorizontalStretchable( TRUE );
719 719
720 connect(searchBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() )); 720 connect(searchBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() ));
721 721
722 searchEdit = new QLineEdit( searchBar, "searchEdit" ); 722 searchEdit = new QLineEdit( searchBar, "searchEdit" );
723// QFont f("unifont", 16 /*, QFont::Bold*/); 723// QFont f("unifont", 16 /*, QFont::Bold*/);
724// searchEdit->setFont( f ); 724// searchEdit->setFont( f );
725 searchBar->setStretchableWidget( searchEdit ); 725 searchBar->setStretchableWidget( searchEdit );
726 726
727 727
728#ifdef __ISEARCH 728#ifdef __ISEARCH
729 connect( searchEdit, SIGNAL( textChanged( const QString & ) ), 729 connect( searchEdit, SIGNAL( textChanged(const QString&) ),
730 this, SLOT( search( const QString& ) ) ); 730 this, SLOT( search(const QString&) ) );
731#else 731#else
732 connect( searchEdit, SIGNAL( returnPressed( ) ), 732 connect( searchEdit, SIGNAL( returnPressed() ),
733 this, SLOT( search( ) ) ); 733 this, SLOT( search() ) );
734#endif 734#endif
735 QAction*a = new QAction( tr( "Find Next" ), geticon( "next" ), QString::null, 0, this, 0 ); 735 QAction*a = new QAction( tr( "Find Next" ), geticon( "next" ), QString::null, 0, this, 0 );
736 connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) ); 736 connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) );
737 a->addTo( searchBar ); 737 a->addTo( searchBar );
738 738
739 a = new QAction( tr( "Close Find" ), geticon( "close" ), QString::null, 0, this, 0 ); 739 a = new QAction( tr( "Close Find" ), geticon( "close" ), QString::null, 0, this, 0 );
740 connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); 740 connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) );
741 a->addTo( searchBar ); 741 a->addTo( searchBar );
742 742
743 searchBar->hide(); 743 searchBar->hide();
744 744
745 regBar = new QFloatBar( "Autogen", this, QMainWindow::Top, TRUE ); 745 regBar = new QFloatBar( "Autogen", this, QMainWindow::Top, TRUE );
746 connect(regBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() )); 746 connect(regBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() ));
747 747
748 regBar->setHorizontalStretchable( TRUE ); 748 regBar->setHorizontalStretchable( TRUE );
749 749
750 regEdit = new QLineEdit( regBar, "regEdit" ); 750 regEdit = new QLineEdit( regBar, "regEdit" );
751// regEdit->setFont( f ); 751// regEdit->setFont( f );
752 752
753 regBar->setStretchableWidget( regEdit ); 753 regBar->setStretchableWidget( regEdit );
754 754
755 connect( regEdit, SIGNAL( returnPressed( ) ), 755 connect( regEdit, SIGNAL( returnPressed() ),
756 this, SLOT( do_regaction() ) ); 756 this, SLOT( do_regaction() ) );
757 757
758 a = new QAction( tr( "Do Reg" ), geticon( "enter" ), QString::null, 0, this, 0 ); 758 a = new QAction( tr( "Do Reg" ), geticon( "enter" ), QString::null, 0, this, 0 );
759 connect( a, SIGNAL( activated() ), this, SLOT( do_regaction() ) ); 759 connect( a, SIGNAL( activated() ), this, SLOT( do_regaction() ) );
760 a->addTo( regBar ); 760 a->addTo( regBar );
761 761
762 a = new QAction( tr( "Close Edit" ), geticon( "close" ), QString::null, 0, this, 0 ); 762 a = new QAction( tr( "Close Edit" ), geticon( "close" ), QString::null, 0, this, 0 );
763 connect( a, SIGNAL( activated() ), this, SLOT( regClose() ) ); 763 connect( a, SIGNAL( activated() ), this, SLOT( regClose() ) );
764 a->addTo( regBar ); 764 a->addTo( regBar );
765 765
766 regBar->hide(); 766 regBar->hide();
767 767
768 m_fontBar = new QToolBar( "Autogen", this, QMainWindow::Top, TRUE ); 768 m_fontBar = new QToolBar( "Autogen", this, QMainWindow::Top, TRUE );
769 769
770 m_fontBar->setHorizontalStretchable( TRUE ); 770 m_fontBar->setHorizontalStretchable( TRUE );
771 771
772// qDebug("Font selector"); 772// qDebug("Font selector");
773 m_fontSelector = new QComboBox(false, m_fontBar); 773 m_fontSelector = new QComboBox(false, m_fontBar);
774 m_fontBar->setStretchableWidget( m_fontSelector ); 774 m_fontBar->setStretchableWidget( m_fontSelector );
775 { 775 {
776#ifndef USEQPE 776#ifndef USEQPE
777 QFontDatabase f; 777 QFontDatabase f;
778#else 778#else
779 FontDatabase f; 779 FontDatabase f;
780#endif 780#endif
781 QStringList flist = f.families(); 781 QStringList flist = f.families();
782 bool realfont = false; 782 bool realfont = false;
783 for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) 783 for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++)
784 { 784 {
785 if (reader->m_fontname == *nm) 785 if (reader->m_fontname == *nm)
786 { 786 {
787 realfont = true; 787 realfont = true;
788 } 788 }
789 if ((*nm).contains(FIXEDFONT,false)) reader->m_fontControl.hasCourier(true, *nm); 789 if ((*nm).contains(FIXEDFONT,false)) reader->m_fontControl.hasCourier(true, *nm);
790 } 790 }
791 if (!realfont) reader->m_fontname = flist[0]; 791 if (!realfont) reader->m_fontname = flist[0];
792 } // delete the FontDatabase!!! 792 } // delete the FontDatabase!!!
793 connect( m_fontSelector, SIGNAL( activated(const QString& ) ), 793 connect( m_fontSelector, SIGNAL( activated(const QString&) ),
794 this, SLOT( do_setfont(const QString&) ) ); 794 this, SLOT( do_setfont(const QString&) ) );
795 connect( m_fontSelector, SIGNAL( activated(int ) ), 795 connect( m_fontSelector, SIGNAL( activated(int) ),
796 this, SLOT( do_setencoding(int) ) ); 796 this, SLOT( do_setencoding(int) ) );
797 797
798 m_fontBar->hide(); 798 m_fontBar->hide();
799 m_fontVisible = false; 799 m_fontVisible = false;
800#ifdef USEMSGS 800#ifdef USEMSGS
801 connect(qApp, SIGNAL( appMessage(const QCString&, const QByteArray& ) ), 801 connect(qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ),
802 this, SLOT( msgHandler(const QCString&, const QByteArray&) ) ); 802 this, SLOT( msgHandler(const QCString&,const QByteArray&) ) );
803#endif 803#endif
804// qDebug("Initing"); 804// qDebug("Initing");
805 reader->init(); 805 reader->init();
806// qDebug("Inited"); 806// qDebug("Inited");
807// m_buttonAction[m_spaceTarget]->setOn(true); 807// m_buttonAction[m_spaceTarget]->setOn(true);
808// qDebug("fonting"); 808// qDebug("fonting");
809 do_setfont(reader->m_fontname); 809 do_setfont(reader->m_fontname);
810 if (!reader->m_lastfile.isEmpty()) 810 if (!reader->m_lastfile.isEmpty())
811 { 811 {
812 //qDebug("doclnk"); 812 //qDebug("doclnk");
813 //doc = new DocLnk(reader->m_lastfile); 813 //doc = new DocLnk(reader->m_lastfile);
814 //qDebug("doclnk done"); 814 //qDebug("doclnk done");
815 if (pOpenlist != NULL) 815 if (pOpenlist != NULL)
816 { 816 {
817 817
818/* 818/*
819 int ind = 0; 819 int ind = 0;
820 Bkmk* p = (*pOpenlist)[ind]; 820 Bkmk* p = (*pOpenlist)[ind];
821 while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile) 821 while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile)
822 { 822 {
823 p = (*pOpenlist)[++ind]; 823 p = (*pOpenlist)[++ind];
824 } 824 }
825*/ 825*/
826 Bkmk* p = NULL; 826 Bkmk* p = NULL;
827 for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++) 827 for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++)
828 { 828 {
829 p = iter.pContent(); 829 p = iter.pContent();
830 if (toQString(CFiledata(p->anno()).name()) == reader->m_lastfile) 830 if (toQString(CFiledata(p->anno()).name()) == reader->m_lastfile)
831 { 831 {
832 break; 832 break;
833 } 833 }
834 // qDebug("Item:%s", (const char*)toQString(CFiledata(p->anno()).name())); 834 // qDebug("Item:%s", (const char*)toQString(CFiledata(p->anno()).name()));
835 p = NULL; 835 p = NULL;
836 } 836 }
837 if (p != NULL) 837 if (p != NULL)
838 { 838 {
839 //qDebug("openfrombkmk"); 839 //qDebug("openfrombkmk");
840 if (!openfrombkmk(p)) 840 if (!openfrombkmk(p))
841 showEditTools(); 841 showEditTools();
842 } 842 }
843 else 843 else
844 { 844 {
845 //qDebug("openfile"); 845 //qDebug("openfile");
846 openFile( reader->m_lastfile ); 846 openFile( reader->m_lastfile );
847 } 847 }
848 } 848 }
849 else 849 else
850 { 850 {
851 // qDebug("Openfile 2"); 851 // qDebug("Openfile 2");
852 if (!reader->m_lastfile.isEmpty()) 852 if (!reader->m_lastfile.isEmpty())
853 openFile( reader->m_lastfile ); 853 openFile( reader->m_lastfile );
854 } 854 }
855 } 855 }
856 else 856 else
857 { 857 {
858 showEditTools(); 858 showEditTools();
859 } 859 }
860// qApp->processEvents(); 860// qApp->processEvents();
861 reader->bDoUpdates = true; 861 reader->bDoUpdates = true;
862 reader->update(); 862 reader->update();
863 config.setGroup("Version"); 863 config.setGroup("Version");
864 int major = config.readNumEntry("Major", 0); 864 int major = config.readNumEntry("Major", 0);
865 int bkmktype = config.readNumEntry("BkmkType", 0); 865 int bkmktype = config.readNumEntry("BkmkType", 0);
866 char minor = config.readNumEntry("Minor", 0); 866 char minor = config.readNumEntry("Minor", 0);
867 if (CheckVersion(major, bkmktype, minor)) 867 if (CheckVersion(major, bkmktype, minor))
868 { 868 {
869 config.writeEntry("Major", major); 869 config.writeEntry("Major", major);
870 config.writeEntry("BkmkType", bkmktype); 870 config.writeEntry("BkmkType", bkmktype);
871 config.writeEntry("Minor", (int)minor); 871 config.writeEntry("Minor", (int)minor);
872 } 872 }
873// qDebug("finished update"); 873// qDebug("finished update");
874} 874}
875 875
876void QTReaderApp::addtoolbars(Config* config) 876void QTReaderApp::addtoolbars(Config* config)
877{ 877{
878 config->setGroup("Toolbar"); 878 config->setGroup("Toolbar");
879 879
880 if (fileBar != NULL) 880 if (fileBar != NULL)
881 { 881 {
882 if (fileBar != menubar) 882 if (fileBar != menubar)
883 { 883 {
884 fileBar->clear(); 884 fileBar->clear();
885 } 885 }
886 else 886 else
887 { 887 {
888 m_preferences_action->removeFrom( filebar() ); 888 m_preferences_action->removeFrom( filebar() );
889 m_open_action->removeFrom( filebar() ); 889 m_open_action->removeFrom( filebar() );
890 m_close_action->removeFrom( filebar() ); 890 m_close_action->removeFrom( filebar() );
891 m_info_action->removeFrom( filebar() ); 891 m_info_action->removeFrom( filebar() );
892 m_touch_action->removeFrom( filebar() ); 892 m_touch_action->removeFrom( filebar() );
893 m_find_action->removeFrom( filebar() ); 893 m_find_action->removeFrom( filebar() );
894 } 894 }
895 } 895 }
896 896
897 m_preferences_action->addTo( filebar() ); 897 m_preferences_action->addTo( filebar() );
898 addfilebar(config, "Open", m_open_action); 898 addfilebar(config, "Open", m_open_action);
899 addfilebar(config, "Close", m_close_action); 899 addfilebar(config, "Close", m_close_action);
900 addfilebar(config, "Info", m_info_action); 900 addfilebar(config, "Info", m_info_action);
901 addfilebar(config, "Two/One Touch", m_touch_action); 901 addfilebar(config, "Two/One Touch", m_touch_action);
902 addfilebar(config, "Find", m_find_action); 902 addfilebar(config, "Find", m_find_action);
903 903
904 if (navBar != NULL) 904 if (navBar != NULL)
905 { 905 {
906 if ((navBar == fileBar) && (fileBar == menubar)) 906 if ((navBar == fileBar) && (fileBar == menubar))
907 { 907 {
908 m_scrollButton->removeFrom( navbar() ); 908 m_scrollButton->removeFrom( navbar() );
909 m_start_action->removeFrom( navbar() ); 909 m_start_action->removeFrom( navbar() );
910 m_end_action->removeFrom( navbar() ); 910 m_end_action->removeFrom( navbar() );
911 m_jump_action->removeFrom( navbar() ); 911 m_jump_action->removeFrom( navbar() );
912 m_pageline_action->removeFrom( navbar() ); 912 m_pageline_action->removeFrom( navbar() );
913 m_pageup_action->removeFrom( navbar() ); 913 m_pageup_action->removeFrom( navbar() );
914 m_pagedn_action->removeFrom( navbar() ); 914 m_pagedn_action->removeFrom( navbar() );
915 m_back_action->removeFrom( navbar() ); 915 m_back_action->removeFrom( navbar() );
916 m_home_action->removeFrom( navbar() ); 916 m_home_action->removeFrom( navbar() );
917 m_forward_action->removeFrom( navbar() ); 917 m_forward_action->removeFrom( navbar() );
918 } 918 }
919 else if (navBar != fileBar) 919 else if (navBar != fileBar)
920 { 920 {
921 navBar->clear(); 921 navBar->clear();
922 } 922 }
923 } 923 }
924 924
925 addnavbar(config, "Scroll", m_scrollButton); 925 addnavbar(config, "Scroll", m_scrollButton);
926 addnavbar(config, "Goto Start", m_start_action); 926 addnavbar(config, "Goto Start", m_start_action);
927 addnavbar(config, "Goto End", m_end_action); 927 addnavbar(config, "Goto End", m_end_action);
928 928
929 addnavbar(config, "Jump", m_jump_action); 929 addnavbar(config, "Jump", m_jump_action);
930 addnavbar(config, "Page/Line Scroll", m_pageline_action); 930 addnavbar(config, "Page/Line Scroll", m_pageline_action);
931 931
932 addnavbar(config, "Page Up", m_pageup_action); 932 addnavbar(config, "Page Up", m_pageup_action);
933 addnavbar(config, "Page Down", m_pagedn_action); 933 addnavbar(config, "Page Down", m_pagedn_action);
934 934
935 addnavbar(config, "Back", m_back_action); 935 addnavbar(config, "Back", m_back_action);
936 addnavbar(config, "Home", m_home_action); 936 addnavbar(config, "Home", m_home_action);
937 addnavbar(config, "Forward", m_forward_action); 937 addnavbar(config, "Forward", m_forward_action);
938 938
939 if (viewBar != NULL) 939 if (viewBar != NULL)
940 { 940 {
941 if ((viewBar == fileBar) && (fileBar == menubar)) 941 if ((viewBar == fileBar) && (fileBar == menubar))
942 { 942 {
943 m_actFullscreen->removeFrom( filebar() ); 943 m_actFullscreen->removeFrom( filebar() );
944 m_zoomin_action->removeFrom( viewbar() ); 944 m_zoomin_action->removeFrom( viewbar() );
945 m_zoomout_action->removeFrom( viewbar() ); 945 m_zoomout_action->removeFrom( viewbar() );
946 m_setfont_action->removeFrom( viewbar() ); 946 m_setfont_action->removeFrom( viewbar() );
947 m_setenc_action->removeFrom( viewbar() ); 947 m_setenc_action->removeFrom( viewbar() );
948 m_setmono_action->removeFrom( viewbar() ); 948 m_setmono_action->removeFrom( viewbar() );
949 } 949 }
950 else if (viewBar != fileBar) 950 else if (viewBar != fileBar)
951 { 951 {
952 viewBar->clear(); 952 viewBar->clear();
953 } 953 }
954 } 954 }
955 955
956 addviewbar(config, "Fullscreen", m_actFullscreen); 956 addviewbar(config, "Fullscreen", m_actFullscreen);
957 addviewbar(config, "Zoom In", m_zoomin_action); 957 addviewbar(config, "Zoom In", m_zoomin_action);
958 addviewbar(config, "Zoom Out", m_zoomout_action); 958 addviewbar(config, "Zoom Out", m_zoomout_action);
959 addviewbar(config, "Set Font", m_setfont_action); 959 addviewbar(config, "Set Font", m_setfont_action);
960 addviewbar(config, "Encoding Select", m_setenc_action); 960 addviewbar(config, "Encoding Select", m_setenc_action);
961 addviewbar(config, "Ideogram Mode", m_setmono_action); 961 addviewbar(config, "Ideogram Mode", m_setmono_action);
962 962
963 if (markBar != NULL) 963 if (markBar != NULL)
964 { 964 {
965 if ((markBar == fileBar) && (fileBar == menubar)) 965 if ((markBar == fileBar) && (fileBar == menubar))
966 { 966 {
967 m_mark_action->removeFrom( markbar() ); 967 m_mark_action->removeFrom( markbar() );
968 m_annotate_action->removeFrom( markbar()); 968 m_annotate_action->removeFrom( markbar());
969 m_goto_action->removeFrom( markbar() ); 969 m_goto_action->removeFrom( markbar() );
970 m_delete_action->removeFrom( markbar() ); 970 m_delete_action->removeFrom( markbar() );
971 m_autogen_action->removeFrom( markbar() ); 971 m_autogen_action->removeFrom( markbar() );
972 m_clear_action->removeFrom( markbar() ); 972 m_clear_action->removeFrom( markbar() );
973 m_save_action->removeFrom( markbar() ); 973 m_save_action->removeFrom( markbar() );
974 m_tidy_action->removeFrom( markbar() ); 974 m_tidy_action->removeFrom( markbar() );
975 m_startBlock_action->removeFrom( markbar() ); 975 m_startBlock_action->removeFrom( markbar() );
976 m_endBlock_action->removeFrom( markbar() ); 976 m_endBlock_action->removeFrom( markbar() );
977 } 977 }
978 else if (markBar != fileBar) 978 else if (markBar != fileBar)
979 { 979 {
980 markBar->clear(); 980 markBar->clear();
981 } 981 }
982 } 982 }
983 addmarkbar(config, "Mark", m_mark_action); 983 addmarkbar(config, "Mark", m_mark_action);
984 addmarkbar(config, "Annotate", m_annotate_action); 984 addmarkbar(config, "Annotate", m_annotate_action);
985 addmarkbar(config, "Goto", m_goto_action); 985 addmarkbar(config, "Goto", m_goto_action);
986 addmarkbar(config, "Delete", m_delete_action); 986 addmarkbar(config, "Delete", m_delete_action);
987 addmarkbar(config, "Autogen", m_autogen_action); 987 addmarkbar(config, "Autogen", m_autogen_action);
988 addmarkbar(config, "Clear", m_clear_action); 988 addmarkbar(config, "Clear", m_clear_action);
989 addmarkbar(config, "Save", m_save_action); 989 addmarkbar(config, "Save", m_save_action);
990 addmarkbar(config, "Tidy", m_tidy_action); 990 addmarkbar(config, "Tidy", m_tidy_action);
991 addmarkbar(config, "Start Block", m_startBlock_action); 991 addmarkbar(config, "Start Block", m_startBlock_action);
992 addmarkbar(config, "Copy Block", m_endBlock_action); 992 addmarkbar(config, "Copy Block", m_endBlock_action);
993 if (checkbar(config, "Annotation indicator")) 993 if (checkbar(config, "Annotation indicator"))
994 { 994 {
995 if (m_bkmkAvail == NULL) 995 if (m_bkmkAvail == NULL)
996 { 996 {
997 m_bkmkAvail = new QAction( tr( "Annotation" ), geticon( "find" ), QString::null, 0, this, 0 ); 997 m_bkmkAvail = new QAction( tr( "Annotation" ), geticon( "find" ), QString::null, 0, this, 0 );
998 connect( m_bkmkAvail, SIGNAL( activated() ), this, SLOT( showAnnotation() ) ); 998 connect( m_bkmkAvail, SIGNAL( activated() ), this, SLOT( showAnnotation() ) );
999 999
1000 m_bkmkAvail->setEnabled(false); 1000 m_bkmkAvail->setEnabled(false);
1001 } 1001 }
1002 QLabel *spacer = new QLabel(markBar, ""); 1002 QLabel *spacer = new QLabel(markBar, "");
1003 markbar()->setStretchableWidget(spacer); 1003 markbar()->setStretchableWidget(spacer);
1004 m_bkmkAvail->removeFrom( markbar() ); 1004 m_bkmkAvail->removeFrom( markbar() );
1005 m_bkmkAvail->addTo( markbar() ); 1005 m_bkmkAvail->addTo( markbar() );
1006 } 1006 }
1007 else 1007 else
1008 { 1008 {
1009 if (m_bkmkAvail != NULL) 1009 if (m_bkmkAvail != NULL)
1010 { 1010 {
1011 m_bkmkAvail->removeFrom( markbar() ); 1011 m_bkmkAvail->removeFrom( markbar() );
1012 delete m_bkmkAvail; 1012 delete m_bkmkAvail;
1013 m_bkmkAvail = NULL; 1013 m_bkmkAvail = NULL;
1014 } 1014 }
1015 } 1015 }
1016} 1016}
1017 1017
1018bool QTReaderApp::checkbar(Config* _config, const QString& key) 1018bool QTReaderApp::checkbar(Config* _config, const QString& key)
1019{ 1019{
1020 return _config->readBoolEntry(key, false); 1020 return _config->readBoolEntry(key, false);
1021} 1021}
1022 1022
1023 1023
1024QToolBar* QTReaderApp::filebar() 1024QToolBar* QTReaderApp::filebar()
1025{ 1025{
1026 if (fileBar == NULL) 1026 if (fileBar == NULL)
1027 { 1027 {
1028 switch (m_tbpol) 1028 switch (m_tbpol)
1029 { 1029 {
1030 case cesSingle: 1030 case cesSingle:
1031 // qDebug("Setting filebar to menubar"); 1031 // qDebug("Setting filebar to menubar");
1032 fileBar = menubar; 1032 fileBar = menubar;
1033 break; 1033 break;
1034 default: 1034 default:
1035 qDebug("Incorrect toolbar policy set"); 1035 qDebug("Incorrect toolbar policy set");
1036 case cesMenuTool: 1036 case cesMenuTool:
1037 case cesMultiple: 1037 case cesMultiple:
1038 // qDebug("Creating new file bar"); 1038 // qDebug("Creating new file bar");
1039 fileBar = new QToolBar("File", this, m_tbposition); 1039 fileBar = new QToolBar("File", this, m_tbposition);
1040 break; 1040 break;
1041 } 1041 }
1042 //fileBar->setHorizontalStretchable( true ); 1042 //fileBar->setHorizontalStretchable( true );
1043 } 1043 }
1044 return fileBar; 1044 return fileBar;
1045} 1045}
1046QToolBar* QTReaderApp::viewbar() 1046QToolBar* QTReaderApp::viewbar()
1047{ 1047{
1048 if (viewBar == NULL) 1048 if (viewBar == NULL)
1049 { 1049 {
1050 switch (m_tbpol) 1050 switch (m_tbpol)
1051 { 1051 {
1052 case cesMultiple: 1052 case cesMultiple:
1053 viewBar = new QToolBar("View", this, m_tbposition); 1053 viewBar = new QToolBar("View", this, m_tbposition);
1054 break; 1054 break;
1055 default: 1055 default:
1056 qDebug("Incorrect toolbar policy set"); 1056 qDebug("Incorrect toolbar policy set");
1057 case cesSingle: 1057 case cesSingle:
1058 case cesMenuTool: 1058 case cesMenuTool:
1059 viewBar = fileBar; 1059 viewBar = fileBar;
1060 break; 1060 break;
1061 } 1061 }
1062 } 1062 }
1063 return viewBar; 1063 return viewBar;
1064} 1064}
1065QToolBar* QTReaderApp::navbar() 1065QToolBar* QTReaderApp::navbar()
1066{ 1066{
1067 if (navBar == NULL) 1067 if (navBar == NULL)
1068 { 1068 {
1069 switch (m_tbpol) 1069 switch (m_tbpol)
1070 { 1070 {
1071 case cesMultiple: 1071 case cesMultiple:
1072 // qDebug("Creating new nav bar"); 1072 // qDebug("Creating new nav bar");
1073 navBar = new QToolBar("Navigation", this, m_tbposition); 1073 navBar = new QToolBar("Navigation", this, m_tbposition);
1074 break; 1074 break;
1075 default: 1075 default:
1076 qDebug("Incorrect toolbar policy set"); 1076 qDebug("Incorrect toolbar policy set");
1077 case cesSingle: 1077 case cesSingle:
1078 case cesMenuTool: 1078 case cesMenuTool:
1079 navBar = fileBar; 1079 navBar = fileBar;
1080 // qDebug("Setting navbar to filebar"); 1080 // qDebug("Setting navbar to filebar");
1081 break; 1081 break;
1082 } 1082 }
1083 } 1083 }
1084 return navBar; 1084 return navBar;
1085} 1085}
1086QToolBar* QTReaderApp::markbar() 1086QToolBar* QTReaderApp::markbar()
1087{ 1087{
1088 if (markBar == NULL) 1088 if (markBar == NULL)
1089 { 1089 {
1090 switch (m_tbpol) 1090 switch (m_tbpol)
1091 { 1091 {
1092 case cesMultiple: 1092 case cesMultiple:
1093 markBar = new QToolBar("Marks", this, m_tbposition); 1093 markBar = new QToolBar("Marks", this, m_tbposition);
1094 break; 1094 break;
1095 default: 1095 default:
1096 qDebug("Incorrect toolbar policy set"); 1096 qDebug("Incorrect toolbar policy set");
1097 case cesSingle: 1097 case cesSingle:
1098 case cesMenuTool: 1098 case cesMenuTool:
1099 markBar = fileBar; 1099 markBar = fileBar;
1100 break; 1100 break;
1101 } 1101 }
1102 } 1102 }
1103 return markBar; 1103 return markBar;
1104} 1104}
1105 1105
1106void QTReaderApp::addfilebar(Config* _config, const QString& key, QAction* a) 1106void QTReaderApp::addfilebar(Config* _config, const QString& key, QAction* a)
1107{ 1107{
1108 if (_config->readBoolEntry(key, false)) a->addTo( filebar() ); 1108 if (_config->readBoolEntry(key, false)) a->addTo( filebar() );
1109} 1109}
1110void QTReaderApp::addnavbar(Config* _config, const QString& key, QAction* a) 1110void QTReaderApp::addnavbar(Config* _config, const QString& key, QAction* a)
1111{ 1111{
1112 if (_config->readBoolEntry(key, false)) a->addTo( navbar() ); 1112 if (_config->readBoolEntry(key, false)) a->addTo( navbar() );
1113} 1113}
1114void QTReaderApp::addmarkbar(Config* _config, const QString& key, QAction* a) 1114void QTReaderApp::addmarkbar(Config* _config, const QString& key, QAction* a)
1115{ 1115{
1116 if (_config->readBoolEntry(key, false)) a->addTo( markbar() ); 1116 if (_config->readBoolEntry(key, false)) a->addTo( markbar() );
1117} 1117}
1118void QTReaderApp::addviewbar(Config* _config, const QString& key, QAction* a) 1118void QTReaderApp::addviewbar(Config* _config, const QString& key, QAction* a)
1119{ 1119{
1120 if (_config->readBoolEntry(key, false)) a->addTo( viewbar() ); 1120 if (_config->readBoolEntry(key, false)) a->addTo( viewbar() );
1121} 1121}
1122 1122
1123void QTReaderApp::suspend() { reader->suspend(); } 1123void QTReaderApp::suspend() { reader->suspend(); }
1124 1124
1125#ifdef USEMSGS 1125#ifdef USEMSGS
1126void QTReaderApp::msgHandler(const QCString& _msg, const QByteArray& _data) 1126void QTReaderApp::msgHandler(const QCString& _msg, const QByteArray& _data)
1127{ 1127{
1128 QString msg = QString::fromUtf8(_msg); 1128 QString msg = QString::fromUtf8(_msg);
1129 1129
1130//// qDebug("Received:%s", (const char*)msg); 1130//// qDebug("Received:%s", (const char*)msg);
1131 1131
1132 QDataStream stream( _data, IO_ReadOnly ); 1132 QDataStream stream( _data, IO_ReadOnly );
1133 if ( msg == "info(QString)" ) 1133 if ( msg == "info(QString)" )
1134 { 1134 {
1135 QString info; 1135 QString info;
1136 stream >> info; 1136 stream >> info;
1137 QMessageBox::information(this, PROGNAME, info); 1137 QMessageBox::information(this, PROGNAME, info);
1138 } 1138 }
1139 else if ( msg == "Update(int)" ) 1139 else if ( msg == "Update(int)" )
1140 { 1140 {
1141 int info; 1141 int info;
1142 stream >> info; 1142 stream >> info;
1143 if (info) 1143 if (info)
1144 { 1144 {
1145 reader->bDoUpdates = true; 1145 reader->bDoUpdates = true;
1146 reader->refresh(); 1146 reader->refresh();
1147 } 1147 }
1148 else 1148 else
1149 { 1149 {
1150 reader->bDoUpdates = false; 1150 reader->bDoUpdates = false;
1151 } 1151 }
1152 } 1152 }
1153 else if ( msg == "warn(QString)" ) 1153 else if ( msg == "warn(QString)" )
1154 { 1154 {
1155 QString info; 1155 QString info;
1156 stream >> info; 1156 stream >> info;
1157 QMessageBox::warning(this, PROGNAME, info); 1157 QMessageBox::warning(this, PROGNAME, info);
1158 } 1158 }
1159 else if ( msg == "exit()" ) 1159 else if ( msg == "exit()" )
1160 { 1160 {
1161 m_dontSave = true; 1161 m_dontSave = true;
1162 close(); 1162 close();
1163 } 1163 }
1164 else if ( msg == "pageDown()" ) 1164 else if ( msg == "pageDown()" )
1165 { 1165 {
1166 reader->dopagedn(); 1166 reader->dopagedn();
1167 } 1167 }
1168 else if ( msg == "pageUp()" ) 1168 else if ( msg == "pageUp()" )
1169 { 1169 {
1170 reader->dopageup(); 1170 reader->dopageup();
1171 } 1171 }
1172 else if ( msg == "lineDown()" ) 1172 else if ( msg == "lineDown()" )
1173 { 1173 {
1174 reader->lineDown(); 1174 reader->lineDown();
1175 } 1175 }
1176 else if ( msg == "lineUp()" ) 1176 else if ( msg == "lineUp()" )
1177 { 1177 {
1178 reader->lineUp(); 1178 reader->lineUp();
1179 } 1179 }
1180 else if ( msg == "showText()" ) 1180 else if ( msg == "showText()" )
1181 { 1181 {
1182 showEditTools(); 1182 showEditTools();
1183 } 1183 }
1184 else if ( msg == "home()" ) 1184 else if ( msg == "home()" )
1185 { 1185 {
1186 reader->goHome(); 1186 reader->goHome();
1187 } 1187 }
1188 else if ( msg == "back()" ) 1188 else if ( msg == "back()" )
1189 { 1189 {
1190 reader->goBack(); 1190 reader->goBack();
1191 } 1191 }
1192 else if ( msg == "forward()" ) 1192 else if ( msg == "forward()" )
1193 { 1193 {
1194 reader->goForward(); 1194 reader->goForward();
1195 } 1195 }
1196 else if ( msg == "File/Open(QString)" ) 1196 else if ( msg == "File/Open(QString)" )
1197 { 1197 {
1198 QString info; 1198 QString info;
1199 stream >> info; 1199 stream >> info;
1200 openFile( info ); 1200 openFile( info );
1201 } 1201 }
1202 else if ( msg == "File/Info()" ) 1202 else if ( msg == "File/Info()" )
1203 { 1203 {
1204 showinfo(); 1204 showinfo();
1205 } 1205 }
1206 else if ( msg == "File/Action(QString)" ) 1206 else if ( msg == "File/Action(QString)" )
1207 { 1207 {
1208 QString info; 1208 QString info;
1209 stream >> info; 1209 stream >> info;
1210 m_spaceTarget = ActNameToInt(info); 1210 m_spaceTarget = ActNameToInt(info);
1211 } 1211 }
1212 else if ( msg == "Navigation/Scroll(int)" ) 1212 else if ( msg == "Navigation/Scroll(int)" )
1213 { 1213 {
1214 int info; 1214 int info;
1215 stream >> info; 1215 stream >> info;
1216 autoScroll(info); 1216 autoScroll(info);
1217 } 1217 }
1218 1218
1219 else if ( msg == "Navigation/GotoStart()" ) 1219 else if ( msg == "Navigation/GotoStart()" )
1220 { 1220 {
1221 gotoStart(); 1221 gotoStart();
1222 } 1222 }
1223 else if ( msg == "Navigation/GotoEnd()" ) 1223 else if ( msg == "Navigation/GotoEnd()" )
1224 { 1224 {
1225 gotoEnd(); 1225 gotoEnd();
1226 } 1226 }
1227 else if ( msg == "Navigation/Jump(int)" ) 1227 else if ( msg == "Navigation/Jump(int)" )
1228 { 1228 {
1229 int info; 1229 int info;
1230 stream >> info; 1230 stream >> info;
1231 reader->locate(info); 1231 reader->locate(info);
1232 } 1232 }
1233 else if ( msg == "Navigation/Page/LineScroll(int)" ) 1233 else if ( msg == "Navigation/Page/LineScroll(int)" )
1234 { 1234 {
1235 int info; 1235 int info;
1236 stream >> info; 1236 stream >> info;
1237 pagemode(info); 1237 pagemode(info);
1238 } 1238 }
1239 else if ( msg == "Navigation/SetOverlap(int)" ) 1239 else if ( msg == "Navigation/SetOverlap(int)" )
1240 { 1240 {
1241 int info; 1241 int info;
1242 stream >> info; 1242 stream >> info;
1243 reader->m_overlap = info; 1243 reader->m_overlap = info;
1244 } 1244 }
1245 else if ( msg == "Navigation/SetMargin(int)" ) 1245 else if ( msg == "Navigation/SetMargin(int)" )
1246 { 1246 {
1247 int info; 1247 int info;
1248 stream >> info; 1248 stream >> info;
1249 do_margin(info); 1249 do_margin(info);
1250 } 1250 }
1251 else if ( msg == "File/SetDictionary(QString)" ) 1251 else if ( msg == "File/SetDictionary(QString)" )
1252 { 1252 {
1253 QString info; 1253 QString info;
1254 stream >> info; 1254 stream >> info;
1255 do_settarget(info); 1255 do_settarget(info);
1256 } 1256 }
1257#ifdef _SCROLLPIPE 1257#ifdef _SCROLLPIPE
1258 else if ( msg == "File/SetScrollTarget(QString)" ) 1258 else if ( msg == "File/SetScrollTarget(QString)" )
1259 { 1259 {
1260 QString info; 1260 QString info;
1261 stream >> info; 1261 stream >> info;
1262 reader->m_pipetarget = info; 1262 reader->m_pipetarget = info;
1263 } 1263 }
1264#endif 1264#endif
1265 else if ( msg == "File/Two/OneTouch(int)" ) 1265 else if ( msg == "File/Two/OneTouch(int)" )
1266 { 1266 {
1267 int info; 1267 int info;
1268 stream >> info; 1268 stream >> info;
1269 setTwoTouch(info); 1269 setTwoTouch(info);
1270 } 1270 }
1271 else if ( msg == "Target/Annotation(int)" ) 1271 else if ( msg == "Target/Annotation(int)" )
1272 { 1272 {
1273 int info; 1273 int info;
1274 stream >> info; 1274 stream >> info;
1275 OnAnnotation(info); 1275 OnAnnotation(info);
1276 } 1276 }
1277 else if ( msg == "Target/Dictionary(int)" ) 1277 else if ( msg == "Target/Dictionary(int)" )
1278 { 1278 {
1279 int info; 1279 int info;
1280 stream >> info; 1280 stream >> info;
1281 OnDictionary(info); 1281 OnDictionary(info);
1282 } 1282 }
1283 else if ( msg == "Target/Clipboard(int)" ) 1283 else if ( msg == "Target/Clipboard(int)" )
1284 { 1284 {
1285 int info; 1285 int info;
1286 stream >> info; 1286 stream >> info;
1287 OnClipboard(info); 1287 OnClipboard(info);
1288 } 1288 }
1289 else if ( msg == "File/Find(QString)" ) 1289 else if ( msg == "File/Find(QString)" )
1290 { 1290 {
1291 QString info; 1291 QString info;
1292 stream >> info; 1292 stream >> info;
1293 QRegExp arg(info); 1293 QRegExp arg(info);
1294 size_t pos = reader->pagelocate(); 1294 size_t pos = reader->pagelocate();
1295 size_t start = pos; 1295 size_t start = pos;
1296 CDrawBuffer test(&(reader->m_fontControl)); 1296 CDrawBuffer test(&(reader->m_fontControl));
1297 reader->getline(&test); 1297 reader->getline(&test);
1298 while (arg.match(toQString(test.data())) == -1) 1298 while (arg.match(toQString(test.data())) == -1)
1299 { 1299 {
1300 pos = reader->locate(); 1300 pos = reader->locate();
1301 if (!reader->getline(&test)) 1301 if (!reader->getline(&test))
1302 { 1302 {
1303 QMessageBox::information(this, PROGNAME, QString("Can't find\n")+info); 1303 QMessageBox::information(this, PROGNAME, QString("Can't find\n")+info);
1304 pos = start; 1304 pos = start;
1305 break; 1305 break;
1306 } 1306 }
1307 } 1307 }
1308 reader->locate(pos); 1308 reader->locate(pos);
1309 } 1309 }
1310 else if ( msg == "File/Fullscreen(int)" ) 1310 else if ( msg == "File/Fullscreen(int)" )
1311 { 1311 {
1312 int info; 1312 int info;
1313 stream >> info; 1313 stream >> info;
1314 setfullscreen(info); 1314 setfullscreen(info);
1315 } 1315 }
1316 else if ( msg == "File/Continuous(int)" ) 1316 else if ( msg == "File/Continuous(int)" )
1317 { 1317 {
1318 int info; 1318 int info;
1319 stream >> info; 1319 stream >> info;
1320 setcontinuous(info); 1320 setcontinuous(info);
1321 } 1321 }
1322 else if ( msg == "Markup(QString)" ) 1322 else if ( msg == "Markup(QString)" )
1323 { 1323 {
1324 QString info; 1324 QString info;
1325 stream >> info; 1325 stream >> info;
1326 if (info == "Auto") 1326 if (info == "Auto")
1327 { 1327 {
1328 autofmt(true); 1328 autofmt(true);
1329 } 1329 }
1330 if (info == "None") 1330 if (info == "None")
1331 { 1331 {
1332 autofmt(false); 1332 autofmt(false);
1333 textfmt(false); 1333 textfmt(false);
1334 striphtml(false); 1334 striphtml(false);
1335 peanut(false); 1335 peanut(false);
1336 } 1336 }
1337 if (info == "Text") 1337 if (info == "Text")
1338 { 1338 {
1339 textfmt(true); 1339 textfmt(true);
1340 } 1340 }
1341 if (info == "HTML") 1341 if (info == "HTML")
1342 { 1342 {
1343 striphtml(true); 1343 striphtml(true);
1344 } 1344 }
1345 if (info == "Peanut/PML") 1345 if (info == "Peanut/PML")
1346 { 1346 {
1347 peanut(true); 1347 peanut(true);
1348 } 1348 }
1349 } 1349 }
1350 else if ( msg == "Layout/StripCR(int)" ) 1350 else if ( msg == "Layout/StripCR(int)" )
1351 { 1351 {
1352 int info; 1352 int info;
1353 stream >> info; 1353 stream >> info;
1354 stripcr(info); 1354 stripcr(info);
1355 } 1355 }
1356 else if ( msg == "Layout/Dehyphen(int)" ) 1356 else if ( msg == "Layout/Dehyphen(int)" )
1357 { 1357 {
1358 int info; 1358 int info;
1359 stream >> info; 1359 stream >> info;
1360 dehyphen(info); 1360 dehyphen(info);
1361 } 1361 }
1362 else if ( msg == "Layout/Depluck(int)" ) 1362 else if ( msg == "Layout/Depluck(int)" )
1363 { 1363 {
1364 int info; 1364 int info;
1365 stream >> info; 1365 stream >> info;
1366 depluck(info); 1366 depluck(info);
1367 } 1367 }
1368 else if ( msg == "Layout/Dejpluck(int)" ) 1368 else if ( msg == "Layout/Dejpluck(int)" )
1369 { 1369 {
1370 int info; 1370 int info;
1371 stream >> info; 1371 stream >> info;
1372 dejpluck(info); 1372 dejpluck(info);
1373 } 1373 }
1374 else if ( msg == "Layout/SingleSpace(int)" ) 1374 else if ( msg == "Layout/SingleSpace(int)" )
1375 { 1375 {
1376 int info; 1376 int info;
1377 stream >> info; 1377 stream >> info;
1378 onespace(info); 1378 onespace(info);
1379 } 1379 }
1380#ifdef REPALM 1380#ifdef REPALM
1381 else if ( msg == "Layout/Repalm(int)" ) 1381 else if ( msg == "Layout/Repalm(int)" )
1382 { 1382 {
1383 int info; 1383 int info;
1384 stream >> info; 1384 stream >> info;
1385 repalm(info); 1385 repalm(info);
1386 } 1386 }
1387#endif 1387#endif
1388 else if ( msg == "Layout/Unindent(int)" ) 1388 else if ( msg == "Layout/Unindent(int)" )
1389 { 1389 {
1390 int info; 1390 int info;
1391 stream >> info; 1391 stream >> info;
1392 unindent(info); 1392 unindent(info);
1393 } 1393 }
1394 else if ( msg == "Layout/Re-paragraph(int)" ) 1394 else if ( msg == "Layout/Re-paragraph(int)" )
1395 { 1395 {
1396 int info; 1396 int info;
1397 stream >> info; 1397 stream >> info;
1398 repara(info); 1398 repara(info);
1399 } 1399 }
1400 else if ( msg == "Layout/DoubleSpace(int)" ) 1400 else if ( msg == "Layout/DoubleSpace(int)" )
1401 { 1401 {
1402 int info; 1402 int info;
1403 stream >> info; 1403 stream >> info;
1404 dblspce(info); 1404 dblspce(info);
1405 } 1405 }
1406 else if ( msg == "Layout/Indent(int)" ) 1406 else if ( msg == "Layout/Indent(int)" )
1407 { 1407 {
1408 int info; 1408 int info;
1409 stream >> info; 1409 stream >> info;
1410 reader->bindenter = info; 1410 reader->bindenter = info;
1411 reader->setfilter(reader->getfilter()); 1411 reader->setfilter(reader->getfilter());
1412 } 1412 }
1413 else if ( msg == "Layout/Remap(int)" ) 1413 else if ( msg == "Layout/Remap(int)" )
1414 { 1414 {
1415 int info; 1415 int info;
1416 stream >> info; 1416 stream >> info;
1417 remap(info); 1417 remap(info);
1418 } 1418 }
1419 else if ( msg == "Layout/Embolden(int)" ) 1419 else if ( msg == "Layout/Embolden(int)" )
1420 { 1420 {
1421 int info; 1421 int info;
1422 stream >> info; 1422 stream >> info;
1423 embolden(info); 1423 embolden(info);
1424 } 1424 }
1425 else if ( msg == "Format/Ideogram/Word(int)" ) 1425 else if ( msg == "Format/Ideogram/Word(int)" )
1426 { 1426 {
1427 int info; 1427 int info;
1428 stream >> info; 1428 stream >> info;
1429 monospace(info); 1429 monospace(info);
1430 } 1430 }
1431 else if ( msg == "Format/SetWidth(int)" ) 1431 else if ( msg == "Format/SetWidth(int)" )
1432 { 1432 {
1433 int info; 1433 int info;
1434 stream >> info; 1434 stream >> info;
1435 reader->m_charpc = info; 1435 reader->m_charpc = info;
1436 reader->setfont(); 1436 reader->setfont();
1437 reader->refresh(); 1437 reader->refresh();
1438 } 1438 }
1439 else if ( msg == "Format/SetFont(QString,int)" ) 1439 else if ( msg == "Format/SetFont(QString,int)" )
1440 { 1440 {
1441 QString fontname; 1441 QString fontname;
1442 int size; 1442 int size;
1443 stream >> fontname; 1443 stream >> fontname;
1444 stream >> size; 1444 stream >> size;
1445 setfontHelper(fontname, size); 1445 setfontHelper(fontname, size);
1446 } 1446 }
1447 else if ( msg == "Marks/Autogen(QString)" ) 1447 else if ( msg == "Marks/Autogen(QString)" )
1448 { 1448 {
1449 QString info; 1449 QString info;
1450 stream >> info; 1450 stream >> info;
1451 do_autogen(info); 1451 do_autogen(info);
1452 } 1452 }
1453 else if ( msg == "File/StartBlock()" ) 1453 else if ( msg == "File/StartBlock()" )
1454 { 1454 {
1455 editMark(); 1455 editMark();
1456 } 1456 }
1457 else if ( msg == "File/CopyBlock()" ) 1457 else if ( msg == "File/CopyBlock()" )
1458 { 1458 {
1459 editCopy(); 1459 editCopy();
1460 } 1460 }
1461} 1461}
1462#endif 1462#endif
1463ActionTypes QTReaderApp::ActNameToInt(const QString& _enc) 1463ActionTypes QTReaderApp::ActNameToInt(const QString& _enc)
1464{ 1464{
1465 for (int i = 0; i < MAX_ACTIONS; i++) 1465 for (int i = 0; i < MAX_ACTIONS; i++)
1466 { 1466 {
1467 if (m_buttonAction[i]->text() == _enc) return (ActionTypes)i; 1467 if (m_buttonAction[i]->text() == _enc) return (ActionTypes)i;
1468 } 1468 }
1469 return cesAutoScroll; 1469 return cesAutoScroll;
1470} 1470}
1471 1471
1472void QTReaderApp::setfullscreen(bool sfs) 1472void QTReaderApp::setfullscreen(bool sfs)
1473{ 1473{
1474 reader->bDoUpdates = false; 1474 reader->bDoUpdates = false;
1475 m_fullscreen = sfs; 1475 m_fullscreen = sfs;
1476 showEditTools(); 1476 showEditTools();
1477// qApp->processEvents(); 1477// qApp->processEvents();
1478 reader->bDoUpdates = true; 1478 reader->bDoUpdates = true;
1479 reader->update(); 1479 reader->update();
1480} 1480}
1481 1481
1482void QTReaderApp::buttonActionSelected(QAction* _a) 1482void QTReaderApp::buttonActionSelected(QAction* _a)
1483{ 1483{
1484//// qDebug("es:%x : %s (%u)", _a, (const char *)(_a->text()), ActNameToInt(_a->text())); 1484//// qDebug("es:%x : %s (%u)", _a, (const char *)(_a->text()), ActNameToInt(_a->text()));
1485 m_spaceTarget = ActNameToInt(_a->text()); 1485 m_spaceTarget = ActNameToInt(_a->text());
1486} 1486}
1487 1487
1488QTReaderApp::~QTReaderApp() 1488QTReaderApp::~QTReaderApp()
1489{ 1489{
1490} 1490}
1491 1491
1492void QTReaderApp::autoScroll(bool _b) 1492void QTReaderApp::autoScroll(bool _b)
1493{ 1493{
1494 reader->setautoscroll(_b); 1494 reader->setautoscroll(_b);
1495 setScrollState(reader->m_autoScroll); 1495 setScrollState(reader->m_autoScroll);
1496} 1496}
1497 1497
1498void QTReaderApp::zoomin() 1498void QTReaderApp::zoomin()
1499{ 1499{
1500 reader->zoomin(); 1500 reader->zoomin();
1501} 1501}
1502 1502
1503void QTReaderApp::zoomout() 1503void QTReaderApp::zoomout()
1504{ 1504{
1505 reader->zoomout(); 1505 reader->zoomout();
1506} 1506}
1507 1507
1508void QTReaderApp::clearBkmkList() 1508void QTReaderApp::clearBkmkList()
1509{ 1509{
1510 delete pBkmklist; 1510 delete pBkmklist;
1511 pBkmklist = NULL; 1511 pBkmklist = NULL;
1512 m_fBkmksChanged = false; 1512 m_fBkmksChanged = false;
1513} 1513}
1514 1514
1515void QTReaderApp::fileClose() 1515void QTReaderApp::fileClose()
1516{ 1516{
1517 CCloseDialog* cd = new CCloseDialog(reader->m_string, false, this); 1517 CCloseDialog* cd = new CCloseDialog(reader->m_string, false, this);
1518 if (cd->exec()) 1518 if (cd->exec())
1519 { 1519 {
1520 if (pOpenlist != NULL) 1520 if (pOpenlist != NULL)
1521 { 1521 {
1522 int ind = 0; 1522 int ind = 0;
1523 Bkmk* p = (*pOpenlist)[ind]; 1523 Bkmk* p = (*pOpenlist)[ind];
1524 while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile) 1524 while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile)
1525 { 1525 {
1526 p = (*pOpenlist)[++ind]; 1526 p = (*pOpenlist)[++ind];
1527 } 1527 }
1528 if (p != NULL) pOpenlist->erase(ind); 1528 if (p != NULL) pOpenlist->erase(ind);
1529 if (cd->delFile()) 1529 if (cd->delFile())
1530 { 1530 {
1531 unlink((const char*)reader->m_lastfile); 1531 unlink((const char*)reader->m_lastfile);
1532 } 1532 }
1533 if (cd->delMarks()) 1533 if (cd->delMarks())
1534 { 1534 {
1535#ifndef USEQPE 1535#ifndef USEQPE
1536 QDir d = QDir::home(); // "/" 1536 QDir d = QDir::home(); // "/"
1537 d.cd(APPDIR); 1537 d.cd(APPDIR);
1538 d.remove(reader->m_string); 1538 d.remove(reader->m_string);
1539#else /* USEQPE */ 1539#else /* USEQPE */
1540 unlink((const char *)Global::applicationFileName(APPDIR,reader->m_string)); 1540 unlink((const char *)Global::applicationFileName(APPDIR,reader->m_string));
1541#endif /* USEQPE */ 1541#endif /* USEQPE */
1542 } 1542 }
1543 if (cd->delConfig()) 1543 if (cd->delConfig())
1544 { 1544 {
1545#ifndef USEQPE 1545#ifndef USEQPE
1546 QDir d = QDir::home(); // "/" 1546 QDir d = QDir::home(); // "/"
1547 d.cd(APPDIR "/configs"); 1547 d.cd(APPDIR "/configs");
1548 d.remove(reader->m_string); 1548 d.remove(reader->m_string);
1549#else /* USEQPE */ 1549#else /* USEQPE */
1550 unlink((const char *)Global::applicationFileName(APPDIR "/configs",reader->m_string)); 1550 unlink((const char *)Global::applicationFileName(APPDIR "/configs",reader->m_string));
1551#endif /* USEQPE */ 1551#endif /* USEQPE */
1552 } 1552 }
1553 } 1553 }
1554 1554
1555 fileOpen2(); 1555 fileOpen2();
1556 } 1556 }
1557 delete cd; 1557 delete cd;
1558} 1558}
1559 1559
1560void QTReaderApp::updatefileinfo() 1560void QTReaderApp::updatefileinfo()
1561{ 1561{
1562 if (reader->m_string.isEmpty()) return; 1562 if (reader->m_string.isEmpty()) return;
1563 if (reader->m_lastfile.isEmpty()) return; 1563 if (reader->m_lastfile.isEmpty()) return;
1564 tchar* nm = fromQString(reader->m_string); 1564 tchar* nm = fromQString(reader->m_string);
1565 tchar* fl = fromQString(reader->m_lastfile); 1565 tchar* fl = fromQString(reader->m_lastfile);
1566// qDebug("Lastfile:%x", fl); 1566// qDebug("Lastfile:%x", fl);
1567 bool notadded = true; 1567 bool notadded = true;
1568 if (pOpenlist == NULL) pOpenlist = new CList<Bkmk>; 1568 if (pOpenlist == NULL) pOpenlist = new CList<Bkmk>;
1569 else 1569 else
1570 { 1570 {
1571 for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++) 1571 for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++)
1572 { 1572 {
1573 if (ustrcmp(CFiledata(iter->anno()).name(), fl) == 0) 1573 if (ustrcmp(CFiledata(iter->anno()).name(), fl) == 0)
1574 { 1574 {
1575 iter->value(reader->pagelocate()); 1575 iter->value(reader->pagelocate());
1576 unsigned short dlen; 1576 unsigned short dlen;
1577 unsigned char* data; 1577 unsigned char* data;
1578 CFiledata fd(iter->anno()); 1578 CFiledata fd(iter->anno());
1579 reader->setSaveData(data, dlen, fd.content(), fd.length()); 1579 reader->setSaveData(data, dlen, fd.content(), fd.length());
1580 // qDebug("Filedata(1):%u, %u", fd.length(), dlen); 1580 // qDebug("Filedata(1):%u, %u", fd.length(), dlen);
1581 // getstate(data, dlen); 1581 // getstate(data, dlen);
1582 iter->setAnno(data, dlen); 1582 iter->setAnno(data, dlen);
1583 notadded = false; 1583 notadded = false;
1584 delete [] data; 1584 delete [] data;
1585 break; 1585 break;
1586 } 1586 }
1587 } 1587 }
1588 } 1588 }
1589// qDebug("Added?:%x", notadded); 1589// qDebug("Added?:%x", notadded);
1590 if (notadded) 1590 if (notadded)
1591 { 1591 {
1592 struct stat fnstat; 1592 struct stat fnstat;
1593 stat((const char *)reader->m_lastfile, &fnstat); 1593 stat((const char *)reader->m_lastfile, &fnstat);
1594 CFiledata fd(fnstat.st_mtime, fl); 1594 CFiledata fd(fnstat.st_mtime, fl);
1595 unsigned short dlen; 1595 unsigned short dlen;
1596 unsigned char* data; 1596 unsigned char* data;
1597 reader->setSaveData(data, dlen, fd.content(), fd.length()); 1597 reader->setSaveData(data, dlen, fd.content(), fd.length());
1598 pOpenlist->push_front(Bkmk(nm, data, dlen, reader->pagelocate())); 1598 pOpenlist->push_front(Bkmk(nm, data, dlen, reader->pagelocate()));
1599 //qDebug("Filedata(2):%u, %u", fd.length(), dlen); 1599 //qDebug("Filedata(2):%u, %u", fd.length(), dlen);
1600 delete [] data; 1600 delete [] data;
1601 } 1601 }
1602 delete [] nm; 1602 delete [] nm;
1603 delete [] fl; 1603 delete [] fl;
1604} 1604}
1605 1605
1606void QTReaderApp::fileOpen() 1606void QTReaderApp::fileOpen()
1607{ 1607{
1608/* 1608/*
1609 menu->hide(); 1609 menu->hide();
1610 fileBar->hide(); 1610 fileBar->hide();
1611 if (regVisible) regBar->hide(); 1611 if (regVisible) regBar->hide();
1612 if (searchVisible) searchBar->hide(); 1612 if (searchVisible) searchBar->hide();
1613*/ 1613*/
1614// qDebug("fileOpen"); 1614// qDebug("fileOpen");
1615// if (!reader->m_lastfile.isEmpty()) 1615// if (!reader->m_lastfile.isEmpty())
1616 updatefileinfo(); 1616 updatefileinfo();
1617 fileOpen2(); 1617 fileOpen2();
1618} 1618}
1619 1619
1620void QTReaderApp::fileOpen2() 1620void QTReaderApp::fileOpen2()
1621{ 1621{
1622 if (pBkmklist != NULL) 1622 if (pBkmklist != NULL)
1623 { 1623 {
1624 if (m_fBkmksChanged) 1624 if (m_fBkmksChanged)
1625 { 1625 {
1626 if (QMessageBox::warning(this, PROGNAME, "Save bookmarks?", "Save", "Don't bother") == 0) 1626 if (QMessageBox::warning(this, PROGNAME, "Save bookmarks?", "Save", "Don't bother") == 0)
1627 savebkmks(); 1627 savebkmks();
1628 } 1628 }
1629 delete pBkmklist; 1629 delete pBkmklist;
1630 pBkmklist = NULL; 1630 pBkmklist = NULL;
1631 m_fBkmksChanged = false; 1631 m_fBkmksChanged = false;
1632 } 1632 }
1633 reader->disableAutoscroll(); 1633 reader->disableAutoscroll();
1634/* 1634/*
1635 editorStack->raiseWidget( fileSelector ); 1635 editorStack->raiseWidget( fileSelector );
1636 fileSelector->reread(); 1636 fileSelector->reread();
1637*/ 1637*/
1638 bool usebrowser = true; 1638 bool usebrowser = true;
1639 if (pOpenlist != NULL) 1639 if (pOpenlist != NULL)
1640 { 1640 {
1641 m_nBkmkAction = cOpenFile; 1641 m_nBkmkAction = cOpenFile;
1642 if (listbkmk(pOpenlist, "Browse")) usebrowser = false; 1642 if (listbkmk(pOpenlist, "Browse")) usebrowser = false;
1643 } 1643 }
1644 if (usebrowser) 1644 if (usebrowser)
1645 { 1645 {
1646 QString fn = usefilebrowser(); 1646 QString fn = usefilebrowser();
1647 //qApp->processEvents(); 1647 //qApp->processEvents();
1648 if (!fn.isEmpty() && QFileInfo(fn).isFile()) 1648 if (!fn.isEmpty() && QFileInfo(fn).isFile())
1649 { 1649 {
1650 openFile(fn); 1650 openFile(fn);
1651 } 1651 }
1652 reader->setFocus(); 1652 reader->setFocus();
1653 } 1653 }
1654// reader->refresh(); 1654// reader->refresh();
1655// qDebug("HEIGHT:%d", reader->m_lastheight); 1655// qDebug("HEIGHT:%d", reader->m_lastheight);
1656} 1656}
1657 1657
1658QString QTReaderApp::usefilebrowser() 1658QString QTReaderApp::usefilebrowser()
1659{ 1659{
1660#ifndef USEQPE 1660#ifndef USEQPE
1661 QString s( QFileDialog::getOpenFileName( reader->m_lastfile, QString::null, this ) ); 1661 QString s( QFileDialog::getOpenFileName( reader->m_lastfile, QString::null, this ) );
1662 return s; 1662 return s;
1663#else 1663#else
1664 fileBrowser* fb = new fileBrowser(false, this,"OpieReader",!m_bFloatingDialog, 1664 fileBrowser* fb = new fileBrowser(false, this,"OpieReader",!m_bFloatingDialog,
1665 0, 1665 0,
1666 // WStyle_Customize | WStyle_NoBorderEx, 1666 // WStyle_Customize | WStyle_NoBorderEx,
1667 "*", QFileInfo(reader->m_lastfile).dirPath(true)); 1667 "*", QFileInfo(reader->m_lastfile).dirPath(true));
1668 1668
1669 1669
1670 QString fn; 1670 QString fn;
1671 if (fb->exec()) 1671 if (fb->exec())
1672 { 1672 {
1673 fn = fb->getCurrentFile(); 1673 fn = fb->getCurrentFile();
1674 } 1674 }
1675// qDebug("Selected %s", (const char*)fn); 1675// qDebug("Selected %s", (const char*)fn);
1676 delete fb; 1676 delete fb;
1677 showEditTools(); 1677 showEditTools();
1678 return fn; 1678 return fn;
1679#endif 1679#endif
1680} 1680}
1681 1681
1682void QTReaderApp::showgraphic(QImage& pm) 1682void QTReaderApp::showgraphic(QImage& pm)
1683{ 1683{
1684 QPixmap pc; 1684 QPixmap pc;
1685 pc.convertFromImage(pm); 1685 pc.convertFromImage(pm);
1686 m_graphicwin->setPixmap(pc); 1686 m_graphicwin->setPixmap(pc);
1687 editorStack->raiseWidget( m_graphicwin ); 1687 editorStack->raiseWidget( m_graphicwin );
1688 m_graphicwin->setFocus(); 1688 m_graphicwin->setFocus();
1689} 1689}
1690 1690
1691 1691
1692void QTReaderApp::showprefs() 1692void QTReaderApp::showprefs()
1693{ 1693{
1694 CPrefs* prefwin = new CPrefs(!m_bFloatingDialog, this); 1694 CPrefs* prefwin = new CPrefs(!m_bFloatingDialog, this);
1695 1695
1696 prefwin->twotouch(m_twoTouch); 1696 prefwin->twotouch(m_twoTouch);
1697 prefwin->propfontchange(m_propogatefontchange); 1697 prefwin->propfontchange(m_propogatefontchange);
1698 prefwin->StripCR(reader->bstripcr); 1698 prefwin->StripCR(reader->bstripcr);
1699 prefwin->Dehyphen(reader->bdehyphen); 1699 prefwin->Dehyphen(reader->bdehyphen);
1700 prefwin->SingleSpace(reader->bonespace); 1700 prefwin->SingleSpace(reader->bonespace);
1701 prefwin->Unindent(reader->bunindent); 1701 prefwin->Unindent(reader->bunindent);
1702 prefwin->Reparagraph(reader->brepara); 1702 prefwin->Reparagraph(reader->brepara);
1703 prefwin->DoubleSpace(reader->bdblspce); 1703 prefwin->DoubleSpace(reader->bdblspce);
1704 prefwin->Remap(reader->bremap); 1704 prefwin->Remap(reader->bremap);
1705 prefwin->Embolden(reader->bmakebold); 1705 prefwin->Embolden(reader->bmakebold);
1706 prefwin->FullJustify(reader->bfulljust); 1706 prefwin->FullJustify(reader->bfulljust);
1707 prefwin->ParaLead(reader->getextraspace()); 1707 prefwin->ParaLead(reader->getextraspace());
1708 prefwin->LineLead(reader->getlead()); 1708 prefwin->LineLead(reader->getlead());
1709 prefwin->Margin(reader->m_border); 1709 prefwin->Margin(reader->m_border);
1710 prefwin->Indent(reader->bindenter); 1710 prefwin->Indent(reader->bindenter);
1711 if (reader->bautofmt) 1711 if (reader->bautofmt)
1712 { 1712 {
1713 prefwin->Markup(0); 1713 prefwin->Markup(0);
1714 } 1714 }
1715 else if (reader->btextfmt) 1715 else if (reader->btextfmt)
1716 { 1716 {
1717 prefwin->Markup(2); 1717 prefwin->Markup(2);
1718 } 1718 }
1719 else if (reader->bstriphtml) 1719 else if (reader->bstriphtml)
1720 { 1720 {
1721 prefwin->Markup(3); 1721 prefwin->Markup(3);
1722 } 1722 }
1723 else if (reader->bpeanut) 1723 else if (reader->bpeanut)
1724 { 1724 {
1725 prefwin->Markup(4); 1725 prefwin->Markup(4);
1726 } 1726 }
1727 else 1727 else
1728 { 1728 {
1729 prefwin->Markup(1); 1729 prefwin->Markup(1);
1730 } 1730 }
1731 prefwin->Depluck(reader->bdepluck); 1731 prefwin->Depluck(reader->bdepluck);
1732 prefwin->Dejpluck(reader->bdejpluck); 1732 prefwin->Dejpluck(reader->bdejpluck);
1733 prefwin->Continuous(reader->m_continuousDocument); 1733 prefwin->Continuous(reader->m_continuousDocument);
1734 1734
1735 prefwin->dictApplication(m_targetapp); 1735 prefwin->dictApplication(m_targetapp);
1736 prefwin->dictMessage(m_targetmsg); 1736 prefwin->dictMessage(m_targetmsg);
1737 1737
1738 prefwin->spaceAction(m_spaceTarget); 1738 prefwin->spaceAction(m_spaceTarget);
1739 prefwin->escapeAction(m_escapeTarget); 1739 prefwin->escapeAction(m_escapeTarget);
1740 prefwin->returnAction(m_returnTarget); 1740 prefwin->returnAction(m_returnTarget);
1741 prefwin->leftAction(m_leftTarget); 1741 prefwin->leftAction(m_leftTarget);
1742 prefwin->rightAction(m_rightTarget); 1742 prefwin->rightAction(m_rightTarget);
1743 prefwin->upAction(m_upTarget); 1743 prefwin->upAction(m_upTarget);
1744 prefwin->downAction(m_downTarget); 1744 prefwin->downAction(m_downTarget);
1745 1745
1746 prefwin->leftScroll(m_leftScroll); 1746 prefwin->leftScroll(m_leftScroll);
1747 prefwin->rightScroll(m_rightScroll); 1747 prefwin->rightScroll(m_rightScroll);
1748 prefwin->upScroll(m_upScroll); 1748 prefwin->upScroll(m_upScroll);
1749 prefwin->downScroll(m_downScroll); 1749 prefwin->downScroll(m_downScroll);
1750 1750
1751 prefwin->miscannotation(m_doAnnotation); 1751 prefwin->miscannotation(m_doAnnotation);
1752 prefwin->miscdictionary(m_doDictionary); 1752 prefwin->miscdictionary(m_doDictionary);
1753 prefwin->miscclipboard(m_doClipboard); 1753 prefwin->miscclipboard(m_doClipboard);
1754 1754
1755 prefwin->SwapMouse(reader->m_swapmouse); 1755 prefwin->SwapMouse(reader->m_swapmouse);
1756 1756
1757 prefwin->Font(reader->m_fontname); 1757 prefwin->Font(reader->m_fontname);
1758 1758
1759 prefwin->gfxsize(reader->getBaseSize()); 1759 prefwin->gfxsize(reader->getBaseSize());
1760 1760
1761 prefwin->pageoverlap(reader->m_overlap); 1761 prefwin->pageoverlap(reader->m_overlap);
1762 1762
1763 prefwin->ideogram(reader->m_bMonoSpaced); 1763 prefwin->ideogram(reader->m_bMonoSpaced);
1764 1764
1765 prefwin->encoding(reader->m_encd); 1765 prefwin->encoding(reader->m_encd);
1766 1766
1767 prefwin->ideogramwidth(reader->m_charpc); 1767 prefwin->ideogramwidth(reader->m_charpc);
1768 1768
1769 if (prefwin->exec()) 1769 if (prefwin->exec())
1770 { 1770 {
1771 m_twoTouch = prefwin->twotouch(); 1771 m_twoTouch = prefwin->twotouch();
1772 reader->setTwoTouch(m_twoTouch); 1772 reader->setTwoTouch(m_twoTouch);
1773 m_touch_action->setOn(m_twoTouch); 1773 m_touch_action->setOn(m_twoTouch);
1774 1774
1775 reader->bstripcr = prefwin->StripCR(); 1775 reader->bstripcr = prefwin->StripCR();
1776 reader->bdehyphen = prefwin->Dehyphen(); 1776 reader->bdehyphen = prefwin->Dehyphen();
1777 reader->bonespace = prefwin->SingleSpace(); 1777 reader->bonespace = prefwin->SingleSpace();
1778 reader->bunindent = prefwin->Unindent(); 1778 reader->bunindent = prefwin->Unindent();
1779 reader->brepara = prefwin->Reparagraph(); 1779 reader->brepara = prefwin->Reparagraph();
1780 reader->bdblspce = prefwin->DoubleSpace(); 1780 reader->bdblspce = prefwin->DoubleSpace();
1781 reader->bremap = prefwin->Remap(); 1781 reader->bremap = prefwin->Remap();
1782 reader->bmakebold = prefwin->Embolden(); 1782 reader->bmakebold = prefwin->Embolden();
1783 reader->bfulljust = prefwin->FullJustify(); 1783 reader->bfulljust = prefwin->FullJustify();
1784 reader->setextraspace(prefwin->ParaLead()); 1784 reader->setextraspace(prefwin->ParaLead());
1785 reader->setlead(prefwin->LineLead()); 1785 reader->setlead(prefwin->LineLead());
1786 reader->m_border = prefwin->Margin(); 1786 reader->m_border = prefwin->Margin();
1787 reader->bindenter = prefwin->Indent(); 1787 reader->bindenter = prefwin->Indent();
1788 reader->bautofmt = reader->btextfmt = reader->bstriphtml = reader->bpeanut = false; 1788 reader->bautofmt = reader->btextfmt = reader->bstriphtml = reader->bpeanut = false;
1789 switch (prefwin->Markup()) 1789 switch (prefwin->Markup())
1790 { 1790 {
1791 case 0: 1791 case 0:
1792 reader->bautofmt = true; 1792 reader->bautofmt = true;
1793 break; 1793 break;
1794 case 1: 1794 case 1:
1795 break; 1795 break;
1796 case 2: 1796 case 2:
1797 reader->btextfmt = true; 1797 reader->btextfmt = true;
1798 break; 1798 break;
1799 case 3: 1799 case 3:
1800 reader->bstriphtml = true; 1800 reader->bstriphtml = true;
1801 break; 1801 break;
1802 case 4: 1802 case 4:
1803 reader->bpeanut = true; 1803 reader->bpeanut = true;
1804 break; 1804 break;
1805 default: 1805 default:
1806 qDebug("Format out of range"); 1806 qDebug("Format out of range");
1807 } 1807 }
1808 reader->bdepluck = prefwin->Depluck(); 1808 reader->bdepluck = prefwin->Depluck();
1809 reader->bdejpluck = prefwin->Dejpluck(); 1809 reader->bdejpluck = prefwin->Dejpluck();
1810 reader->setContinuous(prefwin->Continuous()); 1810 reader->setContinuous(prefwin->Continuous());
1811 1811
1812 m_spaceTarget = (ActionTypes)prefwin->spaceAction(); 1812 m_spaceTarget = (ActionTypes)prefwin->spaceAction();
1813 m_escapeTarget = (ActionTypes)prefwin->escapeAction(); 1813 m_escapeTarget = (ActionTypes)prefwin->escapeAction();
1814 m_returnTarget = (ActionTypes)prefwin->returnAction(); 1814 m_returnTarget = (ActionTypes)prefwin->returnAction();
1815 m_leftTarget = (ActionTypes)prefwin->leftAction(); 1815 m_leftTarget = (ActionTypes)prefwin->leftAction();
1816 m_rightTarget = (ActionTypes)prefwin->rightAction(); 1816 m_rightTarget = (ActionTypes)prefwin->rightAction();
1817 m_upTarget = (ActionTypes)prefwin->upAction(); 1817 m_upTarget = (ActionTypes)prefwin->upAction();
1818 m_downTarget = (ActionTypes)prefwin->downAction(); 1818 m_downTarget = (ActionTypes)prefwin->downAction();
1819 m_leftScroll = prefwin->leftScroll(); 1819 m_leftScroll = prefwin->leftScroll();
1820 m_rightScroll = prefwin->rightScroll(); 1820 m_rightScroll = prefwin->rightScroll();
1821 m_upScroll = prefwin->upScroll(); 1821 m_upScroll = prefwin->upScroll();
1822 m_downScroll = prefwin->downScroll(); 1822 m_downScroll = prefwin->downScroll();
1823 1823
1824 m_targetapp = prefwin->dictApplication(); 1824 m_targetapp = prefwin->dictApplication();
1825 m_targetmsg = prefwin->dictMessage(); 1825 m_targetmsg = prefwin->dictMessage();
1826 1826
1827 m_doAnnotation = prefwin->miscannotation(); 1827 m_doAnnotation = prefwin->miscannotation();
1828 m_doDictionary = prefwin->miscdictionary(); 1828 m_doDictionary = prefwin->miscdictionary();
1829 m_doClipboard = prefwin->miscclipboard(); 1829 m_doClipboard = prefwin->miscclipboard();
1830 reader->m_swapmouse = prefwin->SwapMouse(); 1830 reader->m_swapmouse = prefwin->SwapMouse();
1831 reader->setBaseSize(prefwin->gfxsize()); 1831 reader->setBaseSize(prefwin->gfxsize());
1832 reader->m_overlap = prefwin->pageoverlap(); 1832 reader->m_overlap = prefwin->pageoverlap();
1833 reader->m_bMonoSpaced = prefwin->ideogram(); 1833 reader->m_bMonoSpaced = prefwin->ideogram();
1834 m_setmono_action->setOn(reader->m_bMonoSpaced); 1834 m_setmono_action->setOn(reader->m_bMonoSpaced);
1835 reader->m_encd = prefwin->encoding(); 1835 reader->m_encd = prefwin->encoding();
1836 reader->m_charpc = prefwin->ideogramwidth(); 1836 reader->m_charpc = prefwin->ideogramwidth();
1837 1837
1838 if ( 1838 if (
1839 reader->m_fontname != prefwin->Font() 1839 reader->m_fontname != prefwin->Font()
1840 || 1840 ||
1841 m_propogatefontchange != prefwin->propfontchange()) 1841 m_propogatefontchange != prefwin->propfontchange())
1842 { 1842 {
1843 m_propogatefontchange = prefwin->propfontchange(); 1843 m_propogatefontchange = prefwin->propfontchange();
1844 setfontHelper(prefwin->Font()); 1844 setfontHelper(prefwin->Font());
1845 } 1845 }
1846 delete prefwin; 1846 delete prefwin;
1847 reader->setfilter(reader->getfilter()); 1847 reader->setfilter(reader->getfilter());
1848 reader->refresh(); 1848 reader->refresh();
1849 1849
1850 } 1850 }
1851 else 1851 else
1852 { 1852 {
1853 delete prefwin; 1853 delete prefwin;
1854 } 1854 }
1855} 1855}
1856 1856
1857void QTReaderApp::showtoolbarprefs() 1857void QTReaderApp::showtoolbarprefs()
1858{ 1858{
1859#ifdef USEQPE 1859#ifdef USEQPE
1860 CBarPrefs* prefwin = new CBarPrefs(APPDIR, !m_bFloatingDialog, this); 1860 CBarPrefs* prefwin = new CBarPrefs(APPDIR, !m_bFloatingDialog, this);
1861#else 1861#else
1862 QFileInfo fi; 1862 QFileInfo fi;
1863 QDir d = QDir::home(); // "/" 1863 QDir d = QDir::home(); // "/"
1864 if ( !d.cd(APPDIR) ) 1864 if ( !d.cd(APPDIR) )
1865 { // "/tmp" 1865 { // "/tmp"
1866 qWarning( "Cannot find the \"~/%s\" directory", APPDIR ); 1866 qWarning( "Cannot find the \"~/%s\" directory", APPDIR );
1867 d = QDir::home(); 1867 d = QDir::home();
1868 d.mkdir(APPDIR); 1868 d.mkdir(APPDIR);
1869 d.cd(APPDIR); 1869 d.cd(APPDIR);
1870 } 1870 }
1871 fi.setFile(d, INIFILE); 1871 fi.setFile(d, INIFILE);
1872 CBarPrefs* prefwin = new CBarPrefs(fi.absFilePath(), !m_bFloatingDialog, this); 1872 CBarPrefs* prefwin = new CBarPrefs(fi.absFilePath(), !m_bFloatingDialog, this);
1873#endif 1873#endif
1874 prefwin->tbpolicy(m_tbpolsave); 1874 prefwin->tbpolicy(m_tbpolsave);
1875 prefwin->tbposition(m_tbposition-2); 1875 prefwin->tbposition(m_tbposition-2);
1876 prefwin->tbmovable(m_tbmovesave); 1876 prefwin->tbmovable(m_tbmovesave);
1877 prefwin->floating(m_bFloatingDialog); 1877 prefwin->floating(m_bFloatingDialog);
1878 if (prefwin->exec()) 1878 if (prefwin->exec())
1879 { 1879 {
1880 m_bFloatingDialog = prefwin->floating(); 1880 m_bFloatingDialog = prefwin->floating();
1881 if ( 1881 if (
1882 m_tbpolsave != (ToolbarPolicy)prefwin->tbpolicy() 1882 m_tbpolsave != (ToolbarPolicy)prefwin->tbpolicy()
1883 || 1883 ||
1884 m_tbposition != (ToolBarDock)(prefwin->tbposition()+2) 1884 m_tbposition != (ToolBarDock)(prefwin->tbposition()+2)
1885 || 1885 ||
1886 m_tbmovesave != prefwin->tbmovable() 1886 m_tbmovesave != prefwin->tbmovable()
1887 ) 1887 )
1888 { 1888 {
1889 QMessageBox::warning(this, PROGNAME, "Some changes won't take effect\nuntil the next time the\napplication is started"); 1889 QMessageBox::warning(this, PROGNAME, "Some changes won't take effect\nuntil the next time the\napplication is started");
1890 } 1890 }
1891 m_tbpolsave = (ToolbarPolicy)prefwin->tbpolicy(); 1891 m_tbpolsave = (ToolbarPolicy)prefwin->tbpolicy();
1892 m_tbposition = (ToolBarDock)(prefwin->tbposition()+2); 1892 m_tbposition = (ToolBarDock)(prefwin->tbposition()+2);
1893 m_tbmovesave = prefwin->tbmovable(); 1893 m_tbmovesave = prefwin->tbmovable();
1894 bool isChanged = prefwin->isChanged(); 1894 bool isChanged = prefwin->isChanged();
1895 delete prefwin; 1895 delete prefwin;
1896#ifdef USEQPE 1896#ifdef USEQPE
1897 Config config( APPDIR ); 1897 Config config( APPDIR );
1898#else 1898#else
1899 QFileInfo fi; 1899 QFileInfo fi;
1900 QDir d = QDir::home(); // "/" 1900 QDir d = QDir::home(); // "/"
1901 if ( !d.cd(APPDIR) ) 1901 if ( !d.cd(APPDIR) )
1902 { // "/tmp" 1902 { // "/tmp"
1903 qWarning( "Cannot find the \"~/%s\" directory", APPDIR ); 1903 qWarning( "Cannot find the \"~/%s\" directory", APPDIR );
1904 d = QDir::home(); 1904 d = QDir::home();
1905 d.mkdir(APPDIR); 1905 d.mkdir(APPDIR);
1906 d.cd(APPDIR); 1906 d.cd(APPDIR);
1907 } 1907 }
1908 fi.setFile(d, INIFILE); 1908 fi.setFile(d, INIFILE);
1909 Config config( fi.absFilePath() ); 1909 Config config( fi.absFilePath() );
1910#endif 1910#endif
1911 if (isChanged) addtoolbars(&config); 1911 if (isChanged) addtoolbars(&config);
1912 } 1912 }
1913 else 1913 else
1914 { 1914 {
1915 delete prefwin; 1915 delete prefwin;
1916 } 1916 }
1917} 1917}
1918 1918
1919void QTReaderApp::showinfo() 1919void QTReaderApp::showinfo()
1920{ 1920{
1921 unsigned long fs, ts, pl; 1921 unsigned long fs, ts, pl;
1922 if (reader->empty()) 1922 if (reader->empty())
1923 { 1923 {
1924 QMessageBox::information(this, PROGNAME, "No file loaded", 1); 1924 QMessageBox::information(this, PROGNAME, "No file loaded", 1);
1925 } 1925 }
1926 else 1926 else
1927 { 1927 {
1928 reader->sizes(fs,ts); 1928 reader->sizes(fs,ts);
1929 pl = reader->pagelocate(); 1929 pl = reader->pagelocate();
1930 m_infoWin->setFileSize(fs); 1930 m_infoWin->setFileSize(fs);
1931 m_infoWin->setTextSize(ts); 1931 m_infoWin->setTextSize(ts);
1932 m_infoWin->setRatio(100-(100*fs + (ts >> 1))/ts); 1932 m_infoWin->setRatio(100-(100*fs + (ts >> 1))/ts);
1933 m_infoWin->setLocation(pl); 1933 m_infoWin->setLocation(pl);
1934 m_infoWin->setRead((100*pl + (ts >> 1))/ts); 1934 m_infoWin->setRead((100*pl + (ts >> 1))/ts);
1935 editorStack->raiseWidget( m_infoWin ); 1935 editorStack->raiseWidget( m_infoWin );
1936 m_infoWin->setFocus(); 1936 m_infoWin->setFocus();
1937 } 1937 }
1938} 1938}
1939 1939
1940void QTReaderApp::addAnno(const QString& name, const QString& text, size_t posn) 1940void QTReaderApp::addAnno(const QString& name, const QString& text, size_t posn)
1941{ 1941{
1942 if (pBkmklist == NULL) pBkmklist = new CList<Bkmk>; 1942 if (pBkmklist == NULL) pBkmklist = new CList<Bkmk>;
1943#ifdef _UNICODE 1943#ifdef _UNICODE
1944 CBuffer buff(name.length()+1); 1944 CBuffer buff(name.length()+1);
1945 int i; 1945 int i;
1946 for (i = 0; i < name.length(); i++) 1946 for (i = 0; i < name.length(); i++)
1947 { 1947 {
1948 buff[i] = name[i].unicode(); 1948 buff[i] = name[i].unicode();
1949 } 1949 }
1950 buff[i] = 0; 1950 buff[i] = 0;
1951 CBuffer buff2(text.length()+1); 1951 CBuffer buff2(text.length()+1);
1952 for (i = 0; i < text.length(); i++) 1952 for (i = 0; i < text.length(); i++)
1953 { 1953 {
1954 buff2[i] = text[i].unicode(); 1954 buff2[i] = text[i].unicode();
1955 } 1955 }
1956 buff2[i] = 0; 1956 buff2[i] = 0;
1957 pBkmklist->push_front(Bkmk(buff.data(), buff2.data(), posn)); 1957 pBkmklist->push_front(Bkmk(buff.data(), buff2.data(), posn));
1958#else 1958#else
1959 pBkmklist->push_front(Bkmk((const tchar*)text,posn)); 1959 pBkmklist->push_front(Bkmk((const tchar*)text,posn));
1960#endif 1960#endif
1961 m_fBkmksChanged = true; 1961 m_fBkmksChanged = true;
1962 pBkmklist->sort(); 1962 pBkmklist->sort();
1963} 1963}
1964 1964
1965void QTReaderApp::addAnno(const QString& name, const QString& text) 1965void QTReaderApp::addAnno(const QString& name, const QString& text)
1966{ 1966{
1967 if (m_annoIsEditing) 1967 if (m_annoIsEditing)
1968 { 1968 {
1969 if (name.isEmpty()) 1969 if (name.isEmpty())
1970 { 1970 {
1971 QMessageBox::information(this, PROGNAME, "Need a name for the bookmark\nPlease try again", 1); 1971 QMessageBox::information(this, PROGNAME, "Need a name for the bookmark\nPlease try again", 1);
1972 } 1972 }
1973 else 1973 else
1974 { 1974 {
1975 addAnno(name, text, m_annoWin->getPosn()); 1975 addAnno(name, text, m_annoWin->getPosn());
1976 } 1976 }
1977 showEditTools(); 1977 showEditTools();
1978 } 1978 }
1979 else 1979 else
1980 { 1980 {
1981 if (m_annoWin->edited()) 1981 if (m_annoWin->edited())
1982 { 1982 {
1983 CBuffer buff(text.length()+1); 1983 CBuffer buff(text.length()+1);
1984 int i; 1984 int i;
1985 for (i = 0; i < text.length(); i++) 1985 for (i = 0; i < text.length(); i++)
1986 { 1986 {
1987 buff[i] = text[i].unicode(); 1987 buff[i] = text[i].unicode();
1988 } 1988 }
1989 buff[i] = 0; 1989 buff[i] = 0;
1990 m_fBkmksChanged = true; 1990 m_fBkmksChanged = true;
1991 m_anno->setAnno(buff.data()); 1991 m_anno->setAnno(buff.data());
1992 } 1992 }
1993 bool found = findNextBookmark(m_anno->value()+1); 1993 bool found = findNextBookmark(m_anno->value()+1);
1994 if (found) 1994 if (found)
1995 { 1995 {
1996 m_annoWin->setName(toQString(m_anno->name())); 1996 m_annoWin->setName(toQString(m_anno->name()));
1997 m_annoWin->setAnno(toQString(m_anno->anno())); 1997 m_annoWin->setAnno(toQString(m_anno->anno()));
1998 } 1998 }
1999 else 1999 else
2000 { 2000 {
2001 showEditTools(); 2001 showEditTools();
2002 } 2002 }
2003 } 2003 }
2004} 2004}
2005 2005
2006bool QTReaderApp::findNextBookmark(size_t start) 2006bool QTReaderApp::findNextBookmark(size_t start)
2007{ 2007{
2008 bool found = false; 2008 bool found = false;
2009 for (CList<Bkmk>::iterator iter = pBkmklist->begin(); iter != pBkmklist->end(); iter++) 2009 for (CList<Bkmk>::iterator iter = pBkmklist->begin(); iter != pBkmklist->end(); iter++)
2010 { 2010 {
2011 if (iter->value() >= start) 2011 if (iter->value() >= start)
2012 { 2012 {
2013 if (iter->value() < reader->locate()) 2013 if (iter->value() < reader->locate())
2014 { 2014 {
2015 found = true; 2015 found = true;
2016 m_anno = iter.pContent(); 2016 m_anno = iter.pContent();
2017 } 2017 }
2018 break; 2018 break;
2019 } 2019 }
2020 } 2020 }
2021 return found; 2021 return found;
2022} 2022}
2023 2023
2024void QTReaderApp::addanno() 2024void QTReaderApp::addanno()
2025{ 2025{
2026 if (reader->empty()) 2026 if (reader->empty())
2027 { 2027 {
2028 QMessageBox::information(this, PROGNAME, "No file loaded", 1); 2028 QMessageBox::information(this, PROGNAME, "No file loaded", 1);
2029 } 2029 }
2030 else 2030 else
2031 { 2031 {
2032 m_annoWin->setName(""); 2032 m_annoWin->setName("");
2033 m_annoWin->setAnno(""); 2033 m_annoWin->setAnno("");
2034 m_annoWin->setPosn(reader->pagelocate()); 2034 m_annoWin->setPosn(reader->pagelocate());
2035 m_annoIsEditing = true; 2035 m_annoIsEditing = true;
2036 editorStack->raiseWidget( m_annoWin ); 2036 editorStack->raiseWidget( m_annoWin );
2037#ifdef USEQPE 2037#ifdef USEQPE
2038 Global::showInputMethod(); 2038 Global::showInputMethod();
2039#endif 2039#endif
2040 m_annoWin->setFocus(); 2040 m_annoWin->setFocus();
2041 } 2041 }
2042} 2042}
2043 2043
2044void QTReaderApp::infoClose() 2044void QTReaderApp::infoClose()
2045{ 2045{
2046 showEditTools(); 2046 showEditTools();
2047} 2047}
2048 2048
2049/* 2049/*
2050void QTReaderApp::fileRevert() 2050void QTReaderApp::fileRevert()
2051{ 2051{
2052 clear(); 2052 clear();
2053 fileOpen(); 2053 fileOpen();
2054} 2054}
2055 2055
2056void QTReaderApp::editCut() 2056void QTReaderApp::editCut()
2057{ 2057{
2058#ifndef QT_NO_CLIPBOARD 2058#ifndef QT_NO_CLIPBOARD
2059 editor->cut(); 2059 editor->cut();
2060#endif 2060#endif
2061} 2061}
2062*/ 2062*/
2063void QTReaderApp::editMark() 2063void QTReaderApp::editMark()
2064{ 2064{
2065 m_savedpos = reader->pagelocate(); 2065 m_savedpos = reader->pagelocate();
2066} 2066}
2067 2067
2068void QTReaderApp::editCopy() 2068void QTReaderApp::editCopy()
2069{ 2069{
2070 QClipboard* cb = QApplication::clipboard(); 2070 QClipboard* cb = QApplication::clipboard();
2071 QString text; 2071 QString text;
2072 int ch; 2072 int ch;
2073 unsigned long currentpos = reader->pagelocate(); 2073 unsigned long currentpos = reader->pagelocate();
2074 unsigned long endpos = reader->locate(); 2074 unsigned long endpos = reader->locate();
2075 if (m_savedpos == 0xffffffff) 2075 if (m_savedpos == 0xffffffff)
2076 { 2076 {
2077 m_savedpos = currentpos; 2077 m_savedpos = currentpos;
2078 } 2078 }
2079 reader->jumpto(m_savedpos); 2079 reader->jumpto(m_savedpos);
2080 while (reader->explocate() < endpos && (ch = reader->getch()) != UEOF) 2080 while (reader->explocate() < endpos && (ch = reader->getch()) != UEOF)
2081 { 2081 {
2082 text += ch; 2082 text += ch;
2083 } 2083 }
2084 cb->setText(text); 2084 cb->setText(text);
2085 reader->locate(currentpos); 2085 reader->locate(currentpos);
2086 m_savedpos = 0xffffffff; 2086 m_savedpos = 0xffffffff;
2087} 2087}
2088 2088
2089void QTReaderApp::gotoStart() 2089void QTReaderApp::gotoStart()
2090{ 2090{
2091 reader->locate(reader->buffdoc.startSection()); 2091 reader->locate(reader->buffdoc.startSection());
2092} 2092}
2093 2093
2094void QTReaderApp::gotoEnd() 2094void QTReaderApp::gotoEnd()
2095{ 2095{
2096 reader->dopageup(reader->buffdoc.endSection()); 2096 reader->dopageup(reader->buffdoc.endSection());
2097} 2097}
2098 2098
2099void QTReaderApp::pageup() 2099void QTReaderApp::pageup()
2100{ 2100{
2101 reader->NavUp(); 2101 reader->NavUp();
2102} 2102}
2103 2103
2104void QTReaderApp::pagedn() 2104void QTReaderApp::pagedn()
2105{ 2105{
2106 reader->NavDown(); 2106 reader->NavDown();
2107} 2107}
2108 2108
2109void QTReaderApp::pagemode(bool _b) 2109void QTReaderApp::pagemode(bool _b)
2110{ 2110{
2111 reader->setpagemode(_b); 2111 reader->setpagemode(_b);
2112} 2112}
2113 2113
2114/* 2114/*
2115void QTReaderApp::setspacing() 2115void QTReaderApp::setspacing()
2116{ 2116{
2117 m_nRegAction = cMonoSpace; 2117 m_nRegAction = cMonoSpace;
2118 char lcn[20]; 2118 char lcn[20];
2119 sprintf(lcn, "%lu", reader->m_charpc); 2119 sprintf(lcn, "%lu", reader->m_charpc);
2120 regEdit->setText(lcn); 2120 regEdit->setText(lcn);
2121 do_regedit(); 2121 do_regedit();
2122} 2122}
2123*/ 2123*/
2124void QTReaderApp::settarget() 2124void QTReaderApp::settarget()
2125{ 2125{
2126 m_nRegAction = cSetTarget; 2126 m_nRegAction = cSetTarget;
2127 QString text = ((m_targetapp.isEmpty()) ? QString("") : m_targetapp) 2127 QString text = ((m_targetapp.isEmpty()) ? QString("") : m_targetapp)
2128 + "/" 2128 + "/"
2129 + ((m_targetmsg.isEmpty()) ? QString("") : m_targetmsg); 2129 + ((m_targetmsg.isEmpty()) ? QString("") : m_targetmsg);
2130 regEdit->setText(text); 2130 regEdit->setText(text);
2131 do_regedit(); 2131 do_regedit();
2132} 2132}
2133 2133
2134/* 2134/*
2135void QTReaderApp::do_mono(const QString& lcn) 2135void QTReaderApp::do_mono(const QString& lcn)
2136{ 2136{
2137 bool ok; 2137 bool ok;
2138 unsigned long ulcn = lcn.toULong(&ok); 2138 unsigned long ulcn = lcn.toULong(&ok);
2139 if (ok) 2139 if (ok)
2140 { 2140 {
2141 reader->m_charpc = ulcn; 2141 reader->m_charpc = ulcn;
2142 reader->setfont(); 2142 reader->setfont();
2143 reader->refresh(); 2143 reader->refresh();
2144 //reader->setmono(true); 2144 //reader->setmono(true);
2145 } 2145 }
2146 else 2146 else
2147 QMessageBox::information(this, PROGNAME, "Must be a number"); 2147 QMessageBox::information(this, PROGNAME, "Must be a number");
2148} 2148}
2149*/ 2149*/
2150/* 2150/*
2151void QTReaderApp::editPaste() 2151void QTReaderApp::editPaste()
2152{ 2152{
2153#ifndef QT_NO_CLIPBOARD 2153#ifndef QT_NO_CLIPBOARD
2154 editor->paste(); 2154 editor->paste();
2155#endif 2155#endif
2156} 2156}
2157*/ 2157*/
2158 2158
2159void QTReaderApp::editFind() 2159void QTReaderApp::editFind()
2160{ 2160{
2161 searchStart = reader->pagelocate(); 2161 searchStart = reader->pagelocate();
2162#ifdef __ISEARCH 2162#ifdef __ISEARCH
2163 searchStack = new QStack<searchrecord>; 2163 searchStack = new QStack<searchrecord>;
2164#endif 2164#endif
2165#ifdef USEQPE 2165#ifdef USEQPE
2166 Global::showInputMethod(); 2166 Global::showInputMethod();
2167#endif 2167#endif
2168 searchBar->show(); 2168 searchBar->show();
2169 searchVisible = TRUE; 2169 searchVisible = TRUE;
2170 searchEdit->setFocus(); 2170 searchEdit->setFocus();
2171#ifdef __ISEARCH 2171#ifdef __ISEARCH
2172 searchStack->push(new searchrecord("",reader->pagelocate())); 2172 searchStack->push(new searchrecord("",reader->pagelocate()));
2173#endif 2173#endif
2174} 2174}
2175 2175
2176void QTReaderApp::findNext() 2176void QTReaderApp::findNext()
2177{ 2177{
2178// // qDebug("findNext called\n"); 2178// // qDebug("findNext called\n");
2179#ifdef __ISEARCH 2179#ifdef __ISEARCH
2180 QString arg = searchEdit->text(); 2180 QString arg = searchEdit->text();
2181#else 2181#else
2182 QRegExp arg = searchEdit->text(); 2182 QRegExp arg = searchEdit->text();
2183#endif 2183#endif
2184 CDrawBuffer test(&(reader->m_fontControl)); 2184 CDrawBuffer test(&(reader->m_fontControl));
2185 size_t start = reader->pagelocate(); 2185 size_t start = reader->pagelocate();
2186 reader->jumpto(start); 2186 reader->jumpto(start);
2187 reader->getline(&test); 2187 reader->getline(&test);
2188 dosearch(start, test, arg); 2188 dosearch(start, test, arg);
2189} 2189}
2190 2190
2191void QTReaderApp::findClose() 2191void QTReaderApp::findClose()
2192{ 2192{
2193 searchVisible = FALSE; 2193 searchVisible = FALSE;
2194 searchEdit->setText(""); 2194 searchEdit->setText("");
2195#ifdef USEQPE 2195#ifdef USEQPE
2196 Global::hideInputMethod(); 2196 Global::hideInputMethod();
2197#endif 2197#endif
2198 searchBar->hide(); 2198 searchBar->hide();
2199#ifdef __ISEARCH 2199#ifdef __ISEARCH
2200// searchStack = new QStack<searchrecord>; 2200// searchStack = new QStack<searchrecord>;
2201 while (!searchStack->isEmpty()) 2201 while (!searchStack->isEmpty())
2202 { 2202 {
2203 delete searchStack->pop(); 2203 delete searchStack->pop();
2204 } 2204 }
2205 delete searchStack; 2205 delete searchStack;
2206#endif 2206#endif
2207 reader->setFocus(); 2207 reader->setFocus();
2208} 2208}
2209 2209
2210void QTReaderApp::regClose() 2210void QTReaderApp::regClose()
2211{ 2211{
2212 regVisible = FALSE; 2212 regVisible = FALSE;
2213 regEdit->setText(""); 2213 regEdit->setText("");
2214 regBar->hide(); 2214 regBar->hide();
2215#ifdef USEQPE 2215#ifdef USEQPE
2216 Global::hideInputMethod(); 2216 Global::hideInputMethod();
2217#endif 2217#endif
2218 reader->setFocus(); 2218 reader->setFocus();
2219} 2219}
2220 2220
2221#ifdef __ISEARCH 2221#ifdef __ISEARCH
2222bool QTReaderApp::dosearch(size_t start, CDrawBuffer& test, const QString& arg) 2222bool QTReaderApp::dosearch(size_t start, CDrawBuffer& test, const QString& arg)
2223#else 2223#else
2224bool QTReaderApp::dosearch(size_t start, CDrawBuffer& test, const QRegExp& arg) 2224bool QTReaderApp::dosearch(size_t start, CDrawBuffer& test, const QRegExp& arg)
2225#endif 2225#endif
2226{ 2226{
2227 bool ret = true; 2227 bool ret = true;
2228 unsigned long fs, ts; 2228 unsigned long fs, ts;
2229 reader->sizes(fs,ts); 2229 reader->sizes(fs,ts);
2230 size_t pos = reader->locate(); 2230 size_t pos = reader->locate();
2231 pbar->setGeometry(searchBar->x(),searchBar->y(),searchBar->width(), searchBar->height()); 2231 pbar->setGeometry(searchBar->x(),searchBar->y(),searchBar->width(), searchBar->height());
2232 pbar->show(); 2232 pbar->show();
2233 pbar->raise(); 2233 pbar->raise();
2234 pbar->reset(); 2234 pbar->reset();
2235 int offset; 2235 int offset;
2236 int lastpc = (100*pos)/ts; 2236 int lastpc = (100*pos)/ts;
2237 pbar->setProgress(lastpc); 2237 pbar->setProgress(lastpc);
2238// qApp->processEvents(); 2238// qApp->processEvents();
2239 if (reader->buffdoc.getpara(test) >= 0) 2239 if (reader->buffdoc.getpara(test) >= 0)
2240 { 2240 {
2241 reader->setFocus(); 2241 reader->setFocus();
2242#ifdef __ISEARCH 2242#ifdef __ISEARCH
2243 while (strstr(test.data(),(const tchar*)arg) == NULL) 2243 while (strstr(test.data(),(const tchar*)arg) == NULL)
2244#else 2244#else
2245#ifdef _UNICODE 2245#ifdef _UNICODE
2246 while ((offset = arg.match(toQString(test.data()))) == -1) 2246 while ((offset = arg.match(toQString(test.data()))) == -1)
2247#else 2247#else
2248 while (arg.match(test.data()) == -1) 2248 while (arg.match(test.data()) == -1)
2249#endif 2249#endif
2250#endif 2250#endif
2251 { 2251 {
2252 pos = reader->locate(); 2252 pos = reader->locate();
2253 int pc = (100*pos)/ts; 2253 int pc = (100*pos)/ts;
2254 if (pc != lastpc) 2254 if (pc != lastpc)
2255 { 2255 {
2256 pbar->setProgress(pc); 2256 pbar->setProgress(pc);
2257 qApp->processEvents(); 2257 qApp->processEvents();
2258 reader->setFocus(); 2258 reader->setFocus();
2259 lastpc = pc; 2259 lastpc = pc;
2260 } 2260 }
2261 2261
2262 if (reader->buffdoc.getpara(test) < 0) 2262 if (reader->buffdoc.getpara(test) < 0)
2263 { 2263 {
2264 if (QMessageBox::warning(this, "Can't find", searchEdit->text(), 1, 2) == 2) 2264 if (QMessageBox::warning(this, "Can't find", searchEdit->text(), 1, 2) == 2)
2265 pos = searchStart; 2265 pos = searchStart;
2266 else 2266 else
2267 pos = start; 2267 pos = start;
2268 findClose(); 2268 findClose();
2269 pbar->hide(); 2269 pbar->hide();
2270 reader->locate(pos); 2270 reader->locate(pos);
2271 return false; 2271 return false;
2272 } 2272 }
2273 } 2273 }
2274// qDebug("Found it at %u:%u", pos, offset); 2274// qDebug("Found it at %u:%u", pos, offset);
2275 pbar->hide(); 2275 pbar->hide();
2276// qDebug("Hid"); 2276// qDebug("Hid");
2277 reader->locate(pos+offset); 2277 reader->locate(pos+offset);
2278// qDebug("Loacted"); 2278// qDebug("Loacted");
2279// qDebug("page up"); 2279// qDebug("page up");
2280 ret = true; 2280 ret = true;
2281 } 2281 }
2282 else 2282 else
2283 { 2283 {
2284 if (QMessageBox::warning(this, "Can't find", searchEdit->text(), 1, 2) == 2) 2284 if (QMessageBox::warning(this, "Can't find", searchEdit->text(), 1, 2) == 2)
2285 pos = searchStart; 2285 pos = searchStart;
2286 else 2286 else
2287 pos = start; 2287 pos = start;
2288 ret = false; 2288 ret = false;
2289 findClose(); 2289 findClose();
2290 } 2290 }
2291 return ret; 2291 return ret;
2292} 2292}
2293 2293
2294#ifdef __ISEARCH 2294#ifdef __ISEARCH
2295void QTReaderApp::search(const QString & arg) 2295void QTReaderApp::search(const QString & arg)
2296{ 2296{
2297 searchrecord* ss = searchStack->top(); 2297 searchrecord* ss = searchStack->top();
2298 CBuffer test; 2298 CBuffer test;
2299 size_t start = reader->pagelocate(); 2299 size_t start = reader->pagelocate();
2300 bool haspopped = false; 2300 bool haspopped = false;
2301 while (arg.left(ss->s.length()) != ss->s) 2301 while (arg.left(ss->s.length()) != ss->s)
2302 { 2302 {
2303 haspopped = true; 2303 haspopped = true;
2304 start = ss->pos; 2304 start = ss->pos;
2305// reader->locate(start); 2305// reader->locate(start);
2306 searchStack->pop(); 2306 searchStack->pop();
2307 delete ss; 2307 delete ss;
2308 } 2308 }
2309 if (haspopped) reader->locate(start); 2309 if (haspopped) reader->locate(start);
2310/* 2310/*
2311 if (arg.length() < ss->len) 2311 if (arg.length() < ss->len)
2312 { 2312 {
2313 start = ss->pos; 2313 start = ss->pos;
2314 reader->locate(start); 2314 reader->locate(start);
2315 searchStack->pop(); 2315 searchStack->pop();
2316 delete ss; 2316 delete ss;
2317 } 2317 }
2318*/ 2318*/
2319 else 2319 else
2320 { 2320 {
2321 start = reader->pagelocate(); 2321 start = reader->pagelocate();
2322 reader->jumpto(start); 2322 reader->jumpto(start);
2323 searchStack->push(new searchrecord(arg,start)); 2323 searchStack->push(new searchrecord(arg,start));
2324 } 2324 }
2325 dosearch(start, test, arg); 2325 dosearch(start, test, arg);
2326} 2326}
2327#else 2327#else
2328void QTReaderApp::search() 2328void QTReaderApp::search()
2329{ 2329{
2330 findNext(); 2330 findNext();
2331} 2331}
2332#endif 2332#endif
2333 2333
2334void QTReaderApp::openFile( const QString &f ) 2334void QTReaderApp::openFile( const QString &f )
2335{ 2335{
2336// qDebug("File:%s", (const char*)f); 2336// qDebug("File:%s", (const char*)f);
2337// openFile(DocLnk(f)); 2337// openFile(DocLnk(f));
2338//} 2338//}
2339// 2339//
2340//void QTReaderApp::openFile( const DocLnk &f ) 2340//void QTReaderApp::openFile( const DocLnk &f )
2341//{ 2341//{
2342 clear(); 2342 clear();
2343 QFileInfo fm(f); 2343 QFileInfo fm(f);
2344 if ( fm.exists() ) 2344 if ( fm.exists() )
2345 { 2345 {
2346// QMessageBox::information(0, "Progress", "Calling fileNew()"); 2346// QMessageBox::information(0, "Progress", "Calling fileNew()");
2347#ifdef USEQPE 2347#ifdef USEQPE
2348 if (fm.extension( FALSE ) == "desktop") 2348 if (fm.extension( FALSE ) == "desktop")
2349 { 2349 {
2350 DocLnk d(f); 2350 DocLnk d(f);
2351 QFileInfo fnew(d.file()); 2351 QFileInfo fnew(d.file());
2352 fm = fnew; 2352 fm = fnew;
2353 if (!fm.exists()) return; 2353 if (!fm.exists()) return;
2354 } 2354 }
2355#endif 2355#endif
2356 clear(); 2356 clear();
2357 2357
2358 reader->setText(fm.baseName(), fm.absFilePath()); 2358 reader->setText(fm.baseName(), fm.absFilePath());
2359 m_loadedconfig = readconfig(reader->m_string, false); 2359 m_loadedconfig = readconfig(reader->m_string, false);
2360 showEditTools(); 2360 showEditTools();
2361 readbkmks(); 2361 readbkmks();
2362 m_savedpos = 0xffffffff; 2362 m_savedpos = 0xffffffff;
2363 } 2363 }
2364 else 2364 else
2365 { 2365 {
2366 QMessageBox::information(this, PROGNAME, "File does not exist"); 2366 QMessageBox::information(this, PROGNAME, "File does not exist");
2367 reader->m_lastfile = QString::null; 2367 reader->m_lastfile = QString::null;
2368 } 2368 }
2369 2369
2370} 2370}
2371/* 2371/*
2372void QTReaderApp::resizeEvent(QResizeEvent* e) 2372void QTReaderApp::resizeEvent(QResizeEvent* e)
2373{ 2373{
2374 if (m_fullscreen) 2374 if (m_fullscreen)
2375 { 2375 {
2376 showNormal(); 2376 showNormal();
2377 showFullScreen(); 2377 showFullScreen();
2378 } 2378 }
2379} 2379}
2380*/ 2380*/
2381void QTReaderApp::handlekey(QKeyEvent* e) 2381void QTReaderApp::handlekey(QKeyEvent* e)
2382{ 2382{
2383// qDebug("Keypress event"); 2383// qDebug("Keypress event");
2384 timeb now; 2384 timeb now;
2385 ftime(&now); 2385 ftime(&now);
2386 unsigned long etime = (1000*(now.time - m_lastkeytime.time) + now.millitm)-m_lastkeytime.millitm; 2386 unsigned long etime = (1000*(now.time - m_lastkeytime.time) + now.millitm)-m_lastkeytime.millitm;
2387 if (etime < m_debounce) 2387 if (etime < m_debounce)
2388 { 2388 {
2389 return; 2389 return;
2390 } 2390 }
2391 m_lastkeytime = now; 2391 m_lastkeytime = now;
2392 switch(e->key()) 2392 switch(e->key())
2393 { 2393 {
2394 case Key_Escape: 2394 case Key_Escape:
2395 // qDebug("escape event"); 2395 // qDebug("escape event");
2396 if (m_disableesckey) 2396 if (m_disableesckey)
2397 { 2397 {
2398 m_disableesckey = false; 2398 m_disableesckey = false;
2399 } 2399 }
2400 else 2400 else
2401 { 2401 {
2402 m_bcloseDisabled = true; 2402 m_bcloseDisabled = true;
2403 if (m_fullscreen) 2403 if (m_fullscreen)
2404 { 2404 {
2405 m_actFullscreen->setOn(false); 2405 m_actFullscreen->setOn(false);
2406 e->accept(); 2406 e->accept();
2407 } 2407 }
2408 else 2408 else
2409 { 2409 {
2410 // qDebug("escape action"); 2410 // qDebug("escape action");
2411 doAction(m_escapeTarget, e); 2411 doAction(m_escapeTarget, e);
2412 } 2412 }
2413 } 2413 }
2414 break; 2414 break;
2415 case Key_Space: 2415 case Key_Space:
2416 { 2416 {
2417 doAction(m_spaceTarget, e); 2417 doAction(m_spaceTarget, e);
2418 } 2418 }
2419 break; 2419 break;
2420 case Key_Return: 2420 case Key_Return:
2421 { 2421 {
2422 doAction(m_returnTarget, e); 2422 doAction(m_returnTarget, e);
2423 } 2423 }
2424 break; 2424 break;
2425 case Key_Left: 2425 case Key_Left:
2426 { 2426 {
2427 if (reader->m_autoScroll && m_leftScroll) 2427 if (reader->m_autoScroll && m_leftScroll)
2428 { 2428 {
2429 reader->reduceScroll(); 2429 reader->reduceScroll();
2430 } 2430 }
2431 else 2431 else
2432 { 2432 {
2433 doAction(m_leftTarget, e); 2433 doAction(m_leftTarget, e);
2434 } 2434 }
2435 } 2435 }
2436 break; 2436 break;
2437 case Key_Right: 2437 case Key_Right:
2438 { 2438 {
2439 if (reader->m_autoScroll && m_rightScroll) 2439 if (reader->m_autoScroll && m_rightScroll)
2440 { 2440 {
2441 reader->increaseScroll(); 2441 reader->increaseScroll();
2442 } 2442 }
2443 else 2443 else
2444 { 2444 {
2445 doAction(m_rightTarget, e); 2445 doAction(m_rightTarget, e);
2446 } 2446 }
2447 } 2447 }
2448 break; 2448 break;
2449 case Key_Up: 2449 case Key_Up:
2450 { 2450 {
2451 if (reader->m_autoScroll && m_upScroll) 2451 if (reader->m_autoScroll && m_upScroll)
2452 { 2452 {
2453 reader->increaseScroll(); 2453 reader->increaseScroll();
2454 } 2454 }
2455 else 2455 else
2456 { 2456 {
2457 doAction(m_upTarget, e); 2457 doAction(m_upTarget, e);
2458 } 2458 }
2459 } 2459 }
2460 break; 2460 break;
2461 case Key_Down: 2461 case Key_Down:
2462 { 2462 {
2463 if (reader->m_autoScroll && m_downScroll) 2463 if (reader->m_autoScroll && m_downScroll)
2464 { 2464 {
2465 reader->reduceScroll(); 2465 reader->reduceScroll();
2466 } 2466 }
2467 else 2467 else
2468 { 2468 {
2469 doAction(m_downTarget, e); 2469 doAction(m_downTarget, e);
2470 } 2470 }
2471 } 2471 }
2472 break; 2472 break;
2473 default: 2473 default:
2474 { 2474 {
2475 e->ignore(); 2475 e->ignore();
2476 } 2476 }
2477 2477
2478/* 2478/*
2479 QString msg("Key press was:"); 2479 QString msg("Key press was:");
2480 QString key; 2480 QString key;
2481 msg += key.setNum(e->key()); 2481 msg += key.setNum(e->key());
2482 QMessageBox::information(this, PROGNAME, msg); 2482 QMessageBox::information(this, PROGNAME, msg);
2483*/ 2483*/
2484 } 2484 }
2485} 2485}
2486 2486
2487void QTReaderApp::showEditTools() 2487void QTReaderApp::showEditTools()
2488{ 2488{
2489// if ( !doc ) 2489// if ( !doc )
2490 //close(); 2490 //close();
2491 if (m_fullscreen) 2491 if (m_fullscreen)
2492 { 2492 {
2493 if (menubar != NULL) menubar->hide(); 2493 if (menubar != NULL) menubar->hide();
2494 if (fileBar != NULL) fileBar->hide(); 2494 if (fileBar != NULL) fileBar->hide();
2495 if (viewBar != NULL) viewBar->hide(); 2495 if (viewBar != NULL) viewBar->hide();
2496 if (navBar != NULL) navBar->hide(); 2496 if (navBar != NULL) navBar->hide();
2497 if (markBar != NULL) markBar->hide(); 2497 if (markBar != NULL) markBar->hide();
2498 searchBar->hide(); 2498 searchBar->hide();
2499 regBar->hide(); 2499 regBar->hide();
2500#ifdef USEQPE 2500#ifdef USEQPE
2501 Global::hideInputMethod(); 2501 Global::hideInputMethod();
2502#endif 2502#endif
2503 m_fontBar->hide(); 2503 m_fontBar->hide();
2504 //showNormal(); 2504 //showNormal();
2505 showFullScreen(); 2505 showFullScreen();
2506 } 2506 }
2507 else 2507 else
2508 { 2508 {
2509 //qDebug("him"); 2509 //qDebug("him");
2510#ifdef USEQPE 2510#ifdef USEQPE
2511 Global::hideInputMethod(); 2511 Global::hideInputMethod();
2512#endif 2512#endif
2513 //qDebug("eb"); 2513 //qDebug("eb");
2514 menubar->show(); 2514 menubar->show();
2515 if (fileBar != NULL) fileBar->show(); 2515 if (fileBar != NULL) fileBar->show();
2516 if (viewBar != NULL) viewBar->show(); 2516 if (viewBar != NULL) viewBar->show();
2517 if (navBar != NULL) navBar->show(); 2517 if (navBar != NULL) navBar->show();
2518 if (markBar != NULL) markBar->show(); 2518 if (markBar != NULL) markBar->show();
2519 mb->show(); 2519 mb->show();
2520 if ( searchVisible ) 2520 if ( searchVisible )
2521 { 2521 {
2522#ifdef USEQPE 2522#ifdef USEQPE
2523 Global::showInputMethod(); 2523 Global::showInputMethod();
2524#endif 2524#endif
2525 searchBar->show(); 2525 searchBar->show();
2526 } 2526 }
2527 if ( regVisible ) 2527 if ( regVisible )
2528 { 2528 {
2529#ifdef USEQPE 2529#ifdef USEQPE
2530 Global::showInputMethod(); 2530 Global::showInputMethod();
2531#endif 2531#endif
2532 regBar->show(); 2532 regBar->show();
2533 } 2533 }
2534 if (m_fontVisible) m_fontBar->show(); 2534 if (m_fontVisible) m_fontBar->show();
2535 //qDebug("sn"); 2535 //qDebug("sn");
2536 showNormal(); 2536 showNormal();
2537 //qDebug("sm"); 2537 //qDebug("sm");
2538#ifdef USEQPE 2538#ifdef USEQPE
2539 showMaximized(); 2539 showMaximized();
2540#endif 2540#endif
2541 //setCentralWidget(reader); 2541 //setCentralWidget(reader);
2542 } 2542 }
2543 2543
2544// qDebug("uc"); 2544// qDebug("uc");
2545 updateCaption(); 2545 updateCaption();
2546// qDebug("rw"); 2546// qDebug("rw");
2547 editorStack->raiseWidget( reader ); 2547 editorStack->raiseWidget( reader );
2548// qDebug("sf"); 2548// qDebug("sf");
2549 reader->setFocus(); 2549 reader->setFocus();
2550 reader->refresh(); 2550 reader->refresh();
2551} 2551}
2552/* 2552/*
2553void QTReaderApp::save() 2553void QTReaderApp::save()
2554{ 2554{
2555 if ( !doc ) 2555 if ( !doc )
2556 return; 2556 return;
2557 if ( !editor->edited() ) 2557 if ( !editor->edited() )
2558 return; 2558 return;
2559 2559
2560 QString rt = editor->text(); 2560 QString rt = editor->text();
2561 QString pt = rt; 2561 QString pt = rt;
2562 2562
2563 if ( doc->name().isEmpty() ) { 2563 if ( doc->name().isEmpty() ) {
2564 unsigned ispace = pt.find( ' ' ); 2564 unsigned ispace = pt.find( ' ' );
2565 unsigned ienter = pt.find( '\n' ); 2565 unsigned ienter = pt.find( '\n' );
2566 int i = (ispace < ienter) ? ispace : ienter; 2566 int i = (ispace < ienter) ? ispace : ienter;
2567 QString docname; 2567 QString docname;
2568 if ( i == -1 ) { 2568 if ( i == -1 ) {
2569 if ( pt.isEmpty() ) 2569 if ( pt.isEmpty() )
2570 docname = "Empty Text"; 2570 docname = "Empty Text";
2571 else 2571 else
2572 docname = pt; 2572 docname = pt;
2573 } else { 2573 } else {
2574 docname = pt.left( i ); 2574 docname = pt.left( i );
2575 } 2575 }
2576 doc->setName(docname); 2576 doc->setName(docname);
2577 } 2577 }
2578 FileManager fm; 2578 FileManager fm;
2579 fm.saveFile( *doc, rt ); 2579 fm.saveFile( *doc, rt );
2580} 2580}
2581*/ 2581*/
2582 2582
2583void QTReaderApp::clear() 2583void QTReaderApp::clear()
2584{ 2584{
2585// if (doc != 0) 2585// if (doc != 0)
2586// { 2586// {
2587// QMessageBox::information(this, PROGNAME, "Deleting doc", 1); 2587// QMessageBox::information(this, PROGNAME, "Deleting doc", 1);
2588 //delete doc; 2588 //delete doc;
2589// QMessageBox::information(this, PROGNAME, "Deleted doc", 1); 2589// QMessageBox::information(this, PROGNAME, "Deleted doc", 1);
2590 //doc = 0; 2590 //doc = 0;
2591 // } 2591 // }
2592 reader->clear(); 2592 reader->clear();
2593} 2593}
2594 2594
2595void QTReaderApp::updateCaption() 2595void QTReaderApp::updateCaption()
2596{ 2596{
2597// if ( !doc ) 2597// if ( !doc )
2598 //setCaption( tr("QTReader") ); 2598 //setCaption( tr("QTReader") );
2599// else { 2599// else {
2600 //QString s = doc->name(); 2600 //QString s = doc->name();
2601 //if ( s.isEmpty() ) 2601 //if ( s.isEmpty() )
2602 // s = tr( "Unnamed" ); 2602 // s = tr( "Unnamed" );
2603 setCaption( reader->m_string + " - " + tr("Reader") ); 2603 setCaption( reader->m_string + " - " + tr("Reader") );
2604// } 2604// }
2605} 2605}
2606 2606
2607void QTReaderApp::setDocument(const QString& fileref) 2607void QTReaderApp::setDocument(const QString& fileref)
2608{ 2608{
2609 bFromDocView = TRUE; 2609 bFromDocView = TRUE;
2610//QMessageBox::information(0, "setDocument", fileref); 2610//QMessageBox::information(0, "setDocument", fileref);
2611 openFile(fileref); 2611 openFile(fileref);
2612// showEditTools(); 2612// showEditTools();
2613} 2613}
2614 2614
2615void QTReaderApp::closeEvent( QCloseEvent *e ) 2615void QTReaderApp::closeEvent( QCloseEvent *e )
2616{ 2616{
2617// qDebug("Close event"); 2617// qDebug("Close event");
2618 if (m_fullscreen) 2618 if (m_fullscreen)
2619 { 2619 {
2620 m_fullscreen = false; 2620 m_fullscreen = false;
2621 showEditTools(); 2621 showEditTools();
2622 e->accept(); 2622 e->accept();
2623 } 2623 }
2624 else if (m_dontSave) 2624 else if (m_dontSave)
2625 { 2625 {
2626 e->accept(); 2626 e->accept();
2627 } 2627 }
2628 else 2628 else
2629 { 2629 {
2630 if (editorStack->visibleWidget() == reader) 2630 if (editorStack->visibleWidget() == reader)
2631 { 2631 {
2632 if ((m_escapeTarget != cesNone) && m_bcloseDisabled) 2632 if ((m_escapeTarget != cesNone) && m_bcloseDisabled)
2633 { 2633 {
2634 //qDebug("Close disabled"); 2634 //qDebug("Close disabled");
2635 m_bcloseDisabled = false; 2635 m_bcloseDisabled = false;
2636 e->ignore(); 2636 e->ignore();
2637 } 2637 }
2638 else 2638 else
2639 { 2639 {
2640 if (m_fontVisible) 2640 if (m_fontVisible)
2641 { 2641 {
2642 m_fontBar->hide(); 2642 m_fontBar->hide();
2643 m_fontVisible = false; 2643 m_fontVisible = false;
2644 } 2644 }
2645 if (regVisible) 2645 if (regVisible)
2646 { 2646 {
2647 regBar->hide(); 2647 regBar->hide();
2648#ifdef USEQPE 2648#ifdef USEQPE
2649 Global::hideInputMethod(); 2649 Global::hideInputMethod();
2650#endif 2650#endif
2651 regVisible = false; 2651 regVisible = false;
2652 return; 2652 return;
2653 } 2653 }
2654 if (searchVisible) 2654 if (searchVisible)
2655 { 2655 {
2656 searchBar->hide(); 2656 searchBar->hide();
2657#ifdef USEQPE 2657#ifdef USEQPE
2658 Global::hideInputMethod(); 2658 Global::hideInputMethod();
2659#endif 2659#endif
2660 searchVisible = false; 2660 searchVisible = false;
2661 return; 2661 return;
2662 } 2662 }
2663 if (m_fBkmksChanged && pBkmklist != NULL) 2663 if (m_fBkmksChanged && pBkmklist != NULL)
2664 { 2664 {
2665 if (QMessageBox::warning(this, PROGNAME, "Save bookmarks?", "Save", "Don't bother") == 0) 2665 if (QMessageBox::warning(this, PROGNAME, "Save bookmarks?", "Save", "Don't bother") == 0)
2666 savebkmks(); 2666 savebkmks();
2667 delete pBkmklist; 2667 delete pBkmklist;
2668 pBkmklist = NULL; 2668 pBkmklist = NULL;
2669 m_fBkmksChanged = false; 2669 m_fBkmksChanged = false;
2670 } 2670 }
2671 bFromDocView = FALSE; 2671 bFromDocView = FALSE;
2672 updatefileinfo(); 2672 updatefileinfo();
2673 saveprefs(); 2673 saveprefs();
2674 e->accept(); 2674 e->accept();
2675 } 2675 }
2676 } 2676 }
2677 else 2677 else
2678 { 2678 {
2679 showEditTools(); 2679 showEditTools();
2680 m_disableesckey = true; 2680 m_disableesckey = true;
2681 } 2681 }
2682 } 2682 }
2683} 2683}
2684 2684
2685void QTReaderApp::do_gotomark() 2685void QTReaderApp::do_gotomark()
2686{ 2686{
2687 m_nBkmkAction = cGotoBkmk; 2687 m_nBkmkAction = cGotoBkmk;
2688 if (!listbkmk(pBkmklist)) 2688 if (!listbkmk(pBkmklist))
2689 QMessageBox::information(this, PROGNAME, "No bookmarks in memory"); 2689 QMessageBox::information(this, PROGNAME, "No bookmarks in memory");
2690} 2690}
2691 2691
2692void QTReaderApp::do_delmark() 2692void QTReaderApp::do_delmark()
2693{ 2693{
2694 m_nBkmkAction = cDelBkmk; 2694 m_nBkmkAction = cDelBkmk;
2695 if (!listbkmk(pBkmklist)) 2695 if (!listbkmk(pBkmklist))
2696 QMessageBox::information(this, PROGNAME, "No bookmarks in memory"); 2696 QMessageBox::information(this, PROGNAME, "No bookmarks in memory");
2697} 2697}
2698 2698
2699bool QTReaderApp::listbkmk(CList<Bkmk>* plist, const QString& _lab) 2699bool QTReaderApp::listbkmk(CList<Bkmk>* plist, const QString& _lab)
2700{ 2700{
2701 bkmkselector->clear(); 2701 bkmkselector->clear();
2702 if (_lab.isEmpty()) 2702 if (_lab.isEmpty())
2703 bkmkselector->setText("Cancel"); 2703 bkmkselector->setText("Cancel");
2704 else 2704 else
2705 bkmkselector->setText(_lab); 2705 bkmkselector->setText(_lab);
2706 int cnt = 0; 2706 int cnt = 0;
2707 if (plist != NULL) 2707 if (plist != NULL)
2708 { 2708 {
2709 for (CList<Bkmk>::iterator i = plist->begin(); i != plist->end(); i++) 2709 for (CList<Bkmk>::iterator i = plist->begin(); i != plist->end(); i++)
2710 { 2710 {
2711#ifdef _UNICODE 2711#ifdef _UNICODE
2712 // qDebug("Item:%s", (const char*)toQString(i->name())); 2712 // qDebug("Item:%s", (const char*)toQString(i->name()));
2713 bkmkselector->insertItem(toQString(i->name())); 2713 bkmkselector->insertItem(toQString(i->name()));
2714#else 2714#else
2715 bkmkselector->insertItem(i->name()); 2715 bkmkselector->insertItem(i->name());
2716#endif 2716#endif
2717 cnt++; 2717 cnt++;
2718 } 2718 }
2719 } 2719 }
2720 if (cnt > 0) 2720 if (cnt > 0)
2721 { 2721 {
2722 hidetoolbars(); 2722 hidetoolbars();
2723 editorStack->raiseWidget( bkmkselector ); 2723 editorStack->raiseWidget( bkmkselector );
2724 return true; 2724 return true;
2725 } 2725 }
2726 else 2726 else
2727 return false; 2727 return false;
2728} 2728}
2729 2729
2730void QTReaderApp::do_autogen() 2730void QTReaderApp::do_autogen()
2731{ 2731{
2732 m_nRegAction = cAutoGen; 2732 m_nRegAction = cAutoGen;
2733 regEdit->setText(m_autogenstr); 2733 regEdit->setText(m_autogenstr);
2734 do_regedit(); 2734 do_regedit();
2735} 2735}
2736 2736
2737void QTReaderApp::do_regedit() 2737void QTReaderApp::do_regedit()
2738{ 2738{
2739// fileBar->hide(); 2739// fileBar->hide();
2740 reader->bDoUpdates = false; 2740 reader->bDoUpdates = false;
2741// qDebug("Showing regbar"); 2741// qDebug("Showing regbar");
2742 regBar->show(); 2742 regBar->show();
2743// qDebug("Showing kbd"); 2743// qDebug("Showing kbd");
2744#ifdef USEQPE 2744#ifdef USEQPE
2745 Global::showInputMethod(); 2745 Global::showInputMethod();
2746#endif 2746#endif
2747 regVisible = true; 2747 regVisible = true;
2748 regEdit->setFocus(); 2748 regEdit->setFocus();
2749// qApp->processEvents(); 2749// qApp->processEvents();
2750 reader->bDoUpdates = true; 2750 reader->bDoUpdates = true;
2751 reader->update(); 2751 reader->update();
2752} 2752}
2753 2753
2754bool QTReaderApp::openfrombkmk(Bkmk* bk) 2754bool QTReaderApp::openfrombkmk(Bkmk* bk)
2755{ 2755{
2756 QString fn = toQString( 2756 QString fn = toQString(
2757 CFiledata(bk->anno()).name() 2757 CFiledata(bk->anno()).name()
2758 ); 2758 );
2759 //qDebug("fileinfo"); 2759 //qDebug("fileinfo");
2760 if (!fn.isEmpty() && QFileInfo(fn).isFile()) 2760 if (!fn.isEmpty() && QFileInfo(fn).isFile())
2761 { 2761 {
2762 //qDebug("Opening"); 2762 //qDebug("Opening");
2763 openFile(fn); 2763 openFile(fn);
2764 struct stat fnstat; 2764 struct stat fnstat;
2765 stat((const char *)reader->m_lastfile, &fnstat); 2765 stat((const char *)reader->m_lastfile, &fnstat);
2766 2766
2767 if (CFiledata(bk->anno()).date() 2767 if (CFiledata(bk->anno()).date()
2768 != fnstat.st_mtime) 2768 != fnstat.st_mtime)
2769 { 2769 {
2770 CFiledata fd(bk->anno()); 2770 CFiledata fd(bk->anno());
2771 fd.setdate(fnstat.st_mtime); 2771 fd.setdate(fnstat.st_mtime);
2772 bk->value(0); 2772 bk->value(0);
2773 } 2773 }
2774 else 2774 else
2775 { 2775 {
2776 unsigned short svlen = bk->filedatalen(); 2776 unsigned short svlen = bk->filedatalen();
2777 unsigned char* svdata = bk->filedata(); 2777 unsigned char* svdata = bk->filedata();
2778 reader->putSaveData(svdata, svlen); 2778 reader->putSaveData(svdata, svlen);
2779 // setstate(svdata, svlen); 2779 // setstate(svdata, svlen);
2780 if (svlen != 0) 2780 if (svlen != 0)
2781 { 2781 {
2782 QMessageBox::warning(this, PROGNAME, "Not all file data used\nNew version?"); 2782 QMessageBox::warning(this, PROGNAME, "Not all file data used\nNew version?");
2783 } 2783 }
2784 // qDebug("updating"); 2784 // qDebug("updating");
2785 // showEditTools(); 2785 // showEditTools();
2786 reader->locate(bk->value()); 2786 reader->locate(bk->value());
2787 } 2787 }
2788 return true; 2788 return true;
2789 } 2789 }
2790 else 2790 else
2791 { 2791 {
2792 return false; 2792 return false;
2793 } 2793 }
2794} 2794}
2795 2795
2796void QTReaderApp::gotobkmk(int ind) 2796void QTReaderApp::gotobkmk(int ind)
2797{ 2797{
2798 showEditTools(); 2798 showEditTools();
2799 switch (m_nBkmkAction) 2799 switch (m_nBkmkAction)
2800 { 2800 {
2801 case cOpenFile: 2801 case cOpenFile:
2802 { 2802 {
2803 // qApp->processEvents(); 2803 // qApp->processEvents();
2804 if (!openfrombkmk((*pOpenlist)[ind])) 2804 if (!openfrombkmk((*pOpenlist)[ind]))
2805 { 2805 {
2806 pOpenlist->erase(ind); 2806 pOpenlist->erase(ind);
2807 QMessageBox::information(this, PROGNAME, "Can't find file"); 2807 QMessageBox::information(this, PROGNAME, "Can't find file");
2808 } 2808 }
2809 } 2809 }
2810 break; 2810 break;
2811 case cGotoBkmk: 2811 case cGotoBkmk:
2812 reader->locate((*pBkmklist)[ind]->value()); 2812 reader->locate((*pBkmklist)[ind]->value());
2813 break; 2813 break;
2814 case cDelBkmk: 2814 case cDelBkmk:
2815 //// qDebug("Deleting:%s\n",(*pBkmklist)[ind]->name()); 2815 //// qDebug("Deleting:%s\n",(*pBkmklist)[ind]->name());
2816 pBkmklist->erase(ind); 2816 pBkmklist->erase(ind);
2817 m_fBkmksChanged = true; 2817 m_fBkmksChanged = true;
2818 // pBkmklist->sort(); 2818 // pBkmklist->sort();
2819 break; 2819 break;
2820 case cRmBkmkFile: 2820 case cRmBkmkFile:
2821 { 2821 {
2822#ifndef USEQPE 2822#ifndef USEQPE
2823 QDir d = QDir::home(); // "/" 2823 QDir d = QDir::home(); // "/"
2824 d.cd(APPDIR); 2824 d.cd(APPDIR);
2825 d.remove(bkmkselector->text(ind)); 2825 d.remove(bkmkselector->text(ind));
2826#else /* USEQPE */ 2826#else /* USEQPE */
2827 unlink((const char *)Global::applicationFileName(APPDIR,bkmkselector->text(ind))); 2827 unlink((const char *)Global::applicationFileName(APPDIR,bkmkselector->text(ind)));
2828#endif /* USEQPE */ 2828#endif /* USEQPE */
2829 } 2829 }
2830 break; 2830 break;
2831 case cLdConfig: 2831 case cLdConfig:
2832 readconfig(bkmkselector->text(ind), false); 2832 readconfig(bkmkselector->text(ind), false);
2833 break; 2833 break;
2834 case cRmConfig: 2834 case cRmConfig:
2835 { 2835 {
2836#ifndef USEQPE 2836#ifndef USEQPE
2837 QDir d = QDir::home(); // "/" 2837 QDir d = QDir::home(); // "/"
2838 d.cd(APPDIR "/configs"); 2838 d.cd(APPDIR "/configs");
2839 d.remove(bkmkselector->text(ind)); 2839 d.remove(bkmkselector->text(ind));
2840#else /* USEQPE */ 2840#else /* USEQPE */
2841 unlink((const char *)Global::applicationFileName(APPDIR "/configs",bkmkselector->text(ind))); 2841 unlink((const char *)Global::applicationFileName(APPDIR "/configs",bkmkselector->text(ind)));
2842#endif /* USEQPE */ 2842#endif /* USEQPE */
2843 } 2843 }
2844 break; 2844 break;
2845 case cExportLinks: 2845 case cExportLinks:
2846 { 2846 {
2847#ifndef USEQPE 2847#ifndef USEQPE
2848 QDir d = QDir::home(); // "/" 2848 QDir d = QDir::home(); // "/"
2849 d.cd(APPDIR "/urls"); 2849 d.cd(APPDIR "/urls");
2850 QFileInfo fi(d, bkmkselector->text(ind)); 2850 QFileInfo fi(d, bkmkselector->text(ind));
2851 if (fi.exists()) 2851 if (fi.exists())
2852 { 2852 {
2853 QString outfile( QFileDialog::getSaveFileName( QString::null, QString::null, this ) ); 2853 QString outfile( QFileDialog::getSaveFileName( QString::null, QString::null, this ) );
2854 if (!outfile.isEmpty()) 2854 if (!outfile.isEmpty())
2855 { 2855 {
2856 FILE* fout = fopen((const char *)outfile, "w"); 2856 FILE* fout = fopen((const char *)outfile, "w");
2857 if (fout != NULL) 2857 if (fout != NULL)
2858 { 2858 {
2859 FILE* fin = fopen((const char *)fi.absFilePath(), "r"); 2859 FILE* fin = fopen((const char *)fi.absFilePath(), "r");
2860 if (fin != NULL) 2860 if (fin != NULL)
2861 { 2861 {
2862 fprintf(fout, "<html><body>\n"); 2862 fprintf(fout, "<html><body>\n");
2863 int ch = 0; 2863 int ch = 0;
2864 while ((ch = fgetc(fin)) != EOF) 2864 while ((ch = fgetc(fin)) != EOF)
2865 { 2865 {
2866 fputc(ch, fout); 2866 fputc(ch, fout);
2867 } 2867 }
2868 fclose(fin); 2868 fclose(fin);
2869 fprintf(fout, "</html></body>\n"); 2869 fprintf(fout, "</html></body>\n");
2870 d.remove(bkmkselector->text(ind)); 2870 d.remove(bkmkselector->text(ind));
2871 } 2871 }
2872 fclose(fout); 2872 fclose(fout);
2873 } 2873 }
2874 else 2874 else
2875 QMessageBox::information(this, PROGNAME, "Couldn't open output"); 2875 QMessageBox::information(this, PROGNAME, "Couldn't open output");
2876 } 2876 }
2877 } 2877 }
2878#else /* USEQPE */ 2878#else /* USEQPE */
2879 FILE* fin = fopen((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)), "r"); 2879 FILE* fin = fopen((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)), "r");
2880 if (fin != NULL) 2880 if (fin != NULL)
2881 { 2881 {
2882 bool allok = false; 2882 bool allok = false;
2883 fileBrowser* fb = new fileBrowser(true, this,"OpieReader",!m_bFloatingDialog, 0, "*", QString::null); 2883 fileBrowser* fb = new fileBrowser(true, this,"OpieReader",!m_bFloatingDialog, 0, "*", QString::null);
2884 if (fb->exec()) 2884 if (fb->exec())
2885 { 2885 {
2886 QString outfile = fb->getCurrentFile(); 2886 QString outfile = fb->getCurrentFile();
2887 FILE* fout = fopen((const char *)outfile, "w"); 2887 FILE* fout = fopen((const char *)outfile, "w");
2888 if (fout != NULL) 2888 if (fout != NULL)
2889 { 2889 {
2890 fprintf(fout, "<html><body>\n"); 2890 fprintf(fout, "<html><body>\n");
2891 int ch = 0; 2891 int ch = 0;
2892 while ((ch = fgetc(fin)) != EOF) 2892 while ((ch = fgetc(fin)) != EOF)
2893 { 2893 {
2894 fputc(ch, fout); 2894 fputc(ch, fout);
2895 } 2895 }
2896 fprintf(fout, "</html></body>\n"); 2896 fprintf(fout, "</html></body>\n");
2897 fclose(fout); 2897 fclose(fout);
2898 allok = true; 2898 allok = true;
2899 } 2899 }
2900 else 2900 else
2901 QMessageBox::information(this, PROGNAME, "Couldn't open output"); 2901 QMessageBox::information(this, PROGNAME, "Couldn't open output");
2902 } 2902 }
2903 delete fb; 2903 delete fb;
2904 fclose(fin); 2904 fclose(fin);
2905 if (allok) unlink((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind))); 2905 if (allok) unlink((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)));
2906 } 2906 }
2907 else 2907 else
2908 { 2908 {
2909 QMessageBox::information(this, PROGNAME, "Couldn't open input"); 2909 QMessageBox::information(this, PROGNAME, "Couldn't open input");
2910 } 2910 }
2911 2911
2912/* 2912/*
2913 CFileSelector *f = new CFileSelector("text/html", this, NULL, !m_bFloatingDialog, TRUE, TRUE ); 2913 CFileSelector *f = new CFileSelector("text/html", this, NULL, !m_bFloatingDialog, TRUE, TRUE );
2914 int ret = f->exec(); 2914 int ret = f->exec();
2915 qDebug("Return:%d", ret); 2915 qDebug("Return:%d", ret);
2916 DocLnk* doc = f->getDoc(); 2916 DocLnk* doc = f->getDoc();
2917 if (doc != NULL) 2917 if (doc != NULL)
2918 { 2918 {
2919 FILE* fin = fopen((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)), "r"); 2919 FILE* fin = fopen((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)), "r");
2920 QString rt; 2920 QString rt;
2921 rt = "<html><body>\n"; 2921 rt = "<html><body>\n";
2922 int ch = 0; 2922 int ch = 0;
2923 while ((ch = fgetc(fin)) != EOF) 2923 while ((ch = fgetc(fin)) != EOF)
2924 { 2924 {
2925 rt += (char)ch; 2925 rt += (char)ch;
2926 } 2926 }
2927 fclose(fin); 2927 fclose(fin);
2928 rt += "</html></body>\n"; 2928 rt += "</html></body>\n";
2929 if ( doc->name().isEmpty() ) 2929 if ( doc->name().isEmpty() )
2930 { 2930 {
2931 doc->setName(bkmkselector->text(ind)); 2931 doc->setName(bkmkselector->text(ind));
2932 } 2932 }
2933 FileManager fm; 2933 FileManager fm;
2934 fm.saveFile( *doc, rt ); 2934 fm.saveFile( *doc, rt );
2935 qDebug("YES"); 2935 qDebug("YES");
2936 } 2936 }
2937 else 2937 else
2938 { 2938 {
2939 qDebug("NO"); 2939 qDebug("NO");
2940 } 2940 }
2941 delete f; 2941 delete f;
2942*/ 2942*/
2943 2943
2944#endif /* USEQPE */ 2944#endif /* USEQPE */
2945 } 2945 }
2946 break; 2946 break;
2947 } 2947 }
2948} 2948}
2949 2949
2950void QTReaderApp::cancelbkmk() 2950void QTReaderApp::cancelbkmk()
2951{ 2951{
2952 if (m_nBkmkAction == cOpenFile) 2952 if (m_nBkmkAction == cOpenFile)
2953 { 2953 {
2954 QString fn = usefilebrowser(); 2954 QString fn = usefilebrowser();
2955 if (!fn.isEmpty() && QFileInfo(fn).isFile()) openFile(fn); 2955 if (!fn.isEmpty() && QFileInfo(fn).isFile()) openFile(fn);
2956 } 2956 }
2957 showEditTools(); 2957 showEditTools();
2958} 2958}
2959 2959
2960void QTReaderApp::jump() 2960void QTReaderApp::jump()
2961{ 2961{
2962 m_nRegAction = cJump; 2962 m_nRegAction = cJump;
2963 char lcn[20]; 2963 char lcn[20];
2964 sprintf(lcn, "%lu", reader->pagelocate()); 2964 sprintf(lcn, "%lu", reader->pagelocate());
2965 regEdit->setText(lcn); 2965 regEdit->setText(lcn);
2966 do_regedit(); 2966 do_regedit();
2967} 2967}
2968 2968
2969void QTReaderApp::do_jump(const QString& lcn) 2969void QTReaderApp::do_jump(const QString& lcn)
2970{ 2970{
2971 bool ok; 2971 bool ok;
2972 unsigned long ulcn = lcn.toULong(&ok); 2972 unsigned long ulcn = lcn.toULong(&ok);
2973 if (ok) 2973 if (ok)
2974 reader->locate(ulcn); 2974 reader->locate(ulcn);
2975 else 2975 else
2976 QMessageBox::information(this, PROGNAME, "Must be a number"); 2976 QMessageBox::information(this, PROGNAME, "Must be a number");
2977} 2977}
2978 2978
2979void QTReaderApp::do_regaction() 2979void QTReaderApp::do_regaction()
2980{ 2980{
2981 reader->bDoUpdates = false; 2981 reader->bDoUpdates = false;
2982 regBar->hide(); 2982 regBar->hide();
2983#ifdef USEQPE 2983#ifdef USEQPE
2984 Global::hideInputMethod(); 2984 Global::hideInputMethod();
2985#endif 2985#endif
2986 regVisible = false; 2986 regVisible = false;
2987 switch(m_nRegAction) 2987 switch(m_nRegAction)
2988 { 2988 {
2989 case cAutoGen: 2989 case cAutoGen:
2990 do_autogen(regEdit->text()); 2990 do_autogen(regEdit->text());
2991 break; 2991 break;
2992 case cAddBkmk: 2992 case cAddBkmk:
2993 do_addbkmk(regEdit->text()); 2993 do_addbkmk(regEdit->text());
2994 break; 2994 break;
2995 case cJump: 2995 case cJump:
2996 do_jump(regEdit->text()); 2996 do_jump(regEdit->text());
2997 break; 2997 break;
2998/* 2998/*
2999 case cMonoSpace: 2999 case cMonoSpace:
3000 do_mono(regEdit->text()); 3000 do_mono(regEdit->text());
3001 break; 3001 break;
3002*/ 3002*/
3003 case cSetTarget: 3003 case cSetTarget:
3004 do_settarget(regEdit->text()); 3004 do_settarget(regEdit->text());
3005 break; 3005 break;
3006#ifdef _SCROLLPIPE 3006#ifdef _SCROLLPIPE
3007 case cSetPipeTarget: 3007 case cSetPipeTarget:
3008 do_setpipetarget(regEdit->text()); 3008 do_setpipetarget(regEdit->text());
3009 break; 3009 break;
3010#endif 3010#endif
3011 case cSetConfigName: 3011 case cSetConfigName:
3012 // qDebug("Saving config"); 3012 // qDebug("Saving config");
3013 do_saveconfig(regEdit->text(), false); 3013 do_saveconfig(regEdit->text(), false);
3014 break; 3014 break;
3015 } 3015 }
3016// reader->restore(); 3016// reader->restore();
3017// fileBar->show(); 3017// fileBar->show();
3018 reader->setFocus(); 3018 reader->setFocus();
3019// qApp->processEvents(); 3019// qApp->processEvents();
3020 reader->bDoUpdates = true; 3020 reader->bDoUpdates = true;
3021 reader->update(); 3021 reader->update();
3022} 3022}
3023 3023
3024void QTReaderApp::do_settarget(const QString& _txt) 3024void QTReaderApp::do_settarget(const QString& _txt)
3025{ 3025{
3026 int ind = _txt.find('/'); 3026 int ind = _txt.find('/');
3027 if (ind == -1) 3027 if (ind == -1)
3028 { 3028 {
3029 m_targetapp = ""; 3029 m_targetapp = "";
3030 m_targetmsg = ""; 3030 m_targetmsg = "";
3031 QMessageBox::information(this, PROGNAME, "Format is\nappname/messagename"); 3031 QMessageBox::information(this, PROGNAME, "Format is\nappname/messagename");
3032 } 3032 }
3033 else 3033 else
3034 { 3034 {
3035 m_targetapp = _txt.left(ind); 3035 m_targetapp = _txt.left(ind);
3036 m_targetmsg = _txt.right(_txt.length()-ind-1); 3036 m_targetmsg = _txt.right(_txt.length()-ind-1);
3037 } 3037 }
3038} 3038}
3039 3039
3040void QTReaderApp::chooseencoding() 3040void QTReaderApp::chooseencoding()
3041{ 3041{
3042 m_fontSelector->clear(); 3042 m_fontSelector->clear();
3043 m_fontSelector->insertItem("Ascii"); 3043 m_fontSelector->insertItem("Ascii");
3044 m_fontSelector->insertItem("UTF-8"); 3044 m_fontSelector->insertItem("UTF-8");
3045 m_fontSelector->insertItem("UCS-2(BE)"); 3045 m_fontSelector->insertItem("UCS-2(BE)");
3046 m_fontSelector->insertItem("USC-2(LE)"); 3046 m_fontSelector->insertItem("USC-2(LE)");
3047 m_fontSelector->insertItem("Palm"); 3047 m_fontSelector->insertItem("Palm");
3048 for (unicodetable::iterator iter = unicodetable::begin(); iter != unicodetable::end(); iter++) 3048 for (unicodetable::iterator iter = unicodetable::begin(); iter != unicodetable::end(); iter++)
3049 { 3049 {
3050 m_fontSelector->insertItem(iter->mime); 3050 m_fontSelector->insertItem(iter->mime);
3051 } // delete the FontDatabase!!! 3051 } // delete the FontDatabase!!!
3052 m_fontSelector->setCurrentItem (reader->m_encd); 3052 m_fontSelector->setCurrentItem (reader->m_encd);
3053 m_fontAction = cChooseEncoding; 3053 m_fontAction = cChooseEncoding;
3054 m_fontBar->show(); 3054 m_fontBar->show();
3055 m_fontVisible = true; 3055 m_fontVisible = true;
3056} 3056}
3057 3057
3058void QTReaderApp::setfont() 3058void QTReaderApp::setfont()
3059{ 3059{
3060 m_fontSelector->clear(); 3060 m_fontSelector->clear();
3061 { 3061 {
3062#ifdef USEQPE 3062#ifdef USEQPE
3063 FontDatabase f; 3063 FontDatabase f;
3064#else 3064#else
3065 QFontDatabase f; 3065 QFontDatabase f;
3066#endif 3066#endif
3067 QStringList flist = f.families(); 3067 QStringList flist = f.families();
3068 m_fontSelector->insertStringList(flist); 3068 m_fontSelector->insertStringList(flist);
3069 } // delete the FontDatabase!!! 3069 } // delete the FontDatabase!!!
3070 3070
3071 for (int i = 1; i <= m_fontSelector->count(); i++) 3071 for (int i = 1; i <= m_fontSelector->count(); i++)
3072 { 3072 {
3073 if (m_fontSelector->text(i) == reader->m_fontname) 3073 if (m_fontSelector->text(i) == reader->m_fontname)
3074 { 3074 {
3075 m_fontSelector->setCurrentItem(i); 3075 m_fontSelector->setCurrentItem(i);
3076 break; 3076 break;
3077 } 3077 }
3078 } 3078 }
3079 m_fontAction = cChooseFont; 3079 m_fontAction = cChooseFont;
3080 m_fontBar->show(); 3080 m_fontBar->show();
3081 m_fontVisible = true; 3081 m_fontVisible = true;
3082} 3082}
3083 3083
3084void QTReaderApp::setfontHelper(const QString& lcn, int size) 3084void QTReaderApp::setfontHelper(const QString& lcn, int size)
3085{ 3085{
3086 if (size == 0) size = reader->m_fontControl.currentsize(); 3086 if (size == 0) size = reader->m_fontControl.currentsize();
3087 if (m_propogatefontchange) 3087 if (m_propogatefontchange)
3088 { 3088 {
3089 QFont f(lcn, 10); 3089 QFont f(lcn, 10);
3090 bkmkselector->setFont( f ); 3090 bkmkselector->setFont( f );
3091 regEdit->setFont( f ); 3091 regEdit->setFont( f );
3092 searchEdit->setFont( f ); 3092 searchEdit->setFont( f );
3093 m_annoWin->setFont( f ); 3093 m_annoWin->setFont( f );
3094 } 3094 }
3095 reader->m_fontname = lcn; 3095 reader->m_fontname = lcn;
3096 if (!reader->ChangeFont(size)) 3096 if (!reader->ChangeFont(size))
3097 { 3097 {
3098 reader->ChangeFont(size); 3098 reader->ChangeFont(size);
3099 } 3099 }
3100} 3100}
3101 3101
3102void QTReaderApp::do_setencoding(int i) 3102void QTReaderApp::do_setencoding(int i)
3103{ 3103{
3104// qDebug("setencoding:%d", i); 3104// qDebug("setencoding:%d", i);
3105 if (m_fontAction == cChooseEncoding) 3105 if (m_fontAction == cChooseEncoding)
3106 { 3106 {
3107 reader->setencoding(i); 3107 reader->setencoding(i);
3108 } 3108 }
3109 reader->refresh(); 3109 reader->refresh();
3110 m_fontBar->hide(); 3110 m_fontBar->hide();
3111 m_fontVisible = false; 3111 m_fontVisible = false;
3112// qDebug("showedit"); 3112// qDebug("showedit");
3113 if (reader->isVisible()) showEditTools(); 3113 if (reader->isVisible()) showEditTools();
3114// qDebug("showeditdone"); 3114// qDebug("showeditdone");
3115} 3115}
3116 3116
3117void QTReaderApp::do_setfont(const QString& lcn) 3117void QTReaderApp::do_setfont(const QString& lcn)
3118{ 3118{
3119 if (m_fontAction == cChooseFont) 3119 if (m_fontAction == cChooseFont)
3120 { 3120 {
3121 setfontHelper(lcn); 3121 setfontHelper(lcn);
3122 } 3122 }
3123 reader->refresh(); 3123 reader->refresh();
3124 m_fontBar->hide(); 3124 m_fontBar->hide();
3125 m_fontVisible = false; 3125 m_fontVisible = false;
3126// qDebug("showedit"); 3126// qDebug("showedit");
3127 //if (reader->isVisible()) 3127 //if (reader->isVisible())
3128 showEditTools(); 3128 showEditTools();
3129// qDebug("showeditdone"); 3129// qDebug("showeditdone");
3130} 3130}
3131 3131
3132void QTReaderApp::do_autogen(const QString& regText) 3132void QTReaderApp::do_autogen(const QString& regText)
3133{ 3133{
3134 unsigned long fs, ts; 3134 unsigned long fs, ts;
3135 reader->sizes(fs,ts); 3135 reader->sizes(fs,ts);
3136// // qDebug("Reg:%s\n", (const tchar*)(regEdit->text())); 3136// // qDebug("Reg:%s\n", (const tchar*)(regEdit->text()));
3137 m_autogenstr = regText; 3137 m_autogenstr = regText;
3138 QRegExp re(regText); 3138 QRegExp re(regText);
3139 CBuffer buff; 3139 CBuffer buff;
3140 if (pBkmklist != NULL) delete pBkmklist; 3140 if (pBkmklist != NULL) delete pBkmklist;
3141 pBkmklist = new CList<Bkmk>; 3141 pBkmklist = new CList<Bkmk>;
3142 m_fBkmksChanged = true; 3142 m_fBkmksChanged = true;
3143 3143
3144 pbar->setGeometry(regBar->x(),regBar->y(),regBar->width(), regBar->height()); 3144 pbar->setGeometry(regBar->x(),regBar->y(),regBar->width(), regBar->height());
3145 pbar->show(); 3145 pbar->show();
3146 pbar->raise(); 3146 pbar->raise();
3147 pbar->reset(); 3147 pbar->reset();
3148 reader->update(); 3148 reader->update();
3149 qApp->processEvents(); 3149 qApp->processEvents();
3150 reader->setFocus(); 3150 reader->setFocus();
3151 reader->jumpto(0); 3151 reader->jumpto(0);
3152 int lastpc = 0; 3152 int lastpc = 0;
3153 int i = 0; 3153 int i = 0;
3154 while (i >= 0) 3154 while (i >= 0)
3155 { 3155 {
3156 unsigned int lcn = reader->locate(); 3156 unsigned int lcn = reader->locate();
3157 int pc = (100*lcn)/ts; 3157 int pc = (100*lcn)/ts;
3158 if (pc != lastpc) 3158 if (pc != lastpc)
3159 { 3159 {
3160 pbar->setProgress(pc); 3160 pbar->setProgress(pc);
3161 qApp->processEvents(); 3161 qApp->processEvents();
3162 if (reader->locate() != lcn) reader->jumpto(lcn); 3162 if (reader->locate() != lcn) reader->jumpto(lcn);
3163 reader->setFocus(); 3163 reader->setFocus();
3164 lastpc = pc; 3164 lastpc = pc;
3165 } 3165 }
3166 i = reader->buffdoc.getpara(buff); 3166 i = reader->buffdoc.getpara(buff);
3167#ifdef _UNICODE 3167#ifdef _UNICODE
3168 if (re.match(toQString(buff.data())) != -1) 3168 if (re.match(toQString(buff.data())) != -1)
3169#else 3169#else
3170 if (re.match(buff.data()) != -1) 3170 if (re.match(buff.data()) != -1)
3171#endif 3171#endif
3172 pBkmklist->push_back(Bkmk(buff.data(), NULL, lcn)); 3172 pBkmklist->push_back(Bkmk(buff.data(), NULL, lcn));
3173 } 3173 }
3174 pBkmklist->sort(); 3174 pBkmklist->sort();
3175 pbar->setProgress(100); 3175 pbar->setProgress(100);
3176 qApp->processEvents(); 3176 qApp->processEvents();
3177 pbar->hide(); 3177 pbar->hide();
3178 reader->refresh(); 3178 reader->refresh();
3179} 3179}
3180 3180
3181void QTReaderApp::saveprefs() 3181void QTReaderApp::saveprefs()
3182{ 3182{
3183// qDebug("saveprefs"); 3183// qDebug("saveprefs");
3184// reader->saveprefs("uqtreader"); 3184// reader->saveprefs("uqtreader");
3185// if (!m_loadedconfig) 3185// if (!m_loadedconfig)
3186 do_saveconfig( APPDIR, true ); 3186 do_saveconfig( APPDIR, true );
3187 3187
3188/* 3188/*
3189 Config config( APPDIR ); 3189 Config config( APPDIR );
3190 config.setGroup( "View" ); 3190 config.setGroup( "View" );
3191 3191
3192 reader->m_lastposn = reader->pagelocate(); 3192 reader->m_lastposn = reader->pagelocate();
3193 3193
3194 config.writeEntry("FloatDialogs", m_bFloatingDialog); 3194 config.writeEntry("FloatDialogs", m_bFloatingDialog);
3195 config.writeEntry( "StripCr", reader->bstripcr ); 3195 config.writeEntry( "StripCr", reader->bstripcr );
3196 config.writeEntry( "AutoFmt", reader->bautofmt ); 3196 config.writeEntry( "AutoFmt", reader->bautofmt );
3197 config.writeEntry( "TextFmt", reader->btextfmt ); 3197 config.writeEntry( "TextFmt", reader->btextfmt );
3198 config.writeEntry( "StripHtml", reader->bstriphtml ); 3198 config.writeEntry( "StripHtml", reader->bstriphtml );
3199 config.writeEntry( "Dehyphen", reader->bdehyphen ); 3199 config.writeEntry( "Dehyphen", reader->bdehyphen );
3200 config.writeEntry( "Depluck", reader->bdepluck ); 3200 config.writeEntry( "Depluck", reader->bdepluck );
3201 config.writeEntry( "Dejpluck", reader->bdejpluck ); 3201 config.writeEntry( "Dejpluck", reader->bdejpluck );
3202 config.writeEntry( "OneSpace", reader->bonespace ); 3202 config.writeEntry( "OneSpace", reader->bonespace );
3203 config.writeEntry( "Unindent", reader->bunindent ); 3203 config.writeEntry( "Unindent", reader->bunindent );
3204 config.writeEntry( "Repara", reader->brepara ); 3204 config.writeEntry( "Repara", reader->brepara );
3205 config.writeEntry( "DoubleSpace", reader->bdblspce ); 3205 config.writeEntry( "DoubleSpace", reader->bdblspce );
3206 config.writeEntry( "Indent", reader->bindenter ); 3206 config.writeEntry( "Indent", reader->bindenter );
3207 config.writeEntry( "FontSize", (int)(reader->m_fontControl.currentsize()) ); 3207 config.writeEntry( "FontSize", (int)(reader->m_fontControl.currentsize()) );
3208 config.writeEntry( "ScrollDelay", reader->m_delay); 3208 config.writeEntry( "ScrollDelay", reader->m_delay);
3209 config.writeEntry( "LastFile", reader->m_lastfile ); 3209 config.writeEntry( "LastFile", reader->m_lastfile );
3210 config.writeEntry( "LastPosn", (int)(reader->pagelocate()) ); 3210 config.writeEntry( "LastPosn", (int)(reader->pagelocate()) );
3211 config.writeEntry( "PageMode", reader->m_bpagemode ); 3211 config.writeEntry( "PageMode", reader->m_bpagemode );
3212 config.writeEntry( "MonoSpaced", reader->m_bMonoSpaced ); 3212 config.writeEntry( "MonoSpaced", reader->m_bMonoSpaced );
3213 config.writeEntry( "SwapMouse", reader->m_swapmouse); 3213 config.writeEntry( "SwapMouse", reader->m_swapmouse);
3214 config.writeEntry( "Fontname", reader->m_fontname ); 3214 config.writeEntry( "Fontname", reader->m_fontname );
3215 config.writeEntry( "Encoding", reader->m_encd ); 3215 config.writeEntry( "Encoding", reader->m_encd );
3216 config.writeEntry( "CharSpacing", reader->m_charpc ); 3216 config.writeEntry( "CharSpacing", reader->m_charpc );
3217 config.writeEntry( "Overlap", (int)(reader->m_overlap) ); 3217 config.writeEntry( "Overlap", (int)(reader->m_overlap) );
3218 config.writeEntry( "Margin", (int)reader->m_border ); 3218 config.writeEntry( "Margin", (int)reader->m_border );
3219 config.writeEntry( "TargetApp", m_targetapp ); 3219 config.writeEntry( "TargetApp", m_targetapp );
3220 config.writeEntry( "TargetMsg", m_targetmsg ); 3220 config.writeEntry( "TargetMsg", m_targetmsg );
3221#ifdef _SCROLLPIPE 3221#ifdef _SCROLLPIPE
3222 config.writeEntry( "PipeTarget", reader->m_pipetarget ); 3222 config.writeEntry( "PipeTarget", reader->m_pipetarget );
3223 config.writeEntry( "PauseAfterPara", reader->m_pauseAfterEachPara ); 3223 config.writeEntry( "PauseAfterPara", reader->m_pauseAfterEachPara );
3224#endif 3224#endif
3225 config.writeEntry( "TwoTouch", m_twoTouch ); 3225 config.writeEntry( "TwoTouch", m_twoTouch );
3226 config.writeEntry( "Annotation", m_doAnnotation); 3226 config.writeEntry( "Annotation", m_doAnnotation);
3227 config.writeEntry( "Dictionary", m_doDictionary); 3227 config.writeEntry( "Dictionary", m_doDictionary);
3228 config.writeEntry( "Clipboard", m_doClipboard); 3228 config.writeEntry( "Clipboard", m_doClipboard);
3229 config.writeEntry( "SpaceTarget", m_spaceTarget); 3229 config.writeEntry( "SpaceTarget", m_spaceTarget);
3230 config.writeEntry( "EscapeTarget", m_escapeTarget); 3230 config.writeEntry( "EscapeTarget", m_escapeTarget);
3231 config.writeEntry( "ReturnTarget", m_returnTarget); 3231 config.writeEntry( "ReturnTarget", m_returnTarget);
3232 config.writeEntry( "LeftTarget", m_leftTarget); 3232 config.writeEntry( "LeftTarget", m_leftTarget);
3233 config.writeEntry( "RightTarget", m_rightTarget); 3233 config.writeEntry( "RightTarget", m_rightTarget);
3234 config.writeEntry( "UpTarget", m_upTarget); 3234 config.writeEntry( "UpTarget", m_upTarget);
3235 config.writeEntry( "DownTarget", m_downTarget); 3235 config.writeEntry( "DownTarget", m_downTarget);
3236 config.writeEntry("LeftScroll", m_leftScroll); 3236 config.writeEntry("LeftScroll", m_leftScroll);
3237 config.writeEntry("RightScroll", m_rightScroll); 3237 config.writeEntry("RightScroll", m_rightScroll);
3238 config.writeEntry("UpScroll", m_upScroll); 3238 config.writeEntry("UpScroll", m_upScroll);
3239 config.writeEntry("DownScroll", m_downScroll); 3239 config.writeEntry("DownScroll", m_downScroll);
3240#ifdef REPALM 3240#ifdef REPALM
3241 config.writeEntry( "Repalm", reader->brepalm ); 3241 config.writeEntry( "Repalm", reader->brepalm );
3242#endif 3242#endif
3243 config.writeEntry( "Remap", reader->bremap ); 3243 config.writeEntry( "Remap", reader->bremap );
3244 config.writeEntry( "Peanut", reader->bpeanut ); 3244 config.writeEntry( "Peanut", reader->bpeanut );
3245 config.writeEntry( "MakeBold", reader->bmakebold ); 3245 config.writeEntry( "MakeBold", reader->bmakebold );
3246 config.writeEntry( "Continuous", reader->m_continuousDocument ); 3246 config.writeEntry( "Continuous", reader->m_continuousDocument );
3247 config.writeEntry( "FullJust", reader->bfulljust ); 3247 config.writeEntry( "FullJust", reader->bfulljust );
3248 config.writeEntry( "ExtraSpace", reader->getextraspace() ); 3248 config.writeEntry( "ExtraSpace", reader->getextraspace() );
3249 config.writeEntry( "ExtraLead", reader->getlead() ); 3249 config.writeEntry( "ExtraLead", reader->getlead() );
3250 config.writeEntry( "Basesize", (int)reader->getBaseSize()); 3250 config.writeEntry( "Basesize", (int)reader->getBaseSize());
3251 config.writeEntry( "RequestorFontChange", m_propogatefontchange); 3251 config.writeEntry( "RequestorFontChange", m_propogatefontchange);
3252 3252
3253 config.setGroup( "Toolbar" ); 3253 config.setGroup( "Toolbar" );
3254 config.writeEntry("Movable", m_tbmovesave); 3254 config.writeEntry("Movable", m_tbmovesave);
3255 config.writeEntry("Policy", m_tbpolsave); 3255 config.writeEntry("Policy", m_tbpolsave);
3256 config.writeEntry("Position", m_tbposition); 3256 config.writeEntry("Position", m_tbposition);
3257*/ 3257*/
3258 savefilelist(); 3258 savefilelist();
3259} 3259}
3260 3260
3261/* 3261/*
3262void QTReaderApp::oldFile() 3262void QTReaderApp::oldFile()
3263{ 3263{
3264// qDebug("oldFile called"); 3264// qDebug("oldFile called");
3265 reader->setText(true); 3265 reader->setText(true);
3266// qDebug("settext called"); 3266// qDebug("settext called");
3267 showEditTools(); 3267 showEditTools();
3268// qDebug("showedit called"); 3268// qDebug("showedit called");
3269} 3269}
3270*/ 3270*/
3271 3271
3272/* 3272/*
3273void info_cb(Fl_Widget* o, void* _data) 3273void info_cb(Fl_Widget* o, void* _data)
3274{ 3274{
3275 3275
3276 if (infowin == NULL) 3276 if (infowin == NULL)
3277 { 3277 {
3278 3278
3279 infowin = new Fl_Window(160,240); 3279 infowin = new Fl_Window(160,240);
3280 filename = new Fl_Output(45,5,110,14,"Filename"); 3280 filename = new Fl_Output(45,5,110,14,"Filename");
3281 filesize = new Fl_Output(45,25,110,14,"Filesize"); 3281 filesize = new Fl_Output(45,25,110,14,"Filesize");
3282 textsize = new Fl_Output(45,45,110,14,"Textsize"); 3282 textsize = new Fl_Output(45,45,110,14,"Textsize");
3283 comprat = new CBar(45,65,110,14,"Ratio %"); 3283 comprat = new CBar(45,65,110,14,"Ratio %");
3284 posn = new Fl_Output(45,85,110,14,"Location"); 3284 posn = new Fl_Output(45,85,110,14,"Location");
3285 frcn = new CBar(45,105,110,14,"% Read"); 3285 frcn = new CBar(45,105,110,14,"% Read");
3286 about = new Fl_Multiline_Output(5,125,150,90); 3286 about = new Fl_Multiline_Output(5,125,150,90);
3287 about->value("TWReader - $Name$\n\nA file reader program for the Agenda\n\nReads text, PalmDoc and ppms format files"); 3287 about->value("TWReader - $Name$\n\nA file reader program for the Agenda\n\nReads text, PalmDoc and ppms format files");
3288 Fl_Button *jump_accept = new Fl_Button(62,220,35,14,"Okay"); 3288 Fl_Button *jump_accept = new Fl_Button(62,220,35,14,"Okay");
3289 infowin->set_modal(); 3289 infowin->set_modal();
3290 } 3290 }
3291 if (((reader_ui *)_data)->g_filename[0] != '\0') 3291 if (((reader_ui *)_data)->g_filename[0] != '\0')
3292 { 3292 {
3293 unsigned long fs,ts; 3293 unsigned long fs,ts;
3294 tchar sz[20]; 3294 tchar sz[20];
3295 ((reader_ui *)_data)->input->sizes(fs,ts); 3295 ((reader_ui *)_data)->input->sizes(fs,ts);
3296 unsigned long pl = ((reader_ui *)_data)->input->locate(); 3296 unsigned long pl = ((reader_ui *)_data)->input->locate();
3297 3297
3298 filename->value(((reader_ui *)_data)->g_filename); 3298 filename->value(((reader_ui *)_data)->g_filename);
3299 3299
3300 sprintf(sz,"%u",fs); 3300 sprintf(sz,"%u",fs);
3301 filesize->value(sz); 3301 filesize->value(sz);
3302 3302
3303 sprintf(sz,"%u",ts); 3303 sprintf(sz,"%u",ts);
3304 textsize->value(sz); 3304 textsize->value(sz);
3305 3305
3306 comprat->value(100-(100*fs + (ts >> 1))/ts); 3306 comprat->value(100-(100*fs + (ts >> 1))/ts);
3307 3307
3308 sprintf(sz,"%u",pl); 3308 sprintf(sz,"%u",pl);
3309 posn->value(sz); 3309 posn->value(sz);
3310 3310
3311 frcn->value((100*pl + (ts >> 1))/ts); 3311 frcn->value((100*pl + (ts >> 1))/ts);
3312 } 3312 }
3313 infowin->show(); 3313 infowin->show();
3314} 3314}
3315*/ 3315*/
3316 3316
3317void QTReaderApp::savebkmks() 3317void QTReaderApp::savebkmks()
3318{ 3318{
3319 if (pBkmklist != NULL) 3319 if (pBkmklist != NULL)
3320 { 3320 {
3321#ifndef USEQPE 3321#ifndef USEQPE
3322 QDir d = QDir::home(); // "/" 3322 QDir d = QDir::home(); // "/"
3323 d.cd(APPDIR); 3323 d.cd(APPDIR);
3324 QFileInfo fi(d, reader->m_string); 3324 QFileInfo fi(d, reader->m_string);
3325 BkmkFile bf((const char *)fi.absFilePath(), true); 3325 BkmkFile bf((const char *)fi.absFilePath(), true);
3326#else /* USEQPE */ 3326#else /* USEQPE */
3327 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,reader->m_string), true); 3327 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,reader->m_string), true);
3328#endif /* USEQPE */ 3328#endif /* USEQPE */
3329 bf.write(*pBkmklist); 3329 bf.write(*pBkmklist);
3330 } 3330 }
3331 m_fBkmksChanged = false; 3331 m_fBkmksChanged = false;
3332} 3332}
3333 3333
3334void QTReaderApp::readfilelist() 3334void QTReaderApp::readfilelist()
3335{ 3335{
3336#ifndef USEQPE 3336#ifndef USEQPE
3337 QDir d = QDir::home(); // "/" 3337 QDir d = QDir::home(); // "/"
3338 d.cd(APPDIR); 3338 d.cd(APPDIR);
3339 QFileInfo fi(d, ".openfiles"); 3339 QFileInfo fi(d, ".openfiles");
3340 BkmkFile bf((const char *)fi.absFilePath()); 3340 BkmkFile bf((const char *)fi.absFilePath());
3341#else /* USEQPE */ 3341#else /* USEQPE */
3342 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,".openfiles")); 3342 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,".openfiles"));
3343#endif /* USEQPE */ 3343#endif /* USEQPE */
3344// qDebug("Reading open files"); 3344// qDebug("Reading open files");
3345 pOpenlist = bf.readall(); 3345 pOpenlist = bf.readall();
3346// if (pOpenlist != NULL) qDebug("...with success"); 3346// if (pOpenlist != NULL) qDebug("...with success");
3347// else qDebug("...without success!"); 3347// else qDebug("...without success!");
3348} 3348}
3349 3349
3350void QTReaderApp::savefilelist() 3350void QTReaderApp::savefilelist()
3351{ 3351{
3352 if (pOpenlist != NULL) 3352 if (pOpenlist != NULL)
3353 { 3353 {
3354#ifndef USEQPE 3354#ifndef USEQPE
3355 QDir d = QDir::home(); // "/" 3355 QDir d = QDir::home(); // "/"
3356 d.cd(APPDIR); 3356 d.cd(APPDIR);
3357 QFileInfo fi(d, ".openfiles"); 3357 QFileInfo fi(d, ".openfiles");
3358 BkmkFile bf((const char *)fi.absFilePath(), true); 3358 BkmkFile bf((const char *)fi.absFilePath(), true);
3359#else /* USEQPE */ 3359#else /* USEQPE */
3360 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,".openfiles"), true); 3360 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,".openfiles"), true);
3361#endif /* USEQPE */ 3361#endif /* USEQPE */
3362 //qDebug("Writing open files"); 3362 //qDebug("Writing open files");
3363 bf.write(*pOpenlist); 3363 bf.write(*pOpenlist);
3364 } 3364 }
3365} 3365}
3366 3366
3367void QTReaderApp::readbkmks() 3367void QTReaderApp::readbkmks()
3368{ 3368{
3369 if (pBkmklist != NULL) 3369 if (pBkmklist != NULL)
3370 { 3370 {
3371 delete pBkmklist; 3371 delete pBkmklist;
3372 } 3372 }
3373 struct stat fnstat; 3373 struct stat fnstat;
3374 struct stat bkstat; 3374 struct stat bkstat;
3375#ifndef USEQPE 3375#ifndef USEQPE
3376 QDir d = QDir::home(); // "/" 3376 QDir d = QDir::home(); // "/"
3377 d.cd(APPDIR); 3377 d.cd(APPDIR);
3378 QFileInfo fi(d, reader->m_string); 3378 QFileInfo fi(d, reader->m_string);
3379#endif /* ! USEQPE */ 3379#endif /* ! USEQPE */
3380 if ( 3380 if (
3381 stat((const char *)reader->m_lastfile, &fnstat) == 0 3381 stat((const char *)reader->m_lastfile, &fnstat) == 0
3382 && 3382 &&
3383#ifndef USEQPE 3383#ifndef USEQPE
3384 stat((const char *)fi.absFilePath(), &bkstat) == 0 3384 stat((const char *)fi.absFilePath(), &bkstat) == 0
3385#else /* USEQPE */ 3385#else /* USEQPE */
3386 stat((const char *)Global::applicationFileName(APPDIR,reader->m_string), &bkstat) == 0 3386 stat((const char *)Global::applicationFileName(APPDIR,reader->m_string), &bkstat) == 0
3387#endif /* USEQPE */ 3387#endif /* USEQPE */
3388 ) 3388 )
3389 { 3389 {
3390 if (bkstat.st_mtime < fnstat.st_mtime) 3390 if (bkstat.st_mtime < fnstat.st_mtime)
3391 { 3391 {
3392#ifndef USEQPE 3392#ifndef USEQPE
3393 unlink((const char *)fi.absFilePath()); 3393 unlink((const char *)fi.absFilePath());
3394#else /* USEQPE */ 3394#else /* USEQPE */
3395 unlink((const char *)Global::applicationFileName(APPDIR,reader->m_string)); 3395 unlink((const char *)Global::applicationFileName(APPDIR,reader->m_string));
3396#endif /* USEQPE */ 3396#endif /* USEQPE */
3397 } 3397 }
3398 } 3398 }
3399 3399
3400#ifndef USEQPE 3400#ifndef USEQPE
3401 BkmkFile bf((const char *)fi.absFilePath()); 3401 BkmkFile bf((const char *)fi.absFilePath());
3402#else /* USEQPE */ 3402#else /* USEQPE */
3403 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,reader->m_string)); 3403 BkmkFile bf((const char *)Global::applicationFileName(APPDIR,reader->m_string));
3404#endif /* USEQPE */ 3404#endif /* USEQPE */
3405 3405
3406 pBkmklist = bf.readall(); 3406 pBkmklist = bf.readall();
3407 m_fBkmksChanged = bf.upgraded(); 3407 m_fBkmksChanged = bf.upgraded();
3408 if (pBkmklist == NULL) 3408 if (pBkmklist == NULL)
3409 { 3409 {
3410 pBkmklist = reader->getbkmklist(); 3410 pBkmklist = reader->getbkmklist();
3411 } 3411 }
3412 if (pBkmklist != NULL) 3412 if (pBkmklist != NULL)
3413 pBkmklist->sort(); 3413 pBkmklist->sort();
3414} 3414}
3415 3415
3416void QTReaderApp::addbkmk() 3416void QTReaderApp::addbkmk()
3417{ 3417{
3418 m_nRegAction = cAddBkmk; 3418 m_nRegAction = cAddBkmk;
3419 regEdit->setText(reader->firstword()); 3419 regEdit->setText(reader->firstword());
3420 do_regedit(); 3420 do_regedit();
3421} 3421}
3422 3422
3423void QTReaderApp::do_addbkmk(const QString& text) 3423void QTReaderApp::do_addbkmk(const QString& text)
3424{ 3424{
3425 if (text.isEmpty()) 3425 if (text.isEmpty())
3426 { 3426 {
3427 QMessageBox::information(this, PROGNAME, "Need a name for the bookmark\nSelect add again", 1); 3427 QMessageBox::information(this, PROGNAME, "Need a name for the bookmark\nSelect add again", 1);
3428 } 3428 }
3429 else 3429 else
3430 { 3430 {
3431 if (pBkmklist == NULL) pBkmklist = new CList<Bkmk>; 3431 if (pBkmklist == NULL) pBkmklist = new CList<Bkmk>;
3432#ifdef _UNICODE 3432#ifdef _UNICODE
3433 CBuffer buff; 3433 CBuffer buff;
3434 int i = 0; 3434 int i = 0;
3435 for (i = 0; i < text.length(); i++) 3435 for (i = 0; i < text.length(); i++)
3436 { 3436 {
3437 buff[i] = text[i].unicode(); 3437 buff[i] = text[i].unicode();
3438 } 3438 }
3439 buff[i] = 0; 3439 buff[i] = 0;
3440 pBkmklist->push_front(Bkmk(buff.data(), NULL, reader->pagelocate())); 3440 pBkmklist->push_front(Bkmk(buff.data(), NULL, reader->pagelocate()));
3441#else 3441#else
3442 pBkmklist->push_front(Bkmk((const tchar*)text, reader->pagelocate())); 3442 pBkmklist->push_front(Bkmk((const tchar*)text, reader->pagelocate()));
3443#endif 3443#endif
3444 m_fBkmksChanged = true; 3444 m_fBkmksChanged = true;
3445 pBkmklist->sort(); 3445 pBkmklist->sort();
3446 } 3446 }
3447} 3447}
3448 3448
3449void QTReaderApp::OnRedraw() 3449void QTReaderApp::OnRedraw()
3450{ 3450{
3451 if ((pBkmklist != NULL) && (m_bkmkAvail != NULL)) 3451 if ((pBkmklist != NULL) && (m_bkmkAvail != NULL))
3452 { 3452 {
3453 bool found = findNextBookmark(reader->pagelocate()); 3453 bool found = findNextBookmark(reader->pagelocate());
3454 m_bkmkAvail->setEnabled(found); 3454 m_bkmkAvail->setEnabled(found);
3455 } 3455 }
3456} 3456}
3457 3457
3458void QTReaderApp::showAnnotation() 3458void QTReaderApp::showAnnotation()
3459{ 3459{
3460 m_annoWin->setName(toQString(m_anno->name())); 3460 m_annoWin->setName(toQString(m_anno->name()));
3461 m_annoWin->setAnno(toQString(m_anno->anno())); 3461 m_annoWin->setAnno(toQString(m_anno->anno()));
3462 m_annoIsEditing = false; 3462 m_annoIsEditing = false;
3463#ifdef USEQPE 3463#ifdef USEQPE
3464 Global::showInputMethod(); 3464 Global::showInputMethod();
3465#endif 3465#endif
3466 editorStack->raiseWidget( m_annoWin ); 3466 editorStack->raiseWidget( m_annoWin );
3467 m_annoWin->setFocus(); 3467 m_annoWin->setFocus();
3468} 3468}
3469 3469
3470void QTReaderApp::OnWordSelected(const QString& wrd, size_t posn, const QString& line) 3470void QTReaderApp::OnWordSelected(const QString& wrd, size_t posn, const QString& line)
3471{ 3471{
3472//// qDebug("OnWordSelected(%u):%s", posn, (const char*)wrd); 3472//// qDebug("OnWordSelected(%u):%s", posn, (const char*)wrd);
3473 3473
3474 if (m_doClipboard) 3474 if (m_doClipboard)
3475 { 3475 {
3476 QClipboard* cb = QApplication::clipboard(); 3476 QClipboard* cb = QApplication::clipboard();
3477 cb->setText(wrd); 3477 cb->setText(wrd);
3478#ifdef USEQPE 3478#ifdef USEQPE
3479 if (wrd.length() > 10) 3479 if (wrd.length() > 10)
3480 { 3480 {
3481 Global::statusMessage(wrd.left(8) + ".."); 3481 Global::statusMessage(wrd.left(8) + "..");
3482 } 3482 }
3483 else 3483 else
3484 { 3484 {
3485 Global::statusMessage(wrd); 3485 Global::statusMessage(wrd);
3486 } 3486 }
3487#endif 3487#endif
3488 } 3488 }
3489 if (m_doAnnotation) 3489 if (m_doAnnotation)
3490 { 3490 {
3491 //addAnno(wrd, "Need to be able to edit this", posn); 3491 //addAnno(wrd, "Need to be able to edit this", posn);
3492 m_annoWin->setName(line); 3492 m_annoWin->setName(line);
3493 m_annoWin->setAnno(""); 3493 m_annoWin->setAnno("");
3494 m_annoWin->setPosn(posn); 3494 m_annoWin->setPosn(posn);
3495 m_annoIsEditing = true; 3495 m_annoIsEditing = true;
3496#ifdef USEQPE 3496#ifdef USEQPE
3497 Global::showInputMethod(); 3497 Global::showInputMethod();
3498#endif 3498#endif
3499 editorStack->raiseWidget( m_annoWin ); 3499 editorStack->raiseWidget( m_annoWin );
3500 } 3500 }
3501#ifdef USEQPE 3501#ifdef USEQPE
3502 if (m_doDictionary) 3502 if (m_doDictionary)
3503 { 3503 {
3504 if (!m_targetapp.isEmpty() && !m_targetmsg.isEmpty()) 3504 if (!m_targetapp.isEmpty() && !m_targetmsg.isEmpty())
3505 { 3505 {
3506 QCopEnvelope e(("QPE/Application/"+m_targetapp).utf8(), (m_targetmsg+"(QString)").utf8()); 3506 QCopEnvelope e(("QPE/Application/"+m_targetapp).utf8(), (m_targetmsg+"(QString)").utf8());
3507 e << wrd; 3507 e << wrd;
3508 } 3508 }
3509 } 3509 }
3510#endif 3510#endif
3511} 3511}
3512 3512
3513void QTReaderApp::doAction(ActionTypes a, QKeyEvent* e) 3513void QTReaderApp::doAction(ActionTypes a, QKeyEvent* e)
3514{ 3514{
3515 if (a == 0) 3515 if (a == 0)
3516 { 3516 {
3517 e->ignore(); 3517 e->ignore();
3518 } 3518 }
3519 else 3519 else
3520 { 3520 {
3521 e->accept(); 3521 e->accept();
3522 //qDebug("Accepted"); 3522 //qDebug("Accepted");
3523 switch (a) 3523 switch (a)
3524 { 3524 {
3525 case cesOpenFile: 3525 case cesOpenFile:
3526 { 3526 {
3527 fileOpen(); 3527 fileOpen();
3528 } 3528 }
3529 break; 3529 break;
3530 case cesAutoScroll: 3530 case cesAutoScroll:
3531 { 3531 {
3532 reader->setautoscroll(!reader->m_autoScroll); 3532 reader->setautoscroll(!reader->m_autoScroll);
3533 setScrollState(reader->m_autoScroll); 3533 setScrollState(reader->m_autoScroll);
3534 } 3534 }
3535 break; 3535 break;
3536 case cesActionMark: 3536 case cesActionMark:
3537 { 3537 {
3538 addbkmk(); 3538 addbkmk();
3539 } 3539 }
3540 break; 3540 break;
3541 case cesFullScreen: 3541 case cesFullScreen:
3542 { 3542 {
3543 m_actFullscreen->setOn(!m_fullscreen); 3543 m_actFullscreen->setOn(!m_fullscreen);
3544 } 3544 }
3545 break; 3545 break;
3546 case cesActionAnno: 3546 case cesActionAnno:
3547 { 3547 {
3548 addanno(); 3548 addanno();
3549 } 3549 }
3550 break; 3550 break;
3551 case cesZoomIn: 3551 case cesZoomIn:
3552 zoomin(); 3552 zoomin();
3553 break; 3553 break;
3554 case cesZoomOut: 3554 case cesZoomOut:
3555 zoomout(); 3555 zoomout();
3556 break; 3556 break;
3557 case cesBack: 3557 case cesBack:
3558 reader->goBack(); 3558 reader->goBack();
3559 break; 3559 break;
3560 case cesForward: 3560 case cesForward:
3561 reader->goForward(); 3561 reader->goForward();
3562 break; 3562 break;
3563 case cesHome: 3563 case cesHome:
3564 reader->goHome(); 3564 reader->goHome();
3565 break; 3565 break;
3566 case cesPageUp: 3566 case cesPageUp:
3567 reader->dopageup(); 3567 reader->dopageup();
3568 break; 3568 break;
3569 case cesPageDown: 3569 case cesPageDown:
3570 reader->dopagedn(); 3570 reader->dopagedn();
3571 break; 3571 break;
3572 case cesLineUp: 3572 case cesLineUp:
3573 reader->lineUp(); 3573 reader->lineUp();
3574 break; 3574 break;
3575 case cesLineDown: 3575 case cesLineDown:
3576 reader->lineDown(); 3576 reader->lineDown();
3577 break; 3577 break;
3578 case cesStartDoc: 3578 case cesStartDoc:
3579 gotoStart(); 3579 gotoStart();
3580 break; 3580 break;
3581 case cesEndDoc: 3581 case cesEndDoc:
3582 gotoEnd(); 3582 gotoEnd();
3583 break; 3583 break;
3584 default: 3584 default:
3585 qDebug("Unknown ActionType:%u", a); 3585 qDebug("Unknown ActionType:%u", a);
3586 break; 3586 break;
3587 } 3587 }
3588 } 3588 }
3589} 3589}
3590 3590
3591void QTReaderApp::setTwoTouch(bool _b) { reader->setTwoTouch(_b); } 3591void QTReaderApp::setTwoTouch(bool _b) { reader->setTwoTouch(_b); }
3592void QTReaderApp::restoreFocus() { reader->setFocus(); } 3592void QTReaderApp::restoreFocus() { reader->setFocus(); }
3593 3593
3594void QTReaderApp::SaveConfig() 3594void QTReaderApp::SaveConfig()
3595{ 3595{
3596 m_nRegAction = cSetConfigName; 3596 m_nRegAction = cSetConfigName;
3597 regEdit->setText(reader->m_string); 3597 regEdit->setText(reader->m_string);
3598 do_regedit(); 3598 do_regedit();
3599} 3599}
3600 3600
3601void QTReaderApp::do_saveconfig(const QString& _txt, bool full) 3601void QTReaderApp::do_saveconfig(const QString& _txt, bool full)
3602{ 3602{
3603// qDebug("do_saveconfig:%s", (const char*)_txt); 3603// qDebug("do_saveconfig:%s", (const char*)_txt);
3604#ifdef USEQPE 3604#ifdef USEQPE
3605 QString configname; 3605 QString configname;
3606 Config::Domain dom; 3606 Config::Domain dom;
3607 3607
3608 if (full) 3608 if (full)
3609 { 3609 {
3610 configname = _txt; 3610 configname = _txt;
3611 dom = Config::User; 3611 dom = Config::User;
3612 } 3612 }
3613 else 3613 else
3614 { 3614 {
3615 configname = Global::applicationFileName(APPDIR "/configs", _txt); 3615 configname = Global::applicationFileName(APPDIR "/configs", _txt);
3616 dom = Config::File; 3616 dom = Config::File;
3617 } 3617 }
3618 3618
3619 Config config(configname, dom); 3619 Config config(configname, dom);
3620 config.setGroup( "View" ); 3620 config.setGroup( "View" );
3621 3621
3622#else 3622#else
3623 QFileInfo fi; 3623 QFileInfo fi;
3624 if (full) 3624 if (full)
3625 { 3625 {
3626 // qDebug("full:%s", (const char*)_txt); 3626 // qDebug("full:%s", (const char*)_txt);
3627 QDir d = QDir::home(); // "/" 3627 QDir d = QDir::home(); // "/"
3628 if ( !d.cd(_txt) ) 3628 if ( !d.cd(_txt) )
3629 { // "/tmp" 3629 { // "/tmp"
3630 qWarning( "Cannot find the \"~/%s\" directory", (const char*)_txt ); 3630 qWarning( "Cannot find the \"~/%s\" directory", (const char*)_txt );
3631 d = QDir::home(); 3631 d = QDir::home();
3632 d.mkdir(_txt); 3632 d.mkdir(_txt);
3633 d.cd(_txt); 3633 d.cd(_txt);
3634 } 3634 }
3635 fi.setFile(d, INIFILE); 3635 fi.setFile(d, INIFILE);
3636 } 3636 }
3637 else 3637 else
3638 { 3638 {
3639 QDir d = QDir::home(); // "/" 3639 QDir d = QDir::home(); // "/"
3640 if ( !d.cd(APPDIR) ) 3640 if ( !d.cd(APPDIR) )
3641 { // "/tmp" 3641 { // "/tmp"
3642 qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); 3642 qWarning( "Cannot find the \"~/" APPDIR "\" directory" );
3643 d = QDir::home(); 3643 d = QDir::home();
3644 d.mkdir(APPDIR); 3644 d.mkdir(APPDIR);
3645 d.cd(APPDIR); 3645 d.cd(APPDIR);
3646 } 3646 }
3647 if ( !d.cd("configs") ) 3647 if ( !d.cd("configs") )
3648 { // "/tmp" 3648 { // "/tmp"
3649 qWarning( "Cannot find the \"~/" APPDIR "/configs\" directory" ); 3649 qWarning( "Cannot find the \"~/" APPDIR "/configs\" directory" );
3650 d = QDir::home(); 3650 d = QDir::home();
3651 d.cd(APPDIR); 3651 d.cd(APPDIR);
3652 d.mkdir("configs"); 3652 d.mkdir("configs");
3653 d.cd("configs"); 3653 d.cd("configs");
3654 } 3654 }
3655 fi.setFile(d, _txt); 3655 fi.setFile(d, _txt);
3656 } 3656 }
3657 //qDebug("Path:%s", (const char*)fi.absFilePath()); 3657 //qDebug("Path:%s", (const char*)fi.absFilePath());
3658 Config config(fi.absFilePath()); 3658 Config config(fi.absFilePath());
3659#endif 3659#endif
3660 3660
3661 3661
3662 config.writeEntry( "StripCr", reader->bstripcr ); 3662 config.writeEntry( "StripCr", reader->bstripcr );
3663 config.writeEntry( "AutoFmt", reader->bautofmt ); 3663 config.writeEntry( "AutoFmt", reader->bautofmt );
3664 config.writeEntry( "TextFmt", reader->btextfmt ); 3664 config.writeEntry( "TextFmt", reader->btextfmt );
3665 config.writeEntry( "StripHtml", reader->bstriphtml ); 3665 config.writeEntry( "StripHtml", reader->bstriphtml );
3666 config.writeEntry( "Dehyphen", reader->bdehyphen ); 3666 config.writeEntry( "Dehyphen", reader->bdehyphen );
3667 config.writeEntry( "Depluck", reader->bdepluck ); 3667 config.writeEntry( "Depluck", reader->bdepluck );
3668 config.writeEntry( "Dejpluck", reader->bdejpluck ); 3668 config.writeEntry( "Dejpluck", reader->bdejpluck );
3669 config.writeEntry( "OneSpace", reader->bonespace ); 3669 config.writeEntry( "OneSpace", reader->bonespace );
3670 config.writeEntry( "Unindent", reader->bunindent ); 3670 config.writeEntry( "Unindent", reader->bunindent );
3671 config.writeEntry( "Repara", reader->brepara ); 3671 config.writeEntry( "Repara", reader->brepara );
3672 config.writeEntry( "DoubleSpace", reader->bdblspce ); 3672 config.writeEntry( "DoubleSpace", reader->bdblspce );
3673 config.writeEntry( "Indent", reader->bindenter ); 3673 config.writeEntry( "Indent", reader->bindenter );
3674 config.writeEntry( "FontSize", (int)(reader->m_fontControl.currentsize()) ); 3674 config.writeEntry( "FontSize", (int)(reader->m_fontControl.currentsize()) );
3675 config.writeEntry( "ScrollDelay", reader->m_delay); 3675 config.writeEntry( "ScrollDelay", reader->m_delay);
3676 if (full) 3676 if (full)
3677 { 3677 {
3678 config.writeEntry("Debounce", m_debounce); 3678 config.writeEntry("Debounce", m_debounce);
3679 config.writeEntry("FloatDialogs", m_bFloatingDialog); 3679 config.writeEntry("FloatDialogs", m_bFloatingDialog);
3680 reader->m_lastposn = reader->pagelocate(); 3680 reader->m_lastposn = reader->pagelocate();
3681 config.writeEntry( "LastFile", reader->m_lastfile ); 3681 config.writeEntry( "LastFile", reader->m_lastfile );
3682 config.writeEntry( "LastPosn", (int)(reader->pagelocate()) ); 3682 config.writeEntry( "LastPosn", (int)(reader->pagelocate()) );
3683 } 3683 }
3684 config.writeEntry( "PageMode", reader->m_bpagemode ); 3684 config.writeEntry( "PageMode", reader->m_bpagemode );
3685 config.writeEntry( "MonoSpaced", reader->m_bMonoSpaced ); 3685 config.writeEntry( "MonoSpaced", reader->m_bMonoSpaced );
3686 config.writeEntry( "SwapMouse", reader->m_swapmouse); 3686 config.writeEntry( "SwapMouse", reader->m_swapmouse);
3687 config.writeEntry( "Fontname", reader->m_fontname ); 3687 config.writeEntry( "Fontname", reader->m_fontname );
3688 config.writeEntry( "Encoding", reader->m_encd ); 3688 config.writeEntry( "Encoding", reader->m_encd );
3689 config.writeEntry( "CharSpacing", reader->m_charpc ); 3689 config.writeEntry( "CharSpacing", reader->m_charpc );
3690 config.writeEntry( "Overlap", (int)(reader->m_overlap) ); 3690 config.writeEntry( "Overlap", (int)(reader->m_overlap) );
3691 config.writeEntry( "Margin", (int)reader->m_border ); 3691 config.writeEntry( "Margin", (int)reader->m_border );
3692 config.writeEntry( "TargetApp", m_targetapp ); 3692 config.writeEntry( "TargetApp", m_targetapp );
3693 config.writeEntry( "TargetMsg", m_targetmsg ); 3693 config.writeEntry( "TargetMsg", m_targetmsg );
3694#ifdef _SCROLLPIPE 3694#ifdef _SCROLLPIPE
3695 config.writeEntry( "PipeTarget", reader->m_pipetarget ); 3695 config.writeEntry( "PipeTarget", reader->m_pipetarget );
3696 config.writeEntry( "PauseAfterPara", reader->m_pauseAfterEachPara ); 3696 config.writeEntry( "PauseAfterPara", reader->m_pauseAfterEachPara );
3697#endif 3697#endif
3698 config.writeEntry( "TwoTouch", m_twoTouch ); 3698 config.writeEntry( "TwoTouch", m_twoTouch );
3699 config.writeEntry( "Annotation", m_doAnnotation); 3699 config.writeEntry( "Annotation", m_doAnnotation);
3700 config.writeEntry( "Dictionary", m_doDictionary); 3700 config.writeEntry( "Dictionary", m_doDictionary);
3701 config.writeEntry( "Clipboard", m_doClipboard); 3701 config.writeEntry( "Clipboard", m_doClipboard);
3702 config.writeEntry( "SpaceTarget", m_spaceTarget); 3702 config.writeEntry( "SpaceTarget", m_spaceTarget);
3703 config.writeEntry( "EscapeTarget", m_escapeTarget); 3703 config.writeEntry( "EscapeTarget", m_escapeTarget);
3704 config.writeEntry( "ReturnTarget", m_returnTarget); 3704 config.writeEntry( "ReturnTarget", m_returnTarget);
3705 config.writeEntry( "LeftTarget", m_leftTarget); 3705 config.writeEntry( "LeftTarget", m_leftTarget);
3706 config.writeEntry( "RightTarget", m_rightTarget); 3706 config.writeEntry( "RightTarget", m_rightTarget);
3707 config.writeEntry( "UpTarget", m_upTarget); 3707 config.writeEntry( "UpTarget", m_upTarget);
3708 config.writeEntry( "DownTarget", m_downTarget); 3708 config.writeEntry( "DownTarget", m_downTarget);
3709 config.writeEntry("LeftScroll", m_leftScroll); 3709 config.writeEntry("LeftScroll", m_leftScroll);
3710 config.writeEntry("RightScroll", m_rightScroll); 3710 config.writeEntry("RightScroll", m_rightScroll);
3711 config.writeEntry("UpScroll", m_upScroll); 3711 config.writeEntry("UpScroll", m_upScroll);
3712 config.writeEntry("DownScroll", m_downScroll); 3712 config.writeEntry("DownScroll", m_downScroll);
3713#ifdef REPALM 3713#ifdef REPALM
3714 config.writeEntry( "Repalm", reader->brepalm ); 3714 config.writeEntry( "Repalm", reader->brepalm );
3715#endif 3715#endif
3716 config.writeEntry( "Remap", reader->bremap ); 3716 config.writeEntry( "Remap", reader->bremap );
3717 config.writeEntry( "Peanut", reader->bpeanut ); 3717 config.writeEntry( "Peanut", reader->bpeanut );
3718 config.writeEntry( "MakeBold", reader->bmakebold ); 3718 config.writeEntry( "MakeBold", reader->bmakebold );
3719 config.writeEntry( "Continuous", reader->m_continuousDocument ); 3719 config.writeEntry( "Continuous", reader->m_continuousDocument );
3720 config.writeEntry( "FullJust", reader->bfulljust ); 3720 config.writeEntry( "FullJust", reader->bfulljust );
3721 config.writeEntry( "ExtraSpace", reader->getextraspace() ); 3721 config.writeEntry( "ExtraSpace", reader->getextraspace() );
3722 config.writeEntry( "ExtraLead", reader->getlead() ); 3722 config.writeEntry( "ExtraLead", reader->getlead() );
3723 config.writeEntry( "Basesize", (int)reader->getBaseSize()); 3723 config.writeEntry( "Basesize", (int)reader->getBaseSize());
3724 config.writeEntry( "RequestorFontChange", m_propogatefontchange); 3724 config.writeEntry( "RequestorFontChange", m_propogatefontchange);
3725 if (full) 3725 if (full)
3726 { 3726 {
3727 config.setGroup( "Toolbar" ); 3727 config.setGroup( "Toolbar" );
3728 config.writeEntry("Movable", m_tbmovesave); 3728 config.writeEntry("Movable", m_tbmovesave);
3729 config.writeEntry("Policy", m_tbpolsave); 3729 config.writeEntry("Policy", m_tbpolsave);
3730 config.writeEntry("Position", m_tbposition); 3730 config.writeEntry("Position", m_tbposition);
3731#ifndef USEQPE 3731#ifndef USEQPE
3732 config.setGroup( "Geometry" ); 3732 config.setGroup( "Geometry" );
3733 config.writeEntry( "x", x() ); 3733 config.writeEntry( "x", x() );
3734 config.writeEntry( "y", y() ); 3734 config.writeEntry( "y", y() );
3735 config.writeEntry( "width", width() ); 3735 config.writeEntry( "width", width() );
3736 config.writeEntry( "height", height() ); 3736 config.writeEntry( "height", height() );
3737#endif 3737#endif
3738 } 3738 }
3739} 3739}
3740 3740
3741/* 3741/*
3742void QTReaderApp::setstate(unsigned char* _sd, unsigned short _sdlen) 3742void QTReaderApp::setstate(unsigned char* _sd, unsigned short _sdlen)
3743{ 3743{
3744 unsigned short sdlen; 3744 unsigned short sdlen;
3745 memcpy(&sdlen, _sd, sizeof(sdlen)); 3745 memcpy(&sdlen, _sd, sizeof(sdlen));
3746 sdlen -= sizeof(sdlen); 3746 sdlen -= sizeof(sdlen);
3747 _sd += sizeof(sdlen); 3747 _sd += sizeof(sdlen);
3748 statedata* sd; 3748 statedata* sd;
3749 char* data; 3749 char* data;
3750 if (sdlen < sizeof(statedata)+1) 3750 if (sdlen < sizeof(statedata)+1)
3751 { 3751 {
3752 sdlen = sizeof(statedata)+1; 3752 sdlen = sizeof(statedata)+1;
3753 } 3753 }
3754 data = new char[sdlen]; 3754 data = new char[sdlen];
3755 sd = (statedata*)data; 3755 sd = (statedata*)data;
3756 memcpy(sd, _sd, sdlen); 3756 memcpy(sd, _sd, sdlen);
3757 data[sdlen] = 0; 3757 data[sdlen] = 0;
3758 reader->setstate(*sd); 3758 reader->setstate(*sd);
3759 delete [] data; 3759 delete [] data;
3760} 3760}
3761 3761
3762void QTReaderApp::getstate(unsigned char*& data, unsigned short& len) 3762void QTReaderApp::getstate(unsigned char*& data, unsigned short& len)
3763{ 3763{
3764 unsigned char* olddata = data; 3764 unsigned char* olddata = data;
3765 unsigned short oldlen = len; 3765 unsigned short oldlen = len;
3766 len = oldlen+sizeof(unsigned short)+sizeof(statedata)+reader->m_fontname.length(); 3766 len = oldlen+sizeof(unsigned short)+sizeof(statedata)+reader->m_fontname.length();
3767 data = new unsigned char[len]; 3767 data = new unsigned char[len];
3768 memcpy(data, olddata, oldlen); 3768 memcpy(data, olddata, oldlen);
3769 delete [] olddata; 3769 delete [] olddata;
3770 memcpy(data+oldlen, &len, sizeof(len)); 3770 memcpy(data+oldlen, &len, sizeof(len));
3771 statedata* sd = (statedata*)(data+oldlen+sizeof(unsigned short)); 3771 statedata* sd = (statedata*)(data+oldlen+sizeof(unsigned short));
3772 3772
3773 sd->bstripcr = reader->bstripcr; 3773 sd->bstripcr = reader->bstripcr;
3774 sd->btextfmt = reader->btextfmt; 3774 sd->btextfmt = reader->btextfmt;
3775 sd->bautofmt = reader->bautofmt; 3775 sd->bautofmt = reader->bautofmt;
3776 sd->bstriphtml = reader->bstriphtml; 3776 sd->bstriphtml = reader->bstriphtml;
3777 sd->bpeanut = reader->bpeanut; 3777 sd->bpeanut = reader->bpeanut;
3778 sd->bdehyphen = reader->bdehyphen; 3778 sd->bdehyphen = reader->bdehyphen;
3779 sd->bdepluck = reader->bdepluck; 3779 sd->bdepluck = reader->bdepluck;
3780 sd->bdejpluck = reader->bdejpluck; 3780 sd->bdejpluck = reader->bdejpluck;
3781 sd->bonespace = reader->bonespace; 3781 sd->bonespace = reader->bonespace;
3782 sd->bunindent = reader->bunindent; 3782 sd->bunindent = reader->bunindent;
3783 sd->brepara = reader->brepara; 3783 sd->brepara = reader->brepara;
3784 sd->bdblspce = reader->bdblspce; 3784 sd->bdblspce = reader->bdblspce;
3785 sd->m_bpagemode = reader->m_bpagemode; 3785 sd->m_bpagemode = reader->m_bpagemode;
3786 sd->m_bMonoSpaced = reader->m_bMonoSpaced; 3786 sd->m_bMonoSpaced = reader->m_bMonoSpaced;
3787 sd->bremap = reader->bremap; 3787 sd->bremap = reader->bremap;
3788 sd->bmakebold = reader->bmakebold; 3788 sd->bmakebold = reader->bmakebold;
3789 sd->Continuous = reader->m_continuousDocument; 3789 sd->Continuous = reader->m_continuousDocument;
3790#ifdef REPALM 3790#ifdef REPALM
3791 sd->brepalm = reader->brepalm; 3791 sd->brepalm = reader->brepalm;
3792#endif 3792#endif
3793 sd->bindenter = reader->bindenter; 3793 sd->bindenter = reader->bindenter;
3794 sd->m_textsize = reader->m_textsize; //reader->m_fontControl.currentsize() 3794 sd->m_textsize = reader->m_textsize; //reader->m_fontControl.currentsize()
3795 sd->m_encd = reader->m_encd; 3795 sd->m_encd = reader->m_encd;
3796 sd->m_charpc = reader->m_charpc; 3796 sd->m_charpc = reader->m_charpc;
3797 strcpy(sd->m_fontname, reader->m_fontname.latin1()); 3797 strcpy(sd->m_fontname, reader->m_fontname.latin1());
3798} 3798}
3799*/ 3799*/
3800#ifdef _SCRIPT 3800#ifdef _SCRIPT
3801void QTReaderApp::RunScript() 3801void QTReaderApp::RunScript()
3802{ 3802{
3803 fileBrowser* fb = new fileBrowser(this,"OpieReader",!m_bFloatingDialog, 3803 fileBrowser* fb = new fileBrowser(this,"OpieReader",!m_bFloatingDialog,
3804 0, 3804 0,
3805 // WStyle_Customize | WStyle_NoBorderEx, 3805 // WStyle_Customize | WStyle_NoBorderEx,
3806 "*", Global::applicationFileName(APPDIR "/scripts", "")); 3806 "*", Global::applicationFileName(APPDIR "/scripts", ""));
3807 3807
3808 QString fn; 3808 QString fn;
3809 if (fb->exec()) 3809 if (fb->exec())
3810 { 3810 {
3811 fn = fb->fileList[0]; 3811 fn = fb->fileList[0];
3812 } 3812 }
3813 delete fb; 3813 delete fb;
3814 if ( !fn.isEmpty() && fork() == 0 ) 3814 if ( !fn.isEmpty() && fork() == 0 )
3815 { 3815 {
3816 execlp((const char *)fn,(const char *)fn,NULL); 3816 execlp((const char *)fn,(const char *)fn,NULL);
3817 } 3817 }
3818} 3818}
3819 3819
3820void QTReaderApp::SaveScript(const char* sname) 3820void QTReaderApp::SaveScript(const char* sname)
3821{ 3821{
3822 FILE* f = fopen(sname,"w"); 3822 FILE* f = fopen(sname,"w");
3823 if (f != NULL) 3823 if (f != NULL)
3824 { 3824 {
3825#ifdef OPIE 3825#ifdef OPIE
3826 fprintf(f, "#!/bin/sh\nmsg() {\n\tqcop QPE/Application/reader \"$1\" \"$2\" \"$3\"\n}\n"); 3826 fprintf(f, "#!/bin/sh\nmsg() {\n\tqcop QPE/Application/reader \"$1\" \"$2\" \"$3\"\n}\n");
3827#else 3827#else
3828 fprintf(f, "#!/bin/bash\nmsg() {\n\tqcop QPE/Application/uqtreader \"$1\" \"$2\" \"$3\"\n}\n"); 3828 fprintf(f, "#!/bin/bash\nmsg() {\n\tqcop QPE/Application/uqtreader \"$1\" \"$2\" \"$3\"\n}\n");
3829#endif 3829#endif
3830 fprintf(f, "msg \"Update(int)\" 0\n"); 3830 fprintf(f, "msg \"Update(int)\" 0\n");
3831 fprintf(f, "msg \"Layout/StripCR(int)\" %d\n", (reader->bstripcr) ? 1:0); 3831 fprintf(f, "msg \"Layout/StripCR(int)\" %d\n", (reader->bstripcr) ? 1:0);
3832 if (reader->btextfmt) fprintf(f, "msg \"Markup(QString)\" \"Text\"\n"); 3832 if (reader->btextfmt) fprintf(f, "msg \"Markup(QString)\" \"Text\"\n");
3833 else if (reader->bautofmt) fprintf(f, "msg \"Markup(QString)\" \"Auto\"\n"); 3833 else if (reader->bautofmt) fprintf(f, "msg \"Markup(QString)\" \"Auto\"\n");
3834 else if (reader->bstriphtml) fprintf(f, "msg \"Markup(QString)\" \"HTML\"\n"); 3834 else if (reader->bstriphtml) fprintf(f, "msg \"Markup(QString)\" \"HTML\"\n");
3835 else if (reader->bpeanut) fprintf(f, "msg \"Markup(QString)\" \"Peanut/PML\"\n"); 3835 else if (reader->bpeanut) fprintf(f, "msg \"Markup(QString)\" \"Peanut/PML\"\n");
3836 else fprintf(f, "msg \"Markup(QString)\" \"None\"\n"); 3836 else fprintf(f, "msg \"Markup(QString)\" \"None\"\n");
3837 fprintf(f, "msg \"Layout/Dehyphen(int)\" %d\n", (reader->bdehyphen) ? 1:0); 3837 fprintf(f, "msg \"Layout/Dehyphen(int)\" %d\n", (reader->bdehyphen) ? 1:0);
3838 fprintf(f, "msg \"Layout/Depluck(int)\" %d\n", (reader->bdepluck) ? 1:0); 3838 fprintf(f, "msg \"Layout/Depluck(int)\" %d\n", (reader->bdepluck) ? 1:0);
3839 fprintf(f, "msg \"Layout/Dejpluck(int)\" %d\n", (reader->bdejpluck) ? 1:0); 3839 fprintf(f, "msg \"Layout/Dejpluck(int)\" %d\n", (reader->bdejpluck) ? 1:0);
3840 fprintf(f, "msg \"Layout/SingleSpace(int)\" %d\n", (reader->bonespace) ? 1:0); 3840 fprintf(f, "msg \"Layout/SingleSpace(int)\" %d\n", (reader->bonespace) ? 1:0);
3841 fprintf(f, "msg \"Layout/Unindent(int)\" %d\n", (reader->bunindent) ? 1:0); 3841 fprintf(f, "msg \"Layout/Unindent(int)\" %d\n", (reader->bunindent) ? 1:0);
3842 fprintf(f, "msg \"Layout/Re-paragraph(int)\" %d\n", (reader->brepara) ? 1:0); 3842 fprintf(f, "msg \"Layout/Re-paragraph(int)\" %d\n", (reader->brepara) ? 1:0);
3843 fprintf(f, "msg \"Layout/DoubleSpace(int)\" %d\n", (reader->bdblspce) ? 1:0); 3843 fprintf(f, "msg \"Layout/DoubleSpace(int)\" %d\n", (reader->bdblspce) ? 1:0);
3844 fprintf(f, "msg \"Layout/Indent(int)\" %d\n", reader->bindenter); 3844 fprintf(f, "msg \"Layout/Indent(int)\" %d\n", reader->bindenter);
3845 fprintf(f, "msg \"Format/SetFont(QString,int)\" \"%s\" %d\n", (const char*)reader->m_fontname, reader->m_textsize); 3845 fprintf(f, "msg \"Format/SetFont(QString,int)\" \"%s\" %d\n", (const char*)reader->m_fontname, reader->m_textsize);
3846 fprintf(f, "msg \"Navigation/Page/LineScroll(int)\" %d\n", (reader->m_bpagemode) ? 1:0); 3846 fprintf(f, "msg \"Navigation/Page/LineScroll(int)\" %d\n", (reader->m_bpagemode) ? 1:0);
3847 fprintf(f, "msg \"Format/Ideogram/Word(int)\" %d\n", (reader->m_bMonoSpaced) ? 1:0); 3847 fprintf(f, "msg \"Format/Ideogram/Word(int)\" %d\n", (reader->m_bMonoSpaced) ? 1:0);
3848 fprintf(f, "msg \"Format/Encoding(QString)\" \"%s\"\n", (const char*)m_EncodingAction[reader->m_encd]->text()); 3848 fprintf(f, "msg \"Format/Encoding(QString)\" \"%s\"\n", (const char*)m_EncodingAction[reader->m_encd]->text());
3849 fprintf(f, "msg \"Format/SetWidth(int)\" %d\n", reader->m_charpc); 3849 fprintf(f, "msg \"Format/SetWidth(int)\" %d\n", reader->m_charpc);
3850 fprintf(f, "msg \"Navigation/SetOverlap(int)\" %d\n", reader->m_overlap); 3850 fprintf(f, "msg \"Navigation/SetOverlap(int)\" %d\n", reader->m_overlap);
3851 fprintf(f, "msg \"Layout/Remap(int)\" %d\n", (reader->bremap) ? 1:0); 3851 fprintf(f, "msg \"Layout/Remap(int)\" %d\n", (reader->bremap) ? 1:0);
3852 fprintf(f, "msg \"Layout/Embolden(int)\" %d\n", (reader->bmakebold) ? 1:0); 3852 fprintf(f, "msg \"Layout/Embolden(int)\" %d\n", (reader->bmakebold) ? 1:0);
3853 fprintf(f, "msg \"File/Continuous(int)\" %d\n", (reader->m_continuousDocument) ? 1:0); 3853 fprintf(f, "msg \"File/Continuous(int)\" %d\n", (reader->m_continuousDocument) ? 1:0);
3854 fprintf(f, "msg \"File/SetDictionary(QString)\" \"%s/%s\"\n", (const char *)m_targetapp, (const char *)m_targetmsg); 3854 fprintf(f, "msg \"File/SetDictionary(QString)\" \"%s/%s\"\n", (const char *)m_targetapp, (const char *)m_targetmsg);
3855#ifdef _SCROLLPIPE 3855#ifdef _SCROLLPIPE
3856 fprintf(f, "msg \"File/SetScrollTarget(QString)\" \"%s\"\n", (const char *)reader->m_pipetarget); 3856 fprintf(f, "msg \"File/SetScrollTarget(QString)\" \"%s\"\n", (const char *)reader->m_pipetarget);
3857#endif 3857#endif
3858 fprintf(f, "msg \"File/Two/OneTouch(int)\" %d\n", (m_twoTouch) ? 1:0); 3858 fprintf(f, "msg \"File/Two/OneTouch(int)\" %d\n", (m_twoTouch) ? 1:0);
3859 fprintf(f, "msg \"Target/Annotation(int)\" %d\n", (m_doAnnotation) ? 1:0); 3859 fprintf(f, "msg \"Target/Annotation(int)\" %d\n", (m_doAnnotation) ? 1:0);
3860 fprintf(f, "msg \"Target/Dictionary(int)\" %d\n", (m_doDictionary) ? 1:0); 3860 fprintf(f, "msg \"Target/Dictionary(int)\" %d\n", (m_doDictionary) ? 1:0);
3861 fprintf(f, "msg \"Target/Clipboard(int)\" %d\n", (m_doClipboard) ? 1:0); 3861 fprintf(f, "msg \"Target/Clipboard(int)\" %d\n", (m_doClipboard) ? 1:0);
3862 fprintf(f, "msg \"File/Action(QString)\" \"%s\"\n", (const char *)m_buttonAction[m_spaceTarget]->text()); 3862 fprintf(f, "msg \"File/Action(QString)\" \"%s\"\n", (const char *)m_buttonAction[m_spaceTarget]->text());
3863 fprintf(f, "msg \"Update(int)\" 1\n"); 3863 fprintf(f, "msg \"Update(int)\" 1\n");
3864 fprintf(f, "msg \"info(QString)\" \"All Done\"\n"); 3864 fprintf(f, "msg \"info(QString)\" \"All Done\"\n");
3865 fclose(f); 3865 fclose(f);
3866 chmod(sname, S_IXUSR | S_IXGRP | S_IXOTH); 3866 chmod(sname, S_IXUSR | S_IXGRP | S_IXOTH);
3867 } 3867 }
3868} 3868}
3869 3869
3870void QTReaderApp::SaveConfig() 3870void QTReaderApp::SaveConfig()
3871{ 3871{
3872 m_nRegAction = cSetConfigName; 3872 m_nRegAction = cSetConfigName;
3873 regEdit->setText(""); 3873 regEdit->setText("");
3874 do_regedit(); 3874 do_regedit();
3875} 3875}
3876 3876
3877void QTReaderApp::do_saveconfig(const QString& _txt) 3877void QTReaderApp::do_saveconfig(const QString& _txt)
3878{ 3878{
3879 SaveScript(Global::applicationFileName(APPDIR "/scripts", _txt)); 3879 SaveScript(Global::applicationFileName(APPDIR "/scripts", _txt));
3880} 3880}
3881#endif 3881#endif
3882 3882
3883#ifdef _SCROLLPIPE 3883#ifdef _SCROLLPIPE
3884void QTReaderApp::setpipetarget() 3884void QTReaderApp::setpipetarget()
3885{ 3885{
3886 m_nRegAction = cSetPipeTarget; 3886 m_nRegAction = cSetPipeTarget;
3887 QString text = (reader->m_pipetarget.isEmpty()) ? QString("") : reader->m_pipetarget; 3887 QString text = (reader->m_pipetarget.isEmpty()) ? QString("") : reader->m_pipetarget;
3888 regEdit->setText(text); 3888 regEdit->setText(text);
3889 do_regedit(); 3889 do_regedit();
3890} 3890}
3891 3891
3892void QTReaderApp::do_setpipetarget(const QString& _txt) 3892void QTReaderApp::do_setpipetarget(const QString& _txt)
3893{ 3893{
3894 reader->m_pipetarget = _txt; 3894 reader->m_pipetarget = _txt;
3895} 3895}
3896 3896
3897void QTReaderApp::setpause(bool sfs) 3897void QTReaderApp::setpause(bool sfs)
3898{ 3898{
3899 reader->m_pauseAfterEachPara = sfs; 3899 reader->m_pauseAfterEachPara = sfs;
3900} 3900}
3901#endif 3901#endif
3902 3902
3903void QTReaderApp::monospace(bool _b) 3903void QTReaderApp::monospace(bool _b)
3904{ 3904{
3905 reader->setmono(_b); 3905 reader->setmono(_b);
3906} 3906}
3907 3907
3908bool QTReaderApp::readconfig(const QString& _txt, bool full=false) 3908bool QTReaderApp::readconfig(const QString& _txt, bool full=false)
3909{ 3909{
3910#ifdef USEQPE 3910#ifdef USEQPE
3911 QString configname; 3911 QString configname;
3912 Config::Domain dom; 3912 Config::Domain dom;
3913 3913
3914 if (full) 3914 if (full)
3915 { 3915 {
3916 configname = _txt; 3916 configname = _txt;
3917 dom = Config::User; 3917 dom = Config::User;
3918 } 3918 }
3919 else 3919 else
3920 { 3920 {
3921 configname = Global::applicationFileName(APPDIR "/configs", _txt); 3921 configname = Global::applicationFileName(APPDIR "/configs", _txt);
3922 QFileInfo fm(configname); 3922 QFileInfo fm(configname);
3923 if ( !fm.exists() ) return false; 3923 if ( !fm.exists() ) return false;
3924 dom = Config::File; 3924 dom = Config::File;
3925 } 3925 }
3926 3926
3927 Config config(configname, dom); 3927 Config config(configname, dom);
3928 config.setGroup( "View" ); 3928 config.setGroup( "View" );
3929 3929
3930#else 3930#else
3931 QFileInfo fi; 3931 QFileInfo fi;
3932 if (full) 3932 if (full)
3933 { 3933 {
3934 QDir d = QDir::home(); // "/" 3934 QDir d = QDir::home(); // "/"
3935 if ( !d.cd(_txt) ) 3935 if ( !d.cd(_txt) )
3936 { // "/tmp" 3936 { // "/tmp"
3937 qWarning( "Cannot find the \"~/%s\" directory", (const char*)_txt ); 3937 qWarning( "Cannot find the \"~/%s\" directory", (const char*)_txt );
3938 d = QDir::home(); 3938 d = QDir::home();
3939 d.mkdir(_txt); 3939 d.mkdir(_txt);
3940 d.cd(_txt); 3940 d.cd(_txt);
3941 } 3941 }
3942 fi.setFile(d, INIFILE); 3942 fi.setFile(d, INIFILE);
3943 } 3943 }
3944 else 3944 else
3945 { 3945 {
3946 QDir d = QDir::home(); // "/" 3946 QDir d = QDir::home(); // "/"
3947 if ( !d.cd(APPDIR) ) 3947 if ( !d.cd(APPDIR) )
3948 { // "/tmp" 3948 { // "/tmp"
3949 qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); 3949 qWarning( "Cannot find the \"~/" APPDIR "\" directory" );
3950 d = QDir::home(); 3950 d = QDir::home();
3951 d.mkdir(APPDIR); 3951 d.mkdir(APPDIR);
3952 d.cd(APPDIR); 3952 d.cd(APPDIR);
3953 } 3953 }
3954 if ( !d.cd("configs") ) 3954 if ( !d.cd("configs") )
3955 { // "/tmp" 3955 { // "/tmp"
3956 qWarning( "Cannot find the \"~/" APPDIR "/configs\" directory" ); 3956 qWarning( "Cannot find the \"~/" APPDIR "/configs\" directory" );
3957 d = QDir::home(); 3957 d = QDir::home();
3958 d.mkdir("configs"); 3958 d.mkdir("configs");
3959 d.cd("configs"); 3959 d.cd("configs");
3960 } 3960 }
3961 fi.setFile(d, _txt); 3961 fi.setFile(d, _txt);
3962 } 3962 }
3963#ifdef _WINDOWS 3963#ifdef _WINDOWS
3964 struct stat fnstat; 3964 struct stat fnstat;
3965 if (stat((const char *)reader->m_lastfile, &fnstat) == 0) return false; // get round fileinfo bug on windows 3965 if (stat((const char *)reader->m_lastfile, &fnstat) == 0) return false; // get round fileinfo bug on windows
3966#else 3966#else
3967 if (!fi.exists()) return false; 3967 if (!fi.exists()) return false;
3968#endif 3968#endif
3969 Config config(fi.absFilePath()); 3969 Config config(fi.absFilePath());
3970#endif 3970#endif
3971 if (full) 3971 if (full)
3972 { 3972 {
3973 config.setGroup("Toolbar"); 3973 config.setGroup("Toolbar");
3974 m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", false); 3974 m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", false);
3975 m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", 1); 3975 m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", 1);
3976 m_tbposition = (ToolBarDock)config.readNumEntry("Position", 2); 3976 m_tbposition = (ToolBarDock)config.readNumEntry("Position", 2);
3977 } 3977 }
3978 config.setGroup( "View" ); 3978 config.setGroup( "View" );
3979 m_bFloatingDialog = config.readBoolEntry("FloatDialogs", false); 3979 m_bFloatingDialog = config.readBoolEntry("FloatDialogs", false);
3980 reader->bstripcr = config.readBoolEntry( "StripCr", true ); 3980 reader->bstripcr = config.readBoolEntry( "StripCr", true );
3981 reader->bfulljust = config.readBoolEntry( "FullJust", false ); 3981 reader->bfulljust = config.readBoolEntry( "FullJust", false );
3982 reader->setextraspace(config.readNumEntry( "ExtraSpace", 0 )); 3982 reader->setextraspace(config.readNumEntry( "ExtraSpace", 0 ));
3983 reader->setlead(config.readNumEntry( "ExtraLead", 0 )); 3983 reader->setlead(config.readNumEntry( "ExtraLead", 0 ));
3984 reader->btextfmt = config.readBoolEntry( "TextFmt", false ); 3984 reader->btextfmt = config.readBoolEntry( "TextFmt", false );
3985 reader->bautofmt = config.readBoolEntry( "AutoFmt", true ); 3985 reader->bautofmt = config.readBoolEntry( "AutoFmt", true );
3986 reader->bstriphtml = config.readBoolEntry( "StripHtml", false ); 3986 reader->bstriphtml = config.readBoolEntry( "StripHtml", false );
3987 reader->bpeanut = config.readBoolEntry( "Peanut", false ); 3987 reader->bpeanut = config.readBoolEntry( "Peanut", false );
3988 reader->bdehyphen = config.readBoolEntry( "Dehyphen", false ); 3988 reader->bdehyphen = config.readBoolEntry( "Dehyphen", false );
3989 reader->bdepluck = config.readBoolEntry( "Depluck", false ); 3989 reader->bdepluck = config.readBoolEntry( "Depluck", false );
3990 reader->bdejpluck = config.readBoolEntry( "Dejpluck", false ); 3990 reader->bdejpluck = config.readBoolEntry( "Dejpluck", false );
3991 reader->bonespace = config.readBoolEntry( "OneSpace", false ); 3991 reader->bonespace = config.readBoolEntry( "OneSpace", false );
3992 reader->bunindent = config.readBoolEntry( "Unindent", false ); 3992 reader->bunindent = config.readBoolEntry( "Unindent", false );
3993 reader->brepara = config.readBoolEntry( "Repara", false ); 3993 reader->brepara = config.readBoolEntry( "Repara", false );
3994 reader->bdblspce = config.readBoolEntry( "DoubleSpace", false ); 3994 reader->bdblspce = config.readBoolEntry( "DoubleSpace", false );
3995 reader->bindenter = config.readNumEntry( "Indent", 0 ); 3995 reader->bindenter = config.readNumEntry( "Indent", 0 );
3996 reader->m_textsize = config.readNumEntry( "FontSize", 12 ); 3996 reader->m_textsize = config.readNumEntry( "FontSize", 12 );
3997 reader->m_delay = config.readNumEntry( "ScrollDelay", 5184); 3997 reader->m_delay = config.readNumEntry( "ScrollDelay", 5184);
3998 if (full) 3998 if (full)
3999 { 3999 {
4000 reader->m_lastfile = config.readEntry( "LastFile", QString::null ); 4000 reader->m_lastfile = config.readEntry( "LastFile", QString::null );
4001 reader->m_lastposn = config.readNumEntry( "LastPosn", 0 ); 4001 reader->m_lastposn = config.readNumEntry( "LastPosn", 0 );
4002 } 4002 }
4003 reader->m_bpagemode = config.readBoolEntry( "PageMode", true ); 4003 reader->m_bpagemode = config.readBoolEntry( "PageMode", true );
4004 reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", false); 4004 reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", false);
4005 reader->m_swapmouse = config.readBoolEntry( "SwapMouse", false); 4005 reader->m_swapmouse = config.readBoolEntry( "SwapMouse", false);
4006 reader->m_fontname = config.readEntry( "Fontname", "helvetica" ); 4006 reader->m_fontname = config.readEntry( "Fontname", "helvetica" );
4007 reader->m_encd = config.readNumEntry( "Encoding", 0 ); 4007 reader->m_encd = config.readNumEntry( "Encoding", 0 );
4008 reader->m_charpc = config.readNumEntry( "CharSpacing", 100 ); 4008 reader->m_charpc = config.readNumEntry( "CharSpacing", 100 );
4009 reader->m_overlap = config.readNumEntry( "Overlap", 0 ); 4009 reader->m_overlap = config.readNumEntry( "Overlap", 0 );
4010 reader->m_border = config.readNumEntry( "Margin", 6 ); 4010 reader->m_border = config.readNumEntry( "Margin", 6 );
4011#ifdef REPALM 4011#ifdef REPALM
4012 reader->brepalm = config.readBoolEntry( "Repalm", true ); 4012 reader->brepalm = config.readBoolEntry( "Repalm", true );
4013#endif 4013#endif
4014 reader->bremap = config.readBoolEntry( "Remap", true ); 4014 reader->bremap = config.readBoolEntry( "Remap", true );
4015 reader->bmakebold = config.readBoolEntry( "MakeBold", false ); 4015 reader->bmakebold = config.readBoolEntry( "MakeBold", false );
4016 reader->setContinuous(config.readBoolEntry( "Continuous", true )); 4016 reader->setContinuous(config.readBoolEntry( "Continuous", true ));
4017 m_targetapp = config.readEntry( "TargetApp", QString::null ); 4017 m_targetapp = config.readEntry( "TargetApp", QString::null );
4018 m_targetmsg = config.readEntry( "TargetMsg", QString::null ); 4018 m_targetmsg = config.readEntry( "TargetMsg", QString::null );
4019#ifdef _SCROLLPIPE 4019#ifdef _SCROLLPIPE
4020 reader->m_pipetarget = config.readEntry( "PipeTarget", QString::null ); 4020 reader->m_pipetarget = config.readEntry( "PipeTarget", QString::null );
4021 reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", true ); 4021 reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", true );
4022#endif 4022#endif
4023 m_twoTouch = config.readBoolEntry( "TwoTouch", false); 4023 m_twoTouch = config.readBoolEntry( "TwoTouch", false);
4024 m_doAnnotation = config.readBoolEntry( "Annotation", false); 4024 m_doAnnotation = config.readBoolEntry( "Annotation", false);
4025 m_doDictionary = config.readBoolEntry( "Dictionary", false); 4025 m_doDictionary = config.readBoolEntry( "Dictionary", false);
4026 m_doClipboard = config.readBoolEntry( "Clipboard", false); 4026 m_doClipboard = config.readBoolEntry( "Clipboard", false);
4027 m_spaceTarget = (ActionTypes)config.readNumEntry("SpaceTarget", cesAutoScroll); 4027 m_spaceTarget = (ActionTypes)config.readNumEntry("SpaceTarget", cesAutoScroll);
4028 m_escapeTarget = (ActionTypes)config.readNumEntry("EscapeTarget", cesNone); 4028 m_escapeTarget = (ActionTypes)config.readNumEntry("EscapeTarget", cesNone);
4029 m_returnTarget = (ActionTypes)config.readNumEntry("ReturnTarget", cesFullScreen); 4029 m_returnTarget = (ActionTypes)config.readNumEntry("ReturnTarget", cesFullScreen);
4030 m_leftTarget = (ActionTypes)config.readNumEntry("LeftTarget", cesZoomOut); 4030 m_leftTarget = (ActionTypes)config.readNumEntry("LeftTarget", cesZoomOut);
4031 m_rightTarget = (ActionTypes)config.readNumEntry("RightTarget", cesZoomIn); 4031 m_rightTarget = (ActionTypes)config.readNumEntry("RightTarget", cesZoomIn);
4032 m_upTarget = (ActionTypes)config.readNumEntry("UpTarget", cesPageUp); 4032 m_upTarget = (ActionTypes)config.readNumEntry("UpTarget", cesPageUp);
4033 m_downTarget = (ActionTypes)config.readNumEntry("DownTarget", cesPageDown); 4033 m_downTarget = (ActionTypes)config.readNumEntry("DownTarget", cesPageDown);
4034 4034
4035 m_leftScroll = config.readBoolEntry("LeftScroll", false); 4035 m_leftScroll = config.readBoolEntry("LeftScroll", false);
4036 m_rightScroll = config.readBoolEntry("RightScroll", false); 4036 m_rightScroll = config.readBoolEntry("RightScroll", false);
4037 m_upScroll = config.readBoolEntry("UpScroll", true); 4037 m_upScroll = config.readBoolEntry("UpScroll", true);
4038 m_downScroll = config.readBoolEntry("DownScroll", true); 4038 m_downScroll = config.readBoolEntry("DownScroll", true);
4039 m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", false); 4039 m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", false);
4040 reader->setBaseSize(config.readNumEntry( "Basesize", 10 )); 4040 reader->setBaseSize(config.readNumEntry( "Basesize", 10 ));
4041 reader->setTwoTouch(m_twoTouch); 4041 reader->setTwoTouch(m_twoTouch);
4042 4042
4043 m_touch_action->setOn(m_twoTouch); 4043 m_touch_action->setOn(m_twoTouch);
4044 m_setmono_action->setOn(reader->m_bMonoSpaced); 4044 m_setmono_action->setOn(reader->m_bMonoSpaced);
4045 setfontHelper(reader->m_fontname); 4045 setfontHelper(reader->m_fontname);
4046 if (full) 4046 if (full)
4047 { 4047 {
4048 addtoolbars(&config); 4048 addtoolbars(&config);
4049 } 4049 }
4050 reader->setfilter(reader->getfilter()); 4050 reader->setfilter(reader->getfilter());
4051 reader->refresh(); 4051 reader->refresh();
4052 return true; 4052 return true;
4053} 4053}
4054 4054
4055bool QTReaderApp::PopulateConfig(const char* tgtdir) 4055bool QTReaderApp::PopulateConfig(const char* tgtdir)
4056{ 4056{
4057 bkmkselector->clear(); 4057 bkmkselector->clear();
4058 bkmkselector->setText("Cancel"); 4058 bkmkselector->setText("Cancel");
4059#ifndef USEQPE 4059#ifndef USEQPE
4060 int cnt = 0; 4060 int cnt = 0;
4061 4061
4062 QDir d = QDir::home(); // "/" 4062 QDir d = QDir::home(); // "/"
4063 if ( !d.cd(APPDIR) ) { // "/tmp" 4063 if ( !d.cd(APPDIR) ) { // "/tmp"
4064 qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); 4064 qWarning( "Cannot find the \"~/" APPDIR "\" directory" );
4065 d = QDir::home(); 4065 d = QDir::home();
4066 d.mkdir(APPDIR); 4066 d.mkdir(APPDIR);
4067 d.cd(APPDIR); 4067 d.cd(APPDIR);
4068 } 4068 }
4069 if ( !d.cd(tgtdir) ) { // "/tmp" 4069 if ( !d.cd(tgtdir) ) { // "/tmp"
4070 qWarning( "Cannot find the \"~/" APPDIR "/%s\" directory", tgtdir ); 4070 qWarning( "Cannot find the \"~/" APPDIR "/%s\" directory", tgtdir );
4071 d = QDir::home(); 4071 d = QDir::home();
4072 d.mkdir(tgtdir); 4072 d.mkdir(tgtdir);
4073 d.cd(tgtdir); 4073 d.cd(tgtdir);
4074 } 4074 }
4075 d.setFilter( QDir::Files | QDir::NoSymLinks ); 4075 d.setFilter( QDir::Files | QDir::NoSymLinks );
4076// d.setSorting( QDir::Size | QDir::Reversed ); 4076// d.setSorting( QDir::Size | QDir::Reversed );
4077 4077
4078 const QFileInfoList *list = d.entryInfoList(); 4078 const QFileInfoList *list = d.entryInfoList();
4079 QFileInfoListIterator it( *list ); // create list iterator 4079 QFileInfoListIterator it( *list ); // create list iterator
4080 QFileInfo *fi; // pointer for traversing 4080 QFileInfo *fi; // pointer for traversing
4081 4081
4082 while ( (fi=it.current()) ) { // for each file... 4082 while ( (fi=it.current()) ) { // for each file...
4083 4083
4084 bkmkselector->insertItem(fi->fileName()); 4084 bkmkselector->insertItem(fi->fileName());
4085 cnt++; 4085 cnt++;
4086 4086
4087 //qDebug( "%10li %s", fi->size(), fi->fileName().data() ); 4087 //qDebug( "%10li %s", fi->size(), fi->fileName().data() );
4088 ++it; // goto next list element 4088 ++it; // goto next list element
4089 } 4089 }
4090 4090
4091#else /* USEQPE */ 4091#else /* USEQPE */
4092 int cnt = 0; 4092 int cnt = 0;
4093 DIR *d; 4093 DIR *d;
4094 char* finaldir; 4094 char* finaldir;
4095 finaldir = new char[strlen(APPDIR)+1+strlen(tgtdir)+1]; 4095 finaldir = new char[strlen(APPDIR)+1+strlen(tgtdir)+1];
4096 strcpy(finaldir, APPDIR); 4096 strcpy(finaldir, APPDIR);
4097 strcat(finaldir, "/"); 4097 strcat(finaldir, "/");
4098 strcat(finaldir, tgtdir); 4098 strcat(finaldir, tgtdir);
4099 d = opendir((const char *)Global::applicationFileName(finaldir,"")); 4099 d = opendir((const char *)Global::applicationFileName(finaldir,""));
4100 4100
4101 while(1) 4101 while(1)
4102 { 4102 {
4103 struct dirent* de; 4103 struct dirent* de;
4104 struct stat buf; 4104 struct stat buf;
4105 de = readdir(d); 4105 de = readdir(d);
4106 if (de == NULL) break; 4106 if (de == NULL) break;
4107 4107
4108 if (lstat((const char *)Global::applicationFileName(finaldir,de->d_name),&buf) == 0 && S_ISREG(buf.st_mode)) 4108 if (lstat((const char *)Global::applicationFileName(finaldir,de->d_name),&buf) == 0 && S_ISREG(buf.st_mode))
4109 { 4109 {
4110 bkmkselector->insertItem(de->d_name); 4110 bkmkselector->insertItem(de->d_name);
4111 cnt++; 4111 cnt++;
4112 } 4112 }
4113 } 4113 }
4114 delete [] finaldir; 4114 delete [] finaldir;
4115 closedir(d); 4115 closedir(d);
4116#endif 4116#endif
4117 return (cnt > 0); 4117 return (cnt > 0);
4118} 4118}
4119 4119
4120void QTReaderApp::LoadConfig() 4120void QTReaderApp::LoadConfig()
4121{ 4121{
4122 if (PopulateConfig("configs")) 4122 if (PopulateConfig("configs"))
4123 { 4123 {
4124 editorStack->raiseWidget( bkmkselector ); 4124 editorStack->raiseWidget( bkmkselector );
4125 hidetoolbars(); 4125 hidetoolbars();
4126 m_nBkmkAction = cLdConfig; 4126 m_nBkmkAction = cLdConfig;
4127 } 4127 }
4128 else 4128 else
4129 QMessageBox::information(this, PROGNAME, "No config files"); 4129 QMessageBox::information(this, PROGNAME, "No config files");
4130} 4130}
4131 4131
4132void QTReaderApp::TidyConfig() 4132void QTReaderApp::TidyConfig()
4133{ 4133{
4134 if (PopulateConfig("configs")) 4134 if (PopulateConfig("configs"))
4135 { 4135 {
4136 editorStack->raiseWidget( bkmkselector ); 4136 editorStack->raiseWidget( bkmkselector );
4137 hidetoolbars(); 4137 hidetoolbars();
4138 m_nBkmkAction = cRmConfig; 4138 m_nBkmkAction = cRmConfig;
4139 } 4139 }
4140 else 4140 else
4141 QMessageBox::information(this, PROGNAME, "No config files"); 4141 QMessageBox::information(this, PROGNAME, "No config files");
4142} 4142}
4143 4143
4144void QTReaderApp::ExportLinks() 4144void QTReaderApp::ExportLinks()
4145{ 4145{
4146 if (PopulateConfig("urls")) 4146 if (PopulateConfig("urls"))
4147 { 4147 {
4148 editorStack->raiseWidget( bkmkselector ); 4148 editorStack->raiseWidget( bkmkselector );
4149 hidetoolbars(); 4149 hidetoolbars();
4150 m_nBkmkAction = cExportLinks; 4150 m_nBkmkAction = cExportLinks;
4151 } 4151 }
4152 else 4152 else
4153 QMessageBox::information(this, PROGNAME, "No url files"); 4153 QMessageBox::information(this, PROGNAME, "No url files");
4154} 4154}
4155 4155
4156void QTReaderApp::OnURLSelected(const QString& href) 4156void QTReaderApp::OnURLSelected(const QString& href)
4157{ 4157{
4158 CURLDialog* urld = new CURLDialog(href, false, this); 4158 CURLDialog* urld = new CURLDialog(href, false, this);
4159 urld->clipboard(m_url_clipboard); 4159 urld->clipboard(m_url_clipboard);
4160 urld->localfile(m_url_localfile); 4160 urld->localfile(m_url_localfile);
4161 urld->globalfile(m_url_globalfile); 4161 urld->globalfile(m_url_globalfile);
4162 if (urld->exec()) 4162 if (urld->exec())
4163 { 4163 {
4164 m_url_clipboard = urld->clipboard(); 4164 m_url_clipboard = urld->clipboard();
4165 m_url_localfile = urld->localfile(); 4165 m_url_localfile = urld->localfile();
4166 m_url_globalfile = urld->globalfile(); 4166 m_url_globalfile = urld->globalfile();
4167 if (m_url_clipboard) 4167 if (m_url_clipboard)
4168 { 4168 {
4169 QClipboard* cb = QApplication::clipboard(); 4169 QClipboard* cb = QApplication::clipboard();
4170 cb->setText(href); 4170 cb->setText(href);
4171 qDebug("<a href=\"%s\">%s</a>", (const char*)href, (const char*)href); 4171 qDebug("<a href=\"%s\">%s</a>", (const char*)href, (const char*)href);
4172 } 4172 }
4173 if (m_url_localfile) 4173 if (m_url_localfile)
4174 { 4174 {
4175 writeUrl(reader->m_string, href); 4175 writeUrl(reader->m_string, href);
4176 } 4176 }
4177 if (m_url_globalfile) 4177 if (m_url_globalfile)
4178 { 4178 {
4179 writeUrl("GlobalURLFile", href); 4179 writeUrl("GlobalURLFile", href);
4180 } 4180 }
4181 } 4181 }
4182 delete urld; 4182 delete urld;
4183} 4183}
4184 4184
4185void QTReaderApp::writeUrl(const QString& file, const QString& href) 4185void QTReaderApp::writeUrl(const QString& file, const QString& href)
4186{ 4186{
4187 QString filename; 4187 QString filename;
4188#ifdef USEQPE 4188#ifdef USEQPE
4189 filename = Global::applicationFileName(APPDIR "/urls", file); 4189 filename = Global::applicationFileName(APPDIR "/urls", file);
4190#else 4190#else
4191 QFileInfo fi; 4191 QFileInfo fi;
4192 QDir d = QDir::home(); // "/" 4192 QDir d = QDir::home(); // "/"
4193 if ( !d.cd(APPDIR) ) 4193 if ( !d.cd(APPDIR) )
4194 { // "/tmp" 4194 { // "/tmp"
4195 qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); 4195 qWarning( "Cannot find the \"~/" APPDIR "\" directory" );
4196 d = QDir::home(); 4196 d = QDir::home();
4197 d.mkdir(APPDIR); 4197 d.mkdir(APPDIR);
4198 d.cd(APPDIR); 4198 d.cd(APPDIR);
4199 } 4199 }
4200 if ( !d.cd("urls") ) 4200 if ( !d.cd("urls") )
4201 { // "/tmp" 4201 { // "/tmp"
4202 qWarning( "Cannot find the \"~/" APPDIR "/urls\" directory" ); 4202 qWarning( "Cannot find the \"~/" APPDIR "/urls\" directory" );
4203 d = QDir::home(); 4203 d = QDir::home();
4204 d.cd(APPDIR); 4204 d.cd(APPDIR);
4205 d.mkdir("urls"); 4205 d.mkdir("urls");
4206 d.cd("urls"); 4206 d.cd("urls");
4207 } 4207 }
4208 fi.setFile(d, file); 4208 fi.setFile(d, file);
4209 filename = fi.absFilePath(); 4209 filename = fi.absFilePath();
4210#endif 4210#endif
4211 FILE* fout = fopen(filename, "a"); 4211 FILE* fout = fopen(filename, "a");
4212 if (fout != NULL) 4212 if (fout != NULL)
4213 { 4213 {
4214 fprintf(fout, "<p><a href=\"%s\">%s</a>\n", (const char*)href, (const char*)href); 4214 fprintf(fout, "<p><a href=\"%s\">%s</a>\n", (const char*)href, (const char*)href);
4215 fclose(fout); 4215 fclose(fout);
4216 } 4216 }
4217 else 4217 else
4218 { 4218 {
4219 QMessageBox::warning(this, PROGNAME, "Problem with writing URL"); 4219 QMessageBox::warning(this, PROGNAME, "Problem with writing URL");
4220 } 4220 }
4221} 4221}
diff --git a/noncore/apps/opie-reader/fileBrowser.cpp b/noncore/apps/opie-reader/fileBrowser.cpp
index ebd14f3..e1cde6c 100644
--- a/noncore/apps/opie-reader/fileBrowser.cpp
+++ b/noncore/apps/opie-reader/fileBrowser.cpp
@@ -1,266 +1,266 @@
1/**************************************************************************** 1/****************************************************************************
2 2
3Derived from a file browser which was 3Derived from a file browser which was
4 4
5** copyright 2001 ljp ljp@llornkcor.com 5** copyright 2001 ljp ljp@llornkcor.com
6 6
7Extensive modification by Tim Wentford to allow it to work in rotated mode 7Extensive modification by Tim Wentford to allow it to work in rotated mode
8 8
9****************************************************************************/ 9****************************************************************************/
10#include "fileBrowser.h" 10#include "fileBrowser.h"
11 11
12#include "QtrListView.h" 12#include "QtrListView.h"
13#include <qlineedit.h> 13#include <qlineedit.h>
14#include <qpushbutton.h> 14#include <qpushbutton.h>
15#ifndef _WINDOWS 15#ifndef _WINDOWS
16#include <unistd.h> 16#include <unistd.h>
17#endif 17#endif
18#include <qlayout.h> 18#include <qlayout.h>
19#ifdef _WINDOWS 19#ifdef _WINDOWS
20#include <direct.h> 20#include <direct.h>
21#endif 21#endif
22 22
23#include <qpe/qpeapplication.h> 23#include <qpe/qpeapplication.h>
24 24
25 25
26fileBrowser::fileBrowser( bool allownew, QWidget* parent, const char* name, bool modal, WFlags fl , const QString filter, const QString iPath ) 26fileBrowser::fileBrowser( bool allownew, QWidget* parent, const char* name, bool modal, WFlags fl , const QString filter, const QString iPath )
27 : QDialog( parent, name, true, 27 : QDialog( parent, name, true,
28 fl/* | WStyle_Customize | WStyle_Tool*/), 28 fl/* | WStyle_Customize | WStyle_Tool*/),
29 filterspec(QDir::All) 29 filterspec(QDir::All)
30{ 30{
31// showMaximized(); 31// showMaximized();
32 if ( !name ) 32 if ( !name )
33 setName( "fileBrowser" ); 33 setName( "fileBrowser" );
34/* 34/*
35 if (parent != NULL) 35 if (parent != NULL)
36 { 36 {
37#ifdef OPIE 37#ifdef OPIE
38 move(0,0); 38 move(0,0);
39 resize( parent->width(), parent->height() ); 39 resize( parent->width(), parent->height() );
40#else 40#else
41 setGeometry(parent->x(), parent->y(), parent->width(), parent->height() ); 41 setGeometry(parent->x(), parent->y(), parent->width(), parent->height() );
42#endif 42#endif
43 } 43 }
44*/ 44*/
45// showFullScreen(); 45// showFullScreen();
46 setCaption(tr( "Browse for file" ) ); 46 setCaption(tr( "Browse for file" ) );
47 filterStr=filter; 47 filterStr=filter;
48 48
49 buttonOk = new QPushButton( this, "buttonOk" ); 49 buttonOk = new QPushButton( this, "buttonOk" );
50 buttonOk->setFixedSize( 25, 25 ); 50 buttonOk->setFixedSize( 25, 25 );
51 buttonOk->setAutoDefault( false ); 51 buttonOk->setAutoDefault( false );
52 buttonOk->setText( tr( "/" ) ); 52 buttonOk->setText( tr( "/" ) );
53 53
54 buttonShowHidden = new QPushButton( this, "buttonShowHidden" ); 54 buttonShowHidden = new QPushButton( this, "buttonShowHidden" );
55// buttonShowHidden->setFixedSize( 50, 25 ); 55// buttonShowHidden->setFixedSize( 50, 25 );
56 buttonShowHidden->setText( tr( "Hidden" ) ); 56 buttonShowHidden->setText( tr( "Hidden" ) );
57 buttonShowHidden->setAutoDefault( false ); 57 buttonShowHidden->setAutoDefault( false );
58 buttonShowHidden->setToggleButton( true ); 58 buttonShowHidden->setToggleButton( true );
59 buttonShowHidden->setOn( false ); 59 buttonShowHidden->setOn( false );
60 60
61 dirLabel = new QLabel(this, "DirLabel"); 61 dirLabel = new QLabel(this, "DirLabel");
62 dirLabel->setAlignment(AlignLeft | AlignVCenter | ExpandTabs | WordBreak); 62 dirLabel->setAlignment(AlignLeft | AlignVCenter | ExpandTabs | WordBreak);
63 dirLabel->setText(currentDir.canonicalPath()); 63 dirLabel->setText(currentDir.canonicalPath());
64 64
65 ListView = new QtrListView( this, "ListView" ); 65 ListView = new QtrListView( this, "ListView" );
66 ListView->addColumn( tr( "Name" ) ); 66 ListView->addColumn( tr( "Name" ) );
67 ListView->setSorting( 2, FALSE); 67 ListView->setSorting( 2, FALSE);
68 ListView->addColumn( tr( "Size" ) ); 68 ListView->addColumn( tr( "Size" ) );
69 ListView->setSelectionMode(QListView::Single); 69 ListView->setSelectionMode(QListView::Single);
70 ListView->setAllColumnsShowFocus( TRUE ); 70 ListView->setAllColumnsShowFocus( TRUE );
71 ListView->setColumnWidthMode(0, QListView::Manual); 71 ListView->setColumnWidthMode(0, QListView::Manual);
72 ListView->setColumnWidthMode(1, QListView::Manual); 72 ListView->setColumnWidthMode(1, QListView::Manual);
73 73
74 // signals and slots connections 74 // signals and slots connections
75 connect( buttonShowHidden, SIGNAL( toggled(bool) ), this, SLOT( setHidden(bool) ) ); 75 connect( buttonShowHidden, SIGNAL( toggled(bool) ), this, SLOT( setHidden(bool) ) );
76 connect( buttonOk, SIGNAL( clicked() ), this, SLOT( OnRoot() ) ); 76 connect( buttonOk, SIGNAL( clicked() ), this, SLOT( OnRoot() ) );
77 connect( ListView, SIGNAL(doubleClicked( QListViewItem*)), SLOT(listDoubleClicked(QListViewItem *)) ); 77 connect( ListView, SIGNAL(doubleClicked(QListViewItem*)), SLOT(listDoubleClicked(QListViewItem*)) );
78 connect( ListView, SIGNAL(clicked( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); 78 connect( ListView, SIGNAL(clicked(QListViewItem*)), SLOT(listClicked(QListViewItem*)) );
79 connect( ListView, SIGNAL(OnOKButton( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); 79 connect( ListView, SIGNAL(OnOKButton(QListViewItem*)), SLOT(listClicked(QListViewItem*)) );
80 connect( ListView, SIGNAL(OnCentreButton( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); 80 connect( ListView, SIGNAL(OnCentreButton(QListViewItem*)), SLOT(listClicked(QListViewItem*)) );
81 connect( ListView, SIGNAL(OnCancelButton()), SLOT(OnCancel()) ); 81 connect( ListView, SIGNAL(OnCancelButton()), SLOT(OnCancel()) );
82 82
83 QVBoxLayout* grid = new QVBoxLayout(this); 83 QVBoxLayout* grid = new QVBoxLayout(this);
84 QHBoxLayout* hgrid = new QHBoxLayout(grid); 84 QHBoxLayout* hgrid = new QHBoxLayout(grid);
85 hgrid->addWidget(dirLabel,1); 85 hgrid->addWidget(dirLabel,1);
86 hgrid->addWidget(buttonShowHidden); 86 hgrid->addWidget(buttonShowHidden);
87 hgrid->addWidget(buttonOk); 87 hgrid->addWidget(buttonOk);
88 grid->addWidget(ListView,1); 88 grid->addWidget(ListView,1);
89 if (allownew) 89 if (allownew)
90 { 90 {
91 m_filename = new QLineEdit(this); 91 m_filename = new QLineEdit(this);
92 grid->addWidget(m_filename); 92 grid->addWidget(m_filename);
93 connect( m_filename, SIGNAL( returnPressed() ), this, SLOT( onReturn() )); 93 connect( m_filename, SIGNAL( returnPressed() ), this, SLOT( onReturn() ));
94 } 94 }
95 else 95 else
96 { 96 {
97 m_filename = NULL; 97 m_filename = NULL;
98 } 98 }
99 99
100 if (QFileInfo(iPath).exists()) 100 if (QFileInfo(iPath).exists())
101 { 101 {
102 currentDir.setPath(iPath); 102 currentDir.setPath(iPath);
103#ifdef _WINDOWS 103#ifdef _WINDOWS
104 _chdir(iPath.latin1()); 104 _chdir(iPath.latin1());
105#else 105#else
106 chdir(iPath.latin1()); 106 chdir(iPath.latin1());
107#endif 107#endif
108 } 108 }
109 else 109 else
110 { 110 {
111 currentDir.setPath(QDir::currentDirPath()); 111 currentDir.setPath(QDir::currentDirPath());
112 chdir(QDir::currentDirPath().latin1()); 112 chdir(QDir::currentDirPath().latin1());
113 } 113 }
114 114
115 populateList(); 115 populateList();
116 116
117 if (modal) 117 if (modal)
118 QPEApplication::showDialog( this ); 118 QPEApplication::showDialog( this );
119} 119}
120 120
121void fileBrowser::resizeEvent(QResizeEvent* e) 121void fileBrowser::resizeEvent(QResizeEvent* e)
122{ 122{
123 ListView->setColumnWidth(1,(ListView->width())/4); 123 ListView->setColumnWidth(1,(ListView->width())/4);
124 ListView->setColumnWidth(0,ListView->width()-20-ListView->columnWidth(1)); 124 ListView->setColumnWidth(0,ListView->width()-20-ListView->columnWidth(1));
125} 125}
126 126
127fileBrowser::~fileBrowser() 127fileBrowser::~fileBrowser()
128{ 128{
129} 129}
130 130
131 131
132void fileBrowser::populateList() 132void fileBrowser::populateList()
133{ 133{
134 ListView->clear(); 134 ListView->clear();
135////qDebug(currentDir.canonicalPath()); 135////qDebug(currentDir.canonicalPath());
136// currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks ); 136// currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks );
137 currentDir.setFilter( filterspec ); 137 currentDir.setFilter( filterspec );
138 currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 138 currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
139 currentDir.setMatchAllDirs(TRUE); 139 currentDir.setMatchAllDirs(TRUE);
140 140
141 currentDir.setNameFilter(filterStr); 141 currentDir.setNameFilter(filterStr);
142// currentDir.setNameFilter("*.txt;*.etx"); 142// currentDir.setNameFilter("*.txt;*.etx");
143 QString fileL, fileS; 143 QString fileL, fileS;
144 const QFileInfoList *list = currentDir.entryInfoList(); 144 const QFileInfoList *list = currentDir.entryInfoList();
145 QFileInfoListIterator it(*list); 145 QFileInfoListIterator it(*list);
146 QFileInfo *fi; 146 QFileInfo *fi;
147 while ( (fi=it.current()) ) 147 while ( (fi=it.current()) )
148 { 148 {
149 if (fi->fileName() != ".") 149 if (fi->fileName() != ".")
150 { 150 {
151 fileS.sprintf( "%10li", fi->size() ); 151 fileS.sprintf( "%10li", fi->size() );
152 fileL.sprintf( "%s",fi->fileName().data() ); 152 fileL.sprintf( "%s",fi->fileName().data() );
153 if( fi->isDir() ) 153 if( fi->isDir() )
154 { 154 {
155 fileL+="/"; 155 fileL+="/";
156 } 156 }
157 else 157 else
158 { 158 {
159//// qDebug("Not a dir: "+currentDir.canonicalPath()+fileL); 159//// qDebug("Not a dir: "+currentDir.canonicalPath()+fileL);
160 } 160 }
161 new QListViewItem( ListView,fileL,fileS ); 161 new QListViewItem( ListView,fileL,fileS );
162 } 162 }
163 ++it; 163 ++it;
164 } 164 }
165 ListView->setSorting( 2, FALSE); 165 ListView->setSorting( 2, FALSE);
166 dirLabel->setText("Current Directory:\n"+currentDir.canonicalPath()); 166 dirLabel->setText("Current Directory:\n"+currentDir.canonicalPath());
167 ListView->setFocus(); 167 ListView->setFocus();
168} 168}
169 169
170void fileBrowser::upDir() 170void fileBrowser::upDir()
171{ 171{
172//// qDebug(currentDir.canonicalPath()); 172//// qDebug(currentDir.canonicalPath());
173} 173}
174 174
175void fileBrowser::listClicked(QListViewItem *selectedItem) 175void fileBrowser::listClicked(QListViewItem *selectedItem)
176{ 176{
177 if (selectedItem == NULL) return; 177 if (selectedItem == NULL) return;
178 QString strItem=selectedItem->text(0); 178 QString strItem=selectedItem->text(0);
179 179
180//// qDebug("%s", (const char*)strItem); 180//// qDebug("%s", (const char*)strItem);
181 181
182 182
183 QString strSize=selectedItem->text(1); 183 QString strSize=selectedItem->text(1);
184 184
185 strSize.stripWhiteSpace(); 185 strSize.stripWhiteSpace();
186 186
187 bool ok; 187 bool ok;
188 188
189 QFileInfo fi(strItem); 189 QFileInfo fi(strItem);
190 while (fi.isSymLink()) fi.setFile(fi.readLink()); 190 while (fi.isSymLink()) fi.setFile(fi.readLink());
191 if (fi.isDir()) 191 if (fi.isDir())
192 { 192 {
193 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); 193 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem);
194 194
195 if(QDir(strItem).exists()) 195 if(QDir(strItem).exists())
196 { 196 {
197 currentDir.cd(strItem, TRUE); 197 currentDir.cd(strItem, TRUE);
198 populateList(); 198 populateList();
199 } 199 }
200 } else 200 } else
201 { 201 {
202 QListViewItem *selectedItem = ListView->selectedItem(); 202 QListViewItem *selectedItem = ListView->selectedItem();
203 if (selectedItem == NULL) 203 if (selectedItem == NULL)
204 { 204 {
205 filename = ""; 205 filename = "";
206 } 206 }
207 else 207 else
208 { 208 {
209 filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+selectedItem->text(0)); 209 filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+selectedItem->text(0));
210 } 210 }
211 OnOK(); 211 OnOK();
212 } 212 }
213 chdir(strItem.latin1()); 213 chdir(strItem.latin1());
214// 214//
215 215
216} 216}
217 217
218// you may want to switch these 2 functions. I like single clicks 218// you may want to switch these 2 functions. I like single clicks
219void fileBrowser::listDoubleClicked(QListViewItem *selectedItem) 219void fileBrowser::listDoubleClicked(QListViewItem *selectedItem)
220{ 220{
221} 221}
222 222
223QString fileBrowser::getCurrentFile() 223QString fileBrowser::getCurrentFile()
224{ 224{
225 return filename; 225 return filename;
226} 226}
227 227
228void fileBrowser::OnOK() 228void fileBrowser::OnOK()
229{ 229{
230 accept(); 230 accept();
231} 231}
232 232
233void fileBrowser::OnRoot() 233void fileBrowser::OnRoot()
234{ 234{
235 currentDir.cd("/", TRUE); 235 currentDir.cd("/", TRUE);
236 populateList(); 236 populateList();
237 chdir("/"); 237 chdir("/");
238} 238}
239 239
240void fileBrowser::OnCancel() 240void fileBrowser::OnCancel()
241{ 241{
242 reject(); 242 reject();
243} 243}
244 244
245void fileBrowser::setHidden(bool _hidden) 245void fileBrowser::setHidden(bool _hidden)
246{ 246{
247 if (_hidden) 247 if (_hidden)
248 filterspec = QDir::All | QDir::Hidden; 248 filterspec = QDir::All | QDir::Hidden;
249 else 249 else
250 filterspec = QDir::All; 250 filterspec = QDir::All;
251 populateList(); 251 populateList();
252} 252}
253 253
254void fileBrowser::onReturn() 254void fileBrowser::onReturn()
255{ 255{
256 QListViewItem *selectedItem = ListView->selectedItem(); 256 QListViewItem *selectedItem = ListView->selectedItem();
257 if (selectedItem == NULL) 257 if (selectedItem == NULL)
258 { 258 {
259 filename = m_filename->text(); 259 filename = m_filename->text();
260 } 260 }
261 else 261 else
262 { 262 {
263 filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+m_filename->text()); 263 filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+m_filename->text());
264 } 264 }
265 OnOK(); 265 OnOK();
266} 266}
diff --git a/noncore/apps/opie-sheet/mainwindow.cpp b/noncore/apps/opie-sheet/mainwindow.cpp
index 1fb2a3d..061748e 100644
--- a/noncore/apps/opie-sheet/mainwindow.cpp
+++ b/noncore/apps/opie-sheet/mainwindow.cpp
@@ -1,1007 +1,1007 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10/* 10/*
11 * Opie Sheet (formerly Sheet/Qt) 11 * Opie Sheet (formerly Sheet/Qt)
12 * by Serdar Ozler <sozler@sitebest.com> 12 * by Serdar Ozler <sozler@sitebest.com>
13 */ 13 */
14 14
15#include "mainwindow.h" 15#include "mainwindow.h"
16 16
17#include <qpe/resource.h> 17#include <qpe/resource.h>
18#include <qpe/qpeapplication.h> 18#include <qpe/qpeapplication.h>
19 19
20#include <qmessagebox.h> 20#include <qmessagebox.h>
21#include <qradiobutton.h> 21#include <qradiobutton.h>
22 22
23#include "cellformat.h" 23#include "cellformat.h"
24#include "numberdlg.h" 24#include "numberdlg.h"
25#include "textdlg.h" 25#include "textdlg.h"
26#include "sortdlg.h" 26#include "sortdlg.h"
27#include "finddlg.h" 27#include "finddlg.h"
28 28
29#define DEFAULT_NUM_ROWS 300 29#define DEFAULT_NUM_ROWS 300
30#define DEFAULT_NUM_COLS (26*3) 30#define DEFAULT_NUM_COLS (26*3)
31#define DEFAULT_NUM_SHEETS 3 31#define DEFAULT_NUM_SHEETS 3
32 32
33MainWindow::MainWindow(QWidget *parent, const char* n, WFlags fl) 33MainWindow::MainWindow(QWidget *parent, const char* n, WFlags fl)
34 :QMainWindow(parent, n, fl) 34 :QMainWindow(parent, n, fl)
35{ 35{
36 // initialize variables 36 // initialize variables
37 documentModified=FALSE; 37 documentModified=FALSE;
38 38
39 // construct objects 39 // construct objects
40 currentDoc=0; 40 currentDoc=0;
41 fileSelector=new FileSelector("application/sheet-qt", this, QString::null); 41 fileSelector=new FileSelector("application/sheet-qt", this, QString::null);
42 ExcelSelector=new FileSelector("application/excel",this,QString::null,FALSE); 42 ExcelSelector=new FileSelector("application/excel",this,QString::null,FALSE);
43 connect(fileSelector, SIGNAL(closeMe()), this, SLOT(selectorHide())); 43 connect(fileSelector, SIGNAL(closeMe()), this, SLOT(selectorHide()));
44 connect(fileSelector, SIGNAL(newSelected(const DocLnk &)), this, SLOT(selectorFileNew(const DocLnk &))); 44 connect(fileSelector, SIGNAL(newSelected(const DocLnk&)), this, SLOT(selectorFileNew(const DocLnk&)));
45 connect(fileSelector, SIGNAL(fileSelected(const DocLnk &)), this, SLOT(selectorFileOpen(const DocLnk &))); 45 connect(fileSelector, SIGNAL(fileSelected(const DocLnk&)), this, SLOT(selectorFileOpen(const DocLnk&)));
46 connect(ExcelSelector,SIGNAL(fileSelected(const DocLnk &)),this,SLOT(slotImportExcel(const DocLnk &))); 46 connect(ExcelSelector,SIGNAL(fileSelected(const DocLnk&)),this,SLOT(slotImportExcel(const DocLnk&)));
47 connect(ExcelSelector,SIGNAL(closeMe()), this, SLOT(ExcelSelectorHide())); 47 connect(ExcelSelector,SIGNAL(closeMe()), this, SLOT(ExcelSelectorHide()));
48 48
49 49
50 listSheets.setAutoDelete(TRUE); 50 listSheets.setAutoDelete(TRUE);
51 51
52 initActions(); 52 initActions();
53 initMenu(); 53 initMenu();
54 initEditToolbar(); 54 initEditToolbar();
55 initFunctionsToolbar(); 55 initFunctionsToolbar();
56 initStandardToolbar(); 56 initStandardToolbar();
57 initSheet(); 57 initSheet();
58 58
59 // set window title 59 // set window title
60 setCaption(tr("Opie Sheet")); 60 setCaption(tr("Opie Sheet"));
61 61
62 // create sheets 62 // create sheets
63 selectorFileNew(DocLnk()); 63 selectorFileNew(DocLnk());
64} 64}
65 65
66MainWindow::~MainWindow() 66MainWindow::~MainWindow()
67{ 67{
68 if (currentDoc) delete currentDoc; 68 if (currentDoc) delete currentDoc;
69} 69}
70 70
71void MainWindow::documentSave(DocLnk *lnkDoc) 71void MainWindow::documentSave(DocLnk *lnkDoc)
72{ 72{
73 FileManager fm; 73 FileManager fm;
74 QByteArray streamBuffer; 74 QByteArray streamBuffer;
75 QDataStream stream(streamBuffer, IO_WriteOnly); 75 QDataStream stream(streamBuffer, IO_WriteOnly);
76 76
77 typeSheet *currentSheet=findSheet(sheet->getName()); 77 typeSheet *currentSheet=findSheet(sheet->getName());
78 if (!currentSheet) 78 if (!currentSheet)
79 { 79 {
80 QMessageBox::critical(this, tr("Error"), tr("Inconsistency error!")); 80 QMessageBox::critical(this, tr("Error"), tr("Inconsistency error!"));
81 return; 81 return;
82 } 82 }
83 sheet->copySheetData(&currentSheet->data); 83 sheet->copySheetData(&currentSheet->data);
84 stream.writeRawBytes("SQT100", 6); 84 stream.writeRawBytes("SQT100", 6);
85 stream << (Q_UINT32)listSheets.count(); 85 stream << (Q_UINT32)listSheets.count();
86 for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) 86 for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next())
87 { 87 {
88 stream << tempSheet->name << (Q_UINT32)tempSheet->data.count(); 88 stream << tempSheet->name << (Q_UINT32)tempSheet->data.count();
89 for (typeCellData *tempCell=tempSheet->data.first(); tempCell; tempCell=tempSheet->data.next()) 89 for (typeCellData *tempCell=tempSheet->data.first(); tempCell; tempCell=tempSheet->data.next())
90 stream << (Q_UINT32)tempCell->col << (Q_UINT32)tempCell->row << tempCell->borders.right << tempCell->borders.bottom << tempCell->background << (Q_UINT32)tempCell->alignment << tempCell->fontColor << tempCell->font << tempCell->data; 90 stream << (Q_UINT32)tempCell->col << (Q_UINT32)tempCell->row << tempCell->borders.right << tempCell->borders.bottom << tempCell->background << (Q_UINT32)tempCell->alignment << tempCell->fontColor << tempCell->font << tempCell->data;
91 } 91 }
92 92
93 lnkDoc->setType("application/sheet-qt"); 93 lnkDoc->setType("application/sheet-qt");
94 if (!fm.saveFile(*lnkDoc, streamBuffer)) 94 if (!fm.saveFile(*lnkDoc, streamBuffer))
95 { 95 {
96 QMessageBox::critical(this, tr("Error"), tr("File cannot be saved!")); 96 QMessageBox::critical(this, tr("Error"), tr("File cannot be saved!"));
97 return; 97 return;
98 } 98 }
99 documentModified=FALSE; 99 documentModified=FALSE;
100} 100}
101 101
102void MainWindow::documentOpen(const DocLnk &lnkDoc) 102void MainWindow::documentOpen(const DocLnk &lnkDoc)
103{ 103{
104 FileManager fm; 104 FileManager fm;
105 QByteArray streamBuffer; 105 QByteArray streamBuffer;
106 if (!lnkDoc.isValid() || !fm.loadFile(lnkDoc, streamBuffer)) 106 if (!lnkDoc.isValid() || !fm.loadFile(lnkDoc, streamBuffer))
107 { 107 {
108 QMessageBox::critical(this, tr("Error"), tr("File cannot be opened!")); 108 QMessageBox::critical(this, tr("Error"), tr("File cannot be opened!"));
109 documentModified=FALSE; 109 documentModified=FALSE;
110 selectorFileNew(DocLnk()); 110 selectorFileNew(DocLnk());
111 return; 111 return;
112 } 112 }
113 QDataStream stream(streamBuffer, IO_ReadOnly); 113 QDataStream stream(streamBuffer, IO_ReadOnly);
114 114
115 Q_UINT32 countSheet, countCell, i, j, row, col, alignment; 115 Q_UINT32 countSheet, countCell, i, j, row, col, alignment;
116 typeSheet *newSheet; 116 typeSheet *newSheet;
117 typeCellData *newCell; 117 typeCellData *newCell;
118 118
119 char fileFormat[7]; 119 char fileFormat[7];
120 stream.readRawBytes(fileFormat, 6); 120 stream.readRawBytes(fileFormat, 6);
121 fileFormat[6]=0; 121 fileFormat[6]=0;
122 if ((QString)fileFormat!="SQT100") 122 if ((QString)fileFormat!="SQT100")
123 { 123 {
124 QMessageBox::critical(this, tr("Error"), tr("Invalid file format!")); 124 QMessageBox::critical(this, tr("Error"), tr("Invalid file format!"));
125 documentModified=FALSE; 125 documentModified=FALSE;
126 selectorFileNew(DocLnk()); 126 selectorFileNew(DocLnk());
127 return; 127 return;
128 } 128 }
129 129
130 stream >> countSheet; 130 stream >> countSheet;
131 for (i=0; i<countSheet; ++i) 131 for (i=0; i<countSheet; ++i)
132 { 132 {
133 newSheet=new typeSheet; 133 newSheet=new typeSheet;
134 newSheet->data.setAutoDelete(TRUE); 134 newSheet->data.setAutoDelete(TRUE);
135 stream >> newSheet->name >> countCell; 135 stream >> newSheet->name >> countCell;
136 comboSheets->insertItem(newSheet->name); 136 comboSheets->insertItem(newSheet->name);
137 137
138 for (j=0; j<countCell; ++j) 138 for (j=0; j<countCell; ++j)
139 { 139 {
140 newCell=new typeCellData; 140 newCell=new typeCellData;
141 stream >> col >> row >> newCell->borders.right >> newCell->borders.bottom >> newCell->background >> alignment >> newCell->fontColor >> newCell->font >> newCell->data; 141 stream >> col >> row >> newCell->borders.right >> newCell->borders.bottom >> newCell->background >> alignment >> newCell->fontColor >> newCell->font >> newCell->data;
142 newCell->col=col; 142 newCell->col=col;
143 newCell->row=row; 143 newCell->row=row;
144 newCell->alignment=(Qt::AlignmentFlags)alignment; 144 newCell->alignment=(Qt::AlignmentFlags)alignment;
145 newSheet->data.append(newCell); 145 newSheet->data.append(newCell);
146 } 146 }
147 listSheets.append(newSheet); 147 listSheets.append(newSheet);
148 148
149 if (i==0) 149 if (i==0)
150 { 150 {
151 sheet->setName(newSheet->name); 151 sheet->setName(newSheet->name);
152 sheet->setSheetData(&newSheet->data); 152 sheet->setSheetData(&newSheet->data);
153 } 153 }
154 } 154 }
155} 155}
156 156
157int MainWindow::saveCurrentFile(bool ask) 157int MainWindow::saveCurrentFile(bool ask)
158{ 158{
159 if (ask) 159 if (ask)
160 { 160 {
161 int result=QMessageBox::information(this, tr("Save File"), tr("Do you want to save the current file?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); 161 int result=QMessageBox::information(this, tr("Save File"), tr("Do you want to save the current file?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel);
162 if (result!=QMessageBox::Yes) return result; 162 if (result!=QMessageBox::Yes) return result;
163 } 163 }
164 164
165 if (!currentDoc->isValid()) 165 if (!currentDoc->isValid())
166 { 166 {
167 TextDialog dialogText(this); 167 TextDialog dialogText(this);
168 if (dialogText.exec(tr("Save File"), tr("&File Name:"), tr("UnnamedFile"))!=QDialog::Accepted || dialogText.getValue().isEmpty()) return QMessageBox::Cancel; 168 if (dialogText.exec(tr("Save File"), tr("&File Name:"), tr("UnnamedFile"))!=QDialog::Accepted || dialogText.getValue().isEmpty()) return QMessageBox::Cancel;
169 169
170 currentDoc->setName(dialogText.getValue()); 170 currentDoc->setName(dialogText.getValue());
171 currentDoc->setFile(QString::null); 171 currentDoc->setFile(QString::null);
172 currentDoc->setLinkFile(QString::null); 172 currentDoc->setLinkFile(QString::null);
173 } 173 }
174 174
175 documentSave(currentDoc); 175 documentSave(currentDoc);
176 return QMessageBox::Yes; 176 return QMessageBox::Yes;
177} 177}
178 178
179void MainWindow::selectorFileNew(const DocLnk &lnkDoc) 179void MainWindow::selectorFileNew(const DocLnk &lnkDoc)
180{ 180{
181 selectorHide(); 181 selectorHide();
182 182
183 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; 183 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return;
184 if (currentDoc) delete currentDoc; 184 if (currentDoc) delete currentDoc;
185 currentDoc = new DocLnk(lnkDoc); 185 currentDoc = new DocLnk(lnkDoc);
186 editData->clear(); 186 editData->clear();
187 listSheets.clear(); 187 listSheets.clear();
188 comboSheets->clear(); 188 comboSheets->clear();
189 189
190 typeSheet *newSheet=createNewSheet(); 190 typeSheet *newSheet=createNewSheet();
191 newSheet->data.setAutoDelete(TRUE); 191 newSheet->data.setAutoDelete(TRUE);
192 sheet->setName(newSheet->name); 192 sheet->setName(newSheet->name);
193 sheet->setSheetData(&newSheet->data); 193 sheet->setSheetData(&newSheet->data);
194 for (int i=1; i<DEFAULT_NUM_SHEETS; ++i) 194 for (int i=1; i<DEFAULT_NUM_SHEETS; ++i)
195 createNewSheet(); 195 createNewSheet();
196 documentModified=FALSE; 196 documentModified=FALSE;
197} 197}
198 198
199void MainWindow::closeEvent(QCloseEvent *e) 199void MainWindow::closeEvent(QCloseEvent *e)
200{ 200{
201 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) e->ignore(); 201 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) e->ignore();
202 else e->accept(); 202 else e->accept();
203} 203}
204 204
205void MainWindow::selectorFileOpen(const DocLnk &lnkDoc) 205void MainWindow::selectorFileOpen(const DocLnk &lnkDoc)
206{ 206{
207 selectorHide(); 207 selectorHide();
208 208
209 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; 209 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return;
210 if (currentDoc) delete currentDoc; 210 if (currentDoc) delete currentDoc;
211 currentDoc = new DocLnk(); 211 currentDoc = new DocLnk();
212 listSheets.clear(); 212 listSheets.clear();
213 comboSheets->clear(); 213 comboSheets->clear();
214 214
215 documentOpen(lnkDoc); 215 documentOpen(lnkDoc);
216 documentModified=FALSE; 216 documentModified=FALSE;
217} 217}
218 218
219void MainWindow::selectorShow() 219void MainWindow::selectorShow()
220{ 220{
221 sheet->hide(); 221 sheet->hide();
222 setCentralWidget(fileSelector); 222 setCentralWidget(fileSelector);
223 fileSelector->show(); 223 fileSelector->show();
224 fileSelector->reread(); 224 fileSelector->reread();
225} 225}
226 226
227void MainWindow::selectorHide() 227void MainWindow::selectorHide()
228{ 228{
229 fileSelector->hide(); 229 fileSelector->hide();
230 setCentralWidget(sheet); 230 setCentralWidget(sheet);
231 sheet->show(); 231 sheet->show();
232} 232}
233 233
234void MainWindow::slotFileNew() 234void MainWindow::slotFileNew()
235{ 235{
236 selectorFileNew(DocLnk()); 236 selectorFileNew(DocLnk());
237} 237}
238 238
239void MainWindow::slotFileOpen() 239void MainWindow::slotFileOpen()
240{ 240{
241 selectorShow(); 241 selectorShow();
242} 242}
243 243
244void MainWindow::slotImportExcelOpen() 244void MainWindow::slotImportExcelOpen()
245{ 245{
246 sheet->hide(); 246 sheet->hide();
247 setCentralWidget(ExcelSelector); 247 setCentralWidget(ExcelSelector);
248 ExcelSelector->show(); 248 ExcelSelector->show();
249 ExcelSelector->reread(); 249 ExcelSelector->reread();
250} 250}
251 251
252void MainWindow::ExcelSelectorHide() 252void MainWindow::ExcelSelectorHide()
253{ 253{
254 ExcelSelector->hide(); 254 ExcelSelector->hide();
255 setCentralWidget(sheet); 255 setCentralWidget(sheet);
256 sheet->show(); 256 sheet->show();
257} 257}
258 258
259void MainWindow::slotFileSave() 259void MainWindow::slotFileSave()
260{ 260{
261 saveCurrentFile(FALSE); 261 saveCurrentFile(FALSE);
262} 262}
263 263
264void MainWindow::setDocument(const QString &applnk_filename) 264void MainWindow::setDocument(const QString &applnk_filename)
265{ 265{
266 selectorFileOpen(DocLnk(applnk_filename)); 266 selectorFileOpen(DocLnk(applnk_filename));
267} 267}
268 268
269void MainWindow::initActions() 269void MainWindow::initActions()
270{ 270{
271 fileNew=new QAction(tr("New File"), Resource::loadPixmap( "new" ), tr("&New"), 0, this); 271 fileNew=new QAction(tr("New File"), Resource::loadPixmap( "new" ), tr("&New"), 0, this);
272 connect(fileNew, SIGNAL(activated()), this, SLOT(slotFileNew())); 272 connect(fileNew, SIGNAL(activated()), this, SLOT(slotFileNew()));
273 fileOpen=new QAction(tr("Open File"), Resource::loadPixmap( "fileopen" ), tr("&Open"), 0, this); 273 fileOpen=new QAction(tr("Open File"), Resource::loadPixmap( "fileopen" ), tr("&Open"), 0, this);
274 connect(fileOpen, SIGNAL(activated()), this, SLOT(slotFileOpen())); 274 connect(fileOpen, SIGNAL(activated()), this, SLOT(slotFileOpen()));
275 fileSave=new QAction(tr("Save File"),Resource::loadPixmap( "save" ), tr("&Save"), 0, this); 275 fileSave=new QAction(tr("Save File"),Resource::loadPixmap( "save" ), tr("&Save"), 0, this);
276 connect(fileSave, SIGNAL(activated()), this, SLOT(slotFileSave())); 276 connect(fileSave, SIGNAL(activated()), this, SLOT(slotFileSave()));
277 fileSaveAs=new QAction(tr("Save File As"), Resource::loadPixmap( "save" ), tr("Save &As"), 0, this); 277 fileSaveAs=new QAction(tr("Save File As"), Resource::loadPixmap( "save" ), tr("Save &As"), 0, this);
278 connect(fileSaveAs, SIGNAL(activated()), this, SLOT(slotFileSaveAs())); 278 connect(fileSaveAs, SIGNAL(activated()), this, SLOT(slotFileSaveAs()));
279 279
280 //fileQuit=new QAction(tr("Quit"), tr("&Quit"), 0, this); 280 //fileQuit=new QAction(tr("Quit"), tr("&Quit"), 0, this);
281 //connect(fileQuit, SIGNAL(activated()), this, SLOT(close())); 281 //connect(fileQuit, SIGNAL(activated()), this, SLOT(close()));
282 fileExcelImport=new QAction(tr("Import Excel file"),Resource::loadPixmap( "opie-sheet/excel16" ),tr("Import E&xcel file"),0,this); 282 fileExcelImport=new QAction(tr("Import Excel file"),Resource::loadPixmap( "opie-sheet/excel16" ),tr("Import E&xcel file"),0,this);
283 connect(fileExcelImport, SIGNAL(activated()), this, SLOT(slotImportExcelOpen())); 283 connect(fileExcelImport, SIGNAL(activated()), this, SLOT(slotImportExcelOpen()));
284 284
285 // helpGeneral=new QAction(tr("General Help"), QPixmap(help_general_xpm), tr("&General"), 0, this); 285 // helpGeneral=new QAction(tr("General Help"), QPixmap(help_general_xpm), tr("&General"), 0, this);
286 //connect(helpGeneral, SIGNAL(activated()), this, SLOT(slotHelpGeneral())); 286 //connect(helpGeneral, SIGNAL(activated()), this, SLOT(slotHelpGeneral()));
287 //helpAbout=new QAction(tr("About Opie Sheet"), tr("&About"), 0, this); 287 //helpAbout=new QAction(tr("About Opie Sheet"), tr("&About"), 0, this);
288 //connect(helpAbout, SIGNAL(activated()), this, SLOT(slotHelpAbout())); 288 //connect(helpAbout, SIGNAL(activated()), this, SLOT(slotHelpAbout()));
289 289
290 editAccept=new QAction(tr("Accept"),Resource::loadPixmap( "enter" ) , tr("&Accept"), 0, this); 290 editAccept=new QAction(tr("Accept"),Resource::loadPixmap( "enter" ) , tr("&Accept"), 0, this);
291 connect(editAccept, SIGNAL(activated()), this, SLOT(slotEditAccept())); 291 connect(editAccept, SIGNAL(activated()), this, SLOT(slotEditAccept()));
292 editCancel=new QAction(tr("Cancel"), Resource::loadPixmap( "close" ), tr("&Cancel"), 0, this); 292 editCancel=new QAction(tr("Cancel"), Resource::loadPixmap( "close" ), tr("&Cancel"), 0, this);
293 connect(editCancel, SIGNAL(activated()), this, SLOT(slotEditCancel())); 293 connect(editCancel, SIGNAL(activated()), this, SLOT(slotEditCancel()));
294 editCellSelect=new QAction(tr("Cell Selector"), Resource::loadPixmap( "opie-sheet/cell-select" ), tr("Cell &Selector"), 0, this); 294 editCellSelect=new QAction(tr("Cell Selector"), Resource::loadPixmap( "opie-sheet/cell-select" ), tr("Cell &Selector"), 0, this);
295 editCellSelect->setToggleAction(TRUE); 295 editCellSelect->setToggleAction(TRUE);
296 connect(editCellSelect, SIGNAL(toggled(bool)), this, SLOT(slotCellSelect(bool))); 296 connect(editCellSelect, SIGNAL(toggled(bool)), this, SLOT(slotCellSelect(bool)));
297 editCut=new QAction(tr("Cut Cells"), tr("Cu&t"), 0, this); 297 editCut=new QAction(tr("Cut Cells"), tr("Cu&t"), 0, this);
298 editCopy=new QAction(tr("Copy Cells"), tr("&Copy"), 0, this); 298 editCopy=new QAction(tr("Copy Cells"), tr("&Copy"), 0, this);
299 editPaste=new QAction(tr("Paste Cells"), tr("&Paste"), 0, this); 299 editPaste=new QAction(tr("Paste Cells"), tr("&Paste"), 0, this);
300 connect(editPaste, SIGNAL(activated()), this, SLOT(slotEditPaste())); 300 connect(editPaste, SIGNAL(activated()), this, SLOT(slotEditPaste()));
301 editPasteContents=new QAction(tr("Paste Contents"), tr("Paste Cont&ents"), 0, this); 301 editPasteContents=new QAction(tr("Paste Contents"), tr("Paste Cont&ents"), 0, this);
302 connect(editPasteContents, SIGNAL(activated()), this, SLOT(slotEditPasteContents())); 302 connect(editPasteContents, SIGNAL(activated()), this, SLOT(slotEditPasteContents()));
303 editClear=new QAction(tr("Clear Cells"), tr("C&lear"), 0, this); 303 editClear=new QAction(tr("Clear Cells"), tr("C&lear"), 0, this);
304 304
305 insertCells=new QAction(tr("Insert Cells"), tr("C&ells"), 0, this); 305 insertCells=new QAction(tr("Insert Cells"), tr("C&ells"), 0, this);
306 connect(insertCells, SIGNAL(activated()), this, SLOT(slotInsertCells())); 306 connect(insertCells, SIGNAL(activated()), this, SLOT(slotInsertCells()));
307 insertRows=new QAction(tr("Insert Rows"), tr("&Rows"), 0, this); 307 insertRows=new QAction(tr("Insert Rows"), tr("&Rows"), 0, this);
308 connect(insertRows, SIGNAL(activated()), this, SLOT(slotInsertRows())); 308 connect(insertRows, SIGNAL(activated()), this, SLOT(slotInsertRows()));
309 insertCols=new QAction(tr("Insert Columns"), tr("&Columns"), 0, this); 309 insertCols=new QAction(tr("Insert Columns"), tr("&Columns"), 0, this);
310 connect(insertCols, SIGNAL(activated()), this, SLOT(slotInsertCols())); 310 connect(insertCols, SIGNAL(activated()), this, SLOT(slotInsertCols()));
311 insertSheets=new QAction(tr("Add Sheets"), tr("&Sheets"), 0, this); 311 insertSheets=new QAction(tr("Add Sheets"), tr("&Sheets"), 0, this);
312 connect(insertSheets, SIGNAL(activated()), this, SLOT(slotInsertSheets())); 312 connect(insertSheets, SIGNAL(activated()), this, SLOT(slotInsertSheets()));
313 313
314 formatCells=new QAction(tr("Cells"), tr("&Cells"), 0, this); 314 formatCells=new QAction(tr("Cells"), tr("&Cells"), 0, this);
315 connect(formatCells, SIGNAL(activated()), this, SLOT(slotFormatCells())); 315 connect(formatCells, SIGNAL(activated()), this, SLOT(slotFormatCells()));
316 316
317 rowHeight=new QAction(tr("Row Height"), tr("H&eight"), 0, this); 317 rowHeight=new QAction(tr("Row Height"), tr("H&eight"), 0, this);
318 connect(rowHeight, SIGNAL(activated()), this, SLOT(slotRowHeight())); 318 connect(rowHeight, SIGNAL(activated()), this, SLOT(slotRowHeight()));
319 rowAdjust=new QAction(tr("Adjust Row"), tr("&Adjust"), 0, this); 319 rowAdjust=new QAction(tr("Adjust Row"), tr("&Adjust"), 0, this);
320 connect(rowAdjust, SIGNAL(activated()), this, SLOT(slotRowAdjust())); 320 connect(rowAdjust, SIGNAL(activated()), this, SLOT(slotRowAdjust()));
321 rowShow=new QAction(tr("Show Row"), tr("&Show"), 0, this); 321 rowShow=new QAction(tr("Show Row"), tr("&Show"), 0, this);
322 connect(rowShow, SIGNAL(activated()), this, SLOT(slotRowShow())); 322 connect(rowShow, SIGNAL(activated()), this, SLOT(slotRowShow()));
323 rowHide=new QAction(tr("Hide Row"), tr("&Hide"), 0, this); 323 rowHide=new QAction(tr("Hide Row"), tr("&Hide"), 0, this);
324 connect(rowHide, SIGNAL(activated()), this, SLOT(slotRowHide())); 324 connect(rowHide, SIGNAL(activated()), this, SLOT(slotRowHide()));
325 325
326 colWidth=new QAction(tr("Column Width"), tr("&Width"), 0, this); 326 colWidth=new QAction(tr("Column Width"), tr("&Width"), 0, this);
327 connect(colWidth, SIGNAL(activated()), this, SLOT(slotColumnWidth())); 327 connect(colWidth, SIGNAL(activated()), this, SLOT(slotColumnWidth()));
328 colAdjust=new QAction(tr("Adjust Column"), tr("&Adjust"), 0, this); 328 colAdjust=new QAction(tr("Adjust Column"), tr("&Adjust"), 0, this);
329 connect(colAdjust, SIGNAL(activated()), this, SLOT(slotColumnAdjust())); 329 connect(colAdjust, SIGNAL(activated()), this, SLOT(slotColumnAdjust()));
330 colShow=new QAction(tr("Show Column"), tr("&Show"), 0, this); 330 colShow=new QAction(tr("Show Column"), tr("&Show"), 0, this);
331 connect(colShow, SIGNAL(activated()), this, SLOT(slotColumnShow())); 331 connect(colShow, SIGNAL(activated()), this, SLOT(slotColumnShow()));
332 colHide=new QAction(tr("Hide Column"), tr("&Hide"), 0, this); 332 colHide=new QAction(tr("Hide Column"), tr("&Hide"), 0, this);
333 connect(colHide, SIGNAL(activated()), this, SLOT(slotColumnHide())); 333 connect(colHide, SIGNAL(activated()), this, SLOT(slotColumnHide()));
334 334
335 sheetRename=new QAction(tr("Rename Sheet"), tr("&Rename"), 0, this); 335 sheetRename=new QAction(tr("Rename Sheet"), tr("&Rename"), 0, this);
336 connect(sheetRename, SIGNAL(activated()), this, SLOT(slotSheetRename())); 336 connect(sheetRename, SIGNAL(activated()), this, SLOT(slotSheetRename()));
337 sheetRemove=new QAction(tr("Remove Sheet"), tr("R&emove"), 0, this); 337 sheetRemove=new QAction(tr("Remove Sheet"), tr("R&emove"), 0, this);
338 connect(sheetRemove, SIGNAL(activated()), this, SLOT(slotSheetRemove())); 338 connect(sheetRemove, SIGNAL(activated()), this, SLOT(slotSheetRemove()));
339 339
340 dataSort=new QAction(tr("Sort Data"), tr("&Sort"), 0, this); 340 dataSort=new QAction(tr("Sort Data"), tr("&Sort"), 0, this);
341 connect(dataSort, SIGNAL(activated()), this, SLOT(slotDataSort())); 341 connect(dataSort, SIGNAL(activated()), this, SLOT(slotDataSort()));
342 dataFindReplace=new QAction(tr("Find && Replace"), tr("&Find && Replace"), 0, this); 342 dataFindReplace=new QAction(tr("Find && Replace"), tr("&Find && Replace"), 0, this);
343 connect(dataFindReplace, SIGNAL(activated()), this, SLOT(slotDataFindReplace())); 343 connect(dataFindReplace, SIGNAL(activated()), this, SLOT(slotDataFindReplace()));
344 344
345 funcEqual=new QAction(tr("Equal To"), Resource::loadPixmap( "opie-sheet/func-equal" ), tr("&Equal To"), 0, this); 345 funcEqual=new QAction(tr("Equal To"), Resource::loadPixmap( "opie-sheet/func-equal" ), tr("&Equal To"), 0, this);
346 funcEqual->setToolTip("="); 346 funcEqual->setToolTip("=");
347 connect(funcEqual, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 347 connect(funcEqual, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
348 funcPlus=new QAction(tr("Addition"), Resource::loadPixmap( "opie-sheet/func-plus" ), tr("&Addition"), 0, this); 348 funcPlus=new QAction(tr("Addition"), Resource::loadPixmap( "opie-sheet/func-plus" ), tr("&Addition"), 0, this);
349 funcPlus->setToolTip("+"); 349 funcPlus->setToolTip("+");
350 connect(funcPlus, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 350 connect(funcPlus, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
351 funcMinus=new QAction(tr("Subtraction"), Resource::loadPixmap( "opie-sheet/func-minus" ), tr("&Subtraction"), 0, this); 351 funcMinus=new QAction(tr("Subtraction"), Resource::loadPixmap( "opie-sheet/func-minus" ), tr("&Subtraction"), 0, this);
352 funcMinus->setToolTip("-"); 352 funcMinus->setToolTip("-");
353 connect(funcMinus, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 353 connect(funcMinus, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
354 funcCross=new QAction(tr("Multiplication"), Resource::loadPixmap ("opie-sheet/func-cross" ), tr("&Multiplication"), 0, this); 354 funcCross=new QAction(tr("Multiplication"), Resource::loadPixmap ("opie-sheet/func-cross" ), tr("&Multiplication"), 0, this);
355 funcCross->setToolTip("*"); 355 funcCross->setToolTip("*");
356 connect(funcCross, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 356 connect(funcCross, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
357 funcDivide=new QAction(tr("Division"), Resource::loadPixmap( "opie-sheet/func-divide" ), tr("&Division"), 0, this); 357 funcDivide=new QAction(tr("Division"), Resource::loadPixmap( "opie-sheet/func-divide" ), tr("&Division"), 0, this);
358 funcDivide->setToolTip("/"); 358 funcDivide->setToolTip("/");
359 connect(funcDivide, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 359 connect(funcDivide, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
360 funcParanOpen=new QAction(tr("Open ParanthesistempCellData->row+row1, tempCellData->col+col1"), Resource::loadPixmap( "opie-sheet/func-paran-open" ), tr("&Open Paranthesis"), 0, this); 360 funcParanOpen=new QAction(tr("Open ParanthesistempCellData->row+row1, tempCellData->col+col1"), Resource::loadPixmap( "opie-sheet/func-paran-open" ), tr("&Open Paranthesis"), 0, this);
361 funcParanOpen->setToolTip("("); 361 funcParanOpen->setToolTip("(");
362 connect(funcParanOpen, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 362 connect(funcParanOpen, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
363 funcParanClose=new QAction(tr("Close Paranthesis"), Resource::loadPixmap( "opie-sheet/func-paran-close" ), tr("&Close Paranthesis"), 0, this); 363 funcParanClose=new QAction(tr("Close Paranthesis"), Resource::loadPixmap( "opie-sheet/func-paran-close" ), tr("&Close Paranthesis"), 0, this);
364 funcParanClose->setToolTip(")"); 364 funcParanClose->setToolTip(")");
365 connect(funcParanClose, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 365 connect(funcParanClose, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
366 funcComma=new QAction(tr("Comma"), Resource::loadPixmap( "opie-sheet/func-comma" ), tr("&Comma"), 0, this); 366 funcComma=new QAction(tr("Comma"), Resource::loadPixmap( "opie-sheet/func-comma" ), tr("&Comma"), 0, this);
367 funcComma->setToolTip(","); 367 funcComma->setToolTip(",");
368 connect(funcComma, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 368 connect(funcComma, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
369} 369}
370 370
371void MainWindow::initMenu() 371void MainWindow::initMenu()
372{ 372{
373 menu=new QMenuBar(this); 373 menu=new QMenuBar(this);
374 374
375 menuFile=new QPopupMenu; 375 menuFile=new QPopupMenu;
376 fileNew->addTo(menuFile); 376 fileNew->addTo(menuFile);
377 fileOpen->addTo(menuFile); 377 fileOpen->addTo(menuFile);
378 fileSave->addTo(menuFile); 378 fileSave->addTo(menuFile);
379 fileSaveAs->addTo(menuFile); 379 fileSaveAs->addTo(menuFile);
380// menuFile->insertSeparator(); 380// menuFile->insertSeparator();
381// fileQuit->addTo(menuFile); 381// fileQuit->addTo(menuFile);
382 menuFile->insertSeparator(); 382 menuFile->insertSeparator();
383 fileExcelImport->addTo(menuFile); 383 fileExcelImport->addTo(menuFile);
384 menu->insertItem(tr("&File"), menuFile); 384 menu->insertItem(tr("&File"), menuFile);
385 385
386 menuEdit=new QPopupMenu; 386 menuEdit=new QPopupMenu;
387 editAccept->addTo(menuEdit); 387 editAccept->addTo(menuEdit);
388 editCancel->addTo(menuEdit); 388 editCancel->addTo(menuEdit);
389 editCellSelect->addTo(menuEdit); 389 editCellSelect->addTo(menuEdit);
390 menuEdit->insertSeparator(); 390 menuEdit->insertSeparator();
391 editCut->addTo(menuEdit); 391 editCut->addTo(menuEdit);
392 editCopy->addTo(menuEdit); 392 editCopy->addTo(menuEdit);
393 editPaste->addTo(menuEdit); 393 editPaste->addTo(menuEdit);
394 editPasteContents->addTo(menuEdit); 394 editPasteContents->addTo(menuEdit);
395 editClear->addTo(menuEdit); 395 editClear->addTo(menuEdit);
396 menu->insertItem(tr("&Edit"), menuEdit); 396 menu->insertItem(tr("&Edit"), menuEdit);
397 397
398 menuInsert=new QPopupMenu; 398 menuInsert=new QPopupMenu;
399 menu->insertItem(tr("&Insert"), menuInsert); 399 menu->insertItem(tr("&Insert"), menuInsert);
400 400
401 menuFormat=new QPopupMenu; 401 menuFormat=new QPopupMenu;
402 formatCells->addTo(menuFormat); 402 formatCells->addTo(menuFormat);
403 menu->insertItem(tr("&Format"), menuFormat); 403 menu->insertItem(tr("&Format"), menuFormat);
404 404
405 menuData=new QPopupMenu; 405 menuData=new QPopupMenu;
406 dataSort->addTo(menuData); 406 dataSort->addTo(menuData);
407 dataFindReplace->addTo(menuData); 407 dataFindReplace->addTo(menuData);
408 menu->insertItem(tr("&Data"), menuData); 408 menu->insertItem(tr("&Data"), menuData);
409 409
410// menuHelp=new QPopupMenu; 410// menuHelp=new QPopupMenu;
411// helpGeneral->addTo(menuHelp); 411// helpGeneral->addTo(menuHelp);
412// helpAbout->addTo(menuHelp); 412// helpAbout->addTo(menuHelp);
413// menu->insertItem(tr("&Help"), menuHelp); 413// menu->insertItem(tr("&Help"), menuHelp);
414 414
415 submenuRow=new QPopupMenu; 415 submenuRow=new QPopupMenu;
416 rowHeight->addTo(submenuRow); 416 rowHeight->addTo(submenuRow);
417 rowAdjust->addTo(submenuRow); 417 rowAdjust->addTo(submenuRow);
418 rowShow->addTo(submenuRow); 418 rowShow->addTo(submenuRow);
419 rowHide->addTo(submenuRow); 419 rowHide->addTo(submenuRow);
420 menuFormat->insertItem(tr("&Row"), submenuRow); 420 menuFormat->insertItem(tr("&Row"), submenuRow);
421 421
422 submenuCol=new QPopupMenu; 422 submenuCol=new QPopupMenu;
423 colWidth->addTo(submenuCol); 423 colWidth->addTo(submenuCol);
424 colAdjust->addTo(submenuCol); 424 colAdjust->addTo(submenuCol);
425 colShow->addTo(submenuCol); 425 colShow->addTo(submenuCol);
426 colHide->addTo(submenuCol); 426 colHide->addTo(submenuCol);
427 menuFormat->insertItem(tr("Colum&n"), submenuCol); 427 menuFormat->insertItem(tr("Colum&n"), submenuCol);
428 428
429 submenuSheet=new QPopupMenu; 429 submenuSheet=new QPopupMenu;
430 sheetRename->addTo(submenuSheet); 430 sheetRename->addTo(submenuSheet);
431 sheetRemove->addTo(submenuSheet); 431 sheetRemove->addTo(submenuSheet);
432 menuFormat->insertItem(tr("&Sheet"), submenuSheet); 432 menuFormat->insertItem(tr("&Sheet"), submenuSheet);
433 433
434 submenuFunc=new QPopupMenu; 434 submenuFunc=new QPopupMenu;
435 menuInsert->insertItem(tr("&Function"), submenuFunc); 435 menuInsert->insertItem(tr("&Function"), submenuFunc);
436 436
437 submenuFuncStd=new QPopupMenu; 437 submenuFuncStd=new QPopupMenu;
438 funcPlus->addTo(submenuFuncStd); 438 funcPlus->addTo(submenuFuncStd);
439 funcMinus->addTo(submenuFuncStd); 439 funcMinus->addTo(submenuFuncStd);
440 funcCross->addTo(submenuFuncStd); 440 funcCross->addTo(submenuFuncStd);
441 funcDivide->addTo(submenuFuncStd); 441 funcDivide->addTo(submenuFuncStd);
442 submenuFunc->insertItem(tr("&Simple"), submenuFuncStd); 442 submenuFunc->insertItem(tr("&Simple"), submenuFuncStd);
443 443
444 444
445 445
446 submenuFuncStandard=new QPopupMenu; 446 submenuFuncStandard=new QPopupMenu;
447 addFlyAction(tr("ABS(x)"), tr("ABS(x)"), "ABS(", submenuFuncStandard); 447 addFlyAction(tr("ABS(x)"), tr("ABS(x)"), "ABS(", submenuFuncStandard);
448 addFlyAction(tr("CEILING(x,acc)"), tr("CEILING(x,acc)"), "CEILING(", submenuFuncStandard); 448 addFlyAction(tr("CEILING(x,acc)"), tr("CEILING(x,acc)"), "CEILING(", submenuFuncStandard);
449 addFlyAction(tr("FACT(x)"), tr("FACT(x)"), "FACT(", submenuFuncStandard); 449 addFlyAction(tr("FACT(x)"), tr("FACT(x)"), "FACT(", submenuFuncStandard);
450 addFlyAction(tr("FLOOR(x,acc)"), tr("FLOOR(x,acc)"), "FLOOR(", submenuFuncStandard); 450 addFlyAction(tr("FLOOR(x,acc)"), tr("FLOOR(x,acc)"), "FLOOR(", submenuFuncStandard);
451 addFlyAction(tr("INT(x)"), tr("INT(x)"), "INT(", submenuFuncStandard); 451 addFlyAction(tr("INT(x)"), tr("INT(x)"), "INT(", submenuFuncStandard);
452 addFlyAction(tr("MOD(x,y)"), tr("MOD(x,y)"), "MOD(", submenuFuncStandard); 452 addFlyAction(tr("MOD(x,y)"), tr("MOD(x,y)"), "MOD(", submenuFuncStandard);
453 addFlyAction(tr("ROUND(x,digits)"), tr("ROUND(x,digits)"), "ROUND(", submenuFuncStandard); 453 addFlyAction(tr("ROUND(x,digits)"), tr("ROUND(x,digits)"), "ROUND(", submenuFuncStandard);
454 addFlyAction(tr("SIGN(x)"), tr("SIGN(x)"), "SIGN(", submenuFuncStandard); 454 addFlyAction(tr("SIGN(x)"), tr("SIGN(x)"), "SIGN(", submenuFuncStandard);
455 submenuFuncStandard->insertSeparator(); 455 submenuFuncStandard->insertSeparator();
456 addFlyAction(tr("EXP(x)"), tr("EXP(x)"), "EXP(", submenuFuncStandard); 456 addFlyAction(tr("EXP(x)"), tr("EXP(x)"), "EXP(", submenuFuncStandard);
457 addFlyAction(tr("LN(x)"), tr("LN(x)"), "LN(", submenuFuncStandard); 457 addFlyAction(tr("LN(x)"), tr("LN(x)"), "LN(", submenuFuncStandard);
458 addFlyAction(tr("LOG(x,b)"), tr("LOG(x,b)"), "LOG(", submenuFuncStandard); 458 addFlyAction(tr("LOG(x,b)"), tr("LOG(x,b)"), "LOG(", submenuFuncStandard);
459 addFlyAction(tr("LOG10(x)"), tr("LOG10(x)"), "LOG10(", submenuFuncStandard); 459 addFlyAction(tr("LOG10(x)"), tr("LOG10(x)"), "LOG10(", submenuFuncStandard);
460 addFlyAction(tr("POWER(x,y)"), tr("POWER(x,y)"), "POWER(", submenuFuncStandard); 460 addFlyAction(tr("POWER(x,y)"), tr("POWER(x,y)"), "POWER(", submenuFuncStandard);
461 addFlyAction(tr("SQRT(x)"), tr("SQRT(x)"), "SQRT(", submenuFuncStandard); 461 addFlyAction(tr("SQRT(x)"), tr("SQRT(x)"), "SQRT(", submenuFuncStandard);
462 submenuFuncStandard->insertSeparator(); 462 submenuFuncStandard->insertSeparator();
463 addFlyAction(tr("DEGREES(x)"), tr("DEGREES(x)"), "DEGREES(", submenuFuncStandard); 463 addFlyAction(tr("DEGREES(x)"), tr("DEGREES(x)"), "DEGREES(", submenuFuncStandard);
464 addFlyAction(tr("RADIANS(x)"), tr("RADIANS(x)"), "RADIANS(", submenuFuncStandard); 464 addFlyAction(tr("RADIANS(x)"), tr("RADIANS(x)"), "RADIANS(", submenuFuncStandard);
465 addFlyAction(tr("PI()"), tr("PI()"), "PI()", submenuFuncStandard); 465 addFlyAction(tr("PI()"), tr("PI()"), "PI()", submenuFuncStandard);
466 addFlyAction(tr("RAND()"), tr("RAND()"), "RAND(", submenuFuncStandard); 466 addFlyAction(tr("RAND()"), tr("RAND()"), "RAND(", submenuFuncStandard);
467 addFlyAction(tr("RANDBETWEEN(a,b)"), tr("RANDBETWEEN(a,b)"), "RANDBETWEEN(", submenuFuncStandard); 467 addFlyAction(tr("RANDBETWEEN(a,b)"), tr("RANDBETWEEN(a,b)"), "RANDBETWEEN(", submenuFuncStandard);
468 submenuFunc->insertItem(tr("S&tandard"), submenuFuncStandard); 468 submenuFunc->insertItem(tr("S&tandard"), submenuFuncStandard);
469 469
470 submenuFuncLogic=new QPopupMenu; 470 submenuFuncLogic=new QPopupMenu;
471 addFlyAction(tr("AND(x1,x2)"), tr("AND(x1,x2)"), "AND(", submenuFuncLogic); 471 addFlyAction(tr("AND(x1,x2)"), tr("AND(x1,x2)"), "AND(", submenuFuncLogic);
472 addFlyAction(tr("NOT(x)"), tr("NOT(x)"), "NOT(", submenuFuncLogic); 472 addFlyAction(tr("NOT(x)"), tr("NOT(x)"), "NOT(", submenuFuncLogic);
473 addFlyAction(tr("OR(x1,x2)"), tr("OR(x1,x2)"), "OR(", submenuFuncLogic); 473 addFlyAction(tr("OR(x1,x2)"), tr("OR(x1,x2)"), "OR(", submenuFuncLogic);
474 submenuFuncLogic->insertSeparator(); 474 submenuFuncLogic->insertSeparator();
475 addFlyAction(tr("IF(compare,val1,val2)"), tr("IF(compare,val1,val2)"), "IF(", submenuFuncLogic); 475 addFlyAction(tr("IF(compare,val1,val2)"), tr("IF(compare,val1,val2)"), "IF(", submenuFuncLogic);
476 addFlyAction(tr("INDEX(range,index)"),tr("INDEX(range,index)"), "INDEX(", submenuFuncLogic); 476 addFlyAction(tr("INDEX(range,index)"),tr("INDEX(range,index)"), "INDEX(", submenuFuncLogic);
477 addFlyAction(tr("ISBLANK(x)"), tr("ISBLANK(x)"), "ISBLANK(", submenuFuncLogic); 477 addFlyAction(tr("ISBLANK(x)"), tr("ISBLANK(x)"), "ISBLANK(", submenuFuncLogic);
478 addFlyAction(tr("ISNUMBER(x)"), tr("ISNUMBER(x)"), "ISNUMBER(", submenuFuncLogic); 478 addFlyAction(tr("ISNUMBER(x)"), tr("ISNUMBER(x)"), "ISNUMBER(", submenuFuncLogic);
479 addFlyAction(tr("EVEN(x)"), tr("EVEN(x)"), "EVEN(", submenuFuncLogic); 479 addFlyAction(tr("EVEN(x)"), tr("EVEN(x)"), "EVEN(", submenuFuncLogic);
480 addFlyAction(tr("ISEVEN(x)"), tr("ISEVEN(x)"), "ISEVEN(", submenuFuncLogic); 480 addFlyAction(tr("ISEVEN(x)"), tr("ISEVEN(x)"), "ISEVEN(", submenuFuncLogic);
481 addFlyAction(tr("ODD(x)"), tr("ODD(x)"), "ODD(", submenuFuncLogic); 481 addFlyAction(tr("ODD(x)"), tr("ODD(x)"), "ODD(", submenuFuncLogic);
482 addFlyAction(tr("ISODD(x)"), tr("ISODD(x)"), "ISODD(", submenuFuncLogic); 482 addFlyAction(tr("ISODD(x)"), tr("ISODD(x)"), "ISODD(", submenuFuncLogic);
483 submenuFunc->insertItem(tr("Logical-&Information"), submenuFuncLogic); 483 submenuFunc->insertItem(tr("Logical-&Information"), submenuFuncLogic);
484 484
485 submenuFuncTrig=new QPopupMenu; 485 submenuFuncTrig=new QPopupMenu;
486 addFlyAction(tr("SIN(x)"), tr("SIN(x)"), "SIN(", submenuFuncTrig); 486 addFlyAction(tr("SIN(x)"), tr("SIN(x)"), "SIN(", submenuFuncTrig);
487 addFlyAction(tr("COS(x)"), tr("COS(x)"), "COS(", submenuFuncTrig); 487 addFlyAction(tr("COS(x)"), tr("COS(x)"), "COS(", submenuFuncTrig);
488 addFlyAction(tr("TAN(x)"), tr("TAN(x)"), "TAN(", submenuFuncTrig); 488 addFlyAction(tr("TAN(x)"), tr("TAN(x)"), "TAN(", submenuFuncTrig);
489 addFlyAction(tr("ASIN(x)"), tr("ASIN(x)"), "ASIN(", submenuFuncTrig); 489 addFlyAction(tr("ASIN(x)"), tr("ASIN(x)"), "ASIN(", submenuFuncTrig);
490 addFlyAction(tr("ACOS(x)"), tr("ACOS(x)"), "ACOS(", submenuFuncTrig); 490 addFlyAction(tr("ACOS(x)"), tr("ACOS(x)"), "ACOS(", submenuFuncTrig);
491 addFlyAction(tr("ATAN(x)"), tr("ATAN(x)"), "ATAN(", submenuFuncTrig); 491 addFlyAction(tr("ATAN(x)"), tr("ATAN(x)"), "ATAN(", submenuFuncTrig);
492 addFlyAction(tr("ATAN2(x,y)"), tr("ATAN2(x,y)"), "ATAN2(", submenuFuncTrig); 492 addFlyAction(tr("ATAN2(x,y)"), tr("ATAN2(x,y)"), "ATAN2(", submenuFuncTrig);
493 submenuFuncTrig->insertSeparator(); 493 submenuFuncTrig->insertSeparator();
494 addFlyAction(tr("SINH(x)"), tr("SINH(x)"), "SINH(", submenuFuncTrig); 494 addFlyAction(tr("SINH(x)"), tr("SINH(x)"), "SINH(", submenuFuncTrig);
495 addFlyAction(tr("COSH(x)"), tr("COSH(x)"), "COSH(", submenuFuncTrig); 495 addFlyAction(tr("COSH(x)"), tr("COSH(x)"), "COSH(", submenuFuncTrig);
496 addFlyAction(tr("TANH(x)"), tr("TANH(x)"), "TANH(", submenuFuncTrig); 496 addFlyAction(tr("TANH(x)"), tr("TANH(x)"), "TANH(", submenuFuncTrig);
497 addFlyAction(tr("ACOSH(x)"), tr("ACOSH(x)"), "ACOSH(", submenuFuncTrig); 497 addFlyAction(tr("ACOSH(x)"), tr("ACOSH(x)"), "ACOSH(", submenuFuncTrig);
498 addFlyAction(tr("ASINH(x)"), tr("ASINH(x)"), "ASINH(", submenuFuncTrig); 498 addFlyAction(tr("ASINH(x)"), tr("ASINH(x)"), "ASINH(", submenuFuncTrig);
499 addFlyAction(tr("ATANH(x)"), tr("ATANH(x)"), "ATANH(", submenuFuncTrig); 499 addFlyAction(tr("ATANH(x)"), tr("ATANH(x)"), "ATANH(", submenuFuncTrig);
500 submenuFunc->insertItem(tr("&Trigonometric"), submenuFuncTrig); 500 submenuFunc->insertItem(tr("&Trigonometric"), submenuFuncTrig);
501 501
502 submenuFuncString=new QPopupMenu; 502 submenuFuncString=new QPopupMenu;
503 addFlyAction(tr("LEN(s)"), tr("LEN(s)"), "LEN(",submenuFuncString); 503 addFlyAction(tr("LEN(s)"), tr("LEN(s)"), "LEN(",submenuFuncString);
504 addFlyAction(tr("LEFT(s,num)"), tr("LEFT(s,num)"), "LEFT(",submenuFuncString); 504 addFlyAction(tr("LEFT(s,num)"), tr("LEFT(s,num)"), "LEFT(",submenuFuncString);
505 addFlyAction(tr("RIGHT(s,num)"), tr("RIGHT(s,num)"), "RIGHT(",submenuFuncString); 505 addFlyAction(tr("RIGHT(s,num)"), tr("RIGHT(s,num)"), "RIGHT(",submenuFuncString);
506 addFlyAction(tr("MID(s,pos,len)"), tr("MID(s,pos,len)"), "MID(",submenuFuncString); 506 addFlyAction(tr("MID(s,pos,len)"), tr("MID(s,pos,len)"), "MID(",submenuFuncString);
507 submenuFuncString->insertSeparator(); 507 submenuFuncString->insertSeparator();
508 addFlyAction(tr("CONCATENATE(s1,s2..)"), tr("CONCATENATE(s1,s2..)"), "CONCATENATE(",submenuFuncString); 508 addFlyAction(tr("CONCATENATE(s1,s2..)"), tr("CONCATENATE(s1,s2..)"), "CONCATENATE(",submenuFuncString);
509 addFlyAction(tr("EXACT(s1,s2)"), tr("EXACT(s1,s2)"), "EXACT(",submenuFuncString); 509 addFlyAction(tr("EXACT(s1,s2)"), tr("EXACT(s1,s2)"), "EXACT(",submenuFuncString);
510 addFlyAction(tr("FIND(what,where,pos)"), 510 addFlyAction(tr("FIND(what,where,pos)"),
511 tr("FIND(what,where,pos)"), "FIND(",submenuFuncString); 511 tr("FIND(what,where,pos)"), "FIND(",submenuFuncString);
512 addFlyAction(tr("REPLACE(s,pos,len,ns)"), tr("REPLACE(s,pos,len,ns)"), "REPLACE(",submenuFuncString); 512 addFlyAction(tr("REPLACE(s,pos,len,ns)"), tr("REPLACE(s,pos,len,ns)"), "REPLACE(",submenuFuncString);
513 addFlyAction(tr("REPT(s,n)"), tr("REPT(s,n)"), "REPT(",submenuFuncString); 513 addFlyAction(tr("REPT(s,n)"), tr("REPT(s,n)"), "REPT(",submenuFuncString);
514 submenuFuncString->insertSeparator(); 514 submenuFuncString->insertSeparator();
515 addFlyAction(tr("UPPER(s)"), tr("UPPER(s)"), "UPPER(",submenuFuncString); 515 addFlyAction(tr("UPPER(s)"), tr("UPPER(s)"), "UPPER(",submenuFuncString);
516 addFlyAction(tr("LOWER(s)"), tr("LOWER(s)"), "LOWER(",submenuFuncString); 516 addFlyAction(tr("LOWER(s)"), tr("LOWER(s)"), "LOWER(",submenuFuncString);
517 submenuFunc->insertItem(tr("&Strings"), submenuFuncString); 517 submenuFunc->insertItem(tr("&Strings"), submenuFuncString);
518 518
519 submenuFuncStat=new QPopupMenu; 519 submenuFuncStat=new QPopupMenu;
520 addFlyAction(tr("AVERAGE(range)"), tr("AVERAGE(range)"), "AVERAGE(",submenuFuncStat); 520 addFlyAction(tr("AVERAGE(range)"), tr("AVERAGE(range)"), "AVERAGE(",submenuFuncStat);
521 addFlyAction(tr("COUNT(range)"), tr("COUNT(range)"), "COUNT(",submenuFuncStat); 521 addFlyAction(tr("COUNT(range)"), tr("COUNT(range)"), "COUNT(",submenuFuncStat);
522 addFlyAction(tr("COUNTIF(range,eqls)"), tr("COUNTIF(range,eqls)"), "COUNTIF(",submenuFuncStat); 522 addFlyAction(tr("COUNTIF(range,eqls)"), tr("COUNTIF(range,eqls)"), "COUNTIF(",submenuFuncStat);
523 addFlyAction(tr("MAX(range)"), tr("MAX(range)"), "MAX(",submenuFuncStat); 523 addFlyAction(tr("MAX(range)"), tr("MAX(range)"), "MAX(",submenuFuncStat);
524 addFlyAction(tr("MIN(range)"), tr("MIN(range)"), "MIN(",submenuFuncStat); 524 addFlyAction(tr("MIN(range)"), tr("MIN(range)"), "MIN(",submenuFuncStat);
525 addFlyAction(tr("SUM(range)"), tr("SUM(range)"), "SUM(",submenuFuncStat); 525 addFlyAction(tr("SUM(range)"), tr("SUM(range)"), "SUM(",submenuFuncStat);
526 addFlyAction(tr("SUMSQ(range)"), tr("SUMSQ(range)"), "SUMSQ(",submenuFuncStat); 526 addFlyAction(tr("SUMSQ(range)"), tr("SUMSQ(range)"), "SUMSQ(",submenuFuncStat);
527 submenuFuncStat->insertSeparator(); 527 submenuFuncStat->insertSeparator();
528 addFlyAction(tr("AVERAGE(range)"), tr("AVERAGE(range)"), "AVERAGE(",submenuFuncStat); 528 addFlyAction(tr("AVERAGE(range)"), tr("AVERAGE(range)"), "AVERAGE(",submenuFuncStat);
529 addFlyAction(tr("VAR(range)"), tr("VAR(range)"), "VAR(",submenuFuncStat); 529 addFlyAction(tr("VAR(range)"), tr("VAR(range)"), "VAR(",submenuFuncStat);
530 addFlyAction(tr("VARP(range)"), tr("VARP(range)"), "VARP(",submenuFuncStat); 530 addFlyAction(tr("VARP(range)"), tr("VARP(range)"), "VARP(",submenuFuncStat);
531 addFlyAction(tr("STDEV(range)"), tr("STDEV(range)"), "STDEV(",submenuFuncStat); 531 addFlyAction(tr("STDEV(range)"), tr("STDEV(range)"), "STDEV(",submenuFuncStat);
532 addFlyAction(tr("STDEVP(range)"), tr("STDEVP(range)"), "STDEVP(",submenuFuncStat); 532 addFlyAction(tr("STDEVP(range)"), tr("STDEVP(range)"), "STDEVP(",submenuFuncStat);
533 addFlyAction(tr("SKEW(range)"), tr("SKEW(range)"), "SKEW(",submenuFuncStat); 533 addFlyAction(tr("SKEW(range)"), tr("SKEW(range)"), "SKEW(",submenuFuncStat);
534 addFlyAction(tr("KURT(range)"), tr("KURT(range)"), "KURT(",submenuFuncStat); 534 addFlyAction(tr("KURT(range)"), tr("KURT(range)"), "KURT(",submenuFuncStat);
535 submenuFunc->insertItem(tr("Sta&tistical"), submenuFuncStat); 535 submenuFunc->insertItem(tr("Sta&tistical"), submenuFuncStat);
536 536
537 submenuFuncScientific=new QPopupMenu; 537 submenuFuncScientific=new QPopupMenu;
538 addFlyAction(tr("BESSELI(x,n)"), tr("BESSELI(x,n)"), "BESSELI(",submenuFuncScientific); 538 addFlyAction(tr("BESSELI(x,n)"), tr("BESSELI(x,n)"), "BESSELI(",submenuFuncScientific);
539 addFlyAction(tr("BESSELJ(x,n)"), tr("BESSELJ(x,n)"), "BESSELJ(",submenuFuncScientific); 539 addFlyAction(tr("BESSELJ(x,n)"), tr("BESSELJ(x,n)"), "BESSELJ(",submenuFuncScientific);
540 addFlyAction(tr("BESSELK(x,n)"), tr("BESSELK(x,n)"), "BESSELK(",submenuFuncScientific); 540 addFlyAction(tr("BESSELK(x,n)"), tr("BESSELK(x,n)"), "BESSELK(",submenuFuncScientific);
541 addFlyAction(tr("BESSELY(x,n)"), tr("BESSELY(x,n)"), "BESSELY(",submenuFuncScientific); 541 addFlyAction(tr("BESSELY(x,n)"), tr("BESSELY(x,n)"), "BESSELY(",submenuFuncScientific);
542 submenuFuncScientific->insertSeparator(); 542 submenuFuncScientific->insertSeparator();
543 addFlyAction(tr("BETAI(x,a,b)"), tr("BETAI(x,a,b)"), "BETAI(",submenuFuncScientific); 543 addFlyAction(tr("BETAI(x,a,b)"), tr("BETAI(x,a,b)"), "BETAI(",submenuFuncScientific);
544 addFlyAction(tr("ERF(a,b)"), tr("ERF(a,b)"), "ERF(",submenuFuncScientific); 544 addFlyAction(tr("ERF(a,b)"), tr("ERF(a,b)"), "ERF(",submenuFuncScientific);
545 addFlyAction(tr("ERFC(a,b)"), tr("ERFC(a,b)"), "ERFC(",submenuFuncScientific); 545 addFlyAction(tr("ERFC(a,b)"), tr("ERFC(a,b)"), "ERFC(",submenuFuncScientific);
546 addFlyAction(tr("GAMMALN(x)"), tr("GAMMALN(x)"), "GAMMALN(",submenuFuncScientific); 546 addFlyAction(tr("GAMMALN(x)"), tr("GAMMALN(x)"), "GAMMALN(",submenuFuncScientific);
547 addFlyAction(tr("GAMMAP(x,a)"), tr("GAMMAP(x,a)"), "GAMMAP(",submenuFuncScientific); 547 addFlyAction(tr("GAMMAP(x,a)"), tr("GAMMAP(x,a)"), "GAMMAP(",submenuFuncScientific);
548 addFlyAction(tr("GAMMAQ(x,a)"), tr("GAMMAQ(x,a)"), "GAMMAQ(",submenuFuncScientific); 548 addFlyAction(tr("GAMMAQ(x,a)"), tr("GAMMAQ(x,a)"), "GAMMAQ(",submenuFuncScientific);
549 submenuFunc->insertItem(tr("Scienti&fic"), submenuFuncScientific); 549 submenuFunc->insertItem(tr("Scienti&fic"), submenuFuncScientific);
550 550
551 submenuFuncDistr=new QPopupMenu; 551 submenuFuncDistr=new QPopupMenu;
552 addFlyAction(tr("BETADIST(z,a,b,Q?)"), tr("BETADIST(z,a,b,Q?)"), "BETADIST(",submenuFuncDistr); 552 addFlyAction(tr("BETADIST(z,a,b,Q?)"), tr("BETADIST(z,a,b,Q?)"), "BETADIST(",submenuFuncDistr);
553 addFlyAction(tr("CHI2DIST(x,n,Q?)"), tr("CHI2DIST(x,n,Q?)"), "CHI2DIST(",submenuFuncDistr); 553 addFlyAction(tr("CHI2DIST(x,n,Q?)"), tr("CHI2DIST(x,n,Q?)"), "CHI2DIST(",submenuFuncDistr);
554 addFlyAction(tr("CHIDIST(x,n,Q?)"), tr("CHIDIST(x,n,Q?)"), "CHIDIST(",submenuFuncDistr); 554 addFlyAction(tr("CHIDIST(x,n,Q?)"), tr("CHIDIST(x,n,Q?)"), "CHIDIST(",submenuFuncDistr);
555 addFlyAction(tr("FDIST(z,deg1,deg2,Q?)"), tr("FDIST(z,deg1,deg2,Q?)"), "FDIST(",submenuFuncDistr); 555 addFlyAction(tr("FDIST(z,deg1,deg2,Q?)"), tr("FDIST(z,deg1,deg2,Q?)"), "FDIST(",submenuFuncDistr);
556 addFlyAction(tr("GAMMADIST(x,a,b,Q?)"), tr("GAMMADIST(x,a,b,Q?)"), "GAMMADIST(",submenuFuncDistr); 556 addFlyAction(tr("GAMMADIST(x,a,b,Q?)"), tr("GAMMADIST(x,a,b,Q?)"), "GAMMADIST(",submenuFuncDistr);
557 addFlyAction(tr("NORMALDIST(x,m,s,Q?)"), tr("NORMALDIST(x,m,s,Q?)"), "NORMALDIST(",submenuFuncDistr); 557 addFlyAction(tr("NORMALDIST(x,m,s,Q?)"), tr("NORMALDIST(x,m,s,Q?)"), "NORMALDIST(",submenuFuncDistr);
558 addFlyAction(tr("PHI(x,Q?)"), tr("PHI(x,Q?)"), "PHI(",submenuFuncDistr); 558 addFlyAction(tr("PHI(x,Q?)"), tr("PHI(x,Q?)"), "PHI(",submenuFuncDistr);
559 addFlyAction(tr("POISSON(x,n,Q?)"), tr("POISSON(x,n,Q?)"), "POISSON(",submenuFuncDistr); 559 addFlyAction(tr("POISSON(x,n,Q?)"), tr("POISSON(x,n,Q?)"), "POISSON(",submenuFuncDistr);
560 submenuFunc->insertItem(tr("&Distributions"), submenuFuncDistr); 560 submenuFunc->insertItem(tr("&Distributions"), submenuFuncDistr);
561 561
562 562
563 563
564 menuInsert->insertSeparator(); 564 menuInsert->insertSeparator();
565 insertCells->addTo(menuInsert); 565 insertCells->addTo(menuInsert);
566 insertRows->addTo(menuInsert); 566 insertRows->addTo(menuInsert);
567 insertCols->addTo(menuInsert); 567 insertCols->addTo(menuInsert);
568 insertSheets->addTo(menuInsert); 568 insertSheets->addTo(menuInsert);
569} 569}
570 570
571void MainWindow::initStandardToolbar() 571void MainWindow::initStandardToolbar()
572{ 572{
573 toolbarStandard=new QToolBar(this); 573 toolbarStandard=new QToolBar(this);
574 toolbarStandard->setHorizontalStretchable(TRUE); 574 toolbarStandard->setHorizontalStretchable(TRUE);
575 moveToolBar(toolbarStandard, Top); 575 moveToolBar(toolbarStandard, Top);
576 576
577 fileNew->addTo(toolbarStandard); 577 fileNew->addTo(toolbarStandard);
578 fileOpen->addTo(toolbarStandard); 578 fileOpen->addTo(toolbarStandard);
579 fileSave->addTo(toolbarStandard); 579 fileSave->addTo(toolbarStandard);
580 580
581 comboSheets=new QComboBox(toolbarStandard); 581 comboSheets=new QComboBox(toolbarStandard);
582 toolbarStandard->setStretchableWidget(comboSheets); 582 toolbarStandard->setStretchableWidget(comboSheets);
583 connect(comboSheets, SIGNAL(activated(const QString &)), this, SLOT(slotSheetChanged(const QString &))); 583 connect(comboSheets, SIGNAL(activated(const QString&)), this, SLOT(slotSheetChanged(const QString&)));
584} 584}
585 585
586void MainWindow::initFunctionsToolbar() 586void MainWindow::initFunctionsToolbar()
587{ 587{
588 toolbarFunctions=new QToolBar(this); 588 toolbarFunctions=new QToolBar(this);
589 toolbarFunctions->setHorizontalStretchable(TRUE); 589 toolbarFunctions->setHorizontalStretchable(TRUE);
590 moveToolBar(toolbarFunctions, Bottom); 590 moveToolBar(toolbarFunctions, Bottom);
591 591
592 funcEqual->addTo(toolbarFunctions); 592 funcEqual->addTo(toolbarFunctions);
593 funcPlus->addTo(toolbarFunctions); 593 funcPlus->addTo(toolbarFunctions);
594 funcMinus->addTo(toolbarFunctions); 594 funcMinus->addTo(toolbarFunctions);
595 funcCross->addTo(toolbarFunctions); 595 funcCross->addTo(toolbarFunctions);
596 funcDivide->addTo(toolbarFunctions); 596 funcDivide->addTo(toolbarFunctions);
597 funcParanOpen->addTo(toolbarFunctions); 597 funcParanOpen->addTo(toolbarFunctions);
598 funcParanClose->addTo(toolbarFunctions); 598 funcParanClose->addTo(toolbarFunctions);
599 funcComma->addTo(toolbarFunctions); 599 funcComma->addTo(toolbarFunctions);
600 600
601 toolFunction=new QToolButton(toolbarFunctions); 601 toolFunction=new QToolButton(toolbarFunctions);
602 toolFunction->setPixmap(Resource::loadPixmap( "opie-sheet/func-func" )); 602 toolFunction->setPixmap(Resource::loadPixmap( "opie-sheet/func-func" ));
603 toolFunction->setTextLabel(tr("Functions")); 603 toolFunction->setTextLabel(tr("Functions"));
604 toolFunction->setPopup(submenuFunc); 604 toolFunction->setPopup(submenuFunc);
605 toolFunction->setPopupDelay(0); 605 toolFunction->setPopupDelay(0);
606} 606}
607 607
608void MainWindow::initEditToolbar() 608void MainWindow::initEditToolbar()
609{ 609{
610 toolbarEdit=new QToolBar(this); 610 toolbarEdit=new QToolBar(this);
611 toolbarEdit->setHorizontalStretchable(TRUE); 611 toolbarEdit->setHorizontalStretchable(TRUE);
612 moveToolBar(toolbarEdit, Bottom); 612 moveToolBar(toolbarEdit, Bottom);
613 613
614 editAccept->addTo(toolbarEdit); 614 editAccept->addTo(toolbarEdit);
615 editCancel->addTo(toolbarEdit); 615 editCancel->addTo(toolbarEdit);
616 616
617 editData=new QLineEdit(toolbarEdit); 617 editData=new QLineEdit(toolbarEdit);
618 toolbarEdit->setStretchableWidget(editData); 618 toolbarEdit->setStretchableWidget(editData);
619 connect(editData, SIGNAL(returnPressed()), this, SLOT(slotEditAccept())); 619 connect(editData, SIGNAL(returnPressed()), this, SLOT(slotEditAccept()));
620 620
621 editCellSelect->addTo(toolbarEdit); 621 editCellSelect->addTo(toolbarEdit);
622} 622}
623 623
624void MainWindow::slotHelpAbout() 624void MainWindow::slotHelpAbout()
625{ 625{
626 QDialog dialogAbout(this, 0, TRUE); 626 QDialog dialogAbout(this, 0, TRUE);
627 dialogAbout.resize(width()-40, height()-80); 627 dialogAbout.resize(width()-40, height()-80);
628 dialogAbout.setCaption(tr("About Opie Sheet")); 628 dialogAbout.setCaption(tr("About Opie Sheet"));
629 629
630 QLabel label(tr("Opie Sheet\nSpreadsheet Software for Opie\nQWDC Beta Winner (as Sheet/Qt)\n\nDeveloped by: Serdar Ozler\nRelease 1.0.2\nRelease Date: October 08, 2002\n\nThis product is licensed under GPL. It is freely distributable. If you want to get the latest version and also the source code, please visit the web site.\n\nhttp://qtopia.sitebest.com"), &dialogAbout); 630 QLabel label(tr("Opie Sheet\nSpreadsheet Software for Opie\nQWDC Beta Winner (as Sheet/Qt)\n\nDeveloped by: Serdar Ozler\nRelease 1.0.2\nRelease Date: October 08, 2002\n\nThis product is licensed under GPL. It is freely distributable. If you want to get the latest version and also the source code, please visit the web site.\n\nhttp://qtopia.sitebest.com"), &dialogAbout);
631 label.setGeometry(dialogAbout.rect()); 631 label.setGeometry(dialogAbout.rect());
632 label.setAlignment(Qt::AlignCenter | Qt::WordBreak); 632 label.setAlignment(Qt::AlignCenter | Qt::WordBreak);
633 633
634 dialogAbout.exec(); 634 dialogAbout.exec();
635} 635}
636 636
637void MainWindow::initSheet() 637void MainWindow::initSheet()
638{ 638{
639 sheet=new Sheet(DEFAULT_NUM_ROWS, DEFAULT_NUM_COLS, this); 639 sheet=new Sheet(DEFAULT_NUM_ROWS, DEFAULT_NUM_COLS, this);
640 setCentralWidget(sheet); 640 setCentralWidget(sheet);
641 641
642 connect(sheet, SIGNAL(currentDataChanged(const QString &)), editData, SLOT(setText(const QString &))); 642 connect(sheet, SIGNAL(currentDataChanged(const QString&)), editData, SLOT(setText(const QString&)));
643 connect(sheet, SIGNAL(cellClicked(const QString &)), this, SLOT(slotCellClicked(const QString &))); 643 connect(sheet, SIGNAL(cellClicked(const QString&)), this, SLOT(slotCellClicked(const QString&)));
644 connect(sheet, SIGNAL(sheetModified()), this, SLOT(slotDocModified())); 644 connect(sheet, SIGNAL(sheetModified()), this, SLOT(slotDocModified()));
645 645
646 connect(editCut, SIGNAL(activated()), sheet, SLOT(editCut())); 646 connect(editCut, SIGNAL(activated()), sheet, SLOT(editCut()));
647 connect(editCopy, SIGNAL(activated()), sheet, SLOT(editCopy())); 647 connect(editCopy, SIGNAL(activated()), sheet, SLOT(editCopy()));
648 connect(editClear, SIGNAL(activated()), sheet, SLOT(editClear())); 648 connect(editClear, SIGNAL(activated()), sheet, SLOT(editClear()));
649} 649}
650 650
651void MainWindow::slotEditAccept() 651void MainWindow::slotEditAccept()
652{ 652{
653 sheet->setData(editData->text()); 653 sheet->setData(editData->text());
654} 654}
655 655
656void MainWindow::slotEditCancel() 656void MainWindow::slotEditCancel()
657{ 657{
658 editData->setText(sheet->getData()); 658 editData->setText(sheet->getData());
659} 659}
660 660
661void MainWindow::slotCellSelect(bool lock) 661void MainWindow::slotCellSelect(bool lock)
662{ 662{
663 sheet->lockClicks(lock); 663 sheet->lockClicks(lock);
664} 664}
665 665
666void MainWindow::addToData(const QString &data) 666void MainWindow::addToData(const QString &data)
667{ 667{
668 editData->setText(editData->text().insert(editData->cursorPosition(), data)); 668 editData->setText(editData->text().insert(editData->cursorPosition(), data));
669} 669}
670 670
671void MainWindow::slotFuncOutput() 671void MainWindow::slotFuncOutput()
672{ 672{
673 if (sender()->isA("QAction")) 673 if (sender()->isA("QAction"))
674 addToData(((QAction *)sender())->toolTip()); 674 addToData(((QAction *)sender())->toolTip());
675} 675}
676 676
677void MainWindow::slotInsertRows() 677void MainWindow::slotInsertRows()
678{ 678{
679 NumberDialog dialogNumber(this); 679 NumberDialog dialogNumber(this);
680 if (dialogNumber.exec(tr("Insert Rows"), tr("&Number of rows:"))==QDialog::Accepted) 680 if (dialogNumber.exec(tr("Insert Rows"), tr("&Number of rows:"))==QDialog::Accepted)
681 sheet->insertRows(dialogNumber.getValue()); 681 sheet->insertRows(dialogNumber.getValue());
682} 682}
683 683
684void MainWindow::slotInsertCols() 684void MainWindow::slotInsertCols()
685{ 685{
686 NumberDialog dialogNumber(this); 686 NumberDialog dialogNumber(this);
687 if (dialogNumber.exec(tr("Insert Columns"), tr("&Number of columns:"))==QDialog::Accepted) 687 if (dialogNumber.exec(tr("Insert Columns"), tr("&Number of columns:"))==QDialog::Accepted)
688 sheet->insertColumns(dialogNumber.getValue()); 688 sheet->insertColumns(dialogNumber.getValue());
689} 689}
690 690
691void MainWindow::slotInsertSheets() 691void MainWindow::slotInsertSheets()
692{ 692{
693 NumberDialog dialogNumber(this); 693 NumberDialog dialogNumber(this);
694 if (dialogNumber.exec(tr("Add Sheets"), tr("&Number of sheets:"))==QDialog::Accepted) 694 if (dialogNumber.exec(tr("Add Sheets"), tr("&Number of sheets:"))==QDialog::Accepted)
695 for (int i=dialogNumber.getValue(); i>0; --i) createNewSheet(); 695 for (int i=dialogNumber.getValue(); i>0; --i) createNewSheet();
696} 696}
697 697
698void MainWindow::slotCellClicked(const QString &cell) 698void MainWindow::slotCellClicked(const QString &cell)
699{ 699{
700 editCellSelect->setOn(FALSE); 700 editCellSelect->setOn(FALSE);
701 addToData(cell); 701 addToData(cell);
702} 702}
703 703
704typeSheet *MainWindow::createNewSheet() 704typeSheet *MainWindow::createNewSheet()
705{ 705{
706 typeSheet *newSheet=new typeSheet; 706 typeSheet *newSheet=new typeSheet;
707 int currentNo=1, tempNo=0; 707 int currentNo=1, tempNo=0;
708 bool ok; 708 bool ok;
709 709
710 for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) 710 for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next())
711 if (tempSheet->name.startsWith(tr("Sheet")) && (tempNo=tempSheet->name.mid(tr("Sheet").length()).toInt(&ok))>=currentNo && ok) 711 if (tempSheet->name.startsWith(tr("Sheet")) && (tempNo=tempSheet->name.mid(tr("Sheet").length()).toInt(&ok))>=currentNo && ok)
712 currentNo=tempNo+1; 712 currentNo=tempNo+1;
713 713
714 newSheet->name=tr("Sheet")+QString::number(currentNo); 714 newSheet->name=tr("Sheet")+QString::number(currentNo);
715 newSheet->data.setAutoDelete(TRUE); 715 newSheet->data.setAutoDelete(TRUE);
716 716
717 comboSheets->insertItem(newSheet->name); 717 comboSheets->insertItem(newSheet->name);
718 listSheets.append(newSheet); 718 listSheets.append(newSheet);
719 return newSheet; 719 return newSheet;
720} 720}
721 721
722typeSheet *MainWindow::findSheet(const QString &name) 722typeSheet *MainWindow::findSheet(const QString &name)
723{ 723{
724 for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) 724 for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next())
725 if (tempSheet->name==name) 725 if (tempSheet->name==name)
726 return tempSheet; 726 return tempSheet;
727 return NULL; 727 return NULL;
728} 728}
729 729
730void MainWindow::slotSheetChanged(const QString &name) 730void MainWindow::slotSheetChanged(const QString &name)
731{ 731{
732 sheet->copySheetData(&findSheet(sheet->getName())->data); 732 sheet->copySheetData(&findSheet(sheet->getName())->data);
733 sheet->setName(name); 733 sheet->setName(name);
734 sheet->setSheetData(&findSheet(name)->data); 734 sheet->setSheetData(&findSheet(name)->data);
735 sheet->ReCalc(); 735 sheet->ReCalc();
736} 736}
737 737
738void MainWindow::addFlyAction(const QString &text, const QString &menuText, const QString &tip, QWidget *w) 738void MainWindow::addFlyAction(const QString &text, const QString &menuText, const QString &tip, QWidget *w)
739{ 739{
740 QAction *action=new QAction(text, menuText, 0, this); 740 QAction *action=new QAction(text, menuText, 0, this);
741 action->setToolTip(tip); 741 action->setToolTip(tip);
742 connect(action, SIGNAL(activated()), this, SLOT(slotFuncOutput())); 742 connect(action, SIGNAL(activated()), this, SLOT(slotFuncOutput()));
743 action->addTo(w); 743 action->addTo(w);
744} 744}
745 745
746void MainWindow::slotFormatCells() 746void MainWindow::slotFormatCells()
747{ 747{
748 CellFormat dialogCellFormat(this); 748 CellFormat dialogCellFormat(this);
749 QPEApplication::showDialog( &dialogCellFormat ); 749 QPEApplication::showDialog( &dialogCellFormat );
750 dialogCellFormat.exec(sheet); 750 dialogCellFormat.exec(sheet);
751} 751}
752 752
753void MainWindow::slotEditPaste() 753void MainWindow::slotEditPaste()
754{ 754{
755 sheet->editPaste(); 755 sheet->editPaste();
756} 756}
757 757
758void MainWindow::slotEditPasteContents() 758void MainWindow::slotEditPasteContents()
759{ 759{
760 sheet->editPaste(TRUE); 760 sheet->editPaste(TRUE);
761} 761}
762 762
763void MainWindow::slotRowHeight() 763void MainWindow::slotRowHeight()
764{ 764{
765 int row1, row2, col1, col2; 765 int row1, row2, col1, col2;
766 sheet->getSelection(&row1, &col1, &row2, &col2); 766 sheet->getSelection(&row1, &col1, &row2, &col2);
767 767
768 NumberDialog dialogNumber(this); 768 NumberDialog dialogNumber(this);
769 if (dialogNumber.exec(tr("Row Height"), tr("&Height of each row:"), sheet->rowHeight(row1))==QDialog::Accepted) 769 if (dialogNumber.exec(tr("Row Height"), tr("&Height of each row:"), sheet->rowHeight(row1))==QDialog::Accepted)
770 { 770 {
771 int newHeight=dialogNumber.getValue(), row; 771 int newHeight=dialogNumber.getValue(), row;
772 for (row=row1; row<=row2; ++row) 772 for (row=row1; row<=row2; ++row)
773 sheet->setRowHeight(row, newHeight); 773 sheet->setRowHeight(row, newHeight);
774 } 774 }
775} 775}
776 776
777void MainWindow::slotRowAdjust() 777void MainWindow::slotRowAdjust()
778{ 778{
779 int row1, row2, col1, col2; 779 int row1, row2, col1, col2;
780 sheet->getSelection(&row1, &col1, &row2, &col2); 780 sheet->getSelection(&row1, &col1, &row2, &col2);
781 781
782 for (int row=row1; row<=row2; ++row) 782 for (int row=row1; row<=row2; ++row)
783 sheet->adjustRow(row); 783 sheet->adjustRow(row);
784} 784}
785 785
786void MainWindow::slotRowShow() 786void MainWindow::slotRowShow()
787{ 787{
788 int row1, row2, col1, col2; 788 int row1, row2, col1, col2;
789 sheet->getSelection(&row1, &col1, &row2, &col2); 789 sheet->getSelection(&row1, &col1, &row2, &col2);
790 790
791 for (int row=row1; row<=row2; ++row) 791 for (int row=row1; row<=row2; ++row)
792 sheet->showRow(row); 792 sheet->showRow(row);
793} 793}
794 794
795void MainWindow::slotRowHide() 795void MainWindow::slotRowHide()
796{ 796{
797 int row1, row2, col1, col2; 797 int row1, row2, col1, col2;
798 sheet->getSelection(&row1, &col1, &row2, &col2); 798 sheet->getSelection(&row1, &col1, &row2, &col2);
799 799
800 for (int row=row1; row<=row2; ++row) 800 for (int row=row1; row<=row2; ++row)
801 sheet->hideRow(row); 801 sheet->hideRow(row);
802} 802}
803 803
804void MainWindow::slotColumnWidth() 804void MainWindow::slotColumnWidth()
805{ 805{
806 int row1, row2, col1, col2; 806 int row1, row2, col1, col2;
807 sheet->getSelection(&row1, &col1, &row2, &col2); 807 sheet->getSelection(&row1, &col1, &row2, &col2);
808 808
809 NumberDialog dialogNumber(this); 809 NumberDialog dialogNumber(this);
810 if (dialogNumber.exec(tr("Column Width"), tr("&Width of each column:"), sheet->columnWidth(col1))==QDialog::Accepted) 810 if (dialogNumber.exec(tr("Column Width"), tr("&Width of each column:"), sheet->columnWidth(col1))==QDialog::Accepted)
811 { 811 {
812 int newWidth=dialogNumber.getValue(), col; 812 int newWidth=dialogNumber.getValue(), col;
813 for (col=col1; col<=col2; ++col) 813 for (col=col1; col<=col2; ++col)
814 sheet->setColumnWidth(col, newWidth); 814 sheet->setColumnWidth(col, newWidth);
815 } 815 }
816} 816}
817 817
818void MainWindow::slotColumnAdjust() 818void MainWindow::slotColumnAdjust()
819{ 819{
820 int row1, row2, col1, col2; 820 int row1, row2, col1, col2;
821 sheet->getSelection(&row1, &col1, &row2, &col2); 821 sheet->getSelection(&row1, &col1, &row2, &col2);
822 822
823 for (int col=col1; col<=col2; ++col) 823 for (int col=col1; col<=col2; ++col)
824 sheet->adjustColumn(col); 824 sheet->adjustColumn(col);
825} 825}
826 826
827void MainWindow::slotColumnShow() 827void MainWindow::slotColumnShow()
828{ 828{
829 int row1, row2, col1, col2; 829 int row1, row2, col1, col2;
830 sheet->getSelection(&row1, &col1, &row2, &col2); 830 sheet->getSelection(&row1, &col1, &row2, &col2);
831 831
832 for (int col=col1; col<=col2; ++col) 832 for (int col=col1; col<=col2; ++col)
833 sheet->showColumn(col); 833 sheet->showColumn(col);
834} 834}
835 835
836void MainWindow::slotColumnHide() 836void MainWindow::slotColumnHide()
837{ 837{
838 int row1, row2, col1, col2; 838 int row1, row2, col1, col2;
839 sheet->getSelection(&row1, &col1, &row2, &col2); 839 sheet->getSelection(&row1, &col1, &row2, &col2);
840 840
841 for (int col=col1; col<=col2; ++col) 841 for (int col=col1; col<=col2; ++col)
842 sheet->hideColumn(col); 842 sheet->hideColumn(col);
843} 843}
844 844
845void MainWindow::slotFileSaveAs() 845void MainWindow::slotFileSaveAs()
846{ 846{
847 TextDialog dialogText(this); 847 TextDialog dialogText(this);
848 if (dialogText.exec(tr("Save File As"), tr("&File Name:"), currentDoc->name())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return; 848 if (dialogText.exec(tr("Save File As"), tr("&File Name:"), currentDoc->name())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return;
849 849
850 currentDoc->setName(dialogText.getValue()); 850 currentDoc->setName(dialogText.getValue());
851 currentDoc->setFile(QString::null); 851 currentDoc->setFile(QString::null);
852 currentDoc->setLinkFile(QString::null); 852 currentDoc->setLinkFile(QString::null);
853 documentSave(currentDoc); 853 documentSave(currentDoc);
854} 854}
855 855
856void MainWindow::slotImportExcel(const DocLnk &lnkDoc) 856void MainWindow::slotImportExcel(const DocLnk &lnkDoc)
857{ 857{
858 ExcelBook file1; 858 ExcelBook file1;
859 file1.ParseBook((char *)lnkDoc.file().ascii()); 859 file1.ParseBook((char *)lnkDoc.file().ascii());
860 int NumOfSheets=file1.Sheets.count(); 860 int NumOfSheets=file1.Sheets.count();
861 printf("OpieSheet::NumberOfSheets:%d\r\n",NumOfSheets); 861 printf("OpieSheet::NumberOfSheets:%d\r\n",NumOfSheets);
862 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; 862 if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return;
863 if (currentDoc) delete currentDoc; 863 if (currentDoc) delete currentDoc;
864 currentDoc = new DocLnk(); 864 currentDoc = new DocLnk();
865 listSheets.clear(); 865 listSheets.clear();
866 comboSheets->clear(); 866 comboSheets->clear();
867 int w1,r,c; 867 int w1,r,c;
868 ExcelSheet* sh1; 868 ExcelSheet* sh1;
869 typeSheet* newSheet; 869 typeSheet* newSheet;
870 QString* str; 870 QString* str;
871 typeCellData* newCell; 871 typeCellData* newCell;
872 for(w1=1;w1<=NumOfSheets;w1++) 872 for(w1=1;w1<=NumOfSheets;w1++)
873 { 873 {
874 sh1=file1.Sheets[w1-1]; 874 sh1=file1.Sheets[w1-1];
875 printf("OpieSheet:newSheet:%x,r=%d,c=%d\r\n",sh1,sh1->rows,sh1->cols); 875 printf("OpieSheet:newSheet:%x,r=%d,c=%d\r\n",sh1,sh1->rows,sh1->cols);
876 newSheet=new typeSheet; 876 newSheet=new typeSheet;
877 newSheet->data.setAutoDelete(TRUE); 877 newSheet->data.setAutoDelete(TRUE);
878 newSheet->name=sh1->name; 878 newSheet->name=sh1->name;
879 printf("OpieSheet:Sheetname:%s\r\n",sh1->name.ascii()); 879 printf("OpieSheet:Sheetname:%s\r\n",sh1->name.ascii());
880 comboSheets->insertItem(newSheet->name); 880 comboSheets->insertItem(newSheet->name);
881 for(r=1; r <= sh1->rows; r++) 881 for(r=1; r <= sh1->rows; r++)
882 { 882 {
883 for(c=1;c <= sh1->cols; c++) 883 for(c=1;c <= sh1->cols; c++)
884 { 884 {
885 str=file1.CellDataString(sh1,r-1,c-1); 885 str=file1.CellDataString(sh1,r-1,c-1);
886 if(str!=NULL && r<DEFAULT_NUM_ROWS && c<DEFAULT_NUM_COLS) 886 if(str!=NULL && r<DEFAULT_NUM_ROWS && c<DEFAULT_NUM_COLS)
887 { 887 {
888 newCell=new typeCellData; 888 newCell=new typeCellData;
889 newCell->row=r-1; 889 newCell->row=r-1;
890 newCell->col=c-1; 890 newCell->col=c-1;
891 if(str!=NULL) newCell->data=QString(*str); else newCell->data=QString(""); 891 if(str!=NULL) newCell->data=QString(*str); else newCell->data=QString("");
892 newCell->background=QBrush(Qt::white, Qt::SolidPattern); 892 newCell->background=QBrush(Qt::white, Qt::SolidPattern);
893 newCell->alignment=(Qt::AlignmentFlags)(Qt::AlignLeft | Qt::AlignTop); 893 newCell->alignment=(Qt::AlignmentFlags)(Qt::AlignLeft | Qt::AlignTop);
894 newCell->fontColor=Qt::black; 894 newCell->fontColor=Qt::black;
895 newCell->font=font(); 895 newCell->font=font();
896 newCell->borders.right=QPen(Qt::gray, 1, Qt::SolidLine); 896 newCell->borders.right=QPen(Qt::gray, 1, Qt::SolidLine);
897 newCell->borders.bottom=QPen(Qt::gray, 1, Qt::SolidLine); 897 newCell->borders.bottom=QPen(Qt::gray, 1, Qt::SolidLine);
898 newSheet->data.append(newCell); 898 newSheet->data.append(newCell);
899 //there is no format parsing at the moment or style parsing 899 //there is no format parsing at the moment or style parsing
900 //printf("OpieSheetNumber:row=%d,col=%d,val=%s\r\n",r,c,str->latin1()); 900 //printf("OpieSheetNumber:row=%d,col=%d,val=%s\r\n",r,c,str->latin1());
901 }; 901 };
902 }; 902 };
903 }; 903 };
904 listSheets.append(newSheet); 904 listSheets.append(newSheet);
905 if (w1==1)//if i==0 link sheet1 with sheetview 905 if (w1==1)//if i==0 link sheet1 with sheetview
906 { 906 {
907 sheet->setName(newSheet->name); 907 sheet->setName(newSheet->name);
908 sheet->setSheetData(&newSheet->data); 908 sheet->setSheetData(&newSheet->data);
909 sheet->ReCalc(); 909 sheet->ReCalc();
910 }; 910 };
911 911
912 }; 912 };
913 file1.CloseFile(); 913 file1.CloseFile();
914 printf("Excel FILE read OK\r\n"); 914 printf("Excel FILE read OK\r\n");
915 documentModified=TRUE; 915 documentModified=TRUE;
916 916
917 917
918} 918}
919 919
920void MainWindow::slotSheetRename() 920void MainWindow::slotSheetRename()
921{ 921{
922 TextDialog dialogText(this); 922 TextDialog dialogText(this);
923 if (dialogText.exec(tr("Rename Sheet"), tr("&Sheet Name:"), sheet->getName())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return; 923 if (dialogText.exec(tr("Rename Sheet"), tr("&Sheet Name:"), sheet->getName())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return;
924 QString newName=dialogText.getValue(); 924 QString newName=dialogText.getValue();
925 925
926 typeSheet *tempSheet=findSheet(newName); 926 typeSheet *tempSheet=findSheet(newName);
927 if (tempSheet) 927 if (tempSheet)
928 { 928 {
929 QMessageBox::critical(this, tr("Error"), tr("There is already a sheet named '"+newName+'\'')); 929 QMessageBox::critical(this, tr("Error"), tr("There is already a sheet named '"+newName+'\''));
930 return; 930 return;
931 } 931 }
932 932
933 tempSheet=findSheet(sheet->getName()); 933 tempSheet=findSheet(sheet->getName());
934 for (int i=0; i<comboSheets->count(); ++i) 934 for (int i=0; i<comboSheets->count(); ++i)
935 if (comboSheets->text(i)==tempSheet->name) 935 if (comboSheets->text(i)==tempSheet->name)
936 { 936 {
937 comboSheets->changeItem(newName, i); 937 comboSheets->changeItem(newName, i);
938 break; 938 break;
939 } 939 }
940 tempSheet->name=newName; 940 tempSheet->name=newName;
941 sheet->setName(newName); 941 sheet->setName(newName);
942} 942}
943 943
944void MainWindow::slotSheetRemove() 944void MainWindow::slotSheetRemove()
945{ 945{
946 if (comboSheets->count()<2) 946 if (comboSheets->count()<2)
947 { 947 {
948 QMessageBox::warning(this, tr("Error"), tr("There is only one sheet!")); 948 QMessageBox::warning(this, tr("Error"), tr("There is only one sheet!"));
949 return; 949 return;
950 } 950 }
951 if (QMessageBox::information(this, tr("Remove Sheet"), tr("Are you sure?"), QMessageBox::Yes, QMessageBox::No)==QMessageBox::Yes) 951 if (QMessageBox::information(this, tr("Remove Sheet"), tr("Are you sure?"), QMessageBox::Yes, QMessageBox::No)==QMessageBox::Yes)
952 { 952 {
953 typeSheet *tempSheet=findSheet(sheet->getName()); 953 typeSheet *tempSheet=findSheet(sheet->getName());
954 for (int i=0; i<comboSheets->count(); ++i) 954 for (int i=0; i<comboSheets->count(); ++i)
955 if (comboSheets->text(i)==tempSheet->name) 955 if (comboSheets->text(i)==tempSheet->name)
956 { 956 {
957 comboSheets->removeItem(i); 957 comboSheets->removeItem(i);
958 break; 958 break;
959 } 959 }
960 comboSheets->setCurrentItem(0); 960 comboSheets->setCurrentItem(0);
961 slotSheetChanged(comboSheets->currentText()); 961 slotSheetChanged(comboSheets->currentText());
962 listSheets.remove(tempSheet); 962 listSheets.remove(tempSheet);
963 } 963 }
964} 964}
965 965
966void MainWindow::slotDataSort() 966void MainWindow::slotDataSort()
967{ 967{
968 SortDialog dialogSort(this); 968 SortDialog dialogSort(this);
969 QPEApplication::showDialog( &dialogSort ); 969 QPEApplication::showDialog( &dialogSort );
970 dialogSort.exec(sheet); 970 dialogSort.exec(sheet);
971} 971}
972 972
973void MainWindow::slotDocModified() 973void MainWindow::slotDocModified()
974{ 974{
975 documentModified=TRUE; 975 documentModified=TRUE;
976} 976}
977 977
978void MainWindow::slotInsertCells() 978void MainWindow::slotInsertCells()
979{ 979{
980 QDialog dialogInsert(this, 0, TRUE); 980 QDialog dialogInsert(this, 0, TRUE);
981 dialogInsert.resize(180, 130); 981 dialogInsert.resize(180, 130);
982 dialogInsert.setCaption(tr("Insert Cells")); 982 dialogInsert.setCaption(tr("Insert Cells"));
983 983
984 QVButtonGroup *group=new QVButtonGroup(tr("&Type"), &dialogInsert); 984 QVButtonGroup *group=new QVButtonGroup(tr("&Type"), &dialogInsert);
985 group->setGeometry(10, 10, 160, 110); 985 group->setGeometry(10, 10, 160, 110);
986 QRadioButton *radio=new QRadioButton(tr("Shift cells &down"), group); 986 QRadioButton *radio=new QRadioButton(tr("Shift cells &down"), group);
987 radio=new QRadioButton(tr("Shift cells &right"), group); 987 radio=new QRadioButton(tr("Shift cells &right"), group);
988 radio=new QRadioButton(tr("Entire ro&w"), group); 988 radio=new QRadioButton(tr("Entire ro&w"), group);
989 radio=new QRadioButton(tr("Entire &column"), group); 989 radio=new QRadioButton(tr("Entire &column"), group);
990 group->setButton(0); 990 group->setButton(0);
991 991
992 if (dialogInsert.exec()==QDialog::Accepted) 992 if (dialogInsert.exec()==QDialog::Accepted)
993 switch (group->id(group->selected())) 993 switch (group->id(group->selected()))
994 { 994 {
995 case 0: sheet->insertRows(1, FALSE); break; 995 case 0: sheet->insertRows(1, FALSE); break;
996 case 1: sheet->insertColumns(1, FALSE); break; 996 case 1: sheet->insertColumns(1, FALSE); break;
997 case 2: sheet->insertRows(1, TRUE); break; 997 case 2: sheet->insertRows(1, TRUE); break;
998 case 3: sheet->insertColumns(1, TRUE); break; 998 case 3: sheet->insertColumns(1, TRUE); break;
999 } 999 }
1000} 1000}
1001 1001
1002void MainWindow::slotDataFindReplace() 1002void MainWindow::slotDataFindReplace()
1003{ 1003{
1004 FindDialog dialogFind(this); 1004 FindDialog dialogFind(this);
1005 QPEApplication::showDialog( &dialogFind ); 1005 QPEApplication::showDialog( &dialogFind );
1006 dialogFind.exec(sheet); 1006 dialogFind.exec(sheet);
1007} 1007}
diff --git a/noncore/apps/opie-sheet/sheet.cpp b/noncore/apps/opie-sheet/sheet.cpp
index f303d33..d4419af 100644
--- a/noncore/apps/opie-sheet/sheet.cpp
+++ b/noncore/apps/opie-sheet/sheet.cpp
@@ -1,2566 +1,2566 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10/* 10/*
11 * Opie Sheet (formerly Sheet/Qt) 11 * Opie Sheet (formerly Sheet/Qt)
12 * by Serdar Ozler <sozler@sitebest.com> 12 * by Serdar Ozler <sozler@sitebest.com>
13 */ 13 */
14 14
15#include "sheet.h" 15#include "sheet.h"
16 16
17#include <qmessagebox.h> 17#include <qmessagebox.h>
18#include <math.h> 18#include <math.h>
19#include <stdlib.h> 19#include <stdlib.h>
20#include <stdio.h> 20#include <stdio.h>
21#include <time.h> 21#include <time.h>
22 22
23#define DEFAULT_COL_WIDTH 50 23#define DEFAULT_COL_WIDTH 50
24 24
25Sheet::Sheet(int numRows, int numCols, QWidget *parent) 25Sheet::Sheet(int numRows, int numCols, QWidget *parent)
26 :QTable(numRows, numCols, parent) 26 :QTable(numRows, numCols, parent)
27{ 27{
28 defaultBorders.right=defaultBorders.bottom=QPen(Qt::gray, 1, Qt::SolidLine); 28 defaultBorders.right=defaultBorders.bottom=QPen(Qt::gray, 1, Qt::SolidLine);
29 defaultCellData.data=""; 29 defaultCellData.data="";
30 defaultCellData.background=QBrush(Qt::white, Qt::SolidPattern); 30 defaultCellData.background=QBrush(Qt::white, Qt::SolidPattern);
31 defaultCellData.alignment=(Qt::AlignmentFlags)(Qt::AlignLeft | Qt::AlignTop); 31 defaultCellData.alignment=(Qt::AlignmentFlags)(Qt::AlignLeft | Qt::AlignTop);
32 defaultCellData.fontColor=Qt::black; 32 defaultCellData.fontColor=Qt::black;
33 defaultCellData.font=font(); 33 defaultCellData.font=font();
34 defaultCellData.borders=defaultBorders; 34 defaultCellData.borders=defaultBorders;
35 35
36 clicksLocked=FALSE; 36 clicksLocked=FALSE;
37 selectionNo=-1; 37 selectionNo=-1;
38 setSelectionMode(QTable::Single); 38 setSelectionMode(QTable::Single);
39 39
40 sheetData.setAutoDelete(TRUE); 40 sheetData.setAutoDelete(TRUE);
41 clipboardData.setAutoDelete(TRUE); 41 clipboardData.setAutoDelete(TRUE);
42 for (int i=0; i<numCols; ++i) 42 for (int i=0; i<numCols; ++i)
43 horizontalHeader()->setLabel(i, getHeaderString(i+1), DEFAULT_COL_WIDTH); 43 horizontalHeader()->setLabel(i, getHeaderString(i+1), DEFAULT_COL_WIDTH);
44 44
45 45
46 connect(this, SIGNAL(currentChanged(int, int)), this, SLOT(slotCellSelected(int, int))); 46 connect(this, SIGNAL(currentChanged(int,int)), this, SLOT(slotCellSelected(int,int)));
47 connect(this, SIGNAL(valueChanged(int, int)), this, SLOT(slotCellChanged(int, int))); 47 connect(this, SIGNAL(valueChanged(int,int)), this, SLOT(slotCellChanged(int,int)));
48} 48}
49 49
50Sheet::~Sheet() 50Sheet::~Sheet()
51{ 51{
52} 52}
53 53
54typeCellData *Sheet::findCellData(int row, int col) 54typeCellData *Sheet::findCellData(int row, int col)
55{ 55{
56 typeCellData *tempCellData; 56 typeCellData *tempCellData;
57 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 57 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
58 { 58 {
59 if (tempCellData->row==row && tempCellData->col==col) return tempCellData; 59 if (tempCellData->row==row && tempCellData->col==col) return tempCellData;
60 } 60 }
61 return NULL; 61 return NULL;
62} 62}
63 63
64void Sheet::slotCellSelected(int row, int col) 64void Sheet::slotCellSelected(int row, int col)
65{ 65{
66 typeCellData *cellData=findCellData(row, col); 66 typeCellData *cellData=findCellData(row, col);
67 if (cellData) 67 if (cellData)
68 { 68 {
69 emit currentDataChanged(cellData->data); 69 emit currentDataChanged(cellData->data);
70 }else 70 }else
71 emit currentDataChanged(""); 71 emit currentDataChanged("");
72} 72}
73 73
74typeCellData *Sheet::createCellData(int row, int col) 74typeCellData *Sheet::createCellData(int row, int col)
75{ 75{
76 if (row<0 || col<0) return NULL; 76 if (row<0 || col<0) return NULL;
77 typeCellData *cellData=new typeCellData; 77 typeCellData *cellData=new typeCellData;
78 cellData->row=row; 78 cellData->row=row;
79 cellData->col=col; 79 cellData->col=col;
80 cellData->data=defaultCellData.data; 80 cellData->data=defaultCellData.data;
81 cellData->borders=defaultCellData.borders; 81 cellData->borders=defaultCellData.borders;
82 cellData->alignment=defaultCellData.alignment; 82 cellData->alignment=defaultCellData.alignment;
83 cellData->font=defaultCellData.font; 83 cellData->font=defaultCellData.font;
84 cellData->fontColor=defaultCellData.fontColor; 84 cellData->fontColor=defaultCellData.fontColor;
85 cellData->background=defaultCellData.background; 85 cellData->background=defaultCellData.background;
86 sheetData.append(cellData); 86 sheetData.append(cellData);
87 return cellData; 87 return cellData;
88} 88}
89 89
90void Sheet::slotCellChanged(int row, int col) 90void Sheet::slotCellChanged(int row, int col)
91{ 91{
92 typeCellData *cellData=findCellData(row, col); 92 typeCellData *cellData=findCellData(row, col);
93 if (!cellData) cellData=createCellData(row, col); 93 if (!cellData) cellData=createCellData(row, col);
94 if (cellData) cellData->data=text(row, col); 94 if (cellData) cellData->data=text(row, col);
95 for (cellData=sheetData.first(); cellData; cellData=sheetData.next()) 95 for (cellData=sheetData.first(); cellData; cellData=sheetData.next())
96 { 96 {
97 // modified by Toussis Manolis koppermind@panafonet.gr 97 // modified by Toussis Manolis koppermind@panafonet.gr
98 // the parser was crashing if there were no closed parenthesis. 98 // the parser was crashing if there were no closed parenthesis.
99 int w1,ii=0; 99 int w1,ii=0;
100 for(w1=0;w1<=(int)text(row, col).length();w1++) 100 for(w1=0;w1<=(int)text(row, col).length();w1++)
101 { 101 {
102 if(text(row,col)[w1]=='(') ii++; 102 if(text(row,col)[w1]=='(') ii++;
103 if(text(row,col)[w1]==')') ii--; 103 if(text(row,col)[w1]==')') ii--;
104 }; 104 };
105 if(ii==0) setText(cellData->row, cellData->col, dataParser(findCellName(cellData->row, cellData->col), cellData->data)); 105 if(ii==0) setText(cellData->row, cellData->col, dataParser(findCellName(cellData->row, cellData->col), cellData->data));
106 //end of modification 106 //end of modification
107 // old was plain: 107 // old was plain:
108 //setText(cellData->row, cellData->col, dataParser(findCellName(cellData->row, cellData->col), cellData->data)); 108 //setText(cellData->row, cellData->col, dataParser(findCellName(cellData->row, cellData->col), cellData->data));
109 }; 109 };
110 emit sheetModified(); 110 emit sheetModified();
111} 111}
112 112
113 113
114void Sheet::ReCalc(void) 114void Sheet::ReCalc(void)
115{ 115{
116 typeCellData* cellData; 116 typeCellData* cellData;
117 for (cellData=sheetData.first(); cellData; cellData=sheetData.next()) 117 for (cellData=sheetData.first(); cellData; cellData=sheetData.next())
118 { 118 {
119 //printf("cellchanged:%d, %d\r\n",cellData->row,cellData->col); 119 //printf("cellchanged:%d, %d\r\n",cellData->row,cellData->col);
120 120
121 slotCellChanged(cellData->row,cellData->col); 121 slotCellChanged(cellData->row,cellData->col);
122 }; 122 };
123}; 123};
124 124
125 125
126 126
127 127
128void Sheet::swapCells(int row1, int col1, int row2, int col2) 128void Sheet::swapCells(int row1, int col1, int row2, int col2)
129{ 129{
130 typeCellData *cellData1=findCellData(row1, col1), *cellData2=findCellData(row2, col2); 130 typeCellData *cellData1=findCellData(row1, col1), *cellData2=findCellData(row2, col2);
131 if (!cellData1) cellData1=createCellData(row1, col1); 131 if (!cellData1) cellData1=createCellData(row1, col1);
132 if (!cellData2) cellData2=createCellData(row2, col2); 132 if (!cellData2) cellData2=createCellData(row2, col2);
133 if (cellData1 && cellData2) 133 if (cellData1 && cellData2)
134 { 134 {
135 QString tempData(cellData1->data); 135 QString tempData(cellData1->data);
136 cellData1->data=cellData2->data; 136 cellData1->data=cellData2->data;
137 cellData2->data=tempData; 137 cellData2->data=tempData;
138 setText(cellData1->row, cellData1->col, dataParser(findCellName(cellData1->row, cellData1->col), cellData1->data)); 138 setText(cellData1->row, cellData1->col, dataParser(findCellName(cellData1->row, cellData1->col), cellData1->data));
139 setText(cellData2->row, cellData2->col, dataParser(findCellName(cellData2->row, cellData2->col), cellData2->data)); 139 setText(cellData2->row, cellData2->col, dataParser(findCellName(cellData2->row, cellData2->col), cellData2->data));
140 emit sheetModified(); 140 emit sheetModified();
141 } 141 }
142} 142}
143 143
144QString Sheet::getParameter(const QString &parameters, int paramNo, bool giveError, const QString funcName) 144QString Sheet::getParameter(const QString &parameters, int paramNo, bool giveError, const QString funcName)
145{ 145{
146 QString params(parameters); 146 QString params(parameters);
147 int position; 147 int position;
148 for (int i=0; i<paramNo; ++i) 148 for (int i=0; i<paramNo; ++i)
149 { 149 {
150 position=params.find(','); 150 position=params.find(',');
151 if (position<0) 151 if (position<0)
152 { 152 {
153 if (giveError) QMessageBox::critical(this, tr("Error"), tr("Too few arguments to function '"+funcName+'\'')); 153 if (giveError) QMessageBox::critical(this, tr("Error"), tr("Too few arguments to function '"+funcName+'\''));
154 //printf("params:%s\r\n",parameters.ascii()); 154 //printf("params:%s\r\n",parameters.ascii());
155 return QString(NULL); 155 return QString(NULL);
156 } 156 }
157 params=params.mid(position+1); 157 params=params.mid(position+1);
158 } 158 }
159 position=params.find(','); 159 position=params.find(',');
160 if (position<0) return params; 160 if (position<0) return params;
161 return params.left(position); 161 return params.left(position);
162} 162}
163 163
164bool Sheet::findRange(const QString &variable1, const QString &variable2, int *row1, int *col1, int *row2, int *col2) 164bool Sheet::findRange(const QString &variable1, const QString &variable2, int *row1, int *col1, int *row2, int *col2)
165{ 165{
166 int row, col; 166 int row, col;
167 if (!findRowColumn(variable1, row1, col1, FALSE) || !findRowColumn(variable2, row2, col2, FALSE)) return FALSE; 167 if (!findRowColumn(variable1, row1, col1, FALSE) || !findRowColumn(variable2, row2, col2, FALSE)) return FALSE;
168 if (*row1>*row2) 168 if (*row1>*row2)
169 { 169 {
170 row=*row1; 170 row=*row1;
171 *row1=*row2; 171 *row1=*row2;
172 *row2=row; 172 *row2=row;
173 } 173 }
174 if (*col1>*col2) 174 if (*col1>*col2)
175 { 175 {
176 col=*col1; 176 col=*col1;
177 *col1=*col2; 177 *col1=*col2;
178 *col2=col; 178 *col2=col;
179 } 179 }
180 return TRUE; 180 return TRUE;
181} 181}
182 182
183bool Sheet::findRowColumn(const QString &variable, int *row, int *col, bool giveError) 183bool Sheet::findRowColumn(const QString &variable, int *row, int *col, bool giveError)
184{ 184{
185 int position=variable.find(QRegExp("\\d")); 185 int position=variable.find(QRegExp("\\d"));
186 if (position<1) 186 if (position<1)
187 { 187 {
188 if (giveError) QMessageBox::critical(this, tr("Error"), tr("Invalid variable: '"+variable+'\'')); 188 if (giveError) QMessageBox::critical(this, tr("Error"), tr("Invalid variable: '"+variable+'\''));
189 return FALSE; 189 return FALSE;
190 } 190 }
191 *row=variable.mid(position).toInt()-1; 191 *row=variable.mid(position).toInt()-1;
192 *col=getHeaderColumn(variable.left(position))-1; 192 *col=getHeaderColumn(variable.left(position))-1;
193 return TRUE; 193 return TRUE;
194} 194}
195 195
196QString Sheet::calculateVariable(const QString &variable) 196QString Sheet::calculateVariable(const QString &variable)
197{ 197{
198 bool ok; 198 bool ok;
199 printf("calculateVariable=%s,len=%d\r\n",variable.ascii(),variable.length()); 199 printf("calculateVariable=%s,len=%d\r\n",variable.ascii(),variable.length());
200 if(variable.left(1)=="\"") return QString(variable.mid(1,variable.length()-2)); 200 if(variable.left(1)=="\"") return QString(variable.mid(1,variable.length()-2));
201 double tempResult=variable.toDouble(&ok); 201 double tempResult=variable.toDouble(&ok);
202 if (ok) 202 if (ok)
203 { 203 {
204 if(tempResult!=0.0) 204 if(tempResult!=0.0)
205 { 205 {
206 return QString::number(tempResult); 206 return QString::number(tempResult);
207 } 207 }
208 else 208 else
209 { 209 {
210 if(variable!="0" || variable!="0.0") return QString(variable); // hereis a string variable 210 if(variable!="0" || variable!="0.0") return QString(variable); // hereis a string variable
211 return QString::number(tempResult); 211 return QString::number(tempResult);
212 }; 212 };
213 }; 213 };
214 214
215 int row, col; 215 int row, col;
216 if(findRowColumn(variable, &row, &col, FALSE)) return dataParser(variable, text(row,col)); 216 if(findRowColumn(variable, &row, &col, FALSE)) return dataParser(variable, text(row,col));
217 //return (findRowColumn(variable, &row, &col, TRUE) ? dataParser(variable, text(row, col)) : 0); 217 //return (findRowColumn(variable, &row, &col, TRUE) ? dataParser(variable, text(row, col)) : 0);
218 return QString(variable); 218 return QString(variable);
219} 219}
220 220
221double Sheet::BesselI0(double x) 221double Sheet::BesselI0(double x)
222{ 222{
223 //Returns the modi ed Bessel function I0(x) for any real x. 223 //Returns the modi ed Bessel function I0(x) for any real x.
224 double ax,ans; 224 double ax,ans;
225 double y; 225 double y;
226 if ((ax=fabs(x)) < 3.75) 226 if ((ax=fabs(x)) < 3.75)
227 { 227 {
228 y=x/3.75; 228 y=x/3.75;
229 y*=y; 229 y*=y;
230 ans=1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492 +y*(0.2659732+y*(0.360768e-1+y*0.45813e-2))))); 230 ans=1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492 +y*(0.2659732+y*(0.360768e-1+y*0.45813e-2)))));
231 }else 231 }else
232 { 232 {
233 y=3.75/ax; 233 y=3.75/ax;
234 ans=(exp(ax)/sqrt(ax))*(0.39894228+y*(0.1328592e-1 +y*(0.225319e-2+y*(-0.157565e-2+y*(0.916281e-2 +y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1 +y*0.392377e-2)))))))); 234 ans=(exp(ax)/sqrt(ax))*(0.39894228+y*(0.1328592e-1 +y*(0.225319e-2+y*(-0.157565e-2+y*(0.916281e-2 +y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1 +y*0.392377e-2))))))));
235 } 235 }
236 return ans; 236 return ans;
237}; 237};
238 238
239double Sheet::BesselI1(double x) 239double Sheet::BesselI1(double x)
240{ 240{
241 double ax,ans; 241 double ax,ans;
242 double y; 242 double y;
243 if ((ax=fabs(x)) < 3.75) 243 if ((ax=fabs(x)) < 3.75)
244 { 244 {
245 y=x/3.75; 245 y=x/3.75;
246 y*=y; 246 y*=y;
247 ans=ax*(0.5+y*(0.87890594+y*(0.51498869+y*(0.15084934 +y*(0.2658733e-1+y*(0.301532e-2+y*0.32411e-3)))))); 247 ans=ax*(0.5+y*(0.87890594+y*(0.51498869+y*(0.15084934 +y*(0.2658733e-1+y*(0.301532e-2+y*0.32411e-3))))));
248 } else 248 } else
249 { 249 {
250 y=3.75/ax; 250 y=3.75/ax;
251 ans=0.2282967e-1+y*(-0.2895312e-1+y*(0.1787654e-1 -y*0.420059e-2)); ans=0.39894228+y*(-0.3988024e-1+y*(-0.362018e-2 +y*(0.163801e-2+y*(-0.1031555e-1+y*ans)))); 251 ans=0.2282967e-1+y*(-0.2895312e-1+y*(0.1787654e-1 -y*0.420059e-2)); ans=0.39894228+y*(-0.3988024e-1+y*(-0.362018e-2 +y*(0.163801e-2+y*(-0.1031555e-1+y*ans))));
252 ans *= (exp(ax)/sqrt(ax)); 252 ans *= (exp(ax)/sqrt(ax));
253 } 253 }
254 return x < 0.0 ? -ans : ans; 254 return x < 0.0 ? -ans : ans;
255}; 255};
256 256
257double Sheet::BesselI(int n, double x) 257double Sheet::BesselI(int n, double x)
258{ 258{
259 double ACC=40.0; 259 double ACC=40.0;
260 double BIGNO=1.0e10; 260 double BIGNO=1.0e10;
261 double BIGNI=1.0e-10; 261 double BIGNI=1.0e-10;
262 int j; 262 int j;
263 double bi,bim,bip,tox,ans; 263 double bi,bim,bip,tox,ans;
264 if (n < 2) return 0.0; 264 if (n < 2) return 0.0;
265 if (x == 0.0) return 0.0; else 265 if (x == 0.0) return 0.0; else
266 { 266 {
267 tox=2.0/fabs(x); 267 tox=2.0/fabs(x);
268 bip=ans=0.0; 268 bip=ans=0.0;
269 bi=1.0; 269 bi=1.0;
270 for (j=2*(n+(int) sqrt(ACC*n));j>0;j--) 270 for (j=2*(n+(int) sqrt(ACC*n));j>0;j--)
271 { 271 {
272 bim=bip+j*tox*bi; 272 bim=bip+j*tox*bi;
273 bip=bi; 273 bip=bi;
274 bi=bim; 274 bi=bim;
275 if (fabs(bi) > BIGNO) 275 if (fabs(bi) > BIGNO)
276 { 276 {
277 ans *= BIGNI; 277 ans *= BIGNI;
278 bi *= BIGNI; 278 bi *= BIGNI;
279 bip *= BIGNI; 279 bip *= BIGNI;
280 } 280 }
281 if (j == n) ans=bip; 281 if (j == n) ans=bip;
282 } 282 }
283 ans *= BesselI0(x)/bi; 283 ans *= BesselI0(x)/bi;
284 return x < 0.0 && (n & 1) ? -ans : ans; 284 return x < 0.0 && (n & 1) ? -ans : ans;
285 } 285 }
286}; 286};
287 287
288double Sheet::BesselK0(double x) 288double Sheet::BesselK0(double x)
289{ 289{
290 double y,ans; 290 double y,ans;
291 if (x <= 2.0) 291 if (x <= 2.0)
292 { 292 {
293 y=x*x/4.0; 293 y=x*x/4.0;
294 ans=(-log(x/2.0)*BesselI0(x))+(-0.57721566+y*(0.42278420 +y*(0.23069756+y*(0.3488590e-1+y*(0.262698e-2 +y*(0.10750e-3+y*0.74e-5)))))); 294 ans=(-log(x/2.0)*BesselI0(x))+(-0.57721566+y*(0.42278420 +y*(0.23069756+y*(0.3488590e-1+y*(0.262698e-2 +y*(0.10750e-3+y*0.74e-5))))));
295 } else 295 } else
296 { 296 {
297 y=2.0/x; 297 y=2.0/x;
298 ans=(exp(-x)/sqrt(x))*(1.25331414+y*(-0.7832358e-1 +y*(0.2189568e-1+y*(-0.1062446e-1+y*(0.587872e-2 +y*(-0.251540e-2+y*0.53208e-3)))))); 298 ans=(exp(-x)/sqrt(x))*(1.25331414+y*(-0.7832358e-1 +y*(0.2189568e-1+y*(-0.1062446e-1+y*(0.587872e-2 +y*(-0.251540e-2+y*0.53208e-3))))));
299 } 299 }
300return ans; 300return ans;
301}; 301};
302 302
303double Sheet::BesselK1(double x) 303double Sheet::BesselK1(double x)
304{ 304{
305 double y,ans; 305 double y,ans;
306 if (x <= 2.0) 306 if (x <= 2.0)
307 { 307 {
308 y=x*x/4.0; 308 y=x*x/4.0;
309 ans=(log(x/2.0)*BesselI1(x))+(1.0/x)*(1.0+y*(0.15443144 +y*(-0.67278579+y*(-0.18156897+y*(-0.1919402e-1 +y*(-0.110404e-2+y*(-0.4686e-4))))))); 309 ans=(log(x/2.0)*BesselI1(x))+(1.0/x)*(1.0+y*(0.15443144 +y*(-0.67278579+y*(-0.18156897+y*(-0.1919402e-1 +y*(-0.110404e-2+y*(-0.4686e-4)))))));
310 } else 310 } else
311 { 311 {
312 y=2.0/x; 312 y=2.0/x;
313 ans=(exp(-x)/sqrt(x))*(1.25331414+y*(0.23498619 +y*(-0.3655620e-1+y*(0.1504268e-1+y*(-0.780353e-2 +y*(0.325614e-2+y*(-0.68245e-3))))))); 313 ans=(exp(-x)/sqrt(x))*(1.25331414+y*(0.23498619 +y*(-0.3655620e-1+y*(0.1504268e-1+y*(-0.780353e-2 +y*(0.325614e-2+y*(-0.68245e-3)))))));
314 } 314 }
315 return ans; 315 return ans;
316}; 316};
317 317
318double Sheet::BesselK(int n, double x) 318double Sheet::BesselK(int n, double x)
319{ 319{
320 int j; 320 int j;
321 double bk,bkm,bkp,tox; 321 double bk,bkm,bkp,tox;
322 if (n < 2) return 0.0; 322 if (n < 2) return 0.0;
323 tox=2.0/x; 323 tox=2.0/x;
324 bkm=BesselK0(x); 324 bkm=BesselK0(x);
325 bk=BesselK1(x); 325 bk=BesselK1(x);
326 for (j=1;j<n;j++) 326 for (j=1;j<n;j++)
327 { 327 {
328 bkp=bkm+j*tox*bk; 328 bkp=bkm+j*tox*bk;
329 bkm=bk; 329 bkm=bk;
330 bk=bkp; 330 bk=bkp;
331 } 331 }
332 return bk; 332 return bk;
333}; 333};
334 334
335double Sheet::BesselJ0(double x) 335double Sheet::BesselJ0(double x)
336{ 336{
337 double ax,z; 337 double ax,z;
338 double xx,y,ans,ans1,ans2; 338 double xx,y,ans,ans1,ans2;
339 if ((ax=fabs(x)) < 8.0) 339 if ((ax=fabs(x)) < 8.0)
340 { 340 {
341 y=x*x; 341 y=x*x;
342 ans1=57568490574.0+y*(-13362590354.0+y*(651619640.7 +y*(-11214424.18+y*(77392.33017+y*(-184.9052456))))); 342 ans1=57568490574.0+y*(-13362590354.0+y*(651619640.7 +y*(-11214424.18+y*(77392.33017+y*(-184.9052456)))));
343 ans2=57568490411.0+y*(1029532985.0+y*(9494680.718 +y*(59272.64853+y*(267.8532712+y*1.0)))); 343 ans2=57568490411.0+y*(1029532985.0+y*(9494680.718 +y*(59272.64853+y*(267.8532712+y*1.0))));
344 ans=ans1/ans2; 344 ans=ans1/ans2;
345 } else 345 } else
346 { 346 {
347 z=8.0/ax; 347 z=8.0/ax;
348 y=z*z; 348 y=z*z;
349 xx=ax-0.785398164; 349 xx=ax-0.785398164;
350 ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 +y*(-0.2073370639e-5+y*0.2093887211e-6))); 350 ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 +y*(-0.2073370639e-5+y*0.2093887211e-6)));
351 ans2 = -0.1562499995e-1+y*(0.1430488765e-3 +y*(-0.6911147651e-5+y*(0.7621095161e-6 -y*0.934935152e-7))); 351 ans2 = -0.1562499995e-1+y*(0.1430488765e-3 +y*(-0.6911147651e-5+y*(0.7621095161e-6 -y*0.934935152e-7)));
352 ans=sqrt(0.636619772/ax)*(cos(xx)*ans1-z*sin(xx)*ans2); 352 ans=sqrt(0.636619772/ax)*(cos(xx)*ans1-z*sin(xx)*ans2);
353 } 353 }
354 return ans; 354 return ans;
355}; 355};
356 356
357double Sheet::BesselY0(double x) 357double Sheet::BesselY0(double x)
358{ 358{
359 double z; 359 double z;
360 double xx,y,ans,ans1,ans2; 360 double xx,y,ans,ans1,ans2;
361 if (x < 8.0) 361 if (x < 8.0)
362 { 362 {
363 y=x*x; 363 y=x*x;
364 ans1 = -2957821389.0+y*(7062834065.0+y*(-512359803.6 +y*(10879881.29+y*(-86327.92757+y*228.4622733)))); 364 ans1 = -2957821389.0+y*(7062834065.0+y*(-512359803.6 +y*(10879881.29+y*(-86327.92757+y*228.4622733))));
365 ans2=40076544269.0+y*(745249964.8+y*(7189466.438 +y*(47447.26470+y*(226.1030244+y*1.0)))); 365 ans2=40076544269.0+y*(745249964.8+y*(7189466.438 +y*(47447.26470+y*(226.1030244+y*1.0))));
366 ans=(ans1/ans2)+0.636619772*BesselJ0(x)*log(x); 366 ans=(ans1/ans2)+0.636619772*BesselJ0(x)*log(x);
367 } else 367 } else
368 { 368 {
369 z=8.0/x; 369 z=8.0/x;
370 y=z*z; 370 y=z*z;
371 xx=x-0.785398164; 371 xx=x-0.785398164;
372 ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 +y*(-0.2073370639e-5+y*0.2093887211e-6))); 372 ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 +y*(-0.2073370639e-5+y*0.2093887211e-6)));
373 ans2 = -0.1562499995e-1+y*(0.1430488765e-3 +y*(-0.6911147651e-5+y*(0.7621095161e-6 +y*(-0.934945152e-7)))); 373 ans2 = -0.1562499995e-1+y*(0.1430488765e-3 +y*(-0.6911147651e-5+y*(0.7621095161e-6 +y*(-0.934945152e-7))));
374 ans=sqrt(0.636619772/x)*(sin(xx)*ans1+z*cos(xx)*ans2); 374 ans=sqrt(0.636619772/x)*(sin(xx)*ans1+z*cos(xx)*ans2);
375 } 375 }
376 return ans; 376 return ans;
377}; 377};
378 378
379double Sheet::BesselJ1(double x) 379double Sheet::BesselJ1(double x)
380{ 380{
381 double ax,z; 381 double ax,z;
382 double xx,y,ans,ans1,ans2; 382 double xx,y,ans,ans1,ans2;
383 if ((ax=fabs(x)) < 8.0) 383 if ((ax=fabs(x)) < 8.0)
384 { 384 {
385 y=x*x; 385 y=x*x;
386 ans1=x*(72362614232.0+y*(-7895059235.0+y*(242396853.1 +y*(-2972611.439+y*(15704.48260+y*(-30.16036606)))))); 386 ans1=x*(72362614232.0+y*(-7895059235.0+y*(242396853.1 +y*(-2972611.439+y*(15704.48260+y*(-30.16036606))))));
387 ans2=144725228442.0+y*(2300535178.0+y*(18583304.74 +y*(99447.43394+y*(376.9991397+y*1.0)))); 387 ans2=144725228442.0+y*(2300535178.0+y*(18583304.74 +y*(99447.43394+y*(376.9991397+y*1.0))));
388 ans=ans1/ans2; 388 ans=ans1/ans2;
389 } else 389 } else
390 { 390 {
391 z=8.0/ax; y=z*z; xx=ax-2.356194491; 391 z=8.0/ax; y=z*z; xx=ax-2.356194491;
392 ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4 +y*(0.2457520174e-5+y*(-0.240337019e-6)))); 392 ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4 +y*(0.2457520174e-5+y*(-0.240337019e-6))));
393 ans2=0.04687499995+y*(-0.2002690873e-3 +y*(0.8449199096e-5+y*(-0.88228987e-6 +y*0.105787412e-6))); 393 ans2=0.04687499995+y*(-0.2002690873e-3 +y*(0.8449199096e-5+y*(-0.88228987e-6 +y*0.105787412e-6)));
394 ans=sqrt(0.636619772/ax)*(cos(xx)*ans1-z*sin(xx)*ans2); 394 ans=sqrt(0.636619772/ax)*(cos(xx)*ans1-z*sin(xx)*ans2);
395 if (x < 0.0) ans = -ans; 395 if (x < 0.0) ans = -ans;
396 } 396 }
397 return ans; 397 return ans;
398}; 398};
399 399
400double Sheet::BesselY1(double x) 400double Sheet::BesselY1(double x)
401{ 401{
402 double z; 402 double z;
403 double xx,y,ans,ans1,ans2; 403 double xx,y,ans,ans1,ans2;
404 if (x < 8.0) 404 if (x < 8.0)
405 { 405 {
406 y=x*x; 406 y=x*x;
407 ans1=x*(-0.4900604943e13+y*(0.1275274390e13 +y*(-0.5153438139e11+y*(0.7349264551e9 +y*(-0.4237922726e7+y*0.8511937935e4))))); 407 ans1=x*(-0.4900604943e13+y*(0.1275274390e13 +y*(-0.5153438139e11+y*(0.7349264551e9 +y*(-0.4237922726e7+y*0.8511937935e4)))));
408 ans2=0.2499580570e14+y*(0.4244419664e12 +y*(0.3733650367e10+y*(0.2245904002e8 +y*(0.1020426050e6+y*(0.3549632885e3+y))))); 408 ans2=0.2499580570e14+y*(0.4244419664e12 +y*(0.3733650367e10+y*(0.2245904002e8 +y*(0.1020426050e6+y*(0.3549632885e3+y)))));
409 ans=(ans1/ans2)+0.636619772*(BesselJ1(x)*log(x)-1.0/x); 409 ans=(ans1/ans2)+0.636619772*(BesselJ1(x)*log(x)-1.0/x);
410 } else 410 } else
411 { 411 {
412 z=8.0/x; 412 z=8.0/x;
413 y=z*z; 413 y=z*z;
414 xx=x-2.356194491; 414 xx=x-2.356194491;
415 ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4 +y*(0.2457520174e-5+y*(-0.240337019e-6)))); 415 ans1=1.0+y*(0.183105e-2+y*(-0.3516396496e-4 +y*(0.2457520174e-5+y*(-0.240337019e-6))));
416 ans2=0.04687499995+y*(-0.2002690873e-3 +y*(0.8449199096e-5+y*(-0.88228987e-6 +y*0.105787412e-6))); 416 ans2=0.04687499995+y*(-0.2002690873e-3 +y*(0.8449199096e-5+y*(-0.88228987e-6 +y*0.105787412e-6)));
417 ans=sqrt(0.636619772/x)*(sin(xx)*ans1+z*cos(xx)*ans2); 417 ans=sqrt(0.636619772/x)*(sin(xx)*ans1+z*cos(xx)*ans2);
418 } 418 }
419 return ans; 419 return ans;
420}; 420};
421 421
422double Sheet::BesselY(int n, double x) 422double Sheet::BesselY(int n, double x)
423{ 423{
424 int j; 424 int j;
425 double by,bym,byp,tox; 425 double by,bym,byp,tox;
426 if (n < 2) return 0.0; 426 if (n < 2) return 0.0;
427 tox=2.0/x; 427 tox=2.0/x;
428 by=BesselY1(x); 428 by=BesselY1(x);
429 bym=BesselY0(x); 429 bym=BesselY0(x);
430 for (j=1;j<n;j++) 430 for (j=1;j<n;j++)
431 { 431 {
432 byp=j*tox*by-bym; 432 byp=j*tox*by-bym;
433 bym=by; 433 bym=by;
434 by=byp; 434 by=byp;
435 } 435 }
436 return by; 436 return by;
437}; 437};
438 438
439double Sheet::BesselJ(int n, double x) 439double Sheet::BesselJ(int n, double x)
440{ 440{
441 double ACC=40.0; 441 double ACC=40.0;
442 double BIGNO=1.0e10; 442 double BIGNO=1.0e10;
443 double BIGNI=1.0e-10; 443 double BIGNI=1.0e-10;
444 int j,jsum,m; 444 int j,jsum,m;
445 double ax,bj,bjm,bjp,sum,tox,ans; 445 double ax,bj,bjm,bjp,sum,tox,ans;
446 if (n < 2) return 0.0; 446 if (n < 2) return 0.0;
447 ax=fabs(x); 447 ax=fabs(x);
448 if (ax == 0.0) return 0.0; 448 if (ax == 0.0) return 0.0;
449 else if (ax > (double) n) 449 else if (ax > (double) n)
450 { 450 {
451 tox=2.0/ax; 451 tox=2.0/ax;
452 bjm=BesselJ0(ax); 452 bjm=BesselJ0(ax);
453 bj=BesselJ1(ax); 453 bj=BesselJ1(ax);
454 for (j=1;j<n;j++) 454 for (j=1;j<n;j++)
455 { 455 {
456 bjp=j*tox*bj-bjm; 456 bjp=j*tox*bj-bjm;
457 bjm=bj; 457 bjm=bj;
458 bj=bjp; 458 bj=bjp;
459 } 459 }
460 ans=bj; 460 ans=bj;
461 } else 461 } else
462 { 462 {
463 tox=2.0/ax; 463 tox=2.0/ax;
464 m=2*((n+(int) sqrt(ACC*n))/2); 464 m=2*((n+(int) sqrt(ACC*n))/2);
465 jsum=0; 465 jsum=0;
466 bjp=ans=sum=0.0; 466 bjp=ans=sum=0.0;
467 bj=1.0; 467 bj=1.0;
468 for (j=m;j>0;j--) 468 for (j=m;j>0;j--)
469 { 469 {
470 bjm=j*tox*bj-bjp; 470 bjm=j*tox*bj-bjp;
471 bjp=bj; 471 bjp=bj;
472 bj=bjm; 472 bj=bjm;
473 if (fabs(bj) > BIGNO) 473 if (fabs(bj) > BIGNO)
474 { 474 {
475 bj *= BIGNI; 475 bj *= BIGNI;
476 bjp *= BIGNI; 476 bjp *= BIGNI;
477 ans *= BIGNI; 477 ans *= BIGNI;
478 sum *= BIGNI; 478 sum *= BIGNI;
479 } 479 }
480 if (jsum) sum += bj; 480 if (jsum) sum += bj;
481 jsum=!jsum; 481 jsum=!jsum;
482 if (j == n) ans=bjp; 482 if (j == n) ans=bjp;
483 } 483 }
484 sum=2.0*sum-bj; 484 sum=2.0*sum-bj;
485 ans /= sum; 485 ans /= sum;
486 } 486 }
487 return x < 0.0 && (n & 1) ? -ans : ans; 487 return x < 0.0 && (n & 1) ? -ans : ans;
488}; 488};
489 489
490double Sheet::GammaLn(double xx) 490double Sheet::GammaLn(double xx)
491{ 491{
492 double x,y,tmp,ser; 492 double x,y,tmp,ser;
493 static double cof[6]={76.18009172947146,-86.50532032941677, 24.01409824083091,-1.231739572450155, 0.1208650973866179e-2,-0.5395239384953e-5}; 493 static double cof[6]={76.18009172947146,-86.50532032941677, 24.01409824083091,-1.231739572450155, 0.1208650973866179e-2,-0.5395239384953e-5};
494 int j; 494 int j;
495 y=x=xx; 495 y=x=xx;
496 tmp=x+5.5; 496 tmp=x+5.5;
497 tmp -= (x+0.5)*log(tmp); 497 tmp -= (x+0.5)*log(tmp);
498 ser=1.000000000190015; 498 ser=1.000000000190015;
499 for (j=0;j<=5;j++) ser += cof[j]/++y; 499 for (j=0;j<=5;j++) ser += cof[j]/++y;
500 return -tmp+log(2.5066282746310005*ser/x); 500 return -tmp+log(2.5066282746310005*ser/x);
501}; 501};
502 502
503double Sheet::Factorial(double n) 503double Sheet::Factorial(double n)
504{ 504{
505 if (n < 0) return 0.0; 505 if (n < 0) return 0.0;
506 if (n > 100) return 0.0; 506 if (n > 100) return 0.0;
507 return exp(GammaLn(n+1.0)); 507 return exp(GammaLn(n+1.0));
508}; 508};
509 509
510double Sheet::GammaP(double a, double x) 510double Sheet::GammaP(double a, double x)
511{ 511{
512// returns GammaP(a,x) 512// returns GammaP(a,x)
513//void gcf(float *gammcf, float a, float x, float *gln); 513//void gcf(float *gammcf, float a, float x, float *gln);
514//void gser(float *gamser, float a, float x, float *gln); 514//void gser(float *gamser, float a, float x, float *gln);
515 double gamser,gammcf,gln; 515 double gamser,gammcf,gln;
516 if (x < 0.0 || a <= 0.0) return 0.0;//error 516 if (x < 0.0 || a <= 0.0) return 0.0;//error
517 if (x < (a+1.0)) 517 if (x < (a+1.0))
518 { 518 {
519 GammaSeries(&gamser,a,x,&gln); 519 GammaSeries(&gamser,a,x,&gln);
520 return gamser; 520 return gamser;
521 }else 521 }else
522 { 522 {
523 GammaContinuedFraction(&gammcf,a,x,&gln); 523 GammaContinuedFraction(&gammcf,a,x,&gln);
524 return 1.0-gammcf; 524 return 1.0-gammcf;
525 } 525 }
526}; 526};
527 527
528double Sheet::GammaQ(double a,double x) 528double Sheet::GammaQ(double a,double x)
529{ 529{
530 //returns GammaQ(a,x)=1.0 - GammaP(a,x); 530 //returns GammaQ(a,x)=1.0 - GammaP(a,x);
531 return (1.0-GammaP(a,x)); 531 return (1.0-GammaP(a,x));
532}; 532};
533 533
534 534
535void Sheet::GammaSeries(double *gamser, double a, double x, double *gln) 535void Sheet::GammaSeries(double *gamser, double a, double x, double *gln)
536{ 536{
537 double EPS=3.0e-7; 537 double EPS=3.0e-7;
538 int ITMAX=100; 538 int ITMAX=100;
539 int n; 539 int n;
540 double sum,del,ap; 540 double sum,del,ap;
541 *gln=GammaLn(a); 541 *gln=GammaLn(a);
542 if (x <= 0.0) 542 if (x <= 0.0)
543 { 543 {
544 if (x < 0.0) return;//error 544 if (x < 0.0) return;//error
545 *gamser=0.0; 545 *gamser=0.0;
546 return; 546 return;
547 } else 547 } else
548 { 548 {
549 ap=a; 549 ap=a;
550 del=sum=1.0/a; 550 del=sum=1.0/a;
551 for (n=1;n<=ITMAX;n++) 551 for (n=1;n<=ITMAX;n++)
552 { 552 {
553 ++ap; 553 ++ap;
554 del *= x/ap; 554 del *= x/ap;
555 sum += del; 555 sum += del;
556 if (fabs(del) < fabs(sum)*EPS) 556 if (fabs(del) < fabs(sum)*EPS)
557 { 557 {
558 *gamser=sum*exp(-x+a*log(x)-(*gln)); 558 *gamser=sum*exp(-x+a*log(x)-(*gln));
559 return; 559 return;
560 } 560 }
561 } return; 561 } return;
562 return; 562 return;
563 } 563 }
564}; 564};
565 565
566 566
567void Sheet::GammaContinuedFraction(double *gammcf, double a, double x, double *gln) 567void Sheet::GammaContinuedFraction(double *gammcf, double a, double x, double *gln)
568{ 568{
569 double EPS=3.0e-7; 569 double EPS=3.0e-7;
570 double FPMIN=1.0e-30; 570 double FPMIN=1.0e-30;
571 int ITMAX=100; 571 int ITMAX=100;
572 int i; 572 int i;
573 double an,b,c,d,del,h; 573 double an,b,c,d,del,h;
574 *gln=GammaLn(a); 574 *gln=GammaLn(a);
575 b=x+1.0-a; 575 b=x+1.0-a;
576 c=1.0/FPMIN; 576 c=1.0/FPMIN;
577 d=1.0/b; h=d; 577 d=1.0/b; h=d;
578 for (i=1;i<=ITMAX;i++) 578 for (i=1;i<=ITMAX;i++)
579 { 579 {
580 an = -i*(i-a); 580 an = -i*(i-a);
581 b += 2.0; d=an*d+b; 581 b += 2.0; d=an*d+b;
582 if (fabs(d) < FPMIN) d=FPMIN; 582 if (fabs(d) < FPMIN) d=FPMIN;
583 c=b+an/c; 583 c=b+an/c;
584 if (fabs(c) < FPMIN) c=FPMIN; 584 if (fabs(c) < FPMIN) c=FPMIN;
585 d=1.0/d; del=d*c; h *= del; 585 d=1.0/d; del=d*c; h *= del;
586 if (fabs(del-1.0) < EPS) break; 586 if (fabs(del-1.0) < EPS) break;
587 } 587 }
588 if (i > ITMAX) return; 588 if (i > ITMAX) return;
589 *gammcf=exp(-x+a*log(x)-(*gln))*h; 589 *gammcf=exp(-x+a*log(x)-(*gln))*h;
590}; 590};
591 591
592double Sheet::ErrorFunction(double x) 592double Sheet::ErrorFunction(double x)
593{ 593{
594 return x < 0.0 ? -GammaP(0.5,x*x) : GammaP(0.5,x*x); 594 return x < 0.0 ? -GammaP(0.5,x*x) : GammaP(0.5,x*x);
595}; 595};
596 596
597double Sheet::ErrorFunctionComplementary(double x) 597double Sheet::ErrorFunctionComplementary(double x)
598{ 598{
599 return x < 0.0 ? 1.0+GammaP(0.5,x*x) : GammaQ(0.5,x*x); 599 return x < 0.0 ? 1.0+GammaP(0.5,x*x) : GammaQ(0.5,x*x);
600}; 600};
601 601
602double Sheet::Beta(double z, double w) 602double Sheet::Beta(double z, double w)
603{ 603{
604 return exp(GammaLn(z)+GammaLn(w)-GammaLn(z+w)); 604 return exp(GammaLn(z)+GammaLn(w)-GammaLn(z+w));
605}; 605};
606 606
607 607
608double Sheet::BetaContinuedFraction(double a, double b, double x) 608double Sheet::BetaContinuedFraction(double a, double b, double x)
609{ 609{
610 int MAXIT=100; 610 int MAXIT=100;
611 double EPS=3.0e-7; 611 double EPS=3.0e-7;
612 double FPMIN=1.0e-30; 612 double FPMIN=1.0e-30;
613 int m,m2; 613 int m,m2;
614 double aa,c,d,del,h,qab,qam,qap; 614 double aa,c,d,del,h,qab,qam,qap;
615 qab=a+b; 615 qab=a+b;
616 qap=a+1.0; qam=a-1.0; c=1.0; 616 qap=a+1.0; qam=a-1.0; c=1.0;
617 d=1.0-qab*x/qap; 617 d=1.0-qab*x/qap;
618 if (fabs(d) < FPMIN) d=FPMIN; 618 if (fabs(d) < FPMIN) d=FPMIN;
619 d=1.0/d; h=d; 619 d=1.0/d; h=d;
620 for (m=1;m<=MAXIT;m++) 620 for (m=1;m<=MAXIT;m++)
621 { 621 {
622 m2=2*m; aa=m*(b-m)*x/((qam+m2)*(a+m2)); 622 m2=2*m; aa=m*(b-m)*x/((qam+m2)*(a+m2));
623 d=1.0+aa*d; 623 d=1.0+aa*d;
624 if (fabs(d) < FPMIN) d=FPMIN; 624 if (fabs(d) < FPMIN) d=FPMIN;
625 c=1.0+aa/c; 625 c=1.0+aa/c;
626 if (fabs(c) < FPMIN) c=FPMIN; 626 if (fabs(c) < FPMIN) c=FPMIN;
627 d=1.0/d; h *= d*c; 627 d=1.0/d; h *= d*c;
628 aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2)); d=1.0+aa*d; 628 aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2)); d=1.0+aa*d;
629 if (fabs(d) < FPMIN) d=FPMIN; 629 if (fabs(d) < FPMIN) d=FPMIN;
630 c=1.0+aa/c; 630 c=1.0+aa/c;
631 if (fabs(c) < FPMIN) c=FPMIN; d=1.0/d; 631 if (fabs(c) < FPMIN) c=FPMIN; d=1.0/d;
632 del=d*c; h *= del; 632 del=d*c; h *= del;
633 if (fabs(del-1.0) < EPS) break; 633 if (fabs(del-1.0) < EPS) break;
634 } 634 }
635 if (m > MAXIT) return 0.0; 635 if (m > MAXIT) return 0.0;
636 return h; 636 return h;
637}; 637};
638 638
639double Sheet::BetaIncomplete(double a, double b, double x) 639double Sheet::BetaIncomplete(double a, double b, double x)
640{ 640{
641 double bt; 641 double bt;
642 if (x < 0.0 || x > 1.0) return 0.0; 642 if (x < 0.0 || x > 1.0) return 0.0;
643 if (x == 0.0 || x == 1.0) bt=0.0; else 643 if (x == 0.0 || x == 1.0) bt=0.0; else
644 bt=exp(GammaLn(a+b)-GammaLn(a)-GammaLn(b)+a*log(x)+b*log(1.0-x)); 644 bt=exp(GammaLn(a+b)-GammaLn(a)-GammaLn(b)+a*log(x)+b*log(1.0-x));
645 if (x < (a+1.0)/(a+b+2.0)) return bt*BetaContinuedFraction(a,b,x)/a; else 645 if (x < (a+1.0)/(a+b+2.0)) return bt*BetaContinuedFraction(a,b,x)/a; else
646 return 1.0-bt*BetaContinuedFraction(b,a,1.0-x)/b; 646 return 1.0-bt*BetaContinuedFraction(b,a,1.0-x)/b;
647}; 647};
648 648
649 649
650 650
651double Sheet::functionSum(const QString &param1, const QString &param2) 651double Sheet::functionSum(const QString &param1, const QString &param2)
652{ 652{
653 int row1, col1, row2, col2, row, col; 653 int row1, col1, row2, col2, row, col;
654 double result=0, tempResult; 654 double result=0, tempResult;
655 bool ok; 655 bool ok;
656 if (findRange(param1, param2, &row1, &col1, &row2, &col2)) 656 if (findRange(param1, param2, &row1, &col1, &row2, &col2))
657 { 657 {
658 for (row=row1; row<=row2; ++row) 658 for (row=row1; row<=row2; ++row)
659 for (col=col1; col<=col2; ++col) 659 for (col=col1; col<=col2; ++col)
660 { 660 {
661 tempResult=text(row, col).toDouble(&ok); 661 tempResult=text(row, col).toDouble(&ok);
662 if (ok) result+=tempResult; 662 if (ok) result+=tempResult;
663 } 663 }
664 return result; 664 return result;
665 }else 665 }else
666 { 666 {
667 double d1=0,d2=0; 667 double d1=0,d2=0;
668 d1=calculateVariable(param1).toDouble(&ok); 668 d1=calculateVariable(param1).toDouble(&ok);
669 d2=calculateVariable(param2).toDouble(&ok); 669 d2=calculateVariable(param2).toDouble(&ok);
670 return(d1+d2); 670 return(d1+d2);
671 }; 671 };
672 return 0; 672 return 0;
673} 673}
674 674
675QString Sheet::functionIndex(const QString &param1, const QString &param2, int indx) 675QString Sheet::functionIndex(const QString &param1, const QString &param2, int indx)
676{ 676{
677 int row1, col1, row2, col2, row, col; 677 int row1, col1, row2, col2, row, col;
678 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0; 678 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0;
679 int ii=1; 679 int ii=1;
680 for (col=col1; col<=col2; ++col) 680 for (col=col1; col<=col2; ++col)
681 for (row=row1; row<=row2; ++row) 681 for (row=row1; row<=row2; ++row)
682 { 682 {
683 if(ii==indx) return text(row,col); 683 if(ii==indx) return text(row,col);
684 ii++; 684 ii++;
685 } 685 }
686 return QString(""); 686 return QString("");
687} 687}
688 688
689 689
690 690
691double Sheet::functionVariancePopulation(const QString &param1, const QString &param2) 691double Sheet::functionVariancePopulation(const QString &param1, const QString &param2)
692{ 692{
693 int row1, col1, row2, col2, row, col; 693 int row1, col1, row2, col2, row, col;
694 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0; 694 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0;
695 double avg1=functionAvg(param1,param2); 695 double avg1=functionAvg(param1,param2);
696 double result=0, tempResult; 696 double result=0, tempResult;
697 int count1=0; 697 int count1=0;
698 bool ok; 698 bool ok;
699 for (row=row1; row<=row2; ++row) 699 for (row=row1; row<=row2; ++row)
700 for (col=col1; col<=col2; ++col) 700 for (col=col1; col<=col2; ++col)
701 { 701 {
702 tempResult=text(row, col).toDouble(&ok); 702 tempResult=text(row, col).toDouble(&ok);
703 if (ok) { result=result + (tempResult - avg1)*(tempResult - avg1); count1++;}; 703 if (ok) { result=result + (tempResult - avg1)*(tempResult - avg1); count1++;};
704 } 704 }
705 if(count1>0) result=result/double(count1); else result=0.0; 705 if(count1>0) result=result/double(count1); else result=0.0;
706 return result; 706 return result;
707}; 707};
708 708
709double Sheet::functionVariance(const QString &param1, const QString &param2) 709double Sheet::functionVariance(const QString &param1, const QString &param2)
710{ 710{
711 int row1, col1, row2, col2, row, col; 711 int row1, col1, row2, col2, row, col;
712 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0; 712 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0;
713 double avg1=functionAvg(param1,param2); 713 double avg1=functionAvg(param1,param2);
714 double result=0, tempResult; 714 double result=0, tempResult;
715 int count1=0; 715 int count1=0;
716 bool ok; 716 bool ok;
717 for (row=row1; row<=row2; ++row) 717 for (row=row1; row<=row2; ++row)
718 for (col=col1; col<=col2; ++col) 718 for (col=col1; col<=col2; ++col)
719 { 719 {
720 tempResult=text(row, col).toDouble(&ok); 720 tempResult=text(row, col).toDouble(&ok);
721 if (ok) { result=result + (tempResult - avg1)*(tempResult - avg1); count1++;}; 721 if (ok) { result=result + (tempResult - avg1)*(tempResult - avg1); count1++;};
722 } 722 }
723 if(count1>1) result=result/double(count1-1); else result=0.0; 723 if(count1>1) result=result/double(count1-1); else result=0.0;
724 return result; 724 return result;
725}; 725};
726 726
727double Sheet::functionSkew(const QString &param1, const QString &param2) 727double Sheet::functionSkew(const QString &param1, const QString &param2)
728{ 728{
729 int row1, col1, row2, col2, row, col; 729 int row1, col1, row2, col2, row, col;
730 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0; 730 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0;
731 double avg1=functionAvg(param1,param2); 731 double avg1=functionAvg(param1,param2);
732 double var1=sqrt(functionVariancePopulation(param1,param2)); 732 double var1=sqrt(functionVariancePopulation(param1,param2));
733 if(var1==0.0) return 0.0; 733 if(var1==0.0) return 0.0;
734 double result=0, tempResult; 734 double result=0, tempResult;
735 int count1=0; 735 int count1=0;
736 bool ok; 736 bool ok;
737 for (row=row1; row<=row2; ++row) 737 for (row=row1; row<=row2; ++row)
738 for (col=col1; col<=col2; ++col) 738 for (col=col1; col<=col2; ++col)
739 { 739 {
740 tempResult=text(row, col).toDouble(&ok); 740 tempResult=text(row, col).toDouble(&ok);
741 if (ok) 741 if (ok)
742 { 742 {
743 result=result + (tempResult - avg1)*(tempResult - avg1)*(tempResult - avg1)/(var1*var1*var1); 743 result=result + (tempResult - avg1)*(tempResult - avg1)*(tempResult - avg1)/(var1*var1*var1);
744 count1++; 744 count1++;
745 }; 745 };
746 } 746 }
747 if(count1>0) result=result/double(count1); else result=0.0; 747 if(count1>0) result=result/double(count1); else result=0.0;
748 return result; 748 return result;
749}; 749};
750 750
751double Sheet::functionKurt(const QString &param1, const QString &param2) 751double Sheet::functionKurt(const QString &param1, const QString &param2)
752{ 752{
753 int row1, col1, row2, col2, row, col; 753 int row1, col1, row2, col2, row, col;
754 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0; 754 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0;
755 double avg1=functionAvg(param1,param2); 755 double avg1=functionAvg(param1,param2);
756 double var1=sqrt(functionVariancePopulation(param1,param2)); 756 double var1=sqrt(functionVariancePopulation(param1,param2));
757 if(var1==0.0) return 0.0; 757 if(var1==0.0) return 0.0;
758 double result=0, tempResult; 758 double result=0, tempResult;
759 int count1=0; 759 int count1=0;
760 bool ok; 760 bool ok;
761 for (row=row1; row<=row2; ++row) 761 for (row=row1; row<=row2; ++row)
762 for (col=col1; col<=col2; ++col) 762 for (col=col1; col<=col2; ++col)
763 { 763 {
764 tempResult=text(row, col).toDouble(&ok); 764 tempResult=text(row, col).toDouble(&ok);
765 if (ok) 765 if (ok)
766 { 766 {
767 result=result + (tempResult - avg1)*(tempResult - avg1)* 767 result=result + (tempResult - avg1)*(tempResult - avg1)*
768 (tempResult - avg1)*(tempResult - avg1)/(var1*var1*var1*var1); 768 (tempResult - avg1)*(tempResult - avg1)/(var1*var1*var1*var1);
769 count1++; 769 count1++;
770 }; 770 };
771 } 771 }
772 if(count1>0) result=result/double(count1)-3.0; else result=0.0; 772 if(count1>0) result=result/double(count1)-3.0; else result=0.0;
773 return result; 773 return result;
774}; 774};
775 775
776 776
777 777
778double Sheet::functionSumSQ(const QString &param1, const QString &param2) 778double Sheet::functionSumSQ(const QString &param1, const QString &param2)
779{ 779{
780 int row1, col1, row2, col2, row, col; 780 int row1, col1, row2, col2, row, col;
781 double result=0, tempResult; 781 double result=0, tempResult;
782 bool ok; 782 bool ok;
783 if (findRange(param1, param2, &row1, &col1, &row2, &col2)) 783 if (findRange(param1, param2, &row1, &col1, &row2, &col2))
784 { 784 {
785 for (row=row1; row<=row2; ++row) 785 for (row=row1; row<=row2; ++row)
786 for (col=col1; col<=col2; ++col) 786 for (col=col1; col<=col2; ++col)
787 { 787 {
788 tempResult=text(row, col).toDouble(&ok); 788 tempResult=text(row, col).toDouble(&ok);
789 if (ok) result+=tempResult*tempResult; 789 if (ok) result+=tempResult*tempResult;
790 } 790 }
791 return result; 791 return result;
792 }else 792 }else
793 { 793 {
794 double d1=0,d2=0; 794 double d1=0,d2=0;
795 d1=calculateVariable(param1).toDouble(&ok); 795 d1=calculateVariable(param1).toDouble(&ok);
796 d2=calculateVariable(param2).toDouble(&ok); 796 d2=calculateVariable(param2).toDouble(&ok);
797 return(d1*d1+d2*d2); 797 return(d1*d1+d2*d2);
798 }; 798 };
799 return 0; 799 return 0;
800} 800}
801 801
802 802
803 803
804double Sheet::functionMin(const QString &param1, const QString &param2) 804double Sheet::functionMin(const QString &param1, const QString &param2)
805{ 805{
806 int row1, col1, row2, col2, row, col; 806 int row1, col1, row2, col2, row, col;
807 double min=0, tempMin; 807 double min=0, tempMin;
808 bool ok, init=FALSE; 808 bool ok, init=FALSE;
809 if (findRange(param1, param2, &row1, &col1, &row2, &col2)) 809 if (findRange(param1, param2, &row1, &col1, &row2, &col2))
810 { 810 {
811 for (row=row1; row<=row2; ++row) 811 for (row=row1; row<=row2; ++row)
812 for (col=col1; col<=col2; ++col) 812 for (col=col1; col<=col2; ++col)
813 { 813 {
814 tempMin=text(row, col).toDouble(&ok); 814 tempMin=text(row, col).toDouble(&ok);
815 if (ok && (!init || tempMin<min)) 815 if (ok && (!init || tempMin<min))
816 { 816 {
817 min=tempMin; 817 min=tempMin;
818 init=TRUE; 818 init=TRUE;
819 } 819 }
820 } 820 }
821 return min; 821 return min;
822 }else 822 }else
823 { 823 {
824 double d1=0,d2=0; 824 double d1=0,d2=0;
825 d1=calculateVariable(param1).toDouble(&ok); 825 d1=calculateVariable(param1).toDouble(&ok);
826 d2=calculateVariable(param2).toDouble(&ok); 826 d2=calculateVariable(param2).toDouble(&ok);
827 if(d1<d2) return(d1); else return(d2); 827 if(d1<d2) return(d1); else return(d2);
828 }; 828 };
829 return 0; 829 return 0;
830} 830}
831 831
832double Sheet::functionMax(const QString &param1, const QString &param2) 832double Sheet::functionMax(const QString &param1, const QString &param2)
833{ 833{
834 int row1, col1, row2, col2, row, col; 834 int row1, col1, row2, col2, row, col;
835 double max=0, tempMax; 835 double max=0, tempMax;
836 bool ok, init=FALSE; 836 bool ok, init=FALSE;
837 if (findRange(param1, param2, &row1, &col1, &row2, &col2)) 837 if (findRange(param1, param2, &row1, &col1, &row2, &col2))
838 { 838 {
839 for (row=row1; row<=row2; ++row) 839 for (row=row1; row<=row2; ++row)
840 for (col=col1; col<=col2; ++col) 840 for (col=col1; col<=col2; ++col)
841 { 841 {
842 tempMax=text(row, col).toDouble(&ok); 842 tempMax=text(row, col).toDouble(&ok);
843 if (ok && (!init || tempMax>max)) 843 if (ok && (!init || tempMax>max))
844 { 844 {
845 max=tempMax; 845 max=tempMax;
846 init=TRUE; 846 init=TRUE;
847 } 847 }
848 }; 848 };
849 return max; 849 return max;
850 }else 850 }else
851 { 851 {
852 double d1=0,d2=0; 852 double d1=0,d2=0;
853 d1=calculateVariable(param1).toDouble(&ok); 853 d1=calculateVariable(param1).toDouble(&ok);
854 d2=calculateVariable(param2).toDouble(&ok); 854 d2=calculateVariable(param2).toDouble(&ok);
855 if(d1>d2) return(d1); else return(d2); 855 if(d1>d2) return(d1); else return(d2);
856 }; 856 };
857 return 0; 857 return 0;
858} 858}
859 859
860double Sheet::functionAvg(const QString &param1, const QString &param2) 860double Sheet::functionAvg(const QString &param1, const QString &param2)
861{ 861{
862 double resultSum=functionSum(param1, param2), resultCount=functionCount(param1, param2); 862 double resultSum=functionSum(param1, param2), resultCount=functionCount(param1, param2);
863 return (resultCount>0 ? resultSum/resultCount : 0); 863 return (resultCount>0 ? resultSum/resultCount : 0);
864} 864}
865 865
866double Sheet::functionCount(const QString &param1, const QString &param2) 866double Sheet::functionCount(const QString &param1, const QString &param2)
867{ 867{
868 int row1, col1, row2, col2, row, col; 868 int row1, col1, row2, col2, row, col;
869 int divider=0; 869 int divider=0;
870 bool ok; 870 bool ok;
871 if (findRange(param1, param2, &row1, &col1, &row2, &col2)) 871 if (findRange(param1, param2, &row1, &col1, &row2, &col2))
872 { 872 {
873 for (row=row1; row<=row2; ++row) 873 for (row=row1; row<=row2; ++row)
874 for (col=col1; col<=col2; ++col) 874 for (col=col1; col<=col2; ++col)
875 { 875 {
876 text(row, col).toDouble(&ok); 876 text(row, col).toDouble(&ok);
877 if (ok) ++divider; 877 if (ok) ++divider;
878 }; 878 };
879 return divider; 879 return divider;
880 }else 880 }else
881 { 881 {
882 double d1=0,d2=0;int ii=0; 882 double d1=0,d2=0;int ii=0;
883 d1=calculateVariable(param1).toDouble(&ok); 883 d1=calculateVariable(param1).toDouble(&ok);
884 if (ok) ii++; 884 if (ok) ii++;
885 d2=calculateVariable(param2).toDouble(&ok); 885 d2=calculateVariable(param2).toDouble(&ok);
886 if (ok) ii++; 886 if (ok) ii++;
887 return(ii); 887 return(ii);
888 }; 888 };
889 return 0; 889 return 0;
890} 890}
891 891
892double Sheet::functionCountIf(const QString &param1, const QString &param2, const QString &param3) 892double Sheet::functionCountIf(const QString &param1, const QString &param2, const QString &param3)
893{ 893{
894 int row1, col1, row2, col2, row, col; 894 int row1, col1, row2, col2, row, col;
895 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0; 895 if (!findRange(param1, param2, &row1, &col1, &row2, &col2)) return 0;
896 //same as count except check if each field is equal to param3 896 //same as count except check if each field is equal to param3
897 int divider=0; 897 int divider=0;
898 QString s2; 898 QString s2;
899 bool ok; 899 bool ok;
900 s2=calculateVariable(param3); 900 s2=calculateVariable(param3);
901 for (row=row1; row<=row2; ++row) 901 for (row=row1; row<=row2; ++row)
902 for (col=col1; col<=col2; ++col) 902 for (col=col1; col<=col2; ++col)
903 { 903 {
904 text(row, col).toDouble(&ok); 904 text(row, col).toDouble(&ok);
905 if (ok && (s2==text(row,col)) ) ++divider; 905 if (ok && (s2==text(row,col)) ) ++divider;
906 } 906 }
907 return divider; 907 return divider;
908} 908}
909 909
910 910
911QString Sheet::calculateFunction(const QString &func, const QString &parameters, int NumOfParams) 911QString Sheet::calculateFunction(const QString &func, const QString &parameters, int NumOfParams)
912{ 912{
913 bool ok; 913 bool ok;
914 double val1=0.0,val2=0.0,val3=0.0; 914 double val1=0.0,val2=0.0,val3=0.0;
915 long int vali=0; 915 long int vali=0;
916 int w1,w2; 916 int w1,w2;
917 int row,col; 917 int row,col;
918 QString s1,s2; 918 QString s1,s2;
919//basic functions 919//basic functions
920 QString function; 920 QString function;
921 function=func.upper(); 921 function=func.upper();
922 if (function=="+") 922 if (function=="+")
923 { 923 {
924 s1=calculateVariable(getParameter(parameters, 0)); 924 s1=calculateVariable(getParameter(parameters, 0));
925 s2=calculateVariable(getParameter(parameters, 1)); 925 s2=calculateVariable(getParameter(parameters, 1));
926 val1=s1.toDouble(&ok)+s2.toDouble(&ok); 926 val1=s1.toDouble(&ok)+s2.toDouble(&ok);
927 return QString::number(val1); 927 return QString::number(val1);
928 928
929 }; 929 };
930 if (function=="-") 930 if (function=="-")
931 { 931 {
932 s1=calculateVariable(getParameter(parameters, 0)); 932 s1=calculateVariable(getParameter(parameters, 0));
933 s2=calculateVariable(getParameter(parameters, 1)); 933 s2=calculateVariable(getParameter(parameters, 1));
934 val1=s1.toDouble(&ok)-s2.toDouble(&ok); 934 val1=s1.toDouble(&ok)-s2.toDouble(&ok);
935 return QString::number(val1); 935 return QString::number(val1);
936 }; 936 };
937 if (function=="*") 937 if (function=="*")
938 { 938 {
939 val1=calculateVariable( 939 val1=calculateVariable(
940 getParameter(parameters, 0)).toDouble(&ok) 940 getParameter(parameters, 0)).toDouble(&ok)
941 *calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 941 *calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
942 return QString::number(val1); 942 return QString::number(val1);
943 }; 943 };
944 if (function=="/") 944 if (function=="/")
945 { 945 {
946 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 946 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
947 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 947 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
948 if(val2==0.0) return QString("Err101"); 948 if(val2==0.0) return QString("Err101");
949 val1=val1/val2; 949 val1=val1/val2;
950 return QString::number(val1); 950 return QString::number(val1);
951 }; 951 };
952 if (function==">") 952 if (function==">")
953 { 953 {
954 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 954 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
955 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 955 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
956 if(val1>val2) return QString::number(1); else return QString::number(0); 956 if(val1>val2) return QString::number(1); else return QString::number(0);
957 }; 957 };
958 if (function=="<") 958 if (function=="<")
959 { 959 {
960 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 960 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
961 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 961 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
962 if(val1<val2) return QString::number(1); else return QString::number(0); 962 if(val1<val2) return QString::number(1); else return QString::number(0);
963 }; 963 };
964 if (function==">=") 964 if (function==">=")
965 { 965 {
966 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 966 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
967 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 967 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
968 if(val1>=val2) return QString::number(1); else return QString::number(0); 968 if(val1>=val2) return QString::number(1); else return QString::number(0);
969 }; 969 };
970 if (function=="<=") 970 if (function=="<=")
971 { 971 {
972 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 972 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
973 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 973 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
974 if(val1<=val2) return QString::number(1); else return QString::number(0); 974 if(val1<=val2) return QString::number(1); else return QString::number(0);
975 }; 975 };
976 if (function=="!=") 976 if (function=="!=")
977 { 977 {
978 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 978 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
979 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 979 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
980 if(val1!=val2) return QString::number(1); else return QString::number(0); 980 if(val1!=val2) return QString::number(1); else return QString::number(0);
981 }; 981 };
982 if (function=="=="||function=="=") 982 if (function=="=="||function=="=")
983 { 983 {
984 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok); 984 val1=calculateVariable(getParameter(parameters, 0)).toDouble(&ok);
985 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok); 985 val2=calculateVariable(getParameter(parameters, 1)).toDouble(&ok);
986 if(val1==val2) return QString::number(1); else return QString::number(0); 986 if(val1==val2) return QString::number(1); else return QString::number(0);
987 }; 987 };
988 988
989 //LOGICAL / INFO 989 //LOGICAL / INFO
990 if (function=="ISBLANK") 990 if (function=="ISBLANK")
991 { 991 {
992 if(findRowColumn(getParameter(parameters, 0), &row, &col, FALSE)) 992 if(findRowColumn(getParameter(parameters, 0), &row, &col, FALSE))
993 { 993 {
994 if(text(row,col).length()==0) val1=1; else val1=0; 994 if(text(row,col).length()==0) val1=1; else val1=0;
995 }else 995 }else
996 { 996 {
997 if(findRowColumn(calculateVariable(getParameter(parameters, 0)), &row,&col, FALSE)) 997 if(findRowColumn(calculateVariable(getParameter(parameters, 0)), &row,&col, FALSE))
998 { 998 {
999 if(text(row,col).length()==0) val1=1; else val1=0; 999 if(text(row,col).length()==0) val1=1; else val1=0;
1000 }else 1000 }else
1001 { 1001 {
1002 val1=0; 1002 val1=0;
1003 }; 1003 };
1004 }; 1004 };
1005 return QString::number(val1); 1005 return QString::number(val1);
1006 }; 1006 };
1007 1007
1008 1008
1009 if (function=="ISNUMBER") 1009 if (function=="ISNUMBER")
1010 { 1010 {
1011 if(findRowColumn(getParameter(parameters, 0, TRUE, function), &row, &col, FALSE)) 1011 if(findRowColumn(getParameter(parameters, 0, TRUE, function), &row, &col, FALSE))
1012 { 1012 {
1013 val1=text(row,col).toDouble(&ok); 1013 val1=text(row,col).toDouble(&ok);
1014 if(ok) val1=1; else val1=0; 1014 if(ok) val1=1; else val1=0;
1015 }else 1015 }else
1016 { 1016 {
1017 if(findRowColumn(calculateVariable(getParameter(parameters, 0, TRUE, function)), &row,&col, FALSE)) 1017 if(findRowColumn(calculateVariable(getParameter(parameters, 0, TRUE, function)), &row,&col, FALSE))
1018 { 1018 {
1019 val1=text(row,col).toDouble(&ok); 1019 val1=text(row,col).toDouble(&ok);
1020 if(ok) val1=1; else val1=0; 1020 if(ok) val1=1; else val1=0;
1021 }else 1021 }else
1022 { 1022 {
1023 val1=0; 1023 val1=0;
1024 }; 1024 };
1025 }; 1025 };
1026 return QString::number(val1); 1026 return QString::number(val1);
1027 }; 1027 };
1028 if (function=="AND") 1028 if (function=="AND")
1029 { 1029 {
1030 vali=calculateVariable(getParameter(parameters, 0, TRUE, function)).toInt(&ok) 1030 vali=calculateVariable(getParameter(parameters, 0, TRUE, function)).toInt(&ok)
1031 & calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1031 & calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1032 return QString::number(vali); 1032 return QString::number(vali);
1033 }; 1033 };
1034 if (function=="OR") 1034 if (function=="OR")
1035 { 1035 {
1036 vali=calculateVariable(getParameter(parameters, 0, TRUE, function)).toInt(&ok) 1036 vali=calculateVariable(getParameter(parameters, 0, TRUE, function)).toInt(&ok)
1037 | calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1037 | calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1038 return QString::number(vali); 1038 return QString::number(vali);
1039 }; 1039 };
1040 if (function=="NOT") 1040 if (function=="NOT")
1041 { 1041 {
1042 vali=!calculateVariable(getParameter(parameters, 0, TRUE, function)).toInt(&ok); 1042 vali=!calculateVariable(getParameter(parameters, 0, TRUE, function)).toInt(&ok);
1043 return QString::number(vali); 1043 return QString::number(vali);
1044 }; 1044 };
1045 1045
1046 // MATHEMATICAL FUNCTIONS 1046 // MATHEMATICAL FUNCTIONS
1047 if (function=="ABS") 1047 if (function=="ABS")
1048 { 1048 {
1049 val1=fabs(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1049 val1=fabs(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1050 return QString::number(val1); 1050 return QString::number(val1);
1051 }; 1051 };
1052 if (function=="ACOS") 1052 if (function=="ACOS")
1053 { 1053 {
1054 val1=acos(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1054 val1=acos(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1055 return QString::number(val1); 1055 return QString::number(val1);
1056 }; 1056 };
1057 if (function=="ACOSH") 1057 if (function=="ACOSH")
1058 { 1058 {
1059 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1059 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1060 if(val1<1.0) return QString::number(0); 1060 if(val1<1.0) return QString::number(0);
1061 val1=acosh(val1); 1061 val1=acosh(val1);
1062 return QString::number(val1); 1062 return QString::number(val1);
1063 }; 1063 };
1064 if (function=="ASIN") 1064 if (function=="ASIN")
1065 { 1065 {
1066 val1=asin(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1066 val1=asin(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1067 return QString::number(val1); 1067 return QString::number(val1);
1068 }; 1068 };
1069 if (function=="ASINH") 1069 if (function=="ASINH")
1070 { 1070 {
1071 val1=asinh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1071 val1=asinh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1072 return QString::number(val1); 1072 return QString::number(val1);
1073 }; 1073 };
1074 if (function=="ATAN") 1074 if (function=="ATAN")
1075 { 1075 {
1076 val1=atan(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1076 val1=atan(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1077 return QString::number(val1); 1077 return QString::number(val1);
1078 }; 1078 };
1079 if (function=="ATAN2") 1079 if (function=="ATAN2")
1080 { 1080 {
1081 val1=atan2(calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok), 1081 val1=atan2(calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok),
1082 calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1082 calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1083 return QString::number(val1); 1083 return QString::number(val1);
1084 }; 1084 };
1085 if (function=="ATANH") 1085 if (function=="ATANH")
1086 { 1086 {
1087 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1087 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1088 if(val1<=-1.0 || val1>=1.0) return QString("Err101"); 1088 if(val1<=-1.0 || val1>=1.0) return QString("Err101");
1089 val1=atanh(val1); 1089 val1=atanh(val1);
1090 return QString::number(val1); 1090 return QString::number(val1);
1091 }; 1091 };
1092 if (function=="CEILING") 1092 if (function=="CEILING")
1093 { 1093 {
1094 // rounds up param1 to specified accuracy param2 1094 // rounds up param1 to specified accuracy param2
1095 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1095 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1096 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1096 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1097 if(val2==0.0) return QString::number(val1); 1097 if(val2==0.0) return QString::number(val1);
1098 val1=ceil(val1/val2)*val2; 1098 val1=ceil(val1/val2)*val2;
1099 return QString::number(val1); 1099 return QString::number(val1);
1100 }; 1100 };
1101 if (function=="COS") 1101 if (function=="COS")
1102 { 1102 {
1103 val1=cos(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1103 val1=cos(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1104 return QString::number(val1); 1104 return QString::number(val1);
1105 }; 1105 };
1106 if (function=="COSH") 1106 if (function=="COSH")
1107 { 1107 {
1108 val1=cosh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1108 val1=cosh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1109 return QString::number(val1); 1109 return QString::number(val1);
1110 }; 1110 };
1111 if (function=="DEGREES") 1111 if (function=="DEGREES")
1112 { 1112 {
1113 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)*180.0/M_PI; 1113 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)*180.0/M_PI;
1114 return QString::number(val1); 1114 return QString::number(val1);
1115 }; 1115 };
1116 if (function=="EXP") 1116 if (function=="EXP")
1117 { 1117 {
1118 val1=exp(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1118 val1=exp(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1119 return QString::number(val1); 1119 return QString::number(val1);
1120 }; 1120 };
1121 if (function=="FACT") 1121 if (function=="FACT")
1122 { 1122 {
1123 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1123 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1124 val2=Factorial(val1); 1124 val2=Factorial(val1);
1125 return QString::number(val2); 1125 return QString::number(val2);
1126 }; 1126 };
1127 if (function=="FLOOR") 1127 if (function=="FLOOR")
1128 { 1128 {
1129 // rounds down param1 to specified accuracy param2 1129 // rounds down param1 to specified accuracy param2
1130 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1130 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1131 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1131 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1132 if(val2==0.0) return QString::number(val1); 1132 if(val2==0.0) return QString::number(val1);
1133 val1=floor(val1/val2)*val2; 1133 val1=floor(val1/val2)*val2;
1134 return QString::number(val1); 1134 return QString::number(val1);
1135 }; 1135 };
1136 if (function=="INT") 1136 if (function=="INT")
1137 { 1137 {
1138 // rounds down param1 1138 // rounds down param1
1139 val1=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1139 val1=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1140 return QString::number(val1); 1140 return QString::number(val1);
1141 }; 1141 };
1142 if (function=="EVEN") 1142 if (function=="EVEN")
1143 { 1143 {
1144 //converts param1 to even 1144 //converts param1 to even
1145 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1145 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1146 if(vali % 2 !=0) val1=vali+1; else val1=vali; 1146 if(vali % 2 !=0) val1=vali+1; else val1=vali;
1147 return QString::number(val1); 1147 return QString::number(val1);
1148 }; 1148 };
1149 if (function=="ODD") 1149 if (function=="ODD")
1150 { 1150 {
1151 //converts param1 to odd 1151 //converts param1 to odd
1152 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1152 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1153 if(vali % 2 !=0) val1=vali; else val1=vali+1; 1153 if(vali % 2 !=0) val1=vali; else val1=vali+1;
1154 return QString::number(val1); 1154 return QString::number(val1);
1155 }; 1155 };
1156 if (function=="ISEVEN") 1156 if (function=="ISEVEN")
1157 { 1157 {
1158 //Is Even param1? 1158 //Is Even param1?
1159 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1159 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1160 if(vali % 2 == 0) val1=1; else val1=0; 1160 if(vali % 2 == 0) val1=1; else val1=0;
1161 return QString::number(val1); 1161 return QString::number(val1);
1162 }; 1162 };
1163 if (function=="ISODD") 1163 if (function=="ISODD")
1164 { 1164 {
1165 //Is odd param1? 1165 //Is odd param1?
1166 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1166 vali=int(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1167 if(vali % 2 == 0) val1=0; else val1=1; 1167 if(vali % 2 == 0) val1=0; else val1=1;
1168 return QString::number(val1); 1168 return QString::number(val1);
1169 }; 1169 };
1170 if (function=="LN") 1170 if (function=="LN")
1171 { 1171 {
1172 // returns the natural logarithm of param1 1172 // returns the natural logarithm of param1
1173 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1173 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1174 if(val1<=0.0) return QString("Err101"); 1174 if(val1<=0.0) return QString("Err101");
1175 val1=log(val1); 1175 val1=log(val1);
1176 return QString::number(val1); 1176 return QString::number(val1);
1177 }; 1177 };
1178 if (function=="LOG10") 1178 if (function=="LOG10")
1179 { 1179 {
1180 // returns the base-10 logarithm of param1 1180 // returns the base-10 logarithm of param1
1181 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1181 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1182 if(val1<=0.0) return QString("Err101"); 1182 if(val1<=0.0) return QString("Err101");
1183 val1=log10(val1); 1183 val1=log10(val1);
1184 return QString::number(val1); 1184 return QString::number(val1);
1185 }; 1185 };
1186 if (function=="LOG") 1186 if (function=="LOG")
1187 { 1187 {
1188 // return the base-param2 logarithm of param1 1188 // return the base-param2 logarithm of param1
1189 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1189 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1190 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1190 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1191 if(val1<=0.0 || val2<=0.0 ) return QString("Err101"); 1191 if(val1<=0.0 || val2<=0.0 ) return QString("Err101");
1192 val1=log(val1)/log(val2); 1192 val1=log(val1)/log(val2);
1193 return QString::number(val1); 1193 return QString::number(val1);
1194 }; 1194 };
1195 if (function=="MOD") 1195 if (function=="MOD")
1196 { 1196 {
1197 // return the modulus of param1/param2 1197 // return the modulus of param1/param2
1198 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1198 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1199 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1199 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1200 if(val2==0.0) return QString("Err101"); 1200 if(val2==0.0) return QString("Err101");
1201 val1=(int(val1) % int(val2)); 1201 val1=(int(val1) % int(val2));
1202 return QString::number(val1); 1202 return QString::number(val1);
1203 }; 1203 };
1204 if (function=="POWER") 1204 if (function=="POWER")
1205 { 1205 {
1206 // return the param1^param2 1206 // return the param1^param2
1207 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1207 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1208 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1208 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1209 if(val1<0.0 && (floor(val2)!=val2)) return QString("Err101"); 1209 if(val1<0.0 && (floor(val2)!=val2)) return QString("Err101");
1210 val1=pow(val1,val2); 1210 val1=pow(val1,val2);
1211 return QString::number(val1); 1211 return QString::number(val1);
1212 }; 1212 };
1213 if (function=="PI") 1213 if (function=="PI")
1214 { 1214 {
1215 return QString::number(M_PI); 1215 return QString::number(M_PI);
1216 }; 1216 };
1217 if (function=="RADIANS") 1217 if (function=="RADIANS")
1218 { 1218 {
1219 // param1 deg->rad 1219 // param1 deg->rad
1220 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)*M_PI/180.0; 1220 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)*M_PI/180.0;
1221 return QString::number(val1); 1221 return QString::number(val1);
1222 }; 1222 };
1223 if (function=="RAND") 1223 if (function=="RAND")
1224 { 1224 {
1225 // retuns random number 0>x>1 1225 // retuns random number 0>x>1
1226 srand((unsigned int)time((time_t *)NULL)); 1226 srand((unsigned int)time((time_t *)NULL));
1227 val1=double(rand())/double(RAND_MAX); 1227 val1=double(rand())/double(RAND_MAX);
1228 return QString::number(val1); 1228 return QString::number(val1);
1229 }; 1229 };
1230 if (function=="RANDBETWEEN") 1230 if (function=="RANDBETWEEN")
1231 { 1231 {
1232 // returns random number between param1>x>param2 1232 // returns random number between param1>x>param2
1233 //TOFIX: this is not ok because I think results is always int related. 1233 //TOFIX: this is not ok because I think results is always int related.
1234 srand((unsigned int)time((time_t *)NULL)); 1234 srand((unsigned int)time((time_t *)NULL));
1235 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1235 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1236 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1236 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1237 val1=fmod(double(rand()),(val2-val1))+val1; 1237 val1=fmod(double(rand()),(val2-val1))+val1;
1238 return QString::number(val1); 1238 return QString::number(val1);
1239 }; 1239 };
1240 if (function=="ROUND") 1240 if (function=="ROUND")
1241 { 1241 {
1242 // rounds down param1 to specified digits param2 (positive decimal digits) 1242 // rounds down param1 to specified digits param2 (positive decimal digits)
1243 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1243 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1244 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1244 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1245 val2=pow(10.0,-val2); 1245 val2=pow(10.0,-val2);
1246 val1=floor(val1/val2)*val2; 1246 val1=floor(val1/val2)*val2;
1247 return QString::number(val1); 1247 return QString::number(val1);
1248 }; 1248 };
1249 if (function=="SIGN") 1249 if (function=="SIGN")
1250 { 1250 {
1251 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1251 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1252 if(val1>=0.0) return QString::number(1.0); else return QString::number(-1.0); 1252 if(val1>=0.0) return QString::number(1.0); else return QString::number(-1.0);
1253 }; 1253 };
1254 if (function=="CHGSGN")//changes sign (for unary operator) 1254 if (function=="CHGSGN")//changes sign (for unary operator)
1255 { 1255 {
1256 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1256 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1257 return QString::number((-1.0)*val1); 1257 return QString::number((-1.0)*val1);
1258 }; 1258 };
1259 if (function=="SIN") 1259 if (function=="SIN")
1260 { 1260 {
1261 val1=sin(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1261 val1=sin(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1262 return QString::number(val1); 1262 return QString::number(val1);
1263 }; 1263 };
1264 if (function=="SINH") 1264 if (function=="SINH")
1265 { 1265 {
1266 val1=sinh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1266 val1=sinh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1267 return QString::number(val1); 1267 return QString::number(val1);
1268 }; 1268 };
1269 if (function=="TAN") 1269 if (function=="TAN")
1270 { 1270 {
1271 val1=tan(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1271 val1=tan(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1272 return QString::number(val1); 1272 return QString::number(val1);
1273 }; 1273 };
1274 if (function=="TANH") 1274 if (function=="TANH")
1275 { 1275 {
1276 val1=tanh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1276 val1=tanh(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1277 return QString::number(val1); 1277 return QString::number(val1);
1278 }; 1278 };
1279 if (function=="SQRT") 1279 if (function=="SQRT")
1280 { 1280 {
1281 val1=sqrt(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok)); 1281 val1=sqrt(calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok));
1282 return QString::number(val1); 1282 return QString::number(val1);
1283 }; 1283 };
1284 1284
1285 1285
1286// STRING FUNCTIONS 1286// STRING FUNCTIONS
1287 if (function=="CONCATENATE") 1287 if (function=="CONCATENATE")
1288 { 1288 {
1289 // concatenates strings together 1289 // concatenates strings together
1290 w1=0; 1290 w1=0;
1291 s1=""; 1291 s1="";
1292 while(getParameter(parameters, w1, FALSE, function)!="") //parse all params; 1292 while(getParameter(parameters, w1, FALSE, function)!="") //parse all params;
1293 { 1293 {
1294 s1=s1+calculateVariable(getParameter(parameters, w1)); 1294 s1=s1+calculateVariable(getParameter(parameters, w1));
1295 w1++; 1295 w1++;
1296 }; 1296 };
1297 return QString(s1); 1297 return QString(s1);
1298 }; 1298 };
1299 if (function=="EXACT") 1299 if (function=="EXACT")
1300 { 1300 {
1301 // compare two string if they are exactly the same 1301 // compare two string if they are exactly the same
1302 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1302 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1303 s2=calculateVariable(getParameter(parameters, 1, TRUE, function)); 1303 s2=calculateVariable(getParameter(parameters, 1, TRUE, function));
1304 if(s1==s2) return QString::number(1); else return QString::number(0); 1304 if(s1==s2) return QString::number(1); else return QString::number(0);
1305 }; 1305 };
1306 if (function=="FIND") 1306 if (function=="FIND")
1307 { 1307 {
1308 // finds param1 in param2 from pos param3 and after 1308 // finds param1 in param2 from pos param3 and after
1309 // returns -1 if not found 1309 // returns -1 if not found
1310 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1310 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1311 s2=calculateVariable(getParameter(parameters, 1, TRUE, function)); 1311 s2=calculateVariable(getParameter(parameters, 1, TRUE, function));
1312 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok); 1312 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok);
1313 val1=s2.find(s1,vali); 1313 val1=s2.find(s1,vali);
1314 return QString::number(val1); 1314 return QString::number(val1);
1315 }; 1315 };
1316 if (function=="LEFT") 1316 if (function=="LEFT")
1317 { 1317 {
1318 // returns the param2 left chars from param1 string 1318 // returns the param2 left chars from param1 string
1319 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1319 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1320 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1320 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1321 s2=s1.left(vali); 1321 s2=s1.left(vali);
1322 return QString(s2); 1322 return QString(s2);
1323 }; 1323 };
1324 if (function=="LEN") 1324 if (function=="LEN")
1325 { 1325 {
1326 // return the length of a string(param1) 1326 // return the length of a string(param1)
1327 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1327 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1328 return QString::number(s1.length()); 1328 return QString::number(s1.length());
1329 }; 1329 };
1330 if (function=="MID") 1330 if (function=="MID")
1331 { 1331 {
1332 // returns the mid word of string param1 with start param2 and len param3 1332 // returns the mid word of string param1 with start param2 and len param3
1333 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1333 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1334 w1=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1334 w1=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1335 w2=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok); 1335 w2=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok);
1336 s2=s1.mid(w1,w2); 1336 s2=s1.mid(w1,w2);
1337 return QString(s2); 1337 return QString(s2);
1338 }; 1338 };
1339 if (function=="REPLACE") 1339 if (function=="REPLACE")
1340 { 1340 {
1341 //replace in param1 text in pos param2 and length param3 to newtext param4 1341 //replace in param1 text in pos param2 and length param3 to newtext param4
1342 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1342 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1343 w1=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1343 w1=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1344 w2=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok); 1344 w2=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok);
1345 s2=calculateVariable(getParameter(parameters, 3, TRUE, function)); 1345 s2=calculateVariable(getParameter(parameters, 3, TRUE, function));
1346 if(w1<0 || w2<0) return QString(s1); 1346 if(w1<0 || w2<0) return QString(s1);
1347 s1=s1.left(w2-1)+s2+s1.right(s1.length()-w1-w2); 1347 s1=s1.left(w2-1)+s2+s1.right(s1.length()-w1-w2);
1348 return QString(s1); 1348 return QString(s1);
1349 }; 1349 };
1350 if (function=="REPT") 1350 if (function=="REPT")
1351 { 1351 {
1352 //repeats param1 string param2 times 1352 //repeats param1 string param2 times
1353 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1353 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1354 w1=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1354 w1=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1355 for(w2=1;w2<=w1;w2++) 1355 for(w2=1;w2<=w1;w2++)
1356 { 1356 {
1357 s2=s2.append(s1); 1357 s2=s2.append(s1);
1358 }; 1358 };
1359 return QString(s2); 1359 return QString(s2);
1360 }; 1360 };
1361 if (function=="RIGHT") 1361 if (function=="RIGHT")
1362 { 1362 {
1363 // returns the param2 right chars from param1 string 1363 // returns the param2 right chars from param1 string
1364 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1364 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1365 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1365 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1366 s2=s1.right(vali); 1366 s2=s1.right(vali);
1367 return QString(s2); 1367 return QString(s2);
1368 }; 1368 };
1369 if (function=="UPPER") 1369 if (function=="UPPER")
1370 { 1370 {
1371 // returns the upper param1 string 1371 // returns the upper param1 string
1372 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1372 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1373 s1=s1.upper(); 1373 s1=s1.upper();
1374 return QString(s1); 1374 return QString(s1);
1375 }; 1375 };
1376 if (function=="LOWER") 1376 if (function=="LOWER")
1377 { 1377 {
1378 // returns the lower param1 string 1378 // returns the lower param1 string
1379 s1=calculateVariable(getParameter(parameters, 0, TRUE, function)); 1379 s1=calculateVariable(getParameter(parameters, 0, TRUE, function));
1380 s1=s1.lower(); 1380 s1=s1.lower();
1381 return QString(s1); 1381 return QString(s1);
1382 }; 1382 };
1383 if (function=="IF") 1383 if (function=="IF")
1384 { 1384 {
1385 //usage: IF(param1,param2,param3) 1385 //usage: IF(param1,param2,param3)
1386 //returns param4 if true(param1)/ param5 if false(param1) 1386 //returns param4 if true(param1)/ param5 if false(param1)
1387 val1=getParameter(parameters, 0, TRUE, function).toDouble(&ok); 1387 val1=getParameter(parameters, 0, TRUE, function).toDouble(&ok);
1388 if(val1==1.0) 1388 if(val1==1.0)
1389 { 1389 {
1390 s1=calculateVariable(getParameter(parameters, 1, TRUE, function)); 1390 s1=calculateVariable(getParameter(parameters, 1, TRUE, function));
1391 return QString(s1); 1391 return QString(s1);
1392 }else 1392 }else
1393 { 1393 {
1394 s1=calculateVariable(getParameter(parameters, 2, TRUE, function)); 1394 s1=calculateVariable(getParameter(parameters, 2, TRUE, function));
1395 return QString(s1); 1395 return QString(s1);
1396 }; 1396 };
1397 }; 1397 };
1398 if (function=="SUM") 1398 if (function=="SUM")
1399 { 1399 {
1400 //NumOfParams 1400 //NumOfParams
1401 val2=0.0; 1401 val2=0.0;
1402 for(w1=1;w1<=(NumOfParams/2);w1++) 1402 for(w1=1;w1<=(NumOfParams/2);w1++)
1403 { 1403 {
1404 val1=functionSum(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function)); 1404 val1=functionSum(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function));
1405 val2=val2+val1; 1405 val2=val2+val1;
1406 }; 1406 };
1407 if(NumOfParams%2==1) 1407 if(NumOfParams%2==1)
1408 { 1408 {
1409 val2=val2+calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok); 1409 val2=val2+calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok);
1410 }; 1410 };
1411 return QString::number(val2); 1411 return QString::number(val2);
1412 }; 1412 };
1413 if (function=="INDEX") 1413 if (function=="INDEX")
1414 { 1414 {
1415 s1=functionIndex(getParameter(parameters,0,TRUE,function), getParameter(parameters, 1, TRUE, function), getParameter(parameters,2,TRUE,function).toInt(&ok)); 1415 s1=functionIndex(getParameter(parameters,0,TRUE,function), getParameter(parameters, 1, TRUE, function), getParameter(parameters,2,TRUE,function).toInt(&ok));
1416 return QString(s1); 1416 return QString(s1);
1417 }; 1417 };
1418 if (function=="SUMSQ") 1418 if (function=="SUMSQ")
1419 { 1419 {
1420 //NumOfParams 1420 //NumOfParams
1421 val2=0.0; 1421 val2=0.0;
1422 for(w1=1;w1<=(NumOfParams/2);w1++) 1422 for(w1=1;w1<=(NumOfParams/2);w1++)
1423 { 1423 {
1424 val1=functionSumSQ(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function)); 1424 val1=functionSumSQ(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function));
1425 val2=val2+val1; 1425 val2=val2+val1;
1426 }; 1426 };
1427 if(NumOfParams%2==1) 1427 if(NumOfParams%2==1)
1428 { 1428 {
1429 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok); 1429 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok);
1430 val2=val2+val1*val1; 1430 val2=val2+val1*val1;
1431 }; 1431 };
1432 return QString::number(val2); 1432 return QString::number(val2);
1433 }; 1433 };
1434 if (function=="COUNT") 1434 if (function=="COUNT")
1435 { 1435 {
1436 //NumOfParams 1436 //NumOfParams
1437 val2=0.0; 1437 val2=0.0;
1438 for(w1=1;w1<=(NumOfParams/2);w1++) 1438 for(w1=1;w1<=(NumOfParams/2);w1++)
1439 { 1439 {
1440 val1=functionCount(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function)); 1440 val1=functionCount(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function));
1441 val2=val2+val1; 1441 val2=val2+val1;
1442 }; 1442 };
1443 if(NumOfParams%2==1) 1443 if(NumOfParams%2==1)
1444 { 1444 {
1445 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok); 1445 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok);
1446 if(ok) val2=val2+1; 1446 if(ok) val2=val2+1;
1447 }; 1447 };
1448 return QString::number(val2); 1448 return QString::number(val2);
1449 }; 1449 };
1450 if (function=="COUNTIF") 1450 if (function=="COUNTIF")
1451 { 1451 {
1452 //NumOfParams 1452 //NumOfParams
1453 val1=functionCountIf(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function), getParameter(parameters, 2, TRUE, function)); 1453 val1=functionCountIf(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function), getParameter(parameters, 2, TRUE, function));
1454 return QString::number(val1); 1454 return QString::number(val1);
1455 }; 1455 };
1456 if (function=="MIN") 1456 if (function=="MIN")
1457 { 1457 {
1458 //NumOfParams 1458 //NumOfParams
1459 val2=0.0; 1459 val2=0.0;
1460 for(w1=1;w1<=(NumOfParams/2);w1++) 1460 for(w1=1;w1<=(NumOfParams/2);w1++)
1461 { 1461 {
1462 val1=functionMin(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function)); 1462 val1=functionMin(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function));
1463 val2=val1; 1463 val2=val1;
1464 }; 1464 };
1465 if(NumOfParams%2==1) 1465 if(NumOfParams%2==1)
1466 { 1466 {
1467 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok); 1467 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok);
1468 if(val1<val2) val2=val1; 1468 if(val1<val2) val2=val1;
1469 }; 1469 };
1470 return QString::number(val2); 1470 return QString::number(val2);
1471 }; 1471 };
1472 if (function=="MAX") 1472 if (function=="MAX")
1473 { 1473 {
1474 //NumOfParams 1474 //NumOfParams
1475 val2=0.0; 1475 val2=0.0;
1476 for(w1=1;w1<=(NumOfParams/2);w1++) 1476 for(w1=1;w1<=(NumOfParams/2);w1++)
1477 { 1477 {
1478 val1=functionMax(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function)); 1478 val1=functionMax(getParameter(parameters, (w1-1)*2, FALSE, function), getParameter(parameters, (w1-1)*2+1, TRUE, function));
1479 val2=val1; 1479 val2=val1;
1480 }; 1480 };
1481 if(NumOfParams%2==1) 1481 if(NumOfParams%2==1)
1482 { 1482 {
1483 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok); 1483 val1=calculateVariable(getParameter(parameters,NumOfParams-1,FALSE, function)).toDouble(&ok);
1484 if(val1>val2) val2=val1; 1484 if(val1>val2) val2=val1;
1485 }; 1485 };
1486 return QString::number(val2); 1486 return QString::number(val2);
1487 }; 1487 };
1488 if (function=="AVERAGE") 1488 if (function=="AVERAGE")
1489 { 1489 {
1490 val1=functionAvg(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1490 val1=functionAvg(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1491 return QString::number(val1); 1491 return QString::number(val1);
1492 }; 1492 };
1493 1493
1494 if(function=="BESSELI") 1494 if(function=="BESSELI")
1495 { 1495 {
1496 // BesselI (x,n) 1496 // BesselI (x,n)
1497 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1497 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1498 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1498 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1499 val2=BesselI(vali,val1); 1499 val2=BesselI(vali,val1);
1500 return QString::number(val2); 1500 return QString::number(val2);
1501 }; 1501 };
1502 if(function=="BESSELJ") 1502 if(function=="BESSELJ")
1503 { 1503 {
1504 // BesselJ (x,n) 1504 // BesselJ (x,n)
1505 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1505 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1506 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1506 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1507 val2=BesselJ(vali,val1); 1507 val2=BesselJ(vali,val1);
1508 return QString::number(val2); 1508 return QString::number(val2);
1509 }; 1509 };
1510 if(function=="BESSELK") 1510 if(function=="BESSELK")
1511 { 1511 {
1512 // BesselK (x,n) 1512 // BesselK (x,n)
1513 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1513 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1514 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1514 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1515 val2=BesselK(vali,val1); 1515 val2=BesselK(vali,val1);
1516 return QString::number(val2); 1516 return QString::number(val2);
1517 }; 1517 };
1518 if(function=="BESSELY") 1518 if(function=="BESSELY")
1519 { 1519 {
1520 // BesselY (x,n) 1520 // BesselY (x,n)
1521 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1521 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1522 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1522 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1523 val2=BesselY(vali,val1); 1523 val2=BesselY(vali,val1);
1524 return QString::number(val2); 1524 return QString::number(val2);
1525 }; 1525 };
1526 if(function=="GAMMALN") 1526 if(function=="GAMMALN")
1527 { 1527 {
1528 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1528 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1529 val2=GammaLn(val1); 1529 val2=GammaLn(val1);
1530 return QString::number(val2); 1530 return QString::number(val2);
1531 }; 1531 };
1532 if(function=="ERF") 1532 if(function=="ERF")
1533 { 1533 {
1534 // ERF (a,b) 1534 // ERF (a,b)
1535 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1535 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1536 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1536 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1537 return QString::number(ErrorFunction(val2)-ErrorFunction(val1)); 1537 return QString::number(ErrorFunction(val2)-ErrorFunction(val1));
1538 }; 1538 };
1539 if(function=="ERFC") 1539 if(function=="ERFC")
1540 { 1540 {
1541 // ERFC (a,b) 1541 // ERFC (a,b)
1542 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1542 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1543 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1543 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1544 return QString::number(ErrorFunctionComplementary(val2)-ErrorFunctionComplementary(val1)); 1544 return QString::number(ErrorFunctionComplementary(val2)-ErrorFunctionComplementary(val1));
1545 }; 1545 };
1546 if(function=="POISSON") 1546 if(function=="POISSON")
1547 { 1547 {
1548 // POISSON DISTR(x,n,distr/desnt) 1548 // POISSON DISTR(x,n,distr/desnt)
1549 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1549 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1550 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1550 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1551 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok); 1551 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok);
1552 if(vali==1) 1552 if(vali==1)
1553 { 1553 {
1554 return QString::number(GammaQ(floor(val1)+1, val2)); 1554 return QString::number(GammaQ(floor(val1)+1, val2));
1555 }else 1555 }else
1556 { 1556 {
1557 return QString::number(exp(-val2)*pow(val2,val1)/exp(GammaLn(val1+1.0))); 1557 return QString::number(exp(-val2)*pow(val2,val1)/exp(GammaLn(val1+1.0)));
1558 }; 1558 };
1559 }; 1559 };
1560 if(function=="CHIDIST") 1560 if(function=="CHIDIST")
1561 { 1561 {
1562 // POISSON CHIDIST(x,n,distr/density) 1562 // POISSON CHIDIST(x,n,distr/density)
1563 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1563 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1564 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1564 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1565 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok); 1565 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok);
1566 if(vali==1) 1566 if(vali==1)
1567 { 1567 {
1568 return QString::number(GammaP(val2/2.0,val1*val1/2.0)); 1568 return QString::number(GammaP(val2/2.0,val1*val1/2.0));
1569 } else 1569 } else
1570 { 1570 {
1571 return QString::number( 1571 return QString::number(
1572 pow(val1,val2-1.0)*exp(-val1*val1/2)/ ( pow(2,val2/2.0-1.0)*exp(GammaLn(val2/2.0))) 1572 pow(val1,val2-1.0)*exp(-val1*val1/2)/ ( pow(2,val2/2.0-1.0)*exp(GammaLn(val2/2.0)))
1573 ); 1573 );
1574 }; 1574 };
1575 }; 1575 };
1576 if(function=="CHI2DIST") 1576 if(function=="CHI2DIST")
1577 { 1577 {
1578 // POISSON CHISQUAREDIST(x,n,distr/density) 1578 // POISSON CHISQUAREDIST(x,n,distr/density)
1579 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1579 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1580 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1580 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1581 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok); 1581 vali=calculateVariable(getParameter(parameters, 2, TRUE, function)).toInt(&ok);
1582 if(vali==1) 1582 if(vali==1)
1583 { 1583 {
1584 return QString::number(GammaP(val2/2.0,val1/2.0)); 1584 return QString::number(GammaP(val2/2.0,val1/2.0));
1585 } else 1585 } else
1586 { 1586 {
1587 return QString::number( 1587 return QString::number(
1588 pow(val1,val2/2.0-1.0)/(exp(val1/2.0)*pow(sqrt(2.0),val2)*exp(GammaLn(val2/2.0))) 1588 pow(val1,val2/2.0-1.0)/(exp(val1/2.0)*pow(sqrt(2.0),val2)*exp(GammaLn(val2/2.0)))
1589 ); 1589 );
1590 }; 1590 };
1591 }; 1591 };
1592 if(function=="BETAI") 1592 if(function=="BETAI")
1593 { 1593 {
1594 // BETA INCOMPLETE BETA(x,a,b) 1594 // BETA INCOMPLETE BETA(x,a,b)
1595 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1595 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1596 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1596 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1597 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok); 1597 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok);
1598 return QString::number(BetaIncomplete(val2,val3,val1)); 1598 return QString::number(BetaIncomplete(val2,val3,val1));
1599 }; 1599 };
1600 if(function=="GAMMAP") 1600 if(function=="GAMMAP")
1601 { 1601 {
1602 // GammaP (x,a) 1602 // GammaP (x,a)
1603 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1603 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1604 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1604 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1605 return QString::number(GammaP(val2,val1)); 1605 return QString::number(GammaP(val2,val1));
1606 }; 1606 };
1607 if(function=="GAMMAQ") 1607 if(function=="GAMMAQ")
1608 { 1608 {
1609 // GammaQ (x,a) 1609 // GammaQ (x,a)
1610 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1610 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1611 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1611 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1612 return QString::number(GammaQ(val2,val1)); 1612 return QString::number(GammaQ(val2,val1));
1613 }; 1613 };
1614 if (function=="VAR") 1614 if (function=="VAR")
1615 { 1615 {
1616 val1=functionVariance(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1616 val1=functionVariance(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1617 return QString::number(val1); 1617 return QString::number(val1);
1618 }; 1618 };
1619 if (function=="VARP") 1619 if (function=="VARP")
1620 { 1620 {
1621 val1=functionVariancePopulation(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1621 val1=functionVariancePopulation(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1622 return QString::number(val1); 1622 return QString::number(val1);
1623 }; 1623 };
1624 if (function=="STDEV") 1624 if (function=="STDEV")
1625 { 1625 {
1626 val1=functionVariance(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1626 val1=functionVariance(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1627 if(val1<=0.0) return QString::number(0.0); 1627 if(val1<=0.0) return QString::number(0.0);
1628 return QString::number(sqrt(val1)); 1628 return QString::number(sqrt(val1));
1629 }; 1629 };
1630 if (function=="STDEVP") 1630 if (function=="STDEVP")
1631 { 1631 {
1632 val1=functionVariancePopulation(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1632 val1=functionVariancePopulation(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1633 if(val1<=0.0) return QString::number(0.0); 1633 if(val1<=0.0) return QString::number(0.0);
1634 return QString::number(sqrt(val1)); 1634 return QString::number(sqrt(val1));
1635 }; 1635 };
1636 if (function=="SKEW") 1636 if (function=="SKEW")
1637 { 1637 {
1638 val1=functionSkew(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1638 val1=functionSkew(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1639 return QString::number(val1); 1639 return QString::number(val1);
1640 }; 1640 };
1641 if (function=="KURT") 1641 if (function=="KURT")
1642 { 1642 {
1643 val1=functionKurt(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function)); 1643 val1=functionKurt(getParameter(parameters, 0, TRUE, function), getParameter(parameters, 1, TRUE, function));
1644 return QString::number(val1); 1644 return QString::number(val1);
1645 }; 1645 };
1646 if(function=="GAMMADIST") 1646 if(function=="GAMMADIST")
1647 { 1647 {
1648 // GAMMADIST (x,alpha,beta,distribution?density1:0) 1648 // GAMMADIST (x,alpha,beta,distribution?density1:0)
1649 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1649 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1650 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1650 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1651 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok); 1651 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok);
1652 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok); 1652 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok);
1653 if(vali==1)//distribution 1653 if(vali==1)//distribution
1654 { 1654 {
1655 if(val3==0.0) return QString::number(0.0); 1655 if(val3==0.0) return QString::number(0.0);
1656 else 1656 else
1657 return QString::number(GammaP(val2,val1/val3)); 1657 return QString::number(GammaP(val2,val1/val3));
1658 }else //density 1658 }else //density
1659 { 1659 {
1660 return QString::number( 1660 return QString::number(
1661 pow(val1,val2-1.0)*exp(-val1/val3) / (pow(val3,val2)*exp(GammaLn(val2))) 1661 pow(val1,val2-1.0)*exp(-val1/val3) / (pow(val3,val2)*exp(GammaLn(val2)))
1662 ); 1662 );
1663 }; 1663 };
1664 }; 1664 };
1665 if(function=="BETADIST") 1665 if(function=="BETADIST")
1666 { 1666 {
1667 // BETADIST (z,alpha,beta,distribution?density1:0) 1667 // BETADIST (z,alpha,beta,distribution?density1:0)
1668 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1668 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1669 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1669 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1670 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok); 1670 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok);
1671 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok); 1671 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok);
1672 if(vali==1)//distribution 1672 if(vali==1)//distribution
1673 { 1673 {
1674 return QString::number(BetaIncomplete(val2,val3,val1)); 1674 return QString::number(BetaIncomplete(val2,val3,val1));
1675 }else //density 1675 }else //density
1676 { 1676 {
1677 return QString::number( 1677 return QString::number(
1678 pow(val1,val2-1.0)*pow(1.0-val1,val3-1.0) / Beta(val2,val3) 1678 pow(val1,val2-1.0)*pow(1.0-val1,val3-1.0) / Beta(val2,val3)
1679 ); 1679 );
1680 }; 1680 };
1681 }; 1681 };
1682 if(function=="FDIST") 1682 if(function=="FDIST")
1683 { 1683 {
1684 // FDIST (z,d1,d2,distribution?density1:0) 1684 // FDIST (z,d1,d2,distribution?density1:0)
1685 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1685 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1686 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1686 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1687 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok); 1687 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok);
1688 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok); 1688 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok);
1689 if(vali==1)//distribution 1689 if(vali==1)//distribution
1690 { 1690 {
1691 return QString::number( 1691 return QString::number(
1692 -BetaIncomplete(val3/2,val2/2,val3/(val3+val2*val1)) 1692 -BetaIncomplete(val3/2,val2/2,val3/(val3+val2*val1))
1693 +BetaIncomplete(val3/2,val2/2,1) 1693 +BetaIncomplete(val3/2,val2/2,1)
1694 ); 1694 );
1695 }else //density 1695 }else //density
1696 { 1696 {
1697 return QString::number( 1697 return QString::number(
1698 pow(val2,val2/2)*pow(val3,val3/2)*pow(val1,val2/2-1)/ 1698 pow(val2,val2/2)*pow(val3,val3/2)*pow(val1,val2/2-1)/
1699 (pow(val3+val2*val1,(val2+val3)/2)*Beta(val2/2,val3/2)) 1699 (pow(val3+val2*val1,(val2+val3)/2)*Beta(val2/2,val3/2))
1700 ); 1700 );
1701 }; 1701 };
1702 }; 1702 };
1703 if(function=="NORMALDIST") 1703 if(function=="NORMALDIST")
1704 { 1704 {
1705 // NORMALDIST (x,m,s,distribution?density1:0) 1705 // NORMALDIST (x,m,s,distribution?density1:0)
1706 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1706 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1707 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok); 1707 val2=calculateVariable(getParameter(parameters, 1, TRUE, function)).toDouble(&ok);
1708 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok); 1708 val3=calculateVariable(getParameter(parameters, 2, TRUE, function)).toDouble(&ok);
1709 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok); 1709 vali=calculateVariable(getParameter(parameters, 3, TRUE, function)).toInt(&ok);
1710 if(vali==1)//distribution 1710 if(vali==1)//distribution
1711 { 1711 {
1712 return QString::number( 1712 return QString::number(
1713 (ErrorFunction((val1-val2)/(sqrt(2)*val3))+1)/2.0 1713 (ErrorFunction((val1-val2)/(sqrt(2)*val3))+1)/2.0
1714 ); 1714 );
1715 }else //density 1715 }else //density
1716 { 1716 {
1717 return QString::number( 1717 return QString::number(
1718 exp(-pow(((val1-val2)/val3),2)/2)/(val3*sqrt(2*M_PI)) 1718 exp(-pow(((val1-val2)/val3),2)/2)/(val3*sqrt(2*M_PI))
1719 ); 1719 );
1720 }; 1720 };
1721 }; 1721 };
1722 if(function=="PHI") 1722 if(function=="PHI")
1723 { 1723 {
1724 // NORMALDIST (x,distribution?density1:0) with mean=0 s=1.0 1724 // NORMALDIST (x,distribution?density1:0) with mean=0 s=1.0
1725 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok); 1725 val1=calculateVariable(getParameter(parameters, 0, TRUE, function)).toDouble(&ok);
1726 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok); 1726 vali=calculateVariable(getParameter(parameters, 1, TRUE, function)).toInt(&ok);
1727 if(vali==1)//distribution 1727 if(vali==1)//distribution
1728 { 1728 {
1729 return QString::number( 1729 return QString::number(
1730 (ErrorFunction(val1/(sqrt(2)))+1)/2.0 1730 (ErrorFunction(val1/(sqrt(2)))+1)/2.0
1731 ); 1731 );
1732 }else //density 1732 }else //density
1733 { 1733 {
1734 return QString::number( 1734 return QString::number(
1735 exp(-pow(val1,2)/2)/(sqrt(2*M_PI)) 1735 exp(-pow(val1,2)/2)/(sqrt(2*M_PI))
1736 ); 1736 );
1737 }; 1737 };
1738 }; 1738 };
1739 /* 1739 /*
1740 StudentTDistribution/: PDF[StudentTDistribution[n_], x_] := 1740 StudentTDistribution/: PDF[StudentTDistribution[n_], x_] :=
1741 1/(Sqrt[n] Beta[n/2, 1/2]) Sqrt[n/(n+x^2)]^(n+1) /; 1741 1/(Sqrt[n] Beta[n/2, 1/2]) Sqrt[n/(n+x^2)]^(n+1) /;
1742 ParameterQ[StudentTDistribution[n]] 1742 ParameterQ[StudentTDistribution[n]]
1743 1743
1744 StudentTDistribution/: CDF[StudentTDistribution[n_], x_] := 1744 StudentTDistribution/: CDF[StudentTDistribution[n_], x_] :=
1745 (1 + Sign[x] BetaRegularized[n/(n+x^2), 1, n/2, 1/2])/2 /; 1745 (1 + Sign[x] BetaRegularized[n/(n+x^2), 1, n/2, 1/2])/2 /;
1746 ParameterQ[StudentTDistribution[n]] 1746 ParameterQ[StudentTDistribution[n]]
1747 */ 1747 */
1748 1748
1749 1749
1750 1750
1751 return 0; 1751 return 0;
1752}; 1752};
1753 1753
1754 1754
1755 1755
1756 1756
1757QString Sheet::dataParserHelper(const QString &data) 1757QString Sheet::dataParserHelper(const QString &data)
1758{ 1758{
1759 if(data.left(1)=="""" && data.right(1)=="""") return QString(data); 1759 if(data.left(1)=="""" && data.right(1)=="""") return QString(data);
1760 Expression exp1(data); 1760 Expression exp1(data);
1761 exp1.Parse(); 1761 exp1.Parse();
1762 QStack<QString> stack1; 1762 QStack<QString> stack1;
1763 stack1.setAutoDelete(TRUE); 1763 stack1.setAutoDelete(TRUE);
1764 int i=0; 1764 int i=0;
1765 QString* s1; 1765 QString* s1;
1766 QString* s2=NULL; 1766 QString* s2=NULL;
1767 int* i1; 1767 int* i1;
1768 int args,tokentype; 1768 int args,tokentype;
1769 QString tempval; 1769 QString tempval;
1770 s1=exp1.CompiledBody.first();i1=exp1.CompiledBodyType.first(); 1770 s1=exp1.CompiledBody.first();i1=exp1.CompiledBodyType.first();
1771 while(i<=(int)exp1.CompiledBody.count()-1) 1771 while(i<=(int)exp1.CompiledBody.count()-1)
1772 { 1772 {
1773 args= ((*i1) & 0xFF00)>>8; tokentype=(*i1) & 0x00FF; 1773 args= ((*i1) & 0xFF00)>>8; tokentype=(*i1) & 0x00FF;
1774 if(tokentype==NUMBER_TOKEN) 1774 if(tokentype==NUMBER_TOKEN)
1775 { 1775 {
1776 stack1.push(new QString(*s1)); 1776 stack1.push(new QString(*s1));
1777 //printf("Parse:Number=%s\r\n",s1->latin1()); 1777 //printf("Parse:Number=%s\r\n",s1->latin1());
1778 } 1778 }
1779 else if(tokentype==VARIABLE_TOKEN) 1779 else if(tokentype==VARIABLE_TOKEN)
1780 { 1780 {
1781 stack1.push(new QString(QString(*s1).upper())); 1781 stack1.push(new QString(QString(*s1).upper()));
1782 //printf("Parse:Var=%s\r\n",s1->latin1()); 1782 //printf("Parse:Var=%s\r\n",s1->latin1());
1783 //here to put implementation of other types of variables except cell. 1783 //here to put implementation of other types of variables except cell.
1784 //for example names 1784 //for example names
1785 } 1785 }
1786 else if(tokentype==STRING_TOKEN) 1786 else if(tokentype==STRING_TOKEN)
1787 { 1787 {
1788 stack1.push(new QString(*s1)); 1788 stack1.push(new QString(*s1));
1789 //printf("Parse:String=%s\r\n",s1->ascii()); 1789 //printf("Parse:String=%s\r\n",s1->ascii());
1790 } 1790 }
1791 else if(tokentype==FUNCTION_TOKEN) 1791 else if(tokentype==FUNCTION_TOKEN)
1792 { 1792 {
1793 QString params=""; 1793 QString params="";
1794 for(int w1=1;w1<=args;w1++) 1794 for(int w1=1;w1<=args;w1++)
1795 { 1795 {
1796 if((int)stack1.count()!=0) s2=stack1.pop(); 1796 if((int)stack1.count()!=0) s2=stack1.pop();
1797 params=*s2+params;//args in reverse order 1797 params=*s2+params;//args in reverse order
1798 params=","+params; 1798 params=","+params;
1799 }; 1799 };
1800 params=params.mid(1); 1800 params=params.mid(1);
1801 if(params==NULL) params="0"; 1801 if(params==NULL) params="0";
1802 //printf("Parse:Func=%s, params=%s, stackcount=%d,args=%d\r\n" 1802 //printf("Parse:Func=%s, params=%s, stackcount=%d,args=%d\r\n"
1803 //,s1->latin1(),params.latin1(),stack1.count(),args); 1803 //,s1->latin1(),params.latin1(),stack1.count(),args);
1804 tempval=calculateFunction(*s1,params,args); 1804 tempval=calculateFunction(*s1,params,args);
1805 tempval=tempval; 1805 tempval=tempval;
1806 stack1.push(new QString(tempval)); 1806 stack1.push(new QString(tempval));
1807 }; 1807 };
1808 1808
1809 //loops to next token 1809 //loops to next token
1810 if(exp1.CompiledBody.next()!=NULL) s1=exp1.CompiledBody.current(); else break; 1810 if(exp1.CompiledBody.next()!=NULL) s1=exp1.CompiledBody.current(); else break;
1811 if(exp1.CompiledBodyType.next()!=NULL) i1=exp1.CompiledBodyType.current(); else break; 1811 if(exp1.CompiledBodyType.next()!=NULL) i1=exp1.CompiledBodyType.current(); else break;
1812 i++; 1812 i++;
1813 }; 1813 };
1814 if((int)stack1.count()!=0)s2=stack1.pop(); else s2=new QString("!ERROR"); 1814 if((int)stack1.count()!=0)s2=stack1.pop(); else s2=new QString("!ERROR");
1815 tempval=*s2; 1815 tempval=*s2;
1816 return(tempval); 1816 return(tempval);
1817}; 1817};
1818 1818
1819 1819
1820 1820
1821QString Sheet::dataParser(const QString &cell, const QString &data) 1821QString Sheet::dataParser(const QString &cell, const QString &data)
1822{ 1822{
1823 QString strippedData(data); 1823 QString strippedData(data);
1824 strippedData.replace(QRegExp("\\s"), ""); 1824 strippedData.replace(QRegExp("\\s"), "");
1825 if (strippedData.isEmpty() || strippedData[0]!='=') return data; 1825 if (strippedData.isEmpty() || strippedData[0]!='=') return data;
1826 if (listDataParser.find(cell)!=listDataParser.end()) return "0"; 1826 if (listDataParser.find(cell)!=listDataParser.end()) return "0";
1827 listDataParser.append(cell); 1827 listDataParser.append(cell);
1828 // printf("DATAPARSER: data=%s, cell=%s\r\n",data.ascii(),cell.ascii()); 1828 // printf("DATAPARSER: data=%s, cell=%s\r\n",data.ascii(),cell.ascii());
1829 strippedData=dataParserHelper(strippedData.remove(0, 1).replace(QRegExp(":"), ",")); 1829 strippedData=dataParserHelper(strippedData.remove(0, 1).replace(QRegExp(":"), ","));
1830 1830
1831 int i=0; 1831 int i=0;
1832 QString tempParameter(getParameter(strippedData, i)), result=""; 1832 QString tempParameter(getParameter(strippedData, i)), result="";
1833 do 1833 do
1834 { 1834 {
1835 result+=","+calculateVariable(tempParameter); 1835 result+=","+calculateVariable(tempParameter);
1836 tempParameter=getParameter(strippedData, ++i); 1836 tempParameter=getParameter(strippedData, ++i);
1837 } 1837 }
1838 while (!tempParameter.isNull()); 1838 while (!tempParameter.isNull());
1839 listDataParser.remove(cell); 1839 listDataParser.remove(cell);
1840 return result.mid(1); 1840 return result.mid(1);
1841} 1841}
1842 1842
1843 1843
1844void Sheet::setData(const QString &data) 1844void Sheet::setData(const QString &data)
1845{ 1845{
1846 setText(currentRow(), currentColumn(), data); 1846 setText(currentRow(), currentColumn(), data);
1847 slotCellChanged(currentRow(), currentColumn()); 1847 slotCellChanged(currentRow(), currentColumn());
1848 activateNextCell(); 1848 activateNextCell();
1849} 1849}
1850 1850
1851QString Sheet::getData() 1851QString Sheet::getData()
1852{ 1852{
1853 typeCellData *cellData=findCellData(currentRow(), currentColumn()); 1853 typeCellData *cellData=findCellData(currentRow(), currentColumn());
1854 if (cellData) 1854 if (cellData)
1855 return cellData->data; 1855 return cellData->data;
1856 return ""; 1856 return "";
1857} 1857}
1858 1858
1859void Sheet::lockClicks(bool lock) 1859void Sheet::lockClicks(bool lock)
1860{ 1860{
1861 clicksLocked=lock; 1861 clicksLocked=lock;
1862} 1862}
1863 1863
1864void Sheet::paintCell(QPainter *p, int row, int col, const QRect & cr, bool selected) 1864void Sheet::paintCell(QPainter *p, int row, int col, const QRect & cr, bool selected)
1865{ 1865{
1866 if (selected && row==currentRow() && col==currentColumn()) selected=FALSE; 1866 if (selected && row==currentRow() && col==currentColumn()) selected=FALSE;
1867 1867
1868 int sheetDataCurrent=sheetData.at(); 1868 int sheetDataCurrent=sheetData.at();
1869 typeCellData *cellData=findCellData(row, col); 1869 typeCellData *cellData=findCellData(row, col);
1870 if (sheetDataCurrent>=0) sheetData.at(sheetDataCurrent); 1870 if (sheetDataCurrent>=0) sheetData.at(sheetDataCurrent);
1871 if (!cellData) cellData=&defaultCellData; 1871 if (!cellData) cellData=&defaultCellData;
1872 if (selected) 1872 if (selected)
1873 p->fillRect(0, 0, cr.width(), cr.height(), colorGroup().highlight()); 1873 p->fillRect(0, 0, cr.width(), cr.height(), colorGroup().highlight());
1874 else 1874 else
1875 { 1875 {
1876 p->fillRect(0, 0, cr.width(), cr.height(), colorGroup().base()); 1876 p->fillRect(0, 0, cr.width(), cr.height(), colorGroup().base());
1877 p->fillRect(0, 0, cr.width(), cr.height(), cellData->background); 1877 p->fillRect(0, 0, cr.width(), cr.height(), cellData->background);
1878 } 1878 }
1879 1879
1880 QTableItem *cellItem=item(row, col); 1880 QTableItem *cellItem=item(row, col);
1881 if (cellItem) 1881 if (cellItem)
1882 { 1882 {
1883 p->setPen(selected ? colorGroup().highlightedText() : cellData->fontColor); 1883 p->setPen(selected ? colorGroup().highlightedText() : cellData->fontColor);
1884 p->setFont(cellData->font); 1884 p->setFont(cellData->font);
1885 QString str=cellItem->text(); 1885 QString str=cellItem->text();
1886 p->drawText(2, 2, cr.width()-4, cr.height()-4, cellData->alignment, cellItem->text()); 1886 p->drawText(2, 2, cr.width()-4, cr.height()-4, cellData->alignment, cellItem->text());
1887 } 1887 }
1888 1888
1889 int rx=cr.width()-1, ry=cr.height()-1; 1889 int rx=cr.width()-1, ry=cr.height()-1;
1890 QPen pen(p->pen()); 1890 QPen pen(p->pen());
1891 p->setPen(cellData->borders.right); 1891 p->setPen(cellData->borders.right);
1892 p->drawLine(rx, 0, rx, ry); 1892 p->drawLine(rx, 0, rx, ry);
1893 p->setPen(cellData->borders.bottom); 1893 p->setPen(cellData->borders.bottom);
1894 p->drawLine(0, ry, rx, ry); 1894 p->drawLine(0, ry, rx, ry);
1895 p->setPen(pen); 1895 p->setPen(pen);
1896} 1896}
1897 1897
1898void Sheet::viewportMousePressEvent(QMouseEvent *e) 1898void Sheet::viewportMousePressEvent(QMouseEvent *e)
1899{ 1899{
1900 QMouseEvent ce(e->type(), viewportToContents(e->pos()), e->globalPos(), e->button(), e->state()); 1900 QMouseEvent ce(e->type(), viewportToContents(e->pos()), e->globalPos(), e->button(), e->state());
1901 if (clicksLocked) 1901 if (clicksLocked)
1902 { 1902 {
1903 if (selectionNo<0) 1903 if (selectionNo<0)
1904 { 1904 {
1905 clearSelection(); 1905 clearSelection();
1906 QTableSelection newSelection; 1906 QTableSelection newSelection;
1907 newSelection.init(rowAt(ce.pos().y()), columnAt(ce.pos().x())); 1907 newSelection.init(rowAt(ce.pos().y()), columnAt(ce.pos().x()));
1908 newSelection.expandTo(newSelection.anchorRow(), newSelection.anchorCol()); 1908 newSelection.expandTo(newSelection.anchorRow(), newSelection.anchorCol());
1909 selectionNo=addSelection(newSelection); 1909 selectionNo=addSelection(newSelection);
1910 } 1910 }
1911 } 1911 }
1912 else 1912 else
1913 QTable::contentsMousePressEvent(&ce); 1913 QTable::contentsMousePressEvent(&ce);
1914} 1914}
1915 1915
1916void Sheet::viewportMouseMoveEvent(QMouseEvent *e) 1916void Sheet::viewportMouseMoveEvent(QMouseEvent *e)
1917{ 1917{
1918 QMouseEvent ce(e->type(), viewportToContents(e->pos()), e->globalPos(), e->button(), e->state()); 1918 QMouseEvent ce(e->type(), viewportToContents(e->pos()), e->globalPos(), e->button(), e->state());
1919 if (clicksLocked) 1919 if (clicksLocked)
1920 { 1920 {
1921 if (selectionNo>=0) 1921 if (selectionNo>=0)
1922 { 1922 {
1923 QTableSelection oldSelection(selection(selectionNo)); 1923 QTableSelection oldSelection(selection(selectionNo));
1924 oldSelection.expandTo(rowAt(ce.pos().y()), columnAt(ce.pos().x())); 1924 oldSelection.expandTo(rowAt(ce.pos().y()), columnAt(ce.pos().x()));
1925 if (!(oldSelection==selection(selectionNo))) 1925 if (!(oldSelection==selection(selectionNo)))
1926 { 1926 {
1927 removeSelection(selectionNo); 1927 removeSelection(selectionNo);
1928 selectionNo=addSelection(oldSelection); 1928 selectionNo=addSelection(oldSelection);
1929 } 1929 }
1930 } 1930 }
1931 } 1931 }
1932 else 1932 else
1933 QTable::contentsMouseMoveEvent(&ce); 1933 QTable::contentsMouseMoveEvent(&ce);
1934} 1934}
1935 1935
1936void Sheet::viewportMouseReleaseEvent(QMouseEvent *e) 1936void Sheet::viewportMouseReleaseEvent(QMouseEvent *e)
1937{ 1937{
1938 QMouseEvent ce(e->type(), viewportToContents(e->pos()), e->globalPos(), e->button(), e->state()); 1938 QMouseEvent ce(e->type(), viewportToContents(e->pos()), e->globalPos(), e->button(), e->state());
1939 if (clicksLocked && selectionNo>=0) 1939 if (clicksLocked && selectionNo>=0)
1940 { 1940 {
1941 QTableSelection oldSelection(selection(selectionNo)); 1941 QTableSelection oldSelection(selection(selectionNo));
1942 oldSelection.expandTo(rowAt(ce.pos().y()), columnAt(ce.pos().x())); 1942 oldSelection.expandTo(rowAt(ce.pos().y()), columnAt(ce.pos().x()));
1943 removeSelection(selectionNo); 1943 removeSelection(selectionNo);
1944 selectionNo=-1; 1944 selectionNo=-1;
1945 if (oldSelection.topRow()==oldSelection.bottomRow() && oldSelection.leftCol()==oldSelection.rightCol()) 1945 if (oldSelection.topRow()==oldSelection.bottomRow() && oldSelection.leftCol()==oldSelection.rightCol())
1946 emit cellClicked(findCellName(oldSelection.topRow(), oldSelection.leftCol())); 1946 emit cellClicked(findCellName(oldSelection.topRow(), oldSelection.leftCol()));
1947 else 1947 else
1948 emit cellClicked(findCellName(oldSelection.topRow(), oldSelection.leftCol())+','+findCellName(oldSelection.bottomRow(), oldSelection.rightCol())); 1948 emit cellClicked(findCellName(oldSelection.topRow(), oldSelection.leftCol())+','+findCellName(oldSelection.bottomRow(), oldSelection.rightCol()));
1949 } 1949 }
1950 else 1950 else
1951 QTable::contentsMouseReleaseEvent(&ce); 1951 QTable::contentsMouseReleaseEvent(&ce);
1952} 1952}
1953 1953
1954QString Sheet::findCellName(int row, int col) 1954QString Sheet::findCellName(int row, int col)
1955{ 1955{
1956 return (getHeaderString(col+1)+QString::number(row+1)); 1956 return (getHeaderString(col+1)+QString::number(row+1));
1957} 1957}
1958 1958
1959void Sheet::copySheetData(QList<typeCellData> *destSheetData) 1959void Sheet::copySheetData(QList<typeCellData> *destSheetData)
1960{ 1960{
1961 typeCellData *tempCellData, *newCellData; 1961 typeCellData *tempCellData, *newCellData;
1962 destSheetData->clear(); 1962 destSheetData->clear();
1963 1963
1964 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 1964 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
1965 { 1965 {
1966 newCellData=new typeCellData; 1966 newCellData=new typeCellData;
1967 *newCellData=*tempCellData; 1967 *newCellData=*tempCellData;
1968 destSheetData->append(newCellData); 1968 destSheetData->append(newCellData);
1969 } 1969 }
1970} 1970}
1971 1971
1972void Sheet::setSheetData(QList<typeCellData> *srcSheetData) 1972void Sheet::setSheetData(QList<typeCellData> *srcSheetData)
1973{ 1973{
1974 typeCellData *tempCellData, *newCellData; 1974 typeCellData *tempCellData, *newCellData;
1975 1975
1976 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 1976 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
1977 { 1977 {
1978 clearCell(tempCellData->row, tempCellData->col); 1978 clearCell(tempCellData->row, tempCellData->col);
1979 updateCell(tempCellData->row, tempCellData->col); 1979 updateCell(tempCellData->row, tempCellData->col);
1980 } 1980 }
1981 sheetData.clear(); 1981 sheetData.clear();
1982 1982
1983 for (tempCellData=srcSheetData->first(); tempCellData; tempCellData=srcSheetData->next()) 1983 for (tempCellData=srcSheetData->first(); tempCellData; tempCellData=srcSheetData->next())
1984 { 1984 {
1985 newCellData=new typeCellData; 1985 newCellData=new typeCellData;
1986 *newCellData=*tempCellData; 1986 *newCellData=*tempCellData;
1987 sheetData.append(newCellData); 1987 sheetData.append(newCellData);
1988 setText(newCellData->row, newCellData->col, dataParser(findCellName(newCellData->row, newCellData->col), newCellData->data)); 1988 setText(newCellData->row, newCellData->col, dataParser(findCellName(newCellData->row, newCellData->col), newCellData->data));
1989 } 1989 }
1990 emit sheetModified(); 1990 emit sheetModified();
1991} 1991}
1992 1992
1993void Sheet::setName(const QString &name) 1993void Sheet::setName(const QString &name)
1994{ 1994{
1995 sheetName=name; 1995 sheetName=name;
1996 emit sheetModified(); 1996 emit sheetModified();
1997} 1997}
1998 1998
1999QString Sheet::getName() 1999QString Sheet::getName()
2000{ 2000{
2001 return sheetName; 2001 return sheetName;
2002} 2002}
2003 2003
2004void Sheet::setBrush(int row, int col, const QBrush &brush) 2004void Sheet::setBrush(int row, int col, const QBrush &brush)
2005{ 2005{
2006 typeCellData *cellData=findCellData(row, col); 2006 typeCellData *cellData=findCellData(row, col);
2007 if (!cellData) cellData=createCellData(row, col); 2007 if (!cellData) cellData=createCellData(row, col);
2008 if (cellData) 2008 if (cellData)
2009 { 2009 {
2010 cellData->background=brush; 2010 cellData->background=brush;
2011 emit sheetModified(); 2011 emit sheetModified();
2012 } 2012 }
2013} 2013}
2014 2014
2015QBrush Sheet::getBrush(int row, int col) 2015QBrush Sheet::getBrush(int row, int col)
2016{ 2016{
2017 typeCellData *cellData=findCellData(row, col); 2017 typeCellData *cellData=findCellData(row, col);
2018 if (!cellData) cellData=&defaultCellData; 2018 if (!cellData) cellData=&defaultCellData;
2019 return cellData->background; 2019 return cellData->background;
2020} 2020}
2021 2021
2022void Sheet::setTextAlign(int row, int col, Qt::AlignmentFlags flags) 2022void Sheet::setTextAlign(int row, int col, Qt::AlignmentFlags flags)
2023{ 2023{
2024 typeCellData *cellData=findCellData(row, col); 2024 typeCellData *cellData=findCellData(row, col);
2025 if (!cellData) cellData=createCellData(row, col); 2025 if (!cellData) cellData=createCellData(row, col);
2026 if (cellData) 2026 if (cellData)
2027 { 2027 {
2028 cellData->alignment=flags; 2028 cellData->alignment=flags;
2029 emit sheetModified(); 2029 emit sheetModified();
2030 } 2030 }
2031} 2031}
2032 2032
2033Qt::AlignmentFlags Sheet::getAlignment(int row, int col) 2033Qt::AlignmentFlags Sheet::getAlignment(int row, int col)
2034{ 2034{
2035 typeCellData *cellData=findCellData(row, col); 2035 typeCellData *cellData=findCellData(row, col);
2036 if (!cellData) cellData=&defaultCellData; 2036 if (!cellData) cellData=&defaultCellData;
2037 return cellData->alignment; 2037 return cellData->alignment;
2038} 2038}
2039 2039
2040void Sheet::setTextFont(int row, int col, const QFont &font, const QColor &color) 2040void Sheet::setTextFont(int row, int col, const QFont &font, const QColor &color)
2041{ 2041{
2042 typeCellData *cellData=findCellData(row, col); 2042 typeCellData *cellData=findCellData(row, col);
2043 if (!cellData) cellData=createCellData(row, col); 2043 if (!cellData) cellData=createCellData(row, col);
2044 if (cellData) 2044 if (cellData)
2045 { 2045 {
2046 cellData->font=font; 2046 cellData->font=font;
2047 cellData->fontColor=color; 2047 cellData->fontColor=color;
2048 emit sheetModified(); 2048 emit sheetModified();
2049 } 2049 }
2050} 2050}
2051 2051
2052QFont Sheet::getFont(int row, int col) 2052QFont Sheet::getFont(int row, int col)
2053{ 2053{
2054 typeCellData *cellData=findCellData(row, col); 2054 typeCellData *cellData=findCellData(row, col);
2055 if (!cellData) cellData=&defaultCellData; 2055 if (!cellData) cellData=&defaultCellData;
2056 return cellData->font; 2056 return cellData->font;
2057} 2057}
2058 2058
2059QColor Sheet::getFontColor(int row, int col) 2059QColor Sheet::getFontColor(int row, int col)
2060{ 2060{
2061 typeCellData *cellData=findCellData(row, col); 2061 typeCellData *cellData=findCellData(row, col);
2062 if (!cellData) cellData=&defaultCellData; 2062 if (!cellData) cellData=&defaultCellData;
2063 return cellData->fontColor; 2063 return cellData->fontColor;
2064} 2064}
2065 2065
2066void Sheet::setPen(int row, int col, int vertical, const QPen &pen) 2066void Sheet::setPen(int row, int col, int vertical, const QPen &pen)
2067{ 2067{
2068 typeCellData *cellData=findCellData(row, col); 2068 typeCellData *cellData=findCellData(row, col);
2069 if (!cellData) cellData=createCellData(row, col); 2069 if (!cellData) cellData=createCellData(row, col);
2070 if (cellData) 2070 if (cellData)
2071 { 2071 {
2072 if (vertical) 2072 if (vertical)
2073 cellData->borders.right=pen; 2073 cellData->borders.right=pen;
2074 else 2074 else
2075 cellData->borders.bottom=pen; 2075 cellData->borders.bottom=pen;
2076 emit sheetModified(); 2076 emit sheetModified();
2077 } 2077 }
2078} 2078}
2079 2079
2080QPen Sheet::getPen(int row, int col, int vertical) 2080QPen Sheet::getPen(int row, int col, int vertical)
2081{ 2081{
2082 typeCellData *cellData=findCellData(row, col); 2082 typeCellData *cellData=findCellData(row, col);
2083 if (!cellData) cellData=&defaultCellData; 2083 if (!cellData) cellData=&defaultCellData;
2084 return (vertical ? cellData->borders.right : cellData->borders.bottom); 2084 return (vertical ? cellData->borders.right : cellData->borders.bottom);
2085} 2085}
2086 2086
2087void Sheet::getSelection(int *row1, int *col1, int *row2, int *col2) 2087void Sheet::getSelection(int *row1, int *col1, int *row2, int *col2)
2088{ 2088{
2089 int selectionNo=currentSelection(); 2089 int selectionNo=currentSelection();
2090 if (selectionNo>=0) 2090 if (selectionNo>=0)
2091 { 2091 {
2092 QTableSelection selection(selection(selectionNo)); 2092 QTableSelection selection(selection(selectionNo));
2093 *row1=selection.topRow(); 2093 *row1=selection.topRow();
2094 *row2=selection.bottomRow(); 2094 *row2=selection.bottomRow();
2095 *col1=selection.leftCol(); 2095 *col1=selection.leftCol();
2096 *col2=selection.rightCol(); 2096 *col2=selection.rightCol();
2097 } 2097 }
2098 else 2098 else
2099 { 2099 {
2100 *row1=*row2=currentRow(); 2100 *row1=*row2=currentRow();
2101 *col1=*col2=currentColumn(); 2101 *col1=*col2=currentColumn();
2102 } 2102 }
2103} 2103}
2104 2104
2105void Sheet::editClear() 2105void Sheet::editClear()
2106{ 2106{
2107 int row1, row2, col1, col2; 2107 int row1, row2, col1, col2;
2108 getSelection(&row1, &col1, &row2, &col2); 2108 getSelection(&row1, &col1, &row2, &col2);
2109 2109
2110 int row, col; 2110 int row, col;
2111 for (row=row1; row<=row2; ++row) 2111 for (row=row1; row<=row2; ++row)
2112 for (col=col1; col<=col2; ++col) 2112 for (col=col1; col<=col2; ++col)
2113 { 2113 {
2114 setText(row, col, ""); 2114 setText(row, col, "");
2115 slotCellChanged(row, col); 2115 slotCellChanged(row, col);
2116 } 2116 }
2117} 2117}
2118 2118
2119void Sheet::editCopy() 2119void Sheet::editCopy()
2120{ 2120{
2121 clipboardData.clear(); 2121 clipboardData.clear();
2122 2122
2123 int row1, row2, col1, col2; 2123 int row1, row2, col1, col2;
2124 getSelection(&row1, &col1, &row2, &col2); 2124 getSelection(&row1, &col1, &row2, &col2);
2125 2125
2126 typeCellData *cellData, *newCellData; 2126 typeCellData *cellData, *newCellData;
2127 int row, col; 2127 int row, col;
2128 for (row=row1; row<=row2; ++row) 2128 for (row=row1; row<=row2; ++row)
2129 for (col=col1; col<=col2; ++col) 2129 for (col=col1; col<=col2; ++col)
2130 { 2130 {
2131 cellData=findCellData(row, col); 2131 cellData=findCellData(row, col);
2132 if (cellData) 2132 if (cellData)
2133 { 2133 {
2134 newCellData=new typeCellData; 2134 newCellData=new typeCellData;
2135 *newCellData=*cellData; 2135 *newCellData=*cellData;
2136 newCellData->row-=row1; 2136 newCellData->row-=row1;
2137 newCellData->col-=col1; 2137 newCellData->col-=col1;
2138 clipboardData.append(newCellData); 2138 clipboardData.append(newCellData);
2139 } 2139 }
2140 } 2140 }
2141} 2141}
2142 2142
2143void Sheet::editCut() 2143void Sheet::editCut()
2144{ 2144{
2145 editCopy(); 2145 editCopy();
2146 editClear(); 2146 editClear();
2147} 2147}
2148 2148
2149void Sheet::editPaste(bool onlyContents) 2149void Sheet::editPaste(bool onlyContents)
2150{ 2150{
2151 int row1=currentRow(), col1=currentColumn(); 2151 int row1=currentRow(), col1=currentColumn();
2152 typeCellData *cellData, *tempCellData; 2152 typeCellData *cellData, *tempCellData;
2153 2153
2154 for (tempCellData=clipboardData.first(); tempCellData; tempCellData=clipboardData.next()) 2154 for (tempCellData=clipboardData.first(); tempCellData; tempCellData=clipboardData.next())
2155 { 2155 {
2156 cellData=findCellData(tempCellData->row+row1, tempCellData->col+col1); 2156 cellData=findCellData(tempCellData->row+row1, tempCellData->col+col1);
2157 if (!cellData) cellData=createCellData(tempCellData->row+row1, tempCellData->col+col1); 2157 if (!cellData) cellData=createCellData(tempCellData->row+row1, tempCellData->col+col1);
2158 if (cellData) 2158 if (cellData)
2159 { 2159 {
2160 if (onlyContents) 2160 if (onlyContents)
2161 cellData->data=tempCellData->data; 2161 cellData->data=tempCellData->data;
2162 else 2162 else
2163 { 2163 {
2164 *cellData=*tempCellData; 2164 *cellData=*tempCellData;
2165 cellData->row+=row1; 2165 cellData->row+=row1;
2166 cellData->col+=col1; 2166 cellData->col+=col1;
2167 } 2167 }
2168 setText(cellData->row, cellData->col, dataParser(findCellName(cellData->row, cellData->col), cellData->data)); 2168 setText(cellData->row, cellData->col, dataParser(findCellName(cellData->row, cellData->col), cellData->data));
2169 emit sheetModified(); 2169 emit sheetModified();
2170 } 2170 }
2171 } 2171 }
2172} 2172}
2173 2173
2174void Sheet::insertRows(int no, bool allColumns) 2174void Sheet::insertRows(int no, bool allColumns)
2175{ 2175{
2176 setNumRows(numRows()+no); 2176 setNumRows(numRows()+no);
2177 2177
2178 typeCellData *tempCellData; 2178 typeCellData *tempCellData;
2179 int row=currentRow(), col=currentColumn(); 2179 int row=currentRow(), col=currentColumn();
2180 2180
2181 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 2181 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
2182 if (tempCellData->row>=row && (allColumns || tempCellData->col==col)) 2182 if (tempCellData->row>=row && (allColumns || tempCellData->col==col))
2183 { 2183 {
2184 clearCell(tempCellData->row, tempCellData->col); 2184 clearCell(tempCellData->row, tempCellData->col);
2185 tempCellData->row+=no; 2185 tempCellData->row+=no;
2186 } 2186 }
2187 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 2187 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
2188 if (tempCellData->row>=row && (allColumns || tempCellData->col==col)) 2188 if (tempCellData->row>=row && (allColumns || tempCellData->col==col))
2189 { 2189 {
2190 updateCell(tempCellData->row-no, tempCellData->col); 2190 updateCell(tempCellData->row-no, tempCellData->col);
2191 setText(tempCellData->row, tempCellData->col, dataParser(findCellName(tempCellData->row, tempCellData->col), tempCellData->data)); 2191 setText(tempCellData->row, tempCellData->col, dataParser(findCellName(tempCellData->row, tempCellData->col), tempCellData->data));
2192 } 2192 }
2193 emit sheetModified(); 2193 emit sheetModified();
2194} 2194}
2195 2195
2196void Sheet::insertColumns(int no, bool allRows) 2196void Sheet::insertColumns(int no, bool allRows)
2197{ 2197{
2198 int noCols=numCols(); 2198 int noCols=numCols();
2199 int newCols=noCols+no; 2199 int newCols=noCols+no;
2200 setNumCols(newCols); 2200 setNumCols(newCols);
2201 for (int i=noCols; i<newCols; ++i) 2201 for (int i=noCols; i<newCols; ++i)
2202 horizontalHeader()->setLabel(i, getHeaderString(i+1), DEFAULT_COL_WIDTH); 2202 horizontalHeader()->setLabel(i, getHeaderString(i+1), DEFAULT_COL_WIDTH);
2203 2203
2204 typeCellData *tempCellData; 2204 typeCellData *tempCellData;
2205 int col=currentColumn(), row=currentRow(); 2205 int col=currentColumn(), row=currentRow();
2206 2206
2207 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 2207 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
2208 if (tempCellData->col>=col && (allRows || tempCellData->row==row)) 2208 if (tempCellData->col>=col && (allRows || tempCellData->row==row))
2209 { 2209 {
2210 clearCell(tempCellData->row, tempCellData->col); 2210 clearCell(tempCellData->row, tempCellData->col);
2211 tempCellData->col+=no; 2211 tempCellData->col+=no;
2212 } 2212 }
2213 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 2213 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
2214 if (tempCellData->col>=col && (allRows || tempCellData->row==row)) 2214 if (tempCellData->col>=col && (allRows || tempCellData->row==row))
2215 { 2215 {
2216 updateCell(tempCellData->row, tempCellData->col-no); 2216 updateCell(tempCellData->row, tempCellData->col-no);
2217 setText(tempCellData->row, tempCellData->col, dataParser(findCellName(tempCellData->row, tempCellData->col), tempCellData->data)); 2217 setText(tempCellData->row, tempCellData->col, dataParser(findCellName(tempCellData->row, tempCellData->col), tempCellData->data));
2218 } 2218 }
2219 emit sheetModified(); 2219 emit sheetModified();
2220} 2220}
2221 2221
2222void Sheet::dataFindReplace(const QString &findStr, const QString &replaceStr, bool matchCase, bool allCells, bool entireCell, bool replace, bool replaceAll) 2222void Sheet::dataFindReplace(const QString &findStr, const QString &replaceStr, bool matchCase, bool allCells, bool entireCell, bool replace, bool replaceAll)
2223{ 2223{
2224 typeCellData *tempCellData; 2224 typeCellData *tempCellData;
2225 int row1, col1, row2, col2; 2225 int row1, col1, row2, col2;
2226 getSelection(&row1, &col1, &row2, &col2); 2226 getSelection(&row1, &col1, &row2, &col2);
2227 bool found=FALSE; 2227 bool found=FALSE;
2228 2228
2229 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next()) 2229 for (tempCellData=sheetData.first(); tempCellData; tempCellData=sheetData.next())
2230 if (allCells || (tempCellData->row>=row1 && tempCellData->row<=row2 && tempCellData->col>=col1 && tempCellData->col<=col2)) 2230 if (allCells || (tempCellData->row>=row1 && tempCellData->row<=row2 && tempCellData->col>=col1 && tempCellData->col<=col2))
2231 { 2231 {
2232 QTableItem *cellItem=item(tempCellData->row, tempCellData->col); 2232 QTableItem *cellItem=item(tempCellData->row, tempCellData->col);
2233 if (cellItem && (entireCell ? (matchCase ? cellItem->text()==findStr : cellItem->text().upper()==findStr.upper()) : cellItem->text().find(findStr, 0, matchCase)>=0)) 2233 if (cellItem && (entireCell ? (matchCase ? cellItem->text()==findStr : cellItem->text().upper()==findStr.upper()) : cellItem->text().find(findStr, 0, matchCase)>=0))
2234 { 2234 {
2235 if (!found) 2235 if (!found)
2236 { 2236 {
2237 found=TRUE; 2237 found=TRUE;
2238 clearSelection(); 2238 clearSelection();
2239 } 2239 }
2240 setCurrentCell(tempCellData->row, tempCellData->col); 2240 setCurrentCell(tempCellData->row, tempCellData->col);
2241 if (replace) 2241 if (replace)
2242 { 2242 {
2243 tempCellData->data=cellItem->text().replace(QRegExp(findStr, matchCase), replaceStr); 2243 tempCellData->data=cellItem->text().replace(QRegExp(findStr, matchCase), replaceStr);
2244 setText(tempCellData->row, tempCellData->col, dataParser(findCellName(tempCellData->row, tempCellData->col), tempCellData->data)); 2244 setText(tempCellData->row, tempCellData->col, dataParser(findCellName(tempCellData->row, tempCellData->col), tempCellData->data));
2245 } 2245 }
2246 if (!replace || !replaceAll) break; 2246 if (!replace || !replaceAll) break;
2247 } 2247 }
2248 } 2248 }
2249 2249
2250 if (found) 2250 if (found)
2251 { 2251 {
2252 if (replace) 2252 if (replace)
2253 slotCellChanged(currentRow(), currentColumn()); 2253 slotCellChanged(currentRow(), currentColumn());
2254 } 2254 }
2255 else 2255 else
2256 QMessageBox::warning(this, tr("Error"), tr("Search key not found!")); 2256 QMessageBox::warning(this, tr("Error"), tr("Search key not found!"));
2257} 2257}
2258 2258
2259// 2259//
2260// Static functions 2260// Static functions
2261// 2261//
2262 2262
2263QString Sheet::getHeaderString(int section) 2263QString Sheet::getHeaderString(int section)
2264{ 2264{
2265 if (section<1) return ""; 2265 if (section<1) return "";
2266 return getHeaderString((section-1)/26)+QChar('A'+(section-1)%26); 2266 return getHeaderString((section-1)/26)+QChar('A'+(section-1)%26);
2267} 2267}
2268 2268
2269int Sheet::getHeaderColumn(const QString &section) 2269int Sheet::getHeaderColumn(const QString &section)
2270{ 2270{
2271 if (section.isEmpty()) return 0; 2271 if (section.isEmpty()) return 0;
2272 return (section[section.length()-1]-'A'+1)+getHeaderColumn(section.left(section.length()-1))*26; 2272 return (section[section.length()-1]-'A'+1)+getHeaderColumn(section.left(section.length()-1))*26;
2273} 2273}
2274 2274
2275 2275
2276//Expression Parser Class Definition 2276//Expression Parser Class Definition
2277 2277
2278 2278
2279QChar Expression::chunk0(void) 2279QChar Expression::chunk0(void)
2280{ 2280{
2281 if(chunk.length()>0) return(chunk[0]); else return('\0'); 2281 if(chunk.length()>0) return(chunk[0]); else return('\0');
2282}; 2282};
2283 2283
2284Expression::Expression(QString expr1)// constructor 2284Expression::Expression(QString expr1)// constructor
2285{ 2285{
2286 Body=expr1; 2286 Body=expr1;
2287 SYMBOL="+-*/%^=()<>&|!,"; 2287 SYMBOL="+-*/%^=()<>&|!,";
2288 MATHSYMBOL="+-*/%^=<>&|!,"; 2288 MATHSYMBOL="+-*/%^=<>&|!,";
2289 // lnlim=1.0e-36; // Smallest number allowed 2289 // lnlim=1.0e-36; // Smallest number allowed
2290 // loglim=1.0e-10 ; // Smallest number allowed in call to log10() * 2290 // loglim=1.0e-10 ; // Smallest number allowed in call to log10() *
2291 ErrorFound=TRUE; 2291 ErrorFound=TRUE;
2292 n=0;chunk="";SymbGroup=NONE_TOKEN;InExpr=Body; 2292 n=0;chunk="";SymbGroup=NONE_TOKEN;InExpr=Body;
2293 ArgsOfFunc=0; 2293 ArgsOfFunc=0;
2294 CompiledBody.setAutoDelete(TRUE); 2294 CompiledBody.setAutoDelete(TRUE);
2295 CompiledBodyType.setAutoDelete(TRUE); 2295 CompiledBodyType.setAutoDelete(TRUE);
2296 //CompiledBody=QStringList(0); 2296 //CompiledBody=QStringList(0);
2297}; 2297};
2298 2298
2299bool Expression::isSymbol(QChar ch) 2299bool Expression::isSymbol(QChar ch)
2300{ 2300{
2301 int j = 0; 2301 int j = 0;
2302 while (j<=((int)SYMBOL.length()-1) && ch!=SYMBOL[j]) j++; 2302 while (j<=((int)SYMBOL.length()-1) && ch!=SYMBOL[j]) j++;
2303 if(j<((int)SYMBOL.length())) return true; else return false; 2303 if(j<((int)SYMBOL.length())) return true; else return false;
2304}; 2304};
2305 2305
2306bool Expression::isMathSymbol(QChar ch) 2306bool Expression::isMathSymbol(QChar ch)
2307{ 2307{
2308 int j = 0; 2308 int j = 0;
2309 while (j<=((int)MATHSYMBOL.length()-1) && ch!=MATHSYMBOL[j]) j++; 2309 while (j<=((int)MATHSYMBOL.length()-1) && ch!=MATHSYMBOL[j]) j++;
2310 if(j<((int)MATHSYMBOL.length())) return true; else return false; 2310 if(j<((int)MATHSYMBOL.length())) return true; else return false;
2311}; 2311};
2312 2312
2313void Expression::GetNext() 2313void Expression::GetNext()
2314{ 2314{
2315 chunk=""; 2315 chunk="";
2316 if(n>=(int)InExpr.length()) return; 2316 if(n>=(int)InExpr.length()) return;
2317 while (InExpr[n]==' ') n++; 2317 while (InExpr[n]==' ') n++;
2318 if(InExpr[n]=='\"') 2318 if(InExpr[n]=='\"')
2319 { 2319 {
2320 while ( (n<(int)InExpr.length()) && (InExpr[n+1]!='\"') ) 2320 while ( (n<(int)InExpr.length()) && (InExpr[n+1]!='\"') )
2321 { 2321 {
2322 printf("chunk=%s\r\n",chunk.latin1()); 2322 printf("chunk=%s\r\n",chunk.latin1());
2323 chunk+=InExpr[n]; 2323 chunk+=InExpr[n];
2324 n++; 2324 n++;
2325 }; 2325 };
2326 chunk+=InExpr[n]; 2326 chunk+=InExpr[n];
2327 printf("2\r\n"); 2327 printf("2\r\n");
2328 SymbGroup=STRING_TOKEN; 2328 SymbGroup=STRING_TOKEN;
2329 } 2329 }
2330 else if (isSymbol(InExpr[n])) 2330 else if (isSymbol(InExpr[n]))
2331 { 2331 {
2332 SymbGroup=SYMBOL_TOKEN; 2332 SymbGroup=SYMBOL_TOKEN;
2333 chunk+=InExpr[n]; 2333 chunk+=InExpr[n];
2334 n++; 2334 n++;
2335 if( (n<(int)InExpr.length()) && 2335 if( (n<(int)InExpr.length()) &&
2336 isMathSymbol(InExpr[n-1]) && 2336 isMathSymbol(InExpr[n-1]) &&
2337 isMathSymbol(InExpr[n]) ) 2337 isMathSymbol(InExpr[n]) )
2338 { 2338 {
2339 SymbGroup=SYMBOL_TOKEN; 2339 SymbGroup=SYMBOL_TOKEN;
2340 chunk+=InExpr[n]; 2340 chunk+=InExpr[n];
2341 n++; 2341 n++;
2342 }; 2342 };
2343 } 2343 }
2344 else if ((InExpr[n].isLetter())||(InExpr[n]=='#')) 2344 else if ((InExpr[n].isLetter())||(InExpr[n]=='#'))
2345 { 2345 {
2346 while ( (n<(int)InExpr.length()) && !isSymbol(InExpr[n]) ) 2346 while ( (n<(int)InExpr.length()) && !isSymbol(InExpr[n]) )
2347 { 2347 {
2348 if (!(InExpr[n]==' ')) chunk+=InExpr[n]; 2348 if (!(InExpr[n]==' ')) chunk+=InExpr[n];
2349 n++; 2349 n++;
2350 }; 2350 };
2351 if (InExpr[n]=='(') SymbGroup=FUNCTION_TOKEN; // function TOKEN 2351 if (InExpr[n]=='(') SymbGroup=FUNCTION_TOKEN; // function TOKEN
2352 else SymbGroup=VARIABLE_TOKEN; 2352 else SymbGroup=VARIABLE_TOKEN;
2353 } 2353 }
2354 else if((n<(int)InExpr.length()) && 2354 else if((n<(int)InExpr.length()) &&
2355 ((InExpr[n].isDigit()) || (InExpr[n]=='.'))) 2355 ((InExpr[n].isDigit()) || (InExpr[n]=='.')))
2356 { 2356 {
2357 while( n<(int)InExpr.length() ) 2357 while( n<(int)InExpr.length() )
2358 { 2358 {
2359 if((InExpr[n].isDigit()) || InExpr[n]=='.') 2359 if((InExpr[n].isDigit()) || InExpr[n]=='.')
2360 { 2360 {
2361 chunk+=InExpr[n]; 2361 chunk+=InExpr[n];
2362 SymbGroup=NUMBER_TOKEN; 2362 SymbGroup=NUMBER_TOKEN;
2363 n++; 2363 n++;
2364 } 2364 }
2365 else if(InExpr[n]=='e') 2365 else if(InExpr[n]=='e')
2366 { 2366 {
2367 if((n+1)<(int)InExpr.length()) 2367 if((n+1)<(int)InExpr.length())
2368 { 2368 {
2369 if(InExpr[n+1]=='-' || InExpr[n+1]=='+' || InExpr[n+1].isDigit()) 2369 if(InExpr[n+1]=='-' || InExpr[n+1]=='+' || InExpr[n+1].isDigit())
2370 { 2370 {
2371 chunk+=InExpr[n]; 2371 chunk+=InExpr[n];
2372 chunk+=InExpr[n+1]; 2372 chunk+=InExpr[n+1];
2373 SymbGroup=NUMBER_TOKEN; 2373 SymbGroup=NUMBER_TOKEN;
2374 n+=2; 2374 n+=2;
2375 } 2375 }
2376 } 2376 }
2377 else 2377 else
2378 { 2378 {
2379 break; 2379 break;
2380 } 2380 }
2381 } 2381 }
2382 else 2382 else
2383 { 2383 {
2384 break; 2384 break;
2385 } 2385 }
2386 }//while 2386 }//while
2387 }//else if 2387 }//else if
2388};//end function 2388};//end function
2389 2389
2390 2390
2391void Expression::First() 2391void Expression::First()
2392{ 2392{
2393 GetNext(); 2393 GetNext();
2394 if (!(chunk=="") && !ErrorFound) Third(); 2394 if (!(chunk=="") && !ErrorFound) Third();
2395 else ErrorFound = true; 2395 else ErrorFound = true;
2396}; 2396};
2397 2397
2398void Expression::Third() 2398void Expression::Third()
2399{ 2399{
2400 QChar sign, secS='\0'; 2400 QChar sign, secS='\0';
2401 Fourth(); 2401 Fourth();
2402 sign = chunk0(); 2402 sign = chunk0();
2403 if((int)chunk.length()>1) secS=chunk[1]; 2403 if((int)chunk.length()>1) secS=chunk[1];
2404 while( sign == '+' || sign == '-'|| 2404 while( sign == '+' || sign == '-'||
2405 sign == '<' || sign == '>'|| sign == '%'|| 2405 sign == '<' || sign == '>'|| sign == '%'||
2406 sign == '&' || sign == '|' || sign == '!' || sign == '=' 2406 sign == '&' || sign == '|' || sign == '!' || sign == '='
2407 ) 2407 )
2408 { 2408 {
2409 GetNext(); 2409 GetNext();
2410 Fourth(); 2410 Fourth();
2411 QString name; 2411 QString name;
2412 if( sign == '+' ) name= "+" ; 2412 if( sign == '+' ) name= "+" ;
2413 else if(sign=='-') name= "-" ; 2413 else if(sign=='-') name= "-" ;
2414 else if(sign=='>' && secS=='\0') name= ">" ; 2414 else if(sign=='>' && secS=='\0') name= ">" ;
2415 else if(sign=='<' && secS=='\0') name= "<" ; 2415 else if(sign=='<' && secS=='\0') name= "<" ;
2416 else if(sign=='=' && secS=='=') name= "==" ; 2416 else if(sign=='=' && secS=='=') name= "==" ;
2417 else if(sign=='!' && secS=='=') name= "!=" ; 2417 else if(sign=='!' && secS=='=') name= "!=" ;
2418 else if(sign=='>' && secS=='=') name= ">=" ; 2418 else if(sign=='>' && secS=='=') name= ">=" ;
2419 else if(sign=='<' && secS=='=') name= "<=" ; 2419 else if(sign=='<' && secS=='=') name= "<=" ;
2420 else if(sign=='&' && secS=='&') name= "AND" ; 2420 else if(sign=='&' && secS=='&') name= "AND" ;
2421 else if(sign=='|' && secS=='|') name= "OR" ; 2421 else if(sign=='|' && secS=='|') name= "OR" ;
2422 else if(sign=='%') name= "MOD" ; 2422 else if(sign=='%') name= "MOD" ;
2423 CompiledBody.append(new QString(name)); // not sure if pushed in the back. 2423 CompiledBody.append(new QString(name)); // not sure if pushed in the back.
2424 CompiledBodyType.append(new int(FUNCTION_TOKEN | 2<<8)); //2 argument functions 2424 CompiledBodyType.append(new int(FUNCTION_TOKEN | 2<<8)); //2 argument functions
2425 sign = chunk0(); 2425 sign = chunk0();
2426 } 2426 }
2427}; 2427};
2428 2428
2429void Expression::Fourth() 2429void Expression::Fourth()
2430{ 2430{
2431 QChar sign; 2431 QChar sign;
2432 Fifth(); 2432 Fifth();
2433 sign = chunk0(); 2433 sign = chunk0();
2434 while( sign == '*' || sign == '/' ) 2434 while( sign == '*' || sign == '/' )
2435 { 2435 {
2436 GetNext(); 2436 GetNext();
2437 Fifth(); 2437 Fifth();
2438 QString name; 2438 QString name;
2439 if( sign == '*' ) name= "*" ; 2439 if( sign == '*' ) name= "*" ;
2440 else name= "/" ; 2440 else name= "/" ;
2441 CompiledBody.append(new QString(name)); 2441 CompiledBody.append(new QString(name));
2442 CompiledBodyType.append(new int(FUNCTION_TOKEN | 2<<8)); //2 arguments functions 2442 CompiledBodyType.append(new int(FUNCTION_TOKEN | 2<<8)); //2 arguments functions
2443 sign = chunk0(); 2443 sign = chunk0();
2444 } 2444 }
2445}; 2445};
2446 2446
2447void Expression::Fifth() 2447void Expression::Fifth()
2448{ 2448{
2449 Sixth(); 2449 Sixth();
2450 //if(chunk.Length==0) return; 2450 //if(chunk.Length==0) return;
2451 if( chunk0() == '^' ) 2451 if( chunk0() == '^' )
2452 { 2452 {
2453 GetNext(); 2453 GetNext();
2454 Fifth(); 2454 Fifth();
2455 CompiledBody.append(new QString("POWER")); 2455 CompiledBody.append(new QString("POWER"));
2456 CompiledBodyType.append(new int(FUNCTION_TOKEN | 2<<8)); // 2 argument functions 2456 CompiledBodyType.append(new int(FUNCTION_TOKEN | 2<<8)); // 2 argument functions
2457 } 2457 }
2458}; 2458};
2459 2459
2460void Expression::Sixth() 2460void Expression::Sixth()
2461{ 2461{
2462 char sign; 2462 char sign;
2463 sign = ' '; 2463 sign = ' ';
2464 if(SymbGroup== SYMBOL_TOKEN && 2464 if(SymbGroup== SYMBOL_TOKEN &&
2465 chunk0() == '+' || chunk0() == '-' | chunk0() == '!') 2465 chunk0() == '+' || chunk0() == '-' | chunk0() == '!')
2466 { 2466 {
2467 sign = chunk0(); 2467 sign = chunk0();
2468 GetNext(); 2468 GetNext();
2469 } 2469 }
2470 Seventh(); 2470 Seventh();
2471 if( sign == '-' ) 2471 if( sign == '-' )
2472 { 2472 {
2473 CompiledBody.append(new QString("CHGSGN")); // unary minus 2473 CompiledBody.append(new QString("CHGSGN")); // unary minus
2474 CompiledBodyType.append(new int(FUNCTION_TOKEN | 1<<8)); //1 argument 2474 CompiledBodyType.append(new int(FUNCTION_TOKEN | 1<<8)); //1 argument
2475 } 2475 }
2476 if( sign == '!' ) 2476 if( sign == '!' )
2477 { 2477 {
2478 CompiledBody.append(new QString("NOT")); // unary minus 2478 CompiledBody.append(new QString("NOT")); // unary minus
2479 CompiledBodyType.append(new int(FUNCTION_TOKEN | 1<<8)); //1 argument 2479 CompiledBodyType.append(new int(FUNCTION_TOKEN | 1<<8)); //1 argument
2480 } 2480 }
2481}; 2481};
2482 2482
2483 2483
2484void Expression::Seventh() 2484void Expression::Seventh()
2485{ 2485{
2486 if( chunk0() == '(' && SymbGroup==SYMBOL_TOKEN) 2486 if( chunk0() == '(' && SymbGroup==SYMBOL_TOKEN)
2487 { 2487 {
2488 GetNext(); 2488 GetNext();
2489 Third(); //parse the insides until we get a ')' 2489 Third(); //parse the insides until we get a ')'
2490 if (chunk0() != ')') ErrorFound = true; 2490 if (chunk0() != ')') ErrorFound = true;
2491 GetNext(); 2491 GetNext();
2492 } 2492 }
2493 else Eighth(); 2493 else Eighth();
2494}; 2494};
2495 2495
2496void Expression::Eighth() 2496void Expression::Eighth()
2497{ 2497{
2498 if ( SymbGroup== NUMBER_TOKEN ) 2498 if ( SymbGroup== NUMBER_TOKEN )
2499 { 2499 {
2500 CompiledBody.append(new QString(chunk)); 2500 CompiledBody.append(new QString(chunk));
2501 CompiledBodyType.append(new int(NUMBER_TOKEN)); 2501 CompiledBodyType.append(new int(NUMBER_TOKEN));
2502 GetNext(); 2502 GetNext();
2503 } 2503 }
2504 else if ( SymbGroup== VARIABLE_TOKEN ) 2504 else if ( SymbGroup== VARIABLE_TOKEN )
2505 { 2505 {
2506 CompiledBody.append(new QString(chunk)); 2506 CompiledBody.append(new QString(chunk));
2507 CompiledBodyType.append(new int(VARIABLE_TOKEN)); 2507 CompiledBodyType.append(new int(VARIABLE_TOKEN));
2508 GetNext(); 2508 GetNext();
2509 } 2509 }
2510 else if (SymbGroup== STRING_TOKEN ) 2510 else if (SymbGroup== STRING_TOKEN )
2511 { 2511 {
2512 CompiledBody.append(new QString(chunk+QString("\""))); 2512 CompiledBody.append(new QString(chunk+QString("\"")));
2513 CompiledBodyType.append(new int(STRING_TOKEN)); 2513 CompiledBodyType.append(new int(STRING_TOKEN));
2514 GetNext(); 2514 GetNext();
2515 } 2515 }
2516 else Ninth(); 2516 else Ninth();
2517}; 2517};
2518 2518
2519void Expression::Ninth() 2519void Expression::Ninth()
2520{ 2520{
2521 if ( SymbGroup== FUNCTION_TOKEN ) 2521 if ( SymbGroup== FUNCTION_TOKEN )
2522 { 2522 {
2523 QString TempFunk = chunk ; 2523 QString TempFunk = chunk ;
2524 GetNext(); 2524 GetNext();
2525 if(chunk0() == '(' ) 2525 if(chunk0() == '(' )
2526 { 2526 {
2527 FuncDepth++; 2527 FuncDepth++;
2528 ArgsOfFunc.resize(FuncDepth+1); 2528 ArgsOfFunc.resize(FuncDepth+1);
2529 ArgsOfFunc[FuncDepth]=1; 2529 ArgsOfFunc[FuncDepth]=1;
2530 //ArgsOfFunc=1; 2530 //ArgsOfFunc=1;
2531 GetNext(); 2531 GetNext();
2532 Third(); 2532 Third();
2533 while(chunk0()==',') //function arguments separator 2533 while(chunk0()==',') //function arguments separator
2534 { 2534 {
2535 //ArgsOfFunc++; 2535 //ArgsOfFunc++;
2536 ArgsOfFunc[FuncDepth]++; 2536 ArgsOfFunc[FuncDepth]++;
2537 GetNext(); 2537 GetNext();
2538 Third(); 2538 Third();
2539 }; 2539 };
2540 if (chunk0() != ')') ErrorFound = true; 2540 if (chunk0() != ')') ErrorFound = true;
2541 2541
2542 CompiledBody.append(new QString(TempFunk)); 2542 CompiledBody.append(new QString(TempFunk));
2543 if (TempFunk=="PI") ArgsOfFunc[FuncDepth]=0; 2543 if (TempFunk=="PI") ArgsOfFunc[FuncDepth]=0;
2544 // couldn't find a better way to parse function PI() with 0 args. :) 2544 // couldn't find a better way to parse function PI() with 0 args. :)
2545 CompiledBodyType.append(new int(FUNCTION_TOKEN | (ArgsOfFunc[FuncDepth]<<8) )); 2545 CompiledBodyType.append(new int(FUNCTION_TOKEN | (ArgsOfFunc[FuncDepth]<<8) ));
2546 //the mask &FF00 gives the arguments of the functions passed. 2546 //the mask &FF00 gives the arguments of the functions passed.
2547 FuncDepth--; 2547 FuncDepth--;
2548 ArgsOfFunc.resize(FuncDepth+1); 2548 ArgsOfFunc.resize(FuncDepth+1);
2549 GetNext(); 2549 GetNext();
2550 } 2550 }
2551 } 2551 }
2552 else 2552 else
2553 ErrorFound = true; 2553 ErrorFound = true;
2554}; 2554};
2555 2555
2556bool Expression::Parse() 2556bool Expression::Parse()
2557{ 2557{
2558 CompiledBody.clear(); 2558 CompiledBody.clear();
2559 ErrorFound = false; 2559 ErrorFound = false;
2560 n = 0;ArgsOfFunc.resize(0);FuncDepth=0; 2560 n = 0;ArgsOfFunc.resize(0);FuncDepth=0;
2561 InExpr=Body; 2561 InExpr=Body;
2562 First(); 2562 First();
2563 return(!ErrorFound); 2563 return(!ErrorFound);
2564}; 2564};
2565 2565
2566 2566
diff --git a/noncore/apps/opie-write/mainwindow.cpp b/noncore/apps/opie-write/mainwindow.cpp
index 6bb524f..90e1a70 100644
--- a/noncore/apps/opie-write/mainwindow.cpp
+++ b/noncore/apps/opie-write/mainwindow.cpp
@@ -1,574 +1,574 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** Licensees holding valid Qtopia Developer license may use this 6** Licensees holding valid Qtopia Developer license may use this
7** file in accordance with the Qtopia Developer License Agreement 7** file in accordance with the Qtopia Developer License Agreement
8** provided with the Software. 8** provided with the Software.
9** 9**
10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING 10** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
11** THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR 11** THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
12** PURPOSE. 12** PURPOSE.
13** 13**
14** email sales@trolltech.com for information about Qtopia License 14** email sales@trolltech.com for information about Qtopia License
15** Agreements. 15** Agreements.
16** 16**
17** Contact info@trolltech.com if any conditions of this licensing are 17** Contact info@trolltech.com if any conditions of this licensing are
18** not clear to you. 18** not clear to you.
19** 19**
20**********************************************************************/ 20**********************************************************************/
21 21
22#include "mainwindow.h" 22#include "mainwindow.h"
23#include <qpe/fileselector.h> 23#include <qpe/fileselector.h>
24#include <qpe/applnk.h> 24#include <qpe/applnk.h>
25#include <qpe/resource.h> 25#include <qpe/resource.h>
26#include <qpe/fontdatabase.h> 26#include <qpe/fontdatabase.h>
27 27
28//#include "qspellchecker.h" 28//#include "qspellchecker.h"
29#include "qtextedit.h" 29#include "qtextedit.h"
30#include <qaction.h> 30#include <qaction.h>
31#include <qtoolbar.h> 31#include <qtoolbar.h>
32#include <qtoolbutton.h> 32#include <qtoolbutton.h>
33#include <qtabwidget.h> 33#include <qtabwidget.h>
34#include <qapplication.h> 34#include <qapplication.h>
35#include <qfontdatabase.h> 35#include <qfontdatabase.h>
36#include <qcombobox.h> 36#include <qcombobox.h>
37#include <qlineedit.h> 37#include <qlineedit.h>
38#include <qfileinfo.h> 38#include <qfileinfo.h>
39#include <qfile.h> 39#include <qfile.h>
40#include <qfiledialog.h> 40#include <qfiledialog.h>
41#include <qprinter.h> 41#include <qprinter.h>
42#include <qpaintdevicemetrics.h> 42#include <qpaintdevicemetrics.h>
43#include <qmenubar.h> 43#include <qmenubar.h>
44#include <qpopupmenu.h> 44#include <qpopupmenu.h>
45#include <qcolordialog.h> 45#include <qcolordialog.h>
46#include <qpainter.h> 46#include <qpainter.h>
47#include <qstyle.h> 47#include <qstyle.h>
48 48
49class ButtonMenu : public QToolButton 49class ButtonMenu : public QToolButton
50{ 50{
51 Q_OBJECT 51 Q_OBJECT
52public: 52public:
53 ButtonMenu( QWidget *parent, const char *name=0 ) 53 ButtonMenu( QWidget *parent, const char *name=0 )
54 : QToolButton( parent, name ), current(0) 54 : QToolButton( parent, name ), current(0)
55 { 55 {
56 setPopup( new QPopupMenu( this ) ); 56 setPopup( new QPopupMenu( this ) );
57 setPopupDelay( 1 ); 57 setPopupDelay( 1 );
58 connect( popup(), SIGNAL(activated(int)), this, SLOT(selected(int)) ); 58 connect( popup(), SIGNAL(activated(int)), this, SLOT(selected(int)) );
59 } 59 }
60 60
61 int insertItem(const QIconSet &icon, const QString &text, int id ) { 61 int insertItem(const QIconSet &icon, const QString &text, int id ) {
62 if ( !popup()->count() ) { 62 if ( !popup()->count() ) {
63 setIconSet( icon ); 63 setIconSet( icon );
64 current = id; 64 current = id;
65 } 65 }
66 return popup()->insertItem( icon, text, id ); 66 return popup()->insertItem( icon, text, id );
67 } 67 }
68 68
69 void setCurrentItem( int id ) { 69 void setCurrentItem( int id ) {
70 if ( id != current ) { 70 if ( id != current ) {
71 current = id; 71 current = id;
72 setIconSet( *popup()->iconSet( id ) ); 72 setIconSet( *popup()->iconSet( id ) );
73 } 73 }
74 } 74 }
75 75
76 virtual QSize sizeHint() const { 76 virtual QSize sizeHint() const {
77 return QToolButton::sizeHint() + QSize( 4, 0 ); 77 return QToolButton::sizeHint() + QSize( 4, 0 );
78 } 78 }
79 79
80signals: 80signals:
81 void activated( int id ); 81 void activated( int id );
82 82
83protected slots: 83protected slots:
84 void selected( int id ) { 84 void selected( int id ) {
85 current = id; 85 current = id;
86 setIconSet( *popup()->iconSet( id ) ); 86 setIconSet( *popup()->iconSet( id ) );
87 emit activated( id ); 87 emit activated( id );
88 } 88 }
89 89
90protected: 90protected:
91 virtual void drawButtonLabel( QPainter *p ) { 91 virtual void drawButtonLabel( QPainter *p ) {
92 p->translate( -4, 0 ); 92 p->translate( -4, 0 );
93 QToolButton::drawButtonLabel( p ); 93 QToolButton::drawButtonLabel( p );
94 p->translate( 4, 0 ); 94 p->translate( 4, 0 );
95 } 95 }
96 96
97private: 97private:
98 int current; 98 int current;
99}; 99};
100 100
101//=========================================================================== 101//===========================================================================
102 102
103MainWindow::MainWindow( QWidget *parent, const char *name, WFlags fl ) 103MainWindow::MainWindow( QWidget *parent, const char *name, WFlags fl )
104 : QMainWindow( parent, name, fl ), 104 : QMainWindow( parent, name, fl ),
105 doc( 0 ) 105 doc( 0 )
106{ 106{
107 setRightJustification(TRUE); 107 setRightJustification(TRUE);
108 108
109 editorStack = new QWidgetStack( this ); 109 editorStack = new QWidgetStack( this );
110 110
111 fileSelector = new FileSelector( "text/html", 111 fileSelector = new FileSelector( "text/html",
112 editorStack, "fileselector" ); 112 editorStack, "fileselector" );
113 113
114 114
115 fileSelector->setCloseVisible( FALSE ); 115 fileSelector->setCloseVisible( FALSE );
116 editorStack->addWidget( fileSelector, 0 ); 116 editorStack->addWidget( fileSelector, 0 );
117 117
118 editor = new Qt3::QTextEdit( editorStack ); 118 editor = new Qt3::QTextEdit( editorStack );
119 editor->setTextFormat( Qt::RichText ); 119 editor->setTextFormat( Qt::RichText );
120 editorStack->addWidget( editor, 1 ); 120 editorStack->addWidget( editor, 1 );
121 121
122 setupActions(); 122 setupActions();
123 123
124 QObject::connect( fileSelector, SIGNAL(closeMe()), 124 QObject::connect( fileSelector, SIGNAL(closeMe()),
125 this, SLOT(showEditTools()) ); 125 this, SLOT(showEditTools()) );
126 QObject::connect( fileSelector, SIGNAL(fileSelected(const DocLnk &)), 126 QObject::connect( fileSelector, SIGNAL(fileSelected(const DocLnk&)),
127 this, SLOT(openFile(const DocLnk &)) ); 127 this, SLOT(openFile(const DocLnk&)) );
128 QObject::connect( fileSelector, SIGNAL(newSelected(const DocLnk&)), 128 QObject::connect( fileSelector, SIGNAL(newSelected(const DocLnk&)),
129 this, SLOT(newFile(const DocLnk&)) ); 129 this, SLOT(newFile(const DocLnk&)) );
130 130
131 if ( fileSelector->fileCount() < 1 ) 131 if ( fileSelector->fileCount() < 1 )
132 fileNew(); 132 fileNew();
133 else { 133 else {
134 fileOpen(); 134 fileOpen();
135 } 135 }
136 doConnections( editor ); 136 doConnections( editor );
137 137
138 setCentralWidget( editorStack ); 138 setCentralWidget( editorStack );
139} 139}
140 140
141MainWindow::~MainWindow() 141MainWindow::~MainWindow()
142{ 142{
143 save(); 143 save();
144} 144}
145 145
146void MainWindow::setupActions() 146void MainWindow::setupActions()
147{ 147{
148 setToolBarsMovable(false); 148 setToolBarsMovable(false);
149 149
150 tbMenu = new QToolBar( this ); 150 tbMenu = new QToolBar( this );
151 tbMenu->setHorizontalStretchable( TRUE ); 151 tbMenu->setHorizontalStretchable( TRUE );
152 152
153 QMenuBar *menu = new QMenuBar( tbMenu ); 153 QMenuBar *menu = new QMenuBar( tbMenu );
154 154
155 tbEdit = new QToolBar( this ); 155 tbEdit = new QToolBar( this );
156 156
157 QPopupMenu *file = new QPopupMenu( this ); 157 QPopupMenu *file = new QPopupMenu( this );
158 menu->insertItem( tr("File"), file ); 158 menu->insertItem( tr("File"), file );
159 159
160 QPopupMenu *edit = new QPopupMenu( this ); 160 QPopupMenu *edit = new QPopupMenu( this );
161 menu->insertItem( tr("Edit"), edit ); 161 menu->insertItem( tr("Edit"), edit );
162 162
163 // ### perhaps these shortcut keys should have some 163 // ### perhaps these shortcut keys should have some
164 // IPaq keys defined??? 164 // IPaq keys defined???
165 QAction *a; 165 QAction *a;
166 166
167 a = new QAction( tr( "New" ), Resource::loadPixmap("new"), QString::null, 0, this, 0 ); 167 a = new QAction( tr( "New" ), Resource::loadPixmap("new"), QString::null, 0, this, 0 );
168 connect( a, SIGNAL(activated()), this, SLOT(fileNew()) ); 168 connect( a, SIGNAL(activated()), this, SLOT(fileNew()) );
169 a->addTo( file ); 169 a->addTo( file );
170 170
171 a = new QAction( tr( "Open" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); 171 a = new QAction( tr( "Open" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 );
172 connect( a, SIGNAL(activated()), this, SLOT(fileOpen()) ); 172 connect( a, SIGNAL(activated()), this, SLOT(fileOpen()) );
173 a->addTo( file ); 173 a->addTo( file );
174 174
175 a = new QAction( tr( "Undo" ), Resource::loadIconSet("undo"), 175 a = new QAction( tr( "Undo" ), Resource::loadIconSet("undo"),
176 QString::null, 0, this, "editUndo" ); 176 QString::null, 0, this, "editUndo" );
177 connect( a, SIGNAL( activated() ), this, SLOT( editUndo() ) ); 177 connect( a, SIGNAL( activated() ), this, SLOT( editUndo() ) );
178 connect( editor, SIGNAL(undoAvailable(bool)), a, SLOT(setEnabled(bool)) ); 178 connect( editor, SIGNAL(undoAvailable(bool)), a, SLOT(setEnabled(bool)) );
179 a->addTo( tbEdit ); 179 a->addTo( tbEdit );
180 a->addTo( edit ); 180 a->addTo( edit );
181 a = new QAction( tr( "Redo" ), Resource::loadIconSet("redo"), 181 a = new QAction( tr( "Redo" ), Resource::loadIconSet("redo"),
182 QString::null, 0, this, "editRedo" ); 182 QString::null, 0, this, "editRedo" );
183 connect( a, SIGNAL( activated() ), this, SLOT( editRedo() ) ); 183 connect( a, SIGNAL( activated() ), this, SLOT( editRedo() ) );
184 connect( editor, SIGNAL(redoAvailable(bool)), a, SLOT(setEnabled(bool)) ); 184 connect( editor, SIGNAL(redoAvailable(bool)), a, SLOT(setEnabled(bool)) );
185 a->addTo( tbEdit ); 185 a->addTo( tbEdit );
186 a->addTo( edit ); 186 a->addTo( edit );
187 187
188 edit->insertSeparator(); 188 edit->insertSeparator();
189 189
190 a = new QAction( tr( "Copy" ), Resource::loadIconSet("copy"), 190 a = new QAction( tr( "Copy" ), Resource::loadIconSet("copy"),
191 QString::null, 0, this, "editCopy" ); 191 QString::null, 0, this, "editCopy" );
192 connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) ); 192 connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) );
193 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) ); 193 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) );
194 a->addTo( tbEdit ); 194 a->addTo( tbEdit );
195 a->addTo( edit ); 195 a->addTo( edit );
196 a = new QAction( tr( "Cut" ), Resource::loadIconSet("cut"), 196 a = new QAction( tr( "Cut" ), Resource::loadIconSet("cut"),
197 QString::null, 0, this, "editCut" ); 197 QString::null, 0, this, "editCut" );
198 connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); 198 connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) );
199 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) ); 199 connect( editor, SIGNAL(copyAvailable(bool)), a, SLOT(setEnabled(bool)) );
200 a->addTo( tbEdit ); 200 a->addTo( tbEdit );
201 a->addTo( edit ); 201 a->addTo( edit );
202 a = new QAction( tr( "Paste" ), Resource::loadPixmap("paste"), 202 a = new QAction( tr( "Paste" ), Resource::loadPixmap("paste"),
203 QString::null, 0, this, "editPaste" ); 203 QString::null, 0, this, "editPaste" );
204 connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); 204 connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) );
205 a->addTo( tbEdit ); 205 a->addTo( tbEdit );
206 a->addTo( edit ); 206 a->addTo( edit );
207 207
208 tbFont = new QToolBar( this ); 208 tbFont = new QToolBar( this );
209 tbFont->setLabel( "Font Actions" ); 209 tbFont->setLabel( "Font Actions" );
210 tbFont->setHorizontalStretchable(TRUE); 210 tbFont->setHorizontalStretchable(TRUE);
211 211
212 comboFont = new QComboBox( FALSE, tbFont ); 212 comboFont = new QComboBox( FALSE, tbFont );
213 FontDatabase db; 213 FontDatabase db;
214 QStringList f= db.families(); 214 QStringList f= db.families();
215 comboFont->insertStringList( db.families() ); 215 comboFont->insertStringList( db.families() );
216 connect( comboFont, SIGNAL( activated( const QString & ) ), 216 connect( comboFont, SIGNAL( activated(const QString&) ),
217 this, SLOT( textFamily( const QString & ) ) ); 217 this, SLOT( textFamily(const QString&) ) );
218 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( QApplication::font().family() ) ) ); 218 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( QApplication::font().family() ) ) );
219 comboFont->setMaximumWidth(90); 219 comboFont->setMaximumWidth(90);
220 220
221 comboSize = new QComboBox( TRUE, tbFont ); 221 comboSize = new QComboBox( TRUE, tbFont );
222 QValueList<int> sizes = db.standardSizes(); 222 QValueList<int> sizes = db.standardSizes();
223 QValueList<int>::Iterator it = sizes.begin(); 223 QValueList<int>::Iterator it = sizes.begin();
224 for ( ; it != sizes.end(); ++it ) 224 for ( ; it != sizes.end(); ++it )
225 comboSize->insertItem( QString::number( *it ) ); 225 comboSize->insertItem( QString::number( *it ) );
226 connect( comboSize, SIGNAL( activated( const QString & ) ), 226 connect( comboSize, SIGNAL( activated(const QString&) ),
227 this, SLOT( textSize( const QString & ) ) ); 227 this, SLOT( textSize(const QString&) ) );
228 comboSize->lineEdit()->setText( QString::number( QApplication::font().pointSize() ) ); 228 comboSize->lineEdit()->setText( QString::number( QApplication::font().pointSize() ) );
229 comboSize->setFixedWidth( 38 ); 229 comboSize->setFixedWidth( 38 );
230 230
231 tbStyle = new QToolBar( this ); 231 tbStyle = new QToolBar( this );
232 tbStyle->setLabel( "Style Actions" ); 232 tbStyle->setLabel( "Style Actions" );
233 233
234 actionTextBold = new QAction( tr( "Bold" ), 234 actionTextBold = new QAction( tr( "Bold" ),
235 Resource::loadPixmap("bold"), 235 Resource::loadPixmap("bold"),
236 QString::null, CTRL + Key_B, 236 QString::null, CTRL + Key_B,
237 this, "textBold" ); 237 this, "textBold" );
238 connect( actionTextBold, SIGNAL( activated() ), this, SLOT( textBold() ) ); 238 connect( actionTextBold, SIGNAL( activated() ), this, SLOT( textBold() ) );
239 actionTextBold->addTo( tbStyle ); 239 actionTextBold->addTo( tbStyle );
240 actionTextBold->setToggleAction( TRUE ); 240 actionTextBold->setToggleAction( TRUE );
241 actionTextItalic = new QAction( tr( "Italic" ), 241 actionTextItalic = new QAction( tr( "Italic" ),
242 Resource::loadPixmap("italic"), 242 Resource::loadPixmap("italic"),
243 tr( "&Italic" ), CTRL + Key_I, 243 tr( "&Italic" ), CTRL + Key_I,
244 this, "textItalic" ); 244 this, "textItalic" );
245 connect( actionTextItalic, SIGNAL( activated() ), this, 245 connect( actionTextItalic, SIGNAL( activated() ), this,
246 SLOT( textItalic() ) ); 246 SLOT( textItalic() ) );
247 actionTextItalic->addTo( tbStyle ); 247 actionTextItalic->addTo( tbStyle );
248 actionTextItalic->setToggleAction( TRUE ); 248 actionTextItalic->setToggleAction( TRUE );
249 actionTextUnderline = new QAction( tr( "Underline" ), 249 actionTextUnderline = new QAction( tr( "Underline" ),
250 Resource::loadPixmap("underline"), 250 Resource::loadPixmap("underline"),
251 tr( "&Underline" ), CTRL + Key_U, 251 tr( "&Underline" ), CTRL + Key_U,
252 this, "textUnderline" ); 252 this, "textUnderline" );
253 connect( actionTextUnderline, SIGNAL( activated() ), 253 connect( actionTextUnderline, SIGNAL( activated() ),
254 this, SLOT( textUnderline() ) ); 254 this, SLOT( textUnderline() ) );
255 actionTextUnderline->addTo( tbStyle ); 255 actionTextUnderline->addTo( tbStyle );
256 actionTextUnderline->setToggleAction( TRUE ); 256 actionTextUnderline->setToggleAction( TRUE );
257 257
258 alignMenu = new ButtonMenu( tbStyle ); 258 alignMenu = new ButtonMenu( tbStyle );
259 alignMenu->insertItem( Resource::loadPixmap("left"), tr("Left"), AlignLeft ); 259 alignMenu->insertItem( Resource::loadPixmap("left"), tr("Left"), AlignLeft );
260 alignMenu->insertItem( Resource::loadPixmap("center"), tr("Center"), AlignCenter ); 260 alignMenu->insertItem( Resource::loadPixmap("center"), tr("Center"), AlignCenter );
261 alignMenu->insertItem( Resource::loadPixmap("right"), tr("Right"), AlignRight ); 261 alignMenu->insertItem( Resource::loadPixmap("right"), tr("Right"), AlignRight );
262 alignMenu->insertItem( Resource::loadPixmap("opie-write/justify"), tr("Full"), Qt3::AlignJustify ); 262 alignMenu->insertItem( Resource::loadPixmap("opie-write/justify"), tr("Full"), Qt3::AlignJustify );
263 connect( alignMenu, SIGNAL(activated(int)), this, SLOT(textAlign(int)) ); 263 connect( alignMenu, SIGNAL(activated(int)), this, SLOT(textAlign(int)) );
264} 264}
265 265
266Qt3::QTextEdit *MainWindow::currentEditor() const 266Qt3::QTextEdit *MainWindow::currentEditor() const
267{ 267{
268 return editor; 268 return editor;
269} 269}
270 270
271void MainWindow::doConnections( Qt3::QTextEdit *e ) 271void MainWindow::doConnections( Qt3::QTextEdit *e )
272{ 272{
273 connect( e, SIGNAL( currentFontChanged( const QFont & ) ), 273 connect( e, SIGNAL( currentFontChanged(const QFont&) ),
274 this, SLOT( fontChanged( const QFont & ) ) ); 274 this, SLOT( fontChanged(const QFont&) ) );
275 connect( e, SIGNAL( currentColorChanged( const QColor & ) ), 275 connect( e, SIGNAL( currentColorChanged(const QColor&) ),
276 this, SLOT( colorChanged( const QColor & ) ) ); 276 this, SLOT( colorChanged(const QColor&) ) );
277 connect( e, SIGNAL( currentAlignmentChanged( int ) ), 277 connect( e, SIGNAL( currentAlignmentChanged(int) ),
278 this, SLOT( alignmentChanged( int ) ) ); 278 this, SLOT( alignmentChanged(int) ) );
279} 279}
280 280
281void MainWindow::updateFontSizeCombo( const QFont &f ) 281void MainWindow::updateFontSizeCombo( const QFont &f )
282{ 282{
283 comboSize->clear(); 283 comboSize->clear();
284 FontDatabase fdb; 284 FontDatabase fdb;
285 QValueList<int> sizes = fdb.pointSizes( f.family() ); 285 QValueList<int> sizes = fdb.pointSizes( f.family() );
286 QValueList<int>::Iterator it = sizes.begin(); 286 QValueList<int>::Iterator it = sizes.begin();
287 for ( ; it != sizes.end(); ++it ) 287 for ( ; it != sizes.end(); ++it )
288 comboSize->insertItem( QString::number( *it ) ); 288 comboSize->insertItem( QString::number( *it ) );
289} 289}
290 290
291void MainWindow::editUndo() 291void MainWindow::editUndo()
292{ 292{
293 if ( !currentEditor() ) 293 if ( !currentEditor() )
294 return; 294 return;
295 currentEditor()->undo(); 295 currentEditor()->undo();
296} 296}
297 297
298void MainWindow::editRedo() 298void MainWindow::editRedo()
299{ 299{
300 if ( !currentEditor() ) 300 if ( !currentEditor() )
301 return; 301 return;
302 currentEditor()->redo(); 302 currentEditor()->redo();
303} 303}
304 304
305void MainWindow::editCut() 305void MainWindow::editCut()
306{ 306{
307 if ( !currentEditor() ) 307 if ( !currentEditor() )
308 return; 308 return;
309 currentEditor()->cut(); 309 currentEditor()->cut();
310} 310}
311 311
312void MainWindow::editCopy() 312void MainWindow::editCopy()
313{ 313{
314 if ( !currentEditor() ) 314 if ( !currentEditor() )
315 return; 315 return;
316 currentEditor()->copy(); 316 currentEditor()->copy();
317} 317}
318 318
319void MainWindow::editPaste() 319void MainWindow::editPaste()
320{ 320{
321 if ( !currentEditor() ) 321 if ( !currentEditor() )
322 return; 322 return;
323 currentEditor()->paste(); 323 currentEditor()->paste();
324} 324}
325 325
326void MainWindow::textBold() 326void MainWindow::textBold()
327{ 327{
328 if ( !currentEditor() ) 328 if ( !currentEditor() )
329 return; 329 return;
330 currentEditor()->setBold( actionTextBold->isOn() ); 330 currentEditor()->setBold( actionTextBold->isOn() );
331} 331}
332 332
333void MainWindow::textUnderline() 333void MainWindow::textUnderline()
334{ 334{
335 if ( !currentEditor() ) 335 if ( !currentEditor() )
336 return; 336 return;
337 currentEditor()->setUnderline( actionTextUnderline->isOn() ); 337 currentEditor()->setUnderline( actionTextUnderline->isOn() );
338} 338}
339 339
340void MainWindow::textItalic() 340void MainWindow::textItalic()
341{ 341{
342 if ( !currentEditor() ) 342 if ( !currentEditor() )
343 return; 343 return;
344 currentEditor()->setItalic( actionTextItalic->isOn() ); 344 currentEditor()->setItalic( actionTextItalic->isOn() );
345} 345}
346 346
347void MainWindow::textFamily( const QString &f ) 347void MainWindow::textFamily( const QString &f )
348{ 348{
349 if ( !currentEditor() ) 349 if ( !currentEditor() )
350 return; 350 return;
351 currentEditor()->setFamily( f ); 351 currentEditor()->setFamily( f );
352 currentEditor()->viewport()->setFocus(); 352 currentEditor()->viewport()->setFocus();
353} 353}
354 354
355void MainWindow::textSize( const QString &p ) 355void MainWindow::textSize( const QString &p )
356{ 356{
357 if ( !currentEditor() ) 357 if ( !currentEditor() )
358 return; 358 return;
359 currentEditor()->setPointSize( p.toInt() ); 359 currentEditor()->setPointSize( p.toInt() );
360 currentEditor()->viewport()->setFocus(); 360 currentEditor()->viewport()->setFocus();
361} 361}
362 362
363void MainWindow::textStyle( int i ) 363void MainWindow::textStyle( int i )
364{ 364{
365 if ( !currentEditor() ) 365 if ( !currentEditor() )
366 return; 366 return;
367 if ( i == 0 ) 367 if ( i == 0 )
368 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayBlock, 368 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayBlock,
369 Qt3::QStyleSheetItem::ListDisc ); 369 Qt3::QStyleSheetItem::ListDisc );
370 else if ( i == 1 ) 370 else if ( i == 1 )
371 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 371 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
372 Qt3::QStyleSheetItem::ListDisc ); 372 Qt3::QStyleSheetItem::ListDisc );
373 else if ( i == 2 ) 373 else if ( i == 2 )
374 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 374 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
375 Qt3::QStyleSheetItem::ListCircle ); 375 Qt3::QStyleSheetItem::ListCircle );
376 else if ( i == 3 ) 376 else if ( i == 3 )
377 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 377 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
378 Qt3::QStyleSheetItem::ListSquare ); 378 Qt3::QStyleSheetItem::ListSquare );
379 else if ( i == 4 ) 379 else if ( i == 4 )
380 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 380 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
381 Qt3::QStyleSheetItem::ListDecimal ); 381 Qt3::QStyleSheetItem::ListDecimal );
382 else if ( i == 5 ) 382 else if ( i == 5 )
383 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 383 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
384 Qt3::QStyleSheetItem::ListLowerAlpha ); 384 Qt3::QStyleSheetItem::ListLowerAlpha );
385 else if ( i == 6 ) 385 else if ( i == 6 )
386 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem, 386 currentEditor()->setParagType( Qt3::QStyleSheetItem::DisplayListItem,
387 Qt3::QStyleSheetItem::ListUpperAlpha ); 387 Qt3::QStyleSheetItem::ListUpperAlpha );
388 currentEditor()->viewport()->setFocus(); 388 currentEditor()->viewport()->setFocus();
389} 389}
390 390
391void MainWindow::textAlign( int a ) 391void MainWindow::textAlign( int a )
392{ 392{
393 if ( !currentEditor() ) 393 if ( !currentEditor() )
394 return; 394 return;
395 editor->setAlignment( a ); 395 editor->setAlignment( a );
396} 396}
397 397
398void MainWindow::fontChanged( const QFont &f ) 398void MainWindow::fontChanged( const QFont &f )
399{ 399{
400 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( f.family() ) ) ); 400 comboFont->setCurrentItem( comboFont->listBox()->index( comboFont->listBox()->findItem( f.family() ) ) );
401 updateFontSizeCombo( f ); 401 updateFontSizeCombo( f );
402 comboSize->lineEdit()->setText( QString::number( f.pointSize() ) ); 402 comboSize->lineEdit()->setText( QString::number( f.pointSize() ) );
403 actionTextBold->setOn( f.bold() ); 403 actionTextBold->setOn( f.bold() );
404 actionTextItalic->setOn( f.italic() ); 404 actionTextItalic->setOn( f.italic() );
405 actionTextUnderline->setOn( f.underline() ); 405 actionTextUnderline->setOn( f.underline() );
406} 406}
407 407
408void MainWindow::colorChanged( const QColor & ) 408void MainWindow::colorChanged( const QColor & )
409{ 409{
410} 410}
411 411
412void MainWindow::alignmentChanged( int a ) 412void MainWindow::alignmentChanged( int a )
413{ 413{
414 if ( ( a == Qt3::AlignAuto ) || ( a & AlignLeft )) { 414 if ( ( a == Qt3::AlignAuto ) || ( a & AlignLeft )) {
415 alignMenu->setCurrentItem(AlignLeft); 415 alignMenu->setCurrentItem(AlignLeft);
416 } else if ( ( a & AlignCenter ) ) { 416 } else if ( ( a & AlignCenter ) ) {
417 alignMenu->setCurrentItem(AlignCenter); 417 alignMenu->setCurrentItem(AlignCenter);
418 } else if ( ( a & AlignRight ) ) { 418 } else if ( ( a & AlignRight ) ) {
419 alignMenu->setCurrentItem(AlignRight); 419 alignMenu->setCurrentItem(AlignRight);
420 } else if ( ( a & Qt3::AlignJustify ) ) { 420 } else if ( ( a & Qt3::AlignJustify ) ) {
421 alignMenu->setCurrentItem(Qt3::AlignJustify); 421 alignMenu->setCurrentItem(Qt3::AlignJustify);
422 } 422 }
423} 423}
424 424
425void MainWindow::editorChanged( QWidget * ) 425void MainWindow::editorChanged( QWidget * )
426{ 426{
427 if ( !currentEditor() ) 427 if ( !currentEditor() )
428 return; 428 return;
429 fontChanged( currentEditor()->font() ); 429 fontChanged( currentEditor()->font() );
430 colorChanged( currentEditor()->color() ); 430 colorChanged( currentEditor()->color() );
431 alignmentChanged( currentEditor()->alignment() ); 431 alignmentChanged( currentEditor()->alignment() );
432} 432}
433 433
434void MainWindow::fileOpen() 434void MainWindow::fileOpen()
435{ 435{
436 save(); 436 save();
437 editorStack->raiseWidget( fileSelector ); 437 editorStack->raiseWidget( fileSelector );
438 fileSelector->reread(); 438 fileSelector->reread();
439 hideEditTools(); 439 hideEditTools();
440 fileSelector->setNewVisible( TRUE ); 440 fileSelector->setNewVisible( TRUE );
441 clear(); 441 clear();
442 updateCaption(); 442 updateCaption();
443} 443}
444 444
445void MainWindow::fileRevert() 445void MainWindow::fileRevert()
446{ 446{
447 qDebug( "QMainWindow::fileRevert needs to be done" ); 447 qDebug( "QMainWindow::fileRevert needs to be done" );
448} 448}
449 449
450void MainWindow::fileNew() 450void MainWindow::fileNew()
451{ 451{
452 editor->setTextFormat( Qt::RichText ); 452 editor->setTextFormat( Qt::RichText );
453 save(); 453 save();
454 newFile(DocLnk()); 454 newFile(DocLnk());
455} 455}
456 456
457void MainWindow::insertTable() 457void MainWindow::insertTable()
458{ 458{
459 qDebug( "MainWindow::insertTable() needs to be done" ); 459 qDebug( "MainWindow::insertTable() needs to be done" );
460} 460}
461 461
462void MainWindow::newFile( const DocLnk &dl ) 462void MainWindow::newFile( const DocLnk &dl )
463{ 463{
464 DocLnk nf = dl; 464 DocLnk nf = dl;
465 nf.setType( "text/html" ); 465 nf.setType( "text/html" );
466 clear(); 466 clear();
467 editorStack->raiseWidget( editor ); 467 editorStack->raiseWidget( editor );
468 editor->viewport()->setFocus(); 468 editor->viewport()->setFocus();
469 doc = new DocLnk( nf ); 469 doc = new DocLnk( nf );
470 updateCaption(); 470 updateCaption();
471} 471}
472 472
473void MainWindow::openFile( const DocLnk &dl ) 473void MainWindow::openFile( const DocLnk &dl )
474{ 474{
475 FileManager fm; 475 FileManager fm;
476 QString txt; 476 QString txt;
477 if ( !fm.loadFile( dl, txt ) ) 477 if ( !fm.loadFile( dl, txt ) )
478 qDebug( "couldn't open file" ); 478 qDebug( "couldn't open file" );
479 clear(); 479 clear();
480 editorStack->raiseWidget( editor ); 480 editorStack->raiseWidget( editor );
481 editor->viewport()->setFocus(); 481 editor->viewport()->setFocus();
482 doc = new DocLnk( dl ); 482 doc = new DocLnk( dl );
483 editor->setText( txt ); 483 editor->setText( txt );
484 editor->setModified( FALSE ); 484 editor->setModified( FALSE );
485 updateCaption(); 485 updateCaption();
486} 486}
487 487
488void MainWindow::showEditTools( void ) 488void MainWindow::showEditTools( void )
489{ 489{
490 tbMenu->show(); 490 tbMenu->show();
491 tbEdit->show(); 491 tbEdit->show();
492 tbFont->show(); 492 tbFont->show();
493 tbStyle->show(); 493 tbStyle->show();
494} 494}
495 495
496void MainWindow::hideEditTools( void ) 496void MainWindow::hideEditTools( void )
497{ 497{
498 // let's reset the buttons... 498 // let's reset the buttons...
499 actionTextBold->setOn( FALSE ); 499 actionTextBold->setOn( FALSE );
500 actionTextItalic->setOn( FALSE ); 500 actionTextItalic->setOn( FALSE );
501 actionTextUnderline->setOn( FALSE ); 501 actionTextUnderline->setOn( FALSE );
502 //comboFont->setCurrentText( QApplication::font().family() ); 502 //comboFont->setCurrentText( QApplication::font().family() );
503 comboSize->lineEdit()->setText( QString::number(QApplication::font().pointSize() ) ); 503 comboSize->lineEdit()->setText( QString::number(QApplication::font().pointSize() ) );
504 tbMenu->hide(); 504 tbMenu->hide();
505 tbEdit->hide(); 505 tbEdit->hide();
506 tbFont->hide(); 506 tbFont->hide();
507 tbStyle->hide(); 507 tbStyle->hide();
508} 508}
509 509
510 510
511void MainWindow::save() 511void MainWindow::save()
512{ 512{
513 if ( !doc ) 513 if ( !doc )
514 return; 514 return;
515 if ( !editor->isModified() ) 515 if ( !editor->isModified() )
516 return; 516 return;
517 517
518 QString rt = editor->text(); 518 QString rt = editor->text();
519 519
520 // quick hack to get around formatting... 520 // quick hack to get around formatting...
521 editor->setTextFormat( Qt::PlainText ); 521 editor->setTextFormat( Qt::PlainText );
522 QString pt = editor->text(); 522 QString pt = editor->text();
523 editor->setTextFormat( Qt::RichText ); 523 editor->setTextFormat( Qt::RichText );
524 524
525 if ( doc->name().isEmpty() ) { 525 if ( doc->name().isEmpty() ) {
526 unsigned ispace = pt.find( ' ' ); 526 unsigned ispace = pt.find( ' ' );
527 unsigned ienter = pt.find( '\n' ); 527 unsigned ienter = pt.find( '\n' );
528 int i = (ispace < ienter) ? ispace : ienter; 528 int i = (ispace < ienter) ? ispace : ienter;
529 QString docname; 529 QString docname;
530 if ( i == -1 ) { 530 if ( i == -1 ) {
531 if ( pt.isEmpty() ) 531 if ( pt.isEmpty() )
532 docname = "Empty Text"; 532 docname = "Empty Text";
533 else 533 else
534 docname = pt; 534 docname = pt;
535 } else { 535 } else {
536 docname = pt.left( i ); 536 docname = pt.left( i );
537 } 537 }
538 doc->setName(docname); 538 doc->setName(docname);
539 } 539 }
540 FileManager fm; 540 FileManager fm;
541 fm.saveFile( *doc, rt ); 541 fm.saveFile( *doc, rt );
542} 542}
543 543
544void MainWindow::clear() 544void MainWindow::clear()
545{ 545{
546 delete doc; 546 delete doc;
547 doc = 0; 547 doc = 0;
548 editor->clear(); 548 editor->clear();
549} 549}
550 550
551void MainWindow::updateCaption() 551void MainWindow::updateCaption()
552{ 552{
553 if ( !doc ) 553 if ( !doc )
554 setCaption( tr("Rich Text Editor") ); 554 setCaption( tr("Rich Text Editor") );
555 else { 555 else {
556 QString s = doc->name(); 556 QString s = doc->name();
557 if ( s.isEmpty() ) 557 if ( s.isEmpty() )
558 s = tr( "Unnamed" ); 558 s = tr( "Unnamed" );
559 setCaption( s + " - " + tr("Rich Text Editor") ); 559 setCaption( s + " - " + tr("Rich Text Editor") );
560 } 560 }
561} 561}
562 562
563void MainWindow::closeEvent( QCloseEvent *e ) 563void MainWindow::closeEvent( QCloseEvent *e )
564{ 564{
565 if ( editorStack->visibleWidget() == editor ) { 565 if ( editorStack->visibleWidget() == editor ) {
566 // call fileOpen instead, don't close it 566 // call fileOpen instead, don't close it
567 fileOpen(); 567 fileOpen();
568 e->ignore(); 568 e->ignore();
569 } else { 569 } else {
570 e->accept(); 570 e->accept();
571 } 571 }
572} 572}
573 573
574#include "mainwindow.moc" 574#include "mainwindow.moc"
diff --git a/noncore/apps/opie-write/qtextedit.cpp b/noncore/apps/opie-write/qtextedit.cpp
index 27dd515..73b7b7b 100644
--- a/noncore/apps/opie-write/qtextedit.cpp
+++ b/noncore/apps/opie-write/qtextedit.cpp
@@ -1,4575 +1,4575 @@
1/**************************************************************************** 1/****************************************************************************
2** $Id$ 2** $Id$
3** 3**
4** Implementation of the QTextEdit class 4** Implementation of the QTextEdit class
5** 5**
6** Created : 990101 6** Created : 990101
7** 7**
8** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. 8** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
9** 9**
10** This file is part of the widgets module of the Qt GUI Toolkit. 10** This file is part of the widgets module of the Qt GUI Toolkit.
11** 11**
12** This file may be distributed under the terms of the Q Public License 12** This file may be distributed under the terms of the Q Public License
13** as defined by Trolltech AS of Norway and appearing in the file 13** as defined by Trolltech AS of Norway and appearing in the file
14** LICENSE.QPL included in the packaging of this file. 14** LICENSE.QPL included in the packaging of this file.
15** 15**
16** This file may be distributed and/or modified under the terms of the 16** This file may be distributed and/or modified under the terms of the
17** GNU General Public License version 2 as published by the Free Software 17** GNU General Public License version 2 as published by the Free Software
18** Foundation and appearing in the file LICENSE.GPL included in the 18** Foundation and appearing in the file LICENSE.GPL included in the
19** packaging of this file. 19** packaging of this file.
20** 20**
21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition 21** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22** licenses may use this file in accordance with the Qt Commercial License 22** licenses may use this file in accordance with the Qt Commercial License
23** Agreement provided with the Software. 23** Agreement provided with the Software.
24** 24**
25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27** 27**
28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for 28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29** information about Qt Commercial License Agreements. 29** information about Qt Commercial License Agreements.
30** See http://www.trolltech.com/qpl/ for QPL licensing information. 30** See http://www.trolltech.com/qpl/ for QPL licensing information.
31** See http://www.trolltech.com/gpl/ for GPL licensing information. 31** See http://www.trolltech.com/gpl/ for GPL licensing information.
32** 32**
33** Contact info@trolltech.com if any conditions of this licensing are 33** Contact info@trolltech.com if any conditions of this licensing are
34** not clear to you. 34** not clear to you.
35** 35**
36**********************************************************************/ 36**********************************************************************/
37 37
38#include "qtextedit.h" 38#include "qtextedit.h"
39 39
40#include "qrichtext_p.h" 40#include "qrichtext_p.h"
41#include "qlistbox.h" 41#include "qlistbox.h"
42#include "qclipboard.h" 42#include "qclipboard.h"
43#include "qpopupmenu.h" 43#include "qpopupmenu.h"
44 44
45#define ACCEL_KEY(k) "\t" + QString("Ctrl+" #k) 45#define ACCEL_KEY(k) "\t" + QString("Ctrl+" #k)
46 46
47using namespace Qt3; 47using namespace Qt3;
48 48
49static bool qt_enable_richtext_copy = FALSE; 49static bool qt_enable_richtext_copy = FALSE;
50 50
51struct QUndoRedoInfoPrivate 51struct QUndoRedoInfoPrivate
52{ 52{
53 QTextString text; 53 QTextString text;
54}; 54};
55 55
56namespace Qt3 { 56namespace Qt3 {
57 57
58class QTextEditPrivate 58class QTextEditPrivate
59{ 59{
60public: 60public:
61 QTextEditPrivate() 61 QTextEditPrivate()
62 :preeditStart(-1),preeditLength(-1),ensureCursorVisibleInShowEvent(FALSE) 62 :preeditStart(-1),preeditLength(-1),ensureCursorVisibleInShowEvent(FALSE)
63 { 63 {
64 for ( int i=0; i<7; i++ ) 64 for ( int i=0; i<7; i++ )
65 id[i] = 0; 65 id[i] = 0;
66 } 66 }
67 int id[ 7 ]; 67 int id[ 7 ];
68 int preeditStart; 68 int preeditStart;
69 int preeditLength; 69 int preeditLength;
70 bool ensureCursorVisibleInShowEvent; 70 bool ensureCursorVisibleInShowEvent;
71 QString scrollToAnchor; // used to deferr scrollToAnchor() until the show event when we are resized 71 QString scrollToAnchor; // used to deferr scrollToAnchor() until the show event when we are resized
72}; 72};
73 73
74} 74}
75 75
76static bool block_set_alignment = FALSE; 76static bool block_set_alignment = FALSE;
77 77
78/*! 78/*!
79 \class QTextEdit qtextedit.h 79 \class QTextEdit qtextedit.h
80 \brief The QTextEdit widget provides a powerful single-page rich text editor. 80 \brief The QTextEdit widget provides a powerful single-page rich text editor.
81 81
82 \ingroup basic 82 \ingroup basic
83 \ingroup text 83 \ingroup text
84 \mainclass 84 \mainclass
85 85
86 \tableofcontents 86 \tableofcontents
87 87
88 \section1 Introduction and Concepts 88 \section1 Introduction and Concepts
89 89
90 QTextEdit is an advanced WYSIWYG viewer/editor supporting rich 90 QTextEdit is an advanced WYSIWYG viewer/editor supporting rich
91 text formatting using HTML-style tags. It is optimized to handle 91 text formatting using HTML-style tags. It is optimized to handle
92 large documents and to respond quickly to user input. 92 large documents and to respond quickly to user input.
93 93
94 QTextEdit has three modes of operation: 94 QTextEdit has three modes of operation:
95 \table 95 \table
96 \header \i Mode \i Command \i Notes 96 \header \i Mode \i Command \i Notes
97 \row \i Plain Text Editor \i setTextFormat(PlainText) 97 \row \i Plain Text Editor \i setTextFormat(PlainText)
98 \i Set text with setText(); text() returns plain text. Text 98 \i Set text with setText(); text() returns plain text. Text
99 attributes (e.g. colors) can be set, but plain text is always 99 attributes (e.g. colors) can be set, but plain text is always
100 returned.<sup>1.</sup> 100 returned.<sup>1.</sup>
101 \row \i Rich Text Editor \i setTextFormat(RichText) 101 \row \i Rich Text Editor \i setTextFormat(RichText)
102 \i Set text with setText(); text() returns rich text. Rich 102 \i Set text with setText(); text() returns rich text. Rich
103 text editing is fairly limited. You can't set margins or 103 text editing is fairly limited. You can't set margins or
104 insert images for example (although you can read and 104 insert images for example (although you can read and
105 correctly display files that have margins set and that 105 correctly display files that have margins set and that
106 include images). This mode is mostly useful for editing small 106 include images). This mode is mostly useful for editing small
107 amounts of rich text. <sup>2.</sup> 107 amounts of rich text. <sup>2.</sup>
108 \row \i Text Viewer<sup>3.</sup> \i setReadOnly(TRUE) 108 \row \i Text Viewer<sup>3.</sup> \i setReadOnly(TRUE)
109 \i Set text with setText() or append() (which has no undo 109 \i Set text with setText() or append() (which has no undo
110 history so is faster and uses less memory); text() returns 110 history so is faster and uses less memory); text() returns
111 plain or rich text depending on the textFormat(). This mode 111 plain or rich text depending on the textFormat(). This mode
112 can correctly display a large subset of HTML tags. 112 can correctly display a large subset of HTML tags.
113 \endtable 113 \endtable
114 114
115 <sup>1.</sup><small>We do \e not recommend using QTextEdit to 115 <sup>1.</sup><small>We do \e not recommend using QTextEdit to
116 create syntax highlighting editors because the current API is 116 create syntax highlighting editors because the current API is
117 insufficient for this purpose. We hope to release a more complete 117 insufficient for this purpose. We hope to release a more complete
118 API that will support syntax highlighting in a later 118 API that will support syntax highlighting in a later
119 release.</small> 119 release.</small>
120 120
121 <sup>2.</sup><small>A more complete API that supports setting 121 <sup>2.</sup><small>A more complete API that supports setting
122 margins, images, etc., is planned for a later Qt release.</small> 122 margins, images, etc., is planned for a later Qt release.</small>
123 123
124 <sup>3.</sup><small>Qt 3.1 will provide a Log Viewer mode which is 124 <sup>3.</sup><small>Qt 3.1 will provide a Log Viewer mode which is
125 optimised for the fast and memory efficient display of large 125 optimised for the fast and memory efficient display of large
126 amounts of read only text.</small> 126 amounts of read only text.</small>
127 127
128 We recommend that you always call setTextFormat() to set the mode 128 We recommend that you always call setTextFormat() to set the mode
129 you want to use. If you use \c AutoText then setText() and 129 you want to use. If you use \c AutoText then setText() and
130 append() will try to determine whether the text they are given is 130 append() will try to determine whether the text they are given is
131 plain text or rich text. If you use \c RichText then setText() and 131 plain text or rich text. If you use \c RichText then setText() and
132 append() will assume that the text they are given is rich text. 132 append() will assume that the text they are given is rich text.
133 insert() simply inserts the text it is given. 133 insert() simply inserts the text it is given.
134 134
135 QTextEdit works on paragraphs and characters. A paragraph is a 135 QTextEdit works on paragraphs and characters. A paragraph is a
136 formatted string which is word-wrapped to fit into the width of 136 formatted string which is word-wrapped to fit into the width of
137 the widget. By default when reading plain text, two newlines 137 the widget. By default when reading plain text, two newlines
138 signify a paragraph. A document consists of zero or more 138 signify a paragraph. A document consists of zero or more
139 paragraphs, indexed from 0. Characters are indexed on a 139 paragraphs, indexed from 0. Characters are indexed on a
140 per-paragraph basis, also indexed from 0. The words in the 140 per-paragraph basis, also indexed from 0. The words in the
141 paragraph are aligned in accordance with the paragraph's 141 paragraph are aligned in accordance with the paragraph's
142 alignment(). Paragraphs are separated by hard line breaks. Each 142 alignment(). Paragraphs are separated by hard line breaks. Each
143 character within a paragraph has its own attributes, for example, 143 character within a paragraph has its own attributes, for example,
144 font and color. 144 font and color.
145 145
146 The text edit documentation uses the following concepts: 146 The text edit documentation uses the following concepts:
147 \list 147 \list
148 \i \e{current format} -- 148 \i \e{current format} --
149 this is the format at the current cursor position, \e and it 149 this is the format at the current cursor position, \e and it
150 is the format of the selected text if any. 150 is the format of the selected text if any.
151 \i \e{current paragraph} -- the paragraph which contains the 151 \i \e{current paragraph} -- the paragraph which contains the
152 cursor. 152 cursor.
153 \endlist 153 \endlist
154 154
155 QTextEdit can display images (using QMimeSourceFactory), lists and 155 QTextEdit can display images (using QMimeSourceFactory), lists and
156 tables. If the text is too large to view within the text edit's 156 tables. If the text is too large to view within the text edit's
157 viewport, scrollbars will appear. The text edit can load both 157 viewport, scrollbars will appear. The text edit can load both
158 plain text and HTML files (a subset of HTML 3.2 and 4). The 158 plain text and HTML files (a subset of HTML 3.2 and 4). The
159 rendering style and the set of valid tags are defined by a 159 rendering style and the set of valid tags are defined by a
160 styleSheet(). Custom tags can be created and placed in a custom 160 styleSheet(). Custom tags can be created and placed in a custom
161 style sheet. Change the style sheet with \l{setStyleSheet()}; see 161 style sheet. Change the style sheet with \l{setStyleSheet()}; see
162 QStyleSheet for details. The images identified by image tags are 162 QStyleSheet for details. The images identified by image tags are
163 displayed if they can be interpreted using the text edit's 163 displayed if they can be interpreted using the text edit's
164 \l{QMimeSourceFactory}; see setMimeSourceFactory(). 164 \l{QMimeSourceFactory}; see setMimeSourceFactory().
165 165
166 If you want a text browser with more navigation use QTextBrowser. 166 If you want a text browser with more navigation use QTextBrowser.
167 If you just need to display a small piece of rich text use QLabel 167 If you just need to display a small piece of rich text use QLabel
168 or QSimpleRichText. 168 or QSimpleRichText.
169 169
170 If you create a new QTextEdit, and want to allow the user to edit 170 If you create a new QTextEdit, and want to allow the user to edit
171 rich text, call setTextFormat(Qt::RichText) to ensure that the 171 rich text, call setTextFormat(Qt::RichText) to ensure that the
172 text is treated as rich text. (Rich text uses HTML tags to set 172 text is treated as rich text. (Rich text uses HTML tags to set
173 text formatting attributes. See QStyleSheet for information on the 173 text formatting attributes. See QStyleSheet for information on the
174 HTML tags that are supported.). If you don't call setTextFormat() 174 HTML tags that are supported.). If you don't call setTextFormat()
175 explicitly the text edit will guess from the text itself whether 175 explicitly the text edit will guess from the text itself whether
176 it is rich text or plain text. This means that if the text looks 176 it is rich text or plain text. This means that if the text looks
177 like HTML or XML it will probably be interpreted as rich text, so 177 like HTML or XML it will probably be interpreted as rich text, so
178 you should call setTextFormat(Qt::PlainText) to preserve such 178 you should call setTextFormat(Qt::PlainText) to preserve such
179 text. 179 text.
180 180
181 Note that we do not intend to add a full-featured web browser 181 Note that we do not intend to add a full-featured web browser
182 widget to Qt (because that would easily double Qt's size and only 182 widget to Qt (because that would easily double Qt's size and only
183 a few applications would benefit from it). The rich 183 a few applications would benefit from it). The rich
184 text support in Qt is designed to provide a fast, portable and 184 text support in Qt is designed to provide a fast, portable and
185 efficient way to add reasonable online help facilities to 185 efficient way to add reasonable online help facilities to
186 applications, and to provide a basis for rich text editors. 186 applications, and to provide a basis for rich text editors.
187 \section1 Using QTextEdit as a Display Widget 187 \section1 Using QTextEdit as a Display Widget
188 188
189 QTextEdit can display a large HTML subset, including tables and 189 QTextEdit can display a large HTML subset, including tables and
190 images. 190 images.
191 191
192 The text is set or replaced using setText() which deletes any 192 The text is set or replaced using setText() which deletes any
193 existing text and replaces it with the text passed in the 193 existing text and replaces it with the text passed in the
194 setText() call. If you call setText() with legacy HTML (with 194 setText() call. If you call setText() with legacy HTML (with
195 setTextFormat(RichText) in force), and then call text(), the text 195 setTextFormat(RichText) in force), and then call text(), the text
196 that is returned may have different markup, but will render the 196 that is returned may have different markup, but will render the
197 same. Text can be inserted with insert(), paste(), pasteSubType() 197 same. Text can be inserted with insert(), paste(), pasteSubType()
198 and append(). Text that is appended does not go into the undo 198 and append(). Text that is appended does not go into the undo
199 history; this makes append() faster and consumes less memory. Text 199 history; this makes append() faster and consumes less memory. Text
200 can also be cut(). The entire text is deleted with clear() and the 200 can also be cut(). The entire text is deleted with clear() and the
201 selected text is deleted with removeSelectedText(). Selected 201 selected text is deleted with removeSelectedText(). Selected
202 (marked) text can also be deleted with del() (which will delete 202 (marked) text can also be deleted with del() (which will delete
203 the character to the right of the cursor if no text is selected). 203 the character to the right of the cursor if no text is selected).
204 204
205 Loading and saving text is achieved using setText() and text(), 205 Loading and saving text is achieved using setText() and text(),
206 for example: 206 for example:
207 \code 207 \code
208 QFile file( fileName ); // Read the text from a file 208 QFile file( fileName ); // Read the text from a file
209 if ( file.open( IO_ReadOnly ) ) { 209 if ( file.open( IO_ReadOnly ) ) {
210 QTextStream ts( &file ); 210 QTextStream ts( &file );
211 textEdit->setText( ts.read() ); 211 textEdit->setText( ts.read() );
212 } 212 }
213 \endcode 213 \endcode
214 \code 214 \code
215 QFile file( fileName ); // Write the text to a file 215 QFile file( fileName ); // Write the text to a file
216 if ( file.open( IO_WriteOnly ) ) { 216 if ( file.open( IO_WriteOnly ) ) {
217 QTextStream ts( &file ); 217 QTextStream ts( &file );
218 ts << textEdit->text(); 218 ts << textEdit->text();
219 textEdit->setModified( FALSE ); 219 textEdit->setModified( FALSE );
220 } 220 }
221 \endcode 221 \endcode
222 222
223 By default the text edit wraps words at whitespace to fit within 223 By default the text edit wraps words at whitespace to fit within
224 the text edit widget. The setWordWrap() function is used to 224 the text edit widget. The setWordWrap() function is used to
225 specify the kind of word wrap you want, or \c NoWrap if you don't 225 specify the kind of word wrap you want, or \c NoWrap if you don't
226 want any wrapping. Call setWordWrap() to set a fixed pixel width 226 want any wrapping. Call setWordWrap() to set a fixed pixel width
227 \c FixedPixelWidth, or character column (e.g. 80 column) \c 227 \c FixedPixelWidth, or character column (e.g. 80 column) \c
228 FixedColumnWidth with the pixels or columns specified with 228 FixedColumnWidth with the pixels or columns specified with
229 setWrapColumnOrWidth(). If you use word wrap to the widget's width 229 setWrapColumnOrWidth(). If you use word wrap to the widget's width
230 \c WidgetWidth, you can specify whether to break on whitespace or 230 \c WidgetWidth, you can specify whether to break on whitespace or
231 anywhere with setWrapPolicy(). 231 anywhere with setWrapPolicy().
232 232
233 The background color is set differently than other widgets, using 233 The background color is set differently than other widgets, using
234 setPaper(). You specify a brush style which could be a plain color 234 setPaper(). You specify a brush style which could be a plain color
235 or a complex pixmap. 235 or a complex pixmap.
236 236
237 Hypertext links are automatically underlined; this can be changed 237 Hypertext links are automatically underlined; this can be changed
238 with setLinkUnderline(). The tab stop width is set with 238 with setLinkUnderline(). The tab stop width is set with
239 setTabStopWidth(). 239 setTabStopWidth().
240 240
241 The zoomIn() and zoomOut() functions can be used to resize the 241 The zoomIn() and zoomOut() functions can be used to resize the
242 text by increasing (decreasing for zoomOut()) the point size used. 242 text by increasing (decreasing for zoomOut()) the point size used.
243 Images are not affected by the zoom functions. 243 Images are not affected by the zoom functions.
244 244
245 The lines() function returns the number of lines in the text and 245 The lines() function returns the number of lines in the text and
246 paragraphs() returns the number of paragraphs. The number of lines 246 paragraphs() returns the number of paragraphs. The number of lines
247 within a particular paragraph is returned by linesOfParagraph(). 247 within a particular paragraph is returned by linesOfParagraph().
248 The length of the entire text in characters is returned by 248 The length of the entire text in characters is returned by
249 length(). 249 length().
250 250
251 You can scroll to an anchor in the text, e.g. \c{<a 251 You can scroll to an anchor in the text, e.g. \c{<a
252 name="anchor">} with scrollToAnchor(). The find() function can be 252 name="anchor">} with scrollToAnchor(). The find() function can be
253 used to find and select a given string within the text. 253 used to find and select a given string within the text.
254 254
255 A read-only QTextEdit provides the same functionality as the 255 A read-only QTextEdit provides the same functionality as the
256 (obsolete) QTextView. (QTextView is still supplied for 256 (obsolete) QTextView. (QTextView is still supplied for
257 compatibility with old code.) 257 compatibility with old code.)
258 258
259 \section2 Read-only key bindings 259 \section2 Read-only key bindings
260 260
261 When QTextEdit is used read-only the key-bindings are limited to 261 When QTextEdit is used read-only the key-bindings are limited to
262 navigation, and text may only be selected with the mouse: 262 navigation, and text may only be selected with the mouse:
263 \table 263 \table
264 \header \i Keypresses \i Action 264 \header \i Keypresses \i Action
265 \row \i \e{UpArrow} \i Move one line up 265 \row \i \e{UpArrow} \i Move one line up
266 \row \i \e{DownArrow} \i Move one line down 266 \row \i \e{DownArrow} \i Move one line down
267 \row \i \e{LeftArrow} \i Move one character left 267 \row \i \e{LeftArrow} \i Move one character left
268 \row \i \e{RightArrow} \i Move one character right 268 \row \i \e{RightArrow} \i Move one character right
269 \row \i \e{PageUp} \i Move one (viewport) page up 269 \row \i \e{PageUp} \i Move one (viewport) page up
270 \row \i \e{PageDown} \i Move one (viewport) page down 270 \row \i \e{PageDown} \i Move one (viewport) page down
271 \row \i \e{Home} \i Move to the beginning of the text 271 \row \i \e{Home} \i Move to the beginning of the text
272 \row \i \e{End} \i Move to the end of the text 272 \row \i \e{End} \i Move to the end of the text
273 \row \i \e{Shift+Wheel} \i Scroll the page horizontally (the Wheel is the mouse wheel) 273 \row \i \e{Shift+Wheel} \i Scroll the page horizontally (the Wheel is the mouse wheel)
274 \row \i \e{Ctrl+Wheel} \i Zoom the text 274 \row \i \e{Ctrl+Wheel} \i Zoom the text
275 \endtable 275 \endtable
276 276
277 The text edit may be able to provide some meta-information. For 277 The text edit may be able to provide some meta-information. For
278 example, the documentTitle() function will return the text from 278 example, the documentTitle() function will return the text from
279 within HTML \c{<title>} tags. 279 within HTML \c{<title>} tags.
280 280
281 The text displayed in a text edit has a \e context. The context is 281 The text displayed in a text edit has a \e context. The context is
282 a path which the text edit's QMimeSourceFactory uses to resolve 282 a path which the text edit's QMimeSourceFactory uses to resolve
283 the locations of files and images. It is passed to the 283 the locations of files and images. It is passed to the
284 mimeSourceFactory() when quering data. (See QTextEdit() and 284 mimeSourceFactory() when quering data. (See QTextEdit() and
285 \l{context()}.) 285 \l{context()}.)
286 286
287 \section1 Using QTextEdit as an Editor 287 \section1 Using QTextEdit as an Editor
288 288
289 All the information about using QTextEdit as a display widget also 289 All the information about using QTextEdit as a display widget also
290 applies here. 290 applies here.
291 291
292 The current format's attributes are set with setItalic(), 292 The current format's attributes are set with setItalic(),
293 setBold(), setUnderline(), setFamily() (font family), 293 setBold(), setUnderline(), setFamily() (font family),
294 setPointSize(), setColor() and setCurrentFont(). The current 294 setPointSize(), setColor() and setCurrentFont(). The current
295 paragraph's alignment is set with setAlignment(). 295 paragraph's alignment is set with setAlignment().
296 296
297 Use setSelection() to select text. The setSelectionAttributes() 297 Use setSelection() to select text. The setSelectionAttributes()
298 function is used to indicate how selected text should be 298 function is used to indicate how selected text should be
299 displayed. Use hasSelectedText() to find out if any text is 299 displayed. Use hasSelectedText() to find out if any text is
300 selected. The currently selected text's position is available 300 selected. The currently selected text's position is available
301 using getSelection() and the selected text itself is returned by 301 using getSelection() and the selected text itself is returned by
302 selectedText(). The selection can be copied to the clipboard with 302 selectedText(). The selection can be copied to the clipboard with
303 copy(), or cut to the clipboard with cut(). It can be deleted with 303 copy(), or cut to the clipboard with cut(). It can be deleted with
304 removeSelectedText(). The entire text can be selected (or 304 removeSelectedText(). The entire text can be selected (or
305 unselected) using selectAll(). QTextEdit supports multiple 305 unselected) using selectAll(). QTextEdit supports multiple
306 selections. Most of the selection functions operate on the default 306 selections. Most of the selection functions operate on the default
307 selection, selection 0. If the user presses a non-selecting key, 307 selection, selection 0. If the user presses a non-selecting key,
308 e.g. a cursor key without also holding down Shift, all selections 308 e.g. a cursor key without also holding down Shift, all selections
309 are cleared. 309 are cleared.
310 310
311 Set and get the position of the cursor with setCursorPosition() 311 Set and get the position of the cursor with setCursorPosition()
312 and getCursorPosition() respectively. When the cursor is moved, 312 and getCursorPosition() respectively. When the cursor is moved,
313 the signals currentFontChanged(), currentColorChanged() and 313 the signals currentFontChanged(), currentColorChanged() and
314 currentAlignmentChanged() are emitted to reflect the font, color 314 currentAlignmentChanged() are emitted to reflect the font, color
315 and alignment at the new cursor position. 315 and alignment at the new cursor position.
316 316
317 If the text changes, the textChanged() signal is emitted, and if 317 If the text changes, the textChanged() signal is emitted, and if
318 the user inserts a new line by pressing Return or Enter, 318 the user inserts a new line by pressing Return or Enter,
319 returnPressed() is emitted. The isModified() function will return 319 returnPressed() is emitted. The isModified() function will return
320 TRUE if the text has been modified. 320 TRUE if the text has been modified.
321 321
322 QTextEdit provides command-based undo and redo. To set the depth 322 QTextEdit provides command-based undo and redo. To set the depth
323 of the command history use setUndoDepth() which defaults to 100 323 of the command history use setUndoDepth() which defaults to 100
324 steps. To undo or redo the last operation call undo() or redo(). 324 steps. To undo or redo the last operation call undo() or redo().
325 The signals undoAvailable() and redoAvailable() indicate whether 325 The signals undoAvailable() and redoAvailable() indicate whether
326 the undo and redo operations can be executed. 326 the undo and redo operations can be executed.
327 327
328 The indent() function is used to reindent a paragraph. It is 328 The indent() function is used to reindent a paragraph. It is
329 useful for code editors, for example in <em>Qt Designer</em>'s 329 useful for code editors, for example in <em>Qt Designer</em>'s
330 code editor \e{Ctrl+I} invokes the indent() function. 330 code editor \e{Ctrl+I} invokes the indent() function.
331 331
332 \section2 Editing key bindings 332 \section2 Editing key bindings
333 333
334 The list of key-bindings which are implemented for editing: 334 The list of key-bindings which are implemented for editing:
335 \table 335 \table
336 \header \i Keypresses \i Action 336 \header \i Keypresses \i Action
337 \row \i \e{Backspace} \i Delete the character to the left of the cursor 337 \row \i \e{Backspace} \i Delete the character to the left of the cursor
338 \row \i \e{Delete} \i Delete the character to the right of the cursor 338 \row \i \e{Delete} \i Delete the character to the right of the cursor
339 \row \i \e{Ctrl+A} \i Move the cursor to the beginning of the line 339 \row \i \e{Ctrl+A} \i Move the cursor to the beginning of the line
340 \row \i \e{Ctrl+B} \i Move the cursor one character left 340 \row \i \e{Ctrl+B} \i Move the cursor one character left
341 \row \i \e{Ctrl+C} \i Copy the marked text to the clipboard (also 341 \row \i \e{Ctrl+C} \i Copy the marked text to the clipboard (also
342 \e{Ctrl+Insert} under Windows) 342 \e{Ctrl+Insert} under Windows)
343 \row \i \e{Ctrl+D} \i Delete the character to the right of the cursor 343 \row \i \e{Ctrl+D} \i Delete the character to the right of the cursor
344 \row \i \e{Ctrl+E} \i Move the cursor to the end of the line 344 \row \i \e{Ctrl+E} \i Move the cursor to the end of the line
345 \row \i \e{Ctrl+F} \i Move the cursor one character right 345 \row \i \e{Ctrl+F} \i Move the cursor one character right
346 \row \i \e{Ctrl+H} \i Delete the character to the left of the cursor 346 \row \i \e{Ctrl+H} \i Delete the character to the left of the cursor
347 \row \i \e{Ctrl+K} \i Delete to end of line 347 \row \i \e{Ctrl+K} \i Delete to end of line
348 \row \i \e{Ctrl+N} \i Move the cursor one line down 348 \row \i \e{Ctrl+N} \i Move the cursor one line down
349 \row \i \e{Ctrl+P} \i Move the cursor one line up 349 \row \i \e{Ctrl+P} \i Move the cursor one line up
350 \row \i \e{Ctrl+V} \i Paste the clipboard text into line edit 350 \row \i \e{Ctrl+V} \i Paste the clipboard text into line edit
351 (also \e{Shift+Insert} under Windows) 351 (also \e{Shift+Insert} under Windows)
352 \row \i \e{Ctrl+X} \i Cut the marked text, copy to clipboard 352 \row \i \e{Ctrl+X} \i Cut the marked text, copy to clipboard
353 (also \e{Shift+Delete} under Windows) 353 (also \e{Shift+Delete} under Windows)
354 \row \i \e{Ctrl+Z} \i Undo the last operation 354 \row \i \e{Ctrl+Z} \i Undo the last operation
355 \row \i \e{Ctrl+Y} \i Redo the last operation 355 \row \i \e{Ctrl+Y} \i Redo the last operation
356 \row \i \e{LeftArrow} \i Move the cursor one character left 356 \row \i \e{LeftArrow} \i Move the cursor one character left
357 \row \i \e{Ctrl+LeftArrow} \i Move the cursor one word left 357 \row \i \e{Ctrl+LeftArrow} \i Move the cursor one word left
358 \row \i \e{RightArrow} \i Move the cursor one character right 358 \row \i \e{RightArrow} \i Move the cursor one character right
359 \row \i \e{Ctrl+RightArrow} \i Move the cursor one word right 359 \row \i \e{Ctrl+RightArrow} \i Move the cursor one word right
360 \row \i \e{UpArrow} \i Move the cursor one line up 360 \row \i \e{UpArrow} \i Move the cursor one line up
361 \row \i \e{Ctrl+UpArrow} \i Move the cursor one word up 361 \row \i \e{Ctrl+UpArrow} \i Move the cursor one word up
362 \row \i \e{DownArrow} \i Move the cursor one line down 362 \row \i \e{DownArrow} \i Move the cursor one line down
363 \row \i \e{Ctrl+Down Arrow} \i Move the cursor one word down 363 \row \i \e{Ctrl+Down Arrow} \i Move the cursor one word down
364 \row \i \e{PageUp} \i Move the cursor one page up 364 \row \i \e{PageUp} \i Move the cursor one page up
365 \row \i \e{PageDown} \i Move the cursor one page down 365 \row \i \e{PageDown} \i Move the cursor one page down
366 \row \i \e{Home} \i Move the cursor to the beginning of the line 366 \row \i \e{Home} \i Move the cursor to the beginning of the line
367 \row \i \e{Ctrl+Home} \i Move the cursor to the beginning of the text 367 \row \i \e{Ctrl+Home} \i Move the cursor to the beginning of the text
368 \row \i \e{End} \i Move the cursor to the end of the line 368 \row \i \e{End} \i Move the cursor to the end of the line
369 \row \i \e{Ctrl+End} \i Move the cursor to the end of the text 369 \row \i \e{Ctrl+End} \i Move the cursor to the end of the text
370 \row \i \e{Shift+Wheel} \i Scroll the page horizontally 370 \row \i \e{Shift+Wheel} \i Scroll the page horizontally
371 (the Wheel is the mouse wheel) 371 (the Wheel is the mouse wheel)
372 \row \i \e{Ctrl+Wheel} \i Zoom the text 372 \row \i \e{Ctrl+Wheel} \i Zoom the text
373 \endtable 373 \endtable
374 374
375 To select (mark) text hold down the Shift key whilst pressing one 375 To select (mark) text hold down the Shift key whilst pressing one
376 of the movement keystrokes, for example, <i>Shift+Right Arrow</i> 376 of the movement keystrokes, for example, <i>Shift+Right Arrow</i>
377 will select the character to the right, and <i>Shift+Ctrl+Right 377 will select the character to the right, and <i>Shift+Ctrl+Right
378 Arrow</i> will select the word to the right, etc. 378 Arrow</i> will select the word to the right, etc.
379 379
380 By default the text edit widget operates in insert mode so all 380 By default the text edit widget operates in insert mode so all
381 text that the user enters is inserted into the text edit and any 381 text that the user enters is inserted into the text edit and any
382 text to the right of the cursor is moved out of the way. The mode 382 text to the right of the cursor is moved out of the way. The mode
383 can be changed to overwrite, where new text overwrites any text to 383 can be changed to overwrite, where new text overwrites any text to
384 the right of the cursor, using setOverwriteMode(). 384 the right of the cursor, using setOverwriteMode().
385 385
386*/ 386*/
387 387
388/*! \enum QTextEdit::KeyboardAction 388/*! \enum QTextEdit::KeyboardAction
389 389
390 This enum is used by doKeyboardAction() to specify which action 390 This enum is used by doKeyboardAction() to specify which action
391 should be executed: 391 should be executed:
392 392
393 \value ActionBackspace Delete the character to the left of the 393 \value ActionBackspace Delete the character to the left of the
394 cursor. 394 cursor.
395 395
396 \value ActionDelete Delete the character to the right of the cursor. 396 \value ActionDelete Delete the character to the right of the cursor.
397 397
398 \value ActionReturn Split the paragraph at the cursor position. 398 \value ActionReturn Split the paragraph at the cursor position.
399 399
400 \value ActionKill If the cursor is not at the end of the paragraph, 400 \value ActionKill If the cursor is not at the end of the paragraph,
401 delete the text from the cursor position until the end of the 401 delete the text from the cursor position until the end of the
402 paragraph. If the cursor is at the end of the paragraph, delete the 402 paragraph. If the cursor is at the end of the paragraph, delete the
403 hard line break at the end of the paragraph - this will cause this 403 hard line break at the end of the paragraph - this will cause this
404 paragraph to be joined with the following paragraph. 404 paragraph to be joined with the following paragraph.
405*/ 405*/
406 406
407/*! \enum QTextEdit::VerticalAlignment 407/*! \enum QTextEdit::VerticalAlignment
408 408
409 This enum is used to set the vertical alignment of the text. 409 This enum is used to set the vertical alignment of the text.
410 410
411 \value AlignNormal Normal alignment 411 \value AlignNormal Normal alignment
412 \value AlignSuperScript Superscript 412 \value AlignSuperScript Superscript
413 \value AlignSubScript Subscript 413 \value AlignSubScript Subscript
414*/ 414*/
415 415
416/*! \fn void QTextEdit::copyAvailable (bool yes) 416/*! \fn void QTextEdit::copyAvailable (bool yes)
417 417
418 This signal is emitted when text is selected or de-selected in the text 418 This signal is emitted when text is selected or de-selected in the text
419 edit. 419 edit.
420 420
421 When text is selected this signal will be emitted with \a yes set to 421 When text is selected this signal will be emitted with \a yes set to
422 TRUE. If no text has been selected or if the selected text is 422 TRUE. If no text has been selected or if the selected text is
423 de-selected this signal is emitted with \a yes set to FALSE. 423 de-selected this signal is emitted with \a yes set to FALSE.
424 424
425 If \a yes is TRUE then copy() can be used to copy the selection to the 425 If \a yes is TRUE then copy() can be used to copy the selection to the
426 clipboard. If \a yes is FALSE then copy() does nothing. 426 clipboard. If \a yes is FALSE then copy() does nothing.
427 427
428 \sa selectionChanged() 428 \sa selectionChanged()
429*/ 429*/
430 430
431 431
432/*! \fn void QTextEdit::textChanged() 432/*! \fn void QTextEdit::textChanged()
433 433
434 This signal is emitted whenever the text in the text edit changes. 434 This signal is emitted whenever the text in the text edit changes.
435 435
436 \sa setText() append() 436 \sa setText() append()
437 */ 437 */
438 438
439/*! \fn void QTextEdit::selectionChanged() 439/*! \fn void QTextEdit::selectionChanged()
440 440
441 This signal is emitted whenever the selection changes. 441 This signal is emitted whenever the selection changes.
442 442
443 \sa setSelection() copyAvailable() 443 \sa setSelection() copyAvailable()
444*/ 444*/
445 445
446/*! \fn QTextDocument *QTextEdit::document() const 446/*! \fn QTextDocument *QTextEdit::document() const
447 447
448 \internal 448 \internal
449 449
450 This function returns the QTextDocument which is used by the text 450 This function returns the QTextDocument which is used by the text
451 edit. 451 edit.
452*/ 452*/
453 453
454/*! \fn void QTextEdit::setDocument( QTextDocument *doc ) 454/*! \fn void QTextEdit::setDocument( QTextDocument *doc )
455 455
456 \internal 456 \internal
457 457
458 This function sets the QTextDocument which should be used by the text 458 This function sets the QTextDocument which should be used by the text
459 edit to \a doc. This can be used, for example, if you want to 459 edit to \a doc. This can be used, for example, if you want to
460 display a document using multiple views. You would create a 460 display a document using multiple views. You would create a
461 QTextDocument and set it to the text edits which should display it. 461 QTextDocument and set it to the text edits which should display it.
462 You would need to connect to the textChanged() and 462 You would need to connect to the textChanged() and
463 selectionChanged() signals of all the text edits and update them all 463 selectionChanged() signals of all the text edits and update them all
464 accordingly (preferably with a slight delay for efficiency reasons). 464 accordingly (preferably with a slight delay for efficiency reasons).
465*/ 465*/
466 466
467/*! \enum QTextEdit::CursorAction 467/*! \enum QTextEdit::CursorAction
468 468
469 This enum is used by moveCursor() to specify in which direction 469 This enum is used by moveCursor() to specify in which direction
470 the cursor should be moved: 470 the cursor should be moved:
471 471
472 \value MoveBackward Moves the cursor one character backward 472 \value MoveBackward Moves the cursor one character backward
473 473
474 \value MoveWordBackward Moves the cursor one word backward 474 \value MoveWordBackward Moves the cursor one word backward
475 475
476 \value MoveForward Moves the cursor one character forward 476 \value MoveForward Moves the cursor one character forward
477 477
478 \value MoveWordForward Moves the cursor one word forward 478 \value MoveWordForward Moves the cursor one word forward
479 479
480 \value MoveUp Moves the cursor up one line 480 \value MoveUp Moves the cursor up one line
481 481
482 \value MoveDown Moves the cursor down one line 482 \value MoveDown Moves the cursor down one line
483 483
484 \value MoveLineStart Moves the cursor to the beginning of the line 484 \value MoveLineStart Moves the cursor to the beginning of the line
485 485
486 \value MoveLineEnd Moves the cursor to the end of the line 486 \value MoveLineEnd Moves the cursor to the end of the line
487 487
488 \value MoveHome Moves the cursor to the beginning of the document 488 \value MoveHome Moves the cursor to the beginning of the document
489 489
490 \value MoveEnd Moves the cursor to the end of the document 490 \value MoveEnd Moves the cursor to the end of the document
491 491
492 \value MovePgUp Moves the cursor one page up 492 \value MovePgUp Moves the cursor one page up
493 493
494 \value MovePgDown Moves the cursor one page down 494 \value MovePgDown Moves the cursor one page down
495*/ 495*/
496 496
497 497
498/*! 498/*!
499 \property QTextEdit::overwriteMode 499 \property QTextEdit::overwriteMode
500 \brief the text edit's overwrite mode 500 \brief the text edit's overwrite mode
501 501
502 If FALSE (the default) characters entered by the user are inserted 502 If FALSE (the default) characters entered by the user are inserted
503 with any characters to the right being moved out of the way. 503 with any characters to the right being moved out of the way.
504 If TRUE, the editor is in overwrite mode, i.e. characters entered by 504 If TRUE, the editor is in overwrite mode, i.e. characters entered by
505 the user overwrite any characters to the right of the cursor position. 505 the user overwrite any characters to the right of the cursor position.
506*/ 506*/
507 507
508/*! \fn void QTextEdit::setCurrentFont( const QFont &f ) 508/*! \fn void QTextEdit::setCurrentFont( const QFont &f )
509 509
510 Sets the font of the current format to \a f. 510 Sets the font of the current format to \a f.
511 511
512 \sa font() setPointSize() setFamily() 512 \sa font() setPointSize() setFamily()
513*/ 513*/
514 514
515/*! 515/*!
516 \property QTextEdit::undoDepth 516 \property QTextEdit::undoDepth
517 \brief the depth of the undo history 517 \brief the depth of the undo history
518 518
519 The maximum number of steps in the undo/redo history. 519 The maximum number of steps in the undo/redo history.
520 The default is 100. 520 The default is 100.
521 521
522 \sa undo() redo() 522 \sa undo() redo()
523*/ 523*/
524 524
525/*! \fn void QTextEdit::undoAvailable( bool yes ) 525/*! \fn void QTextEdit::undoAvailable( bool yes )
526 526
527 This signal is emitted when the availability of undo changes. If \a 527 This signal is emitted when the availability of undo changes. If \a
528 yes is TRUE, then undo() will work until undoAvailable( FALSE ) is 528 yes is TRUE, then undo() will work until undoAvailable( FALSE ) is
529 next emitted. 529 next emitted.
530 530
531 \sa undo() undoDepth() 531 \sa undo() undoDepth()
532*/ 532*/
533 533
534/*! \fn void QTextEdit::modificationChanged( bool m ) 534/*! \fn void QTextEdit::modificationChanged( bool m )
535 535
536 This signal is emitted when the modification of the document 536 This signal is emitted when the modification of the document
537 changed. If \a m is TRUE, the document was modified, otherwise the 537 changed. If \a m is TRUE, the document was modified, otherwise the
538 modification state has been reset to unmodified. 538 modification state has been reset to unmodified.
539 539
540 \sa modified 540 \sa modified
541*/ 541*/
542 542
543/*! \fn void QTextEdit::redoAvailable( bool yes ) 543/*! \fn void QTextEdit::redoAvailable( bool yes )
544 544
545 This signal is emitted when the availability of redo changes. If \a 545 This signal is emitted when the availability of redo changes. If \a
546 yes is TRUE, then redo() will work until redoAvailable( FALSE ) is 546 yes is TRUE, then redo() will work until redoAvailable( FALSE ) is
547 next emitted. 547 next emitted.
548 548
549 \sa redo() undoDepth() 549 \sa redo() undoDepth()
550*/ 550*/
551 551
552/*! \fn void QTextEdit::currentFontChanged( const QFont &f ) 552/*! \fn void QTextEdit::currentFontChanged( const QFont &f )
553 553
554 This signal is emitted if the font of the current format has changed. 554 This signal is emitted if the font of the current format has changed.
555 555
556 The new font is \a f. 556 The new font is \a f.
557 557
558 \sa setCurrentFont() 558 \sa setCurrentFont()
559*/ 559*/
560 560
561/*! \fn void QTextEdit::currentColorChanged( const QColor &c ) 561/*! \fn void QTextEdit::currentColorChanged( const QColor &c )
562 562
563 This signal is emitted if the color of the current format has changed. 563 This signal is emitted if the color of the current format has changed.
564 564
565 The new color is \a c. 565 The new color is \a c.
566 566
567 \sa setColor() 567 \sa setColor()
568*/ 568*/
569 569
570/*! \fn void QTextEdit::currentVerticalAlignmentChanged( VerticalAlignment a ) 570/*! \fn void QTextEdit::currentVerticalAlignmentChanged( VerticalAlignment a )
571 571
572 This signal is emitted if the vertical alignment of the current 572 This signal is emitted if the vertical alignment of the current
573 format has changed. 573 format has changed.
574 574
575 The new vertical alignment is \a a. 575 The new vertical alignment is \a a.
576 576
577 \sa setVerticalAlignment() 577 \sa setVerticalAlignment()
578*/ 578*/
579 579
580/*! \fn void QTextEdit::currentAlignmentChanged( int a ) 580/*! \fn void QTextEdit::currentAlignmentChanged( int a )
581 581
582 This signal is emitted if the alignment of the current paragraph 582 This signal is emitted if the alignment of the current paragraph
583 has changed. 583 has changed.
584 584
585 The new alignment is \a a. 585 The new alignment is \a a.
586 586
587 \sa setAlignment() 587 \sa setAlignment()
588*/ 588*/
589 589
590/*! \fn void QTextEdit::cursorPositionChanged( QTextCursor *c ) 590/*! \fn void QTextEdit::cursorPositionChanged( QTextCursor *c )
591 591
592 This signal is emitted if the position of the cursor changed. \a c 592 This signal is emitted if the position of the cursor changed. \a c
593 points to the text cursor object. 593 points to the text cursor object.
594 594
595 \sa setCursorPosition() 595 \sa setCursorPosition()
596*/ 596*/
597 597
598/*! \overload void QTextEdit::cursorPositionChanged( int para, int pos ) 598/*! \overload void QTextEdit::cursorPositionChanged( int para, int pos )
599 599
600 This signal is emitted if the position of the cursor changed. \a 600 This signal is emitted if the position of the cursor changed. \a
601 para contains the paragraph index and \a pos contains the character 601 para contains the paragraph index and \a pos contains the character
602 position within the paragraph. 602 position within the paragraph.
603 603
604 \sa setCursorPosition() 604 \sa setCursorPosition()
605*/ 605*/
606 606
607/*! \fn void QTextEdit::returnPressed() 607/*! \fn void QTextEdit::returnPressed()
608 608
609 This signal is emitted if the user pressed the Return or the Enter key. 609 This signal is emitted if the user pressed the Return or the Enter key.
610*/ 610*/
611 611
612/*! 612/*!
613 \fn QTextCursor *QTextEdit::textCursor() const 613 \fn QTextCursor *QTextEdit::textCursor() const
614 614
615 Returns the text edit's text cursor. 615 Returns the text edit's text cursor.
616 616
617 \warning QTextCursor is not in the public API, but in special 617 \warning QTextCursor is not in the public API, but in special
618 circumstances you might wish to use it. 618 circumstances you might wish to use it.
619*/ 619*/
620 620
621/*! Constructs an empty QTextEdit with parent \a parent and name \a 621/*! Constructs an empty QTextEdit with parent \a parent and name \a
622 name. 622 name.
623*/ 623*/
624 624
625QTextEdit::QTextEdit( QWidget *parent, const char *name ) 625QTextEdit::QTextEdit( QWidget *parent, const char *name )
626 : QScrollView( parent, name, WStaticContents | WRepaintNoErase | WResizeNoErase ), 626 : QScrollView( parent, name, WStaticContents | WRepaintNoErase | WResizeNoErase ),
627 doc( new QTextDocument( 0 ) ), undoRedoInfo( doc ) 627 doc( new QTextDocument( 0 ) ), undoRedoInfo( doc )
628{ 628{
629 init(); 629 init();
630} 630}
631 631
632/*! 632/*!
633 Constructs a QTextEdit with parent \a parent and name \a name. The 633 Constructs a QTextEdit with parent \a parent and name \a name. The
634 text edit will display the text \a text using context \a context. 634 text edit will display the text \a text using context \a context.
635 635
636 The \a context is a path which the text edit's QMimeSourceFactory 636 The \a context is a path which the text edit's QMimeSourceFactory
637 uses to resolve the locations of files and images. It is passed to 637 uses to resolve the locations of files and images. It is passed to
638 the mimeSourceFactory() when quering data. 638 the mimeSourceFactory() when quering data.
639 639
640 For example if the text contains an image tag, 640 For example if the text contains an image tag,
641 \c{<img src="image.png">}, and the context is "path/to/look/in", the 641 \c{<img src="image.png">}, and the context is "path/to/look/in", the
642 QMimeSourceFactory will try to load the image from 642 QMimeSourceFactory will try to load the image from
643 "path/to/look/in/image.png". If the tag was 643 "path/to/look/in/image.png". If the tag was
644 \c{<img src="/image.png">}, the context will not be used (because 644 \c{<img src="/image.png">}, the context will not be used (because
645 QMimeSourceFactory recognizes that we have used an absolute path) 645 QMimeSourceFactory recognizes that we have used an absolute path)
646 and will try to load "/image.png". The context is applied in exactly 646 and will try to load "/image.png". The context is applied in exactly
647 the same way to \e hrefs, for example, 647 the same way to \e hrefs, for example,
648 \c{<a href="target.html">Target</a>}, would resolve to 648 \c{<a href="target.html">Target</a>}, would resolve to
649 "path/to/look/in/target.html". 649 "path/to/look/in/target.html".
650 650
651*/ 651*/
652 652
653QTextEdit::QTextEdit( const QString& text, const QString& context, 653QTextEdit::QTextEdit( const QString& text, const QString& context,
654 QWidget *parent, const char *name) 654 QWidget *parent, const char *name)
655 : QScrollView( parent, name, WStaticContents | WRepaintNoErase | WResizeNoErase ), 655 : QScrollView( parent, name, WStaticContents | WRepaintNoErase | WResizeNoErase ),
656 doc( new QTextDocument( 0 ) ), undoRedoInfo( doc ) 656 doc( new QTextDocument( 0 ) ), undoRedoInfo( doc )
657{ 657{
658 init(); 658 init();
659 setText( text, context ); 659 setText( text, context );
660} 660}
661 661
662/*! \reimp */ 662/*! \reimp */
663 663
664QTextEdit::~QTextEdit() 664QTextEdit::~QTextEdit()
665{ 665{
666 delete undoRedoInfo.d; 666 delete undoRedoInfo.d;
667 undoRedoInfo.d = 0; 667 undoRedoInfo.d = 0;
668 delete cursor; 668 delete cursor;
669 delete doc; 669 delete doc;
670 delete d; 670 delete d;
671} 671}
672 672
673void QTextEdit::init() 673void QTextEdit::init()
674{ 674{
675 setFrameStyle( Sunken ); 675 setFrameStyle( Sunken );
676 undoEnabled = TRUE; 676 undoEnabled = TRUE;
677 readonly = TRUE; 677 readonly = TRUE;
678 setReadOnly( FALSE ); 678 setReadOnly( FALSE );
679 d = new QTextEditPrivate; 679 d = new QTextEditPrivate;
680 connect( doc, SIGNAL( minimumWidthChanged( int ) ), 680 connect( doc, SIGNAL( minimumWidthChanged(int) ),
681 this, SLOT( documentWidthChanged( int ) ) ); 681 this, SLOT( documentWidthChanged(int) ) );
682 682
683 mousePressed = FALSE; 683 mousePressed = FALSE;
684 inDoubleClick = FALSE; 684 inDoubleClick = FALSE;
685 modified = FALSE; 685 modified = FALSE;
686 onLink = QString::null; 686 onLink = QString::null;
687 overWrite = FALSE; 687 overWrite = FALSE;
688 wrapMode = WidgetWidth; 688 wrapMode = WidgetWidth;
689 wrapWidth = -1; 689 wrapWidth = -1;
690 wPolicy = AtWhiteSpace; 690 wPolicy = AtWhiteSpace;
691 inDnD = FALSE; 691 inDnD = FALSE;
692 692
693 doc->setFormatter( new QTextFormatterBreakWords ); 693 doc->setFormatter( new QTextFormatterBreakWords );
694 doc->formatCollection()->defaultFormat()->setFont( QScrollView::font() ); 694 doc->formatCollection()->defaultFormat()->setFont( QScrollView::font() );
695 doc->formatCollection()->defaultFormat()->setColor( colorGroup().color( QColorGroup::Text ) ); 695 doc->formatCollection()->defaultFormat()->setColor( colorGroup().color( QColorGroup::Text ) );
696 currentFormat = doc->formatCollection()->defaultFormat(); 696 currentFormat = doc->formatCollection()->defaultFormat();
697 currentAlignment = Qt3::AlignAuto; 697 currentAlignment = Qt3::AlignAuto;
698 698
699 viewport()->setBackgroundMode( PaletteBase ); 699 viewport()->setBackgroundMode( PaletteBase );
700 viewport()->setAcceptDrops( TRUE ); 700 viewport()->setAcceptDrops( TRUE );
701 resizeContents( 0, doc->lastParagraph() ? 701 resizeContents( 0, doc->lastParagraph() ?
702 ( doc->lastParagraph()->paragId() + 1 ) * doc->formatCollection()->defaultFormat()->height() : 0 ); 702 ( doc->lastParagraph()->paragId() + 1 ) * doc->formatCollection()->defaultFormat()->height() : 0 );
703 703
704 setKeyCompression( TRUE ); 704 setKeyCompression( TRUE );
705 viewport()->setMouseTracking( TRUE ); 705 viewport()->setMouseTracking( TRUE );
706#ifndef QT_NO_CURSOR 706#ifndef QT_NO_CURSOR
707 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 707 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
708#endif 708#endif
709 cursor = new QTextCursor( doc ); 709 cursor = new QTextCursor( doc );
710 710
711 formatTimer = new QTimer( this ); 711 formatTimer = new QTimer( this );
712 connect( formatTimer, SIGNAL( timeout() ), 712 connect( formatTimer, SIGNAL( timeout() ),
713 this, SLOT( formatMore() ) ); 713 this, SLOT( formatMore() ) );
714 lastFormatted = doc->firstParagraph(); 714 lastFormatted = doc->firstParagraph();
715 715
716 scrollTimer = new QTimer( this ); 716 scrollTimer = new QTimer( this );
717 connect( scrollTimer, SIGNAL( timeout() ), 717 connect( scrollTimer, SIGNAL( timeout() ),
718 this, SLOT( autoScrollTimerDone() ) ); 718 this, SLOT( autoScrollTimerDone() ) );
719 719
720 interval = 0; 720 interval = 0;
721 changeIntervalTimer = new QTimer( this ); 721 changeIntervalTimer = new QTimer( this );
722 connect( changeIntervalTimer, SIGNAL( timeout() ), 722 connect( changeIntervalTimer, SIGNAL( timeout() ),
723 this, SLOT( doChangeInterval() ) ); 723 this, SLOT( doChangeInterval() ) );
724 724
725 cursorVisible = TRUE; 725 cursorVisible = TRUE;
726 blinkTimer = new QTimer( this ); 726 blinkTimer = new QTimer( this );
727 connect( blinkTimer, SIGNAL( timeout() ), 727 connect( blinkTimer, SIGNAL( timeout() ),
728 this, SLOT( blinkCursor() ) ); 728 this, SLOT( blinkCursor() ) );
729 729
730#ifndef QT_NO_DRAGANDDROP 730#ifndef QT_NO_DRAGANDDROP
731 dragStartTimer = new QTimer( this ); 731 dragStartTimer = new QTimer( this );
732 connect( dragStartTimer, SIGNAL( timeout() ), 732 connect( dragStartTimer, SIGNAL( timeout() ),
733 this, SLOT( startDrag() ) ); 733 this, SLOT( startDrag() ) );
734#endif 734#endif
735 735
736 736
737 formatMore(); 737 formatMore();
738 738
739 blinkCursorVisible = FALSE; 739 blinkCursorVisible = FALSE;
740 740
741 viewport()->setFocusProxy( this ); 741 viewport()->setFocusProxy( this );
742 viewport()->setFocusPolicy( WheelFocus ); 742 viewport()->setFocusPolicy( WheelFocus );
743 viewport()->installEventFilter( this ); 743 viewport()->installEventFilter( this );
744 installEventFilter( this ); 744 installEventFilter( this );
745} 745}
746 746
747void QTextEdit::paintDocument( bool drawAll, QPainter *p, int cx, int cy, int cw, int ch ) 747void QTextEdit::paintDocument( bool drawAll, QPainter *p, int cx, int cy, int cw, int ch )
748{ 748{
749 bool drawCur = hasFocus() || viewport()->hasFocus(); 749 bool drawCur = hasFocus() || viewport()->hasFocus();
750 if ( hasSelectedText() || isReadOnly() || !cursorVisible ) 750 if ( hasSelectedText() || isReadOnly() || !cursorVisible )
751 drawCur = FALSE; 751 drawCur = FALSE;
752 QColorGroup g = colorGroup(); 752 QColorGroup g = colorGroup();
753 if ( doc->paper() ) 753 if ( doc->paper() )
754 g.setBrush( QColorGroup::Base, *doc->paper() ); 754 g.setBrush( QColorGroup::Base, *doc->paper() );
755 755
756 if ( contentsY() < doc->y() ) { 756 if ( contentsY() < doc->y() ) {
757 p->fillRect( contentsX(), contentsY(), visibleWidth(), doc->y(), 757 p->fillRect( contentsX(), contentsY(), visibleWidth(), doc->y(),
758 g.brush( QColorGroup::Base ) ); 758 g.brush( QColorGroup::Base ) );
759 } 759 }
760 if ( drawAll && doc->width() - contentsX() < cx + cw ) { 760 if ( drawAll && doc->width() - contentsX() < cx + cw ) {
761 p->fillRect( doc->width() - contentsX(), cy, cx + cw - doc->width() + contentsX(), ch, 761 p->fillRect( doc->width() - contentsX(), cy, cx + cw - doc->width() + contentsX(), ch,
762 g.brush( QColorGroup::Base ) ); 762 g.brush( QColorGroup::Base ) );
763 } 763 }
764 764
765 p->setBrushOrigin( -contentsX(), -contentsY() ); 765 p->setBrushOrigin( -contentsX(), -contentsY() );
766 766
767 lastFormatted = doc->draw( p, cx, cy, cw, ch, g, !drawAll, drawCur, cursor ); 767 lastFormatted = doc->draw( p, cx, cy, cw, ch, g, !drawAll, drawCur, cursor );
768 768
769 if ( lastFormatted == doc->lastParagraph() ) 769 if ( lastFormatted == doc->lastParagraph() )
770 resizeContents( contentsWidth(), doc->height() ); 770 resizeContents( contentsWidth(), doc->height() );
771 771
772 if ( contentsHeight() < visibleHeight() && ( !doc->lastParagraph() || doc->lastParagraph()->isValid() ) && drawAll ) 772 if ( contentsHeight() < visibleHeight() && ( !doc->lastParagraph() || doc->lastParagraph()->isValid() ) && drawAll )
773 p->fillRect( 0, contentsHeight(), visibleWidth(), 773 p->fillRect( 0, contentsHeight(), visibleWidth(),
774 visibleHeight() - contentsHeight(), g.brush( QColorGroup::Base ) ); 774 visibleHeight() - contentsHeight(), g.brush( QColorGroup::Base ) );
775} 775}
776 776
777/*! \reimp */ 777/*! \reimp */
778 778
779void QTextEdit::drawContents( QPainter *p, int cx, int cy, int cw, int ch ) 779void QTextEdit::drawContents( QPainter *p, int cx, int cy, int cw, int ch )
780{ 780{
781 paintDocument( TRUE, p, cx, cy, cw, ch ); 781 paintDocument( TRUE, p, cx, cy, cw, ch );
782 int v; 782 int v;
783 p->setPen( foregroundColor() ); 783 p->setPen( foregroundColor() );
784 if ( document()->isPageBreakEnabled() && ( v = document()->flow()->pageSize() ) > 0 ) { 784 if ( document()->isPageBreakEnabled() && ( v = document()->flow()->pageSize() ) > 0 ) {
785 int l = int(cy / v) * v; 785 int l = int(cy / v) * v;
786 while ( l < cy + ch ) { 786 while ( l < cy + ch ) {
787 p->drawLine( cx, l, cx + cw - 1, l ); 787 p->drawLine( cx, l, cx + cw - 1, l );
788 l += v; 788 l += v;
789 } 789 }
790 } 790 }
791 791
792} 792}
793 793
794/*! \reimp */ 794/*! \reimp */
795 795
796void QTextEdit::drawContents( QPainter * ) 796void QTextEdit::drawContents( QPainter * )
797{ 797{
798} 798}
799 799
800/*! \reimp */ 800/*! \reimp */
801 801
802bool QTextEdit::event( QEvent *e ) 802bool QTextEdit::event( QEvent *e )
803{ 803{
804 if ( e->type() == QEvent::AccelOverride && !isReadOnly() ) { 804 if ( e->type() == QEvent::AccelOverride && !isReadOnly() ) {
805 QKeyEvent* ke = (QKeyEvent*) e; 805 QKeyEvent* ke = (QKeyEvent*) e;
806 if ( ke->state() == NoButton || ke->state() == Keypad ) { 806 if ( ke->state() == NoButton || ke->state() == Keypad ) {
807 if ( ke->key() < Key_Escape ) { 807 if ( ke->key() < Key_Escape ) {
808 ke->accept(); 808 ke->accept();
809 } else { 809 } else {
810 switch ( ke->key() ) { 810 switch ( ke->key() ) {
811 case Key_Return: 811 case Key_Return:
812 case Key_Enter: 812 case Key_Enter:
813 case Key_Delete: 813 case Key_Delete:
814 case Key_Home: 814 case Key_Home:
815 case Key_End: 815 case Key_End:
816 case Key_Backspace: 816 case Key_Backspace:
817 ke->accept(); 817 ke->accept();
818 default: 818 default:
819 break; 819 break;
820 } 820 }
821 } 821 }
822 } else if ( ke->state() & ControlButton ) { 822 } else if ( ke->state() & ControlButton ) {
823 switch ( ke->key() ) { 823 switch ( ke->key() ) {
824// Those are too frequently used for application functionality 824// Those are too frequently used for application functionality
825 /* case Key_A: 825 /* case Key_A:
826 case Key_B: 826 case Key_B:
827 case Key_D: 827 case Key_D:
828 case Key_E: 828 case Key_E:
829 case Key_F: 829 case Key_F:
830 case Key_H: 830 case Key_H:
831 case Key_I: 831 case Key_I:
832 case Key_K: 832 case Key_K:
833 case Key_N: 833 case Key_N:
834 case Key_P: 834 case Key_P:
835 case Key_T: 835 case Key_T:
836*/ 836*/
837 case Key_C: 837 case Key_C:
838 case Key_V: 838 case Key_V:
839 case Key_X: 839 case Key_X:
840 case Key_Y: 840 case Key_Y:
841 case Key_Z: 841 case Key_Z:
842 case Key_Left: 842 case Key_Left:
843 case Key_Right: 843 case Key_Right:
844 case Key_Up: 844 case Key_Up:
845 case Key_Down: 845 case Key_Down:
846 case Key_Home: 846 case Key_Home:
847 case Key_End: 847 case Key_End:
848 case Key_Tab: 848 case Key_Tab:
849#if defined (Q_WS_WIN) 849#if defined (Q_WS_WIN)
850 case Key_Insert: 850 case Key_Insert:
851 case Key_Delete: 851 case Key_Delete:
852#endif 852#endif
853 ke->accept(); 853 ke->accept();
854 default: 854 default:
855 break; 855 break;
856 } 856 }
857 } else { 857 } else {
858 switch ( ke->key() ) { 858 switch ( ke->key() ) {
859#if defined (Q_WS_WIN) 859#if defined (Q_WS_WIN)
860 case Key_Insert: 860 case Key_Insert:
861 ke->accept(); 861 ke->accept();
862#endif 862#endif
863 default: 863 default:
864 break; 864 break;
865 } 865 }
866 } 866 }
867 } 867 }
868 868
869 if ( e->type() == QEvent::Show ) { 869 if ( e->type() == QEvent::Show ) {
870 if ( d->ensureCursorVisibleInShowEvent ) { 870 if ( d->ensureCursorVisibleInShowEvent ) {
871 sync(); 871 sync();
872 ensureCursorVisible(); 872 ensureCursorVisible();
873 d->ensureCursorVisibleInShowEvent = FALSE; 873 d->ensureCursorVisibleInShowEvent = FALSE;
874 } 874 }
875 if ( !d->scrollToAnchor.isEmpty() ) { 875 if ( !d->scrollToAnchor.isEmpty() ) {
876 scrollToAnchor( d->scrollToAnchor ); 876 scrollToAnchor( d->scrollToAnchor );
877 d->scrollToAnchor = QString::null; 877 d->scrollToAnchor = QString::null;
878 } 878 }
879 } 879 }
880 return QWidget::event( e ); 880 return QWidget::event( e );
881} 881}
882 882
883/*! 883/*!
884 Processes the key event, \a e. 884 Processes the key event, \a e.
885 By default key events are used to provide keyboard navigation and 885 By default key events are used to provide keyboard navigation and
886 text editing. 886 text editing.
887*/ 887*/
888 888
889void QTextEdit::keyPressEvent( QKeyEvent *e ) 889void QTextEdit::keyPressEvent( QKeyEvent *e )
890{ 890{
891 changeIntervalTimer->stop(); 891 changeIntervalTimer->stop();
892 interval = 10; 892 interval = 10;
893 bool unknown = FALSE; 893 bool unknown = FALSE;
894 if ( isReadOnly() ) { 894 if ( isReadOnly() ) {
895 if ( !handleReadOnlyKeyEvent( e ) ) 895 if ( !handleReadOnlyKeyEvent( e ) )
896 QScrollView::keyPressEvent( e ); 896 QScrollView::keyPressEvent( e );
897 changeIntervalTimer->start( 100, TRUE ); 897 changeIntervalTimer->start( 100, TRUE );
898 return; 898 return;
899 } 899 }
900 900
901 901
902 bool selChanged = FALSE; 902 bool selChanged = FALSE;
903 for ( int i = 1; i < doc->numSelections(); ++i ) // start with 1 as we don't want to remove the Standard-Selection 903 for ( int i = 1; i < doc->numSelections(); ++i ) // start with 1 as we don't want to remove the Standard-Selection
904 selChanged = doc->removeSelection( i ) || selChanged; 904 selChanged = doc->removeSelection( i ) || selChanged;
905 905
906 if ( selChanged ) { 906 if ( selChanged ) {
907 cursor->paragraph()->document()->nextDoubleBuffered = TRUE; 907 cursor->paragraph()->document()->nextDoubleBuffered = TRUE;
908 repaintChanged(); 908 repaintChanged();
909 } 909 }
910 910
911 bool clearUndoRedoInfo = TRUE; 911 bool clearUndoRedoInfo = TRUE;
912 912
913 913
914 switch ( e->key() ) { 914 switch ( e->key() ) {
915 case Key_Left: 915 case Key_Left:
916 case Key_Right: { 916 case Key_Right: {
917 // a bit hacky, but can't change this without introducing new enum values for move and keeping the 917 // a bit hacky, but can't change this without introducing new enum values for move and keeping the
918 // correct semantics and movement for BiDi and non BiDi text. 918 // correct semantics and movement for BiDi and non BiDi text.
919 CursorAction a; 919 CursorAction a;
920 if ( cursor->paragraph()->string()->isRightToLeft() == (e->key() == Key_Right) ) 920 if ( cursor->paragraph()->string()->isRightToLeft() == (e->key() == Key_Right) )
921 a = e->state() & ControlButton ? MoveWordBackward : MoveBackward; 921 a = e->state() & ControlButton ? MoveWordBackward : MoveBackward;
922 else 922 else
923 a = e->state() & ControlButton ? MoveWordForward : MoveForward; 923 a = e->state() & ControlButton ? MoveWordForward : MoveForward;
924 moveCursor( a, e->state() & ShiftButton ); 924 moveCursor( a, e->state() & ShiftButton );
925 break; 925 break;
926 } 926 }
927 case Key_Up: 927 case Key_Up:
928 moveCursor( e->state() & ControlButton ? MovePgUp : MoveUp, e->state() & ShiftButton ); 928 moveCursor( e->state() & ControlButton ? MovePgUp : MoveUp, e->state() & ShiftButton );
929 break; 929 break;
930 case Key_Down: 930 case Key_Down:
931 moveCursor( e->state() & ControlButton ? MovePgDown : MoveDown, e->state() & ShiftButton ); 931 moveCursor( e->state() & ControlButton ? MovePgDown : MoveDown, e->state() & ShiftButton );
932 break; 932 break;
933 case Key_Home: 933 case Key_Home:
934 moveCursor( e->state() & ControlButton ? MoveHome : MoveLineStart, e->state() & ShiftButton ); 934 moveCursor( e->state() & ControlButton ? MoveHome : MoveLineStart, e->state() & ShiftButton );
935 break; 935 break;
936 case Key_End: 936 case Key_End:
937 moveCursor( e->state() & ControlButton ? MoveEnd : MoveLineEnd, e->state() & ShiftButton ); 937 moveCursor( e->state() & ControlButton ? MoveEnd : MoveLineEnd, e->state() & ShiftButton );
938 break; 938 break;
939 case Key_Prior: 939 case Key_Prior:
940 moveCursor( MovePgUp, e->state() & ShiftButton ); 940 moveCursor( MovePgUp, e->state() & ShiftButton );
941 break; 941 break;
942 case Key_Next: 942 case Key_Next:
943 moveCursor( MovePgDown, e->state() & ShiftButton ); 943 moveCursor( MovePgDown, e->state() & ShiftButton );
944 break; 944 break;
945 case Key_Return: case Key_Enter: 945 case Key_Return: case Key_Enter:
946 if ( doc->hasSelection( QTextDocument::Standard, FALSE ) ) 946 if ( doc->hasSelection( QTextDocument::Standard, FALSE ) )
947 removeSelectedText(); 947 removeSelectedText();
948 if ( textFormat() == Qt::RichText && ( e->state() & ControlButton ) ) { 948 if ( textFormat() == Qt::RichText && ( e->state() & ControlButton ) ) {
949 // Ctrl-Enter inserts a line break in rich text mode 949 // Ctrl-Enter inserts a line break in rich text mode
950 insert( QString( QChar( 0x2028) ), TRUE, FALSE, TRUE ); 950 insert( QString( QChar( 0x2028) ), TRUE, FALSE, TRUE );
951 } else { 951 } else {
952#ifndef QT_NO_CURSOR 952#ifndef QT_NO_CURSOR
953 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 953 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
954#endif 954#endif
955 clearUndoRedoInfo = FALSE; 955 clearUndoRedoInfo = FALSE;
956 doKeyboardAction( ActionReturn ); 956 doKeyboardAction( ActionReturn );
957 emit returnPressed(); 957 emit returnPressed();
958 } 958 }
959 break; 959 break;
960 case Key_Delete: 960 case Key_Delete:
961#if defined (Q_WS_WIN) 961#if defined (Q_WS_WIN)
962 if ( e->state() & ShiftButton ) { 962 if ( e->state() & ShiftButton ) {
963 cut(); 963 cut();
964 break; 964 break;
965 } else 965 } else
966#endif 966#endif
967 if ( doc->hasSelection( QTextDocument::Standard, TRUE ) ) { 967 if ( doc->hasSelection( QTextDocument::Standard, TRUE ) ) {
968 removeSelectedText(); 968 removeSelectedText();
969 break; 969 break;
970 } 970 }
971 doKeyboardAction( ActionDelete ); 971 doKeyboardAction( ActionDelete );
972 clearUndoRedoInfo = FALSE; 972 clearUndoRedoInfo = FALSE;
973 973
974 break; 974 break;
975 case Key_Insert: 975 case Key_Insert:
976 if ( e->state() & ShiftButton ) 976 if ( e->state() & ShiftButton )
977 paste(); 977 paste();
978#if defined (Q_WS_WIN) 978#if defined (Q_WS_WIN)
979 else if ( e->state() & ControlButton ) 979 else if ( e->state() & ControlButton )
980 copy(); 980 copy();
981#endif 981#endif
982 break; 982 break;
983 case Key_Backspace: 983 case Key_Backspace:
984 if ( doc->hasSelection( QTextDocument::Standard, TRUE ) ) { 984 if ( doc->hasSelection( QTextDocument::Standard, TRUE ) ) {
985 removeSelectedText(); 985 removeSelectedText();
986 break; 986 break;
987 } 987 }
988 988
989 doKeyboardAction( ActionBackspace ); 989 doKeyboardAction( ActionBackspace );
990 clearUndoRedoInfo = FALSE; 990 clearUndoRedoInfo = FALSE;
991 991
992 break; 992 break;
993 case Key_F16: // Copy key on Sun keyboards 993 case Key_F16: // Copy key on Sun keyboards
994 copy(); 994 copy();
995 break; 995 break;
996 case Key_F18: // Paste key on Sun keyboards 996 case Key_F18: // Paste key on Sun keyboards
997 paste(); 997 paste();
998 break; 998 break;
999 case Key_F20: // Cut key on Sun keyboards 999 case Key_F20: // Cut key on Sun keyboards
1000 cut(); 1000 cut();
1001 break; 1001 break;
1002 default: { 1002 default: {
1003 if ( e->text().length() && 1003 if ( e->text().length() &&
1004 ( !( e->state() & ControlButton ) && 1004 ( !( e->state() & ControlButton ) &&
1005 !( e->state() & AltButton ) || 1005 !( e->state() & AltButton ) ||
1006 ( ( e->state() & ControlButton | AltButton ) == (ControlButton|AltButton) ) ) && 1006 ( ( e->state() & ControlButton | AltButton ) == (ControlButton|AltButton) ) ) &&
1007 ( !e->ascii() || e->ascii() >= 32 || e->text() == "\t" ) ) { 1007 ( !e->ascii() || e->ascii() >= 32 || e->text() == "\t" ) ) {
1008 clearUndoRedoInfo = FALSE; 1008 clearUndoRedoInfo = FALSE;
1009 if ( e->key() == Key_Tab ) { 1009 if ( e->key() == Key_Tab ) {
1010 if ( textFormat() == Qt::RichText && cursor->paragraph()->isListItem() ) { 1010 if ( textFormat() == Qt::RichText && cursor->paragraph()->isListItem() ) {
1011 clearUndoRedo(); 1011 clearUndoRedo();
1012 undoRedoInfo.type = UndoRedoInfo::Style; 1012 undoRedoInfo.type = UndoRedoInfo::Style;
1013 undoRedoInfo.id = cursor->paragraph()->paragId(); 1013 undoRedoInfo.id = cursor->paragraph()->paragId();
1014 undoRedoInfo.eid = undoRedoInfo.id; 1014 undoRedoInfo.eid = undoRedoInfo.id;
1015 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid ); 1015 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid );
1016 cursor->paragraph()->setListDepth( cursor->paragraph()->listDepth() +1 ); 1016 cursor->paragraph()->setListDepth( cursor->paragraph()->listDepth() +1 );
1017 clearUndoRedo(); 1017 clearUndoRedo();
1018 drawCursor( FALSE ); 1018 drawCursor( FALSE );
1019 repaintChanged(); 1019 repaintChanged();
1020 drawCursor( TRUE ); 1020 drawCursor( TRUE );
1021 break; 1021 break;
1022 } 1022 }
1023 } 1023 }
1024 1024
1025 if ( textFormat() == Qt::RichText && !cursor->paragraph()->isListItem() ) { 1025 if ( textFormat() == Qt::RichText && !cursor->paragraph()->isListItem() ) {
1026 if ( cursor->index() == 0 && ( e->text()[0] == '-' || e->text()[0] == '*' ) ) { 1026 if ( cursor->index() == 0 && ( e->text()[0] == '-' || e->text()[0] == '*' ) ) {
1027 clearUndoRedo(); 1027 clearUndoRedo();
1028 undoRedoInfo.type = UndoRedoInfo::Style; 1028 undoRedoInfo.type = UndoRedoInfo::Style;
1029 undoRedoInfo.id = cursor->paragraph()->paragId(); 1029 undoRedoInfo.id = cursor->paragraph()->paragId();
1030 undoRedoInfo.eid = undoRedoInfo.id; 1030 undoRedoInfo.eid = undoRedoInfo.id;
1031 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid ); 1031 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid );
1032 setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListDisc ); 1032 setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListDisc );
1033 clearUndoRedo(); 1033 clearUndoRedo();
1034 drawCursor( FALSE ); 1034 drawCursor( FALSE );
1035 repaintChanged(); 1035 repaintChanged();
1036 drawCursor( TRUE ); 1036 drawCursor( TRUE );
1037 break; 1037 break;
1038 } 1038 }
1039 } 1039 }
1040 if ( overWrite && !cursor->atParagEnd() ) 1040 if ( overWrite && !cursor->atParagEnd() )
1041 cursor->remove(); 1041 cursor->remove();
1042 QString t = e->text(); 1042 QString t = e->text();
1043 QTextParagraph *p = cursor->paragraph(); 1043 QTextParagraph *p = cursor->paragraph();
1044 if ( p && p->string() && p->string()->isRightToLeft() ) { 1044 if ( p && p->string() && p->string()->isRightToLeft() ) {
1045 QChar *c = (QChar *)t.unicode(); 1045 QChar *c = (QChar *)t.unicode();
1046 int l = t.length(); 1046 int l = t.length();
1047 while( l-- ) { 1047 while( l-- ) {
1048 if ( c->mirrored() ) 1048 if ( c->mirrored() )
1049 *c = c->mirroredChar(); 1049 *c = c->mirroredChar();
1050 c++; 1050 c++;
1051 } 1051 }
1052 } 1052 }
1053 insert( t, TRUE, FALSE, TRUE ); 1053 insert( t, TRUE, FALSE, TRUE );
1054 break; 1054 break;
1055 } else if ( e->state() & ControlButton ) { 1055 } else if ( e->state() & ControlButton ) {
1056 switch ( e->key() ) { 1056 switch ( e->key() ) {
1057 case Key_C: case Key_F16: // Copy key on Sun keyboards 1057 case Key_C: case Key_F16: // Copy key on Sun keyboards
1058 copy(); 1058 copy();
1059 break; 1059 break;
1060 case Key_V: 1060 case Key_V:
1061 paste(); 1061 paste();
1062 break; 1062 break;
1063 case Key_X: 1063 case Key_X:
1064 cut(); 1064 cut();
1065 break; 1065 break;
1066 case Key_I: case Key_T: case Key_Tab: 1066 case Key_I: case Key_T: case Key_Tab:
1067 indent(); 1067 indent();
1068 break; 1068 break;
1069 case Key_A: 1069 case Key_A:
1070#if defined(Q_WS_X11) 1070#if defined(Q_WS_X11)
1071 moveCursor( MoveLineStart, e->state() & ShiftButton ); 1071 moveCursor( MoveLineStart, e->state() & ShiftButton );
1072#else 1072#else
1073 selectAll( TRUE ); 1073 selectAll( TRUE );
1074#endif 1074#endif
1075 break; 1075 break;
1076 case Key_B: 1076 case Key_B:
1077 moveCursor( MoveBackward, e->state() & ShiftButton ); 1077 moveCursor( MoveBackward, e->state() & ShiftButton );
1078 break; 1078 break;
1079 case Key_F: 1079 case Key_F:
1080 moveCursor( MoveForward, e->state() & ShiftButton ); 1080 moveCursor( MoveForward, e->state() & ShiftButton );
1081 break; 1081 break;
1082 case Key_D: 1082 case Key_D:
1083 if ( doc->hasSelection( QTextDocument::Standard ) ) { 1083 if ( doc->hasSelection( QTextDocument::Standard ) ) {
1084 removeSelectedText(); 1084 removeSelectedText();
1085 break; 1085 break;
1086 } 1086 }
1087 doKeyboardAction( ActionDelete ); 1087 doKeyboardAction( ActionDelete );
1088 clearUndoRedoInfo = FALSE; 1088 clearUndoRedoInfo = FALSE;
1089 break; 1089 break;
1090 case Key_H: 1090 case Key_H:
1091 if ( doc->hasSelection( QTextDocument::Standard ) ) { 1091 if ( doc->hasSelection( QTextDocument::Standard ) ) {
1092 removeSelectedText(); 1092 removeSelectedText();
1093 break; 1093 break;
1094 } 1094 }
1095 if ( !cursor->paragraph()->prev() && 1095 if ( !cursor->paragraph()->prev() &&
1096 cursor->atParagStart() ) 1096 cursor->atParagStart() )
1097 break; 1097 break;
1098 1098
1099 doKeyboardAction( ActionBackspace ); 1099 doKeyboardAction( ActionBackspace );
1100 clearUndoRedoInfo = FALSE; 1100 clearUndoRedoInfo = FALSE;
1101 break; 1101 break;
1102 case Key_E: 1102 case Key_E:
1103 moveCursor( MoveLineEnd, e->state() & ShiftButton ); 1103 moveCursor( MoveLineEnd, e->state() & ShiftButton );
1104 break; 1104 break;
1105 case Key_N: 1105 case Key_N:
1106 moveCursor( MoveDown, e->state() & ShiftButton ); 1106 moveCursor( MoveDown, e->state() & ShiftButton );
1107 break; 1107 break;
1108 case Key_P: 1108 case Key_P:
1109 moveCursor( MoveUp, e->state() & ShiftButton ); 1109 moveCursor( MoveUp, e->state() & ShiftButton );
1110 break; 1110 break;
1111 case Key_Z: 1111 case Key_Z:
1112 if(e->state() & ShiftButton) 1112 if(e->state() & ShiftButton)
1113 redo(); 1113 redo();
1114 else 1114 else
1115 undo(); 1115 undo();
1116 break; 1116 break;
1117 case Key_Y: 1117 case Key_Y:
1118 redo(); 1118 redo();
1119 break; 1119 break;
1120 case Key_K: 1120 case Key_K:
1121 doKeyboardAction( ActionKill ); 1121 doKeyboardAction( ActionKill );
1122 break; 1122 break;
1123#if defined(Q_WS_WIN) 1123#if defined(Q_WS_WIN)
1124 case Key_Insert: 1124 case Key_Insert:
1125 copy(); 1125 copy();
1126 break; 1126 break;
1127 case Key_Delete: 1127 case Key_Delete:
1128 del(); 1128 del();
1129 break; 1129 break;
1130#endif 1130#endif
1131 default: 1131 default:
1132 unknown = FALSE; 1132 unknown = FALSE;
1133 break; 1133 break;
1134 } 1134 }
1135 } else { 1135 } else {
1136 unknown = TRUE; 1136 unknown = TRUE;
1137 } 1137 }
1138 } 1138 }
1139 } 1139 }
1140 1140
1141 emit cursorPositionChanged( cursor ); 1141 emit cursorPositionChanged( cursor );
1142 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() ); 1142 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() );
1143 if ( clearUndoRedoInfo ) 1143 if ( clearUndoRedoInfo )
1144 clearUndoRedo(); 1144 clearUndoRedo();
1145 changeIntervalTimer->start( 100, TRUE ); 1145 changeIntervalTimer->start( 100, TRUE );
1146 if ( unknown ) 1146 if ( unknown )
1147 e->ignore(); 1147 e->ignore();
1148} 1148}
1149 1149
1150/*! 1150/*!
1151 Executes keyboard action \a action. This is normally called by 1151 Executes keyboard action \a action. This is normally called by
1152 a key event handler. 1152 a key event handler.
1153*/ 1153*/
1154 1154
1155void QTextEdit::doKeyboardAction( KeyboardAction action ) 1155void QTextEdit::doKeyboardAction( KeyboardAction action )
1156{ 1156{
1157 if ( isReadOnly() ) 1157 if ( isReadOnly() )
1158 return; 1158 return;
1159 1159
1160 if ( cursor->nestedDepth() != 0 ) // #### for 3.0, disable editing of tables as this is not advanced enough 1160 if ( cursor->nestedDepth() != 0 ) // #### for 3.0, disable editing of tables as this is not advanced enough
1161 return; 1161 return;
1162 1162
1163 lastFormatted = cursor->paragraph(); 1163 lastFormatted = cursor->paragraph();
1164 drawCursor( FALSE ); 1164 drawCursor( FALSE );
1165 bool doUpdateCurrentFormat = TRUE; 1165 bool doUpdateCurrentFormat = TRUE;
1166 1166
1167 switch ( action ) { 1167 switch ( action ) {
1168 case ActionDelete: 1168 case ActionDelete:
1169 if ( !cursor->atParagEnd() ) { 1169 if ( !cursor->atParagEnd() ) {
1170 checkUndoRedoInfo( UndoRedoInfo::Delete ); 1170 checkUndoRedoInfo( UndoRedoInfo::Delete );
1171 if ( !undoRedoInfo.valid() ) { 1171 if ( !undoRedoInfo.valid() ) {
1172 undoRedoInfo.id = cursor->paragraph()->paragId(); 1172 undoRedoInfo.id = cursor->paragraph()->paragId();
1173 undoRedoInfo.index = cursor->index(); 1173 undoRedoInfo.index = cursor->index();
1174 undoRedoInfo.d->text = QString::null; 1174 undoRedoInfo.d->text = QString::null;
1175 } 1175 }
1176 undoRedoInfo.d->text.insert( undoRedoInfo.d->text.length(), cursor->paragraph()->at( cursor->index() ), TRUE ); 1176 undoRedoInfo.d->text.insert( undoRedoInfo.d->text.length(), cursor->paragraph()->at( cursor->index() ), TRUE );
1177 cursor->remove(); 1177 cursor->remove();
1178 } else { 1178 } else {
1179 clearUndoRedo(); 1179 clearUndoRedo();
1180 doc->setSelectionStart( QTextDocument::Temp, *cursor ); 1180 doc->setSelectionStart( QTextDocument::Temp, *cursor );
1181 cursor->gotoNextLetter(); 1181 cursor->gotoNextLetter();
1182 doc->setSelectionEnd( QTextDocument::Temp, *cursor ); 1182 doc->setSelectionEnd( QTextDocument::Temp, *cursor );
1183 removeSelectedText( QTextDocument::Temp ); 1183 removeSelectedText( QTextDocument::Temp );
1184 } 1184 }
1185 break; 1185 break;
1186 case ActionBackspace: 1186 case ActionBackspace:
1187 if ( textFormat() == Qt::RichText && cursor->paragraph()->isListItem() && cursor->index() == 0 ) { 1187 if ( textFormat() == Qt::RichText && cursor->paragraph()->isListItem() && cursor->index() == 0 ) {
1188 clearUndoRedo(); 1188 clearUndoRedo();
1189 undoRedoInfo.type = UndoRedoInfo::Style; 1189 undoRedoInfo.type = UndoRedoInfo::Style;
1190 undoRedoInfo.id = cursor->paragraph()->paragId(); 1190 undoRedoInfo.id = cursor->paragraph()->paragId();
1191 undoRedoInfo.eid = undoRedoInfo.id; 1191 undoRedoInfo.eid = undoRedoInfo.id;
1192 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid ); 1192 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid );
1193 int ldepth = cursor->paragraph()->listDepth(); 1193 int ldepth = cursor->paragraph()->listDepth();
1194 ldepth = QMAX( ldepth-1, 0 ); 1194 ldepth = QMAX( ldepth-1, 0 );
1195 cursor->paragraph()->setListDepth( ldepth ); 1195 cursor->paragraph()->setListDepth( ldepth );
1196 if ( ldepth == 0 ) 1196 if ( ldepth == 0 )
1197 cursor->paragraph()->setListItem( FALSE ); 1197 cursor->paragraph()->setListItem( FALSE );
1198 clearUndoRedo(); 1198 clearUndoRedo();
1199 lastFormatted = cursor->paragraph(); 1199 lastFormatted = cursor->paragraph();
1200 repaintChanged(); 1200 repaintChanged();
1201 drawCursor( TRUE ); 1201 drawCursor( TRUE );
1202 return; 1202 return;
1203 } 1203 }
1204 if ( !cursor->atParagStart() ) { 1204 if ( !cursor->atParagStart() ) {
1205 checkUndoRedoInfo( UndoRedoInfo::Delete ); 1205 checkUndoRedoInfo( UndoRedoInfo::Delete );
1206 if ( !undoRedoInfo.valid() ) { 1206 if ( !undoRedoInfo.valid() ) {
1207 undoRedoInfo.id = cursor->paragraph()->paragId(); 1207 undoRedoInfo.id = cursor->paragraph()->paragId();
1208 undoRedoInfo.index = cursor->index(); 1208 undoRedoInfo.index = cursor->index();
1209 undoRedoInfo.d->text = QString::null; 1209 undoRedoInfo.d->text = QString::null;
1210 } 1210 }
1211 cursor->gotoPreviousLetter(); 1211 cursor->gotoPreviousLetter();
1212 undoRedoInfo.d->text.insert( 0, cursor->paragraph()->at( cursor->index() ), TRUE ); 1212 undoRedoInfo.d->text.insert( 0, cursor->paragraph()->at( cursor->index() ), TRUE );
1213 undoRedoInfo.index = cursor->index(); 1213 undoRedoInfo.index = cursor->index();
1214 cursor->remove(); 1214 cursor->remove();
1215 lastFormatted = cursor->paragraph(); 1215 lastFormatted = cursor->paragraph();
1216 } else if ( cursor->paragraph()->prev() ){ 1216 } else if ( cursor->paragraph()->prev() ){
1217 clearUndoRedo(); 1217 clearUndoRedo();
1218 doc->setSelectionStart( QTextDocument::Temp, *cursor ); 1218 doc->setSelectionStart( QTextDocument::Temp, *cursor );
1219 cursor->gotoPreviousLetter(); 1219 cursor->gotoPreviousLetter();
1220 doc->setSelectionEnd( QTextDocument::Temp, *cursor ); 1220 doc->setSelectionEnd( QTextDocument::Temp, *cursor );
1221 removeSelectedText( QTextDocument::Temp ); 1221 removeSelectedText( QTextDocument::Temp );
1222 } 1222 }
1223 break; 1223 break;
1224 case ActionReturn: 1224 case ActionReturn:
1225 checkUndoRedoInfo( UndoRedoInfo::Return ); 1225 checkUndoRedoInfo( UndoRedoInfo::Return );
1226 if ( !undoRedoInfo.valid() ) { 1226 if ( !undoRedoInfo.valid() ) {
1227 undoRedoInfo.id = cursor->paragraph()->paragId(); 1227 undoRedoInfo.id = cursor->paragraph()->paragId();
1228 undoRedoInfo.index = cursor->index(); 1228 undoRedoInfo.index = cursor->index();
1229 undoRedoInfo.d->text = QString::null; 1229 undoRedoInfo.d->text = QString::null;
1230 } 1230 }
1231 undoRedoInfo.d->text += "\n"; 1231 undoRedoInfo.d->text += "\n";
1232 cursor->splitAndInsertEmptyParagraph(); 1232 cursor->splitAndInsertEmptyParagraph();
1233 if ( cursor->paragraph()->prev() ) { 1233 if ( cursor->paragraph()->prev() ) {
1234 lastFormatted = cursor->paragraph()->prev(); 1234 lastFormatted = cursor->paragraph()->prev();
1235 lastFormatted->invalidate( 0 ); 1235 lastFormatted->invalidate( 0 );
1236 } 1236 }
1237 doUpdateCurrentFormat = FALSE; 1237 doUpdateCurrentFormat = FALSE;
1238 break; 1238 break;
1239 case ActionKill: 1239 case ActionKill:
1240 clearUndoRedo(); 1240 clearUndoRedo();
1241 doc->setSelectionStart( QTextDocument::Temp, *cursor ); 1241 doc->setSelectionStart( QTextDocument::Temp, *cursor );
1242 if ( cursor->atParagEnd() ) 1242 if ( cursor->atParagEnd() )
1243 cursor->gotoNextLetter(); 1243 cursor->gotoNextLetter();
1244 else 1244 else
1245 cursor->setIndex( cursor->paragraph()->length() - 1 ); 1245 cursor->setIndex( cursor->paragraph()->length() - 1 );
1246 doc->setSelectionEnd( QTextDocument::Temp, *cursor ); 1246 doc->setSelectionEnd( QTextDocument::Temp, *cursor );
1247 removeSelectedText( QTextDocument::Temp ); 1247 removeSelectedText( QTextDocument::Temp );
1248 break; 1248 break;
1249 } 1249 }
1250 1250
1251 formatMore(); 1251 formatMore();
1252 repaintChanged(); 1252 repaintChanged();
1253 ensureCursorVisible(); 1253 ensureCursorVisible();
1254 drawCursor( TRUE ); 1254 drawCursor( TRUE );
1255 updateMicroFocusHint(); 1255 updateMicroFocusHint();
1256 if ( doUpdateCurrentFormat ) 1256 if ( doUpdateCurrentFormat )
1257 updateCurrentFormat(); 1257 updateCurrentFormat();
1258 setModified(); 1258 setModified();
1259 emit textChanged(); 1259 emit textChanged();
1260} 1260}
1261 1261
1262void QTextEdit::readFormats( QTextCursor &c1, QTextCursor &c2, QTextString &text, bool fillStyles ) 1262void QTextEdit::readFormats( QTextCursor &c1, QTextCursor &c2, QTextString &text, bool fillStyles )
1263{ 1263{
1264 QDataStream styleStream( undoRedoInfo.styleInformation, IO_WriteOnly ); 1264 QDataStream styleStream( undoRedoInfo.styleInformation, IO_WriteOnly );
1265 c2.restoreState(); 1265 c2.restoreState();
1266 c1.restoreState(); 1266 c1.restoreState();
1267 int lastIndex = text.length(); 1267 int lastIndex = text.length();
1268 if ( c1.paragraph() == c2.paragraph() ) { 1268 if ( c1.paragraph() == c2.paragraph() ) {
1269 for ( int i = c1.index(); i < c2.index(); ++i ) 1269 for ( int i = c1.index(); i < c2.index(); ++i )
1270 text.insert( lastIndex + i - c1.index(), c1.paragraph()->at( i ), TRUE ); 1270 text.insert( lastIndex + i - c1.index(), c1.paragraph()->at( i ), TRUE );
1271 if ( fillStyles ) { 1271 if ( fillStyles ) {
1272 styleStream << (int) 1; 1272 styleStream << (int) 1;
1273 c1.paragraph()->writeStyleInformation( styleStream ); 1273 c1.paragraph()->writeStyleInformation( styleStream );
1274 } 1274 }
1275 } else { 1275 } else {
1276 int i; 1276 int i;
1277 for ( i = c1.index(); i < c1.paragraph()->length()-1; ++i ) 1277 for ( i = c1.index(); i < c1.paragraph()->length()-1; ++i )
1278 text.insert( lastIndex++, c1.paragraph()->at( i ), TRUE ); 1278 text.insert( lastIndex++, c1.paragraph()->at( i ), TRUE );
1279 int num = 2; // start and end, being different 1279 int num = 2; // start and end, being different
1280 text += "\n"; lastIndex++; 1280 text += "\n"; lastIndex++;
1281 QTextParagraph *p = c1.paragraph()->next(); 1281 QTextParagraph *p = c1.paragraph()->next();
1282 while ( p && p != c2.paragraph() ) { 1282 while ( p && p != c2.paragraph() ) {
1283 for ( i = 0; i < p->length()-1; ++i ) 1283 for ( i = 0; i < p->length()-1; ++i )
1284 text.insert( lastIndex++ , p->at( i ), TRUE ); 1284 text.insert( lastIndex++ , p->at( i ), TRUE );
1285 text += "\n"; num++; lastIndex++; 1285 text += "\n"; num++; lastIndex++;
1286 p = p->next(); 1286 p = p->next();
1287 } 1287 }
1288 for ( i = 0; i < c2.index(); ++i ) 1288 for ( i = 0; i < c2.index(); ++i )
1289 text.insert( i + lastIndex, c2.paragraph()->at( i ), TRUE ); 1289 text.insert( i + lastIndex, c2.paragraph()->at( i ), TRUE );
1290 if ( fillStyles ) { 1290 if ( fillStyles ) {
1291 styleStream << num; 1291 styleStream << num;
1292 for ( QTextParagraph *p = c1.paragraph(); --num >= 0; p = p->next() ) 1292 for ( QTextParagraph *p = c1.paragraph(); --num >= 0; p = p->next() )
1293 p->writeStyleInformation( styleStream ); 1293 p->writeStyleInformation( styleStream );
1294 } 1294 }
1295 } 1295 }
1296} 1296}
1297 1297
1298/*! Removes the selection \a selNum (by default 0). This does not 1298/*! Removes the selection \a selNum (by default 0). This does not
1299 remove the selected text. 1299 remove the selected text.
1300 1300
1301 \sa removeSelectedText() 1301 \sa removeSelectedText()
1302*/ 1302*/
1303 1303
1304void QTextEdit::removeSelection( int selNum ) 1304void QTextEdit::removeSelection( int selNum )
1305{ 1305{
1306 doc->removeSelection( selNum ); 1306 doc->removeSelection( selNum );
1307 repaintChanged(); 1307 repaintChanged();
1308} 1308}
1309 1309
1310/*! Deletes the selected text (i.e. the default selection's text) of 1310/*! Deletes the selected text (i.e. the default selection's text) of
1311 the selection \a selNum (by default, 0). If there is no selected text 1311 the selection \a selNum (by default, 0). If there is no selected text
1312 nothing happens. 1312 nothing happens.
1313 1313
1314 \sa selectedText removeSelection() 1314 \sa selectedText removeSelection()
1315*/ 1315*/
1316 1316
1317void QTextEdit::removeSelectedText( int selNum ) 1317void QTextEdit::removeSelectedText( int selNum )
1318{ 1318{
1319 if ( isReadOnly() ) 1319 if ( isReadOnly() )
1320 return; 1320 return;
1321 1321
1322 QTextCursor c1 = doc->selectionStartCursor( selNum ); 1322 QTextCursor c1 = doc->selectionStartCursor( selNum );
1323 c1.restoreState(); 1323 c1.restoreState();
1324 QTextCursor c2 = doc->selectionEndCursor( selNum ); 1324 QTextCursor c2 = doc->selectionEndCursor( selNum );
1325 c2.restoreState(); 1325 c2.restoreState();
1326 1326
1327 // ### no support for editing tables yet, plus security for broken selections 1327 // ### no support for editing tables yet, plus security for broken selections
1328 if ( c1.nestedDepth() || c2.nestedDepth() ) 1328 if ( c1.nestedDepth() || c2.nestedDepth() )
1329 return; 1329 return;
1330 1330
1331 for ( int i = 0; i < (int)doc->numSelections(); ++i ) { 1331 for ( int i = 0; i < (int)doc->numSelections(); ++i ) {
1332 if ( i == selNum ) 1332 if ( i == selNum )
1333 continue; 1333 continue;
1334 doc->removeSelection( i ); 1334 doc->removeSelection( i );
1335 } 1335 }
1336 1336
1337 drawCursor( FALSE ); 1337 drawCursor( FALSE );
1338 checkUndoRedoInfo( UndoRedoInfo::RemoveSelected ); 1338 checkUndoRedoInfo( UndoRedoInfo::RemoveSelected );
1339 if ( !undoRedoInfo.valid() ) { 1339 if ( !undoRedoInfo.valid() ) {
1340 doc->selectionStart( selNum, undoRedoInfo.id, undoRedoInfo.index ); 1340 doc->selectionStart( selNum, undoRedoInfo.id, undoRedoInfo.index );
1341 undoRedoInfo.d->text = QString::null; 1341 undoRedoInfo.d->text = QString::null;
1342 } 1342 }
1343 readFormats( c1, c2, undoRedoInfo.d->text, TRUE ); 1343 readFormats( c1, c2, undoRedoInfo.d->text, TRUE );
1344 1344
1345 1345
1346 doc->removeSelectedText( selNum, cursor ); 1346 doc->removeSelectedText( selNum, cursor );
1347 if ( cursor->isValid() ) { 1347 if ( cursor->isValid() ) {
1348 ensureCursorVisible(); 1348 ensureCursorVisible();
1349 lastFormatted = cursor->paragraph(); 1349 lastFormatted = cursor->paragraph();
1350 formatMore(); 1350 formatMore();
1351 repaintChanged(); 1351 repaintChanged();
1352 ensureCursorVisible(); 1352 ensureCursorVisible();
1353 drawCursor( TRUE ); 1353 drawCursor( TRUE );
1354 clearUndoRedo(); 1354 clearUndoRedo();
1355#if defined(Q_WS_WIN) 1355#if defined(Q_WS_WIN)
1356 // there seems to be a problem with repainting or erasing the area 1356 // there seems to be a problem with repainting or erasing the area
1357 // of the scrollview which is not the contents on windows 1357 // of the scrollview which is not the contents on windows
1358 if ( contentsHeight() < visibleHeight() ) 1358 if ( contentsHeight() < visibleHeight() )
1359 viewport()->repaint( 0, contentsHeight(), visibleWidth(), visibleHeight() - contentsHeight(), TRUE ); 1359 viewport()->repaint( 0, contentsHeight(), visibleWidth(), visibleHeight() - contentsHeight(), TRUE );
1360#endif 1360#endif
1361#ifndef QT_NO_CURSOR 1361#ifndef QT_NO_CURSOR
1362 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 1362 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
1363#endif 1363#endif
1364 updateMicroFocusHint(); 1364 updateMicroFocusHint();
1365 } else { 1365 } else {
1366 delete cursor; 1366 delete cursor;
1367 cursor = new QTextCursor( doc ); 1367 cursor = new QTextCursor( doc );
1368 drawCursor( TRUE ); 1368 drawCursor( TRUE );
1369 viewport()->repaint( TRUE ); 1369 viewport()->repaint( TRUE );
1370 } 1370 }
1371 setModified(); 1371 setModified();
1372 emit textChanged(); 1372 emit textChanged();
1373 emit selectionChanged(); 1373 emit selectionChanged();
1374} 1374}
1375 1375
1376/*! Moves the text cursor according to \a action. This is normally 1376/*! Moves the text cursor according to \a action. This is normally
1377 used by some key event handler. \a select specifies whether the text 1377 used by some key event handler. \a select specifies whether the text
1378 between the current cursor position and the new position should be 1378 between the current cursor position and the new position should be
1379 selected. 1379 selected.
1380*/ 1380*/
1381 1381
1382void QTextEdit::moveCursor( CursorAction action, bool select ) 1382void QTextEdit::moveCursor( CursorAction action, bool select )
1383{ 1383{
1384 drawCursor( FALSE ); 1384 drawCursor( FALSE );
1385 if ( select ) { 1385 if ( select ) {
1386 if ( !doc->hasSelection( QTextDocument::Standard ) ) 1386 if ( !doc->hasSelection( QTextDocument::Standard ) )
1387 doc->setSelectionStart( QTextDocument::Standard, *cursor ); 1387 doc->setSelectionStart( QTextDocument::Standard, *cursor );
1388 moveCursor( action ); 1388 moveCursor( action );
1389 if ( doc->setSelectionEnd( QTextDocument::Standard, *cursor ) ) { 1389 if ( doc->setSelectionEnd( QTextDocument::Standard, *cursor ) ) {
1390 cursor->paragraph()->document()->nextDoubleBuffered = TRUE; 1390 cursor->paragraph()->document()->nextDoubleBuffered = TRUE;
1391 repaintChanged(); 1391 repaintChanged();
1392 } else { 1392 } else {
1393 drawCursor( TRUE ); 1393 drawCursor( TRUE );
1394 } 1394 }
1395 ensureCursorVisible(); 1395 ensureCursorVisible();
1396 emit selectionChanged(); 1396 emit selectionChanged();
1397 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) ); 1397 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) );
1398 } else { 1398 } else {
1399 bool redraw = doc->removeSelection( QTextDocument::Standard ); 1399 bool redraw = doc->removeSelection( QTextDocument::Standard );
1400 moveCursor( action ); 1400 moveCursor( action );
1401 if ( !redraw ) { 1401 if ( !redraw ) {
1402 ensureCursorVisible(); 1402 ensureCursorVisible();
1403 drawCursor( TRUE ); 1403 drawCursor( TRUE );
1404 } else { 1404 } else {
1405 cursor->paragraph()->document()->nextDoubleBuffered = TRUE; 1405 cursor->paragraph()->document()->nextDoubleBuffered = TRUE;
1406 repaintChanged(); 1406 repaintChanged();
1407 ensureCursorVisible(); 1407 ensureCursorVisible();
1408 drawCursor( TRUE ); 1408 drawCursor( TRUE );
1409#ifndef QT_NO_CURSOR 1409#ifndef QT_NO_CURSOR
1410 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 1410 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
1411#endif 1411#endif
1412 } 1412 }
1413 if ( redraw ) { 1413 if ( redraw ) {
1414 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) ); 1414 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) );
1415 emit selectionChanged(); 1415 emit selectionChanged();
1416 } 1416 }
1417 } 1417 }
1418 1418
1419 drawCursor( TRUE ); 1419 drawCursor( TRUE );
1420 updateCurrentFormat(); 1420 updateCurrentFormat();
1421 updateMicroFocusHint(); 1421 updateMicroFocusHint();
1422} 1422}
1423 1423
1424/*! \overload 1424/*! \overload
1425*/ 1425*/
1426 1426
1427void QTextEdit::moveCursor( CursorAction action ) 1427void QTextEdit::moveCursor( CursorAction action )
1428{ 1428{
1429 switch ( action ) { 1429 switch ( action ) {
1430 case MoveBackward: 1430 case MoveBackward:
1431 cursor->gotoPreviousLetter(); 1431 cursor->gotoPreviousLetter();
1432 break; 1432 break;
1433 case MoveWordBackward: 1433 case MoveWordBackward:
1434 cursor->gotoPreviousWord(); 1434 cursor->gotoPreviousWord();
1435 break; 1435 break;
1436 case MoveForward: 1436 case MoveForward:
1437 cursor->gotoNextLetter(); 1437 cursor->gotoNextLetter();
1438 break; 1438 break;
1439 case MoveWordForward: 1439 case MoveWordForward:
1440 cursor->gotoNextWord(); 1440 cursor->gotoNextWord();
1441 break; 1441 break;
1442 case MoveUp: 1442 case MoveUp:
1443 cursor->gotoUp(); 1443 cursor->gotoUp();
1444 break; 1444 break;
1445 case MovePgUp: 1445 case MovePgUp:
1446 cursor->gotoPageUp( visibleHeight() ); 1446 cursor->gotoPageUp( visibleHeight() );
1447 break; 1447 break;
1448 case MoveDown: 1448 case MoveDown:
1449 cursor->gotoDown(); 1449 cursor->gotoDown();
1450 break; 1450 break;
1451 case MovePgDown: 1451 case MovePgDown:
1452 cursor->gotoPageDown( visibleHeight() ); 1452 cursor->gotoPageDown( visibleHeight() );
1453 break; 1453 break;
1454 case MoveLineStart: 1454 case MoveLineStart:
1455 cursor->gotoLineStart(); 1455 cursor->gotoLineStart();
1456 break; 1456 break;
1457 case MoveHome: 1457 case MoveHome:
1458 cursor->gotoHome(); 1458 cursor->gotoHome();
1459 break; 1459 break;
1460 case MoveLineEnd: 1460 case MoveLineEnd:
1461 cursor->gotoLineEnd(); 1461 cursor->gotoLineEnd();
1462 break; 1462 break;
1463 case MoveEnd: 1463 case MoveEnd:
1464 ensureFormatted( doc->lastParagraph() ); 1464 ensureFormatted( doc->lastParagraph() );
1465 cursor->gotoEnd(); 1465 cursor->gotoEnd();
1466 break; 1466 break;
1467 } 1467 }
1468 updateMicroFocusHint(); 1468 updateMicroFocusHint();
1469 updateCurrentFormat(); 1469 updateCurrentFormat();
1470} 1470}
1471 1471
1472/*! \reimp */ 1472/*! \reimp */
1473 1473
1474void QTextEdit::resizeEvent( QResizeEvent *e ) 1474void QTextEdit::resizeEvent( QResizeEvent *e )
1475{ 1475{
1476 QScrollView::resizeEvent( e ); 1476 QScrollView::resizeEvent( e );
1477 if ( doc->visibleWidth() == 0 ) 1477 if ( doc->visibleWidth() == 0 )
1478 doResize(); 1478 doResize();
1479} 1479}
1480 1480
1481/*! \reimp */ 1481/*! \reimp */
1482 1482
1483void QTextEdit::viewportResizeEvent( QResizeEvent *e ) 1483void QTextEdit::viewportResizeEvent( QResizeEvent *e )
1484{ 1484{
1485 QScrollView::viewportResizeEvent( e ); 1485 QScrollView::viewportResizeEvent( e );
1486 if ( e->oldSize().width() != e->size().width() ) { 1486 if ( e->oldSize().width() != e->size().width() ) {
1487 bool stayAtBottom = e->oldSize().height() != e->size().height() && 1487 bool stayAtBottom = e->oldSize().height() != e->size().height() &&
1488 contentsY() > 0 && contentsY() >= doc->height() - e->oldSize().height(); 1488 contentsY() > 0 && contentsY() >= doc->height() - e->oldSize().height();
1489 doResize(); 1489 doResize();
1490 if ( stayAtBottom ) 1490 if ( stayAtBottom )
1491 scrollToBottom(); 1491 scrollToBottom();
1492 } 1492 }
1493} 1493}
1494 1494
1495/*! 1495/*!
1496 Ensures that the cursor is visible by scrolling the text edit if 1496 Ensures that the cursor is visible by scrolling the text edit if
1497 necessary. 1497 necessary.
1498 1498
1499 \sa setCursorPosition() 1499 \sa setCursorPosition()
1500*/ 1500*/
1501 1501
1502void QTextEdit::ensureCursorVisible() 1502void QTextEdit::ensureCursorVisible()
1503{ 1503{
1504 if ( !isVisible() ) { 1504 if ( !isVisible() ) {
1505 d->ensureCursorVisibleInShowEvent = TRUE; 1505 d->ensureCursorVisibleInShowEvent = TRUE;
1506 return; 1506 return;
1507 } 1507 }
1508 lastFormatted = cursor->paragraph(); 1508 lastFormatted = cursor->paragraph();
1509 formatMore(); 1509 formatMore();
1510 QTextStringChar *chr = cursor->paragraph()->at( cursor->index() ); 1510 QTextStringChar *chr = cursor->paragraph()->at( cursor->index() );
1511 int h = cursor->paragraph()->lineHeightOfChar( cursor->index() ); 1511 int h = cursor->paragraph()->lineHeightOfChar( cursor->index() );
1512 int x = cursor->paragraph()->rect().x() + chr->x + cursor->offsetX(); 1512 int x = cursor->paragraph()->rect().x() + chr->x + cursor->offsetX();
1513 int y = 0; int dummy; 1513 int y = 0; int dummy;
1514 cursor->paragraph()->lineHeightOfChar( cursor->index(), &dummy, &y ); 1514 cursor->paragraph()->lineHeightOfChar( cursor->index(), &dummy, &y );
1515 y += cursor->paragraph()->rect().y() + cursor->offsetY(); 1515 y += cursor->paragraph()->rect().y() + cursor->offsetY();
1516 int w = 1; 1516 int w = 1;
1517 ensureVisible( x, y + h / 2, w, h / 2 + 2 ); 1517 ensureVisible( x, y + h / 2, w, h / 2 + 2 );
1518} 1518}
1519 1519
1520/*! 1520/*!
1521 \internal 1521 \internal
1522*/ 1522*/
1523void QTextEdit::drawCursor( bool visible ) 1523void QTextEdit::drawCursor( bool visible )
1524{ 1524{
1525 if ( !isUpdatesEnabled() || 1525 if ( !isUpdatesEnabled() ||
1526 !viewport()->isUpdatesEnabled() || 1526 !viewport()->isUpdatesEnabled() ||
1527 !cursor->paragraph() || 1527 !cursor->paragraph() ||
1528 !cursor->paragraph()->isValid() || 1528 !cursor->paragraph()->isValid() ||
1529 !selectedText().isEmpty() || 1529 !selectedText().isEmpty() ||
1530 ( visible && !hasFocus() && !viewport()->hasFocus() && !inDnD ) || 1530 ( visible && !hasFocus() && !viewport()->hasFocus() && !inDnD ) ||
1531 isReadOnly() ) 1531 isReadOnly() )
1532 return; 1532 return;
1533 1533
1534 QPainter p( viewport() ); 1534 QPainter p( viewport() );
1535 QRect r( cursor->topParagraph()->rect() ); 1535 QRect r( cursor->topParagraph()->rect() );
1536 cursor->paragraph()->setChanged( TRUE ); 1536 cursor->paragraph()->setChanged( TRUE );
1537 p.translate( -contentsX() + cursor->totalOffsetX(), -contentsY() + cursor->totalOffsetY() ); 1537 p.translate( -contentsX() + cursor->totalOffsetX(), -contentsY() + cursor->totalOffsetY() );
1538 QPixmap *pix = 0; 1538 QPixmap *pix = 0;
1539 QColorGroup cg( colorGroup() ); 1539 QColorGroup cg( colorGroup() );
1540 if ( cursor->paragraph()->background() ) 1540 if ( cursor->paragraph()->background() )
1541 cg.setBrush( QColorGroup::Base, *cursor->paragraph()->background() ); 1541 cg.setBrush( QColorGroup::Base, *cursor->paragraph()->background() );
1542 else if ( doc->paper() ) 1542 else if ( doc->paper() )
1543 cg.setBrush( QColorGroup::Base, *doc->paper() ); 1543 cg.setBrush( QColorGroup::Base, *doc->paper() );
1544 p.setBrushOrigin( -contentsX(), -contentsY() ); 1544 p.setBrushOrigin( -contentsX(), -contentsY() );
1545 cursor->paragraph()->document()->nextDoubleBuffered = TRUE; 1545 cursor->paragraph()->document()->nextDoubleBuffered = TRUE;
1546 if ( !cursor->nestedDepth() ) { 1546 if ( !cursor->nestedDepth() ) {
1547 int h = cursor->paragraph()->lineHeightOfChar( cursor->index() ); 1547 int h = cursor->paragraph()->lineHeightOfChar( cursor->index() );
1548 int dist = 5; 1548 int dist = 5;
1549 if ( ( cursor->paragraph()->alignment() & Qt3::AlignJustify ) == Qt3::AlignJustify ) 1549 if ( ( cursor->paragraph()->alignment() & Qt3::AlignJustify ) == Qt3::AlignJustify )
1550 dist = 50; 1550 dist = 50;
1551 int x = r.x() - cursor->totalOffsetX() + cursor->x() - dist; 1551 int x = r.x() - cursor->totalOffsetX() + cursor->x() - dist;
1552 x = QMAX( x, 0 ); 1552 x = QMAX( x, 0 );
1553 p.setClipRect( QRect( x - contentsX(), 1553 p.setClipRect( QRect( x - contentsX(),
1554 r.y() - cursor->totalOffsetY() + cursor->y() - contentsY(), 2 * dist, h ) ); 1554 r.y() - cursor->totalOffsetY() + cursor->y() - contentsY(), 2 * dist, h ) );
1555 doc->drawParagraph( &p, cursor->paragraph(), x, 1555 doc->drawParagraph( &p, cursor->paragraph(), x,
1556 r.y() - cursor->totalOffsetY() + cursor->y(), 2 * dist, h, pix, cg, visible, cursor ); 1556 r.y() - cursor->totalOffsetY() + cursor->y(), 2 * dist, h, pix, cg, visible, cursor );
1557 } else { 1557 } else {
1558 doc->drawParagraph( &p, cursor->paragraph(), r.x() - cursor->totalOffsetX(), 1558 doc->drawParagraph( &p, cursor->paragraph(), r.x() - cursor->totalOffsetX(),
1559 r.y() - cursor->totalOffsetY(), r.width(), r.height(), 1559 r.y() - cursor->totalOffsetY(), r.width(), r.height(),
1560 pix, cg, visible, cursor ); 1560 pix, cg, visible, cursor );
1561 } 1561 }
1562 cursorVisible = visible; 1562 cursorVisible = visible;
1563} 1563}
1564 1564
1565enum { 1565enum {
1566 IdUndo = 0, 1566 IdUndo = 0,
1567 IdRedo = 1, 1567 IdRedo = 1,
1568 IdCut = 2, 1568 IdCut = 2,
1569 IdCopy = 3, 1569 IdCopy = 3,
1570 IdPaste = 4, 1570 IdPaste = 4,
1571 IdClear = 5, 1571 IdClear = 5,
1572 IdSelectAll = 6 1572 IdSelectAll = 6
1573}; 1573};
1574 1574
1575/*! \reimp */ 1575/*! \reimp */
1576#ifndef QT_NO_WHEELEVENT 1576#ifndef QT_NO_WHEELEVENT
1577void QTextEdit::contentsWheelEvent( QWheelEvent *e ) 1577void QTextEdit::contentsWheelEvent( QWheelEvent *e )
1578{ 1578{
1579 if ( isReadOnly() ) { 1579 if ( isReadOnly() ) {
1580 if ( e->state() & ControlButton ) { 1580 if ( e->state() & ControlButton ) {
1581 if ( e->delta() > 0 ) 1581 if ( e->delta() > 0 )
1582 zoomOut(); 1582 zoomOut();
1583 else if ( e->delta() < 0 ) 1583 else if ( e->delta() < 0 )
1584 zoomIn(); 1584 zoomIn();
1585 return; 1585 return;
1586 } 1586 }
1587 } 1587 }
1588 QScrollView::contentsWheelEvent( e ); 1588 QScrollView::contentsWheelEvent( e );
1589} 1589}
1590#endif 1590#endif
1591 1591
1592/*! \reimp */ 1592/*! \reimp */
1593 1593
1594void QTextEdit::contentsMousePressEvent( QMouseEvent *e ) 1594void QTextEdit::contentsMousePressEvent( QMouseEvent *e )
1595{ 1595{
1596 clearUndoRedo(); 1596 clearUndoRedo();
1597 QTextCursor oldCursor = *cursor; 1597 QTextCursor oldCursor = *cursor;
1598 QTextCursor c = *cursor; 1598 QTextCursor c = *cursor;
1599 mousePos = e->pos(); 1599 mousePos = e->pos();
1600 mightStartDrag = FALSE; 1600 mightStartDrag = FALSE;
1601 pressedLink = QString::null; 1601 pressedLink = QString::null;
1602 1602
1603 if ( e->button() == LeftButton ) { 1603 if ( e->button() == LeftButton ) {
1604 mousePressed = TRUE; 1604 mousePressed = TRUE;
1605 drawCursor( FALSE ); 1605 drawCursor( FALSE );
1606 placeCursor( e->pos() ); 1606 placeCursor( e->pos() );
1607 ensureCursorVisible(); 1607 ensureCursorVisible();
1608 1608
1609 if ( isReadOnly() && linksEnabled() ) { 1609 if ( isReadOnly() && linksEnabled() ) {
1610 QTextCursor c = *cursor; 1610 QTextCursor c = *cursor;
1611 placeCursor( e->pos(), &c, TRUE ); 1611 placeCursor( e->pos(), &c, TRUE );
1612 if ( c.paragraph() && c.paragraph()->at( c.index() ) && 1612 if ( c.paragraph() && c.paragraph()->at( c.index() ) &&
1613 c.paragraph()->at( c.index() )->isAnchor() ) { 1613 c.paragraph()->at( c.index() )->isAnchor() ) {
1614 pressedLink = c.paragraph()->at( c.index() )->anchorHref(); 1614 pressedLink = c.paragraph()->at( c.index() )->anchorHref();
1615 } 1615 }
1616 } 1616 }
1617 1617
1618#ifndef QT_NO_DRAGANDDROP 1618#ifndef QT_NO_DRAGANDDROP
1619 if ( doc->inSelection( QTextDocument::Standard, e->pos() ) ) { 1619 if ( doc->inSelection( QTextDocument::Standard, e->pos() ) ) {
1620 mightStartDrag = TRUE; 1620 mightStartDrag = TRUE;
1621 drawCursor( TRUE ); 1621 drawCursor( TRUE );
1622 dragStartTimer->start( QApplication::startDragTime(), TRUE ); 1622 dragStartTimer->start( QApplication::startDragTime(), TRUE );
1623 dragStartPos = e->pos(); 1623 dragStartPos = e->pos();
1624 return; 1624 return;
1625 } 1625 }
1626#endif 1626#endif
1627 1627
1628 bool redraw = FALSE; 1628 bool redraw = FALSE;
1629 if ( doc->hasSelection( QTextDocument::Standard ) ) { 1629 if ( doc->hasSelection( QTextDocument::Standard ) ) {
1630 if ( !( e->state() & ShiftButton ) ) { 1630 if ( !( e->state() & ShiftButton ) ) {
1631 redraw = doc->removeSelection( QTextDocument::Standard ); 1631 redraw = doc->removeSelection( QTextDocument::Standard );
1632 doc->setSelectionStart( QTextDocument::Standard, *cursor ); 1632 doc->setSelectionStart( QTextDocument::Standard, *cursor );
1633 } else { 1633 } else {
1634 redraw = doc->setSelectionEnd( QTextDocument::Standard, *cursor ) || redraw; 1634 redraw = doc->setSelectionEnd( QTextDocument::Standard, *cursor ) || redraw;
1635 } 1635 }
1636 } else { 1636 } else {
1637 if ( isReadOnly() || !( e->state() & ShiftButton ) ) { 1637 if ( isReadOnly() || !( e->state() & ShiftButton ) ) {
1638 doc->setSelectionStart( QTextDocument::Standard, *cursor ); 1638 doc->setSelectionStart( QTextDocument::Standard, *cursor );
1639 } else { 1639 } else {
1640 doc->setSelectionStart( QTextDocument::Standard, c ); 1640 doc->setSelectionStart( QTextDocument::Standard, c );
1641 redraw = doc->setSelectionEnd( QTextDocument::Standard, *cursor ) || redraw; 1641 redraw = doc->setSelectionEnd( QTextDocument::Standard, *cursor ) || redraw;
1642 } 1642 }
1643 } 1643 }
1644 1644
1645 for ( int i = 1; i < doc->numSelections(); ++i ) // start with 1 as we don't want to remove the Standard-Selection 1645 for ( int i = 1; i < doc->numSelections(); ++i ) // start with 1 as we don't want to remove the Standard-Selection
1646 redraw = doc->removeSelection( i ) || redraw; 1646 redraw = doc->removeSelection( i ) || redraw;
1647 1647
1648 if ( !redraw ) { 1648 if ( !redraw ) {
1649 drawCursor( TRUE ); 1649 drawCursor( TRUE );
1650 } else { 1650 } else {
1651 repaintChanged(); 1651 repaintChanged();
1652#ifndef QT_NO_CURSOR 1652#ifndef QT_NO_CURSOR
1653 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 1653 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
1654#endif 1654#endif
1655 } 1655 }
1656 } else if ( e->button() == MidButton ) { 1656 } else if ( e->button() == MidButton ) {
1657 bool redraw = doc->removeSelection( QTextDocument::Standard ); 1657 bool redraw = doc->removeSelection( QTextDocument::Standard );
1658 if ( !redraw ) { 1658 if ( !redraw ) {
1659 drawCursor( TRUE ); 1659 drawCursor( TRUE );
1660 } else { 1660 } else {
1661 repaintChanged(); 1661 repaintChanged();
1662#ifndef QT_NO_CURSOR 1662#ifndef QT_NO_CURSOR
1663 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 1663 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
1664#endif 1664#endif
1665 } 1665 }
1666 } 1666 }
1667 1667
1668 if ( *cursor != oldCursor ) 1668 if ( *cursor != oldCursor )
1669 updateCurrentFormat(); 1669 updateCurrentFormat();
1670} 1670}
1671 1671
1672/*! \reimp */ 1672/*! \reimp */
1673 1673
1674void QTextEdit::contentsMouseMoveEvent( QMouseEvent *e ) 1674void QTextEdit::contentsMouseMoveEvent( QMouseEvent *e )
1675{ 1675{
1676 if ( mousePressed ) { 1676 if ( mousePressed ) {
1677#ifndef QT_NO_DRAGANDDROP 1677#ifndef QT_NO_DRAGANDDROP
1678 if ( mightStartDrag ) { 1678 if ( mightStartDrag ) {
1679 dragStartTimer->stop(); 1679 dragStartTimer->stop();
1680 if ( ( e->pos() - dragStartPos ).manhattanLength() > QApplication::startDragDistance() ) 1680 if ( ( e->pos() - dragStartPos ).manhattanLength() > QApplication::startDragDistance() )
1681 startDrag(); 1681 startDrag();
1682#ifndef QT_NO_CURSOR 1682#ifndef QT_NO_CURSOR
1683 if ( !isReadOnly() ) 1683 if ( !isReadOnly() )
1684 viewport()->setCursor( ibeamCursor ); 1684 viewport()->setCursor( ibeamCursor );
1685#endif 1685#endif
1686 return; 1686 return;
1687 } 1687 }
1688#endif 1688#endif
1689 mousePos = e->pos(); 1689 mousePos = e->pos();
1690 handleMouseMove( mousePos ); 1690 handleMouseMove( mousePos );
1691 oldMousePos = mousePos; 1691 oldMousePos = mousePos;
1692 } 1692 }
1693 1693
1694#ifndef QT_NO_CURSOR 1694#ifndef QT_NO_CURSOR
1695 if ( !isReadOnly() && !mousePressed ) { 1695 if ( !isReadOnly() && !mousePressed ) {
1696 if ( doc->hasSelection( QTextDocument::Standard ) && doc->inSelection( QTextDocument::Standard, e->pos() ) ) 1696 if ( doc->hasSelection( QTextDocument::Standard ) && doc->inSelection( QTextDocument::Standard, e->pos() ) )
1697 viewport()->setCursor( arrowCursor ); 1697 viewport()->setCursor( arrowCursor );
1698 else 1698 else
1699 viewport()->setCursor( ibeamCursor ); 1699 viewport()->setCursor( ibeamCursor );
1700 } 1700 }
1701#endif 1701#endif
1702 updateCursor( e->pos() ); 1702 updateCursor( e->pos() );
1703} 1703}
1704 1704
1705/*! \reimp */ 1705/*! \reimp */
1706 1706
1707void QTextEdit::contentsMouseReleaseEvent( QMouseEvent * e ) 1707void QTextEdit::contentsMouseReleaseEvent( QMouseEvent * e )
1708{ 1708{
1709 QTextCursor oldCursor = *cursor; 1709 QTextCursor oldCursor = *cursor;
1710 if ( scrollTimer->isActive() ) 1710 if ( scrollTimer->isActive() )
1711 scrollTimer->stop(); 1711 scrollTimer->stop();
1712#ifndef QT_NO_DRAGANDDROP 1712#ifndef QT_NO_DRAGANDDROP
1713 if ( dragStartTimer->isActive() ) 1713 if ( dragStartTimer->isActive() )
1714 dragStartTimer->stop(); 1714 dragStartTimer->stop();
1715 if ( mightStartDrag ) { 1715 if ( mightStartDrag ) {
1716 selectAll( FALSE ); 1716 selectAll( FALSE );
1717 mousePressed = FALSE; 1717 mousePressed = FALSE;
1718 } 1718 }
1719#endif 1719#endif
1720 if ( mousePressed ) { 1720 if ( mousePressed ) {
1721 mousePressed = FALSE; 1721 mousePressed = FALSE;
1722 } 1722 }
1723 emit cursorPositionChanged( cursor ); 1723 emit cursorPositionChanged( cursor );
1724 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() ); 1724 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() );
1725 if ( oldCursor != *cursor ) 1725 if ( oldCursor != *cursor )
1726 updateCurrentFormat(); 1726 updateCurrentFormat();
1727 inDoubleClick = FALSE; 1727 inDoubleClick = FALSE;
1728 1728
1729#ifndef QT_NO_NETWORKPROTOCOL 1729#ifndef QT_NO_NETWORKPROTOCOL
1730 if ( !onLink.isEmpty() && onLink == pressedLink && linksEnabled() ) { 1730 if ( !onLink.isEmpty() && onLink == pressedLink && linksEnabled() ) {
1731 QUrl u( doc->context(), onLink, TRUE ); 1731 QUrl u( doc->context(), onLink, TRUE );
1732 emitLinkClicked( u.toString( FALSE, FALSE ) ); 1732 emitLinkClicked( u.toString( FALSE, FALSE ) );
1733 1733
1734 // emitting linkClicked() may result in that the cursor winds 1734 // emitting linkClicked() may result in that the cursor winds
1735 // up hovering over a different valid link - check this and 1735 // up hovering over a different valid link - check this and
1736 // set the appropriate cursor shape 1736 // set the appropriate cursor shape
1737 updateCursor( e->pos() ); 1737 updateCursor( e->pos() );
1738 } 1738 }
1739#endif 1739#endif
1740 drawCursor( TRUE ); 1740 drawCursor( TRUE );
1741 if ( !doc->hasSelection( QTextDocument::Standard, TRUE ) ) 1741 if ( !doc->hasSelection( QTextDocument::Standard, TRUE ) )
1742 doc->removeSelection( QTextDocument::Standard ); 1742 doc->removeSelection( QTextDocument::Standard );
1743 1743
1744 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) ); 1744 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) );
1745 emit selectionChanged(); 1745 emit selectionChanged();
1746} 1746}
1747 1747
1748/*! \reimp */ 1748/*! \reimp */
1749 1749
1750void QTextEdit::contentsMouseDoubleClickEvent( QMouseEvent * ) 1750void QTextEdit::contentsMouseDoubleClickEvent( QMouseEvent * )
1751{ 1751{
1752 QTextCursor c1 = *cursor; 1752 QTextCursor c1 = *cursor;
1753 QTextCursor c2 = *cursor; 1753 QTextCursor c2 = *cursor;
1754 if ( cursor->index() > 0 && !cursor->paragraph()->at( cursor->index()-1 )->c.isSpace() ) 1754 if ( cursor->index() > 0 && !cursor->paragraph()->at( cursor->index()-1 )->c.isSpace() )
1755 c1.gotoPreviousWord(); 1755 c1.gotoPreviousWord();
1756 if ( !cursor->paragraph()->at( cursor->index() )->c.isSpace() && !cursor->atParagEnd() ) 1756 if ( !cursor->paragraph()->at( cursor->index() )->c.isSpace() && !cursor->atParagEnd() )
1757 c2.gotoNextWord(); 1757 c2.gotoNextWord();
1758 1758
1759 doc->setSelectionStart( QTextDocument::Standard, c1 ); 1759 doc->setSelectionStart( QTextDocument::Standard, c1 );
1760 doc->setSelectionEnd( QTextDocument::Standard, c2 ); 1760 doc->setSelectionEnd( QTextDocument::Standard, c2 );
1761 1761
1762 *cursor = c2; 1762 *cursor = c2;
1763 1763
1764 repaintChanged(); 1764 repaintChanged();
1765 1765
1766 inDoubleClick = TRUE; 1766 inDoubleClick = TRUE;
1767 mousePressed = TRUE; 1767 mousePressed = TRUE;
1768} 1768}
1769 1769
1770#ifndef QT_NO_DRAGANDDROP 1770#ifndef QT_NO_DRAGANDDROP
1771 1771
1772/*! \reimp */ 1772/*! \reimp */
1773 1773
1774void QTextEdit::contentsDragEnterEvent( QDragEnterEvent *e ) 1774void QTextEdit::contentsDragEnterEvent( QDragEnterEvent *e )
1775{ 1775{
1776 if ( isReadOnly() || !QTextDrag::canDecode( e ) ) { 1776 if ( isReadOnly() || !QTextDrag::canDecode( e ) ) {
1777 e->ignore(); 1777 e->ignore();
1778 return; 1778 return;
1779 } 1779 }
1780 e->acceptAction(); 1780 e->acceptAction();
1781 inDnD = TRUE; 1781 inDnD = TRUE;
1782} 1782}
1783 1783
1784/*! \reimp */ 1784/*! \reimp */
1785 1785
1786void QTextEdit::contentsDragMoveEvent( QDragMoveEvent *e ) 1786void QTextEdit::contentsDragMoveEvent( QDragMoveEvent *e )
1787{ 1787{
1788 if ( isReadOnly() || !QTextDrag::canDecode( e ) ) { 1788 if ( isReadOnly() || !QTextDrag::canDecode( e ) ) {
1789 e->ignore(); 1789 e->ignore();
1790 return; 1790 return;
1791 } 1791 }
1792 drawCursor( FALSE ); 1792 drawCursor( FALSE );
1793 placeCursor( e->pos(), cursor ); 1793 placeCursor( e->pos(), cursor );
1794 drawCursor( TRUE ); 1794 drawCursor( TRUE );
1795 e->acceptAction(); 1795 e->acceptAction();
1796} 1796}
1797 1797
1798/*! \reimp */ 1798/*! \reimp */
1799 1799
1800void QTextEdit::contentsDragLeaveEvent( QDragLeaveEvent * ) 1800void QTextEdit::contentsDragLeaveEvent( QDragLeaveEvent * )
1801{ 1801{
1802 inDnD = FALSE; 1802 inDnD = FALSE;
1803} 1803}
1804 1804
1805/*! \reimp */ 1805/*! \reimp */
1806 1806
1807void QTextEdit::contentsDropEvent( QDropEvent *e ) 1807void QTextEdit::contentsDropEvent( QDropEvent *e )
1808{ 1808{
1809 if ( isReadOnly() ) 1809 if ( isReadOnly() )
1810 return; 1810 return;
1811 inDnD = FALSE; 1811 inDnD = FALSE;
1812 e->acceptAction(); 1812 e->acceptAction();
1813 QString text; 1813 QString text;
1814 bool intern = FALSE; 1814 bool intern = FALSE;
1815 if ( QTextDrag::decode( e, text ) ) { 1815 if ( QTextDrag::decode( e, text ) ) {
1816 bool hasSel = doc->hasSelection( QTextDocument::Standard ); 1816 bool hasSel = doc->hasSelection( QTextDocument::Standard );
1817 bool internalDrag = e->source() == this || e->source() == viewport(); 1817 bool internalDrag = e->source() == this || e->source() == viewport();
1818 int dropId, dropIndex; 1818 int dropId, dropIndex;
1819 QTextCursor insertCursor = *cursor; 1819 QTextCursor insertCursor = *cursor;
1820 dropId = cursor->paragraph()->paragId(); 1820 dropId = cursor->paragraph()->paragId();
1821 dropIndex = cursor->index(); 1821 dropIndex = cursor->index();
1822 if ( hasSel && internalDrag ) { 1822 if ( hasSel && internalDrag ) {
1823 QTextCursor c1, c2; 1823 QTextCursor c1, c2;
1824 int selStartId, selStartIndex; 1824 int selStartId, selStartIndex;
1825 int selEndId, selEndIndex; 1825 int selEndId, selEndIndex;
1826 c1 = doc->selectionStartCursor( QTextDocument::Standard ); 1826 c1 = doc->selectionStartCursor( QTextDocument::Standard );
1827 c1.restoreState(); 1827 c1.restoreState();
1828 c2 = doc->selectionEndCursor( QTextDocument::Standard ); 1828 c2 = doc->selectionEndCursor( QTextDocument::Standard );
1829 c2.restoreState(); 1829 c2.restoreState();
1830 selStartId = c1.paragraph()->paragId(); 1830 selStartId = c1.paragraph()->paragId();
1831 selStartIndex = c1.index(); 1831 selStartIndex = c1.index();
1832 selEndId = c2.paragraph()->paragId(); 1832 selEndId = c2.paragraph()->paragId();
1833 selEndIndex = c2.index(); 1833 selEndIndex = c2.index();
1834 if ( ( ( dropId > selStartId ) || 1834 if ( ( ( dropId > selStartId ) ||
1835 ( dropId == selStartId && dropIndex > selStartIndex ) ) && 1835 ( dropId == selStartId && dropIndex > selStartIndex ) ) &&
1836 ( ( dropId < selEndId ) || 1836 ( ( dropId < selEndId ) ||
1837 ( dropId == selEndId && dropIndex <= selEndIndex ) ) ) 1837 ( dropId == selEndId && dropIndex <= selEndIndex ) ) )
1838 insertCursor = c1; 1838 insertCursor = c1;
1839 if ( dropId == selEndId && dropIndex > selEndIndex ) { 1839 if ( dropId == selEndId && dropIndex > selEndIndex ) {
1840 insertCursor = c1; 1840 insertCursor = c1;
1841 if ( selStartId == selEndId ) { 1841 if ( selStartId == selEndId ) {
1842 insertCursor.setIndex( dropIndex - 1842 insertCursor.setIndex( dropIndex -
1843 ( selEndIndex - selStartIndex ) ); 1843 ( selEndIndex - selStartIndex ) );
1844 } else { 1844 } else {
1845 insertCursor.setIndex( dropIndex - selEndIndex + 1845 insertCursor.setIndex( dropIndex - selEndIndex +
1846 selStartIndex ); 1846 selStartIndex );
1847 } 1847 }
1848 } 1848 }
1849 } 1849 }
1850 1850
1851 if ( internalDrag && e->action() == QDropEvent::Move ) { 1851 if ( internalDrag && e->action() == QDropEvent::Move ) {
1852 removeSelectedText(); 1852 removeSelectedText();
1853 intern = TRUE; 1853 intern = TRUE;
1854 } else { 1854 } else {
1855 doc->removeSelection( QTextDocument::Standard ); 1855 doc->removeSelection( QTextDocument::Standard );
1856#ifndef QT_NO_CURSOR 1856#ifndef QT_NO_CURSOR
1857 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 1857 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
1858#endif 1858#endif
1859 } 1859 }
1860 drawCursor( FALSE ); 1860 drawCursor( FALSE );
1861 cursor->setParagraph( insertCursor.paragraph() ); 1861 cursor->setParagraph( insertCursor.paragraph() );
1862 cursor->setIndex( insertCursor.index() ); 1862 cursor->setIndex( insertCursor.index() );
1863 drawCursor( TRUE ); 1863 drawCursor( TRUE );
1864 if ( !cursor->nestedDepth() ) { 1864 if ( !cursor->nestedDepth() ) {
1865 insert( text, FALSE, TRUE, FALSE ); 1865 insert( text, FALSE, TRUE, FALSE );
1866 } else { 1866 } else {
1867 if ( intern ) 1867 if ( intern )
1868 undo(); 1868 undo();
1869 e->ignore(); 1869 e->ignore();
1870 } 1870 }
1871 } 1871 }
1872} 1872}
1873 1873
1874#endif 1874#endif
1875 1875
1876void QTextEdit::autoScrollTimerDone() 1876void QTextEdit::autoScrollTimerDone()
1877{ 1877{
1878 if ( mousePressed ) 1878 if ( mousePressed )
1879 handleMouseMove( viewportToContents( viewport()->mapFromGlobal( QCursor::pos() ) ) ); 1879 handleMouseMove( viewportToContents( viewport()->mapFromGlobal( QCursor::pos() ) ) );
1880} 1880}
1881 1881
1882void QTextEdit::handleMouseMove( const QPoint& pos ) 1882void QTextEdit::handleMouseMove( const QPoint& pos )
1883{ 1883{
1884 if ( !mousePressed ) 1884 if ( !mousePressed )
1885 return; 1885 return;
1886 1886
1887 if ( !scrollTimer->isActive() && pos.y() < contentsY() || pos.y() > contentsY() + visibleHeight() ) 1887 if ( !scrollTimer->isActive() && pos.y() < contentsY() || pos.y() > contentsY() + visibleHeight() )
1888 scrollTimer->start( 100, FALSE ); 1888 scrollTimer->start( 100, FALSE );
1889 else if ( scrollTimer->isActive() && pos.y() >= contentsY() && pos.y() <= contentsY() + visibleHeight() ) 1889 else if ( scrollTimer->isActive() && pos.y() >= contentsY() && pos.y() <= contentsY() + visibleHeight() )
1890 scrollTimer->stop(); 1890 scrollTimer->stop();
1891 1891
1892 drawCursor( FALSE ); 1892 drawCursor( FALSE );
1893 QTextCursor oldCursor = *cursor; 1893 QTextCursor oldCursor = *cursor;
1894 1894
1895 placeCursor( pos ); 1895 placeCursor( pos );
1896 1896
1897 if ( inDoubleClick ) { 1897 if ( inDoubleClick ) {
1898 QTextCursor cl = *cursor; 1898 QTextCursor cl = *cursor;
1899 cl.gotoPreviousWord(); 1899 cl.gotoPreviousWord();
1900 QTextCursor cr = *cursor; 1900 QTextCursor cr = *cursor;
1901 cr.gotoNextWord(); 1901 cr.gotoNextWord();
1902 1902
1903 int diff = QABS( oldCursor.paragraph()->at( oldCursor.index() )->x - mousePos.x() ); 1903 int diff = QABS( oldCursor.paragraph()->at( oldCursor.index() )->x - mousePos.x() );
1904 int ldiff = QABS( cl.paragraph()->at( cl.index() )->x - mousePos.x() ); 1904 int ldiff = QABS( cl.paragraph()->at( cl.index() )->x - mousePos.x() );
1905 int rdiff = QABS( cr.paragraph()->at( cr.index() )->x - mousePos.x() ); 1905 int rdiff = QABS( cr.paragraph()->at( cr.index() )->x - mousePos.x() );
1906 1906
1907 1907
1908 if ( cursor->paragraph()->lineStartOfChar( cursor->index() ) != 1908 if ( cursor->paragraph()->lineStartOfChar( cursor->index() ) !=
1909 oldCursor.paragraph()->lineStartOfChar( oldCursor.index() ) ) 1909 oldCursor.paragraph()->lineStartOfChar( oldCursor.index() ) )
1910 diff = 0xFFFFFF; 1910 diff = 0xFFFFFF;
1911 1911
1912 if ( rdiff < diff && rdiff < ldiff ) 1912 if ( rdiff < diff && rdiff < ldiff )
1913 *cursor = cr; 1913 *cursor = cr;
1914 else if ( ldiff < diff && ldiff < rdiff ) 1914 else if ( ldiff < diff && ldiff < rdiff )
1915 *cursor = cl; 1915 *cursor = cl;
1916 else 1916 else
1917 *cursor = oldCursor; 1917 *cursor = oldCursor;
1918 1918
1919 } 1919 }
1920 ensureCursorVisible(); 1920 ensureCursorVisible();
1921 1921
1922 bool redraw = FALSE; 1922 bool redraw = FALSE;
1923 if ( doc->hasSelection( QTextDocument::Standard ) ) { 1923 if ( doc->hasSelection( QTextDocument::Standard ) ) {
1924 redraw = doc->setSelectionEnd( QTextDocument::Standard, *cursor ) || redraw; 1924 redraw = doc->setSelectionEnd( QTextDocument::Standard, *cursor ) || redraw;
1925 } 1925 }
1926 1926
1927 if ( !redraw ) { 1927 if ( !redraw ) {
1928 drawCursor( TRUE ); 1928 drawCursor( TRUE );
1929 } else { 1929 } else {
1930 repaintChanged(); 1930 repaintChanged();
1931 drawCursor( TRUE ); 1931 drawCursor( TRUE );
1932 } 1932 }
1933 1933
1934 if ( currentFormat && currentFormat->key() != cursor->paragraph()->at( cursor->index() )->format()->key() ) { 1934 if ( currentFormat && currentFormat->key() != cursor->paragraph()->at( cursor->index() )->format()->key() ) {
1935 currentFormat->removeRef(); 1935 currentFormat->removeRef();
1936 currentFormat = doc->formatCollection()->format( cursor->paragraph()->at( cursor->index() )->format() ); 1936 currentFormat = doc->formatCollection()->format( cursor->paragraph()->at( cursor->index() )->format() );
1937 if ( currentFormat->isMisspelled() ) { 1937 if ( currentFormat->isMisspelled() ) {
1938 currentFormat->removeRef(); 1938 currentFormat->removeRef();
1939 currentFormat = doc->formatCollection()->format( currentFormat->font(), currentFormat->color() ); 1939 currentFormat = doc->formatCollection()->format( currentFormat->font(), currentFormat->color() );
1940 } 1940 }
1941 emit currentFontChanged( currentFormat->font() ); 1941 emit currentFontChanged( currentFormat->font() );
1942 emit currentColorChanged( currentFormat->color() ); 1942 emit currentColorChanged( currentFormat->color() );
1943 emit currentVerticalAlignmentChanged( (VerticalAlignment)currentFormat->vAlign() ); 1943 emit currentVerticalAlignmentChanged( (VerticalAlignment)currentFormat->vAlign() );
1944 } 1944 }
1945 1945
1946 if ( currentAlignment != cursor->paragraph()->alignment() ) { 1946 if ( currentAlignment != cursor->paragraph()->alignment() ) {
1947 currentAlignment = cursor->paragraph()->alignment(); 1947 currentAlignment = cursor->paragraph()->alignment();
1948 block_set_alignment = TRUE; 1948 block_set_alignment = TRUE;
1949 emit currentAlignmentChanged( currentAlignment ); 1949 emit currentAlignmentChanged( currentAlignment );
1950 block_set_alignment = FALSE; 1950 block_set_alignment = FALSE;
1951 } 1951 }
1952} 1952}
1953 1953
1954/*! 1954/*!
1955 \fn void QTextEdit::placeCursor( const QPoint &pos, QTextCursor *c ) 1955 \fn void QTextEdit::placeCursor( const QPoint &pos, QTextCursor *c )
1956 Places the cursor \a c at the character which is closest to position 1956 Places the cursor \a c at the character which is closest to position
1957 \a pos (in contents coordinates). If \a c is 0, the default text 1957 \a pos (in contents coordinates). If \a c is 0, the default text
1958 cursor is used. 1958 cursor is used.
1959 1959
1960 \sa setCursorPosition() 1960 \sa setCursorPosition()
1961*/ 1961*/
1962 1962
1963void QTextEdit::placeCursor( const QPoint &pos, QTextCursor *c, bool link ) 1963void QTextEdit::placeCursor( const QPoint &pos, QTextCursor *c, bool link )
1964{ 1964{
1965 if ( !c ) 1965 if ( !c )
1966 c = cursor; 1966 c = cursor;
1967 1967
1968 c->restoreState(); 1968 c->restoreState();
1969 QTextParagraph *s = doc->firstParagraph(); 1969 QTextParagraph *s = doc->firstParagraph();
1970 c->place( pos, s, link ); 1970 c->place( pos, s, link );
1971 updateMicroFocusHint(); 1971 updateMicroFocusHint();
1972} 1972}
1973 1973
1974 1974
1975void QTextEdit::updateMicroFocusHint() 1975void QTextEdit::updateMicroFocusHint()
1976{ 1976{
1977 QTextCursor c( *cursor ); 1977 QTextCursor c( *cursor );
1978 if ( d->preeditStart != -1 ) 1978 if ( d->preeditStart != -1 )
1979 c.setIndex( d->preeditStart ); 1979 c.setIndex( d->preeditStart );
1980 1980
1981 if ( hasFocus() || viewport()->hasFocus() ) { 1981 if ( hasFocus() || viewport()->hasFocus() ) {
1982 int h = c.paragraph()->lineHeightOfChar( cursor->index() ); 1982 int h = c.paragraph()->lineHeightOfChar( cursor->index() );
1983 if ( !readonly ) { 1983 if ( !readonly ) {
1984 QFont f = c.paragraph()->at( c.index() )->format()->font(); 1984 QFont f = c.paragraph()->at( c.index() )->format()->font();
1985 setMicroFocusHint( c.x() - contentsX() + frameWidth(), 1985 setMicroFocusHint( c.x() - contentsX() + frameWidth(),
1986 c.y() + cursor->paragraph()->rect().y() - contentsY() + frameWidth(), 0, h, TRUE ); 1986 c.y() + cursor->paragraph()->rect().y() - contentsY() + frameWidth(), 0, h, TRUE );
1987 } 1987 }
1988 } 1988 }
1989} 1989}
1990 1990
1991 1991
1992 1992
1993void QTextEdit::formatMore() 1993void QTextEdit::formatMore()
1994{ 1994{
1995 if ( !lastFormatted ) 1995 if ( !lastFormatted )
1996 return; 1996 return;
1997 1997
1998 int bottom = contentsHeight(); 1998 int bottom = contentsHeight();
1999 int lastBottom = -1; 1999 int lastBottom = -1;
2000 int to = 20; 2000 int to = 20;
2001 bool firstVisible = FALSE; 2001 bool firstVisible = FALSE;
2002 QRect cr( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 2002 QRect cr( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
2003 for ( int i = 0; ( i < to || firstVisible ) && lastFormatted; ++i ) { 2003 for ( int i = 0; ( i < to || firstVisible ) && lastFormatted; ++i ) {
2004 lastFormatted->format(); 2004 lastFormatted->format();
2005 if ( i == 0 ) 2005 if ( i == 0 )
2006 firstVisible = lastFormatted->rect().intersects( cr ); 2006 firstVisible = lastFormatted->rect().intersects( cr );
2007 else if ( firstVisible ) 2007 else if ( firstVisible )
2008 firstVisible = lastFormatted->rect().intersects( cr ); 2008 firstVisible = lastFormatted->rect().intersects( cr );
2009 bottom = QMAX( bottom, lastFormatted->rect().top() + 2009 bottom = QMAX( bottom, lastFormatted->rect().top() +
2010 lastFormatted->rect().height() ); 2010 lastFormatted->rect().height() );
2011 lastBottom = lastFormatted->rect().top() + lastFormatted->rect().height(); 2011 lastBottom = lastFormatted->rect().top() + lastFormatted->rect().height();
2012 lastFormatted = lastFormatted->next(); 2012 lastFormatted = lastFormatted->next();
2013 if ( lastFormatted ) 2013 if ( lastFormatted )
2014 lastBottom = -1; 2014 lastBottom = -1;
2015 } 2015 }
2016 2016
2017 if ( bottom > contentsHeight() ) { 2017 if ( bottom > contentsHeight() ) {
2018 resizeContents( contentsWidth(), QMAX( doc->height(), bottom ) ); 2018 resizeContents( contentsWidth(), QMAX( doc->height(), bottom ) );
2019 } else if ( lastBottom != -1 && lastBottom < contentsHeight() ) { 2019 } else if ( lastBottom != -1 && lastBottom < contentsHeight() ) {
2020 resizeContents( contentsWidth(), QMAX( doc->height(), lastBottom ) ); 2020 resizeContents( contentsWidth(), QMAX( doc->height(), lastBottom ) );
2021 if ( contentsHeight() < visibleHeight() ) 2021 if ( contentsHeight() < visibleHeight() )
2022 updateContents( 0, contentsHeight(), visibleWidth(), 2022 updateContents( 0, contentsHeight(), visibleWidth(),
2023 visibleHeight() - contentsHeight() ); 2023 visibleHeight() - contentsHeight() );
2024 } 2024 }
2025 2025
2026 if ( lastFormatted ) 2026 if ( lastFormatted )
2027 formatTimer->start( interval, TRUE ); 2027 formatTimer->start( interval, TRUE );
2028 else 2028 else
2029 interval = QMAX( 0, interval ); 2029 interval = QMAX( 0, interval );
2030} 2030}
2031 2031
2032void QTextEdit::doResize() 2032void QTextEdit::doResize()
2033{ 2033{
2034 if ( wrapMode == FixedPixelWidth ) 2034 if ( wrapMode == FixedPixelWidth )
2035 return; 2035 return;
2036 doc->setMinimumWidth( -1 ); 2036 doc->setMinimumWidth( -1 );
2037 resizeContents( 0, 0 ); 2037 resizeContents( 0, 0 );
2038 doc->setWidth( visibleWidth() ); 2038 doc->setWidth( visibleWidth() );
2039 doc->invalidate(); 2039 doc->invalidate();
2040 lastFormatted = doc->firstParagraph(); 2040 lastFormatted = doc->firstParagraph();
2041 interval = 0; 2041 interval = 0;
2042 formatMore(); 2042 formatMore();
2043 repaintContents( contentsX(), contentsY(), visibleWidth(), visibleHeight(), FALSE ); 2043 repaintContents( contentsX(), contentsY(), visibleWidth(), visibleHeight(), FALSE );
2044} 2044}
2045 2045
2046/*! \internal */ 2046/*! \internal */
2047 2047
2048void QTextEdit::doChangeInterval() 2048void QTextEdit::doChangeInterval()
2049{ 2049{
2050 interval = 0; 2050 interval = 0;
2051} 2051}
2052 2052
2053/*! \reimp */ 2053/*! \reimp */
2054 2054
2055bool QTextEdit::eventFilter( QObject *o, QEvent *e ) 2055bool QTextEdit::eventFilter( QObject *o, QEvent *e )
2056{ 2056{
2057 if ( o == this || o == viewport() ) { 2057 if ( o == this || o == viewport() ) {
2058 if ( e->type() == QEvent::FocusIn ) { 2058 if ( e->type() == QEvent::FocusIn ) {
2059 blinkTimer->start( QApplication::cursorFlashTime() / 2 ); 2059 blinkTimer->start( QApplication::cursorFlashTime() / 2 );
2060 drawCursor( TRUE ); 2060 drawCursor( TRUE );
2061 updateMicroFocusHint(); 2061 updateMicroFocusHint();
2062 } else if ( e->type() == QEvent::FocusOut ) { 2062 } else if ( e->type() == QEvent::FocusOut ) {
2063 blinkTimer->stop(); 2063 blinkTimer->stop();
2064 drawCursor( FALSE ); 2064 drawCursor( FALSE );
2065 } 2065 }
2066 } 2066 }
2067 2067
2068 return QScrollView::eventFilter( o, e ); 2068 return QScrollView::eventFilter( o, e );
2069} 2069}
2070 2070
2071/*! Inserts \a text at the current cursor position. If \a indent is 2071/*! Inserts \a text at the current cursor position. If \a indent is
2072 TRUE, the paragraph is re-indented. If \a checkNewLine is TRUE, 2072 TRUE, the paragraph is re-indented. If \a checkNewLine is TRUE,
2073 newline characters in \a text result in hard line breaks (i.e. new 2073 newline characters in \a text result in hard line breaks (i.e. new
2074 paragraphs). If \a checkNewLine is FALSE and there are newlines in 2074 paragraphs). If \a checkNewLine is FALSE and there are newlines in
2075 \a text, the behavior is undefined. If \a checkNewLine is FALSE the 2075 \a text, the behavior is undefined. If \a checkNewLine is FALSE the
2076 behaviour of the editor is undefined if the \a text contains 2076 behaviour of the editor is undefined if the \a text contains
2077 newlines. If \a removeSelected is TRUE, any selected text (in 2077 newlines. If \a removeSelected is TRUE, any selected text (in
2078 selection 0) is removed before the text is inserted. 2078 selection 0) is removed before the text is inserted.
2079 2079
2080 \sa paste() pasteSubType() 2080 \sa paste() pasteSubType()
2081*/ 2081*/
2082 2082
2083void QTextEdit::insert( const QString &text, bool indent, bool checkNewLine, bool removeSelected ) 2083void QTextEdit::insert( const QString &text, bool indent, bool checkNewLine, bool removeSelected )
2084{ 2084{
2085 if ( cursor->nestedDepth() != 0 ) // #### for 3.0, disable editing of tables as this is not advanced enough 2085 if ( cursor->nestedDepth() != 0 ) // #### for 3.0, disable editing of tables as this is not advanced enough
2086 return; 2086 return;
2087 QString txt( text ); 2087 QString txt( text );
2088 drawCursor( FALSE ); 2088 drawCursor( FALSE );
2089 if ( !isReadOnly() && doc->hasSelection( QTextDocument::Standard ) && removeSelected ) 2089 if ( !isReadOnly() && doc->hasSelection( QTextDocument::Standard ) && removeSelected )
2090 removeSelectedText(); 2090 removeSelectedText();
2091 QTextCursor c2 = *cursor; 2091 QTextCursor c2 = *cursor;
2092 int oldLen = 0; 2092 int oldLen = 0;
2093 2093
2094 if ( undoEnabled && !isReadOnly() ) { 2094 if ( undoEnabled && !isReadOnly() ) {
2095 checkUndoRedoInfo( UndoRedoInfo::Insert ); 2095 checkUndoRedoInfo( UndoRedoInfo::Insert );
2096 if ( !undoRedoInfo.valid() ) { 2096 if ( !undoRedoInfo.valid() ) {
2097 undoRedoInfo.id = cursor->paragraph()->paragId(); 2097 undoRedoInfo.id = cursor->paragraph()->paragId();
2098 undoRedoInfo.index = cursor->index(); 2098 undoRedoInfo.index = cursor->index();
2099 undoRedoInfo.d->text = QString::null; 2099 undoRedoInfo.d->text = QString::null;
2100 } 2100 }
2101 oldLen = undoRedoInfo.d->text.length(); 2101 oldLen = undoRedoInfo.d->text.length();
2102 } 2102 }
2103 2103
2104 lastFormatted = checkNewLine && cursor->paragraph()->prev() ? 2104 lastFormatted = checkNewLine && cursor->paragraph()->prev() ?
2105 cursor->paragraph()->prev() : cursor->paragraph(); 2105 cursor->paragraph()->prev() : cursor->paragraph();
2106 QTextCursor oldCursor = *cursor; 2106 QTextCursor oldCursor = *cursor;
2107 cursor->insert( txt, checkNewLine ); 2107 cursor->insert( txt, checkNewLine );
2108 if ( doc->useFormatCollection() ) { 2108 if ( doc->useFormatCollection() ) {
2109 doc->setSelectionStart( QTextDocument::Temp, oldCursor ); 2109 doc->setSelectionStart( QTextDocument::Temp, oldCursor );
2110 doc->setSelectionEnd( QTextDocument::Temp, *cursor ); 2110 doc->setSelectionEnd( QTextDocument::Temp, *cursor );
2111 doc->setFormat( QTextDocument::Temp, currentFormat, QTextFormat::Format ); 2111 doc->setFormat( QTextDocument::Temp, currentFormat, QTextFormat::Format );
2112 doc->removeSelection( QTextDocument::Temp ); 2112 doc->removeSelection( QTextDocument::Temp );
2113 } 2113 }
2114 2114
2115 if ( indent && ( txt == "{" || txt == "}" || txt == ":" || txt == "#" ) ) 2115 if ( indent && ( txt == "{" || txt == "}" || txt == ":" || txt == "#" ) )
2116 cursor->indent(); 2116 cursor->indent();
2117 formatMore(); 2117 formatMore();
2118 repaintChanged(); 2118 repaintChanged();
2119 ensureCursorVisible(); 2119 ensureCursorVisible();
2120 drawCursor( TRUE ); 2120 drawCursor( TRUE );
2121 2121
2122 if ( undoEnabled && !isReadOnly() ) { 2122 if ( undoEnabled && !isReadOnly() ) {
2123 undoRedoInfo.d->text += txt; 2123 undoRedoInfo.d->text += txt;
2124 if ( !doc->preProcessor() ) { 2124 if ( !doc->preProcessor() ) {
2125 for ( int i = 0; i < (int)txt.length(); ++i ) { 2125 for ( int i = 0; i < (int)txt.length(); ++i ) {
2126 if ( txt[ i ] != '\n' && c2.paragraph()->at( c2.index() )->format() ) { 2126 if ( txt[ i ] != '\n' && c2.paragraph()->at( c2.index() )->format() ) {
2127 c2.paragraph()->at( c2.index() )->format()->addRef(); 2127 c2.paragraph()->at( c2.index() )->format()->addRef();
2128 undoRedoInfo.d->text.setFormat( oldLen + i, c2.paragraph()->at( c2.index() )->format(), TRUE ); 2128 undoRedoInfo.d->text.setFormat( oldLen + i, c2.paragraph()->at( c2.index() )->format(), TRUE );
2129 } 2129 }
2130 c2.gotoNextLetter(); 2130 c2.gotoNextLetter();
2131 } 2131 }
2132 } 2132 }
2133 } 2133 }
2134 2134
2135 if ( !removeSelected ) { 2135 if ( !removeSelected ) {
2136 doc->setSelectionStart( QTextDocument::Standard, oldCursor ); 2136 doc->setSelectionStart( QTextDocument::Standard, oldCursor );
2137 doc->setSelectionEnd( QTextDocument::Standard, *cursor ); 2137 doc->setSelectionEnd( QTextDocument::Standard, *cursor );
2138 repaintChanged(); 2138 repaintChanged();
2139 } 2139 }
2140 updateMicroFocusHint(); 2140 updateMicroFocusHint();
2141 setModified(); 2141 setModified();
2142 emit textChanged(); 2142 emit textChanged();
2143} 2143}
2144 2144
2145/*! Inserts \a text in the paragraph \a para and position \a index */ 2145/*! Inserts \a text in the paragraph \a para and position \a index */
2146 2146
2147void QTextEdit::insertAt( const QString &text, int para, int index ) 2147void QTextEdit::insertAt( const QString &text, int para, int index )
2148{ 2148{
2149 removeSelection( QTextDocument::Standard ); 2149 removeSelection( QTextDocument::Standard );
2150 QTextParagraph *p = doc->paragAt( para ); 2150 QTextParagraph *p = doc->paragAt( para );
2151 if ( !p ) 2151 if ( !p )
2152 return; 2152 return;
2153 QTextCursor tmp = *cursor; 2153 QTextCursor tmp = *cursor;
2154 cursor->setParagraph( p ); 2154 cursor->setParagraph( p );
2155 cursor->setIndex( index ); 2155 cursor->setIndex( index );
2156 insert( text, FALSE, TRUE, FALSE ); 2156 insert( text, FALSE, TRUE, FALSE );
2157 *cursor = tmp; 2157 *cursor = tmp;
2158 removeSelection( QTextDocument::Standard ); 2158 removeSelection( QTextDocument::Standard );
2159} 2159}
2160 2160
2161/*! Inserts \a text as the paragraph at position \a para. If \a para 2161/*! Inserts \a text as the paragraph at position \a para. If \a para
2162 is -1, the text is appended. 2162 is -1, the text is appended.
2163*/ 2163*/
2164 2164
2165void QTextEdit::insertParagraph( const QString &text, int para ) 2165void QTextEdit::insertParagraph( const QString &text, int para )
2166{ 2166{
2167 QTextParagraph *p = doc->paragAt( para ); 2167 QTextParagraph *p = doc->paragAt( para );
2168 if ( p ) { 2168 if ( p ) {
2169 QTextCursor tmp( doc ); 2169 QTextCursor tmp( doc );
2170 tmp.setParagraph( p ); 2170 tmp.setParagraph( p );
2171 tmp.setIndex( 0 ); 2171 tmp.setIndex( 0 );
2172 tmp.insert( text, TRUE ); 2172 tmp.insert( text, TRUE );
2173 tmp.splitAndInsertEmptyParagraph(); 2173 tmp.splitAndInsertEmptyParagraph();
2174 repaintChanged(); 2174 repaintChanged();
2175 } else { 2175 } else {
2176 append( text ); 2176 append( text );
2177 } 2177 }
2178} 2178}
2179 2179
2180/*! Removes the paragraph \a para */ 2180/*! Removes the paragraph \a para */
2181 2181
2182void QTextEdit::removeParagraph( int para ) 2182void QTextEdit::removeParagraph( int para )
2183{ 2183{
2184 QTextParagraph *p = doc->paragAt( para ); 2184 QTextParagraph *p = doc->paragAt( para );
2185 if ( !p ) 2185 if ( !p )
2186 return; 2186 return;
2187 for ( int i = 0; i < doc->numSelections(); ++i ) 2187 for ( int i = 0; i < doc->numSelections(); ++i )
2188 doc->removeSelection( i ); 2188 doc->removeSelection( i );
2189 2189
2190 if ( p == doc->firstParagraph() && p == doc->lastParagraph() ) { 2190 if ( p == doc->firstParagraph() && p == doc->lastParagraph() ) {
2191 p->remove( 0, p->length() - 1 ); 2191 p->remove( 0, p->length() - 1 );
2192 repaintChanged(); 2192 repaintChanged();
2193 return; 2193 return;
2194 } 2194 }
2195 drawCursor( FALSE ); 2195 drawCursor( FALSE );
2196 bool resetCursor = cursor->paragraph() == p; 2196 bool resetCursor = cursor->paragraph() == p;
2197 if ( p->prev() ) 2197 if ( p->prev() )
2198 p->prev()->setNext( p->next() ); 2198 p->prev()->setNext( p->next() );
2199 else 2199 else
2200 doc->setFirstParagraph( p->next() ); 2200 doc->setFirstParagraph( p->next() );
2201 if ( p->next() ) 2201 if ( p->next() )
2202 p->next()->setPrev( p->prev() ); 2202 p->next()->setPrev( p->prev() );
2203 else 2203 else
2204 doc->setLastParagraph( p->prev() ); 2204 doc->setLastParagraph( p->prev() );
2205 QTextParagraph *start = p->next(); 2205 QTextParagraph *start = p->next();
2206 int h = p->rect().height(); 2206 int h = p->rect().height();
2207 delete p; 2207 delete p;
2208 p = start; 2208 p = start;
2209 int dy = -h; 2209 int dy = -h;
2210 while ( p ) { 2210 while ( p ) {
2211 p->setParagId( p->prev() ? p->prev()->paragId() + 1 : 0 ); 2211 p->setParagId( p->prev() ? p->prev()->paragId() + 1 : 0 );
2212 p->move( dy ); 2212 p->move( dy );
2213 p->invalidate( 0 ); 2213 p->invalidate( 0 );
2214 p->setEndState( -1 ); 2214 p->setEndState( -1 );
2215 p = p->next(); 2215 p = p->next();
2216 } 2216 }
2217 2217
2218 if ( resetCursor ) { 2218 if ( resetCursor ) {
2219 cursor->setParagraph( doc->firstParagraph() ); 2219 cursor->setParagraph( doc->firstParagraph() );
2220 cursor->setIndex( 0 ); 2220 cursor->setIndex( 0 );
2221 } 2221 }
2222 repaintChanged(); 2222 repaintChanged();
2223 drawCursor( TRUE ); 2223 drawCursor( TRUE );
2224} 2224}
2225 2225
2226/*! 2226/*!
2227 Undoes the last operation. 2227 Undoes the last operation.
2228 2228
2229 If there is no operation to undo, e.g. there is no undo step in the 2229 If there is no operation to undo, e.g. there is no undo step in the
2230 undo/redo history, nothing happens. 2230 undo/redo history, nothing happens.
2231 2231
2232 \sa undoAvailable() redo() undoDepth() 2232 \sa undoAvailable() redo() undoDepth()
2233*/ 2233*/
2234 2234
2235void QTextEdit::undo() 2235void QTextEdit::undo()
2236{ 2236{
2237 // XXX FIXME The next line is here because there may be a command 2237 // XXX FIXME The next line is here because there may be a command
2238 // that needs to be 'flushed'. The FIXME is because I am not 2238 // that needs to be 'flushed'. The FIXME is because I am not
2239 // 100% certain this is the right call to do this. 2239 // 100% certain this is the right call to do this.
2240 clearUndoRedo(); 2240 clearUndoRedo();
2241 if ( isReadOnly() || !doc->commands()->isUndoAvailable() || !undoEnabled ) 2241 if ( isReadOnly() || !doc->commands()->isUndoAvailable() || !undoEnabled )
2242 return; 2242 return;
2243 2243
2244 for ( int i = 0; i < (int)doc->numSelections(); ++i ) 2244 for ( int i = 0; i < (int)doc->numSelections(); ++i )
2245 doc->removeSelection( i ); 2245 doc->removeSelection( i );
2246 2246
2247#ifndef QT_NO_CURSOR 2247#ifndef QT_NO_CURSOR
2248 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 2248 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
2249#endif 2249#endif
2250 2250
2251 clearUndoRedo(); 2251 clearUndoRedo();
2252 drawCursor( FALSE ); 2252 drawCursor( FALSE );
2253 QTextCursor *c = doc->undo( cursor ); 2253 QTextCursor *c = doc->undo( cursor );
2254 if ( !c ) { 2254 if ( !c ) {
2255 drawCursor( TRUE ); 2255 drawCursor( TRUE );
2256 return; 2256 return;
2257 } 2257 }
2258 lastFormatted = 0; 2258 lastFormatted = 0;
2259 ensureCursorVisible(); 2259 ensureCursorVisible();
2260 repaintChanged(); 2260 repaintChanged();
2261 drawCursor( TRUE ); 2261 drawCursor( TRUE );
2262 updateMicroFocusHint(); 2262 updateMicroFocusHint();
2263 setModified(); 2263 setModified();
2264 emit textChanged(); 2264 emit textChanged();
2265} 2265}
2266 2266
2267/*! 2267/*!
2268 Redoes the last operation. 2268 Redoes the last operation.
2269 2269
2270 If there is no operation to redo, e.g. there is no redo step in the 2270 If there is no operation to redo, e.g. there is no redo step in the
2271 undo/redo history, nothing happens. 2271 undo/redo history, nothing happens.
2272 2272
2273 \sa redoAvailable() undo() undoDepth() 2273 \sa redoAvailable() undo() undoDepth()
2274*/ 2274*/
2275 2275
2276void QTextEdit::redo() 2276void QTextEdit::redo()
2277{ 2277{
2278 if ( isReadOnly() || !doc->commands()->isRedoAvailable() || !undoEnabled ) 2278 if ( isReadOnly() || !doc->commands()->isRedoAvailable() || !undoEnabled )
2279 return; 2279 return;
2280 2280
2281 for ( int i = 0; i < (int)doc->numSelections(); ++i ) 2281 for ( int i = 0; i < (int)doc->numSelections(); ++i )
2282 doc->removeSelection( i ); 2282 doc->removeSelection( i );
2283 2283
2284#ifndef QT_NO_CURSOR 2284#ifndef QT_NO_CURSOR
2285 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 2285 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
2286#endif 2286#endif
2287 2287
2288 clearUndoRedo(); 2288 clearUndoRedo();
2289 drawCursor( FALSE ); 2289 drawCursor( FALSE );
2290 QTextCursor *c = doc->redo( cursor ); 2290 QTextCursor *c = doc->redo( cursor );
2291 if ( !c ) { 2291 if ( !c ) {
2292 drawCursor( TRUE ); 2292 drawCursor( TRUE );
2293 return; 2293 return;
2294 } 2294 }
2295 lastFormatted = 0; 2295 lastFormatted = 0;
2296 ensureCursorVisible(); 2296 ensureCursorVisible();
2297 repaintChanged(); 2297 repaintChanged();
2298 ensureCursorVisible(); 2298 ensureCursorVisible();
2299 drawCursor( TRUE ); 2299 drawCursor( TRUE );
2300 updateMicroFocusHint(); 2300 updateMicroFocusHint();
2301 setModified(); 2301 setModified();
2302 emit textChanged(); 2302 emit textChanged();
2303} 2303}
2304 2304
2305/*! 2305/*!
2306 Pastes the text from the clipboard into the text edit at the current 2306 Pastes the text from the clipboard into the text edit at the current
2307 cursor position. Only plain text is pasted. 2307 cursor position. Only plain text is pasted.
2308 2308
2309 If there is no text in the clipboard nothing happens. 2309 If there is no text in the clipboard nothing happens.
2310 2310
2311 \sa pasteSubType() cut() QTextEdit::copy() 2311 \sa pasteSubType() cut() QTextEdit::copy()
2312*/ 2312*/
2313 2313
2314void QTextEdit::paste() 2314void QTextEdit::paste()
2315{ 2315{
2316#ifndef QT_NO_CLIPBOARD 2316#ifndef QT_NO_CLIPBOARD
2317 if ( isReadOnly() ) 2317 if ( isReadOnly() )
2318 return; 2318 return;
2319 pasteSubType( "plain" ); 2319 pasteSubType( "plain" );
2320 updateMicroFocusHint(); 2320 updateMicroFocusHint();
2321#endif 2321#endif
2322} 2322}
2323 2323
2324void QTextEdit::checkUndoRedoInfo( UndoRedoInfo::Type t ) 2324void QTextEdit::checkUndoRedoInfo( UndoRedoInfo::Type t )
2325{ 2325{
2326 if ( undoRedoInfo.valid() && t != undoRedoInfo.type ) { 2326 if ( undoRedoInfo.valid() && t != undoRedoInfo.type ) {
2327 clearUndoRedo(); 2327 clearUndoRedo();
2328 } 2328 }
2329 undoRedoInfo.type = t; 2329 undoRedoInfo.type = t;
2330} 2330}
2331 2331
2332/*! Repaints any paragraphs that have changed. 2332/*! Repaints any paragraphs that have changed.
2333 2333
2334 Although used extensively internally you shouldn't need to call this 2334 Although used extensively internally you shouldn't need to call this
2335 yourself. 2335 yourself.
2336*/ 2336*/
2337 2337
2338void QTextEdit::repaintChanged() 2338void QTextEdit::repaintChanged()
2339{ 2339{
2340 if ( !isUpdatesEnabled() || !viewport()->isUpdatesEnabled() ) 2340 if ( !isUpdatesEnabled() || !viewport()->isUpdatesEnabled() )
2341 return; 2341 return;
2342 QPainter p( viewport() ); 2342 QPainter p( viewport() );
2343 p.translate( -contentsX(), -contentsY() ); 2343 p.translate( -contentsX(), -contentsY() );
2344 paintDocument( FALSE, &p, contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 2344 paintDocument( FALSE, &p, contentsX(), contentsY(), visibleWidth(), visibleHeight() );
2345} 2345}
2346 2346
2347/*! 2347/*!
2348 Copies the selected text (from selection 0) to the clipboard and 2348 Copies the selected text (from selection 0) to the clipboard and
2349 deletes it from the text edit. 2349 deletes it from the text edit.
2350 2350
2351 If there is no selected text (in selection 0) nothing happens. 2351 If there is no selected text (in selection 0) nothing happens.
2352 2352
2353 \sa QTextEdit::copy() paste() pasteSubType() 2353 \sa QTextEdit::copy() paste() pasteSubType()
2354*/ 2354*/
2355 2355
2356void QTextEdit::cut() 2356void QTextEdit::cut()
2357{ 2357{
2358 if ( isReadOnly() ) 2358 if ( isReadOnly() )
2359 return; 2359 return;
2360 2360
2361 QString t; 2361 QString t;
2362 if ( doc->hasSelection( QTextDocument::Standard ) && 2362 if ( doc->hasSelection( QTextDocument::Standard ) &&
2363 !( t = doc->selectedText( QTextDocument::Standard, qt_enable_richtext_copy ) ).isEmpty() ) { 2363 !( t = doc->selectedText( QTextDocument::Standard, qt_enable_richtext_copy ) ).isEmpty() ) {
2364 QApplication::clipboard()->setText( t ); 2364 QApplication::clipboard()->setText( t );
2365 removeSelectedText(); 2365 removeSelectedText();
2366 } 2366 }
2367 updateMicroFocusHint(); 2367 updateMicroFocusHint();
2368} 2368}
2369 2369
2370/*! Copies any selected text (from selection 0) to the clipboard. 2370/*! Copies any selected text (from selection 0) to the clipboard.
2371 2371
2372 \sa hasSelectedText() copyAvailable() 2372 \sa hasSelectedText() copyAvailable()
2373 */ 2373 */
2374 2374
2375void QTextEdit::copy() 2375void QTextEdit::copy()
2376{ 2376{
2377 QString t = doc->selectedText( QTextDocument::Standard, qt_enable_richtext_copy ); 2377 QString t = doc->selectedText( QTextDocument::Standard, qt_enable_richtext_copy );
2378 if ( doc->hasSelection( QTextDocument::Standard ) && 2378 if ( doc->hasSelection( QTextDocument::Standard ) &&
2379 !t.isEmpty() && t.simplifyWhiteSpace() != "<selstart/>" ) 2379 !t.isEmpty() && t.simplifyWhiteSpace() != "<selstart/>" )
2380 QApplication::clipboard()->setText( t ); 2380 QApplication::clipboard()->setText( t );
2381} 2381}
2382 2382
2383/*! 2383/*!
2384 Re-indents the current paragraph. 2384 Re-indents the current paragraph.
2385*/ 2385*/
2386 2386
2387void QTextEdit::indent() 2387void QTextEdit::indent()
2388{ 2388{
2389 if ( isReadOnly() ) 2389 if ( isReadOnly() )
2390 return; 2390 return;
2391 2391
2392 drawCursor( FALSE ); 2392 drawCursor( FALSE );
2393 if ( !doc->hasSelection( QTextDocument::Standard ) ) 2393 if ( !doc->hasSelection( QTextDocument::Standard ) )
2394 cursor->indent(); 2394 cursor->indent();
2395 else 2395 else
2396 doc->indentSelection( QTextDocument::Standard ); 2396 doc->indentSelection( QTextDocument::Standard );
2397 repaintChanged(); 2397 repaintChanged();
2398 drawCursor( TRUE ); 2398 drawCursor( TRUE );
2399 setModified(); 2399 setModified();
2400 emit textChanged(); 2400 emit textChanged();
2401} 2401}
2402 2402
2403/*! Reimplemented to allow tabbing through links. 2403/*! Reimplemented to allow tabbing through links.
2404 If \a n is TRUE the tab moves the focus to the next child; if \a n 2404 If \a n is TRUE the tab moves the focus to the next child; if \a n
2405 is FALSE the tab moves the focus to the previous child. 2405 is FALSE the tab moves the focus to the previous child.
2406 Returns TRUE if the focus was moved; otherwise returns FALSE. 2406 Returns TRUE if the focus was moved; otherwise returns FALSE.
2407 */ 2407 */
2408 2408
2409bool QTextEdit::focusNextPrevChild( bool n ) 2409bool QTextEdit::focusNextPrevChild( bool n )
2410{ 2410{
2411 if ( !isReadOnly() || !linksEnabled() ) 2411 if ( !isReadOnly() || !linksEnabled() )
2412 return FALSE; 2412 return FALSE;
2413 bool b = doc->focusNextPrevChild( n ); 2413 bool b = doc->focusNextPrevChild( n );
2414 repaintChanged(); 2414 repaintChanged();
2415 if ( b ) 2415 if ( b )
2416 //##### this does not work with tables. The focusIndicator 2416 //##### this does not work with tables. The focusIndicator
2417 //should really be a QTextCursor. Fix 3.1 2417 //should really be a QTextCursor. Fix 3.1
2418 makeParagVisible( doc->focusIndicator.parag ); 2418 makeParagVisible( doc->focusIndicator.parag );
2419 return b; 2419 return b;
2420} 2420}
2421 2421
2422/*! 2422/*!
2423 \internal 2423 \internal
2424 2424
2425 This functions sets the current format to \a f. Only the fields of \a 2425 This functions sets the current format to \a f. Only the fields of \a
2426 f which are specified by the \a flags are used. 2426 f which are specified by the \a flags are used.
2427*/ 2427*/
2428 2428
2429void QTextEdit::setFormat( QTextFormat *f, int flags ) 2429void QTextEdit::setFormat( QTextFormat *f, int flags )
2430{ 2430{
2431 if ( doc->hasSelection( QTextDocument::Standard ) ) { 2431 if ( doc->hasSelection( QTextDocument::Standard ) ) {
2432 drawCursor( FALSE ); 2432 drawCursor( FALSE );
2433 QTextCursor c1 = doc->selectionStartCursor( QTextDocument::Standard ); 2433 QTextCursor c1 = doc->selectionStartCursor( QTextDocument::Standard );
2434 c1.restoreState(); 2434 c1.restoreState();
2435 QTextCursor c2 = doc->selectionEndCursor( QTextDocument::Standard ); 2435 QTextCursor c2 = doc->selectionEndCursor( QTextDocument::Standard );
2436 c2.restoreState(); 2436 c2.restoreState();
2437 clearUndoRedo(); 2437 clearUndoRedo();
2438 undoRedoInfo.type = UndoRedoInfo::Format; 2438 undoRedoInfo.type = UndoRedoInfo::Format;
2439 undoRedoInfo.id = c1.paragraph()->paragId(); 2439 undoRedoInfo.id = c1.paragraph()->paragId();
2440 undoRedoInfo.index = c1.index(); 2440 undoRedoInfo.index = c1.index();
2441 undoRedoInfo.eid = c2.paragraph()->paragId(); 2441 undoRedoInfo.eid = c2.paragraph()->paragId();
2442 undoRedoInfo.eindex = c2.index(); 2442 undoRedoInfo.eindex = c2.index();
2443 readFormats( c1, c2, undoRedoInfo.d->text ); 2443 readFormats( c1, c2, undoRedoInfo.d->text );
2444 undoRedoInfo.format = f; 2444 undoRedoInfo.format = f;
2445 undoRedoInfo.flags = flags; 2445 undoRedoInfo.flags = flags;
2446 clearUndoRedo(); 2446 clearUndoRedo();
2447 doc->setFormat( QTextDocument::Standard, f, flags ); 2447 doc->setFormat( QTextDocument::Standard, f, flags );
2448 repaintChanged(); 2448 repaintChanged();
2449 formatMore(); 2449 formatMore();
2450 drawCursor( TRUE ); 2450 drawCursor( TRUE );
2451 setModified(); 2451 setModified();
2452 emit textChanged(); 2452 emit textChanged();
2453 } 2453 }
2454 if ( currentFormat && currentFormat->key() != f->key() ) { 2454 if ( currentFormat && currentFormat->key() != f->key() ) {
2455 currentFormat->removeRef(); 2455 currentFormat->removeRef();
2456 currentFormat = doc->formatCollection()->format( f ); 2456 currentFormat = doc->formatCollection()->format( f );
2457 if ( currentFormat->isMisspelled() ) { 2457 if ( currentFormat->isMisspelled() ) {
2458 currentFormat->removeRef(); 2458 currentFormat->removeRef();
2459 currentFormat = doc->formatCollection()->format( currentFormat->font(), currentFormat->color() ); 2459 currentFormat = doc->formatCollection()->format( currentFormat->font(), currentFormat->color() );
2460 } 2460 }
2461 emit currentFontChanged( currentFormat->font() ); 2461 emit currentFontChanged( currentFormat->font() );
2462 emit currentColorChanged( currentFormat->color() ); 2462 emit currentColorChanged( currentFormat->color() );
2463 emit currentVerticalAlignmentChanged( (VerticalAlignment)currentFormat->vAlign() ); 2463 emit currentVerticalAlignmentChanged( (VerticalAlignment)currentFormat->vAlign() );
2464 if ( cursor->index() == cursor->paragraph()->length() - 1 ) { 2464 if ( cursor->index() == cursor->paragraph()->length() - 1 ) {
2465 currentFormat->addRef(); 2465 currentFormat->addRef();
2466 cursor->paragraph()->string()->setFormat( cursor->index(), currentFormat, TRUE ); 2466 cursor->paragraph()->string()->setFormat( cursor->index(), currentFormat, TRUE );
2467 if ( cursor->paragraph()->length() == 1 ) { 2467 if ( cursor->paragraph()->length() == 1 ) {
2468 cursor->paragraph()->invalidate( 0 ); 2468 cursor->paragraph()->invalidate( 0 );
2469 cursor->paragraph()->format(); 2469 cursor->paragraph()->format();
2470 repaintChanged(); 2470 repaintChanged();
2471 } 2471 }
2472 } 2472 }
2473 } 2473 }
2474} 2474}
2475 2475
2476/*! \reimp */ 2476/*! \reimp */
2477 2477
2478void QTextEdit::setPalette( const QPalette &p ) 2478void QTextEdit::setPalette( const QPalette &p )
2479{ 2479{
2480 QScrollView::setPalette( p ); 2480 QScrollView::setPalette( p );
2481 if ( textFormat() == PlainText ) { 2481 if ( textFormat() == PlainText ) {
2482 QTextFormat *f = doc->formatCollection()->defaultFormat(); 2482 QTextFormat *f = doc->formatCollection()->defaultFormat();
2483 f->setColor( colorGroup().text() ); 2483 f->setColor( colorGroup().text() );
2484 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 2484 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
2485 } 2485 }
2486} 2486}
2487 2487
2488/*! \internal 2488/*! \internal
2489 2489
2490 \warning In Qt 3.1 we will provide a cleaer API for the 2490 \warning In Qt 3.1 we will provide a cleaer API for the
2491 functionality which is provided by this function and in Qt 4.0 this 2491 functionality which is provided by this function and in Qt 4.0 this
2492 function will go away. 2492 function will go away.
2493 2493
2494 Sets the paragraph style of the current paragraph 2494 Sets the paragraph style of the current paragraph
2495 to \a dm. If \a dm is QStyleSheetItem::DisplayListItem, the 2495 to \a dm. If \a dm is QStyleSheetItem::DisplayListItem, the
2496 type of the list item is set to \a listStyle. 2496 type of the list item is set to \a listStyle.
2497 2497
2498 \sa setAlignment() 2498 \sa setAlignment()
2499*/ 2499*/
2500 2500
2501void QTextEdit::setParagType( QStyleSheetItem::DisplayMode dm, QStyleSheetItem::ListStyle listStyle ) 2501void QTextEdit::setParagType( QStyleSheetItem::DisplayMode dm, QStyleSheetItem::ListStyle listStyle )
2502{ 2502{
2503 if ( isReadOnly() ) 2503 if ( isReadOnly() )
2504 return; 2504 return;
2505 2505
2506 drawCursor( FALSE ); 2506 drawCursor( FALSE );
2507 QTextParagraph *start = cursor->paragraph(); 2507 QTextParagraph *start = cursor->paragraph();
2508 QTextParagraph *end = start; 2508 QTextParagraph *end = start;
2509 if ( doc->hasSelection( QTextDocument::Standard ) ) { 2509 if ( doc->hasSelection( QTextDocument::Standard ) ) {
2510 start = doc->selectionStartCursor( QTextDocument::Standard ).topParagraph(); 2510 start = doc->selectionStartCursor( QTextDocument::Standard ).topParagraph();
2511 end = doc->selectionEndCursor( QTextDocument::Standard ).topParagraph(); 2511 end = doc->selectionEndCursor( QTextDocument::Standard ).topParagraph();
2512 if ( end->paragId() < start->paragId() ) 2512 if ( end->paragId() < start->paragId() )
2513 return; // do not trust our selections 2513 return; // do not trust our selections
2514 } 2514 }
2515 2515
2516 clearUndoRedo(); 2516 clearUndoRedo();
2517 undoRedoInfo.type = UndoRedoInfo::Style; 2517 undoRedoInfo.type = UndoRedoInfo::Style;
2518 undoRedoInfo.id = start->paragId(); 2518 undoRedoInfo.id = start->paragId();
2519 undoRedoInfo.eid = end->paragId(); 2519 undoRedoInfo.eid = end->paragId();
2520 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid ); 2520 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid );
2521 2521
2522 while ( start != end->next() ) { 2522 while ( start != end->next() ) {
2523 start->setListStyle( listStyle ); 2523 start->setListStyle( listStyle );
2524 if ( dm == QStyleSheetItem::DisplayListItem ) { 2524 if ( dm == QStyleSheetItem::DisplayListItem ) {
2525 start->setListItem( TRUE ); 2525 start->setListItem( TRUE );
2526 if( start->listDepth() == 0 ) 2526 if( start->listDepth() == 0 )
2527 start->setListDepth( 1 ); 2527 start->setListDepth( 1 );
2528 } else if ( start->isListItem() ) { 2528 } else if ( start->isListItem() ) {
2529 start->setListItem( FALSE ); 2529 start->setListItem( FALSE );
2530 start->setListDepth( QMAX( start->listDepth()-1, 0 ) ); 2530 start->setListDepth( QMAX( start->listDepth()-1, 0 ) );
2531 } 2531 }
2532 start = start->next(); 2532 start = start->next();
2533 } 2533 }
2534 2534
2535 clearUndoRedo(); 2535 clearUndoRedo();
2536 repaintChanged(); 2536 repaintChanged();
2537 formatMore(); 2537 formatMore();
2538 drawCursor( TRUE ); 2538 drawCursor( TRUE );
2539 setModified(); 2539 setModified();
2540 emit textChanged(); 2540 emit textChanged();
2541} 2541}
2542 2542
2543/*! 2543/*!
2544 Sets the alignment of the current paragraph to \a a. Valid alignments 2544 Sets the alignment of the current paragraph to \a a. Valid alignments
2545 are \c Qt::AlignLeft, \c Qt::AlignRight, Qt::AlignJustify and 2545 are \c Qt::AlignLeft, \c Qt::AlignRight, Qt::AlignJustify and
2546 Qt::AlignCenter (which centers horizontally). 2546 Qt::AlignCenter (which centers horizontally).
2547 2547
2548*/ 2548*/
2549 2549
2550void QTextEdit::setAlignment( int a ) 2550void QTextEdit::setAlignment( int a )
2551{ 2551{
2552 if ( isReadOnly() || block_set_alignment ) 2552 if ( isReadOnly() || block_set_alignment )
2553 return; 2553 return;
2554 2554
2555 drawCursor( FALSE ); 2555 drawCursor( FALSE );
2556 QTextParagraph *start = cursor->paragraph(); 2556 QTextParagraph *start = cursor->paragraph();
2557 QTextParagraph *end = start; 2557 QTextParagraph *end = start;
2558 if ( doc->hasSelection( QTextDocument::Standard ) ) { 2558 if ( doc->hasSelection( QTextDocument::Standard ) ) {
2559 start = doc->selectionStartCursor( QTextDocument::Standard ).topParagraph(); 2559 start = doc->selectionStartCursor( QTextDocument::Standard ).topParagraph();
2560 end = doc->selectionEndCursor( QTextDocument::Standard ).topParagraph(); 2560 end = doc->selectionEndCursor( QTextDocument::Standard ).topParagraph();
2561 if ( end->paragId() < start->paragId() ) 2561 if ( end->paragId() < start->paragId() )
2562 return; // do not trust our selections 2562 return; // do not trust our selections
2563 } 2563 }
2564 2564
2565 clearUndoRedo(); 2565 clearUndoRedo();
2566 undoRedoInfo.type = UndoRedoInfo::Style; 2566 undoRedoInfo.type = UndoRedoInfo::Style;
2567 undoRedoInfo.id = start->paragId(); 2567 undoRedoInfo.id = start->paragId();
2568 undoRedoInfo.eid = end->paragId(); 2568 undoRedoInfo.eid = end->paragId();
2569 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid ); 2569 undoRedoInfo.styleInformation = QTextStyleCommand::readStyleInformation( doc, undoRedoInfo.id, undoRedoInfo.eid );
2570 2570
2571 while ( start != end->next() ) { 2571 while ( start != end->next() ) {
2572 start->setAlignment( a ); 2572 start->setAlignment( a );
2573 start = start->next(); 2573 start = start->next();
2574 } 2574 }
2575 2575
2576 clearUndoRedo(); 2576 clearUndoRedo();
2577 repaintChanged(); 2577 repaintChanged();
2578 formatMore(); 2578 formatMore();
2579 drawCursor( TRUE ); 2579 drawCursor( TRUE );
2580 if ( currentAlignment != a ) { 2580 if ( currentAlignment != a ) {
2581 currentAlignment = a; 2581 currentAlignment = a;
2582 emit currentAlignmentChanged( currentAlignment ); 2582 emit currentAlignmentChanged( currentAlignment );
2583 } 2583 }
2584 setModified(); 2584 setModified();
2585 emit textChanged(); 2585 emit textChanged();
2586} 2586}
2587 2587
2588void QTextEdit::updateCurrentFormat() 2588void QTextEdit::updateCurrentFormat()
2589{ 2589{
2590 int i = cursor->index(); 2590 int i = cursor->index();
2591 if ( i > 0 ) 2591 if ( i > 0 )
2592 --i; 2592 --i;
2593 if ( doc->useFormatCollection() && 2593 if ( doc->useFormatCollection() &&
2594 ( !currentFormat || currentFormat->key() != cursor->paragraph()->at( i )->format()->key() ) ) { 2594 ( !currentFormat || currentFormat->key() != cursor->paragraph()->at( i )->format()->key() ) ) {
2595 if ( currentFormat ) 2595 if ( currentFormat )
2596 currentFormat->removeRef(); 2596 currentFormat->removeRef();
2597 currentFormat = doc->formatCollection()->format( cursor->paragraph()->at( i )->format() ); 2597 currentFormat = doc->formatCollection()->format( cursor->paragraph()->at( i )->format() );
2598 if ( currentFormat->isMisspelled() ) { 2598 if ( currentFormat->isMisspelled() ) {
2599 currentFormat->removeRef(); 2599 currentFormat->removeRef();
2600 currentFormat = doc->formatCollection()->format( currentFormat->font(), currentFormat->color() ); 2600 currentFormat = doc->formatCollection()->format( currentFormat->font(), currentFormat->color() );
2601 } 2601 }
2602 emit currentFontChanged( currentFormat->font() ); 2602 emit currentFontChanged( currentFormat->font() );
2603 emit currentColorChanged( currentFormat->color() ); 2603 emit currentColorChanged( currentFormat->color() );
2604 emit currentVerticalAlignmentChanged( (VerticalAlignment)currentFormat->vAlign() ); 2604 emit currentVerticalAlignmentChanged( (VerticalAlignment)currentFormat->vAlign() );
2605 } 2605 }
2606 2606
2607 if ( currentAlignment != cursor->paragraph()->alignment() ) { 2607 if ( currentAlignment != cursor->paragraph()->alignment() ) {
2608 currentAlignment = cursor->paragraph()->alignment(); 2608 currentAlignment = cursor->paragraph()->alignment();
2609 block_set_alignment = TRUE; 2609 block_set_alignment = TRUE;
2610 emit currentAlignmentChanged( currentAlignment ); 2610 emit currentAlignmentChanged( currentAlignment );
2611 block_set_alignment = FALSE; 2611 block_set_alignment = FALSE;
2612 } 2612 }
2613} 2613}
2614 2614
2615/*! 2615/*!
2616 If \a b is TRUE sets the current format to italic; otherwise sets 2616 If \a b is TRUE sets the current format to italic; otherwise sets
2617 the current format to non-italic. 2617 the current format to non-italic.
2618 2618
2619 \sa italic() 2619 \sa italic()
2620*/ 2620*/
2621 2621
2622void QTextEdit::setItalic( bool b ) 2622void QTextEdit::setItalic( bool b )
2623{ 2623{
2624 QTextFormat f( *currentFormat ); 2624 QTextFormat f( *currentFormat );
2625 f.setItalic( b ); 2625 f.setItalic( b );
2626 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2626 QTextFormat *f2 = doc->formatCollection()->format( &f );
2627 setFormat( f2, QTextFormat::Italic ); 2627 setFormat( f2, QTextFormat::Italic );
2628} 2628}
2629 2629
2630/*! 2630/*!
2631 If \a b is TRUE sets the current format to bold; otherwise sets the 2631 If \a b is TRUE sets the current format to bold; otherwise sets the
2632 current format to non-bold. 2632 current format to non-bold.
2633 2633
2634 \sa bold() 2634 \sa bold()
2635*/ 2635*/
2636 2636
2637void QTextEdit::setBold( bool b ) 2637void QTextEdit::setBold( bool b )
2638{ 2638{
2639 QTextFormat f( *currentFormat ); 2639 QTextFormat f( *currentFormat );
2640 f.setBold( b ); 2640 f.setBold( b );
2641 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2641 QTextFormat *f2 = doc->formatCollection()->format( &f );
2642 setFormat( f2, QTextFormat::Bold ); 2642 setFormat( f2, QTextFormat::Bold );
2643} 2643}
2644 2644
2645/*! 2645/*!
2646 If \a b is TRUE sets the current format to underline; otherwise sets 2646 If \a b is TRUE sets the current format to underline; otherwise sets
2647 the current format to non-underline. 2647 the current format to non-underline.
2648 2648
2649 \sa underline() 2649 \sa underline()
2650*/ 2650*/
2651 2651
2652void QTextEdit::setUnderline( bool b ) 2652void QTextEdit::setUnderline( bool b )
2653{ 2653{
2654 QTextFormat f( *currentFormat ); 2654 QTextFormat f( *currentFormat );
2655 f.setUnderline( b ); 2655 f.setUnderline( b );
2656 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2656 QTextFormat *f2 = doc->formatCollection()->format( &f );
2657 setFormat( f2, QTextFormat::Underline ); 2657 setFormat( f2, QTextFormat::Underline );
2658} 2658}
2659 2659
2660/*! 2660/*!
2661 Sets the font family of the current format to \a fontFamily. 2661 Sets the font family of the current format to \a fontFamily.
2662 2662
2663 \sa family() setCurrentFont() 2663 \sa family() setCurrentFont()
2664*/ 2664*/
2665 2665
2666void QTextEdit::setFamily( const QString &fontFamily ) 2666void QTextEdit::setFamily( const QString &fontFamily )
2667{ 2667{
2668 QTextFormat f( *currentFormat ); 2668 QTextFormat f( *currentFormat );
2669 f.setFamily( fontFamily ); 2669 f.setFamily( fontFamily );
2670 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2670 QTextFormat *f2 = doc->formatCollection()->format( &f );
2671 setFormat( f2, QTextFormat::Family ); 2671 setFormat( f2, QTextFormat::Family );
2672} 2672}
2673 2673
2674/*! 2674/*!
2675 Sets the point size of the current format to \a s. 2675 Sets the point size of the current format to \a s.
2676 2676
2677 Note that if \a s is zero or negative, the behaviour of this 2677 Note that if \a s is zero or negative, the behaviour of this
2678 function is not defined. 2678 function is not defined.
2679 2679
2680 \sa pointSize() setCurrentFont() setFamily() 2680 \sa pointSize() setCurrentFont() setFamily()
2681*/ 2681*/
2682 2682
2683void QTextEdit::setPointSize( int s ) 2683void QTextEdit::setPointSize( int s )
2684{ 2684{
2685 QTextFormat f( *currentFormat ); 2685 QTextFormat f( *currentFormat );
2686 f.setPointSize( s ); 2686 f.setPointSize( s );
2687 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2687 QTextFormat *f2 = doc->formatCollection()->format( &f );
2688 setFormat( f2, QTextFormat::Size ); 2688 setFormat( f2, QTextFormat::Size );
2689} 2689}
2690 2690
2691/*! 2691/*!
2692 Sets the color of the current format, i.e. of the text, to \a c. 2692 Sets the color of the current format, i.e. of the text, to \a c.
2693 2693
2694 \sa color() setPaper() 2694 \sa color() setPaper()
2695*/ 2695*/
2696 2696
2697void QTextEdit::setColor( const QColor &c ) 2697void QTextEdit::setColor( const QColor &c )
2698{ 2698{
2699 QTextFormat f( *currentFormat ); 2699 QTextFormat f( *currentFormat );
2700 f.setColor( c ); 2700 f.setColor( c );
2701 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2701 QTextFormat *f2 = doc->formatCollection()->format( &f );
2702 setFormat( f2, QTextFormat::Color ); 2702 setFormat( f2, QTextFormat::Color );
2703} 2703}
2704 2704
2705/*! 2705/*!
2706 Sets the vertical alignment of the current format, i.e. of the text, to \a a. 2706 Sets the vertical alignment of the current format, i.e. of the text, to \a a.
2707 2707
2708 \sa color() setPaper() 2708 \sa color() setPaper()
2709*/ 2709*/
2710 2710
2711void QTextEdit::setVerticalAlignment( VerticalAlignment a ) 2711void QTextEdit::setVerticalAlignment( VerticalAlignment a )
2712{ 2712{
2713 QTextFormat f( *currentFormat ); 2713 QTextFormat f( *currentFormat );
2714 f.setVAlign( (QTextFormat::VerticalAlignment)a ); 2714 f.setVAlign( (QTextFormat::VerticalAlignment)a );
2715 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2715 QTextFormat *f2 = doc->formatCollection()->format( &f );
2716 setFormat( f2, QTextFormat::VAlign ); 2716 setFormat( f2, QTextFormat::VAlign );
2717} 2717}
2718 2718
2719void QTextEdit::setFontInternal( const QFont &f_ ) 2719void QTextEdit::setFontInternal( const QFont &f_ )
2720{ 2720{
2721 QTextFormat f( *currentFormat ); 2721 QTextFormat f( *currentFormat );
2722 f.setFont( f_ ); 2722 f.setFont( f_ );
2723 QTextFormat *f2 = doc->formatCollection()->format( &f ); 2723 QTextFormat *f2 = doc->formatCollection()->format( &f );
2724 setFormat( f2, QTextFormat::Font ); 2724 setFormat( f2, QTextFormat::Font );
2725} 2725}
2726 2726
2727 2727
2728QString QTextEdit::text() const 2728QString QTextEdit::text() const
2729{ 2729{
2730 if ( isReadOnly() ) 2730 if ( isReadOnly() )
2731 return doc->originalText(); 2731 return doc->originalText();
2732 return doc->text(); 2732 return doc->text();
2733} 2733}
2734 2734
2735/*! 2735/*!
2736 \overload 2736 \overload
2737 Returns the text of paragraph \a para. 2737 Returns the text of paragraph \a para.
2738 2738
2739 If textFormat() is \c RichText the text will contain HTML 2739 If textFormat() is \c RichText the text will contain HTML
2740 formatting tags. 2740 formatting tags.
2741*/ 2741*/
2742 2742
2743QString QTextEdit::text( int para ) const 2743QString QTextEdit::text( int para ) const
2744{ 2744{
2745 return doc->text( para ); 2745 return doc->text( para );
2746} 2746}
2747 2747
2748/*! 2748/*!
2749 \overload 2749 \overload
2750 2750
2751 Changes the text of the text edit to the string \a text and the 2751 Changes the text of the text edit to the string \a text and the
2752 context to \a context. Any previous text is removed. 2752 context to \a context. Any previous text is removed.
2753 2753
2754 \a text may be interpreted either as plain text or as rich text, 2754 \a text may be interpreted either as plain text or as rich text,
2755 depending on the textFormat(). The default setting is \c AutoText, 2755 depending on the textFormat(). The default setting is \c AutoText,
2756 i.e. the text edit autodetects the format from \a text. 2756 i.e. the text edit autodetects the format from \a text.
2757 2757
2758 The optional \a context is a path which the text edit's 2758 The optional \a context is a path which the text edit's
2759 QMimeSourceFactory uses to resolve the locations of files and images. 2759 QMimeSourceFactory uses to resolve the locations of files and images.
2760 (See \l{QTextEdit::QTextEdit()}.) It is passed to the text edit's 2760 (See \l{QTextEdit::QTextEdit()}.) It is passed to the text edit's
2761 QMimeSourceFactory when quering data. 2761 QMimeSourceFactory when quering data.
2762 2762
2763 Note that the undo/redo history is cleared by this function. 2763 Note that the undo/redo history is cleared by this function.
2764 2764
2765 \sa text(), setTextFormat() 2765 \sa text(), setTextFormat()
2766*/ 2766*/
2767 2767
2768void QTextEdit::setText( const QString &text, const QString &context ) 2768void QTextEdit::setText( const QString &text, const QString &context )
2769{ 2769{
2770 if ( !isModified() && isReadOnly() && 2770 if ( !isModified() && isReadOnly() &&
2771 this->context() == context && this->text() == text ) 2771 this->context() == context && this->text() == text )
2772 return; 2772 return;
2773 2773
2774 emit undoAvailable( FALSE ); 2774 emit undoAvailable( FALSE );
2775 emit redoAvailable( FALSE ); 2775 emit redoAvailable( FALSE );
2776 undoRedoInfo.clear(); 2776 undoRedoInfo.clear();
2777 doc->commands()->clear(); 2777 doc->commands()->clear();
2778 2778
2779 lastFormatted = 0; 2779 lastFormatted = 0;
2780 cursor->restoreState(); 2780 cursor->restoreState();
2781 doc->setText( text, context ); 2781 doc->setText( text, context );
2782 2782
2783 if ( wrapMode == FixedPixelWidth ) { 2783 if ( wrapMode == FixedPixelWidth ) {
2784 resizeContents( wrapWidth, 0 ); 2784 resizeContents( wrapWidth, 0 );
2785 doc->setWidth( wrapWidth ); 2785 doc->setWidth( wrapWidth );
2786 doc->setMinimumWidth( wrapWidth ); 2786 doc->setMinimumWidth( wrapWidth );
2787 } else { 2787 } else {
2788 doc->setMinimumWidth( -1 ); 2788 doc->setMinimumWidth( -1 );
2789 resizeContents( 0, 0 ); 2789 resizeContents( 0, 0 );
2790 } 2790 }
2791 2791
2792 lastFormatted = doc->firstParagraph(); 2792 lastFormatted = doc->firstParagraph();
2793 delete cursor; 2793 delete cursor;
2794 cursor = new QTextCursor( doc ); 2794 cursor = new QTextCursor( doc );
2795 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 2795 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
2796 2796
2797 if ( isModified() ) 2797 if ( isModified() )
2798 setModified( FALSE ); 2798 setModified( FALSE );
2799 emit textChanged(); 2799 emit textChanged();
2800 formatMore(); 2800 formatMore();
2801 updateCurrentFormat(); 2801 updateCurrentFormat();
2802 d->scrollToAnchor = QString::null; 2802 d->scrollToAnchor = QString::null;
2803} 2803}
2804 2804
2805/*! 2805/*!
2806 \property QTextEdit::text 2806 \property QTextEdit::text
2807 \brief the text edit's text 2807 \brief the text edit's text
2808 2808
2809 There is no default text. 2809 There is no default text.
2810 2810
2811 On setting, any previous text is deleted. 2811 On setting, any previous text is deleted.
2812 2812
2813 The text may be interpreted either as plain text or as rich text, 2813 The text may be interpreted either as plain text or as rich text,
2814 depending on the textFormat(). The default setting is \c AutoText, 2814 depending on the textFormat(). The default setting is \c AutoText,
2815 i.e. the text edit autodetects the format of the text. 2815 i.e. the text edit autodetects the format of the text.
2816 2816
2817 For richtext, calling text() on an editable QTextEdit will cause the text 2817 For richtext, calling text() on an editable QTextEdit will cause the text
2818 to be regenerated from the textedit. This may mean that the QString returned 2818 to be regenerated from the textedit. This may mean that the QString returned
2819 may not be exactly the same as the one that was set. 2819 may not be exactly the same as the one that was set.
2820 2820
2821 \sa textFormat 2821 \sa textFormat
2822*/ 2822*/
2823 2823
2824 2824
2825/*! 2825/*!
2826 \property QTextEdit::readOnly 2826 \property QTextEdit::readOnly
2827 \brief whether the text edit is read-only 2827 \brief whether the text edit is read-only
2828 2828
2829 In a read-only text edit the user can only navigate through the text 2829 In a read-only text edit the user can only navigate through the text
2830 and select text; modifying the text is not possible. 2830 and select text; modifying the text is not possible.
2831 2831
2832 This property's default is FALSE. 2832 This property's default is FALSE.
2833*/ 2833*/
2834 2834
2835/*! 2835/*!
2836 Finds the next occurrence of the string, \a expr. Returns TRUE if 2836 Finds the next occurrence of the string, \a expr. Returns TRUE if
2837 \a expr is found; otherwise returns FALSE. 2837 \a expr is found; otherwise returns FALSE.
2838 2838
2839 If \a para and \a index are both null the search begins from the 2839 If \a para and \a index are both null the search begins from the
2840 current cursor position. If \a para and \a index are both not 2840 current cursor position. If \a para and \a index are both not
2841 null, the search begins from the \e *\a index character position 2841 null, the search begins from the \e *\a index character position
2842 in the \e *\a para paragraph. 2842 in the \e *\a para paragraph.
2843 2843
2844 If \a cs is TRUE the search is case sensitive, otherwise it is 2844 If \a cs is TRUE the search is case sensitive, otherwise it is
2845 case insensitive. If \a wo is TRUE the search looks for whole word 2845 case insensitive. If \a wo is TRUE the search looks for whole word
2846 matches only; otherwise it searches for any matching text. If \a 2846 matches only; otherwise it searches for any matching text. If \a
2847 forward is TRUE (the default) the search works forward from the 2847 forward is TRUE (the default) the search works forward from the
2848 starting position to the end of the text, otherwise it works 2848 starting position to the end of the text, otherwise it works
2849 backwards to the beginning of the text. 2849 backwards to the beginning of the text.
2850 2850
2851 If \a expr is found the function returns TRUE. If \a index and \a 2851 If \a expr is found the function returns TRUE. If \a index and \a
2852 para are not null, the number of the paragraph in which the first 2852 para are not null, the number of the paragraph in which the first
2853 character of the match was found is put into \e *\a para, and the 2853 character of the match was found is put into \e *\a para, and the
2854 index position of that character within the paragraph is put into 2854 index position of that character within the paragraph is put into
2855 \e *\a index. 2855 \e *\a index.
2856 2856
2857 If \a expr is not found the function returns FALSE. If \a index 2857 If \a expr is not found the function returns FALSE. If \a index
2858 and \a para are not null and \a expr is not found, \e *\a index 2858 and \a para are not null and \a expr is not found, \e *\a index
2859 and \e *\a para are undefined. 2859 and \e *\a para are undefined.
2860*/ 2860*/
2861 2861
2862bool QTextEdit::find( const QString &expr, bool cs, bool wo, bool forward, 2862bool QTextEdit::find( const QString &expr, bool cs, bool wo, bool forward,
2863 int *para, int *index ) 2863 int *para, int *index )
2864{ 2864{
2865 drawCursor( FALSE ); 2865 drawCursor( FALSE );
2866#ifndef QT_NO_CURSOR 2866#ifndef QT_NO_CURSOR
2867 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 2867 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
2868#endif 2868#endif
2869 QTextCursor findcur = *cursor; 2869 QTextCursor findcur = *cursor;
2870 if ( para && index ) { 2870 if ( para && index ) {
2871 if ( doc->paragAt( *para ) ) 2871 if ( doc->paragAt( *para ) )
2872 findcur.gotoPosition( doc->paragAt(*para), *index ); 2872 findcur.gotoPosition( doc->paragAt(*para), *index );
2873 else 2873 else
2874 findcur.gotoEnd(); 2874 findcur.gotoEnd();
2875 } else if ( doc->hasSelection( QTextDocument::Standard ) ){ 2875 } else if ( doc->hasSelection( QTextDocument::Standard ) ){
2876 // maks sure we do not find the same selection again 2876 // maks sure we do not find the same selection again
2877 if ( forward ) 2877 if ( forward )
2878 findcur.gotoNextLetter(); 2878 findcur.gotoNextLetter();
2879 else 2879 else
2880 findcur.gotoPreviousLetter(); 2880 findcur.gotoPreviousLetter();
2881 } 2881 }
2882 removeSelection( QTextDocument::Standard ); 2882 removeSelection( QTextDocument::Standard );
2883 bool found = doc->find( findcur, expr, cs, wo, forward ); 2883 bool found = doc->find( findcur, expr, cs, wo, forward );
2884 if ( found ) { 2884 if ( found ) {
2885 if ( para ) 2885 if ( para )
2886 *para = findcur.paragraph()->paragId(); 2886 *para = findcur.paragraph()->paragId();
2887 if ( index ) 2887 if ( index )
2888 *index = findcur.index(); 2888 *index = findcur.index();
2889 *cursor = findcur; 2889 *cursor = findcur;
2890 repaintChanged(); 2890 repaintChanged();
2891 ensureCursorVisible(); 2891 ensureCursorVisible();
2892 } 2892 }
2893 drawCursor( TRUE ); 2893 drawCursor( TRUE );
2894 return found; 2894 return found;
2895} 2895}
2896 2896
2897void QTextEdit::blinkCursor() 2897void QTextEdit::blinkCursor()
2898{ 2898{
2899 if ( !cursorVisible ) 2899 if ( !cursorVisible )
2900 return; 2900 return;
2901 bool cv = cursorVisible; 2901 bool cv = cursorVisible;
2902 blinkCursorVisible = !blinkCursorVisible; 2902 blinkCursorVisible = !blinkCursorVisible;
2903 drawCursor( blinkCursorVisible ); 2903 drawCursor( blinkCursorVisible );
2904 cursorVisible = cv; 2904 cursorVisible = cv;
2905} 2905}
2906 2906
2907/*! 2907/*!
2908 Sets the cursor to position \a index in paragraph \a para. 2908 Sets the cursor to position \a index in paragraph \a para.
2909 2909
2910 \sa getCursorPosition() 2910 \sa getCursorPosition()
2911*/ 2911*/
2912 2912
2913void QTextEdit::setCursorPosition( int para, int index ) 2913void QTextEdit::setCursorPosition( int para, int index )
2914{ 2914{
2915 QTextParagraph *p = doc->paragAt( para ); 2915 QTextParagraph *p = doc->paragAt( para );
2916 if ( !p ) 2916 if ( !p )
2917 return; 2917 return;
2918 2918
2919 if ( index > p->length() - 1 ) 2919 if ( index > p->length() - 1 )
2920 index = p->length() - 1; 2920 index = p->length() - 1;
2921 2921
2922 drawCursor( FALSE ); 2922 drawCursor( FALSE );
2923 cursor->setParagraph( p ); 2923 cursor->setParagraph( p );
2924 cursor->setIndex( index ); 2924 cursor->setIndex( index );
2925 ensureCursorVisible(); 2925 ensureCursorVisible();
2926 drawCursor( TRUE ); 2926 drawCursor( TRUE );
2927 updateCurrentFormat(); 2927 updateCurrentFormat();
2928 emit cursorPositionChanged( cursor ); 2928 emit cursorPositionChanged( cursor );
2929 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() ); 2929 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() );
2930} 2930}
2931 2931
2932/*! 2932/*!
2933 This function sets the \e *\a para and \e *\a index parameters to the 2933 This function sets the \e *\a para and \e *\a index parameters to the
2934 current cursor position. \a para and \a index must be non-null int 2934 current cursor position. \a para and \a index must be non-null int
2935 pointers. 2935 pointers.
2936 2936
2937 \sa setCursorPosition() 2937 \sa setCursorPosition()
2938 */ 2938 */
2939 2939
2940void QTextEdit::getCursorPosition( int *para, int *index ) const 2940void QTextEdit::getCursorPosition( int *para, int *index ) const
2941{ 2941{
2942 if ( !para || !index ) 2942 if ( !para || !index )
2943 return; 2943 return;
2944 *para = cursor->paragraph()->paragId(); 2944 *para = cursor->paragraph()->paragId();
2945 *index = cursor->index(); 2945 *index = cursor->index();
2946} 2946}
2947 2947
2948/*! Sets a selection which starts at position \a indexFrom in 2948/*! Sets a selection which starts at position \a indexFrom in
2949 paragraph \a paraFrom and ends at position \a indexTo in paragraph 2949 paragraph \a paraFrom and ends at position \a indexTo in paragraph
2950 \a paraTo. Existing selections which have a different id (selNum) 2950 \a paraTo. Existing selections which have a different id (selNum)
2951 are not removed, existing selections which have the same id as \a 2951 are not removed, existing selections which have the same id as \a
2952 selNum are removed. 2952 selNum are removed.
2953 2953
2954 Uses the selection settings of selection \a selNum. If \a selNum is 0, 2954 Uses the selection settings of selection \a selNum. If \a selNum is 0,
2955 this is the default selection. 2955 this is the default selection.
2956 2956
2957 The cursor is moved to the end of the selection if \a selNum is 0, 2957 The cursor is moved to the end of the selection if \a selNum is 0,
2958 otherwise the cursor position remains unchanged. 2958 otherwise the cursor position remains unchanged.
2959 2959
2960 \sa getSelection() selectedText 2960 \sa getSelection() selectedText
2961*/ 2961*/
2962 2962
2963void QTextEdit::setSelection( int paraFrom, int indexFrom, 2963void QTextEdit::setSelection( int paraFrom, int indexFrom,
2964 int paraTo, int indexTo, int selNum ) 2964 int paraTo, int indexTo, int selNum )
2965{ 2965{
2966 if ( doc->hasSelection( selNum ) ) { 2966 if ( doc->hasSelection( selNum ) ) {
2967 doc->removeSelection( selNum ); 2967 doc->removeSelection( selNum );
2968 repaintChanged(); 2968 repaintChanged();
2969 } 2969 }
2970 if ( selNum > doc->numSelections() - 1 ) 2970 if ( selNum > doc->numSelections() - 1 )
2971 doc->addSelection( selNum ); 2971 doc->addSelection( selNum );
2972 QTextParagraph *p1 = doc->paragAt( paraFrom ); 2972 QTextParagraph *p1 = doc->paragAt( paraFrom );
2973 if ( !p1 ) 2973 if ( !p1 )
2974 return; 2974 return;
2975 QTextParagraph *p2 = doc->paragAt( paraTo ); 2975 QTextParagraph *p2 = doc->paragAt( paraTo );
2976 if ( !p2 ) 2976 if ( !p2 )
2977 return; 2977 return;
2978 2978
2979 if ( indexFrom > p1->length() - 1 ) 2979 if ( indexFrom > p1->length() - 1 )
2980 indexFrom = p1->length() - 1; 2980 indexFrom = p1->length() - 1;
2981 if ( indexTo > p2->length() - 1 ) 2981 if ( indexTo > p2->length() - 1 )
2982 indexTo = p2->length() - 1; 2982 indexTo = p2->length() - 1;
2983 2983
2984 drawCursor( FALSE ); 2984 drawCursor( FALSE );
2985 QTextCursor c = *cursor; 2985 QTextCursor c = *cursor;
2986 QTextCursor oldCursor = *cursor; 2986 QTextCursor oldCursor = *cursor;
2987 c.setParagraph( p1 ); 2987 c.setParagraph( p1 );
2988 c.setIndex( indexFrom ); 2988 c.setIndex( indexFrom );
2989 cursor->setParagraph( p2 ); 2989 cursor->setParagraph( p2 );
2990 cursor->setIndex( indexTo ); 2990 cursor->setIndex( indexTo );
2991 doc->setSelectionStart( selNum, c ); 2991 doc->setSelectionStart( selNum, c );
2992 doc->setSelectionEnd( selNum, *cursor ); 2992 doc->setSelectionEnd( selNum, *cursor );
2993 repaintChanged(); 2993 repaintChanged();
2994 ensureCursorVisible(); 2994 ensureCursorVisible();
2995 if ( selNum != QTextDocument::Standard ) 2995 if ( selNum != QTextDocument::Standard )
2996 *cursor = oldCursor; 2996 *cursor = oldCursor;
2997 drawCursor( TRUE ); 2997 drawCursor( TRUE );
2998} 2998}
2999 2999
3000/*! 3000/*!
3001 If there is a selection, \e *\a paraFrom is set to the number of the 3001 If there is a selection, \e *\a paraFrom is set to the number of the
3002 paragraph in which the selection begins and \e *\a paraTo is set to 3002 paragraph in which the selection begins and \e *\a paraTo is set to
3003 the number of the paragraph in which the selection ends. (They could 3003 the number of the paragraph in which the selection ends. (They could
3004 be the same.) \e *\a indexFrom is set to the index at which the 3004 be the same.) \e *\a indexFrom is set to the index at which the
3005 selection begins within \e *\a paraFrom, and \e *\a indexTo is set to 3005 selection begins within \e *\a paraFrom, and \e *\a indexTo is set to
3006 the index at which the selection ends within \e *\a paraTo. 3006 the index at which the selection ends within \e *\a paraTo.
3007 3007
3008 If there is no selection, \e *\a paraFrom, \e *\a indexFrom, \e *\a 3008 If there is no selection, \e *\a paraFrom, \e *\a indexFrom, \e *\a
3009 paraTo and \e *\a indexTo are all set to -1. 3009 paraTo and \e *\a indexTo are all set to -1.
3010 3010
3011 \a paraFrom, \a indexFrom, \a paraTo and \a indexTo must be non-null 3011 \a paraFrom, \a indexFrom, \a paraTo and \a indexTo must be non-null
3012 int pointers. 3012 int pointers.
3013 3013
3014 The \a selNum is the number of the selection (multiple selections 3014 The \a selNum is the number of the selection (multiple selections
3015 are supported). It defaults to 0 (the default selection). 3015 are supported). It defaults to 0 (the default selection).
3016 3016
3017 \sa setSelection() selectedText 3017 \sa setSelection() selectedText
3018*/ 3018*/
3019 3019
3020void QTextEdit::getSelection( int *paraFrom, int *indexFrom, 3020void QTextEdit::getSelection( int *paraFrom, int *indexFrom,
3021 int *paraTo, int *indexTo, int selNum ) const 3021 int *paraTo, int *indexTo, int selNum ) const
3022{ 3022{
3023 if ( !paraFrom || !paraTo || !indexFrom || !indexTo ) 3023 if ( !paraFrom || !paraTo || !indexFrom || !indexTo )
3024 return; 3024 return;
3025 if ( !doc->hasSelection( selNum ) ) { 3025 if ( !doc->hasSelection( selNum ) ) {
3026 *paraFrom = -1; 3026 *paraFrom = -1;
3027 *indexFrom = -1; 3027 *indexFrom = -1;
3028 *paraTo = -1; 3028 *paraTo = -1;
3029 *indexTo = -1; 3029 *indexTo = -1;
3030 return; 3030 return;
3031 } 3031 }
3032 3032
3033 doc->selectionStart( selNum, *paraFrom, *indexFrom ); 3033 doc->selectionStart( selNum, *paraFrom, *indexFrom );
3034 doc->selectionEnd( selNum, *paraTo, *indexTo ); 3034 doc->selectionEnd( selNum, *paraTo, *indexTo );
3035} 3035}
3036 3036
3037/*! 3037/*!
3038 \property QTextEdit::textFormat 3038 \property QTextEdit::textFormat
3039 \brief the text format: rich text, plain text or auto text 3039 \brief the text format: rich text, plain text or auto text
3040 3040
3041 The text format is one of the following: 3041 The text format is one of the following:
3042 \list 3042 \list
3043 \i PlainText - all characters, except newlines, are displayed 3043 \i PlainText - all characters, except newlines, are displayed
3044 verbatim, including spaces. Whenever a newline appears in the text the 3044 verbatim, including spaces. Whenever a newline appears in the text the
3045 text edit inserts a hard line break and begins a new paragraph. 3045 text edit inserts a hard line break and begins a new paragraph.
3046 \i RichText - rich text rendering. The available styles are 3046 \i RichText - rich text rendering. The available styles are
3047 defined in the default stylesheet QStyleSheet::defaultSheet(). 3047 defined in the default stylesheet QStyleSheet::defaultSheet().
3048 \i AutoText - this is the default. The text edit autodetects 3048 \i AutoText - this is the default. The text edit autodetects
3049 which rendering style is best, \c PlainText or \c RichText. This is 3049 which rendering style is best, \c PlainText or \c RichText. This is
3050 done by using the QStyleSheet::mightBeRichText() function. 3050 done by using the QStyleSheet::mightBeRichText() function.
3051 \endlist 3051 \endlist
3052*/ 3052*/
3053 3053
3054void QTextEdit::setTextFormat( TextFormat format ) 3054void QTextEdit::setTextFormat( TextFormat format )
3055{ 3055{
3056 doc->setTextFormat( format ); 3056 doc->setTextFormat( format );
3057} 3057}
3058 3058
3059Qt::TextFormat QTextEdit::textFormat() const 3059Qt::TextFormat QTextEdit::textFormat() const
3060{ 3060{
3061 return doc->textFormat(); 3061 return doc->textFormat();
3062} 3062}
3063 3063
3064/*! 3064/*!
3065 Returns the number of paragraphs in the text; this could be 0. 3065 Returns the number of paragraphs in the text; this could be 0.
3066*/ 3066*/
3067 3067
3068int QTextEdit::paragraphs() const 3068int QTextEdit::paragraphs() const
3069{ 3069{
3070 return doc->lastParagraph()->paragId() + 1; 3070 return doc->lastParagraph()->paragId() + 1;
3071} 3071}
3072 3072
3073/*! 3073/*!
3074 Returns the number of lines in paragraph \a para, or -1 if there 3074 Returns the number of lines in paragraph \a para, or -1 if there
3075 is no paragraph with index \a para. 3075 is no paragraph with index \a para.
3076*/ 3076*/
3077 3077
3078int QTextEdit::linesOfParagraph( int para ) const 3078int QTextEdit::linesOfParagraph( int para ) const
3079{ 3079{
3080 QTextParagraph *p = doc->paragAt( para ); 3080 QTextParagraph *p = doc->paragAt( para );
3081 if ( !p ) 3081 if ( !p )
3082 return -1; 3082 return -1;
3083 return p->lines(); 3083 return p->lines();
3084} 3084}
3085 3085
3086/*! 3086/*!
3087 Returns the length of the paragraph \a para (number of 3087 Returns the length of the paragraph \a para (number of
3088 characters), or -1 if there is no paragraph with index \a para 3088 characters), or -1 if there is no paragraph with index \a para
3089*/ 3089*/
3090 3090
3091int QTextEdit::paragraphLength( int para ) const 3091int QTextEdit::paragraphLength( int para ) const
3092{ 3092{
3093 QTextParagraph *p = doc->paragAt( para ); 3093 QTextParagraph *p = doc->paragAt( para );
3094 if ( !p ) 3094 if ( !p )
3095 return -1; 3095 return -1;
3096 return p->length() - 1; 3096 return p->length() - 1;
3097} 3097}
3098 3098
3099/*! 3099/*!
3100 Returns the number of lines in the text edit; this could be 0. 3100 Returns the number of lines in the text edit; this could be 0.
3101 3101
3102 \warning This function may be slow. Lines change all the time 3102 \warning This function may be slow. Lines change all the time
3103 during word wrapping, so this function has to iterate over all the 3103 during word wrapping, so this function has to iterate over all the
3104 paragraphs and get the number of lines from each one individually. 3104 paragraphs and get the number of lines from each one individually.
3105*/ 3105*/
3106 3106
3107int QTextEdit::lines() const 3107int QTextEdit::lines() const
3108{ 3108{
3109 QTextParagraph *p = doc->firstParagraph(); 3109 QTextParagraph *p = doc->firstParagraph();
3110 int l = 0; 3110 int l = 0;
3111 while ( p ) { 3111 while ( p ) {
3112 l += p->lines(); 3112 l += p->lines();
3113 p = p->next(); 3113 p = p->next();
3114 } 3114 }
3115 3115
3116 return l; 3116 return l;
3117} 3117}
3118 3118
3119/*! 3119/*!
3120 Returns the line number of the line in paragraph \a para in which 3120 Returns the line number of the line in paragraph \a para in which
3121 the character at position \a index appears. The \a index position is 3121 the character at position \a index appears. The \a index position is
3122 relative to the beginning of the paragraph. If there is no such 3122 relative to the beginning of the paragraph. If there is no such
3123 paragraph or no such character at the \a index position (e.g. the 3123 paragraph or no such character at the \a index position (e.g. the
3124 index is out of range) -1 is returned. 3124 index is out of range) -1 is returned.
3125*/ 3125*/
3126 3126
3127int QTextEdit::lineOfChar( int para, int index ) 3127int QTextEdit::lineOfChar( int para, int index )
3128{ 3128{
3129 QTextParagraph *p = doc->paragAt( para ); 3129 QTextParagraph *p = doc->paragAt( para );
3130 if ( !p ) 3130 if ( !p )
3131 return -1; 3131 return -1;
3132 3132
3133 int idx, line; 3133 int idx, line;
3134 QTextStringChar *c = p->lineStartOfChar( index, &idx, &line ); 3134 QTextStringChar *c = p->lineStartOfChar( index, &idx, &line );
3135 if ( !c ) 3135 if ( !c )
3136 return -1; 3136 return -1;
3137 3137
3138 return line; 3138 return line;
3139} 3139}
3140 3140
3141void QTextEdit::setModified( bool m ) 3141void QTextEdit::setModified( bool m )
3142{ 3142{
3143 bool oldModified = modified; 3143 bool oldModified = modified;
3144 modified = m; 3144 modified = m;
3145 if ( modified && doc->oTextValid ) 3145 if ( modified && doc->oTextValid )
3146 doc->invalidateOriginalText(); 3146 doc->invalidateOriginalText();
3147 if ( oldModified != modified ) 3147 if ( oldModified != modified )
3148 emit modificationChanged( modified ); 3148 emit modificationChanged( modified );
3149} 3149}
3150 3150
3151/*! \property QTextEdit::modified 3151/*! \property QTextEdit::modified
3152 \brief whether the document has been modified by the user 3152 \brief whether the document has been modified by the user
3153*/ 3153*/
3154 3154
3155bool QTextEdit::isModified() const 3155bool QTextEdit::isModified() const
3156{ 3156{
3157 return modified; 3157 return modified;
3158} 3158}
3159 3159
3160void QTextEdit::setModified() 3160void QTextEdit::setModified()
3161{ 3161{
3162 if ( !isModified() ) 3162 if ( !isModified() )
3163 setModified( TRUE ); 3163 setModified( TRUE );
3164} 3164}
3165 3165
3166/*! 3166/*!
3167 Returns TRUE if the current format is italic; otherwise returns FALSE. 3167 Returns TRUE if the current format is italic; otherwise returns FALSE.
3168 3168
3169 \sa setItalic() 3169 \sa setItalic()
3170*/ 3170*/
3171 3171
3172bool QTextEdit::italic() const 3172bool QTextEdit::italic() const
3173{ 3173{
3174 return currentFormat->font().italic(); 3174 return currentFormat->font().italic();
3175} 3175}
3176 3176
3177/*! 3177/*!
3178 Returns TRUE if the current format is bold; otherwise returns FALSE. 3178 Returns TRUE if the current format is bold; otherwise returns FALSE.
3179 3179
3180 \sa setBold() 3180 \sa setBold()
3181*/ 3181*/
3182 3182
3183bool QTextEdit::bold() const 3183bool QTextEdit::bold() const
3184{ 3184{
3185 return currentFormat->font().bold(); 3185 return currentFormat->font().bold();
3186} 3186}
3187 3187
3188/*! 3188/*!
3189 Returns TRUE if the current format is underlined; otherwise returns 3189 Returns TRUE if the current format is underlined; otherwise returns
3190 FALSE. 3190 FALSE.
3191 3191
3192 \sa setUnderline() 3192 \sa setUnderline()
3193*/ 3193*/
3194 3194
3195bool QTextEdit::underline() const 3195bool QTextEdit::underline() const
3196{ 3196{
3197 return currentFormat->font().underline(); 3197 return currentFormat->font().underline();
3198} 3198}
3199 3199
3200/*! 3200/*!
3201 Returns the font family of the current format. 3201 Returns the font family of the current format.
3202 3202
3203 \sa setFamily() setCurrentFont() setPointSize() 3203 \sa setFamily() setCurrentFont() setPointSize()
3204*/ 3204*/
3205 3205
3206QString QTextEdit::family() const 3206QString QTextEdit::family() const
3207{ 3207{
3208 return currentFormat->font().family(); 3208 return currentFormat->font().family();
3209} 3209}
3210 3210
3211/*! 3211/*!
3212 Returns the point size of the font of the current format. 3212 Returns the point size of the font of the current format.
3213 3213
3214 \sa setFamily() setCurrentFont() setPointSize() 3214 \sa setFamily() setCurrentFont() setPointSize()
3215 3215
3216*/ 3216*/
3217 3217
3218int QTextEdit::pointSize() const 3218int QTextEdit::pointSize() const
3219{ 3219{
3220 return currentFormat->font().pointSize(); 3220 return currentFormat->font().pointSize();
3221} 3221}
3222 3222
3223/*! 3223/*!
3224 Returns the color of the current format. 3224 Returns the color of the current format.
3225 3225
3226 \sa setColor() setPaper() 3226 \sa setColor() setPaper()
3227*/ 3227*/
3228 3228
3229QColor QTextEdit::color() const 3229QColor QTextEdit::color() const
3230{ 3230{
3231 return currentFormat->color(); 3231 return currentFormat->color();
3232} 3232}
3233 3233
3234/*! 3234/*!
3235 Returns the font of the current format. 3235 Returns the font of the current format.
3236 3236
3237 \sa setCurrentFont() setFamily() setPointSize() 3237 \sa setCurrentFont() setFamily() setPointSize()
3238 3238
3239*/ 3239*/
3240 3240
3241QFont QTextEdit::font() const 3241QFont QTextEdit::font() const
3242{ 3242{
3243 return currentFormat->font(); 3243 return currentFormat->font();
3244} 3244}
3245 3245
3246/*! 3246/*!
3247 Returns the alignment of the current paragraph. 3247 Returns the alignment of the current paragraph.
3248 3248
3249 \sa setAlignment() 3249 \sa setAlignment()
3250*/ 3250*/
3251 3251
3252int QTextEdit::alignment() const 3252int QTextEdit::alignment() const
3253{ 3253{
3254 return currentAlignment; 3254 return currentAlignment;
3255} 3255}
3256 3256
3257void QTextEdit::startDrag() 3257void QTextEdit::startDrag()
3258{ 3258{
3259#ifndef QT_NO_DRAGANDDROP 3259#ifndef QT_NO_DRAGANDDROP
3260 mousePressed = FALSE; 3260 mousePressed = FALSE;
3261 inDoubleClick = FALSE; 3261 inDoubleClick = FALSE;
3262 QDragObject *drag = new QTextDrag( doc->selectedText( QTextDocument::Standard, qt_enable_richtext_copy ), viewport() ); 3262 QDragObject *drag = new QTextDrag( doc->selectedText( QTextDocument::Standard, qt_enable_richtext_copy ), viewport() );
3263 if ( isReadOnly() ) { 3263 if ( isReadOnly() ) {
3264 drag->dragCopy(); 3264 drag->dragCopy();
3265 } else { 3265 } else {
3266 if ( drag->drag() && QDragObject::target() != this && QDragObject::target() != viewport() ) 3266 if ( drag->drag() && QDragObject::target() != this && QDragObject::target() != viewport() )
3267 removeSelectedText(); 3267 removeSelectedText();
3268 } 3268 }
3269#endif 3269#endif
3270} 3270}
3271 3271
3272/*! 3272/*!
3273 If \a select is TRUE (the default), all the text is selected as 3273 If \a select is TRUE (the default), all the text is selected as
3274 selection 0. 3274 selection 0.
3275 If \a select is FALSE any selected text is unselected, i.e., the 3275 If \a select is FALSE any selected text is unselected, i.e., the
3276 default selection (selection 0) is cleared. 3276 default selection (selection 0) is cleared.
3277 3277
3278 \sa selectedText 3278 \sa selectedText
3279*/ 3279*/
3280 3280
3281void QTextEdit::selectAll( bool select ) 3281void QTextEdit::selectAll( bool select )
3282{ 3282{
3283 if ( !select ) 3283 if ( !select )
3284 doc->removeSelection( QTextDocument::Standard ); 3284 doc->removeSelection( QTextDocument::Standard );
3285 else 3285 else
3286 doc->selectAll( QTextDocument::Standard ); 3286 doc->selectAll( QTextDocument::Standard );
3287 repaintChanged(); 3287 repaintChanged();
3288 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) ); 3288 emit copyAvailable( doc->hasSelection( QTextDocument::Standard ) );
3289 emit selectionChanged(); 3289 emit selectionChanged();
3290#ifndef QT_NO_CURSOR 3290#ifndef QT_NO_CURSOR
3291 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 3291 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
3292#endif 3292#endif
3293} 3293}
3294 3294
3295void QTextEdit::UndoRedoInfo::clear() 3295void QTextEdit::UndoRedoInfo::clear()
3296{ 3296{
3297 if ( valid() ) { 3297 if ( valid() ) {
3298 if ( type == Insert || type == Return ) 3298 if ( type == Insert || type == Return )
3299 doc->addCommand( new QTextInsertCommand( doc, id, index, d->text.rawData(), styleInformation ) ); 3299 doc->addCommand( new QTextInsertCommand( doc, id, index, d->text.rawData(), styleInformation ) );
3300 else if ( type == Format ) 3300 else if ( type == Format )
3301 doc->addCommand( new QTextFormatCommand( doc, id, index, eid, eindex, d->text.rawData(), format, flags ) ); 3301 doc->addCommand( new QTextFormatCommand( doc, id, index, eid, eindex, d->text.rawData(), format, flags ) );
3302 else if ( type == Style ) 3302 else if ( type == Style )
3303 doc->addCommand( new QTextStyleCommand( doc, id, eid, styleInformation ) ); 3303 doc->addCommand( new QTextStyleCommand( doc, id, eid, styleInformation ) );
3304 else if ( type != Invalid ) { 3304 else if ( type != Invalid ) {
3305 doc->addCommand( new QTextDeleteCommand( doc, id, index, d->text.rawData(), styleInformation ) ); 3305 doc->addCommand( new QTextDeleteCommand( doc, id, index, d->text.rawData(), styleInformation ) );
3306 } 3306 }
3307 } 3307 }
3308 type = Invalid; 3308 type = Invalid;
3309 d->text = QString::null; 3309 d->text = QString::null;
3310 id = -1; 3310 id = -1;
3311 index = -1; 3311 index = -1;
3312 styleInformation = QByteArray(); 3312 styleInformation = QByteArray();
3313} 3313}
3314 3314
3315 3315
3316/*! 3316/*!
3317 If there is some selected text (in selection 0) it is deleted. If 3317 If there is some selected text (in selection 0) it is deleted. If
3318 there is no selected text (in selection 0) the character to the 3318 there is no selected text (in selection 0) the character to the
3319 right of the text cursor is deleted. 3319 right of the text cursor is deleted.
3320 3320
3321 \sa removeSelectedText() cut() 3321 \sa removeSelectedText() cut()
3322 3322
3323*/ 3323*/
3324 3324
3325void QTextEdit::del() 3325void QTextEdit::del()
3326{ 3326{
3327 if ( doc->hasSelection( QTextDocument::Standard ) ) { 3327 if ( doc->hasSelection( QTextDocument::Standard ) ) {
3328 removeSelectedText(); 3328 removeSelectedText();
3329 return; 3329 return;
3330 } 3330 }
3331 3331
3332 doKeyboardAction( ActionDelete ); 3332 doKeyboardAction( ActionDelete );
3333} 3333}
3334 3334
3335 3335
3336QTextEdit::UndoRedoInfo::UndoRedoInfo( QTextDocument *dc ) 3336QTextEdit::UndoRedoInfo::UndoRedoInfo( QTextDocument *dc )
3337 : type( Invalid ), doc( dc ) 3337 : type( Invalid ), doc( dc )
3338{ 3338{
3339 d = new QUndoRedoInfoPrivate; 3339 d = new QUndoRedoInfoPrivate;
3340 d->text = QString::null; 3340 d->text = QString::null;
3341 id = -1; 3341 id = -1;
3342 index = -1; 3342 index = -1;
3343} 3343}
3344 3344
3345QTextEdit::UndoRedoInfo::~UndoRedoInfo() 3345QTextEdit::UndoRedoInfo::~UndoRedoInfo()
3346{ 3346{
3347 delete d; 3347 delete d;
3348} 3348}
3349 3349
3350bool QTextEdit::UndoRedoInfo::valid() const 3350bool QTextEdit::UndoRedoInfo::valid() const
3351{ 3351{
3352 return id >= 0 && type != Invalid; 3352 return id >= 0 && type != Invalid;
3353} 3353}
3354 3354
3355/*! 3355/*!
3356 \internal 3356 \internal
3357 3357
3358 Resets the current format to the default format. 3358 Resets the current format to the default format.
3359*/ 3359*/
3360 3360
3361void QTextEdit::resetFormat() 3361void QTextEdit::resetFormat()
3362{ 3362{
3363 setAlignment( Qt3::AlignAuto ); 3363 setAlignment( Qt3::AlignAuto );
3364 setParagType( QStyleSheetItem::DisplayBlock, QStyleSheetItem::ListDisc ); 3364 setParagType( QStyleSheetItem::DisplayBlock, QStyleSheetItem::ListDisc );
3365 setFormat( doc->formatCollection()->defaultFormat(), QTextFormat::Format ); 3365 setFormat( doc->formatCollection()->defaultFormat(), QTextFormat::Format );
3366} 3366}
3367 3367
3368/*! Returns the QStyleSheet which is currently used in this text edit. 3368/*! Returns the QStyleSheet which is currently used in this text edit.
3369 3369
3370 \sa setStyleSheet() 3370 \sa setStyleSheet()
3371 */ 3371 */
3372 3372
3373QStyleSheet* QTextEdit::styleSheet() const 3373QStyleSheet* QTextEdit::styleSheet() const
3374{ 3374{
3375 return doc->styleSheet(); 3375 return doc->styleSheet();
3376} 3376}
3377 3377
3378/*! Sets the stylesheet to use with this text edit to \a styleSheet. Changes 3378/*! Sets the stylesheet to use with this text edit to \a styleSheet. Changes
3379 will only take effect for new text added with setText() or append(). 3379 will only take effect for new text added with setText() or append().
3380 3380
3381 \sa styleSheet() 3381 \sa styleSheet()
3382 */ 3382 */
3383 3383
3384void QTextEdit::setStyleSheet( QStyleSheet* styleSheet ) 3384void QTextEdit::setStyleSheet( QStyleSheet* styleSheet )
3385{ 3385{
3386 doc->setStyleSheet( styleSheet ); 3386 doc->setStyleSheet( styleSheet );
3387} 3387}
3388 3388
3389/*! 3389/*!
3390 \property QTextEdit::paper 3390 \property QTextEdit::paper
3391 \brief the background (paper) brush. 3391 \brief the background (paper) brush.
3392 3392
3393 The brush that is currently used to draw the background of the 3393 The brush that is currently used to draw the background of the
3394 text edit. The initial setting is an empty brush. 3394 text edit. The initial setting is an empty brush.
3395 */ 3395 */
3396 3396
3397void QTextEdit::setPaper( const QBrush& pap ) 3397void QTextEdit::setPaper( const QBrush& pap )
3398{ 3398{
3399 doc->setPaper( new QBrush( pap ) ); 3399 doc->setPaper( new QBrush( pap ) );
3400 viewport()->setBackgroundColor( pap.color() ); 3400 viewport()->setBackgroundColor( pap.color() );
3401 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 3401 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
3402} 3402}
3403 3403
3404QBrush QTextEdit::paper() const 3404QBrush QTextEdit::paper() const
3405{ 3405{
3406 if ( doc->paper() ) 3406 if ( doc->paper() )
3407 return *doc->paper(); 3407 return *doc->paper();
3408 return QBrush(); 3408 return QBrush();
3409} 3409}
3410 3410
3411/*! 3411/*!
3412 \property QTextEdit::linkUnderline 3412 \property QTextEdit::linkUnderline
3413 \brief whether hypertext links will be underlined 3413 \brief whether hypertext links will be underlined
3414 3414
3415 If TRUE (the default) hypertext links will be displayed underlined. 3415 If TRUE (the default) hypertext links will be displayed underlined.
3416 If FALSE links will not be displayed underlined. 3416 If FALSE links will not be displayed underlined.
3417*/ 3417*/
3418 3418
3419void QTextEdit::setLinkUnderline( bool b ) 3419void QTextEdit::setLinkUnderline( bool b )
3420{ 3420{
3421 doc->setUnderlineLinks( b ); 3421 doc->setUnderlineLinks( b );
3422} 3422}
3423 3423
3424bool QTextEdit::linkUnderline() const 3424bool QTextEdit::linkUnderline() const
3425{ 3425{
3426 return doc->underlineLinks(); 3426 return doc->underlineLinks();
3427} 3427}
3428 3428
3429/*! Sets the text edit's mimesource factory to \a factory. See 3429/*! Sets the text edit's mimesource factory to \a factory. See
3430 QMimeSourceFactory for further details. 3430 QMimeSourceFactory for further details.
3431 3431
3432 \sa mimeSourceFactory() 3432 \sa mimeSourceFactory()
3433 */ 3433 */
3434 3434
3435void QTextEdit::setMimeSourceFactory( QMimeSourceFactory* factory ) 3435void QTextEdit::setMimeSourceFactory( QMimeSourceFactory* factory )
3436{ 3436{
3437 doc->setMimeSourceFactory( factory ); 3437 doc->setMimeSourceFactory( factory );
3438} 3438}
3439 3439
3440/*! Returns the QMimeSourceFactory which is currently used by this 3440/*! Returns the QMimeSourceFactory which is currently used by this
3441 text edit. 3441 text edit.
3442 3442
3443 \sa setMimeSourceFactory() 3443 \sa setMimeSourceFactory()
3444*/ 3444*/
3445 3445
3446QMimeSourceFactory* QTextEdit::mimeSourceFactory() const 3446QMimeSourceFactory* QTextEdit::mimeSourceFactory() const
3447{ 3447{
3448 return doc->mimeSourceFactory(); 3448 return doc->mimeSourceFactory();
3449} 3449}
3450 3450
3451/*! 3451/*!
3452 Returns how many pixels high the text edit needs to be to display 3452 Returns how many pixels high the text edit needs to be to display
3453 all the text if the text edit is \a w pixels wide. 3453 all the text if the text edit is \a w pixels wide.
3454*/ 3454*/
3455 3455
3456int QTextEdit::heightForWidth( int w ) const 3456int QTextEdit::heightForWidth( int w ) const
3457{ 3457{
3458 int oldw = doc->width(); 3458 int oldw = doc->width();
3459 doc->doLayout( 0, w ); 3459 doc->doLayout( 0, w );
3460 int h = doc->height(); 3460 int h = doc->height();
3461 doc->setWidth( oldw ); 3461 doc->setWidth( oldw );
3462 doc->invalidate(); 3462 doc->invalidate();
3463 ( (QTextEdit*)this )->formatMore(); 3463 ( (QTextEdit*)this )->formatMore();
3464 return h; 3464 return h;
3465} 3465}
3466 3466
3467/*! Appends the text \a text to the end of the text edit. 3467/*! Appends the text \a text to the end of the text edit.
3468 Note that the undo/redo history is cleared by this function. 3468 Note that the undo/redo history is cleared by this function.
3469 */ 3469 */
3470 3470
3471void QTextEdit::append( const QString &text ) 3471void QTextEdit::append( const QString &text )
3472{ 3472{
3473 // flush and clear the undo/redo stack if necessary 3473 // flush and clear the undo/redo stack if necessary
3474 undoRedoInfo.clear(); 3474 undoRedoInfo.clear();
3475 doc->commands()->clear(); 3475 doc->commands()->clear();
3476 3476
3477 doc->removeSelection( QTextDocument::Standard ); 3477 doc->removeSelection( QTextDocument::Standard );
3478 TextFormat f = doc->textFormat(); 3478 TextFormat f = doc->textFormat();
3479 if ( f == AutoText ) { 3479 if ( f == AutoText ) {
3480 if ( QStyleSheet::mightBeRichText( text ) ) 3480 if ( QStyleSheet::mightBeRichText( text ) )
3481 f = RichText; 3481 f = RichText;
3482 else 3482 else
3483 f = PlainText; 3483 f = PlainText;
3484 } 3484 }
3485 3485
3486 drawCursor( FALSE ); 3486 drawCursor( FALSE );
3487 QTextCursor oldc( *cursor ); 3487 QTextCursor oldc( *cursor );
3488 ensureFormatted( doc->lastParagraph() ); 3488 ensureFormatted( doc->lastParagraph() );
3489 bool atBottom = contentsY() >= contentsHeight() - visibleHeight(); 3489 bool atBottom = contentsY() >= contentsHeight() - visibleHeight();
3490 cursor->gotoEnd(); 3490 cursor->gotoEnd();
3491 if ( cursor->index() > 0 ) 3491 if ( cursor->index() > 0 )
3492 cursor->splitAndInsertEmptyParagraph(); 3492 cursor->splitAndInsertEmptyParagraph();
3493 QTextCursor oldCursor2 = *cursor; 3493 QTextCursor oldCursor2 = *cursor;
3494 3494
3495 if ( f == Qt::PlainText ) { 3495 if ( f == Qt::PlainText ) {
3496 cursor->insert( text, TRUE ); 3496 cursor->insert( text, TRUE );
3497 if ( doc->useFormatCollection() && 3497 if ( doc->useFormatCollection() &&
3498 currentFormat != cursor->paragraph()->at( cursor->index() )->format() ) { 3498 currentFormat != cursor->paragraph()->at( cursor->index() )->format() ) {
3499 doc->setSelectionStart( QTextDocument::Temp, oldCursor2 ); 3499 doc->setSelectionStart( QTextDocument::Temp, oldCursor2 );
3500 doc->setSelectionEnd( QTextDocument::Temp, *cursor ); 3500 doc->setSelectionEnd( QTextDocument::Temp, *cursor );
3501 doc->setFormat( QTextDocument::Temp, currentFormat, QTextFormat::Format ); 3501 doc->setFormat( QTextDocument::Temp, currentFormat, QTextFormat::Format );
3502 doc->removeSelection( QTextDocument::Temp ); 3502 doc->removeSelection( QTextDocument::Temp );
3503 } 3503 }
3504 } else { 3504 } else {
3505 if ( cursor->paragraph()->prev() ) 3505 if ( cursor->paragraph()->prev() )
3506 cursor->paragraph()->prev()->invalidate(0); // vertical margins might have to change 3506 cursor->paragraph()->prev()->invalidate(0); // vertical margins might have to change
3507 doc->setRichTextInternal( text ); 3507 doc->setRichTextInternal( text );
3508 } 3508 }
3509 formatMore(); 3509 formatMore();
3510 repaintChanged(); 3510 repaintChanged();
3511 if ( atBottom ) 3511 if ( atBottom )
3512 scrollToBottom(); 3512 scrollToBottom();
3513 *cursor = oldc; 3513 *cursor = oldc;
3514 if ( !isReadOnly() ) 3514 if ( !isReadOnly() )
3515 cursorVisible = TRUE; 3515 cursorVisible = TRUE;
3516 setModified(); 3516 setModified();
3517 emit textChanged(); 3517 emit textChanged();
3518} 3518}
3519 3519
3520/*! \property QTextEdit::hasSelectedText 3520/*! \property QTextEdit::hasSelectedText
3521 \brief whether some text is selected in selection 0 3521 \brief whether some text is selected in selection 0
3522 */ 3522 */
3523 3523
3524bool QTextEdit::hasSelectedText() const 3524bool QTextEdit::hasSelectedText() const
3525{ 3525{
3526 return doc->hasSelection( QTextDocument::Standard ); 3526 return doc->hasSelection( QTextDocument::Standard );
3527} 3527}
3528 3528
3529/*!\property QTextEdit::selectedText 3529/*!\property QTextEdit::selectedText
3530 \brief The selected text (from selection 0) or an empty string if 3530 \brief The selected text (from selection 0) or an empty string if
3531 there is no currently selected text (in selection 0). 3531 there is no currently selected text (in selection 0).
3532 3532
3533 The text is always returned as \c PlainText regardless of the text 3533 The text is always returned as \c PlainText regardless of the text
3534 format. In a future version of Qt an HTML subset \e may be returned 3534 format. In a future version of Qt an HTML subset \e may be returned
3535 depending on the text format. 3535 depending on the text format.
3536 3536
3537 \sa hasSelectedText 3537 \sa hasSelectedText
3538 */ 3538 */
3539 3539
3540QString QTextEdit::selectedText() const 3540QString QTextEdit::selectedText() const
3541{ 3541{
3542 return doc->selectedText( QTextDocument::Standard ); 3542 return doc->selectedText( QTextDocument::Standard );
3543} 3543}
3544 3544
3545bool QTextEdit::handleReadOnlyKeyEvent( QKeyEvent *e ) 3545bool QTextEdit::handleReadOnlyKeyEvent( QKeyEvent *e )
3546{ 3546{
3547 switch( e->key() ) { 3547 switch( e->key() ) {
3548 case Key_Down: 3548 case Key_Down:
3549 setContentsPos( contentsX(), contentsY() + 10 ); 3549 setContentsPos( contentsX(), contentsY() + 10 );
3550 break; 3550 break;
3551 case Key_Up: 3551 case Key_Up:
3552 setContentsPos( contentsX(), contentsY() - 10 ); 3552 setContentsPos( contentsX(), contentsY() - 10 );
3553 break; 3553 break;
3554 case Key_Left: 3554 case Key_Left:
3555 setContentsPos( contentsX() - 10, contentsY() ); 3555 setContentsPos( contentsX() - 10, contentsY() );
3556 break; 3556 break;
3557 case Key_Right: 3557 case Key_Right:
3558 setContentsPos( contentsX() + 10, contentsY() ); 3558 setContentsPos( contentsX() + 10, contentsY() );
3559 break; 3559 break;
3560 case Key_PageUp: 3560 case Key_PageUp:
3561 setContentsPos( contentsX(), contentsY() - visibleHeight() ); 3561 setContentsPos( contentsX(), contentsY() - visibleHeight() );
3562 break; 3562 break;
3563 case Key_PageDown: 3563 case Key_PageDown:
3564 setContentsPos( contentsX(), contentsY() + visibleHeight() ); 3564 setContentsPos( contentsX(), contentsY() + visibleHeight() );
3565 break; 3565 break;
3566 case Key_Home: 3566 case Key_Home:
3567 setContentsPos( contentsX(), 0 ); 3567 setContentsPos( contentsX(), 0 );
3568 break; 3568 break;
3569 case Key_End: 3569 case Key_End:
3570 setContentsPos( contentsX(), contentsHeight() - visibleHeight() ); 3570 setContentsPos( contentsX(), contentsHeight() - visibleHeight() );
3571 break; 3571 break;
3572 case Key_F16: // Copy key on Sun keyboards 3572 case Key_F16: // Copy key on Sun keyboards
3573 copy(); 3573 copy();
3574 break; 3574 break;
3575#ifndef QT_NO_NETWORKPROTOCOL 3575#ifndef QT_NO_NETWORKPROTOCOL
3576 case Key_Return: 3576 case Key_Return:
3577 case Key_Enter: 3577 case Key_Enter:
3578 case Key_Space: { 3578 case Key_Space: {
3579 if ( !doc->focusIndicator.href.isEmpty() ) { 3579 if ( !doc->focusIndicator.href.isEmpty() ) {
3580 QUrl u( doc->context(), doc->focusIndicator.href, TRUE ); 3580 QUrl u( doc->context(), doc->focusIndicator.href, TRUE );
3581 emitLinkClicked( u.toString( FALSE, FALSE ) ); 3581 emitLinkClicked( u.toString( FALSE, FALSE ) );
3582#ifndef QT_NO_CURSOR 3582#ifndef QT_NO_CURSOR
3583 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 3583 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
3584#endif 3584#endif
3585 } 3585 }
3586 } break; 3586 } break;
3587#endif 3587#endif
3588 default: 3588 default:
3589 if ( e->state() & ControlButton ) { 3589 if ( e->state() & ControlButton ) {
3590 switch ( e->key() ) { 3590 switch ( e->key() ) {
3591 case Key_C: case Key_F16: // Copy key on Sun keyboards 3591 case Key_C: case Key_F16: // Copy key on Sun keyboards
3592 copy(); 3592 copy();
3593 break; 3593 break;
3594 } 3594 }
3595 } 3595 }
3596 return FALSE; 3596 return FALSE;
3597 } 3597 }
3598 return TRUE; 3598 return TRUE;
3599} 3599}
3600 3600
3601/*! Returns the context of the edit. 3601/*! Returns the context of the edit.
3602 The context is a path which the text edit's QMimeSourceFactory 3602 The context is a path which the text edit's QMimeSourceFactory
3603 uses to resolve the locations of files and images. 3603 uses to resolve the locations of files and images.
3604 3604
3605 \sa text 3605 \sa text
3606*/ 3606*/
3607 3607
3608QString QTextEdit::context() const 3608QString QTextEdit::context() const
3609{ 3609{
3610 return doc->context(); 3610 return doc->context();
3611} 3611}
3612 3612
3613/*! 3613/*!
3614 \property QTextEdit::documentTitle 3614 \property QTextEdit::documentTitle
3615 \brief the title of the document parsed from the text. 3615 \brief the title of the document parsed from the text.
3616 3616
3617 For \c PlainText the title will be an empty string. For \c RichText 3617 For \c PlainText the title will be an empty string. For \c RichText
3618 the title will be the text between the \c{<title>} tags, if present, 3618 the title will be the text between the \c{<title>} tags, if present,
3619 otherwise an empty string. 3619 otherwise an empty string.
3620*/ 3620*/
3621 3621
3622QString QTextEdit::documentTitle() const 3622QString QTextEdit::documentTitle() const
3623{ 3623{
3624 return doc->attributes()[ "title" ]; 3624 return doc->attributes()[ "title" ];
3625} 3625}
3626 3626
3627void QTextEdit::makeParagVisible( QTextParagraph *p ) 3627void QTextEdit::makeParagVisible( QTextParagraph *p )
3628{ 3628{
3629 setContentsPos( contentsX(), QMIN( p->rect().y(), contentsHeight() - visibleHeight() ) ); 3629 setContentsPos( contentsX(), QMIN( p->rect().y(), contentsHeight() - visibleHeight() ) );
3630} 3630}
3631 3631
3632/*! Scrolls the text edit to make the text at the anchor called \a name 3632/*! Scrolls the text edit to make the text at the anchor called \a name
3633 visible, if it can be found in the document. If the anchor isn't found 3633 visible, if it can be found in the document. If the anchor isn't found
3634 no scrolling will occur. An anchor is defined using the HTML anchor 3634 no scrolling will occur. An anchor is defined using the HTML anchor
3635 tag, e.g. \c{<a name="target">}. 3635 tag, e.g. \c{<a name="target">}.
3636*/ 3636*/
3637 3637
3638void QTextEdit::scrollToAnchor( const QString& name ) 3638void QTextEdit::scrollToAnchor( const QString& name )
3639{ 3639{
3640 if ( !isVisible() ) { 3640 if ( !isVisible() ) {
3641 d->scrollToAnchor = name; 3641 d->scrollToAnchor = name;
3642 return; 3642 return;
3643 } 3643 }
3644 if ( name.isEmpty() ) 3644 if ( name.isEmpty() )
3645 return; 3645 return;
3646 sync(); 3646 sync();
3647 QTextCursor cursor( doc ); 3647 QTextCursor cursor( doc );
3648 QTextParagraph* last = doc->lastParagraph(); 3648 QTextParagraph* last = doc->lastParagraph();
3649 for (;;) { 3649 for (;;) {
3650 QTextStringChar* c = cursor.paragraph()->at( cursor.index() ); 3650 QTextStringChar* c = cursor.paragraph()->at( cursor.index() );
3651 if( c->isAnchor() ) { 3651 if( c->isAnchor() ) {
3652 QString a = c->anchorName(); 3652 QString a = c->anchorName();
3653 if ( a == name || 3653 if ( a == name ||
3654 (a.contains( '#' ) && QStringList::split( '#', a ).contains( name ) ) ) { 3654 (a.contains( '#' ) && QStringList::split( '#', a ).contains( name ) ) ) {
3655 setContentsPos( contentsX(), QMIN( cursor.paragraph()->rect().top() + cursor.totalOffsetY(), contentsHeight() - visibleHeight() ) ); 3655 setContentsPos( contentsX(), QMIN( cursor.paragraph()->rect().top() + cursor.totalOffsetY(), contentsHeight() - visibleHeight() ) );
3656 break; 3656 break;
3657 } 3657 }
3658 } 3658 }
3659 if ( cursor.paragraph() == last && cursor.atParagEnd() ) 3659 if ( cursor.paragraph() == last && cursor.atParagEnd() )
3660 break; 3660 break;
3661 cursor.gotoNextLetter(); 3661 cursor.gotoNextLetter();
3662 } 3662 }
3663} 3663}
3664 3664
3665/*! If there is an anchor at position \a pos (in contents 3665/*! If there is an anchor at position \a pos (in contents
3666 coordinates), its name is returned, otherwise an empty string is 3666 coordinates), its name is returned, otherwise an empty string is
3667 returned. 3667 returned.
3668*/ 3668*/
3669 3669
3670QString QTextEdit::anchorAt( const QPoint& pos ) 3670QString QTextEdit::anchorAt( const QPoint& pos )
3671{ 3671{
3672 QTextCursor c( doc ); 3672 QTextCursor c( doc );
3673 placeCursor( pos, &c ); 3673 placeCursor( pos, &c );
3674 return c.paragraph()->at( c.index() )->anchorHref(); 3674 return c.paragraph()->at( c.index() )->anchorHref();
3675} 3675}
3676 3676
3677void QTextEdit::documentWidthChanged( int w ) 3677void QTextEdit::documentWidthChanged( int w )
3678{ 3678{
3679 resizeContents( QMAX( visibleWidth(), w), contentsHeight() ); 3679 resizeContents( QMAX( visibleWidth(), w), contentsHeight() );
3680} 3680}
3681 3681
3682/*! \internal 3682/*! \internal
3683 3683
3684 This function does nothing 3684 This function does nothing
3685*/ 3685*/
3686 3686
3687void QTextEdit::updateStyles() 3687void QTextEdit::updateStyles()
3688{ 3688{
3689} 3689}
3690 3690
3691void QTextEdit::setDocument( QTextDocument *dc ) 3691void QTextEdit::setDocument( QTextDocument *dc )
3692{ 3692{
3693 if ( dc == doc ) 3693 if ( dc == doc )
3694 return; 3694 return;
3695 doc = dc; 3695 doc = dc;
3696 delete cursor; 3696 delete cursor;
3697 cursor = new QTextCursor( doc ); 3697 cursor = new QTextCursor( doc );
3698 clearUndoRedo(); 3698 clearUndoRedo();
3699 undoRedoInfo.doc = doc; 3699 undoRedoInfo.doc = doc;
3700 lastFormatted = 0; 3700 lastFormatted = 0;
3701} 3701}
3702 3702
3703#ifndef QT_NO_CLIPBOARD 3703#ifndef QT_NO_CLIPBOARD
3704 3704
3705/*! 3705/*!
3706 Pastes the text with format \a subtype from the clipboard into the 3706 Pastes the text with format \a subtype from the clipboard into the
3707 text edit at the current cursor position. The \a subtype can be 3707 text edit at the current cursor position. The \a subtype can be
3708 "plain" or "html". 3708 "plain" or "html".
3709 3709
3710 If there is no text with format \a subtype in the clipboard nothing 3710 If there is no text with format \a subtype in the clipboard nothing
3711 happens. 3711 happens.
3712 3712
3713 \sa paste() cut() QTextEdit::copy() 3713 \sa paste() cut() QTextEdit::copy()
3714*/ 3714*/
3715void QTextEdit::pasteSubType( const QCString& subtype ) 3715void QTextEdit::pasteSubType( const QCString& subtype )
3716{ 3716{
3717 QCString st = subtype; 3717 QCString st = subtype;
3718 QString t = QApplication::clipboard()->text(st); 3718 QString t = QApplication::clipboard()->text(st);
3719 if ( doc->hasSelection( QTextDocument::Standard ) ) 3719 if ( doc->hasSelection( QTextDocument::Standard ) )
3720 removeSelectedText(); 3720 removeSelectedText();
3721 if ( !t.isEmpty() ) { 3721 if ( !t.isEmpty() ) {
3722 if ( t.startsWith( "<selstart/>" ) ) { 3722 if ( t.startsWith( "<selstart/>" ) ) {
3723 t.remove( 0, 11 ); 3723 t.remove( 0, 11 );
3724 QTextCursor oldC = *cursor; 3724 QTextCursor oldC = *cursor;
3725 lastFormatted = cursor->paragraph(); 3725 lastFormatted = cursor->paragraph();
3726 if ( lastFormatted->prev() ) 3726 if ( lastFormatted->prev() )
3727 lastFormatted = lastFormatted->prev(); 3727 lastFormatted = lastFormatted->prev();
3728 doc->setRichTextInternal( t, cursor ); 3728 doc->setRichTextInternal( t, cursor );
3729 3729
3730 if ( undoEnabled && !isReadOnly() ) { 3730 if ( undoEnabled && !isReadOnly() ) {
3731 doc->setSelectionStart( QTextDocument::Temp, oldC ); 3731 doc->setSelectionStart( QTextDocument::Temp, oldC );
3732 doc->setSelectionEnd( QTextDocument::Temp, *cursor ); 3732 doc->setSelectionEnd( QTextDocument::Temp, *cursor );
3733 3733
3734 checkUndoRedoInfo( UndoRedoInfo::Insert ); 3734 checkUndoRedoInfo( UndoRedoInfo::Insert );
3735 if ( !undoRedoInfo.valid() ) { 3735 if ( !undoRedoInfo.valid() ) {
3736 undoRedoInfo.id = oldC.paragraph()->paragId(); 3736 undoRedoInfo.id = oldC.paragraph()->paragId();
3737 undoRedoInfo.index = oldC.index(); 3737 undoRedoInfo.index = oldC.index();
3738 undoRedoInfo.d->text = QString::null; 3738 undoRedoInfo.d->text = QString::null;
3739 } 3739 }
3740 int oldLen = undoRedoInfo.d->text.length(); 3740 int oldLen = undoRedoInfo.d->text.length();
3741 if ( !doc->preProcessor() ) { 3741 if ( !doc->preProcessor() ) {
3742 QString txt = doc->selectedText( QTextDocument::Temp ); 3742 QString txt = doc->selectedText( QTextDocument::Temp );
3743 undoRedoInfo.d->text += txt; 3743 undoRedoInfo.d->text += txt;
3744 for ( int i = 0; i < (int)txt.length(); ++i ) { 3744 for ( int i = 0; i < (int)txt.length(); ++i ) {
3745 if ( txt[ i ] != '\n' && oldC.paragraph()->at( oldC.index() )->format() ) { 3745 if ( txt[ i ] != '\n' && oldC.paragraph()->at( oldC.index() )->format() ) {
3746 oldC.paragraph()->at( oldC.index() )->format()->addRef(); 3746 oldC.paragraph()->at( oldC.index() )->format()->addRef();
3747 undoRedoInfo.d->text. 3747 undoRedoInfo.d->text.
3748 setFormat( oldLen + i, oldC.paragraph()->at( oldC.index() )->format(), TRUE ); 3748 setFormat( oldLen + i, oldC.paragraph()->at( oldC.index() )->format(), TRUE );
3749 } 3749 }
3750 oldC.gotoNextLetter(); 3750 oldC.gotoNextLetter();
3751 } 3751 }
3752 } 3752 }
3753 undoRedoInfo.clear(); 3753 undoRedoInfo.clear();
3754 removeSelection( QTextDocument::Temp ); 3754 removeSelection( QTextDocument::Temp );
3755 } 3755 }
3756 3756
3757 formatMore(); 3757 formatMore();
3758 setModified(); 3758 setModified();
3759 emit textChanged(); 3759 emit textChanged();
3760 repaintChanged(); 3760 repaintChanged();
3761 ensureCursorVisible(); 3761 ensureCursorVisible();
3762 return; 3762 return;
3763 } 3763 }
3764 3764
3765#if defined(Q_OS_WIN32) 3765#if defined(Q_OS_WIN32)
3766 // Need to convert CRLF to LF 3766 // Need to convert CRLF to LF
3767 int index = t.find( QString::fromLatin1("\r\n"), 0 ); 3767 int index = t.find( QString::fromLatin1("\r\n"), 0 );
3768 while ( index != -1 ) { 3768 while ( index != -1 ) {
3769 t.replace( index, 2, QChar('\n') ); 3769 t.replace( index, 2, QChar('\n') );
3770 index = t.find( "\r\n", index ); 3770 index = t.find( "\r\n", index );
3771 } 3771 }
3772#elif defined(Q_OS_MAC) 3772#elif defined(Q_OS_MAC)
3773 //need to convert CR to LF 3773 //need to convert CR to LF
3774 for( unsigned int index = 0; index < t.length(); index++ ) 3774 for( unsigned int index = 0; index < t.length(); index++ )
3775 if(t[index] == '\r') 3775 if(t[index] == '\r')
3776 t[index] = '\n'; 3776 t[index] = '\n';
3777#endif 3777#endif
3778 for ( int i=0; (uint) i<t.length(); i++ ) { 3778 for ( int i=0; (uint) i<t.length(); i++ ) {
3779 if ( t[ i ] < ' ' && t[ i ] != '\n' && t[ i ] != '\t' ) 3779 if ( t[ i ] < ' ' && t[ i ] != '\n' && t[ i ] != '\t' )
3780 t[ i ] = ' '; 3780 t[ i ] = ' ';
3781 } 3781 }
3782 if ( !t.isEmpty() ) 3782 if ( !t.isEmpty() )
3783 insert( t, FALSE, TRUE, TRUE ); 3783 insert( t, FALSE, TRUE, TRUE );
3784 } 3784 }
3785} 3785}
3786 3786
3787#ifndef QT_NO_MIMECLIPBOARD 3787#ifndef QT_NO_MIMECLIPBOARD
3788/*! 3788/*!
3789 Prompts the user to choose a type from a list of text types available, 3789 Prompts the user to choose a type from a list of text types available,
3790 then copies text from the clipboard (if there is any) into the text 3790 then copies text from the clipboard (if there is any) into the text
3791 edit at the current text cursor position. Any selected text (in 3791 edit at the current text cursor position. Any selected text (in
3792 selection 0) is first deleted. 3792 selection 0) is first deleted.
3793*/ 3793*/
3794void QTextEdit::pasteSpecial( const QPoint& pt ) 3794void QTextEdit::pasteSpecial( const QPoint& pt )
3795{ 3795{
3796 QCString st = pickSpecial( QApplication::clipboard()->data(), TRUE, pt ); 3796 QCString st = pickSpecial( QApplication::clipboard()->data(), TRUE, pt );
3797 if ( !st.isEmpty() ) 3797 if ( !st.isEmpty() )
3798 pasteSubType( st ); 3798 pasteSubType( st );
3799} 3799}
3800#endif 3800#endif
3801#ifndef QT_NO_MIME 3801#ifndef QT_NO_MIME
3802QCString QTextEdit::pickSpecial( QMimeSource* ms, bool always_ask, const QPoint& pt ) 3802QCString QTextEdit::pickSpecial( QMimeSource* ms, bool always_ask, const QPoint& pt )
3803{ 3803{
3804 if ( ms ) { 3804 if ( ms ) {
3805#ifndef QT_NO_POPUPMENU 3805#ifndef QT_NO_POPUPMENU
3806 QPopupMenu popup( this, "qt_pickspecial_menu" ); 3806 QPopupMenu popup( this, "qt_pickspecial_menu" );
3807 QString fmt; 3807 QString fmt;
3808 int n = 0; 3808 int n = 0;
3809 QDict<void> done; 3809 QDict<void> done;
3810 for (int i = 0; !( fmt = ms->format( i ) ).isNull(); i++) { 3810 for (int i = 0; !( fmt = ms->format( i ) ).isNull(); i++) {
3811 int semi = fmt.find( ";" ); 3811 int semi = fmt.find( ";" );
3812 if ( semi >= 0 ) 3812 if ( semi >= 0 )
3813 fmt = fmt.left( semi ); 3813 fmt = fmt.left( semi );
3814 if ( fmt.left( 5 ) == "text/" ) { 3814 if ( fmt.left( 5 ) == "text/" ) {
3815 fmt = fmt.mid( 5 ); 3815 fmt = fmt.mid( 5 );
3816 if ( !done.find( fmt ) ) { 3816 if ( !done.find( fmt ) ) {
3817 done.insert( fmt,(void*)1 ); 3817 done.insert( fmt,(void*)1 );
3818 popup.insertItem( fmt, i ); 3818 popup.insertItem( fmt, i );
3819 n++; 3819 n++;
3820 } 3820 }
3821 } 3821 }
3822 } 3822 }
3823 if ( n ) { 3823 if ( n ) {
3824 int i = n ==1 && !always_ask ? popup.idAt( 0 ) : popup.exec( pt ); 3824 int i = n ==1 && !always_ask ? popup.idAt( 0 ) : popup.exec( pt );
3825 if ( i >= 0 ) 3825 if ( i >= 0 )
3826 return popup.text(i).latin1(); 3826 return popup.text(i).latin1();
3827 } 3827 }
3828#else 3828#else
3829 QString fmt; 3829 QString fmt;
3830 for (int i = 0; !( fmt = ms->format( i ) ).isNull(); i++) { 3830 for (int i = 0; !( fmt = ms->format( i ) ).isNull(); i++) {
3831 int semi = fmt.find( ";" ); 3831 int semi = fmt.find( ";" );
3832 if ( semi >= 0 ) 3832 if ( semi >= 0 )
3833 fmt = fmt.left( semi ); 3833 fmt = fmt.left( semi );
3834 if ( fmt.left( 5 ) == "text/" ) { 3834 if ( fmt.left( 5 ) == "text/" ) {
3835 fmt = fmt.mid( 5 ); 3835 fmt = fmt.mid( 5 );
3836 return fmt.latin1(); 3836 return fmt.latin1();
3837 } 3837 }
3838 } 3838 }
3839#endif 3839#endif
3840 } 3840 }
3841 return QCString(); 3841 return QCString();
3842} 3842}
3843#endif // QT_NO_MIME 3843#endif // QT_NO_MIME
3844#endif // QT_NO_CLIPBOARD 3844#endif // QT_NO_CLIPBOARD
3845 3845
3846/*! \enum QTextEdit::WordWrap 3846/*! \enum QTextEdit::WordWrap
3847 3847
3848 This enum defines the QTextEdit's word wrap modes. The following 3848 This enum defines the QTextEdit's word wrap modes. The following
3849 values are valid: 3849 values are valid:
3850 3850
3851 \value NoWrap Do not wrap the text. 3851 \value NoWrap Do not wrap the text.
3852 3852
3853 \value WidgetWidth Wrap the text at the current width of the 3853 \value WidgetWidth Wrap the text at the current width of the
3854 widget (this is the default). Wrapping is at whitespace by default; 3854 widget (this is the default). Wrapping is at whitespace by default;
3855 this can be changed with setWrapPolicy(). 3855 this can be changed with setWrapPolicy().
3856 3856
3857 \value FixedPixelWidth Wrap the text at a fixed number of pixels from 3857 \value FixedPixelWidth Wrap the text at a fixed number of pixels from
3858 the widget's left side. The number of pixels is set with 3858 the widget's left side. The number of pixels is set with
3859 wrapColumnOrWidth(). 3859 wrapColumnOrWidth().
3860 3860
3861 \value FixedColumnWidth Wrap the text at a fixed number of character 3861 \value FixedColumnWidth Wrap the text at a fixed number of character
3862 columns from the widget's left side. The number of characters is set 3862 columns from the widget's left side. The number of characters is set
3863 with wrapColumnOrWidth(). 3863 with wrapColumnOrWidth().
3864 This is useful if you need formatted text that can also be 3864 This is useful if you need formatted text that can also be
3865 displayed gracefully on devices with monospaced fonts, for example a 3865 displayed gracefully on devices with monospaced fonts, for example a
3866 standard VT100 terminal, where you might set wrapColumnOrWidth() to 3866 standard VT100 terminal, where you might set wrapColumnOrWidth() to
3867 80. 3867 80.
3868 3868
3869 \sa setWordWrap() wordWrap() 3869 \sa setWordWrap() wordWrap()
3870*/ 3870*/
3871 3871
3872/*! 3872/*!
3873 \property QTextEdit::wordWrap 3873 \property QTextEdit::wordWrap
3874 \brief the word wrap mode 3874 \brief the word wrap mode
3875 3875
3876 The default mode is \c WidgetWidth which causes words to be wrapped 3876 The default mode is \c WidgetWidth which causes words to be wrapped
3877 at the right edge of the text edit. Wrapping occurs at whitespace, 3877 at the right edge of the text edit. Wrapping occurs at whitespace,
3878 keeping whole words intact. If you want wrapping to occur within 3878 keeping whole words intact. If you want wrapping to occur within
3879 words use setWrapPolicy(). If you set a wrap mode of \c 3879 words use setWrapPolicy(). If you set a wrap mode of \c
3880 FixedPixelWidth or \c FixedColumnWidth you should also call 3880 FixedPixelWidth or \c FixedColumnWidth you should also call
3881 setWrapColumnOrWidth() with the width you want. 3881 setWrapColumnOrWidth() with the width you want.
3882 3882
3883 \sa WordWrap, wrapColumnOrWidth, wrapPolicy, 3883 \sa WordWrap, wrapColumnOrWidth, wrapPolicy,
3884*/ 3884*/
3885 3885
3886void QTextEdit::setWordWrap( WordWrap mode ) 3886void QTextEdit::setWordWrap( WordWrap mode )
3887{ 3887{
3888 if ( wrapMode == mode ) 3888 if ( wrapMode == mode )
3889 return; 3889 return;
3890 wrapMode = mode; 3890 wrapMode = mode;
3891 switch ( mode ) { 3891 switch ( mode ) {
3892 case NoWrap: 3892 case NoWrap:
3893 document()->formatter()->setWrapEnabled( FALSE ); 3893 document()->formatter()->setWrapEnabled( FALSE );
3894 document()->formatter()->setWrapAtColumn( -1 ); 3894 document()->formatter()->setWrapAtColumn( -1 );
3895 doc->setWidth( visibleWidth() ); 3895 doc->setWidth( visibleWidth() );
3896 doc->setMinimumWidth( -1 ); 3896 doc->setMinimumWidth( -1 );
3897 doc->invalidate(); 3897 doc->invalidate();
3898 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 3898 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
3899 lastFormatted = doc->firstParagraph(); 3899 lastFormatted = doc->firstParagraph();
3900 interval = 0; 3900 interval = 0;
3901 formatMore(); 3901 formatMore();
3902 break; 3902 break;
3903 case WidgetWidth: 3903 case WidgetWidth:
3904 document()->formatter()->setWrapEnabled( TRUE ); 3904 document()->formatter()->setWrapEnabled( TRUE );
3905 document()->formatter()->setWrapAtColumn( -1 ); 3905 document()->formatter()->setWrapAtColumn( -1 );
3906 doResize(); 3906 doResize();
3907 break; 3907 break;
3908 case FixedPixelWidth: 3908 case FixedPixelWidth:
3909 document()->formatter()->setWrapEnabled( TRUE ); 3909 document()->formatter()->setWrapEnabled( TRUE );
3910 document()->formatter()->setWrapAtColumn( -1 ); 3910 document()->formatter()->setWrapAtColumn( -1 );
3911 if ( wrapWidth < 0 ) 3911 if ( wrapWidth < 0 )
3912 wrapWidth = 200; 3912 wrapWidth = 200;
3913 setWrapColumnOrWidth( wrapWidth ); 3913 setWrapColumnOrWidth( wrapWidth );
3914 break; 3914 break;
3915 case FixedColumnWidth: 3915 case FixedColumnWidth:
3916 if ( wrapWidth < 0 ) 3916 if ( wrapWidth < 0 )
3917 wrapWidth = 80; 3917 wrapWidth = 80;
3918 document()->formatter()->setWrapEnabled( TRUE ); 3918 document()->formatter()->setWrapEnabled( TRUE );
3919 document()->formatter()->setWrapAtColumn( wrapWidth ); 3919 document()->formatter()->setWrapAtColumn( wrapWidth );
3920 setWrapColumnOrWidth( wrapWidth ); 3920 setWrapColumnOrWidth( wrapWidth );
3921 break; 3921 break;
3922 } 3922 }
3923} 3923}
3924 3924
3925QTextEdit::WordWrap QTextEdit::wordWrap() const 3925QTextEdit::WordWrap QTextEdit::wordWrap() const
3926{ 3926{
3927 return wrapMode; 3927 return wrapMode;
3928} 3928}
3929 3929
3930/*! 3930/*!
3931 \property QTextEdit::wrapColumnOrWidth 3931 \property QTextEdit::wrapColumnOrWidth
3932 \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped 3932 \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped
3933 3933
3934 If the wrap mode is \c FixedPixelWidth, the value is the number 3934 If the wrap mode is \c FixedPixelWidth, the value is the number
3935 of pixels from the left edge of the text edit at which text should 3935 of pixels from the left edge of the text edit at which text should
3936 be wrapped. If the wrap mode is \c FixedColumnWidth, the value is 3936 be wrapped. If the wrap mode is \c FixedColumnWidth, the value is
3937 the column number (in character columns) from the left edge of the 3937 the column number (in character columns) from the left edge of the
3938 text edit at which text should be wrapped. 3938 text edit at which text should be wrapped.
3939 3939
3940 \sa wordWrap 3940 \sa wordWrap
3941 */ 3941 */
3942void QTextEdit::setWrapColumnOrWidth( int value ) 3942void QTextEdit::setWrapColumnOrWidth( int value )
3943{ 3943{
3944 wrapWidth = value; 3944 wrapWidth = value;
3945 if ( wrapMode == FixedColumnWidth ) { 3945 if ( wrapMode == FixedColumnWidth ) {
3946 document()->formatter()->setWrapAtColumn( wrapWidth ); 3946 document()->formatter()->setWrapAtColumn( wrapWidth );
3947 resizeContents( 0, 0 ); 3947 resizeContents( 0, 0 );
3948 doc->setWidth( visibleWidth() ); 3948 doc->setWidth( visibleWidth() );
3949 doc->setMinimumWidth( -1 ); 3949 doc->setMinimumWidth( -1 );
3950 } else if (wrapMode == FixedPixelWidth ) { 3950 } else if (wrapMode == FixedPixelWidth ) {
3951 document()->formatter()->setWrapAtColumn( -1 ); 3951 document()->formatter()->setWrapAtColumn( -1 );
3952 resizeContents( wrapWidth, 0 ); 3952 resizeContents( wrapWidth, 0 );
3953 doc->setWidth( wrapWidth ); 3953 doc->setWidth( wrapWidth );
3954 doc->setMinimumWidth( wrapWidth ); 3954 doc->setMinimumWidth( wrapWidth );
3955 } else { 3955 } else {
3956 return; 3956 return;
3957 } 3957 }
3958 doc->invalidate(); 3958 doc->invalidate();
3959 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 3959 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
3960 lastFormatted = doc->firstParagraph(); 3960 lastFormatted = doc->firstParagraph();
3961 interval = 0; 3961 interval = 0;
3962 formatMore(); 3962 formatMore();
3963} 3963}
3964 3964
3965int QTextEdit::wrapColumnOrWidth() const 3965int QTextEdit::wrapColumnOrWidth() const
3966{ 3966{
3967 if ( wrapMode == WidgetWidth ) 3967 if ( wrapMode == WidgetWidth )
3968 return visibleWidth(); 3968 return visibleWidth();
3969 return wrapWidth; 3969 return wrapWidth;
3970} 3970}
3971 3971
3972 3972
3973/*! \enum QTextEdit::WrapPolicy 3973/*! \enum QTextEdit::WrapPolicy
3974 3974
3975 This enum defines where text can be wrapped in word wrap mode. 3975 This enum defines where text can be wrapped in word wrap mode.
3976 3976
3977 The following values are valid: 3977 The following values are valid:
3978 \value AtWhiteSpace Break lines at whitespace, e.g. spaces or 3978 \value AtWhiteSpace Break lines at whitespace, e.g. spaces or
3979 newlines. 3979 newlines.
3980 \value Anywhere Break anywhere, including within words. 3980 \value Anywhere Break anywhere, including within words.
3981 \value AtWordBoundary Don't use this deprecated value (it is a 3981 \value AtWordBoundary Don't use this deprecated value (it is a
3982 synonym for AtWhiteSpace which you should use instead). 3982 synonym for AtWhiteSpace which you should use instead).
3983 3983
3984 \sa setWrapPolicy() 3984 \sa setWrapPolicy()
3985*/ 3985*/
3986 3986
3987/*! 3987/*!
3988 \property QTextEdit::wrapPolicy 3988 \property QTextEdit::wrapPolicy
3989 \brief the word wrap policy, at whitespace or anywhere 3989 \brief the word wrap policy, at whitespace or anywhere
3990 3990
3991 Defines where text can be wrapped when word wrap mode is not 3991 Defines where text can be wrapped when word wrap mode is not
3992 \c NoWrap. The choices are \c AtWhiteSpace (the default) and \c 3992 \c NoWrap. The choices are \c AtWhiteSpace (the default) and \c
3993 Anywhere. 3993 Anywhere.
3994 3994
3995 \sa wordWrap 3995 \sa wordWrap
3996 */ 3996 */
3997 3997
3998void QTextEdit::setWrapPolicy( WrapPolicy policy ) 3998void QTextEdit::setWrapPolicy( WrapPolicy policy )
3999{ 3999{
4000 if ( wPolicy == policy ) 4000 if ( wPolicy == policy )
4001 return; 4001 return;
4002 wPolicy = policy; 4002 wPolicy = policy;
4003 QTextFormatter *formatter; 4003 QTextFormatter *formatter;
4004 if ( policy == AtWhiteSpace ) 4004 if ( policy == AtWhiteSpace )
4005 formatter = new QTextFormatterBreakWords; 4005 formatter = new QTextFormatterBreakWords;
4006 else 4006 else
4007 formatter = new QTextFormatterBreakInWords; 4007 formatter = new QTextFormatterBreakInWords;
4008 formatter->setWrapAtColumn( document()->formatter()->wrapAtColumn() ); 4008 formatter->setWrapAtColumn( document()->formatter()->wrapAtColumn() );
4009 formatter->setWrapEnabled( document()->formatter()->isWrapEnabled( 0 ) ); 4009 formatter->setWrapEnabled( document()->formatter()->isWrapEnabled( 0 ) );
4010 document()->setFormatter( formatter ); 4010 document()->setFormatter( formatter );
4011 doc->invalidate(); 4011 doc->invalidate();
4012 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 4012 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
4013 lastFormatted = doc->firstParagraph(); 4013 lastFormatted = doc->firstParagraph();
4014 interval = 0; 4014 interval = 0;
4015 formatMore(); 4015 formatMore();
4016} 4016}
4017 4017
4018QTextEdit::WrapPolicy QTextEdit::wrapPolicy() const 4018QTextEdit::WrapPolicy QTextEdit::wrapPolicy() const
4019{ 4019{
4020 return wPolicy; 4020 return wPolicy;
4021} 4021}
4022 4022
4023/*! 4023/*!
4024 Deletes all the text in the text edit. 4024 Deletes all the text in the text edit.
4025 4025
4026 \sa cut() removeSelectedText() setText() 4026 \sa cut() removeSelectedText() setText()
4027 4027
4028*/ 4028*/
4029 4029
4030void QTextEdit::clear() 4030void QTextEdit::clear()
4031{ 4031{
4032 // make clear undoable 4032 // make clear undoable
4033 doc->selectAll( QTextDocument::Temp ); 4033 doc->selectAll( QTextDocument::Temp );
4034 removeSelectedText( QTextDocument::Temp ); 4034 removeSelectedText( QTextDocument::Temp );
4035 4035
4036 setContentsPos( 0, 0 ); 4036 setContentsPos( 0, 0 );
4037 if ( cursor->isValid() ) 4037 if ( cursor->isValid() )
4038 cursor->restoreState(); 4038 cursor->restoreState();
4039 doc->clear( TRUE ); 4039 doc->clear( TRUE );
4040 delete cursor; 4040 delete cursor;
4041 cursor = new QTextCursor( doc ); 4041 cursor = new QTextCursor( doc );
4042 lastFormatted = 0; 4042 lastFormatted = 0;
4043 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 4043 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
4044 4044
4045 emit cursorPositionChanged( cursor ); 4045 emit cursorPositionChanged( cursor );
4046 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() ); 4046 emit cursorPositionChanged( cursor->paragraph()->paragId(), cursor->index() );
4047} 4047}
4048 4048
4049int QTextEdit::undoDepth() const 4049int QTextEdit::undoDepth() const
4050{ 4050{
4051 return document()->undoDepth(); 4051 return document()->undoDepth();
4052} 4052}
4053 4053
4054/*! 4054/*!
4055 \property QTextEdit::length 4055 \property QTextEdit::length
4056 \brief the number of characters in the text 4056 \brief the number of characters in the text
4057 4057
4058*/ 4058*/
4059 4059
4060int QTextEdit::length() const 4060int QTextEdit::length() const
4061{ 4061{
4062 return document()->length(); 4062 return document()->length();
4063} 4063}
4064 4064
4065/*! 4065/*!
4066 \property QTextEdit::tabStopWidth 4066 \property QTextEdit::tabStopWidth
4067 \brief the tab stop width in pixels 4067 \brief the tab stop width in pixels
4068 4068
4069*/ 4069*/
4070 4070
4071int QTextEdit::tabStopWidth() const 4071int QTextEdit::tabStopWidth() const
4072{ 4072{
4073 return document()->tabStopWidth(); 4073 return document()->tabStopWidth();
4074} 4074}
4075 4075
4076void QTextEdit::setUndoDepth( int d ) 4076void QTextEdit::setUndoDepth( int d )
4077{ 4077{
4078 document()->setUndoDepth( d ); 4078 document()->setUndoDepth( d );
4079} 4079}
4080 4080
4081void QTextEdit::setTabStopWidth( int ts ) 4081void QTextEdit::setTabStopWidth( int ts )
4082{ 4082{
4083 document()->setTabStops( ts ); 4083 document()->setTabStops( ts );
4084 doc->invalidate(); 4084 doc->invalidate();
4085 lastFormatted = doc->firstParagraph(); 4085 lastFormatted = doc->firstParagraph();
4086 interval = 0; 4086 interval = 0;
4087 formatMore(); 4087 formatMore();
4088 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 4088 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
4089} 4089}
4090 4090
4091/*! \reimp */ 4091/*! \reimp */
4092 4092
4093QSize QTextEdit::sizeHint() const 4093QSize QTextEdit::sizeHint() const
4094{ 4094{
4095 // ### calculate a reasonable one 4095 // ### calculate a reasonable one
4096 return QSize( 100, 100 ); 4096 return QSize( 100, 100 );
4097} 4097}
4098 4098
4099void QTextEdit::clearUndoRedo() 4099void QTextEdit::clearUndoRedo()
4100{ 4100{
4101 undoRedoInfo.clear(); 4101 undoRedoInfo.clear();
4102 emit undoAvailable( doc->commands()->isUndoAvailable() ); 4102 emit undoAvailable( doc->commands()->isUndoAvailable() );
4103 emit redoAvailable( doc->commands()->isRedoAvailable() ); 4103 emit redoAvailable( doc->commands()->isRedoAvailable() );
4104} 4104}
4105 4105
4106/*! \internal 4106/*! \internal
4107 4107
4108 \warning In Qt 3.1 we will provide a cleaer API for the 4108 \warning In Qt 3.1 we will provide a cleaer API for the
4109 functionality which is provided by this function and in Qt 4.0 this 4109 functionality which is provided by this function and in Qt 4.0 this
4110 function will go away. 4110 function will go away.
4111 4111
4112 This function gets the format of the character at position \a 4112 This function gets the format of the character at position \a
4113 index in paragraph \a para. Sets \a font to the character's font, \a 4113 index in paragraph \a para. Sets \a font to the character's font, \a
4114 color to the character's color and \a verticalAlignment to the 4114 color to the character's color and \a verticalAlignment to the
4115 character's vertical alignment. 4115 character's vertical alignment.
4116 4116
4117 Returns FALSE if \a para or \a index is out of range otherwise 4117 Returns FALSE if \a para or \a index is out of range otherwise
4118 returns TRUE. 4118 returns TRUE.
4119*/ 4119*/
4120 4120
4121bool QTextEdit::getFormat( int para, int index, QFont *font, QColor *color, VerticalAlignment *verticalAlignment ) 4121bool QTextEdit::getFormat( int para, int index, QFont *font, QColor *color, VerticalAlignment *verticalAlignment )
4122{ 4122{
4123 if ( !font || !color ) 4123 if ( !font || !color )
4124 return FALSE; 4124 return FALSE;
4125 QTextParagraph *p = doc->paragAt( para ); 4125 QTextParagraph *p = doc->paragAt( para );
4126 if ( !p ) 4126 if ( !p )
4127 return FALSE; 4127 return FALSE;
4128 if ( index < 0 || index >= p->length() ) 4128 if ( index < 0 || index >= p->length() )
4129 return FALSE; 4129 return FALSE;
4130 *font = p->at( index )->format()->font(); 4130 *font = p->at( index )->format()->font();
4131 *color = p->at( index )->format()->color(); 4131 *color = p->at( index )->format()->color();
4132 *verticalAlignment = (VerticalAlignment)p->at( index )->format()->vAlign(); 4132 *verticalAlignment = (VerticalAlignment)p->at( index )->format()->vAlign();
4133 return TRUE; 4133 return TRUE;
4134} 4134}
4135 4135
4136/*! \internal 4136/*! \internal
4137 4137
4138 \warning In Qt 3.1 we will provide a cleaer API for the 4138 \warning In Qt 3.1 we will provide a cleaer API for the
4139 functionality which is provided by this function and in Qt 4.0 this 4139 functionality which is provided by this function and in Qt 4.0 this
4140 function will go away. 4140 function will go away.
4141 4141
4142 This function gets the format of the paragraph \a para. Sets \a 4142 This function gets the format of the paragraph \a para. Sets \a
4143 font to the paragraphs's font, \a color to the paragraph's color, \a 4143 font to the paragraphs's font, \a color to the paragraph's color, \a
4144 verticalAlignment to the paragraph's vertical alignment, \a 4144 verticalAlignment to the paragraph's vertical alignment, \a
4145 alignment to the paragraph's alignment, \a displayMode to the 4145 alignment to the paragraph's alignment, \a displayMode to the
4146 paragraph's display mode, \a listStyle to the paragraph's list style 4146 paragraph's display mode, \a listStyle to the paragraph's list style
4147 (if the display mode is QStyleSheetItem::DisplayListItem) and \a 4147 (if the display mode is QStyleSheetItem::DisplayListItem) and \a
4148 listDepth to the depth of the list (if the display mode is 4148 listDepth to the depth of the list (if the display mode is
4149 QStyleSheetItem::DisplayListItem). 4149 QStyleSheetItem::DisplayListItem).
4150 4150
4151 Returns FALSE if \a para is out of range otherwise returns TRUE. 4151 Returns FALSE if \a para is out of range otherwise returns TRUE.
4152*/ 4152*/
4153 4153
4154bool QTextEdit::getParagraphFormat( int para, QFont *font, QColor *color, 4154bool QTextEdit::getParagraphFormat( int para, QFont *font, QColor *color,
4155 VerticalAlignment *verticalAlignment, int *alignment, 4155 VerticalAlignment *verticalAlignment, int *alignment,
4156 QStyleSheetItem::DisplayMode *displayMode, 4156 QStyleSheetItem::DisplayMode *displayMode,
4157 QStyleSheetItem::ListStyle *listStyle, 4157 QStyleSheetItem::ListStyle *listStyle,
4158 int *listDepth ) 4158 int *listDepth )
4159{ 4159{
4160 if ( !font || !color || !alignment || !displayMode || !listStyle ) 4160 if ( !font || !color || !alignment || !displayMode || !listStyle )
4161 return FALSE; 4161 return FALSE;
4162 QTextParagraph *p = doc->paragAt( para ); 4162 QTextParagraph *p = doc->paragAt( para );
4163 if ( !p ) 4163 if ( !p )
4164 return FALSE; 4164 return FALSE;
4165 *font = p->at(0)->format()->font(); 4165 *font = p->at(0)->format()->font();
4166 *color = p->at(0)->format()->color(); 4166 *color = p->at(0)->format()->color();
4167 *verticalAlignment = (VerticalAlignment)p->at(0)->format()->vAlign(); 4167 *verticalAlignment = (VerticalAlignment)p->at(0)->format()->vAlign();
4168 *alignment = p->alignment(); 4168 *alignment = p->alignment();
4169 *displayMode = p->isListItem() ? QStyleSheetItem::DisplayListItem : QStyleSheetItem::DisplayBlock; 4169 *displayMode = p->isListItem() ? QStyleSheetItem::DisplayListItem : QStyleSheetItem::DisplayBlock;
4170 *listStyle = p->listStyle(); 4170 *listStyle = p->listStyle();
4171 *listDepth = p->listDepth(); 4171 *listDepth = p->listDepth();
4172 return TRUE; 4172 return TRUE;
4173} 4173}
4174 4174
4175 4175
4176 4176
4177/*! 4177/*!
4178 4178
4179 This function is called to create a right mouse button popup menu 4179 This function is called to create a right mouse button popup menu
4180 at the document position \a pos. If you want to create a custom 4180 at the document position \a pos. If you want to create a custom
4181 popup menu, reimplement this function and return the created 4181 popup menu, reimplement this function and return the created
4182 popup menu. Ownership of the popup menu is transferred to the 4182 popup menu. Ownership of the popup menu is transferred to the
4183 caller. 4183 caller.
4184*/ 4184*/
4185 4185
4186QPopupMenu *QTextEdit::createPopupMenu( const QPoint& pos ) 4186QPopupMenu *QTextEdit::createPopupMenu( const QPoint& pos )
4187{ 4187{
4188#ifndef QT_NO_POPUPMENU 4188#ifndef QT_NO_POPUPMENU
4189 QPopupMenu *popup = new QPopupMenu( this, "qt_edit_menu" ); 4189 QPopupMenu *popup = new QPopupMenu( this, "qt_edit_menu" );
4190 if ( !isReadOnly() ) { 4190 if ( !isReadOnly() ) {
4191 d->id[ IdUndo ] = popup->insertItem( tr( "&Undo" ) + ACCEL_KEY( Z ) ); 4191 d->id[ IdUndo ] = popup->insertItem( tr( "&Undo" ) + ACCEL_KEY( Z ) );
4192 d->id[ IdRedo ] = popup->insertItem( tr( "&Redo" ) + ACCEL_KEY( Y ) ); 4192 d->id[ IdRedo ] = popup->insertItem( tr( "&Redo" ) + ACCEL_KEY( Y ) );
4193 popup->insertSeparator(); 4193 popup->insertSeparator();
4194 } 4194 }
4195#ifndef QT_NO_CLIPBOARD 4195#ifndef QT_NO_CLIPBOARD
4196 if ( !isReadOnly() ) 4196 if ( !isReadOnly() )
4197 d->id[ IdCut ] = popup->insertItem( tr( "Cu&t" ) + ACCEL_KEY( X ) ); 4197 d->id[ IdCut ] = popup->insertItem( tr( "Cu&t" ) + ACCEL_KEY( X ) );
4198 d->id[ IdCopy ] = popup->insertItem( tr( "&Copy" ) + ACCEL_KEY( C ) ); 4198 d->id[ IdCopy ] = popup->insertItem( tr( "&Copy" ) + ACCEL_KEY( C ) );
4199 if ( !isReadOnly() ) 4199 if ( !isReadOnly() )
4200 d->id[ IdPaste ] = popup->insertItem( tr( "&Paste" ) + ACCEL_KEY( V ) ); 4200 d->id[ IdPaste ] = popup->insertItem( tr( "&Paste" ) + ACCEL_KEY( V ) );
4201#endif 4201#endif
4202 if ( !isReadOnly() ) { 4202 if ( !isReadOnly() ) {
4203 d->id[ IdClear ] = popup->insertItem( tr( "Clear" ) ); 4203 d->id[ IdClear ] = popup->insertItem( tr( "Clear" ) );
4204 popup->insertSeparator(); 4204 popup->insertSeparator();
4205 } 4205 }
4206#if defined(Q_WS_X11) 4206#if defined(Q_WS_X11)
4207 d->id[ IdSelectAll ] = popup->insertItem( tr( "Select All" ) ); 4207 d->id[ IdSelectAll ] = popup->insertItem( tr( "Select All" ) );
4208#else 4208#else
4209 d->id[ IdSelectAll ] = popup->insertItem( tr( "Select All" ) + ACCEL_KEY( A ) ); 4209 d->id[ IdSelectAll ] = popup->insertItem( tr( "Select All" ) + ACCEL_KEY( A ) );
4210#endif 4210#endif
4211 popup->setItemEnabled( d->id[ IdUndo ], !isReadOnly() && doc->commands()->isUndoAvailable() ); 4211 popup->setItemEnabled( d->id[ IdUndo ], !isReadOnly() && doc->commands()->isUndoAvailable() );
4212 popup->setItemEnabled( d->id[ IdRedo ], !isReadOnly() && doc->commands()->isRedoAvailable() ); 4212 popup->setItemEnabled( d->id[ IdRedo ], !isReadOnly() && doc->commands()->isRedoAvailable() );
4213#ifndef QT_NO_CLIPBOARD 4213#ifndef QT_NO_CLIPBOARD
4214 popup->setItemEnabled( d->id[ IdCut ], !isReadOnly() && doc->hasSelection( QTextDocument::Standard, TRUE ) ); 4214 popup->setItemEnabled( d->id[ IdCut ], !isReadOnly() && doc->hasSelection( QTextDocument::Standard, TRUE ) );
4215 popup->setItemEnabled( d->id[ IdCopy ], doc->hasSelection( QTextDocument::Standard, TRUE ) ); 4215 popup->setItemEnabled( d->id[ IdCopy ], doc->hasSelection( QTextDocument::Standard, TRUE ) );
4216 popup->setItemEnabled( d->id[ IdPaste ], !isReadOnly() && !QApplication::clipboard()->text().isEmpty() ); 4216 popup->setItemEnabled( d->id[ IdPaste ], !isReadOnly() && !QApplication::clipboard()->text().isEmpty() );
4217#endif 4217#endif
4218 popup->setItemEnabled( d->id[ IdClear ], !isReadOnly() && !text().isEmpty() ); 4218 popup->setItemEnabled( d->id[ IdClear ], !isReadOnly() && !text().isEmpty() );
4219 popup->setItemEnabled( d->id[ IdSelectAll ], (bool)text().length() ); 4219 popup->setItemEnabled( d->id[ IdSelectAll ], (bool)text().length() );
4220 return popup; 4220 return popup;
4221#else 4221#else
4222 return 0; 4222 return 0;
4223#endif 4223#endif
4224} 4224}
4225 4225
4226/*! \overload 4226/*! \overload
4227 \obsolete 4227 \obsolete
4228 This function is called to create a right mouse button popup menu. 4228 This function is called to create a right mouse button popup menu.
4229 If you want to create a custom popup menu, reimplement this function 4229 If you want to create a custom popup menu, reimplement this function
4230 and return the created popup menu. Ownership of the popup menu is 4230 and return the created popup menu. Ownership of the popup menu is
4231 transferred to the caller. 4231 transferred to the caller.
4232 4232
4233 This function is only called if createPopupMenu( const QPoint & ) 4233 This function is only called if createPopupMenu( const QPoint & )
4234 returns 0. 4234 returns 0.
4235*/ 4235*/
4236 4236
4237QPopupMenu *QTextEdit::createPopupMenu() 4237QPopupMenu *QTextEdit::createPopupMenu()
4238{ 4238{
4239 return 0; 4239 return 0;
4240} 4240}
4241 4241
4242/*! \reimp */ 4242/*! \reimp */
4243 4243
4244void QTextEdit::setFont( const QFont &f ) 4244void QTextEdit::setFont( const QFont &f )
4245{ 4245{
4246 QFont old( QScrollView::font() ); 4246 QFont old( QScrollView::font() );
4247 QScrollView::setFont( f ); 4247 QScrollView::setFont( f );
4248 doc->setMinimumWidth( -1 ); 4248 doc->setMinimumWidth( -1 );
4249 doc->setDefaultFormat( f, doc->formatCollection()->defaultFormat()->color() ); 4249 doc->setDefaultFormat( f, doc->formatCollection()->defaultFormat()->color() );
4250 lastFormatted = doc->firstParagraph(); 4250 lastFormatted = doc->firstParagraph();
4251 formatMore(); 4251 formatMore();
4252 repaintChanged(); 4252 repaintChanged();
4253} 4253}
4254 4254
4255/*! \fn QTextEdit::zoomIn() 4255/*! \fn QTextEdit::zoomIn()
4256 4256
4257 \overload 4257 \overload
4258 4258
4259 Zooms in on the text by by making the base font size one 4259 Zooms in on the text by by making the base font size one
4260 point larger and recalculating all font sizes. This does not change 4260 point larger and recalculating all font sizes. This does not change
4261 the size of any images. 4261 the size of any images.
4262 4262
4263 \sa zoomOut() 4263 \sa zoomOut()
4264 4264
4265*/ 4265*/
4266 4266
4267/*! \fn QTextEdit::zoomOut() 4267/*! \fn QTextEdit::zoomOut()
4268 4268
4269 \overload 4269 \overload
4270 4270
4271 Zooms out on the text by by making the base font size one 4271 Zooms out on the text by by making the base font size one
4272 point smaller and recalculating all font sizes. This does not change 4272 point smaller and recalculating all font sizes. This does not change
4273 the size of any images. 4273 the size of any images.
4274 4274
4275 \sa zoomIn() 4275 \sa zoomIn()
4276*/ 4276*/
4277 4277
4278 4278
4279/*! 4279/*!
4280 Zooms in on the text by by making the base font size \a range 4280 Zooms in on the text by by making the base font size \a range
4281 points larger and recalculating all font sizes. This does not change 4281 points larger and recalculating all font sizes. This does not change
4282 the size of any images. 4282 the size of any images.
4283 4283
4284 \sa zoomOut() 4284 \sa zoomOut()
4285*/ 4285*/
4286 4286
4287void QTextEdit::zoomIn( int range ) 4287void QTextEdit::zoomIn( int range )
4288{ 4288{
4289 QFont f( QScrollView::font() ); 4289 QFont f( QScrollView::font() );
4290 f.setPointSize( f.pointSize() + range ); 4290 f.setPointSize( f.pointSize() + range );
4291 setFont( f ); 4291 setFont( f );
4292} 4292}
4293 4293
4294/*! Zooms out on the text by making the base font size \a range 4294/*! Zooms out on the text by making the base font size \a range
4295 points smaller and recalculating all font sizes. This does not 4295 points smaller and recalculating all font sizes. This does not
4296 change the size of any images. 4296 change the size of any images.
4297 4297
4298 \sa zoomIn() 4298 \sa zoomIn()
4299*/ 4299*/
4300 4300
4301void QTextEdit::zoomOut( int range ) 4301void QTextEdit::zoomOut( int range )
4302{ 4302{
4303 QFont f( QScrollView::font() ); 4303 QFont f( QScrollView::font() );
4304 f.setPointSize( QMAX( 1, f.pointSize() - range ) ); 4304 f.setPointSize( QMAX( 1, f.pointSize() - range ) );
4305 setFont( f ); 4305 setFont( f );
4306} 4306}
4307 4307
4308/*! Zooms the text by making the base font size \a size points and 4308/*! Zooms the text by making the base font size \a size points and
4309 recalculating all font sizes. This does not change the size of any 4309 recalculating all font sizes. This does not change the size of any
4310 images. 4310 images.
4311*/ 4311*/
4312 4312
4313void QTextEdit::zoomTo( int size ) 4313void QTextEdit::zoomTo( int size )
4314{ 4314{
4315 QFont f( QScrollView::font() ); 4315 QFont f( QScrollView::font() );
4316 f.setPointSize( size ); 4316 f.setPointSize( size );
4317 setFont( f ); 4317 setFont( f );
4318} 4318}
4319 4319
4320/*! 4320/*!
4321 \internal 4321 \internal
4322 4322
4323 QTextEdit is optimized for large amounts text. One of its 4323 QTextEdit is optimized for large amounts text. One of its
4324 optimizations is to format only the visible text, formatting the rest 4324 optimizations is to format only the visible text, formatting the rest
4325 on demand, e.g. as the user scrolls, so you don't usually need to 4325 on demand, e.g. as the user scrolls, so you don't usually need to
4326 call this function. 4326 call this function.
4327 4327
4328 In some situations you may want to force the whole text 4328 In some situations you may want to force the whole text
4329 to be formatted. For example, if after calling setText(), you wanted 4329 to be formatted. For example, if after calling setText(), you wanted
4330 to know the height of the document (using contentsHeight()), you 4330 to know the height of the document (using contentsHeight()), you
4331 would call this function first. 4331 would call this function first.
4332*/ 4332*/
4333 4333
4334void QTextEdit::sync() 4334void QTextEdit::sync()
4335{ 4335{
4336 while ( lastFormatted ) { 4336 while ( lastFormatted ) {
4337 lastFormatted->format(); 4337 lastFormatted->format();
4338 lastFormatted = lastFormatted->next(); 4338 lastFormatted = lastFormatted->next();
4339 } 4339 }
4340 resizeContents( contentsWidth(), doc->height() ); 4340 resizeContents( contentsWidth(), doc->height() );
4341} 4341}
4342 4342
4343/*! \reimp */ 4343/*! \reimp */
4344 4344
4345void QTextEdit::setEnabled( bool b ) 4345void QTextEdit::setEnabled( bool b )
4346{ 4346{
4347 QScrollView::setEnabled( b ); 4347 QScrollView::setEnabled( b );
4348 if ( !b ) { 4348 if ( !b ) {
4349 blinkTimer->stop(); 4349 blinkTimer->stop();
4350 drawCursor( FALSE ); 4350 drawCursor( FALSE );
4351 } 4351 }
4352 if ( textFormat() == PlainText ) { 4352 if ( textFormat() == PlainText ) {
4353 QTextFormat *f = doc->formatCollection()->defaultFormat(); 4353 QTextFormat *f = doc->formatCollection()->defaultFormat();
4354 f->setColor( colorGroup().text() ); 4354 f->setColor( colorGroup().text() );
4355 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 4355 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
4356 } 4356 }
4357 if ( b ) { 4357 if ( b ) {
4358 blinkTimer->start( QApplication::cursorFlashTime() / 2 ); 4358 blinkTimer->start( QApplication::cursorFlashTime() / 2 );
4359 drawCursor( TRUE ); 4359 drawCursor( TRUE );
4360 } 4360 }
4361} 4361}
4362 4362
4363/*! 4363/*!
4364 Sets the background color of selection number \a selNum to \a back and 4364 Sets the background color of selection number \a selNum to \a back and
4365 specifies whether the text of this selection should be inverted with \a 4365 specifies whether the text of this selection should be inverted with \a
4366 invertText. 4366 invertText.
4367 4367
4368 This only works for \a selNum > 0. The default selection (\a selNum == 4368 This only works for \a selNum > 0. The default selection (\a selNum ==
4369 0) gets its attributes from the colorGroup() of this widget. 4369 0) gets its attributes from the colorGroup() of this widget.
4370*/ 4370*/
4371 4371
4372void QTextEdit::setSelectionAttributes( int selNum, const QColor &back, bool invertText ) 4372void QTextEdit::setSelectionAttributes( int selNum, const QColor &back, bool invertText )
4373{ 4373{
4374 if ( selNum < 1 ) 4374 if ( selNum < 1 )
4375 return; 4375 return;
4376 if ( selNum > doc->numSelections() ) 4376 if ( selNum > doc->numSelections() )
4377 doc->addSelection( selNum ); 4377 doc->addSelection( selNum );
4378 doc->setSelectionColor( selNum, back ); 4378 doc->setSelectionColor( selNum, back );
4379 doc->setInvertSelectionText( selNum, invertText ); 4379 doc->setInvertSelectionText( selNum, invertText );
4380} 4380}
4381 4381
4382/*! \reimp */ 4382/*! \reimp */
4383void QTextEdit::windowActivationChange( bool ) 4383void QTextEdit::windowActivationChange( bool )
4384{ 4384{
4385 if ( !isVisible() ) 4385 if ( !isVisible() )
4386 return; 4386 return;
4387 4387
4388 if ( palette().active() != palette().inactive() ) 4388 if ( palette().active() != palette().inactive() )
4389 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() ); 4389 updateContents( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
4390} 4390}
4391 4391
4392void QTextEdit::setReadOnly( bool b ) 4392void QTextEdit::setReadOnly( bool b )
4393{ 4393{
4394 if ( readonly == b ) 4394 if ( readonly == b )
4395 return; 4395 return;
4396 readonly = b; 4396 readonly = b;
4397#ifndef QT_NO_CURSOR 4397#ifndef QT_NO_CURSOR
4398 if ( readonly ) 4398 if ( readonly )
4399 viewport()->setCursor( arrowCursor ); 4399 viewport()->setCursor( arrowCursor );
4400 else 4400 else
4401 viewport()->setCursor( ibeamCursor ); 4401 viewport()->setCursor( ibeamCursor );
4402#endif 4402#endif
4403} 4403}
4404 4404
4405/*! Scrolls to the bottom of the document and does formatting if 4405/*! Scrolls to the bottom of the document and does formatting if
4406 required */ 4406 required */
4407 4407
4408void QTextEdit::scrollToBottom() 4408void QTextEdit::scrollToBottom()
4409{ 4409{
4410 sync(); 4410 sync();
4411 setContentsPos( contentsX(), contentsHeight() - visibleHeight() ); 4411 setContentsPos( contentsX(), contentsHeight() - visibleHeight() );
4412} 4412}
4413 4413
4414/*! Returns the rectangle of the paragraph \a para in contents 4414/*! Returns the rectangle of the paragraph \a para in contents
4415 coordinates, or an invalid rectangle if \a para is out of range. 4415 coordinates, or an invalid rectangle if \a para is out of range.
4416*/ 4416*/
4417 4417
4418QRect QTextEdit::paragraphRect( int para ) const 4418QRect QTextEdit::paragraphRect( int para ) const
4419{ 4419{
4420 QTextEdit *that = (QTextEdit *)this; 4420 QTextEdit *that = (QTextEdit *)this;
4421 that->sync(); 4421 that->sync();
4422 QTextParagraph *p = doc->paragAt( para ); 4422 QTextParagraph *p = doc->paragAt( para );
4423 if ( !p ) 4423 if ( !p )
4424 return QRect( -1, -1, -1, -1 ); 4424 return QRect( -1, -1, -1, -1 );
4425 return p->rect(); 4425 return p->rect();
4426} 4426}
4427 4427
4428/*! 4428/*!
4429 Returns the paragraph which is at position \a pos (in contents 4429 Returns the paragraph which is at position \a pos (in contents
4430 coordinates), or -1 if there is no paragraph with index \a pos. 4430 coordinates), or -1 if there is no paragraph with index \a pos.
4431*/ 4431*/
4432 4432
4433int QTextEdit::paragraphAt( const QPoint &pos ) const 4433int QTextEdit::paragraphAt( const QPoint &pos ) const
4434{ 4434{
4435 QTextCursor c( doc ); 4435 QTextCursor c( doc );
4436 c.place( pos, doc->firstParagraph() ); 4436 c.place( pos, doc->firstParagraph() );
4437 if ( c.paragraph() ) 4437 if ( c.paragraph() )
4438 return c.paragraph()->paragId(); 4438 return c.paragraph()->paragId();
4439 return -1; 4439 return -1;
4440} 4440}
4441 4441
4442/*! 4442/*!
4443 Returns the index of the character (relative to its paragraph) at 4443 Returns the index of the character (relative to its paragraph) at
4444 position \a pos (in contents coordinates). If \a para is not null, 4444 position \a pos (in contents coordinates). If \a para is not null,
4445 \e *\a para is set to this paragraph. If there is no character at 4445 \e *\a para is set to this paragraph. If there is no character at
4446 \a pos, -1 is returned. 4446 \a pos, -1 is returned.
4447*/ 4447*/
4448 4448
4449int QTextEdit::charAt( const QPoint &pos, int *para ) const 4449int QTextEdit::charAt( const QPoint &pos, int *para ) const
4450{ 4450{
4451 QTextCursor c( doc ); 4451 QTextCursor c( doc );
4452 c.place( pos, doc->firstParagraph() ); 4452 c.place( pos, doc->firstParagraph() );
4453 if ( c.paragraph() ) { 4453 if ( c.paragraph() ) {
4454 if ( para ) 4454 if ( para )
4455 *para = c.paragraph()->paragId(); 4455 *para = c.paragraph()->paragId();
4456 return c.index(); 4456 return c.index();
4457 } 4457 }
4458 return -1; 4458 return -1;
4459} 4459}
4460 4460
4461/*! Sets the background color of the paragraph \a para to \a bg */ 4461/*! Sets the background color of the paragraph \a para to \a bg */
4462 4462
4463void QTextEdit::setParagraphBackgroundColor( int para, const QColor &bg ) 4463void QTextEdit::setParagraphBackgroundColor( int para, const QColor &bg )
4464{ 4464{
4465 QTextParagraph *p = doc->paragAt( para ); 4465 QTextParagraph *p = doc->paragAt( para );
4466 if ( !p ) 4466 if ( !p )
4467 return; 4467 return;
4468 p->setBackgroundColor( bg ); 4468 p->setBackgroundColor( bg );
4469 repaintChanged(); 4469 repaintChanged();
4470} 4470}
4471 4471
4472/*! Clears the background color of the paragraph \a para, so that the 4472/*! Clears the background color of the paragraph \a para, so that the
4473 default color is used again. 4473 default color is used again.
4474*/ 4474*/
4475 4475
4476void QTextEdit::clearParagraphBackground( int para ) 4476void QTextEdit::clearParagraphBackground( int para )
4477{ 4477{
4478 QTextParagraph *p = doc->paragAt( para ); 4478 QTextParagraph *p = doc->paragAt( para );
4479 if ( !p ) 4479 if ( !p )
4480 return; 4480 return;
4481 p->clearBackgroundColor(); 4481 p->clearBackgroundColor();
4482 repaintChanged(); 4482 repaintChanged();
4483} 4483}
4484 4484
4485/*! Returns the background color of the paragraph \a para or an 4485/*! Returns the background color of the paragraph \a para or an
4486 invalid color if \a para is out of range or the paragraph has no 4486 invalid color if \a para is out of range or the paragraph has no
4487 background set 4487 background set
4488*/ 4488*/
4489 4489
4490QColor QTextEdit::paragraphBackgroundColor( int para ) const 4490QColor QTextEdit::paragraphBackgroundColor( int para ) const
4491{ 4491{
4492 QTextParagraph *p = doc->paragAt( para ); 4492 QTextParagraph *p = doc->paragAt( para );
4493 if ( !p ) 4493 if ( !p )
4494 return QColor(); 4494 return QColor();
4495 QColor *c = p->backgroundColor(); 4495 QColor *c = p->backgroundColor();
4496 if ( c ) 4496 if ( c )
4497 return *c; 4497 return *c;
4498 return QColor(); 4498 return QColor();
4499} 4499}
4500 4500
4501/*! \property QTextEdit::undoRedoEnabled 4501/*! \property QTextEdit::undoRedoEnabled
4502 \brief whether undo/redo is enabled 4502 \brief whether undo/redo is enabled
4503 4503
4504 The default is TRUE. 4504 The default is TRUE.
4505*/ 4505*/
4506 4506
4507void QTextEdit::setUndoRedoEnabled( bool b ) 4507void QTextEdit::setUndoRedoEnabled( bool b )
4508{ 4508{
4509 undoEnabled = b; 4509 undoEnabled = b;
4510} 4510}
4511 4511
4512bool QTextEdit::isUndoRedoEnabled() const 4512bool QTextEdit::isUndoRedoEnabled() const
4513{ 4513{
4514 return undoEnabled; 4514 return undoEnabled;
4515} 4515}
4516 4516
4517/*! Returns whether undo is available */ 4517/*! Returns whether undo is available */
4518 4518
4519bool QTextEdit::isUndoAvailable() const 4519bool QTextEdit::isUndoAvailable() const
4520{ 4520{
4521 return doc->commands()->isUndoAvailable() || undoRedoInfo.valid(); 4521 return doc->commands()->isUndoAvailable() || undoRedoInfo.valid();
4522} 4522}
4523 4523
4524/*! Returns whether redo is available */ 4524/*! Returns whether redo is available */
4525 4525
4526bool QTextEdit::isRedoAvailable() const 4526bool QTextEdit::isRedoAvailable() const
4527{ 4527{
4528 return doc->commands()->isRedoAvailable(); 4528 return doc->commands()->isRedoAvailable();
4529} 4529}
4530 4530
4531void QTextEdit::ensureFormatted( QTextParagraph *p ) 4531void QTextEdit::ensureFormatted( QTextParagraph *p )
4532{ 4532{
4533 while ( !p->isValid() ) { 4533 while ( !p->isValid() ) {
4534 if ( !lastFormatted ) 4534 if ( !lastFormatted )
4535 return; 4535 return;
4536 formatMore(); 4536 formatMore();
4537 } 4537 }
4538} 4538}
4539 4539
4540/*! \internal */ 4540/*! \internal */
4541void QTextEdit::updateCursor( const QPoint & pos ) 4541void QTextEdit::updateCursor( const QPoint & pos )
4542{ 4542{
4543 if ( isReadOnly() && linksEnabled() ) { 4543 if ( isReadOnly() && linksEnabled() ) {
4544 QTextCursor c = *cursor; 4544 QTextCursor c = *cursor;
4545 placeCursor( pos, &c, TRUE ); 4545 placeCursor( pos, &c, TRUE );
4546 4546
4547#ifndef QT_NO_NETWORKPROTOCOL 4547#ifndef QT_NO_NETWORKPROTOCOL
4548 if ( c.paragraph() && c.paragraph()->at( c.index() ) && 4548 if ( c.paragraph() && c.paragraph()->at( c.index() ) &&
4549 c.paragraph()->at( c.index() )->isAnchor() && 4549 c.paragraph()->at( c.index() )->isAnchor() &&
4550 !c.paragraph()->at( c.index() )->anchorHref().isEmpty() ) { 4550 !c.paragraph()->at( c.index() )->anchorHref().isEmpty() ) {
4551 if ( c.index() < c.paragraph()->length() - 1 ) 4551 if ( c.index() < c.paragraph()->length() - 1 )
4552 onLink = c.paragraph()->at( c.index() )->anchorHref(); 4552 onLink = c.paragraph()->at( c.index() )->anchorHref();
4553 else 4553 else
4554 onLink = QString::null; 4554 onLink = QString::null;
4555 4555
4556#ifndef QT_NO_CURSOR 4556#ifndef QT_NO_CURSOR
4557 viewport()->setCursor( onLink.isEmpty() ? arrowCursor : pointingHandCursor ); 4557 viewport()->setCursor( onLink.isEmpty() ? arrowCursor : pointingHandCursor );
4558#endif 4558#endif
4559 QUrl u( doc->context(), onLink, TRUE ); 4559 QUrl u( doc->context(), onLink, TRUE );
4560 emitHighlighted( u.toString( FALSE, FALSE ) ); 4560 emitHighlighted( u.toString( FALSE, FALSE ) );
4561 } else { 4561 } else {
4562#ifndef QT_NO_CURSOR 4562#ifndef QT_NO_CURSOR
4563 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor ); 4563 viewport()->setCursor( isReadOnly() ? arrowCursor : ibeamCursor );
4564#endif 4564#endif
4565 onLink = QString::null; 4565 onLink = QString::null;
4566 emitHighlighted( QString::null ); 4566 emitHighlighted( QString::null );
4567 } 4567 }
4568#endif 4568#endif
4569 } 4569 }
4570} 4570}
4571 4571
4572void QTextEdit::placeCursor( const QPoint &pos, QTextCursor *c ) 4572void QTextEdit::placeCursor( const QPoint &pos, QTextCursor *c )
4573{ 4573{
4574 placeCursor( pos, c, FALSE ); 4574 placeCursor( pos, c, FALSE );
4575} 4575}
diff --git a/noncore/apps/qashmoney/accountdisplay.cpp b/noncore/apps/qashmoney/accountdisplay.cpp
index 5ef5454..0fe5b09 100755
--- a/noncore/apps/qashmoney/accountdisplay.cpp
+++ b/noncore/apps/qashmoney/accountdisplay.cpp
@@ -1,446 +1,446 @@
1#include <qmessagebox.h> 1#include <qmessagebox.h>
2#include <qheader.h> 2#include <qheader.h>
3 3
4#include "accountdisplay.h" 4#include "accountdisplay.h"
5#include "newaccount.h" 5#include "newaccount.h"
6#include "transaction.h" 6#include "transaction.h"
7#include "transferdialog.h" 7#include "transferdialog.h"
8#include "transfer.h" 8#include "transfer.h"
9 9
10extern Account *account; 10extern Account *account;
11extern Transaction *transaction; 11extern Transaction *transaction;
12extern Transfer *transfer; 12extern Transfer *transfer;
13extern Preferences *preferences; 13extern Preferences *preferences;
14 14
15AccountDisplay::AccountDisplay ( QWidget *parent ) : QWidget ( parent ) 15AccountDisplay::AccountDisplay ( QWidget *parent ) : QWidget ( parent )
16 { 16 {
17 cleared = 0; 17 cleared = 0;
18 18
19 firstline = new QHBox ( this ); 19 firstline = new QHBox ( this );
20 firstline->setSpacing ( 2 ); 20 firstline->setSpacing ( 2 );
21 21
22 newaccount = new QPushButton ( firstline ); 22 newaccount = new QPushButton ( firstline );
23 newaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") ); 23 newaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") );
24 connect ( newaccount, SIGNAL ( released () ), this, SLOT ( addAccount () ) ); 24 connect ( newaccount, SIGNAL ( released() ), this, SLOT ( addAccount() ) );
25 25
26 editaccount = new QPushButton ( firstline ); 26 editaccount = new QPushButton ( firstline );
27 editaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/edit.png") ); 27 editaccount->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/edit.png") );
28 connect ( editaccount, SIGNAL ( released () ), this, SLOT ( editAccount () ) ); 28 connect ( editaccount, SIGNAL ( released() ), this, SLOT ( editAccount() ) );
29 29
30 deleteaccount = new QPushButton ( firstline ); 30 deleteaccount = new QPushButton ( firstline );
31 deleteaccount->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") ); 31 deleteaccount->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") );
32 connect ( deleteaccount, SIGNAL ( released () ), this, SLOT ( deleteAccount () ) ); 32 connect ( deleteaccount, SIGNAL ( released() ), this, SLOT ( deleteAccount() ) );
33 33
34 transferbutton = new QPushButton ( firstline ); 34 transferbutton = new QPushButton ( firstline );
35 transferbutton->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/transfer.png") ); 35 transferbutton->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/transfer.png") );
36 transferbutton->setToggleButton ( TRUE ); 36 transferbutton->setToggleButton ( TRUE );
37 connect ( transferbutton, SIGNAL ( toggled ( bool ) ), this, SLOT ( accountTransfer ( bool ) ) ); 37 connect ( transferbutton, SIGNAL ( toggled(bool) ), this, SLOT ( accountTransfer(bool) ) );
38 38
39 listview = new QListView ( this ); 39 listview = new QListView ( this );
40 listview->setAllColumnsShowFocus ( TRUE ); 40 listview->setAllColumnsShowFocus ( TRUE );
41 listview->setShowSortIndicator ( TRUE ); 41 listview->setShowSortIndicator ( TRUE );
42 listview->setRootIsDecorated ( TRUE ); 42 listview->setRootIsDecorated ( TRUE );
43 listview->setMultiSelection ( FALSE ); 43 listview->setMultiSelection ( FALSE );
44 connect ( listview, SIGNAL ( expanded ( QListViewItem * ) ), this, SLOT ( setAccountExpanded ( QListViewItem * ) ) ); 44 connect ( listview, SIGNAL ( expanded(QListViewItem*) ), this, SLOT ( setAccountExpanded(QListViewItem*) ) );
45 connect ( listview, SIGNAL ( collapsed ( QListViewItem * ) ), this, SLOT ( setAccountCollapsed ( QListViewItem * ) ) ); 45 connect ( listview, SIGNAL ( collapsed(QListViewItem*) ), this, SLOT ( setAccountCollapsed(QListViewItem*) ) );
46 46
47 listview->header()->setTracking ( FALSE ); 47 listview->header()->setTracking ( FALSE );
48 connect ( listview->header(), SIGNAL ( sizeChange ( int, int, int ) ), this, SLOT ( saveColumnSize ( int, int, int ) ) ); 48 connect ( listview->header(), SIGNAL ( sizeChange(int,int,int) ), this, SLOT ( saveColumnSize(int,int,int) ) );
49 connect ( listview->header(), SIGNAL ( clicked ( int ) ), this, SLOT ( saveSortingPreference ( int ) ) ); 49 connect ( listview->header(), SIGNAL ( clicked(int) ), this, SLOT ( saveSortingPreference(int) ) );
50 50
51 layout = new QVBoxLayout ( this, 2, 5 ); 51 layout = new QVBoxLayout ( this, 2, 5 );
52 layout->addWidget ( firstline ); 52 layout->addWidget ( firstline );
53 layout->addWidget ( listview ); 53 layout->addWidget ( listview );
54 } 54 }
55 55
56void AccountDisplay::setTabs ( QWidget *newtab2, QTabWidget *newtabs ) 56void AccountDisplay::setTabs ( QWidget *newtab2, QTabWidget *newtabs )
57 { 57 {
58 tab2 = newtab2; 58 tab2 = newtab2;
59 maintabs = newtabs; 59 maintabs = newtabs;
60 } 60 }
61 61
62void AccountDisplay::addAccount () 62void AccountDisplay::addAccount ()
63 { 63 {
64 // initialize local variables 64 // initialize local variables
65 int parentid = 0; 65 int parentid = 0;
66 type = 0; 66 type = 0;
67 QString parentlist [ listview->childCount() + 1 ] [ 3 ] ; 67 QString parentlist [ listview->childCount() + 1 ] [ 3 ] ;
68 68
69 // create new account window for entering data 69 // create new account window for entering data
70 NewAccount *newaccount = new NewAccount ( this ); 70 NewAccount *newaccount = new NewAccount ( this );
71 int width = this->width(); 71 int width = this->width();
72 newaccount->accountbox->setMaximumWidth ( ( int ) ( width * 0.5 ) ); 72 newaccount->accountbox->setMaximumWidth ( ( int ) ( width * 0.5 ) );
73 newaccount->datebox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 73 newaccount->datebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
74 newaccount->childbox->setMaximumWidth ( ( int ) ( width * 0.5 ) ); 74 newaccount->childbox->setMaximumWidth ( ( int ) ( width * 0.5 ) );
75 newaccount->balancebox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 75 newaccount->balancebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
76 newaccount->creditlimitbox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 76 newaccount->creditlimitbox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
77 77
78 // if there are no accounts, disable the child check box 78 // if there are no accounts, disable the child check box
79 if ( account->getNumberOfAccounts () == 0 ) 79 if ( account->getNumberOfAccounts () == 0 )
80 newaccount->childcheckbox->setEnabled ( FALSE ); 80 newaccount->childcheckbox->setEnabled ( FALSE );
81 81
82 // if there are accounts, fill up the pulldown menu for 82 // if there are accounts, fill up the pulldown menu for
83 // selecting a parent account. We should only add those parents without transactions 83 // selecting a parent account. We should only add those parents without transactions
84 else 84 else
85 { 85 {
86 int c = 0; 86 int c = 0;
87 QListViewItemIterator it ( listview ); 87 QListViewItemIterator it ( listview );
88 for ( ; it.current(); ++it ) 88 for ( ; it.current(); ++it )
89 { 89 {
90 int id = it.current()->text ( getIDColumn() ).toInt(); 90 int id = it.current()->text ( getIDColumn() ).toInt();
91 // iterate through accountdisplay listview and add parents with no transactions 91 // iterate through accountdisplay listview and add parents with no transactions
92 // add this item to the list box only if it is a parent and has no transactions 92 // add this item to the list box only if it is a parent and has no transactions
93 if ( transfer->getNumberOfTransfers ( id ) == 0 && transaction->getNumberOfTransactions ( id ) == 0 && it.current()->parent() == 0 ) 93 if ( transfer->getNumberOfTransfers ( id ) == 0 && transaction->getNumberOfTransactions ( id ) == 0 && it.current()->parent() == 0 )
94 { 94 {
95 newaccount->childbox->insertItem ( it.current()->text ( 0 ) ); 95 newaccount->childbox->insertItem ( it.current()->text ( 0 ) );
96 parentlist [ c ] [ 0 ] = it.current()->text ( 0 ); 96 parentlist [ c ] [ 0 ] = it.current()->text ( 0 );
97 parentlist [ c ] [ 1 ] = it.current()->text ( getIDColumn() ); 97 parentlist [ c ] [ 1 ] = it.current()->text ( getIDColumn() );
98 parentlist [ c ] [ 2 ] = QString::number ( c ); 98 parentlist [ c ] [ 2 ] = QString::number ( c );
99 c++; 99 c++;
100 } 100 }
101 } 101 }
102 } 102 }
103 103
104 if ( preferences->getPreference ( 4 ) == 0 ) 104 if ( preferences->getPreference ( 4 ) == 0 )
105 newaccount->currencybox->setEnabled ( FALSE ); 105 newaccount->currencybox->setEnabled ( FALSE );
106 106
107 // enter today's date in the date box as default 107 // enter today's date in the date box as default
108 QDate today = QDate::currentDate (); 108 QDate today = QDate::currentDate ();
109 int defaultday = today.day(); 109 int defaultday = today.day();
110 int defaultmonth = today.month(); 110 int defaultmonth = today.month();
111 int defaultyear = today.year(); 111 int defaultyear = today.year();
112 newaccount->startdate->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) ); 112 newaccount->startdate->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) );
113 113
114 //add account information if user pushes OK button 114 //add account information if user pushes OK button
115 if ( newaccount->exec() == QDialog::Accepted ) 115 if ( newaccount->exec() == QDialog::Accepted )
116 { 116 {
117 if ( newaccount->childcheckbox->isChecked () == TRUE ) // set a parent id and type for a child account 117 if ( newaccount->childcheckbox->isChecked () == TRUE ) // set a parent id and type for a child account
118 { 118 {
119 // go through the parentlist we created and determine the parent accountid 119 // go through the parentlist we created and determine the parent accountid
120 // we can't use the name of the account because there may be two accounts 120 // we can't use the name of the account because there may be two accounts
121 // with the same name. This function does it all by accountid 121 // with the same name. This function does it all by accountid
122 int counter; 122 int counter;
123 for ( counter = 0; counter < listview->childCount() + 1; counter++ ) 123 for ( counter = 0; counter < listview->childCount() + 1; counter++ )
124 if ( ( parentlist [ counter ] [ 2 ].toInt() ) == newaccount->childbox->currentItem() ) 124 if ( ( parentlist [ counter ] [ 2 ].toInt() ) == newaccount->childbox->currentItem() )
125 { 125 {
126 parentid = parentlist [ counter ] [ 1 ].toInt(); 126 parentid = parentlist [ counter ] [ 1 ].toInt();
127 break; 127 break;
128 } 128 }
129 type = ( newaccount->accounttype->currentItem() ) + 6; // sets account ids for child accounts. See accountdisplay.h for types 129 type = ( newaccount->accounttype->currentItem() ) + 6; // sets account ids for child accounts. See accountdisplay.h for types
130 } 130 }
131 else 131 else
132 { 132 {
133 parentid = -1; 133 parentid = -1;
134 type = newaccount->accounttype->currentItem(); // sets account ids for parent accounts 134 type = newaccount->accounttype->currentItem(); // sets account ids for parent accounts
135 } 135 }
136 136
137 // add the new account 137 // add the new account
138 if ( newaccount->getDateEdited () == TRUE ) 138 if ( newaccount->getDateEdited () == TRUE )
139 account->addAccount ( newaccount->accountname->text(), parentid, newaccount->accountbalance->text().toFloat(), type, 139 account->addAccount ( newaccount->accountname->text(), parentid, newaccount->accountbalance->text().toFloat(), type,
140 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), newaccount->getYear(), 140 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), newaccount->getYear(),
141 newaccount->getMonth(), newaccount->getDay(), newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() ); 141 newaccount->getMonth(), newaccount->getDay(), newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() );
142 else 142 else
143 account->addAccount ( newaccount->accountname->text (), parentid, newaccount->accountbalance->text().toFloat(), type, 143 account->addAccount ( newaccount->accountname->text (), parentid, newaccount->accountbalance->text().toFloat(), type,
144 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), defaultyear, 144 newaccount->getDescription(), newaccount->creditlimit->text().toFloat(), defaultyear,
145 defaultmonth, defaultday, newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() ); 145 defaultmonth, defaultday, newaccount->accountbalance->text().toFloat(), newaccount->currencybox->currencybox->currentText() );
146 146
147 if ( parentid != -1 ) 147 if ( parentid != -1 )
148 account->changeParentAccountBalance ( parentid ); 148 account->changeParentAccountBalance ( parentid );
149 149
150 // redisplay accounts 150 // redisplay accounts
151 // this function clears the account display first 151 // this function clears the account display first
152 account->displayAccounts ( listview ); 152 account->displayAccounts ( listview );
153 setToggleButton(); 153 setToggleButton();
154 } 154 }
155 maintabs->setTabEnabled ( tab2, FALSE ); 155 maintabs->setTabEnabled ( tab2, FALSE );
156 } 156 }
157 157
158void AccountDisplay::deleteAccount () 158void AccountDisplay::deleteAccount ()
159 { 159 {
160 if ( listview->selectedItem() == 0 ) 160 if ( listview->selectedItem() == 0 )
161 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto delete."); 161 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto delete.");
162 else if ( listview->selectedItem()->parent() == 0 && listview->selectedItem()->childCount() != 0 ) 162 else if ( listview->selectedItem()->parent() == 0 && listview->selectedItem()->childCount() != 0 )
163 QMessageBox::warning ( this, "QashMoney", "Can't delete parent accounts\nwith children"); 163 QMessageBox::warning ( this, "QashMoney", "Can't delete parent accounts\nwith children");
164 else 164 else
165 { 165 {
166 QMessageBox mb ( "Delete Account", "This will delete all transactions\nand transfers for this account.", QMessageBox::Information, QMessageBox::Ok, QMessageBox::Cancel, QMessageBox::NoButton ); 166 QMessageBox mb ( "Delete Account", "This will delete all transactions\nand transfers for this account.", QMessageBox::Information, QMessageBox::Ok, QMessageBox::Cancel, QMessageBox::NoButton );
167 if ( mb.exec() == QMessageBox::Ok ) 167 if ( mb.exec() == QMessageBox::Ok )
168 { 168 {
169 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt (); 169 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt ();
170 int parentid = account->getParentAccountID ( accountid ); 170 int parentid = account->getParentAccountID ( accountid );
171 171
172 // delete all the transactions and transfers for the account 172 // delete all the transactions and transfers for the account
173 transaction->deleteAllTransactions ( accountid ); 173 transaction->deleteAllTransactions ( accountid );
174 transfer->deleteAllTransfers ( accountid ); 174 transfer->deleteAllTransfers ( accountid );
175 175
176 // delete the account 176 // delete the account
177 account->deleteAccount ( accountid ); 177 account->deleteAccount ( accountid );
178 178
179 // update account balances 179 // update account balances
180 if ( parentid != -1 ) 180 if ( parentid != -1 )
181 account->changeParentAccountBalance ( parentid ); 181 account->changeParentAccountBalance ( parentid );
182 182
183 //redisplay accounts 183 //redisplay accounts
184 account->displayAccounts ( listview ); 184 account->displayAccounts ( listview );
185 185
186 //remove all the columns from the accountdisplay if there are not any accounts 186 //remove all the columns from the accountdisplay if there are not any accounts
187 if ( account->getNumberOfAccounts() == 0 ) 187 if ( account->getNumberOfAccounts() == 0 )
188 { 188 {
189 int columns = listview->columns(); 189 int columns = listview->columns();
190 int counter; 190 int counter;
191 for ( counter = 0; counter <= columns; counter++ ) 191 for ( counter = 0; counter <= columns; counter++ )
192 listview->removeColumn ( 0 ); 192 listview->removeColumn ( 0 );
193 } 193 }
194 194
195 setToggleButton(); 195 setToggleButton();
196 } 196 }
197 } 197 }
198 maintabs->setTabEnabled ( tab2, FALSE ); 198 maintabs->setTabEnabled ( tab2, FALSE );
199 } 199 }
200 200
201void AccountDisplay::setToggleButton () 201void AccountDisplay::setToggleButton ()
202 { 202 {
203 // iterate through account display and determine how many "transferable" accounts we have 203 // iterate through account display and determine how many "transferable" accounts we have
204 // if there are less than two, disable the transfer button 204 // if there are less than two, disable the transfer button
205 QListViewItemIterator it ( listview ); 205 QListViewItemIterator it ( listview );
206 int counter = 0; 206 int counter = 0;
207 for ( ; it.current(); ++it ) 207 for ( ; it.current(); ++it )
208 { 208 {
209 // add one to counter if we find a transferable account 209 // add one to counter if we find a transferable account
210 if ( it.current()->parent() != 0 || ( it.current()->childCount() ) == 0 ) 210 if ( it.current()->parent() != 0 || ( it.current()->childCount() ) == 0 )
211 counter++; 211 counter++;
212 } 212 }
213 if ( counter > 1 ) 213 if ( counter > 1 )
214 transferbutton->show(); 214 transferbutton->show();
215 else 215 else
216 transferbutton->hide(); 216 transferbutton->hide();
217 } 217 }
218 218
219void AccountDisplay::accountTransfer ( bool state ) 219void AccountDisplay::accountTransfer ( bool state )
220 { 220 {
221 if ( state == TRUE ) 221 if ( state == TRUE )
222 { 222 {
223 firstaccountid = -1; 223 firstaccountid = -1;
224 secondaccountid = -1; 224 secondaccountid = -1;
225 listview->clearSelection (); 225 listview->clearSelection ();
226 listview->setMultiSelection ( TRUE ); 226 listview->setMultiSelection ( TRUE );
227 disableParentsWithChildren (); 227 disableParentsWithChildren ();
228 connect ( listview, SIGNAL ( clicked ( QListViewItem * ) ), this, SLOT ( getTransferAccounts ( QListViewItem * ) ) ); 228 connect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
229 } 229 }
230 else 230 else
231 { 231 {
232 firstaccountid = -1; 232 firstaccountid = -1;
233 secondaccountid = -1; 233 secondaccountid = -1;
234 listview->clearSelection (); 234 listview->clearSelection ();
235 listview->setMultiSelection ( FALSE ); 235 listview->setMultiSelection ( FALSE );
236 enableAccounts (); 236 enableAccounts ();
237 disconnect ( listview, SIGNAL ( clicked ( QListViewItem * ) ), this, SLOT ( getTransferAccounts ( QListViewItem * ) ) ); 237 disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
238 } 238 }
239 } 239 }
240 240
241void AccountDisplay::getTransferAccounts ( QListViewItem * item ) 241void AccountDisplay::getTransferAccounts ( QListViewItem * item )
242 { 242 {
243 if ( item->parent() != 0 || item->childCount() == 0 ) // only set an account for transfer if its a child or parent with no children 243 if ( item->parent() != 0 || item->childCount() == 0 ) // only set an account for transfer if its a child or parent with no children
244 { 244 {
245 if ( firstaccountid == -1 ) 245 if ( firstaccountid == -1 )
246 firstaccountid = item->text ( getIDColumn() ).toInt(); // set first account if we've selected a valid account 246 firstaccountid = item->text ( getIDColumn() ).toInt(); // set first account if we've selected a valid account
247 else 247 else
248 if ( item->text ( getIDColumn() ).toInt() != firstaccountid ) // set the second account if its not equal to the first 248 if ( item->text ( getIDColumn() ).toInt() != firstaccountid ) // set the second account if its not equal to the first
249 secondaccountid = item->text ( getIDColumn() ).toInt(); 249 secondaccountid = item->text ( getIDColumn() ).toInt();
250 } 250 }
251 251
252 // open transfer window if both accounts are set 252 // open transfer window if both accounts are set
253 if ( firstaccountid != -1 && secondaccountid != -1 ) 253 if ( firstaccountid != -1 && secondaccountid != -1 )
254 { 254 {
255 // construct the transferdialog window 255 // construct the transferdialog window
256 TransferDialog *td = new TransferDialog ( this, firstaccountid, secondaccountid ); 256 TransferDialog *td = new TransferDialog ( this, firstaccountid, secondaccountid );
257 257
258 // enter today's date in the date box as default 258 // enter today's date in the date box as default
259 QDate today = QDate::currentDate (); 259 QDate today = QDate::currentDate ();
260 int defaultday = today.day(); 260 int defaultday = today.day();
261 int defaultmonth = today.month(); 261 int defaultmonth = today.month();
262 int defaultyear = today.year(); 262 int defaultyear = today.year();
263 td->date->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) ); 263 td->date->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) );
264 264
265 if ( td->exec() == QDialog::Accepted ) 265 if ( td->exec() == QDialog::Accepted )
266 { 266 {
267 // set the cleared integer if the checkbox is checked 267 // set the cleared integer if the checkbox is checked
268 if ( td->clearedcheckbox->isChecked() == TRUE ) 268 if ( td->clearedcheckbox->isChecked() == TRUE )
269 cleared = 1; 269 cleared = 1;
270 qDebug("Year from transferdialog = %i",td->getYear()); 270 qDebug("Year from transferdialog = %i",td->getYear());
271 // add the transfer with a new date if its been edited or use the default date 271 // add the transfer with a new date if its been edited or use the default date
272 if ( td->getDateEdited () == TRUE ) 272 if ( td->getDateEdited () == TRUE )
273 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), td->getDay(), td->getMonth(), td->getYear(), td->amount->text().toFloat(), cleared ); 273 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), td->getDay(), td->getMonth(), td->getYear(), td->amount->text().toFloat(), cleared );
274 else 274 else
275 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), defaultday, defaultmonth, defaultyear, td->amount->text().toFloat(), cleared ); 275 transfer->addTransfer ( firstaccountid, account->getParentAccountID ( firstaccountid ), secondaccountid, account->getParentAccountID ( secondaccountid ), defaultday, defaultmonth, defaultyear, td->amount->text().toFloat(), cleared );
276 276
277 // update account balances of both accounts and parents if necessary 277 // update account balances of both accounts and parents if necessary
278 account->updateAccountBalance ( firstaccountid ); 278 account->updateAccountBalance ( firstaccountid );
279 if ( account->getParentAccountID ( firstaccountid ) != -1 ) 279 if ( account->getParentAccountID ( firstaccountid ) != -1 )
280 account->changeParentAccountBalance ( account->getParentAccountID ( firstaccountid ) ); 280 account->changeParentAccountBalance ( account->getParentAccountID ( firstaccountid ) );
281 account->updateAccountBalance ( secondaccountid ); 281 account->updateAccountBalance ( secondaccountid );
282 if ( account->getParentAccountID ( secondaccountid ) != -1 ) 282 if ( account->getParentAccountID ( secondaccountid ) != -1 )
283 account->changeParentAccountBalance ( account->getParentAccountID ( secondaccountid ) ); 283 account->changeParentAccountBalance ( account->getParentAccountID ( secondaccountid ) );
284 284
285 // redisplay accounts 285 // redisplay accounts
286 account->displayAccounts ( listview ); 286 account->displayAccounts ( listview );
287 } 287 }
288 else 288 else
289 { 289 {
290 firstaccountid = -1; 290 firstaccountid = -1;
291 secondaccountid = -1; 291 secondaccountid = -1;
292 listview->clearSelection (); 292 listview->clearSelection ();
293 listview->setMultiSelection ( FALSE ); 293 listview->setMultiSelection ( FALSE );
294 disconnect ( listview, SIGNAL ( clicked ( QListViewItem * ) ), this, SLOT ( getTransferAccounts ( QListViewItem * ) ) ); 294 disconnect ( listview, SIGNAL ( clicked(QListViewItem*) ), this, SLOT ( getTransferAccounts(QListViewItem*) ) );
295 } 295 }
296 296
297 // reset the accounts display window 297 // reset the accounts display window
298 transferbutton->toggle(); // toggling this button with clear the window as well 298 transferbutton->toggle(); // toggling this button with clear the window as well
299 299
300 // reenable all the accounts so the transaction tab will be properly set 300 // reenable all the accounts so the transaction tab will be properly set
301 enableAccounts (); 301 enableAccounts ();
302 } 302 }
303 } 303 }
304 304
305void AccountDisplay::disableParentsWithChildren () 305void AccountDisplay::disableParentsWithChildren ()
306 { 306 {
307 // iterate through accountdisplay listview and disable all the parents that have children 307 // iterate through accountdisplay listview and disable all the parents that have children
308 QListViewItemIterator it ( listview ); 308 QListViewItemIterator it ( listview );
309 for ( ; it.current(); ++it ) 309 for ( ; it.current(); ++it )
310 { 310 {
311 if ( it.current()->parent() == 0 && it.current()->childCount() != 0 ) 311 if ( it.current()->parent() == 0 && it.current()->childCount() != 0 )
312 it.current()->setSelectable ( FALSE ); 312 it.current()->setSelectable ( FALSE );
313 } 313 }
314 } 314 }
315 315
316void AccountDisplay::enableAccounts () 316void AccountDisplay::enableAccounts ()
317 { 317 {
318 // iterate through accountdisplay listview and enable all accounts 318 // iterate through accountdisplay listview and enable all accounts
319 QListViewItemIterator it ( listview ); 319 QListViewItemIterator it ( listview );
320 for ( ; it.current(); ++it ) 320 for ( ; it.current(); ++it )
321 it.current()->setSelectable ( TRUE ); 321 it.current()->setSelectable ( TRUE );
322 } 322 }
323 323
324void AccountDisplay::saveColumnSize ( int column, int oldsize, int newsize ) 324void AccountDisplay::saveColumnSize ( int column, int oldsize, int newsize )
325 { 325 {
326 switch ( column ) 326 switch ( column )
327 { 327 {
328 case 0: 328 case 0:
329 if ( listview->columns() == 3 ) 329 if ( listview->columns() == 3 )
330 preferences->changeColumnPreference ( 1, newsize ); 330 preferences->changeColumnPreference ( 1, newsize );
331 else 331 else
332 preferences->changeColumnPreference ( 10, newsize ); 332 preferences->changeColumnPreference ( 10, newsize );
333 break; 333 break;
334 case 1: 334 case 1:
335 if ( listview->columns() == 3 ) 335 if ( listview->columns() == 3 )
336 preferences->changeColumnPreference ( 2, newsize ); 336 preferences->changeColumnPreference ( 2, newsize );
337 else 337 else
338 preferences->changeColumnPreference ( 11, newsize ); 338 preferences->changeColumnPreference ( 11, newsize );
339 break; 339 break;
340 case 2: 340 case 2:
341 preferences->changeColumnPreference ( 12, newsize ); 341 preferences->changeColumnPreference ( 12, newsize );
342 break; 342 break;
343 } 343 }
344 344
345 } 345 }
346 346
347void AccountDisplay::saveSortingPreference ( int column ) 347void AccountDisplay::saveSortingPreference ( int column )
348 { 348 {
349 preferences->changeSortingPreference ( 1, column ); 349 preferences->changeSortingPreference ( 1, column );
350 } 350 }
351 351
352int AccountDisplay::getIDColumn () 352int AccountDisplay::getIDColumn ()
353 { 353 {
354 int counter; 354 int counter;
355 int columns = listview->columns(); 355 int columns = listview->columns();
356 for ( counter = 0; counter <= columns; counter++ ) 356 for ( counter = 0; counter <= columns; counter++ )
357 if ( listview->header()->label ( counter ).length() == 0 ) 357 if ( listview->header()->label ( counter ).length() == 0 )
358 return counter; 358 return counter;
359 } 359 }
360 360
361void AccountDisplay::editAccount () 361void AccountDisplay::editAccount ()
362 { 362 {
363 if ( listview->selectedItem() == 0 ) 363 if ( listview->selectedItem() == 0 )
364 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto edit."); 364 QMessageBox::warning ( this, "QashMoney", "Please select an account\nto edit.");
365 else 365 else
366 { 366 {
367 // set the accountid 367 // set the accountid
368 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt(); 368 int accountid = listview->selectedItem()->text ( getIDColumn() ).toInt();
369 369
370 //construct new dialog box 370 //construct new dialog box
371 QDialog *editaccountwindow = new QDialog ( this, 0, TRUE ); 371 QDialog *editaccountwindow = new QDialog ( this, 0, TRUE );
372 editaccountwindow->setCaption ( "Edit Account" ); 372 editaccountwindow->setCaption ( "Edit Account" );
373 373
374 // construct the items which will go in the dialog bix 374 // construct the items which will go in the dialog bix
375 QLabel *namelabel = new QLabel ( "Account Name", editaccountwindow ); 375 QLabel *namelabel = new QLabel ( "Account Name", editaccountwindow );
376 QLineEdit *accountname = new QLineEdit ( editaccountwindow ); 376 QLineEdit *accountname = new QLineEdit ( editaccountwindow );
377 QLabel *descriptionlabel = new QLabel ( "Account Description", editaccountwindow ); 377 QLabel *descriptionlabel = new QLabel ( "Account Description", editaccountwindow );
378 QLineEdit *accountdescription = new QLineEdit ( editaccountwindow ); 378 QLineEdit *accountdescription = new QLineEdit ( editaccountwindow );
379 Currency *currencybox = new Currency ( editaccountwindow ); 379 Currency *currencybox = new Currency ( editaccountwindow );
380 380
381 QVBoxLayout *layout = new QVBoxLayout ( editaccountwindow, 5, 2 ); 381 QVBoxLayout *layout = new QVBoxLayout ( editaccountwindow, 5, 2 );
382 layout->addWidget ( namelabel ); 382 layout->addWidget ( namelabel );
383 layout->addWidget ( accountname ); 383 layout->addWidget ( accountname );
384 layout->addWidget ( descriptionlabel ); 384 layout->addWidget ( descriptionlabel );
385 layout->addWidget ( accountdescription ); 385 layout->addWidget ( accountdescription );
386 layout->addWidget ( currencybox ); 386 layout->addWidget ( currencybox );
387 387
388 //set the account name 388 //set the account name
389 accountname->setText ( listview->selectedItem()->text ( 0 ) ); 389 accountname->setText ( listview->selectedItem()->text ( 0 ) );
390 390
391 //set the account description 391 //set the account description
392 accountdescription->setText ( account->getAccountDescription ( accountid ) ); 392 accountdescription->setText ( account->getAccountDescription ( accountid ) );
393 393
394 if ( preferences->getPreference ( 4 ) == 1 ) 394 if ( preferences->getPreference ( 4 ) == 1 )
395 { 395 {
396 // get currency code for this account then iterate through the currency box 396 // get currency code for this account then iterate through the currency box
397 // to find the one we want 397 // to find the one we want
398 int count = currencybox->currencybox->count(); 398 int count = currencybox->currencybox->count();
399 QString code = account->getCurrencyCode ( accountid ); 399 QString code = account->getCurrencyCode ( accountid );
400 for ( int counter = 0; count - 1; counter++ ) 400 for ( int counter = 0; count - 1; counter++ )
401 { 401 {
402 if ( QString::compare ( currencybox->currencybox->text ( counter ), code ) == 0 ) 402 if ( QString::compare ( currencybox->currencybox->text ( counter ), code ) == 0 )
403 { 403 {
404 currencybox->currencybox->setCurrentItem ( counter ); 404 currencybox->currencybox->setCurrentItem ( counter );
405 break; 405 break;
406 } 406 }
407 } 407 }
408 } 408 }
409 else 409 else
410 currencybox->setEnabled ( FALSE ); 410 currencybox->setEnabled ( FALSE );
411 411
412 //execute the dialog box 412 //execute the dialog box
413 int response = editaccountwindow->exec(); 413 int response = editaccountwindow->exec();
414 if ( response == 1 ) 414 if ( response == 1 )
415 { 415 {
416 account->updateAccount ( accountname->text(), accountdescription->text(), currencybox->currencybox->currentText(), accountid ); 416 account->updateAccount ( accountname->text(), accountdescription->text(), currencybox->currencybox->currentText(), accountid );
417 account->displayAccounts ( listview ); 417 account->displayAccounts ( listview );
418 418
419 // Try and select the same account that was just edited 419 // Try and select the same account that was just edited
420 QListViewItemIterator it ( listview ); 420 QListViewItemIterator it ( listview );
421 for ( ; it.current(); ++it ) 421 for ( ; it.current(); ++it )
422 { 422 {
423 if ( it.current()->text ( 0 ) == accountname->text() ) 423 if ( it.current()->text ( 0 ) == accountname->text() )
424 { 424 {
425 listview->setSelected ( it.current(), TRUE ); 425 listview->setSelected ( it.current(), TRUE );
426 return; 426 return;
427 } 427 }
428 } 428 }
429 maintabs->setTabEnabled ( tab2, FALSE ); 429 maintabs->setTabEnabled ( tab2, FALSE );
430 } 430 }
431 } 431 }
432 } 432 }
433 433
434void AccountDisplay::setAccountExpanded ( QListViewItem *item ) 434void AccountDisplay::setAccountExpanded ( QListViewItem *item )
435 { 435 {
436 int accountid = item->text ( getIDColumn() ).toInt(); 436 int accountid = item->text ( getIDColumn() ).toInt();
437 account->setAccountExpanded ( 1, accountid ); 437 account->setAccountExpanded ( 1, accountid );
438 } 438 }
439 439
440void AccountDisplay::setAccountCollapsed ( QListViewItem *item ) 440void AccountDisplay::setAccountCollapsed ( QListViewItem *item )
441 { 441 {
442 int accountid = item->text ( getIDColumn() ).toInt(); 442 int accountid = item->text ( getIDColumn() ).toInt();
443 account->setAccountExpanded ( 0, accountid ); 443 account->setAccountExpanded ( 0, accountid );
444 } 444 }
445 445
446 446
diff --git a/noncore/apps/qashmoney/budgetdisplay.cpp b/noncore/apps/qashmoney/budgetdisplay.cpp
index d4047bf..3fc4e6c 100755
--- a/noncore/apps/qashmoney/budgetdisplay.cpp
+++ b/noncore/apps/qashmoney/budgetdisplay.cpp
@@ -1,417 +1,417 @@
1#include <qmessagebox.h> 1#include <qmessagebox.h>
2#include <qheader.h> 2#include <qheader.h>
3#include <sqlite.h> 3#include <sqlite.h>
4 4
5#include "budgetdisplay.h" 5#include "budgetdisplay.h"
6#include "budget.h" 6#include "budget.h"
7#include "datepicker.h" 7#include "datepicker.h"
8#include "transaction.h" 8#include "transaction.h"
9 9
10extern Preferences *preferences; 10extern Preferences *preferences;
11extern Budget *budget; 11extern Budget *budget;
12extern Transaction *transaction; 12extern Transaction *transaction;
13 13
14BudgetDisplay::BudgetDisplay ( QWidget *parent ) : QWidget ( parent ) 14BudgetDisplay::BudgetDisplay ( QWidget *parent ) : QWidget ( parent )
15 { 15 {
16 QFont font = this->font(); 16 QFont font = this->font();
17 font.setWeight ( QFont::Bold ); 17 font.setWeight ( QFont::Bold );
18 18
19 //set the default date to today 19 //set the default date to today
20 newDate = QDate::currentDate (); 20 newDate = QDate::currentDate ();
21 year = newDate.year(); 21 year = newDate.year();
22 month = newDate.month(); 22 month = newDate.month();
23 day = newDate.day(); 23 day = newDate.day();
24 datelabel = preferences->getDate ( year, month ); 24 datelabel = preferences->getDate ( year, month );
25 25
26 setCaption ( "Budget" ); 26 setCaption ( "Budget" );
27 27
28 firstline = new QHBox ( this ); 28 firstline = new QHBox ( this );
29 firstline->setSpacing ( 2 ); 29 firstline->setSpacing ( 2 );
30 secondline = new QHBox ( this ); 30 secondline = new QHBox ( this );
31 secondline->setSpacing ( 10 ); 31 secondline->setSpacing ( 10 );
32 32
33 menu = new QMenuBar ( this ); 33 menu = new QMenuBar ( this );
34 menu->setFrameStyle ( QFrame::Box | QFrame::Sunken ); 34 menu->setFrameStyle ( QFrame::Box | QFrame::Sunken );
35 budgetmenu = new QPopupMenu ( this ); 35 budgetmenu = new QPopupMenu ( this );
36 lineitemsmenu = new QPopupMenu ( this ); 36 lineitemsmenu = new QPopupMenu ( this );
37 datemenu = new QPopupMenu ( this ); 37 datemenu = new QPopupMenu ( this );
38 menu->insertItem ( "Budget", budgetmenu ); 38 menu->insertItem ( "Budget", budgetmenu );
39 menu->insertItem ( "Line Item", lineitemsmenu ); 39 menu->insertItem ( "Line Item", lineitemsmenu );
40 menu->insertItem ( "Date", datemenu ); 40 menu->insertItem ( "Date", datemenu );
41 budgetmenu->insertItem ( "New", this, SLOT ( newBudget () ), 0, 1 ); 41 budgetmenu->insertItem ( "New", this, SLOT ( newBudget() ), 0, 1 );
42 budgetmenu->insertItem ( "Edit", this, SLOT ( editBudget () ), 0, 2 ); 42 budgetmenu->insertItem ( "Edit", this, SLOT ( editBudget() ), 0, 2 );
43 budgetmenu->insertItem ( "Delete", this, SLOT ( deleteBudget () ), 0, 3 ); 43 budgetmenu->insertItem ( "Delete", this, SLOT ( deleteBudget() ), 0, 3 );
44 lineitemsmenu->insertItem ( "New", this, SLOT ( newLineItem () ), 0, 1 ); 44 lineitemsmenu->insertItem ( "New", this, SLOT ( newLineItem() ), 0, 1 );
45 lineitemsmenu->insertItem ( "Edit", this, SLOT ( editLineItem () ), 0, 2 ); 45 lineitemsmenu->insertItem ( "Edit", this, SLOT ( editLineItem() ), 0, 2 );
46 lineitemsmenu->insertItem ( "Delete", this, SLOT ( deleteLineItem () ), 0, 3 ); 46 lineitemsmenu->insertItem ( "Delete", this, SLOT ( deleteLineItem() ), 0, 3 );
47 datemenu->insertItem ( "Change", this, SLOT ( showCalendar() ) ); 47 datemenu->insertItem ( "Change", this, SLOT ( showCalendar() ) );
48 48
49 budgetbox = new QComboBox ( firstline ); 49 budgetbox = new QComboBox ( firstline );
50 connect ( budgetbox, SIGNAL ( activated ( int ) ), this, SLOT ( setCurrentBudget ( int ) ) ); 50 connect ( budgetbox, SIGNAL ( activated(int) ), this, SLOT ( setCurrentBudget(int) ) );
51 51
52 budgetview = new QComboBox ( firstline ); 52 budgetview = new QComboBox ( firstline );
53 budgetview->insertItem ( "Month" ); 53 budgetview->insertItem ( "Month" );
54 budgetview->insertItem ( "Year" ); 54 budgetview->insertItem ( "Year" );
55 connect ( budgetview, SIGNAL ( activated ( int ) ), this, SLOT ( setCurrentView ( int ) ) ); 55 connect ( budgetview, SIGNAL ( activated(int) ), this, SLOT ( setCurrentView(int) ) );
56 56
57 budgeted = new QLabel ( secondline ); 57 budgeted = new QLabel ( secondline );
58 budgeted->setFont ( font ); 58 budgeted->setFont ( font );
59 actual = new QLabel ( secondline ); 59 actual = new QLabel ( secondline );
60 actual->setFont ( font ); 60 actual->setFont ( font );
61 date = new QLabel ( secondline ); 61 date = new QLabel ( secondline );
62 date->setFont ( font ); 62 date->setFont ( font );
63 63
64 listview = new QListView ( this ); 64 listview = new QListView ( this );
65 listview->setAllColumnsShowFocus ( TRUE ); 65 listview->setAllColumnsShowFocus ( TRUE );
66 listview->setShowSortIndicator ( TRUE ); 66 listview->setShowSortIndicator ( TRUE );
67 listview->setRootIsDecorated ( TRUE ); 67 listview->setRootIsDecorated ( TRUE );
68 listview->setMultiSelection ( FALSE ); 68 listview->setMultiSelection ( FALSE );
69 listview->addColumn ( "Line Item", preferences->getColumnPreference ( 13 ) ); // column id 13 69 listview->addColumn ( "Line Item", preferences->getColumnPreference ( 13 ) ); // column id 13
70 listview->addColumn ( "Budget", preferences->getColumnPreference ( 14 ) ); // column id 14 70 listview->addColumn ( "Budget", preferences->getColumnPreference ( 14 ) ); // column id 14
71 listview->addColumn ( "Actual", preferences->getColumnPreference ( 15 ) ); // column id 15 71 listview->addColumn ( "Actual", preferences->getColumnPreference ( 15 ) ); // column id 15
72 listview->addColumn ( "", 0 ); // line item ids 72 listview->addColumn ( "", 0 ); // line item ids
73 listview->setColumnWidthMode ( 0, QListView::Manual ); 73 listview->setColumnWidthMode ( 0, QListView::Manual );
74 listview->setColumnWidthMode ( 1, QListView::Manual ); 74 listview->setColumnWidthMode ( 1, QListView::Manual );
75 listview->setColumnWidthMode ( 2, QListView::Manual ); 75 listview->setColumnWidthMode ( 2, QListView::Manual );
76 listview->setColumnAlignment ( 1, Qt::AlignRight ); 76 listview->setColumnAlignment ( 1, Qt::AlignRight );
77 listview->setColumnAlignment ( 2, Qt::AlignRight ); 77 listview->setColumnAlignment ( 2, Qt::AlignRight );
78 listview->setColumnWidthMode ( 3, QListView::Manual ); 78 listview->setColumnWidthMode ( 3, QListView::Manual );
79 79
80 listview->header()->setTracking ( FALSE ); 80 listview->header()->setTracking ( FALSE );
81 connect ( listview->header(), SIGNAL ( sizeChange ( int, int, int ) ), this, SLOT ( saveColumnSize ( int, int, int ) ) ); 81 connect ( listview->header(), SIGNAL ( sizeChange(int,int,int) ), this, SLOT ( saveColumnSize(int,int,int) ) );
82 connect ( listview->header(), SIGNAL ( clicked ( int ) ), this, SLOT ( saveSortingPreference ( int ) ) ); 82 connect ( listview->header(), SIGNAL ( clicked(int) ), this, SLOT ( saveSortingPreference(int) ) );
83 83
84 // pull the column sorting preference from the preferences table, and configure the listview accordingly 84 // pull the column sorting preference from the preferences table, and configure the listview accordingly
85 int column = 0; 85 int column = 0;
86 int direction = 0; 86 int direction = 0;
87 preferences->getSortingPreference ( 3, &column, &direction ); 87 preferences->getSortingPreference ( 3, &column, &direction );
88 listview->setSorting ( column, direction ); 88 listview->setSorting ( column, direction );
89 89
90 displayBudgetNames(); 90 displayBudgetNames();
91 91
92 layout = new QVBoxLayout ( this, 2, 2 ); 92 layout = new QVBoxLayout ( this, 2, 2 );
93 layout->setMenuBar ( menu ); 93 layout->setMenuBar ( menu );
94 layout->addWidget ( firstline ); 94 layout->addWidget ( firstline );
95 layout->addWidget ( secondline ); 95 layout->addWidget ( secondline );
96 layout->addWidget ( listview ); 96 layout->addWidget ( listview );
97 } 97 }
98 98
99void BudgetDisplay::deleteBudget () 99void BudgetDisplay::deleteBudget ()
100 { 100 {
101 listview->clear(); 101 listview->clear();
102 transaction->clearBudgetIDs ( currentbudget ); 102 transaction->clearBudgetIDs ( currentbudget );
103 budget->deleteBudget ( currentbudget ); 103 budget->deleteBudget ( currentbudget );
104 if ( budgetbox->count() != 0 ) 104 if ( budgetbox->count() != 0 )
105 displayBudgetNames(); 105 displayBudgetNames();
106 checkBudgets(); 106 checkBudgets();
107 } 107 }
108 108
109void BudgetDisplay::saveColumnSize ( int column, int oldsize, int newsize ) 109void BudgetDisplay::saveColumnSize ( int column, int oldsize, int newsize )
110 { 110 {
111 switch ( column ) 111 switch ( column )
112 { 112 {
113 case 0: 113 case 0:
114 preferences->changeColumnPreference ( 13, newsize ); 114 preferences->changeColumnPreference ( 13, newsize );
115 break; 115 break;
116 case 1: 116 case 1:
117 preferences->changeColumnPreference ( 14, newsize ); 117 preferences->changeColumnPreference ( 14, newsize );
118 break; 118 break;
119 case 2: 119 case 2:
120 preferences->changeColumnPreference ( 15, newsize ); 120 preferences->changeColumnPreference ( 15, newsize );
121 break; 121 break;
122 } 122 }
123 } 123 }
124 124
125void BudgetDisplay::saveSortingPreference ( int column ) 125void BudgetDisplay::saveSortingPreference ( int column )
126 { 126 {
127 preferences->changeSortingPreference ( 3, column ); 127 preferences->changeSortingPreference ( 3, column );
128 } 128 }
129 129
130int BudgetDisplay::getIDColumn () 130int BudgetDisplay::getIDColumn ()
131 { 131 {
132 int counter; 132 int counter;
133 int columns = listview->columns(); 133 int columns = listview->columns();
134 for ( counter = 0; counter <= columns; counter++ ) 134 for ( counter = 0; counter <= columns; counter++ )
135 if ( listview->header()->label ( counter ).length() == 0 ) 135 if ( listview->header()->label ( counter ).length() == 0 )
136 return counter; 136 return counter;
137 } 137 }
138 138
139void BudgetDisplay::newBudget () 139void BudgetDisplay::newBudget ()
140 { 140 {
141 constructBudgetWindow(); 141 constructBudgetWindow();
142 int response = nb->exec(); 142 int response = nb->exec();
143 if ( response == 1 ) 143 if ( response == 1 )
144 { 144 {
145 // open a new budget object 145 // open a new budget object
146 int addedbudget = budget->addBudget ( budgetname->text(), 0, description->text(), currencybox->currencybox->currentText(), day, month, year, day, month, year, 0 ); 146 int addedbudget = budget->addBudget ( budgetname->text(), 0, description->text(), currencybox->currencybox->currentText(), day, month, year, day, month, year, 0 );
147 transaction->clearBudgetIDs ( addedbudget ); 147 transaction->clearBudgetIDs ( addedbudget );
148 displayBudgetNames(); 148 displayBudgetNames();
149 } 149 }
150 checkBudgets(); 150 checkBudgets();
151 } 151 }
152 152
153void BudgetDisplay::constructBudgetWindow () 153void BudgetDisplay::constructBudgetWindow ()
154 { 154 {
155 //construct and format the new budget window 155 //construct and format the new budget window
156 nb = new QDialog ( this, 0, TRUE ); 156 nb = new QDialog ( this, 0, TRUE );
157 nb->setCaption ( "Budget" ); 157 nb->setCaption ( "Budget" );
158 QLabel *namelabel = new QLabel ( "Budget Name", nb ); 158 QLabel *namelabel = new QLabel ( "Budget Name", nb );
159 budgetname = new QLineEdit ( nb ); 159 budgetname = new QLineEdit ( nb );
160 QLabel *descriptionlabel = new QLabel ( "Description", nb ); 160 QLabel *descriptionlabel = new QLabel ( "Description", nb );
161 description = new QLineEdit ( nb ); 161 description = new QLineEdit ( nb );
162 currencybox = new Currency ( nb ); 162 currencybox = new Currency ( nb );
163 QBoxLayout *layout = new QVBoxLayout ( nb, 2, 2 ); 163 QBoxLayout *layout = new QVBoxLayout ( nb, 2, 2 );
164 layout->addWidget ( namelabel ); 164 layout->addWidget ( namelabel );
165 layout->addWidget ( budgetname ); 165 layout->addWidget ( budgetname );
166 layout->addWidget ( descriptionlabel ); 166 layout->addWidget ( descriptionlabel );
167 layout->addWidget ( description ); 167 layout->addWidget ( description );
168 layout->addWidget ( currencybox ); 168 layout->addWidget ( currencybox );
169 } 169 }
170 170
171void BudgetDisplay::displayBudgetNames () 171void BudgetDisplay::displayBudgetNames ()
172 { 172 {
173 budgetbox->clear(); 173 budgetbox->clear();
174 if ( budget->getNumberOfBudgets() != 0 ) 174 if ( budget->getNumberOfBudgets() != 0 )
175 { 175 {
176 ids = budget->getBudgetIDs(); 176 ids = budget->getBudgetIDs();
177 for ( QStringList::Iterator it = ids->begin(); it != ids->end(); ++it ) 177 for ( QStringList::Iterator it = ids->begin(); it != ids->end(); ++it )
178 { 178 {
179 QString flag = "/opt/QtPalmtop/pics/flags/"; 179 QString flag = "/opt/QtPalmtop/pics/flags/";
180 flag.append ( budget->getCurrency ( (*it).toInt() ) ); 180 flag.append ( budget->getCurrency ( (*it).toInt() ) );
181 flag.append ( ".png" ); 181 flag.append ( ".png" );
182 budgetbox->insertItem ( QPixmap ( flag ), budget->getBudgetName ( (*it).toInt() ) ); 182 budgetbox->insertItem ( QPixmap ( flag ), budget->getBudgetName ( (*it).toInt() ) );
183 } 183 }
184 setCurrentBudget ( 0 ); 184 setCurrentBudget ( 0 );
185 } 185 }
186 else 186 else
187 checkBudgets(); 187 checkBudgets();
188 } 188 }
189 189
190void BudgetDisplay::setCurrentBudget ( int index ) 190void BudgetDisplay::setCurrentBudget ( int index )
191 { 191 {
192 currentbudget = ( ids->operator[] ( index ).toInt() ); 192 currentbudget = ( ids->operator[] ( index ).toInt() );
193 displayLineItems(); 193 displayLineItems();
194 } 194 }
195 195
196void BudgetDisplay::setCurrentView ( int index ) 196void BudgetDisplay::setCurrentView ( int index )
197 { 197 {
198 displayLineItems(); 198 displayLineItems();
199 } 199 }
200 200
201void BudgetDisplay::showCalendar () 201void BudgetDisplay::showCalendar ()
202 { 202 {
203 // create new calendar object and show it 203 // create new calendar object and show it
204 DatePicker *dp = new DatePicker ( QDate ( year, month, day ) ); 204 DatePicker *dp = new DatePicker ( QDate ( year, month, day ) );
205 dp->daylabel->hide(); 205 dp->daylabel->hide();
206 dp->daybox->hide(); 206 dp->daybox->hide();
207 if ( budgetview->currentItem() == 1 ) 207 if ( budgetview->currentItem() == 1 )
208 { 208 {
209 dp->monthlabel->hide(); 209 dp->monthlabel->hide();
210 dp->monthbox->hide(); 210 dp->monthbox->hide();
211 } 211 }
212 dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); 212 dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) );
213 213
214 int response = dp->exec(); 214 int response = dp->exec();
215 if ( response == 1 ) 215 if ( response == 1 )
216 { 216 {
217 // Set date integers 217 // Set date integers
218 year = dp->getYear(); 218 year = dp->getYear();
219 if ( budgetview->currentItem() == 0 ) 219 if ( budgetview->currentItem() == 0 )
220 month = dp->getMonth(); 220 month = dp->getMonth();
221 else 221 else
222 month = newDate.month(); 222 month = newDate.month();
223 datelabel = preferences->getDate ( year, month ); 223 datelabel = preferences->getDate ( year, month );
224 displayLineItems(); 224 displayLineItems();
225 } 225 }
226 } 226 }
227 227
228void BudgetDisplay::newLineItem () 228void BudgetDisplay::newLineItem ()
229 { 229 {
230 //construct and format the new line item window 230 //construct and format the new line item window
231 constructLineItemWindow (); 231 constructLineItemWindow ();
232 232
233 int response = newlineitem->exec(); 233 int response = newlineitem->exec();
234 if ( response == 1 ) 234 if ( response == 1 )
235 { 235 {
236 float amount; 236 float amount;
237 if ( lineitemtime->currentItem() == 0 ) 237 if ( lineitemtime->currentItem() == 0 )
238 amount = lineitemamount->text().toFloat(); 238 amount = lineitemamount->text().toFloat();
239 else if ( lineitemtime->currentItem() == 1 ) 239 else if ( lineitemtime->currentItem() == 1 )
240 amount = lineitemamount->text().toFloat() * 12; 240 amount = lineitemamount->text().toFloat() * 12;
241 else 241 else
242 amount = lineitemamount->text().toFloat() * 52; 242 amount = lineitemamount->text().toFloat() * 52;
243 int lineitemadded = budget->addLineItem ( currentbudget, lineitemname->text(), amount, lineitemtime->currentItem() ); 243 int lineitemadded = budget->addLineItem ( currentbudget, lineitemname->text(), amount, lineitemtime->currentItem() );
244 transaction->clearBudgetIDs ( currentbudget, lineitemadded ); 244 transaction->clearBudgetIDs ( currentbudget, lineitemadded );
245 displayLineItems(); 245 displayLineItems();
246 } 246 }
247 checkBudgets(); 247 checkBudgets();
248 } 248 }
249 249
250void BudgetDisplay::constructLineItemWindow () 250void BudgetDisplay::constructLineItemWindow ()
251 { 251 {
252 //construct and format the new budget window 252 //construct and format the new budget window
253 newlineitem = new QDialog ( this, 0, TRUE ); 253 newlineitem = new QDialog ( this, 0, TRUE );
254 newlineitem->setCaption ( "Line Item" ); 254 newlineitem->setCaption ( "Line Item" );
255 QLabel *namelabel = new QLabel ( "Line Item Name", newlineitem ); 255 QLabel *namelabel = new QLabel ( "Line Item Name", newlineitem );
256 lineitemname = new QLineEdit ( newlineitem ); 256 lineitemname = new QLineEdit ( newlineitem );
257 QLabel *budgetamountlabel = new QLabel ( "Budget Amount", newlineitem ); 257 QLabel *budgetamountlabel = new QLabel ( "Budget Amount", newlineitem );
258 lineitemamount = new QLineEdit ( newlineitem ); 258 lineitemamount = new QLineEdit ( newlineitem );
259 QLabel *lineitemtimelabel = new QLabel ( "Per:", newlineitem ); 259 QLabel *lineitemtimelabel = new QLabel ( "Per:", newlineitem );
260 lineitemtime = new QComboBox ( newlineitem ); 260 lineitemtime = new QComboBox ( newlineitem );
261 lineitemtime->insertItem ( "Year" ); // type 0 261 lineitemtime->insertItem ( "Year" ); // type 0
262 lineitemtime->insertItem ( "Month" ); // type 1 262 lineitemtime->insertItem ( "Month" ); // type 1
263 lineitemtime->insertItem ( "Week" ); // type 2 263 lineitemtime->insertItem ( "Week" ); // type 2
264 QBoxLayout *layout = new QVBoxLayout ( newlineitem, 2, 2 ); 264 QBoxLayout *layout = new QVBoxLayout ( newlineitem, 2, 2 );
265 layout->addWidget ( namelabel ); 265 layout->addWidget ( namelabel );
266 layout->addWidget ( lineitemname ); 266 layout->addWidget ( lineitemname );
267 layout->addWidget ( budgetamountlabel ); 267 layout->addWidget ( budgetamountlabel );
268 layout->addWidget ( lineitemamount ); 268 layout->addWidget ( lineitemamount );
269 layout->addWidget ( lineitemtimelabel ); 269 layout->addWidget ( lineitemtimelabel );
270 layout->addWidget ( lineitemtime ); 270 layout->addWidget ( lineitemtime );
271 } 271 }
272 272
273void BudgetDisplay::deleteLineItem () 273void BudgetDisplay::deleteLineItem ()
274 { 274 {
275 if ( listview->selectedItem() != 0 ) 275 if ( listview->selectedItem() != 0 )
276 { 276 {
277 int lineitemid = listview->selectedItem()->text ( getIDColumn() ).toInt(); 277 int lineitemid = listview->selectedItem()->text ( getIDColumn() ).toInt();
278 transaction->clearBudgetIDs ( currentbudget, lineitemid ); 278 transaction->clearBudgetIDs ( currentbudget, lineitemid );
279 budget->deleteLineItem ( currentbudget, lineitemid ); 279 budget->deleteLineItem ( currentbudget, lineitemid );
280 displayBudgetNames(); 280 displayBudgetNames();
281 } 281 }
282 else 282 else
283 QMessageBox::warning ( this, "QashMoney", "Please select a line item to delete." ); 283 QMessageBox::warning ( this, "QashMoney", "Please select a line item to delete." );
284 checkBudgets(); 284 checkBudgets();
285 } 285 }
286 286
287void BudgetDisplay::displayLineItems () 287void BudgetDisplay::displayLineItems ()
288 { 288 {
289 listview->clear(); 289 listview->clear();
290 if ( budget->getNumberOfBudgets() != 0 ) 290 if ( budget->getNumberOfBudgets() != 0 )
291 { 291 {
292 QString budgettable = budgetbox->currentText(); 292 QString budgettable = budgetbox->currentText();
293 budgettable.append ( QString::number ( currentbudget ) ); 293 budgettable.append ( QString::number ( currentbudget ) );
294 budget->displayLineItems ( currentbudget, listview, month, year, budgetview->currentItem() ); 294 budget->displayLineItems ( currentbudget, listview, month, year, budgetview->currentItem() );
295 totalactual = transaction->getActualTotal ( currentbudget, year, month, budgetview->currentItem() ); 295 totalactual = transaction->getActualTotal ( currentbudget, year, month, budgetview->currentItem() );
296 totalbudget = budget->getBudgetTotal ( currentbudget, budgetview->currentItem() ); 296 totalbudget = budget->getBudgetTotal ( currentbudget, budgetview->currentItem() );
297 updateBudgetInformation(); 297 updateBudgetInformation();
298 } 298 }
299 } 299 }
300 300
301void BudgetDisplay::checkBudgets () 301void BudgetDisplay::checkBudgets ()
302 { 302 {
303 if ( budget->getNumberOfBudgets() == 0 ) 303 if ( budget->getNumberOfBudgets() == 0 )
304 { 304 {
305 budgetview->setEnabled ( FALSE ); 305 budgetview->setEnabled ( FALSE );
306 budgetmenu->setItemEnabled ( 2, FALSE ); 306 budgetmenu->setItemEnabled ( 2, FALSE );
307 budgetmenu->setItemEnabled ( 3, FALSE ); 307 budgetmenu->setItemEnabled ( 3, FALSE );
308 lineitemsmenu->setItemEnabled ( 1, FALSE ); 308 lineitemsmenu->setItemEnabled ( 1, FALSE );
309 lineitemsmenu->setItemEnabled ( 2, FALSE ); 309 lineitemsmenu->setItemEnabled ( 2, FALSE );
310 lineitemsmenu->setItemEnabled ( 3, FALSE ); 310 lineitemsmenu->setItemEnabled ( 3, FALSE );
311 } 311 }
312 else 312 else
313 { 313 {
314 budgetview->setEnabled ( TRUE ); 314 budgetview->setEnabled ( TRUE );
315 budgetmenu->setItemEnabled ( 2, TRUE ); 315 budgetmenu->setItemEnabled ( 2, TRUE );
316 budgetmenu->setItemEnabled ( 3, TRUE ); 316 budgetmenu->setItemEnabled ( 3, TRUE );
317 lineitemsmenu->setItemEnabled ( 1, TRUE ); 317 lineitemsmenu->setItemEnabled ( 1, TRUE );
318 lineitemsmenu->setItemEnabled ( 2, FALSE ); 318 lineitemsmenu->setItemEnabled ( 2, FALSE );
319 lineitemsmenu->setItemEnabled ( 3, FALSE ); 319 lineitemsmenu->setItemEnabled ( 3, FALSE );
320 320
321 if ( budget->getNumberOfLineItems ( currentbudget ) != 0 ) 321 if ( budget->getNumberOfLineItems ( currentbudget ) != 0 )
322 { 322 {
323 lineitemsmenu->setItemEnabled ( 2, TRUE ); 323 lineitemsmenu->setItemEnabled ( 2, TRUE );
324 lineitemsmenu->setItemEnabled ( 3, TRUE ); 324 lineitemsmenu->setItemEnabled ( 3, TRUE );
325 } 325 }
326 } 326 }
327 } 327 }
328 328
329void BudgetDisplay::updateBudgetInformation () 329void BudgetDisplay::updateBudgetInformation ()
330 { 330 {
331 if ( budgetview->currentItem() == 0 ) 331 if ( budgetview->currentItem() == 0 )
332 { 332 {
333 datelabel = preferences->getDate ( year, month ); 333 datelabel = preferences->getDate ( year, month );
334 datelabel.prepend ( "Date: " ); 334 datelabel.prepend ( "Date: " );
335 date->setText ( datelabel ); 335 date->setText ( datelabel );
336 } 336 }
337 else 337 else
338 date->setText ( QString::number ( year ) ); 338 date->setText ( QString::number ( year ) );
339 339
340 QString budget = "Budget: "; 340 QString budget = "Budget: ";
341 budget.append ( totalbudget ); 341 budget.append ( totalbudget );
342 budgeted->setText ( budget ); 342 budgeted->setText ( budget );
343 343
344 QString actualamount = "Actual: "; 344 QString actualamount = "Actual: ";
345 actualamount.append ( totalactual ); 345 actualamount.append ( totalactual );
346 actual->setText ( actualamount ); 346 actual->setText ( actualamount );
347 } 347 }
348 348
349void BudgetDisplay::editBudget () 349void BudgetDisplay::editBudget ()
350 { 350 {
351 constructBudgetWindow(); 351 constructBudgetWindow();
352 352
353 //set the title 353 //set the title
354 budgetname->setText ( budget->getBudgetName ( currentbudget ) ); 354 budgetname->setText ( budget->getBudgetName ( currentbudget ) );
355 //set the description 355 //set the description
356 description->setText ( budget->getBudgetDescription ( currentbudget ) ); 356 description->setText ( budget->getBudgetDescription ( currentbudget ) );
357 // retrieve the two character currency code then 357 // retrieve the two character currency code then
358 // go through the currencty box and find the code 358 // go through the currencty box and find the code
359 //set the currency box to that index number 359 //set the currency box to that index number
360 int count = currencybox->currencybox->count(); 360 int count = currencybox->currencybox->count();
361 QString code = budget->getCurrency ( currentbudget ); 361 QString code = budget->getCurrency ( currentbudget );
362 for ( int counter = 0; count - 1; counter++ ) 362 for ( int counter = 0; count - 1; counter++ )
363 { 363 {
364 if ( QString::compare (currencybox->currencybox->text ( counter ), code ) == 0 ) 364 if ( QString::compare (currencybox->currencybox->text ( counter ), code ) == 0 )
365 { 365 {
366 currencybox->currencybox->setCurrentItem ( counter ); 366 currencybox->currencybox->setCurrentItem ( counter );
367 break; 367 break;
368 } 368 }
369 } 369 }
370 int response = nb->exec(); 370 int response = nb->exec();
371 if ( response == 1 ) 371 if ( response == 1 )
372 { 372 {
373 budget->updateBudget ( budgetname->text(), description->text(), currencybox->currencybox->currentText(), currentbudget ); 373 budget->updateBudget ( budgetname->text(), description->text(), currencybox->currencybox->currentText(), currentbudget );
374 displayBudgetNames(); 374 displayBudgetNames();
375 } 375 }
376 } 376 }
377 377
378void BudgetDisplay::editLineItem () 378void BudgetDisplay::editLineItem ()
379 { 379 {
380 if ( listview->selectedItem() != 0 ) 380 if ( listview->selectedItem() != 0 )
381 { 381 {
382 constructLineItemWindow(); 382 constructLineItemWindow();
383 383
384 // set the line item name 384 // set the line item name
385 lineitemname->setText ( listview->selectedItem()->text( 0 ) ); 385 lineitemname->setText ( listview->selectedItem()->text( 0 ) );
386 386
387 // set the line item time combobox 387 // set the line item time combobox
388 int lineitemtype = budget->getLineItemTime ( currentbudget, listview->selectedItem()->text ( 3 ).toInt() ); 388 int lineitemtype = budget->getLineItemTime ( currentbudget, listview->selectedItem()->text ( 3 ).toInt() );
389 lineitemtime->setCurrentItem ( lineitemtype ); 389 lineitemtime->setCurrentItem ( lineitemtype );
390 390
391 // set the line item amount 391 // set the line item amount
392 float amount = budget->getLineItemAmount ( currentbudget, listview->selectedItem()->text ( 3 ).toInt() ); 392 float amount = budget->getLineItemAmount ( currentbudget, listview->selectedItem()->text ( 3 ).toInt() );
393 if ( lineitemtype == 1 ) 393 if ( lineitemtype == 1 )
394 amount = amount / 12; 394 amount = amount / 12;
395 else if ( lineitemtype == 2 ) 395 else if ( lineitemtype == 2 )
396 amount = amount / 52; 396 amount = amount / 52;
397 lineitemamount->setText ( QString::number ( amount ) ); 397 lineitemamount->setText ( QString::number ( amount ) );
398 398
399 int response = newlineitem->exec(); 399 int response = newlineitem->exec();
400 if ( response == 1 ) 400 if ( response == 1 )
401 { 401 {
402 float amount; 402 float amount;
403 if ( lineitemtime->currentItem() == 0 ) 403 if ( lineitemtime->currentItem() == 0 )
404 amount = lineitemamount->text().toFloat(); 404 amount = lineitemamount->text().toFloat();
405 else if ( lineitemtime->currentItem() == 1 ) 405 else if ( lineitemtime->currentItem() == 1 )
406 amount = lineitemamount->text().toFloat() * 12; 406 amount = lineitemamount->text().toFloat() * 12;
407 else 407 else
408 amount = lineitemamount->text().toFloat() * 52; 408 amount = lineitemamount->text().toFloat() * 52;
409 budget->updateLineItem ( lineitemname->text(), amount, lineitemtime->currentItem(), currentbudget, listview->selectedItem()->text ( 3 ).toInt() ); 409 budget->updateLineItem ( lineitemname->text(), amount, lineitemtime->currentItem(), currentbudget, listview->selectedItem()->text ( 3 ).toInt() );
410 displayLineItems(); 410 displayLineItems();
411 } 411 }
412 } 412 }
413 else 413 else
414 QMessageBox::warning ( this, "QashMoney", "Please select a line item to edit." ); 414 QMessageBox::warning ( this, "QashMoney", "Please select a line item to edit." );
415 } 415 }
416 416
417 417
diff --git a/noncore/apps/qashmoney/calculator.cpp b/noncore/apps/qashmoney/calculator.cpp
index 0e0a043..2c92103 100755
--- a/noncore/apps/qashmoney/calculator.cpp
+++ b/noncore/apps/qashmoney/calculator.cpp
@@ -1,113 +1,113 @@
1#include "calculator.h" 1#include "calculator.h"
2 2
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4 4
5Calculator::Calculator ( QWidget* parent ) : QDialog ( parent, 0, TRUE ) 5Calculator::Calculator ( QWidget* parent ) : QDialog ( parent, 0, TRUE )
6 { 6 {
7 7
8 display = new QLineEdit ( this, "display" ); 8 display = new QLineEdit ( this, "display" );
9 display->setFrame ( FALSE ); 9 display->setFrame ( FALSE );
10 display->setAlignment ( Qt::AlignRight ); 10 display->setAlignment ( Qt::AlignRight );
11 11
12 QPushButton *one = new QPushButton ( "1", this, "one" ); // make buttons for first row 12 QPushButton *one = new QPushButton ( "1", this, "one" ); // make buttons for first row
13 one->setFlat ( TRUE ); 13 one->setFlat ( TRUE );
14 connect ( one, SIGNAL ( released () ), this, SLOT ( displayOne () ) ); 14 connect ( one, SIGNAL ( released() ), this, SLOT ( displayOne() ) );
15 15
16 QPushButton *two = new QPushButton ( "2", this, "two" ); 16 QPushButton *two = new QPushButton ( "2", this, "two" );
17 two->setFlat ( TRUE ); 17 two->setFlat ( TRUE );
18 connect ( two, SIGNAL ( released () ), this, SLOT ( displayTwo () ) ); 18 connect ( two, SIGNAL ( released() ), this, SLOT ( displayTwo() ) );
19 19
20 QPushButton *three = new QPushButton ( "3", this, "three" ); 20 QPushButton *three = new QPushButton ( "3", this, "three" );
21 three->setFlat ( TRUE ); 21 three->setFlat ( TRUE );
22 connect ( three, SIGNAL ( released () ), this, SLOT ( displayThree () ) ); 22 connect ( three, SIGNAL ( released() ), this, SLOT ( displayThree() ) );
23 23
24 QPushButton *four = new QPushButton ( "4", this, "four" ); // make buttons for second row 24 QPushButton *four = new QPushButton ( "4", this, "four" ); // make buttons for second row
25 four->setFlat ( TRUE ); 25 four->setFlat ( TRUE );
26 connect ( four, SIGNAL ( released () ), this, SLOT ( displayFour () ) ); 26 connect ( four, SIGNAL ( released() ), this, SLOT ( displayFour() ) );
27 27
28 QPushButton *five = new QPushButton ( "5", this, "five" ); 28 QPushButton *five = new QPushButton ( "5", this, "five" );
29 five->setFlat ( TRUE ); 29 five->setFlat ( TRUE );
30 connect ( five, SIGNAL ( released () ), this, SLOT ( displayFive () ) ); 30 connect ( five, SIGNAL ( released() ), this, SLOT ( displayFive() ) );
31 31
32 QPushButton *six = new QPushButton ( "6", this, "six" ); 32 QPushButton *six = new QPushButton ( "6", this, "six" );
33 six->setFlat ( TRUE ); 33 six->setFlat ( TRUE );
34 connect ( six, SIGNAL ( released () ), this, SLOT ( displaySix () ) ); 34 connect ( six, SIGNAL ( released() ), this, SLOT ( displaySix() ) );
35 35
36 QPushButton *seven = new QPushButton ( "7", this, "seven" ); // make buttons for third row 36 QPushButton *seven = new QPushButton ( "7", this, "seven" ); // make buttons for third row
37 seven->setFlat ( TRUE ); 37 seven->setFlat ( TRUE );
38 connect ( seven, SIGNAL ( released () ), this, SLOT ( displaySeven () ) ); 38 connect ( seven, SIGNAL ( released() ), this, SLOT ( displaySeven() ) );
39 39
40 QPushButton *eight = new QPushButton ( "8", this, "eight" ); 40 QPushButton *eight = new QPushButton ( "8", this, "eight" );
41 eight->setFlat ( TRUE ); 41 eight->setFlat ( TRUE );
42 connect ( eight, SIGNAL ( released () ), this, SLOT ( displayEight () ) ); 42 connect ( eight, SIGNAL ( released() ), this, SLOT ( displayEight() ) );
43 43
44 QPushButton *nine = new QPushButton ( "9", this, "nine" ); 44 QPushButton *nine = new QPushButton ( "9", this, "nine" );
45 nine->setFlat ( TRUE ); 45 nine->setFlat ( TRUE );
46 connect ( nine, SIGNAL ( released () ), this, SLOT ( displayNine () ) ); 46 connect ( nine, SIGNAL ( released() ), this, SLOT ( displayNine() ) );
47 47
48 QPushButton *zero = new QPushButton ( "0", this, "zero" ); 48 QPushButton *zero = new QPushButton ( "0", this, "zero" );
49 zero->setFlat ( TRUE ); 49 zero->setFlat ( TRUE );
50 connect ( zero, SIGNAL ( released () ), this, SLOT ( displayZero () ) ); 50 connect ( zero, SIGNAL ( released() ), this, SLOT ( displayZero() ) );
51 51
52 QPushButton *dp = new QPushButton ( ".", this, "dp" ); 52 QPushButton *dp = new QPushButton ( ".", this, "dp" );
53 dp->setFlat ( TRUE ); 53 dp->setFlat ( TRUE );
54 connect ( dp, SIGNAL ( released () ), this, SLOT ( displayPoint () ) ); 54 connect ( dp, SIGNAL ( released() ), this, SLOT ( displayPoint() ) );
55 55
56 QPushButton *back = new QPushButton ( "<-", this, "back" ); 56 QPushButton *back = new QPushButton ( "<-", this, "back" );
57 back->setFlat ( TRUE ); 57 back->setFlat ( TRUE );
58 connect ( back, SIGNAL ( released () ), this, SLOT ( back () ) ); 58 connect ( back, SIGNAL ( released() ), this, SLOT ( back() ) );
59 59
60 layout = new QGridLayout ( this, 5, 3, 5, 1, "calculatorlayout" ); 60 layout = new QGridLayout ( this, 5, 3, 5, 1, "calculatorlayout" );
61 layout->addMultiCellWidget ( display, 0, 0, 0, 2 ); 61 layout->addMultiCellWidget ( display, 0, 0, 0, 2 );
62 layout->addWidget ( one, 1, 0 ); 62 layout->addWidget ( one, 1, 0 );
63 layout->addWidget ( two, 1, 1 ); 63 layout->addWidget ( two, 1, 1 );
64 layout->addWidget ( three, 1, 2 ); 64 layout->addWidget ( three, 1, 2 );
65 layout->addWidget ( four, 2, 0 ); 65 layout->addWidget ( four, 2, 0 );
66 layout->addWidget ( five, 2, 1 ); 66 layout->addWidget ( five, 2, 1 );
67 layout->addWidget ( six, 2, 2 ); 67 layout->addWidget ( six, 2, 2 );
68 layout->addWidget ( seven, 3, 0 ); 68 layout->addWidget ( seven, 3, 0 );
69 layout->addWidget ( eight, 3, 1 ); 69 layout->addWidget ( eight, 3, 1 );
70 layout->addWidget ( nine, 3, 2 ); 70 layout->addWidget ( nine, 3, 2 );
71 layout->addWidget ( zero, 4, 0 ); 71 layout->addWidget ( zero, 4, 0 );
72 layout->addWidget ( dp, 4, 1 ); 72 layout->addWidget ( dp, 4, 1 );
73 layout->addWidget ( back, 4, 2 ); 73 layout->addWidget ( back, 4, 2 );
74 74
75 } 75 }
76 76
77void Calculator::displayOne () 77void Calculator::displayOne ()
78 { display->insert ( "1" ); } 78 { display->insert ( "1" ); }
79 79
80void Calculator::displayTwo () 80void Calculator::displayTwo ()
81 { display->insert ( "2" ); } 81 { display->insert ( "2" ); }
82 82
83void Calculator::displayThree () 83void Calculator::displayThree ()
84 { display->insert ( "3" ); } 84 { display->insert ( "3" ); }
85 85
86void Calculator::displayFour () 86void Calculator::displayFour ()
87 { display->insert ( "4" ); } 87 { display->insert ( "4" ); }
88 88
89void Calculator::displayFive () 89void Calculator::displayFive ()
90 { display->insert ( "5" ); } 90 { display->insert ( "5" ); }
91 91
92void Calculator::displaySix () 92void Calculator::displaySix ()
93 { display->insert ( "6" ); } 93 { display->insert ( "6" ); }
94 94
95void Calculator::displaySeven () 95void Calculator::displaySeven ()
96 { display->insert ( "7" ); } 96 { display->insert ( "7" ); }
97 97
98void Calculator::displayEight () 98void Calculator::displayEight ()
99 { display->insert ( "8" ); } 99 { display->insert ( "8" ); }
100 100
101void Calculator::displayNine () 101void Calculator::displayNine ()
102 { display->insert ( "9" ); } 102 { display->insert ( "9" ); }
103 103
104void Calculator::displayZero () 104void Calculator::displayZero ()
105 { display->insert ( "0" ); } 105 { display->insert ( "0" ); }
106 106
107void Calculator::displayPoint () 107void Calculator::displayPoint ()
108 { display->insert ( "." ); } 108 { display->insert ( "." ); }
109 109
110void Calculator::back () 110void Calculator::back ()
111 { display->backspace(); } 111 { display->backspace(); }
112 112
113 113
diff --git a/noncore/apps/qashmoney/datepicker.cpp b/noncore/apps/qashmoney/datepicker.cpp
index 02fbcf3..7997c0b 100755
--- a/noncore/apps/qashmoney/datepicker.cpp
+++ b/noncore/apps/qashmoney/datepicker.cpp
@@ -1,95 +1,95 @@
1#include "datepicker.h" 1#include "datepicker.h"
2 2
3DatePicker::DatePicker ( QDate entrydate ) : QDialog ( 0, 0, TRUE ) 3DatePicker::DatePicker ( QDate entrydate ) : QDialog ( 0, 0, TRUE )
4 { 4 {
5 setCaption ( "Select Date" ); 5 setCaption ( "Select Date" );
6 date = entrydate; 6 date = entrydate;
7 day = date.day(); 7 day = date.day();
8 month = date.month(); 8 month = date.month();
9 year = date.year(); 9 year = date.year();
10 10
11 daylabel = new QLabel ( "Day", this ); 11 daylabel = new QLabel ( "Day", this );
12 monthlabel = new QLabel ( "Month", this ); 12 monthlabel = new QLabel ( "Month", this );
13 yearlabel = new QLabel ( "Year", this ); 13 yearlabel = new QLabel ( "Year", this );
14 14
15 daybox = new QComboBox ( this, "daybox" ); 15 daybox = new QComboBox ( this, "daybox" );
16 connect ( daybox, SIGNAL ( activated ( int ) ), this, SLOT ( setDay ( int ) ) ); 16 connect ( daybox, SIGNAL ( activated(int) ), this, SLOT ( setDay(int) ) );
17 displayDays ( daybox ); 17 displayDays ( daybox );
18 monthbox = new QComboBox ( this, "monthbox" ); 18 monthbox = new QComboBox ( this, "monthbox" );
19 connect ( monthbox, SIGNAL ( activated ( int ) ), this, SLOT ( setMonth ( int ) ) ); 19 connect ( monthbox, SIGNAL ( activated(int) ), this, SLOT ( setMonth(int) ) );
20 displayMonths ( monthbox ); 20 displayMonths ( monthbox );
21 yearbox = new QComboBox ( this, "yearbox" ); 21 yearbox = new QComboBox ( this, "yearbox" );
22 connect ( yearbox, SIGNAL ( activated ( int ) ), this, SLOT ( setYear ( int ) ) ); 22 connect ( yearbox, SIGNAL ( activated(int) ), this, SLOT ( setYear(int) ) );
23 displayYears ( yearbox ); 23 displayYears ( yearbox );
24 24
25 layout = new QGridLayout ( this, 2, 3, 5, 5, "datepickerlayout" ); 25 layout = new QGridLayout ( this, 2, 3, 5, 5, "datepickerlayout" );
26 layout->addWidget ( daylabel, 0, 2 ); 26 layout->addWidget ( daylabel, 0, 2 );
27 layout->addWidget ( monthlabel, 0, 1 ); 27 layout->addWidget ( monthlabel, 0, 1 );
28 layout->addWidget ( yearlabel, 0, 0 ); 28 layout->addWidget ( yearlabel, 0, 0 );
29 layout->addWidget ( daybox, 1, 2 ); 29 layout->addWidget ( daybox, 1, 2 );
30 layout->addWidget ( monthbox, 1, 1 ); 30 layout->addWidget ( monthbox, 1, 1 );
31 layout->addWidget ( yearbox, 1, 0 ); 31 layout->addWidget ( yearbox, 1, 0 );
32 } 32 }
33 33
34void DatePicker::displayDays ( QComboBox *daybox ) 34void DatePicker::displayDays ( QComboBox *daybox )
35 { 35 {
36 int counter; 36 int counter;
37 int days = date.daysInMonth(); 37 int days = date.daysInMonth();
38 for ( counter = 1; counter <= days; counter++ ) 38 for ( counter = 1; counter <= days; counter++ )
39 daybox->insertItem ( QString::number ( counter ) ); 39 daybox->insertItem ( QString::number ( counter ) );
40 daybox->setCurrentItem ( ( date.day() ) - 1 ); 40 daybox->setCurrentItem ( ( date.day() ) - 1 );
41 } 41 }
42 42
43void DatePicker::displayMonths ( QComboBox *monthbox ) 43void DatePicker::displayMonths ( QComboBox *monthbox )
44 { 44 {
45 int counter; 45 int counter;
46 for ( counter = 1; counter <= 12; counter++ ) 46 for ( counter = 1; counter <= 12; counter++ )
47 monthbox->insertItem ( QString::number ( counter ) ); 47 monthbox->insertItem ( QString::number ( counter ) );
48 monthbox->setCurrentItem ( ( date.month() ) - 1 ); 48 monthbox->setCurrentItem ( ( date.month() ) - 1 );
49 } 49 }
50 50
51void DatePicker::displayYears ( QComboBox *yearbox ) 51void DatePicker::displayYears ( QComboBox *yearbox )
52 { 52 {
53 int counter; 53 int counter;
54 int indexcounter = 0; 54 int indexcounter = 0;
55 int yearindex = 0; 55 int yearindex = 0;
56 int year = date.year(); 56 int year = date.year();
57 for ( counter = ( year - 1 ); counter <= ( year + 1 ); counter++ ) 57 for ( counter = ( year - 1 ); counter <= ( year + 1 ); counter++ )
58 { 58 {
59 yearbox->insertItem ( QString::number ( counter ) ); 59 yearbox->insertItem ( QString::number ( counter ) );
60 if ( date.year() == counter ) 60 if ( date.year() == counter )
61 yearindex = indexcounter; 61 yearindex = indexcounter;
62 indexcounter ++; 62 indexcounter ++;
63 } 63 }
64 yearbox->setCurrentItem ( yearindex ); 64 yearbox->setCurrentItem ( yearindex );
65 } 65 }
66 66
67void DatePicker::setDay ( int index ) 67void DatePicker::setDay ( int index )
68 { 68 {
69 day = daybox->text ( index ).toInt(); 69 day = daybox->text ( index ).toInt();
70 } 70 }
71 71
72void DatePicker::setMonth ( int index ) 72void DatePicker::setMonth ( int index )
73 { 73 {
74 month = monthbox->text( index ).toInt(); 74 month = monthbox->text( index ).toInt();
75 } 75 }
76 76
77void DatePicker::setYear ( int index ) 77void DatePicker::setYear ( int index )
78 { 78 {
79 year = yearbox->text ( index ).toInt(); 79 year = yearbox->text ( index ).toInt();
80 } 80 }
81 81
82int DatePicker::getDay () 82int DatePicker::getDay ()
83 { return day; } 83 { return day; }
84 84
85int DatePicker::getMonth () 85int DatePicker::getMonth ()
86 { return month; } 86 { return month; }
87 87
88int DatePicker::getYear () 88int DatePicker::getYear ()
89 { return year; } 89 { return year; }
90 90
91 91
92 92
93 93
94 94
95 95
diff --git a/noncore/apps/qashmoney/memorydialog.cpp b/noncore/apps/qashmoney/memorydialog.cpp
index e9ebd54..ba11540 100755
--- a/noncore/apps/qashmoney/memorydialog.cpp
+++ b/noncore/apps/qashmoney/memorydialog.cpp
@@ -1,86 +1,86 @@
1#include "memorydialog.h" 1#include "memorydialog.h"
2#include "memory.h" 2#include "memory.h"
3#include <qmessagebox.h> 3#include <qmessagebox.h>
4 4
5extern Memory *memory; 5extern Memory *memory;
6 6
7MemoryDialog::MemoryDialog () : QDialog ( 0, 0, TRUE ) 7MemoryDialog::MemoryDialog () : QDialog ( 0, 0, TRUE )
8{ 8{
9 setCaption ( tr ( "Edit Memory" ) ); 9 setCaption ( tr ( "Edit Memory" ) );
10 10
11 listbox = new QListBox ( this, "listbox" ); 11 listbox = new QListBox ( this, "listbox" );
12 memory->displayMemoryItems ( listbox ); 12 memory->displayMemoryItems ( listbox );
13 listbox->clearSelection(); 13 listbox->clearSelection();
14 14
15 secondline = new QHBox ( this ); 15 secondline = new QHBox ( this );
16 16
17 newbutton = new QPushButton ( secondline ); 17 newbutton = new QPushButton ( secondline );
18 newbutton->setPixmap( QPixmap ("/opt/QtPalmtop/pics/new.png") ); 18 newbutton->setPixmap( QPixmap ("/opt/QtPalmtop/pics/new.png") );
19 connect ( newbutton, SIGNAL ( released () ), this, SLOT ( addItem () ) ); 19 connect ( newbutton, SIGNAL ( released() ), this, SLOT ( addItem() ) );
20 20
21 editbutton = new QPushButton ( secondline ); 21 editbutton = new QPushButton ( secondline );
22 editbutton->setPixmap( QPixmap ("/opt/QtPalmtop/pics/edit.png") ); 22 editbutton->setPixmap( QPixmap ("/opt/QtPalmtop/pics/edit.png") );
23 connect ( editbutton, SIGNAL ( released () ), this, SLOT ( editItem () ) ); 23 connect ( editbutton, SIGNAL ( released() ), this, SLOT ( editItem() ) );
24 24
25 deletebutton = new QPushButton( secondline ); 25 deletebutton = new QPushButton( secondline );
26 deletebutton->setPixmap( QPixmap ("/opt/QtPalmtop/pics/delete.png") ); 26 deletebutton->setPixmap( QPixmap ("/opt/QtPalmtop/pics/delete.png") );
27 connect ( deletebutton, SIGNAL ( released () ), this, SLOT ( deleteItem () ) ); 27 connect ( deletebutton, SIGNAL ( released() ), this, SLOT ( deleteItem() ) );
28 28
29 lineedit = new QLineEdit ( this ); 29 lineedit = new QLineEdit ( this );
30 30
31 layout = new QVBoxLayout ( this, 2, 2 ); 31 layout = new QVBoxLayout ( this, 2, 2 );
32 layout->addWidget ( listbox ); 32 layout->addWidget ( listbox );
33 layout->addWidget ( secondline ); 33 layout->addWidget ( secondline );
34 layout->addWidget ( lineedit ); 34 layout->addWidget ( lineedit );
35} 35}
36 36
37MemoryDialog::~MemoryDialog() 37MemoryDialog::~MemoryDialog()
38 { 38 {
39 } 39 }
40 40
41void MemoryDialog::addItem () 41void MemoryDialog::addItem ()
42 { 42 {
43 if ( lineedit->text().length() != 0 ) 43 if ( lineedit->text().length() != 0 )
44 { 44 {
45 memory->addMemoryItem ( lineedit->text() ); 45 memory->addMemoryItem ( lineedit->text() );
46 listbox->clear (); 46 listbox->clear ();
47 memory->displayMemoryItems ( listbox ); 47 memory->displayMemoryItems ( listbox );
48 listbox->clearFocus(); 48 listbox->clearFocus();
49 listbox->clearSelection (); 49 listbox->clearSelection ();
50 lineedit->clear(); 50 lineedit->clear();
51 } 51 }
52 } 52 }
53 53
54void MemoryDialog::editItem () 54void MemoryDialog::editItem ()
55 { 55 {
56 if ( listbox->currentItem() != -1 ) 56 if ( listbox->currentItem() != -1 )
57 { 57 {
58 lineedit->setText ( listbox->currentText() ); 58 lineedit->setText ( listbox->currentText() );
59 memory->deleteMemoryItem ( listbox->currentText() ); 59 memory->deleteMemoryItem ( listbox->currentText() );
60 listbox->clear (); 60 listbox->clear ();
61 memory->displayMemoryItems ( listbox ); 61 memory->displayMemoryItems ( listbox );
62 listbox->clearSelection(); 62 listbox->clearSelection();
63 } 63 }
64 else 64 else
65 QMessageBox::warning ( this, "QashMoney", "Please select an item to edit." ); 65 QMessageBox::warning ( this, "QashMoney", "Please select an item to edit." );
66 } 66 }
67 67
68void MemoryDialog::deleteItem () 68void MemoryDialog::deleteItem ()
69 { 69 {
70 if ( listbox->currentItem() != -1 ) 70 if ( listbox->currentItem() != -1 )
71 { 71 {
72 memory->deleteMemoryItem ( listbox->currentText() ); 72 memory->deleteMemoryItem ( listbox->currentText() );
73 listbox->clear (); 73 listbox->clear ();
74 memory->displayMemoryItems ( listbox ); 74 memory->displayMemoryItems ( listbox );
75 listbox->clearSelection(); 75 listbox->clearSelection();
76 } 76 }
77 else 77 else
78 QMessageBox::warning ( this, "QashMoney", "Please select an item to delete." ); 78 QMessageBox::warning ( this, "QashMoney", "Please select an item to delete." );
79 } 79 }
80 80
81 81
82 82
83 83
84 84
85 85
86 86
diff --git a/noncore/apps/qashmoney/newaccount.cpp b/noncore/apps/qashmoney/newaccount.cpp
index 7e57a18..5932182 100755
--- a/noncore/apps/qashmoney/newaccount.cpp
+++ b/noncore/apps/qashmoney/newaccount.cpp
@@ -1,206 +1,206 @@
1#include "newaccount.h" 1#include "newaccount.h"
2#include "calculator.h" 2#include "calculator.h"
3#include "datepicker.h" 3#include "datepicker.h"
4#include <qmultilineedit.h> 4#include <qmultilineedit.h>
5 5
6extern Preferences *preferences; 6extern Preferences *preferences;
7 7
8NewAccount::NewAccount ( QWidget *parent, const char *name, bool modal ) : QDialog ( parent, name, modal ) 8NewAccount::NewAccount ( QWidget *parent, const char *name, bool modal ) : QDialog ( parent, name, modal )
9 { 9 {
10 accountdescription = ""; 10 accountdescription = "";
11 dateedited = FALSE; 11 dateedited = FALSE;
12 setCaption( tr( "Account" ) ); 12 setCaption( tr( "Account" ) );
13 13
14 namelabel = new QLabel ( "Account Name", this ); 14 namelabel = new QLabel ( "Account Name", this );
15 15
16 accountbox = new QHBox ( this ); 16 accountbox = new QHBox ( this );
17 accountname = new QLineEdit ( accountbox ); 17 accountname = new QLineEdit ( accountbox );
18 descriptionbutton = new QPushButton ( accountbox ); 18 descriptionbutton = new QPushButton ( accountbox );
19 descriptionbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/info.png" ) ); 19 descriptionbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/info.png" ) );
20 20
21 datelabel = new QLabel ( "Date", this ); 21 datelabel = new QLabel ( "Date", this );
22 22
23 datebox = new QHBox ( this ); 23 datebox = new QHBox ( this );
24 startdate = new QLineEdit ( datebox ); 24 startdate = new QLineEdit ( datebox );
25 startdate->setDisabled ( TRUE ); 25 startdate->setDisabled ( TRUE );
26 datebutton = new QPushButton ( datebox ); 26 datebutton = new QPushButton ( datebox );
27 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) ); 27 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) );
28 28
29 childcheckbox = new QCheckBox ( this ); 29 childcheckbox = new QCheckBox ( this );
30 childcheckbox->setText( tr ( "Child Account" ) ); 30 childcheckbox->setText( tr ( "Child Account" ) );
31 31
32 childlabel = new QLabel ( "Child of", this ); 32 childlabel = new QLabel ( "Child of", this );
33 childbox = new QComboBox ( FALSE, this ); 33 childbox = new QComboBox ( FALSE, this );
34 hideChildPulldownMenu (); 34 hideChildPulldownMenu ();
35 35
36 balancelabel = new QLabel ( "Balance", this ); 36 balancelabel = new QLabel ( "Balance", this );
37 37
38 balancebox = new QHBox ( this ); 38 balancebox = new QHBox ( this );
39 accountbalance = new QLineEdit ( balancebox ); 39 accountbalance = new QLineEdit ( balancebox );
40 accountbalance->setText ( "0.00" ); 40 accountbalance->setText ( "0.00" );
41 balancecalculator = new QPushButton( balancebox ); 41 balancecalculator = new QPushButton( balancebox );
42 balancecalculator->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) ); 42 balancecalculator->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) );
43 43
44 creditlimitlabel = new QLabel ( "Credit Limit", this ); 44 creditlimitlabel = new QLabel ( "Credit Limit", this );
45 45
46 creditlimitbox = new QHBox ( this ); 46 creditlimitbox = new QHBox ( this );
47 creditlimit = new QLineEdit ( creditlimitbox ); 47 creditlimit = new QLineEdit ( creditlimitbox );
48 creditlimitbox->setEnabled ( FALSE ); 48 creditlimitbox->setEnabled ( FALSE );
49 creditlimitcalculator = new QPushButton( creditlimitbox ); 49 creditlimitcalculator = new QPushButton( creditlimitbox );
50 creditlimitcalculator->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) ); 50 creditlimitcalculator->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) );
51 51
52 currencybox = new Currency ( this ); 52 currencybox = new Currency ( this );
53 53
54 typelabel = new QLabel ( "Type", this ); 54 typelabel = new QLabel ( "Type", this );
55 accounttype = new QComboBox ( FALSE, this ); 55 accounttype = new QComboBox ( FALSE, this );
56 accounttype->insertItem( tr( "Bank" ) ); 56 accounttype->insertItem( tr( "Bank" ) );
57 accounttype->insertItem( tr( "Cash" ) ); 57 accounttype->insertItem( tr( "Cash" ) );
58 accounttype->insertItem( tr( "Credit Card" ) ); 58 accounttype->insertItem( tr( "Credit Card" ) );
59 accounttype->insertItem( tr( "Equity" ) ); 59 accounttype->insertItem( tr( "Equity" ) );
60 accounttype->insertItem( tr( "Asset" ) ); 60 accounttype->insertItem( tr( "Asset" ) );
61 accounttype->insertItem( tr( "Liability" ) ); 61 accounttype->insertItem( tr( "Liability" ) );
62 62
63 layout = new QGridLayout ( this, 7, 2, 4, 2 ); 63 layout = new QGridLayout ( this, 7, 2, 4, 2 );
64 layout->addWidget ( namelabel , 0, 0, Qt::AlignLeft ); 64 layout->addWidget ( namelabel , 0, 0, Qt::AlignLeft );
65 layout->addWidget ( accountbox, 1, 0, Qt::AlignLeft ); 65 layout->addWidget ( accountbox, 1, 0, Qt::AlignLeft );
66 layout->addWidget ( datelabel, 2, 0, Qt::AlignLeft ); 66 layout->addWidget ( datelabel, 2, 0, Qt::AlignLeft );
67 layout->addWidget ( datebox, 3, 0, Qt::AlignLeft ); 67 layout->addWidget ( datebox, 3, 0, Qt::AlignLeft );
68 layout->addWidget ( childcheckbox, 4, 0, Qt::AlignLeft ); 68 layout->addWidget ( childcheckbox, 4, 0, Qt::AlignLeft );
69 layout->addWidget ( childlabel, 5, 0, Qt::AlignLeft ); 69 layout->addWidget ( childlabel, 5, 0, Qt::AlignLeft );
70 layout->addWidget ( childbox, 6, 0, Qt::AlignLeft ); 70 layout->addWidget ( childbox, 6, 0, Qt::AlignLeft );
71 layout->addWidget ( balancelabel, 0, 1, Qt::AlignLeft ); 71 layout->addWidget ( balancelabel, 0, 1, Qt::AlignLeft );
72 layout->addWidget ( balancebox, 1, 1, Qt::AlignLeft ); 72 layout->addWidget ( balancebox, 1, 1, Qt::AlignLeft );
73 layout->addWidget ( creditlimitlabel, 2, 1, Qt::AlignLeft ); 73 layout->addWidget ( creditlimitlabel, 2, 1, Qt::AlignLeft );
74 layout->addWidget ( creditlimitbox, 3, 1, Qt::AlignLeft ); 74 layout->addWidget ( creditlimitbox, 3, 1, Qt::AlignLeft );
75 layout->addWidget ( currencybox, 4, 1, Qt::AlignLeft ); 75 layout->addWidget ( currencybox, 4, 1, Qt::AlignLeft );
76 layout->addWidget ( typelabel, 5, 1, Qt::AlignLeft ); 76 layout->addWidget ( typelabel, 5, 1, Qt::AlignLeft );
77 layout->addWidget ( accounttype, 6, 1, Qt::AlignLeft ); 77 layout->addWidget ( accounttype, 6, 1, Qt::AlignLeft );
78 78
79 connect ( childcheckbox, SIGNAL ( clicked () ), this, SLOT ( showChildPulldownMenu() ) ); 79 connect ( childcheckbox, SIGNAL ( clicked() ), this, SLOT ( showChildPulldownMenu() ) );
80 connect ( balancecalculator, SIGNAL ( released() ), this, SLOT ( showCalculator() ) ); 80 connect ( balancecalculator, SIGNAL ( released() ), this, SLOT ( showCalculator() ) );
81 connect ( creditlimitcalculator, SIGNAL ( released() ), this, SLOT ( showCreditLimitCalculator() ) ); 81 connect ( creditlimitcalculator, SIGNAL ( released() ), this, SLOT ( showCreditLimitCalculator() ) );
82 connect ( accounttype, SIGNAL ( activated ( int ) ), this, SLOT ( activateCreditLimit ( int ) ) ); 82 connect ( accounttype, SIGNAL ( activated(int) ), this, SLOT ( activateCreditLimit(int) ) );
83 connect ( datebutton, SIGNAL ( released () ), this, SLOT ( showCalendar () ) ); 83 connect ( datebutton, SIGNAL ( released() ), this, SLOT ( showCalendar() ) );
84 connect ( descriptionbutton, SIGNAL ( released () ), this, SLOT ( addAccountDescription() ) ); 84 connect ( descriptionbutton, SIGNAL ( released() ), this, SLOT ( addAccountDescription() ) );
85} 85}
86 86
87NewAccount::~NewAccount () 87NewAccount::~NewAccount ()
88 { 88 {
89 } 89 }
90 90
91void NewAccount::showChildPulldownMenu () 91void NewAccount::showChildPulldownMenu ()
92 { 92 {
93 if ( childcheckbox->isChecked() == TRUE ) 93 if ( childcheckbox->isChecked() == TRUE )
94 { 94 {
95 childlabel->setEnabled ( TRUE ); 95 childlabel->setEnabled ( TRUE );
96 childbox->setEnabled ( TRUE ); 96 childbox->setEnabled ( TRUE );
97 } 97 }
98 else 98 else
99 hideChildPulldownMenu(); 99 hideChildPulldownMenu();
100 } 100 }
101 101
102void NewAccount::hideChildPulldownMenu () 102void NewAccount::hideChildPulldownMenu ()
103 { 103 {
104 childlabel->setEnabled ( FALSE ); 104 childlabel->setEnabled ( FALSE );
105 childbox->setEnabled ( FALSE ); 105 childbox->setEnabled ( FALSE );
106 } 106 }
107 107
108void NewAccount::showCalculator () 108void NewAccount::showCalculator ()
109 { 109 {
110 Calculator *calculator = new Calculator ( this ); 110 Calculator *calculator = new Calculator ( this );
111 calculator->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); 111 calculator->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) );
112 if ( calculator->exec () == QDialog::Accepted ) 112 if ( calculator->exec () == QDialog::Accepted )
113 accountbalance->setText ( calculator->display->text() ); 113 accountbalance->setText ( calculator->display->text() );
114 } 114 }
115 115
116void NewAccount::showCreditLimitCalculator () 116void NewAccount::showCreditLimitCalculator ()
117 { 117 {
118 Calculator *calculator = new Calculator ( this ); 118 Calculator *calculator = new Calculator ( this );
119 calculator->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); 119 calculator->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) );
120 if ( calculator->exec () == QDialog::Accepted ) 120 if ( calculator->exec () == QDialog::Accepted )
121 creditlimit->setText ( calculator->display->text() ); 121 creditlimit->setText ( calculator->display->text() );
122 } 122 }
123 123
124void NewAccount::activateCreditLimit ( int index ) 124void NewAccount::activateCreditLimit ( int index )
125 { 125 {
126 if ( index == 2 || index == 5 ) 126 if ( index == 2 || index == 5 )
127 creditlimitbox->setEnabled ( TRUE ); 127 creditlimitbox->setEnabled ( TRUE );
128 else 128 else
129 { 129 {
130 creditlimit->clear (); 130 creditlimit->clear ();
131 creditlimitbox->setEnabled ( FALSE ); 131 creditlimitbox->setEnabled ( FALSE );
132 } 132 }
133 } 133 }
134 134
135void NewAccount::showCalendar () 135void NewAccount::showCalendar ()
136 { 136 {
137 QDate newDate = QDate::currentDate (); 137 QDate newDate = QDate::currentDate ();
138 DatePicker *dp = new DatePicker ( newDate ); 138 DatePicker *dp = new DatePicker ( newDate );
139 dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); 139 dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) );
140 140
141 int response = dp->exec(); 141 int response = dp->exec();
142 if ( response == QDialog::Accepted ) 142 if ( response == QDialog::Accepted )
143 { 143 {
144 // Set date integers 144 // Set date integers
145 year = dp->getYear(); 145 year = dp->getYear();
146 month = dp->getMonth(); 146 month = dp->getMonth();
147 day = dp->getDay(); 147 day = dp->getDay();
148 148
149 // Set dateedited to TRUE 149 // Set dateedited to TRUE
150 // This tells the accountdisplay object that the user edited an account 150 // This tells the accountdisplay object that the user edited an account
151 // and did change the date 151 // and did change the date
152 dateedited = TRUE; 152 dateedited = TRUE;
153 153
154 // Display date with our selected format 154 // Display date with our selected format
155 startdate->setText ( preferences->getDate ( year, month, day ) ); 155 startdate->setText ( preferences->getDate ( year, month, day ) );
156 } 156 }
157 } 157 }
158 158
159bool NewAccount::getDateEdited () 159bool NewAccount::getDateEdited ()
160 { 160 {
161 return dateedited; 161 return dateedited;
162 } 162 }
163 163
164int NewAccount::getDay () 164int NewAccount::getDay ()
165 { 165 {
166 return day; 166 return day;
167 } 167 }
168 168
169int NewAccount::getMonth () 169int NewAccount::getMonth ()
170 { 170 {
171 return month; 171 return month;
172 } 172 }
173 173
174int NewAccount::getYear () 174int NewAccount::getYear ()
175 { 175 {
176 return year; 176 return year;
177 } 177 }
178 178
179QString NewAccount::getDescription () 179QString NewAccount::getDescription ()
180 { 180 {
181 return accountdescription; 181 return accountdescription;
182 } 182 }
183 183
184void NewAccount::setDescription ( QString description ) 184void NewAccount::setDescription ( QString description )
185 { 185 {
186 accountdescription = description; 186 accountdescription = description;
187 } 187 }
188 188
189void NewAccount::addAccountDescription () 189void NewAccount::addAccountDescription ()
190 { 190 {
191 // Function for adding or editing an account description. 191 // Function for adding or editing an account description.
192 QDialog *description = new QDialog ( this, "description", TRUE ); 192 QDialog *description = new QDialog ( this, "description", TRUE );
193 description->setCaption ( "Notes" ); 193 description->setCaption ( "Notes" );
194 QMultiLineEdit *enter = new QMultiLineEdit ( description ); 194 QMultiLineEdit *enter = new QMultiLineEdit ( description );
195 enter->setFixedSize ( ( int ) (this->width() * 0.75 ), ( int ) ( this->height() * 0.5 ) ); 195 enter->setFixedSize ( ( int ) (this->width() * 0.75 ), ( int ) ( this->height() * 0.5 ) );
196 enter->setWrapColumnOrWidth ( ( int ) (this->width() * 0.75 ) ); 196 enter->setWrapColumnOrWidth ( ( int ) (this->width() * 0.75 ) );
197 enter->setWordWrap ( QMultiLineEdit::WidgetWidth ); 197 enter->setWordWrap ( QMultiLineEdit::WidgetWidth );
198 if ( accountdescription != "(NULL)" ) 198 if ( accountdescription != "(NULL)" )
199 enter->setText ( accountdescription ); 199 enter->setText ( accountdescription );
200 if ( description->exec () == QDialog::Accepted ) 200 if ( description->exec () == QDialog::Accepted )
201 accountdescription = enter->text (); 201 accountdescription = enter->text ();
202 } 202 }
203 203
204 204
205 205
206 206
diff --git a/noncore/apps/qashmoney/newtransaction.cpp b/noncore/apps/qashmoney/newtransaction.cpp
index 5c78139..87b7f7e 100755
--- a/noncore/apps/qashmoney/newtransaction.cpp
+++ b/noncore/apps/qashmoney/newtransaction.cpp
@@ -1,274 +1,274 @@
1#include "newtransaction.h" 1#include "newtransaction.h"
2#include "calculator.h" 2#include "calculator.h"
3#include "datepicker.h" 3#include "datepicker.h"
4#include "budget.h" 4#include "budget.h"
5 5
6#include <qmultilineedit.h> 6#include <qmultilineedit.h>
7 7
8extern Budget *budget; 8extern Budget *budget;
9extern Preferences *preferences; 9extern Preferences *preferences;
10 10
11NewTransaction::NewTransaction ( QWidget* parent ) : QDialog ( parent, 0, TRUE ) 11NewTransaction::NewTransaction ( QWidget* parent ) : QDialog ( parent, 0, TRUE )
12 { 12 {
13 transactiondescription = ""; 13 transactiondescription = "";
14 currentlineitem = -1; 14 currentlineitem = -1;
15 currentbudget = -1; 15 currentbudget = -1;
16 dateedited = FALSE; 16 dateedited = FALSE;
17 setCaption( tr( "Transaction" ) ); 17 setCaption( tr( "Transaction" ) );
18 18
19 // START FIRST COLUMN 19 // START FIRST COLUMN
20 20
21 namelabel = new QLabel ( "Transaction", this ); 21 namelabel = new QLabel ( "Transaction", this );
22 22
23 transactionnamebox = new QHBox ( this ); 23 transactionnamebox = new QHBox ( this );
24 transactionname = new QComboBox ( transactionnamebox ); 24 transactionname = new QComboBox ( transactionnamebox );
25 transactionname->setEditable ( TRUE ); 25 transactionname->setEditable ( TRUE );
26 descriptionbutton = new QPushButton ( transactionnamebox ); 26 descriptionbutton = new QPushButton ( transactionnamebox );
27 descriptionbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/info.png" ) ); 27 descriptionbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/info.png" ) );
28 connect ( descriptionbutton, SIGNAL ( released () ), this, SLOT ( addTransactionDescription() ) ); 28 connect ( descriptionbutton, SIGNAL ( released() ), this, SLOT ( addTransactionDescription() ) );
29 29
30 amountlabel = new QLabel ( "Amount", this ); 30 amountlabel = new QLabel ( "Amount", this );
31 31
32 transactionamountbox = new QHBox ( this ); 32 transactionamountbox = new QHBox ( this );
33 transactionamount = new QLineEdit ( transactionamountbox ); 33 transactionamount = new QLineEdit ( transactionamountbox );
34 transactionamount->setAlignment ( Qt::AlignRight ); 34 transactionamount->setAlignment ( Qt::AlignRight );
35 transactionamount->setText ( "0.00" ); 35 transactionamount->setText ( "0.00" );
36 calculatorbutton = new QPushButton( transactionamountbox ); 36 calculatorbutton = new QPushButton( transactionamountbox );
37 calculatorbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) ); 37 calculatorbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) );
38 connect ( calculatorbutton, SIGNAL ( released() ), this, SLOT ( showCalculator() ) ); 38 connect ( calculatorbutton, SIGNAL ( released() ), this, SLOT ( showCalculator() ) );
39 39
40 datelabel = new QLabel ( "Date", this ); 40 datelabel = new QLabel ( "Date", this );
41 41
42 transactiondatebox = new QHBox ( this ); 42 transactiondatebox = new QHBox ( this );
43 transactiondate = new QLineEdit ( transactiondatebox ); 43 transactiondate = new QLineEdit ( transactiondatebox );
44 transactiondate->setAlignment ( Qt::AlignRight ); 44 transactiondate->setAlignment ( Qt::AlignRight );
45 transactiondate->setDisabled ( TRUE ); 45 transactiondate->setDisabled ( TRUE );
46 datebutton = new QPushButton( transactiondatebox ); 46 datebutton = new QPushButton( transactiondatebox );
47 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) ); 47 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) );
48 connect ( datebutton, SIGNAL ( released () ), this, SLOT ( showCalendar () ) ); 48 connect ( datebutton, SIGNAL ( released() ), this, SLOT ( showCalendar() ) );
49 49
50 clearedcheckbox = new QCheckBox ( "Cleared", this ); 50 clearedcheckbox = new QCheckBox ( "Cleared", this );
51 depositbox = new QCheckBox ( "Credit", this ); 51 depositbox = new QCheckBox ( "Credit", this );
52 52
53 // START SECOND COLUMN 53 // START SECOND COLUMN
54 54
55 numberlabel = new QLabel ( "Number", this ); 55 numberlabel = new QLabel ( "Number", this );
56 transactionnumber = new QLineEdit ( this ); 56 transactionnumber = new QLineEdit ( this );
57 57
58 budgetlabel = new QLabel ( "Budget", this ); 58 budgetlabel = new QLabel ( "Budget", this );
59 budgetbox = new QComboBox ( FALSE, this ); 59 budgetbox = new QComboBox ( FALSE, this );
60 60
61 lineitemlabel = new QLabel ( "LineItem", this ); 61 lineitemlabel = new QLabel ( "LineItem", this );
62 lineitembox = new QComboBox ( FALSE, this ); 62 lineitembox = new QComboBox ( FALSE, this );
63 63
64 layout = new QGridLayout ( this, 7, 2, 2, 2 ); 64 layout = new QGridLayout ( this, 7, 2, 2, 2 );
65 layout->addWidget ( namelabel, 0, 0, Qt::AlignLeft ); 65 layout->addWidget ( namelabel, 0, 0, Qt::AlignLeft );
66 layout->addWidget ( transactionnamebox, 1, 0, Qt::AlignLeft ); 66 layout->addWidget ( transactionnamebox, 1, 0, Qt::AlignLeft );
67 layout->addWidget ( amountlabel, 2, 0, Qt::AlignLeft ); 67 layout->addWidget ( amountlabel, 2, 0, Qt::AlignLeft );
68 layout->addWidget ( transactionamountbox, 3, 0, Qt::AlignLeft ); 68 layout->addWidget ( transactionamountbox, 3, 0, Qt::AlignLeft );
69 layout->addWidget ( datelabel, 4, 0, Qt::AlignLeft ); 69 layout->addWidget ( datelabel, 4, 0, Qt::AlignLeft );
70 layout->addWidget ( transactiondatebox, 5, 0, Qt::AlignLeft ); 70 layout->addWidget ( transactiondatebox, 5, 0, Qt::AlignLeft );
71 layout->addWidget ( clearedcheckbox, 6, 0, Qt::AlignLeft ); 71 layout->addWidget ( clearedcheckbox, 6, 0, Qt::AlignLeft );
72 layout->addWidget ( numberlabel, 0, 1, Qt::AlignLeft ); 72 layout->addWidget ( numberlabel, 0, 1, Qt::AlignLeft );
73 layout->addWidget ( transactionnumber, 1, 1, Qt::AlignLeft ); 73 layout->addWidget ( transactionnumber, 1, 1, Qt::AlignLeft );
74 layout->addWidget ( budgetlabel, 2, 1, Qt::AlignLeft ); 74 layout->addWidget ( budgetlabel, 2, 1, Qt::AlignLeft );
75 layout->addWidget ( budgetbox, 3, 1, Qt::AlignLeft ); 75 layout->addWidget ( budgetbox, 3, 1, Qt::AlignLeft );
76 layout->addWidget ( lineitemlabel, 4, 1, Qt::AlignLeft ); 76 layout->addWidget ( lineitemlabel, 4, 1, Qt::AlignLeft );
77 layout->addWidget ( lineitembox, 5, 1, Qt::AlignLeft ); 77 layout->addWidget ( lineitembox, 5, 1, Qt::AlignLeft );
78 layout->addWidget ( depositbox, 6, 1, Qt::AlignLeft ); 78 layout->addWidget ( depositbox, 6, 1, Qt::AlignLeft );
79 79
80 if ( budget->getNumberOfBudgets() != 0 ) 80 if ( budget->getNumberOfBudgets() != 0 )
81 { 81 {
82 budgetnameslist = budget->getBudgetNames(); 82 budgetnameslist = budget->getBudgetNames();
83 budgetidslist = budget->getBudgetIDs(); 83 budgetidslist = budget->getBudgetIDs();
84 budgetbox->insertStringList ( *budgetnameslist ); 84 budgetbox->insertStringList ( *budgetnameslist );
85 lineitemlabel->setEnabled ( FALSE ); 85 lineitemlabel->setEnabled ( FALSE );
86 lineitembox->setEnabled ( FALSE ); 86 lineitembox->setEnabled ( FALSE );
87 connect ( budgetbox, SIGNAL ( activated ( int ) ), this, SLOT ( setCurrentBudget ( int ) ) ); 87 connect ( budgetbox, SIGNAL ( activated(int) ), this, SLOT ( setCurrentBudget(int) ) );
88 connect ( lineitembox, SIGNAL ( activated ( int ) ), this, SLOT ( setCurrentLineItem ( int ) ) ); 88 connect ( lineitembox, SIGNAL ( activated(int) ), this, SLOT ( setCurrentLineItem(int) ) );
89 } 89 }
90 else 90 else
91 { 91 {
92 budgetlabel->setEnabled ( FALSE ); 92 budgetlabel->setEnabled ( FALSE );
93 budgetbox->setEnabled ( FALSE ); 93 budgetbox->setEnabled ( FALSE );
94 lineitemlabel->setEnabled ( FALSE ); 94 lineitemlabel->setEnabled ( FALSE );
95 lineitembox->setEnabled ( FALSE ); 95 lineitembox->setEnabled ( FALSE );
96 } 96 }
97 97
98} 98}
99 99
100NewTransaction::~NewTransaction () 100NewTransaction::~NewTransaction ()
101 { 101 {
102 } 102 }
103 103
104void NewTransaction::showCalculator () 104void NewTransaction::showCalculator ()
105{ 105{
106 Calculator *calculator = new Calculator ( this ); 106 Calculator *calculator = new Calculator ( this );
107 calculator->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); 107 calculator->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) );
108 if ( calculator->exec () == QDialog::Accepted ) 108 if ( calculator->exec () == QDialog::Accepted )
109 transactionamount->setText ( calculator->display->text() ); 109 transactionamount->setText ( calculator->display->text() );
110} 110}
111 111
112void NewTransaction::showCalendar () 112void NewTransaction::showCalendar ()
113 { 113 {
114 QDate newDate = QDate::currentDate (); 114 QDate newDate = QDate::currentDate ();
115 DatePicker *dp = new DatePicker ( newDate ); 115 DatePicker *dp = new DatePicker ( newDate );
116 dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); 116 dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) );
117 117
118 int response = dp->exec(); 118 int response = dp->exec();
119 if ( response == QDialog::Accepted ) 119 if ( response == QDialog::Accepted )
120 { 120 {
121 // Set date integers 121 // Set date integers
122 year = dp->getYear(); 122 year = dp->getYear();
123 month = dp->getMonth(); 123 month = dp->getMonth();
124 day = dp->getDay(); 124 day = dp->getDay();
125 125
126 // Set dateedited to TRUE 126 // Set dateedited to TRUE
127 // This tells the transactiondisplay object that the user edited an transaction 127 // This tells the transactiondisplay object that the user edited an transaction
128 // and did change the date3 128 // and did change the date3
129 dateedited = TRUE; 129 dateedited = TRUE;
130 130
131 // Display date with our selected format 131 // Display date with our selected format
132 transactiondate->setText ( preferences->getDate ( year, month, day ) ); 132 transactiondate->setText ( preferences->getDate ( year, month, day ) );
133 } 133 }
134 } 134 }
135 135
136bool NewTransaction::getDateEdited () 136bool NewTransaction::getDateEdited ()
137 { 137 {
138 return dateedited; 138 return dateedited;
139 } 139 }
140 140
141int NewTransaction::getDay () 141int NewTransaction::getDay ()
142 { 142 {
143 return day; 143 return day;
144 } 144 }
145 145
146int NewTransaction::getMonth () 146int NewTransaction::getMonth ()
147 { 147 {
148 return month; 148 return month;
149 } 149 }
150 150
151int NewTransaction::getYear () 151int NewTransaction::getYear ()
152 { 152 {
153 return year; 153 return year;
154 } 154 }
155 155
156QString NewTransaction::getDescription () 156QString NewTransaction::getDescription ()
157 { 157 {
158 return transactiondescription; 158 return transactiondescription;
159 } 159 }
160 160
161void NewTransaction::setDescription ( QString description ) 161void NewTransaction::setDescription ( QString description )
162 { 162 {
163 transactiondescription = description; 163 transactiondescription = description;
164 } 164 }
165 165
166void NewTransaction::addTransactionDescription () 166void NewTransaction::addTransactionDescription ()
167 { 167 {
168 // Function for adding or editing an transaction description. 168 // Function for adding or editing an transaction description.
169 QDialog *description = new QDialog ( this, "description", TRUE ); 169 QDialog *description = new QDialog ( this, "description", TRUE );
170 description->setCaption ( "Notes" ); 170 description->setCaption ( "Notes" );
171 QMultiLineEdit *enter = new QMultiLineEdit ( description ); 171 QMultiLineEdit *enter = new QMultiLineEdit ( description );
172 enter->setFixedSize ( ( int ) (this->width() * 0.75 ), ( int ) ( this->height() * 0.5 ) ); 172 enter->setFixedSize ( ( int ) (this->width() * 0.75 ), ( int ) ( this->height() * 0.5 ) );
173 enter->setWrapColumnOrWidth ( ( int ) (this->width() * 0.75 ) ); 173 enter->setWrapColumnOrWidth ( ( int ) (this->width() * 0.75 ) );
174 enter->setWordWrap ( QMultiLineEdit::WidgetWidth ); 174 enter->setWordWrap ( QMultiLineEdit::WidgetWidth );
175 if ( transactiondescription != "(NULL)" ) 175 if ( transactiondescription != "(NULL)" )
176 enter->setText ( transactiondescription ); 176 enter->setText ( transactiondescription );
177 if ( description->exec () == QDialog::Accepted ) 177 if ( description->exec () == QDialog::Accepted )
178 transactiondescription = enter->text (); 178 transactiondescription = enter->text ();
179 } 179 }
180 180
181int NewTransaction::getNameIndex ( QString name ) 181int NewTransaction::getNameIndex ( QString name )
182 { 182 {
183 int counter; 183 int counter;
184 int items = transactionname->count(); 184 int items = transactionname->count();
185 for ( counter = 0; ( items - 1 ); counter++ ) 185 for ( counter = 0; ( items - 1 ); counter++ )
186 { 186 {
187 if ( name == transactionname->text ( counter ) ) 187 if ( name == transactionname->text ( counter ) )
188 { 188 {
189 return counter; 189 return counter;
190 break; 190 break;
191 } 191 }
192 } 192 }
193 return 0; 193 return 0;
194 } 194 }
195 195
196void NewTransaction::setCurrentBudget ( int index ) 196void NewTransaction::setCurrentBudget ( int index )
197 { 197 {
198 if ( index != 0 ) 198 if ( index != 0 )
199 { 199 {
200 currentbudget = budgetidslist->operator[] ( index - 1 ).toInt(); 200 currentbudget = budgetidslist->operator[] ( index - 1 ).toInt();
201 lineitemslist = budget->getLineItems ( currentbudget ); 201 lineitemslist = budget->getLineItems ( currentbudget );
202 lineitemidslist = budget->getLineItemIDs ( currentbudget ); 202 lineitemidslist = budget->getLineItemIDs ( currentbudget );
203 lineitemlabel->setEnabled ( TRUE ); 203 lineitemlabel->setEnabled ( TRUE );
204 lineitembox->setEnabled ( TRUE ); 204 lineitembox->setEnabled ( TRUE );
205 lineitembox->clear(); 205 lineitembox->clear();
206 lineitembox->insertStringList ( lineitemslist ); 206 lineitembox->insertStringList ( lineitemslist );
207 setCurrentLineItem ( 0 ); 207 setCurrentLineItem ( 0 );
208 } 208 }
209 else 209 else
210 { 210 {
211 lineitembox->clear(); 211 lineitembox->clear();
212 lineitemlabel->setEnabled ( FALSE ); 212 lineitemlabel->setEnabled ( FALSE );
213 lineitembox->setEnabled ( FALSE ); 213 lineitembox->setEnabled ( FALSE );
214 currentlineitem = -1; 214 currentlineitem = -1;
215 currentbudget = -1; 215 currentbudget = -1;
216 } 216 }
217 } 217 }
218 218
219void NewTransaction::setCurrentLineItem ( int index ) 219void NewTransaction::setCurrentLineItem ( int index )
220 { 220 {
221 currentlineitem = ( lineitemidslist.operator[] ( index ).toInt() ); 221 currentlineitem = ( lineitemidslist.operator[] ( index ).toInt() );
222 } 222 }
223 223
224int NewTransaction::getCurrentBudget () 224int NewTransaction::getCurrentBudget ()
225 { 225 {
226 return currentbudget; 226 return currentbudget;
227 } 227 }
228 228
229int NewTransaction::getBudgetIndex ( int budgetid ) 229int NewTransaction::getBudgetIndex ( int budgetid )
230 { 230 {
231 currentbudget = budgetid; 231 currentbudget = budgetid;
232 const QString budget = QString::number ( budgetid ); 232 const QString budget = QString::number ( budgetid );
233 return budgetidslist->findIndex ( budget ); 233 return budgetidslist->findIndex ( budget );
234 } 234 }
235 235
236int NewTransaction::getLineItemIndex ( int lineitemid ) 236int NewTransaction::getLineItemIndex ( int lineitemid )
237 { 237 {
238 currentlineitem = lineitemid; 238 currentlineitem = lineitemid;
239 const QString lineitem = QString::number ( lineitemid ); 239 const QString lineitem = QString::number ( lineitemid );
240 return lineitemidslist.findIndex ( lineitem ); 240 return lineitemidslist.findIndex ( lineitem );
241 } 241 }
242 242
243void NewTransaction::setLineItems () 243void NewTransaction::setLineItems ()
244 { 244 {
245 lineitemslist = budget->getLineItems ( currentbudget ); 245 lineitemslist = budget->getLineItems ( currentbudget );
246 lineitemidslist = budget->getLineItemIDs ( currentbudget ); 246 lineitemidslist = budget->getLineItemIDs ( currentbudget );
247 lineitemlabel->setEnabled ( TRUE ); 247 lineitemlabel->setEnabled ( TRUE );
248 lineitembox->setEnabled ( TRUE ); 248 lineitembox->setEnabled ( TRUE );
249 lineitembox->clear(); 249 lineitembox->clear();
250 lineitembox->insertStringList ( lineitemslist ); 250 lineitembox->insertStringList ( lineitemslist );
251 } 251 }
252 252
253int NewTransaction::getCurrentLineItem () 253int NewTransaction::getCurrentLineItem ()
254 { 254 {
255 return currentlineitem; 255 return currentlineitem;
256 } 256 }
257 257
258void NewTransaction::setComboBoxes ( int budgetid, int lineitemid ) 258void NewTransaction::setComboBoxes ( int budgetid, int lineitemid )
259 { 259 {
260 const QString budgetname = QString::number ( budgetid ); 260 const QString budgetname = QString::number ( budgetid );
261 budgetbox->setCurrentItem ( ( budgetidslist->findIndex ( budgetname ) ) ); 261 budgetbox->setCurrentItem ( ( budgetidslist->findIndex ( budgetname ) ) );
262 currentbudget = budgetidslist->operator[] ( budgetbox->currentItem() - 1 ).toInt(); 262 currentbudget = budgetidslist->operator[] ( budgetbox->currentItem() - 1 ).toInt();
263 263
264 lineitemslist = budget->getLineItems ( currentbudget ); 264 lineitemslist = budget->getLineItems ( currentbudget );
265 lineitemidslist = budget->getLineItemIDs ( currentbudget ); 265 lineitemidslist = budget->getLineItemIDs ( currentbudget );
266 lineitemlabel->setEnabled ( TRUE ); 266 lineitemlabel->setEnabled ( TRUE );
267 lineitembox->setEnabled ( TRUE ); 267 lineitembox->setEnabled ( TRUE );
268 lineitembox->clear(); 268 lineitembox->clear();
269 lineitembox->insertStringList ( lineitemslist ); 269 lineitembox->insertStringList ( lineitemslist );
270 270
271 const QString lineitem = QString::number ( lineitemid ); 271 const QString lineitem = QString::number ( lineitemid );
272 lineitembox->setCurrentItem ( lineitemidslist.findIndex ( lineitem ) ); 272 lineitembox->setCurrentItem ( lineitemidslist.findIndex ( lineitem ) );
273 currentlineitem = ( lineitemidslist.operator[] ( lineitembox->currentItem() ).toInt() ); 273 currentlineitem = ( lineitemidslist.operator[] ( lineitembox->currentItem() ).toInt() );
274 } 274 }
diff --git a/noncore/apps/qashmoney/preferencedialogs.cpp b/noncore/apps/qashmoney/preferencedialogs.cpp
index 5408a5b..b83c957 100755
--- a/noncore/apps/qashmoney/preferencedialogs.cpp
+++ b/noncore/apps/qashmoney/preferencedialogs.cpp
@@ -1,216 +1,216 @@
1#include "preferencedialogs.h" 1#include "preferencedialogs.h"
2#include "preferences.h" 2#include "preferences.h"
3 3
4extern Preferences *preferences; 4extern Preferences *preferences;
5 5
6DatePreferences::DatePreferences ( QWidget* parent ) : QDialog ( parent, 0, TRUE ) 6DatePreferences::DatePreferences ( QWidget* parent ) : QDialog ( parent, 0, TRUE )
7 { 7 {
8 setCaption( tr( "Date" ) ); 8 setCaption( tr( "Date" ) );
9 9
10 QLabel *datelabel = new QLabel ( "Format", this ); 10 QLabel *datelabel = new QLabel ( "Format", this );
11 dateformat = new QComboBox ( this ); 11 dateformat = new QComboBox ( this );
12 dateformat->setEditable ( FALSE ); 12 dateformat->setEditable ( FALSE );
13 dateformat->insertItem ( "yyyymmdd" ); 13 dateformat->insertItem ( "yyyymmdd" );
14 dateformat->insertItem ( "yymmdd" ); 14 dateformat->insertItem ( "yymmdd" );
15 dateformat->insertItem ( "mmddyyyy" ); 15 dateformat->insertItem ( "mmddyyyy" );
16 dateformat->insertItem ( "mmddyy" ); 16 dateformat->insertItem ( "mmddyy" );
17 dateformat->insertItem ( "yyyyddmm" ); 17 dateformat->insertItem ( "yyyyddmm" );
18 dateformat->insertItem ( "yyddmm" ); 18 dateformat->insertItem ( "yyddmm" );
19 dateformat->insertItem ( "ddmmyyyy" ); 19 dateformat->insertItem ( "ddmmyyyy" );
20 dateformat->insertItem ( "ddmmyy" ); 20 dateformat->insertItem ( "ddmmyy" );
21 connect ( dateformat, SIGNAL ( activated ( int ) ), this, SLOT ( changeDateFormat ( int ) ) ); 21 connect ( dateformat, SIGNAL ( activated(int) ), this, SLOT ( changeDateFormat(int) ) );
22 22
23 QLabel *dateseparatorlabel = new QLabel ( "Separator", this ); 23 QLabel *dateseparatorlabel = new QLabel ( "Separator", this );
24 dateseparator = new QComboBox ( this ); 24 dateseparator = new QComboBox ( this );
25 dateseparator->insertItem ( "/" ); 25 dateseparator->insertItem ( "/" );
26 dateseparator->insertItem ( "-" ); 26 dateseparator->insertItem ( "-" );
27 dateseparator->insertItem ( "." ); 27 dateseparator->insertItem ( "." );
28 connect ( dateseparator, SIGNAL ( activated ( int ) ), this, SLOT ( changeDateSeparator ( int ) ) ); 28 connect ( dateseparator, SIGNAL ( activated(int) ), this, SLOT ( changeDateSeparator(int) ) );
29 29
30 defaults = new QPushButton ( QPixmap ( "/opt/QtPalmtop/pics/defaults.png" ), "Defaults", this ); 30 defaults = new QPushButton ( QPixmap ( "/opt/QtPalmtop/pics/defaults.png" ), "Defaults", this );
31 connect ( defaults, SIGNAL ( released () ), this, SLOT ( setDefaultDatePreferences () ) ); 31 connect ( defaults, SIGNAL ( released() ), this, SLOT ( setDefaultDatePreferences() ) );
32 32
33 dateformat->setCurrentItem ( ( preferences->getPreference ( 1 ) ) - 1 ); 33 dateformat->setCurrentItem ( ( preferences->getPreference ( 1 ) ) - 1 );
34 dateseparator->setCurrentItem ( ( preferences->getPreference ( 2 ) ) - 1 ); 34 dateseparator->setCurrentItem ( ( preferences->getPreference ( 2 ) ) - 1 );
35 35
36 layout = new QVBoxLayout ( this, 2, 2 ); 36 layout = new QVBoxLayout ( this, 2, 2 );
37 layout->addWidget ( datelabel ); 37 layout->addWidget ( datelabel );
38 layout->addWidget ( dateformat ); 38 layout->addWidget ( dateformat );
39 layout->addWidget ( dateseparatorlabel ); 39 layout->addWidget ( dateseparatorlabel );
40 layout->addWidget ( dateseparator ); 40 layout->addWidget ( dateseparator );
41 layout->insertSpacing ( 4, 5 ); 41 layout->insertSpacing ( 4, 5 );
42 layout->addWidget ( defaults ); 42 layout->addWidget ( defaults );
43 43
44 } 44 }
45 45
46DatePreferences::~DatePreferences () 46DatePreferences::~DatePreferences ()
47 { 47 {
48 } 48 }
49 49
50void DatePreferences::changeDateFormat ( int index ) 50void DatePreferences::changeDateFormat ( int index )
51 { 51 {
52 index ++; 52 index ++;
53 preferences->changePreference ( 1, index ); 53 preferences->changePreference ( 1, index );
54 } 54 }
55 55
56void DatePreferences::changeDateSeparator ( int index ) 56void DatePreferences::changeDateSeparator ( int index )
57 { 57 {
58 index ++; 58 index ++;
59 preferences->changePreference ( 2, index ); 59 preferences->changePreference ( 2, index );
60 } 60 }
61 61
62void DatePreferences::setDefaultDatePreferences () 62void DatePreferences::setDefaultDatePreferences ()
63 { 63 {
64 preferences->setDefaultDatePreferences (); 64 preferences->setDefaultDatePreferences ();
65 dateformat->setCurrentItem ( ( preferences->getPreference ( 1 ) ) - 1 ); 65 dateformat->setCurrentItem ( ( preferences->getPreference ( 1 ) ) - 1 );
66 dateseparator->setCurrentItem ( ( preferences->getPreference ( 2 ) ) - 1 ); 66 dateseparator->setCurrentItem ( ( preferences->getPreference ( 2 ) ) - 1 );
67 } 67 }
68 68
69// START TRANSACTION PREFERENCES 69// START TRANSACTION PREFERENCES
70 70
71TransactionPreferences::TransactionPreferences ( QWidget* parent ) : QDialog ( parent, 0, TRUE ) 71TransactionPreferences::TransactionPreferences ( QWidget* parent ) : QDialog ( parent, 0, TRUE )
72{ 72{
73 setCaption( tr ( "Transaction" ) ); 73 setCaption( tr ( "Transaction" ) );
74 74
75 showclearedtransactions = new QCheckBox ( this ); 75 showclearedtransactions = new QCheckBox ( this );
76 showclearedtransactions->setText ( "Show Cleared Transactions" ); 76 showclearedtransactions->setText ( "Show Cleared Transactions" );
77 77
78 limittransactionsbox = new QHBox ( this ); 78 limittransactionsbox = new QHBox ( this );
79 limittransactionsbox->setSpacing ( 2 ); 79 limittransactionsbox->setSpacing ( 2 );
80 limittransactionslabel = new QLabel ( "Show ", limittransactionsbox ); 80 limittransactionslabel = new QLabel ( "Show ", limittransactionsbox );
81 limittransactions = new QComboBox ( limittransactionsbox ); 81 limittransactions = new QComboBox ( limittransactionsbox );
82 QLabel *limittransactionslabel2 = new QLabel ( "of cleared transactions. ", limittransactionsbox ); 82 QLabel *limittransactionslabel2 = new QLabel ( "of cleared transactions. ", limittransactionsbox );
83 limittransactions->insertItem ( "14 days" ); 83 limittransactions->insertItem ( "14 days" );
84 limittransactions->insertItem ( "30 days" ); 84 limittransactions->insertItem ( "30 days" );
85 limittransactions->insertItem ( "90 days" ); 85 limittransactions->insertItem ( "90 days" );
86 limittransactions->insertItem ( "180 days" ); 86 limittransactions->insertItem ( "180 days" );
87 limittransactions->insertItem ( "365 days" ); 87 limittransactions->insertItem ( "365 days" );
88 limittransactions->insertItem ( "All" ); 88 limittransactions->insertItem ( "All" );
89 limittransactions->setCurrentItem ( preferences->getPreference ( 7 ) ); 89 limittransactions->setCurrentItem ( preferences->getPreference ( 7 ) );
90 90
91 excludetransfers = new QCheckBox ( this ); 91 excludetransfers = new QCheckBox ( this );
92 excludetransfers->setText ( "Include Transfers In Limit View" ); 92 excludetransfers->setText ( "Include Transfers In Limit View" );
93 93
94 if ( preferences->getPreference ( 3 ) == 1 ) 94 if ( preferences->getPreference ( 3 ) == 1 )
95 showclearedtransactions->setChecked ( TRUE ); 95 showclearedtransactions->setChecked ( TRUE );
96 else 96 else
97 showclearedtransactions->setChecked ( FALSE ); 97 showclearedtransactions->setChecked ( FALSE );
98 98
99 if ( preferences->getPreference ( 6 ) == 1 ) 99 if ( preferences->getPreference ( 6 ) == 1 )
100 excludetransfers->setChecked ( TRUE ); 100 excludetransfers->setChecked ( TRUE );
101 else 101 else
102 excludetransfers->setChecked ( FALSE ); 102 excludetransfers->setChecked ( FALSE );
103 103
104 defaults = new QPushButton ( QPixmap ( "/opt/QtPalmtop/pics/defaults.png" ), "Defaults", this ); 104 defaults = new QPushButton ( QPixmap ( "/opt/QtPalmtop/pics/defaults.png" ), "Defaults", this );
105 connect ( defaults, SIGNAL ( released () ), this, SLOT ( setDefaultTransactionPreferences () ) ); 105 connect ( defaults, SIGNAL ( released() ), this, SLOT ( setDefaultTransactionPreferences() ) );
106 106
107 layout = new QVBoxLayout ( this, 2, 2 ); 107 layout = new QVBoxLayout ( this, 2, 2 );
108 layout->addWidget ( showclearedtransactions ); 108 layout->addWidget ( showclearedtransactions );
109 layout->addWidget ( limittransactionsbox ); 109 layout->addWidget ( limittransactionsbox );
110 layout->addWidget ( excludetransfers ); 110 layout->addWidget ( excludetransfers );
111 layout->insertSpacing ( 3, 5 ); 111 layout->insertSpacing ( 3, 5 );
112 layout->addWidget ( defaults ); 112 layout->addWidget ( defaults );
113 113
114 connect ( showclearedtransactions, SIGNAL ( toggled ( bool ) ), this, SLOT ( changeShowClearedPreference ( bool ) ) ); 114 connect ( showclearedtransactions, SIGNAL ( toggled(bool) ), this, SLOT ( changeShowClearedPreference(bool) ) );
115 connect ( excludetransfers, SIGNAL ( toggled ( bool ) ), this, SLOT ( changeExcludeTranfersPreference ( bool ) ) ); 115 connect ( excludetransfers, SIGNAL ( toggled(bool) ), this, SLOT ( changeExcludeTranfersPreference(bool) ) );
116 connect ( limittransactions, SIGNAL ( activated ( int ) ), this, SLOT ( changeLimitTransactionsPreference ( int ) ) ); 116 connect ( limittransactions, SIGNAL ( activated(int) ), this, SLOT ( changeLimitTransactionsPreference(int) ) );
117} 117}
118 118
119TransactionPreferences::~TransactionPreferences () 119TransactionPreferences::~TransactionPreferences ()
120 { 120 {
121 } 121 }
122 122
123void TransactionPreferences::changeLimitTransactionsPreference ( int pref ) 123void TransactionPreferences::changeLimitTransactionsPreference ( int pref )
124 { 124 {
125 preferences->changePreference ( 7, pref ); 125 preferences->changePreference ( 7, pref );
126 } 126 }
127 127
128void TransactionPreferences::changeShowClearedPreference ( bool state ) 128void TransactionPreferences::changeShowClearedPreference ( bool state )
129 { 129 {
130 if ( state == TRUE ) 130 if ( state == TRUE )
131 preferences->changePreference ( 3, 1 ); 131 preferences->changePreference ( 3, 1 );
132 else 132 else
133 preferences->changePreference ( 3, 0 ); 133 preferences->changePreference ( 3, 0 );
134 } 134 }
135 135
136void TransactionPreferences::changeExcludeTranfersPreference ( bool state ) 136void TransactionPreferences::changeExcludeTranfersPreference ( bool state )
137 { 137 {
138 if ( state == TRUE ) 138 if ( state == TRUE )
139 preferences->changePreference ( 6, 1 ); 139 preferences->changePreference ( 6, 1 );
140 else 140 else
141 preferences->changePreference ( 6, 0 ); 141 preferences->changePreference ( 6, 0 );
142 } 142 }
143 143
144void TransactionPreferences::setDefaultTransactionPreferences () 144void TransactionPreferences::setDefaultTransactionPreferences ()
145 { 145 {
146 preferences->changePreference ( 3, 0 ); 146 preferences->changePreference ( 3, 0 );
147 preferences->changePreference ( 6, 0 ); 147 preferences->changePreference ( 6, 0 );
148 preferences->changePreference ( 7, 0 ); 148 preferences->changePreference ( 7, 0 );
149 showclearedtransactions->setChecked ( FALSE ); 149 showclearedtransactions->setChecked ( FALSE );
150 limittransactions->setCurrentItem ( 0 ); 150 limittransactions->setCurrentItem ( 0 );
151 } 151 }
152 152
153// START ACCOUNT PREFERNCES 153// START ACCOUNT PREFERNCES
154 154
155AccountPreferences::AccountPreferences ( QWidget* parent ) : QDialog ( parent, 0, TRUE ) 155AccountPreferences::AccountPreferences ( QWidget* parent ) : QDialog ( parent, 0, TRUE )
156{ 156{
157 157
158 setCaption( tr ( "Account" ) ); 158 setCaption( tr ( "Account" ) );
159 159
160 currencysupport = new QCheckBox ( this ); 160 currencysupport = new QCheckBox ( this );
161 currencysupport->setText ( "Enable Currency Support" ); 161 currencysupport->setText ( "Enable Currency Support" );
162 162
163 onetouch = new QCheckBox ( this ); 163 onetouch = new QCheckBox ( this );
164 onetouch->setText ( "One Touch Account Viewing" ); 164 onetouch->setText ( "One Touch Account Viewing" );
165 165
166 if ( preferences->getPreference ( 4 ) == 1 ) 166 if ( preferences->getPreference ( 4 ) == 1 )
167 currencysupport->setChecked ( TRUE ); 167 currencysupport->setChecked ( TRUE );
168 else 168 else
169 currencysupport->setChecked ( FALSE ); 169 currencysupport->setChecked ( FALSE );
170 170
171 if ( preferences->getPreference ( 5 ) == 1 ) 171 if ( preferences->getPreference ( 5 ) == 1 )
172 onetouch->setChecked ( TRUE ); 172 onetouch->setChecked ( TRUE );
173 else 173 else
174 onetouch->setChecked ( FALSE ); 174 onetouch->setChecked ( FALSE );
175 175
176 defaults = new QPushButton ( QPixmap ( "/opt/QtPalmtop/pics/defaults.png" ), "Defaults", this ); 176 defaults = new QPushButton ( QPixmap ( "/opt/QtPalmtop/pics/defaults.png" ), "Defaults", this );
177 connect ( defaults, SIGNAL ( released () ), this, SLOT ( setDefaultAccountPreferences () ) ); 177 connect ( defaults, SIGNAL ( released() ), this, SLOT ( setDefaultAccountPreferences() ) );
178 178
179 layout = new QVBoxLayout ( this, 2, 2 ); 179 layout = new QVBoxLayout ( this, 2, 2 );
180 layout->addWidget ( currencysupport ); 180 layout->addWidget ( currencysupport );
181 layout->addWidget ( onetouch ); 181 layout->addWidget ( onetouch );
182 layout->insertSpacing ( 2, 5 ); 182 layout->insertSpacing ( 2, 5 );
183 layout->addWidget ( defaults ); 183 layout->addWidget ( defaults );
184 184
185 connect ( currencysupport, SIGNAL ( toggled ( bool ) ), this, SLOT ( changeCurrencySupport ( bool ) ) ); 185 connect ( currencysupport, SIGNAL ( toggled(bool) ), this, SLOT ( changeCurrencySupport(bool) ) );
186 connect ( onetouch, SIGNAL ( toggled ( bool ) ), this, SLOT ( changeOneTouchViewing ( bool ) ) ); 186 connect ( onetouch, SIGNAL ( toggled(bool) ), this, SLOT ( changeOneTouchViewing(bool) ) );
187} 187}
188 188
189AccountPreferences::~AccountPreferences () 189AccountPreferences::~AccountPreferences ()
190 { 190 {
191 } 191 }
192 192
193void AccountPreferences::changeCurrencySupport ( bool state ) 193void AccountPreferences::changeCurrencySupport ( bool state )
194 { 194 {
195 if ( state == TRUE ) 195 if ( state == TRUE )
196 preferences->changePreference ( 4, 1 ); 196 preferences->changePreference ( 4, 1 );
197 else 197 else
198 preferences->changePreference ( 4, 0 ); 198 preferences->changePreference ( 4, 0 );
199 } 199 }
200 200
201void AccountPreferences::changeOneTouchViewing ( bool state ) 201void AccountPreferences::changeOneTouchViewing ( bool state )
202 { 202 {
203 if ( state == TRUE ) 203 if ( state == TRUE )
204 preferences->changePreference ( 5, 1 ); 204 preferences->changePreference ( 5, 1 );
205 else 205 else
206 preferences->changePreference ( 5, 0 ); 206 preferences->changePreference ( 5, 0 );
207 } 207 }
208 208
209void AccountPreferences::setDefaultAccountPreferences () 209void AccountPreferences::setDefaultAccountPreferences ()
210 { 210 {
211 preferences->changePreference ( 4, 0 ); 211 preferences->changePreference ( 4, 0 );
212 preferences->changePreference ( 5, 0 ); 212 preferences->changePreference ( 5, 0 );
213 currencysupport->setChecked ( FALSE ); 213 currencysupport->setChecked ( FALSE );
214 onetouch->setChecked ( FALSE ); 214 onetouch->setChecked ( FALSE );
215 } 215 }
216 216
diff --git a/noncore/apps/qashmoney/qashmoney.cpp b/noncore/apps/qashmoney/qashmoney.cpp
index d4cbc14..1455eb0 100755
--- a/noncore/apps/qashmoney/qashmoney.cpp
+++ b/noncore/apps/qashmoney/qashmoney.cpp
@@ -1,402 +1,402 @@
1#include "qashmoney.h" 1#include "qashmoney.h"
2#include "preferencedialogs.h" 2#include "preferencedialogs.h"
3#include "memorydialog.h" 3#include "memorydialog.h"
4 4
5#include <qheader.h> 5#include <qheader.h>
6 6
7Budget *budget = new Budget (); 7Budget *budget = new Budget ();
8Preferences *preferences = new Preferences (); 8Preferences *preferences = new Preferences ();
9Account *account = new Account (); 9Account *account = new Account ();
10Transaction *transaction = new Transaction (); 10Transaction *transaction = new Transaction ();
11Transfer *transfer = new Transfer (); 11Transfer *transfer = new Transfer ();
12Memory *memory = new Memory (); 12Memory *memory = new Memory ();
13 13
14QashMoney::QashMoney () : QWidget () 14QashMoney::QashMoney () : QWidget ()
15 { 15 {
16 preferences->addPreferences (); 16 preferences->addPreferences ();
17 preferences->initializeColumnPreferences (); 17 preferences->initializeColumnPreferences ();
18 preferences->initializeSortingPreferences (); 18 preferences->initializeSortingPreferences ();
19 19
20 // set the text in the upper part of the frame 20 // set the text in the upper part of the frame
21 setCaption ( tr ( "QashMoney" ) ); 21 setCaption ( tr ( "QashMoney" ) );
22 22
23 // Create new menubar for our mainwindow 23 // Create new menubar for our mainwindow
24 // and add menu items 24 // and add menu items
25 mainmenu = new QMenuBar ( this ); 25 mainmenu = new QMenuBar ( this );
26 mainmenu->setFrameStyle ( QFrame::PopupPanel | QFrame::Raised ); 26 mainmenu->setFrameStyle ( QFrame::PopupPanel | QFrame::Raised );
27 preferencesmenu = new QPopupMenu ( this ); 27 preferencesmenu = new QPopupMenu ( this );
28 utilitiesmenu = new QPopupMenu ( this ); 28 utilitiesmenu = new QPopupMenu ( this );
29 mainmenu->insertItem ( "Preferences", preferencesmenu ); 29 mainmenu->insertItem ( "Preferences", preferencesmenu );
30 mainmenu->insertItem ( "Utilities", utilitiesmenu ); 30 mainmenu->insertItem ( "Utilities", utilitiesmenu );
31 preferencesmenu->insertItem ( "Date", this, SLOT ( displayDatePreferencesDialog () ) ); 31 preferencesmenu->insertItem ( "Date", this, SLOT ( displayDatePreferencesDialog() ) );
32 preferencesmenu->insertItem ( "Account", this, SLOT ( displayAccountPreferencesDialog () ) ); 32 preferencesmenu->insertItem ( "Account", this, SLOT ( displayAccountPreferencesDialog() ) );
33 preferencesmenu->insertItem ( "Transaction", this, SLOT ( displayTransactionPreferencesDialog () ) ); 33 preferencesmenu->insertItem ( "Transaction", this, SLOT ( displayTransactionPreferencesDialog() ) );
34 utilitiesmenu->insertItem ( "Memory", this, SLOT ( displayMemoryDialog () ) ); 34 utilitiesmenu->insertItem ( "Memory", this, SLOT ( displayMemoryDialog() ) );
35 35
36 // create the main tabwidget for displaying accounts and transactions 36 // create the main tabwidget for displaying accounts and transactions
37 maintabs = new QTabWidget ( this ); 37 maintabs = new QTabWidget ( this );
38 tab = new QWidget ( this ); 38 tab = new QWidget ( this );
39 tab_2 = new QWidget ( this ); 39 tab_2 = new QWidget ( this );
40 tab_3 = new QWidget ( this ); 40 tab_3 = new QWidget ( this );
41 maintabs->addTab ( tab, "Accounts" ); 41 maintabs->addTab ( tab, "Accounts" );
42 maintabs->addTab ( tab_2, "Transactions" ); 42 maintabs->addTab ( tab_2, "Transactions" );
43 maintabs->addTab ( tab_3, "Budgets" ); 43 maintabs->addTab ( tab_3, "Budgets" );
44 tabheight = tab->height(); 44 tabheight = tab->height();
45 maintabs->setTabEnabled ( tab_2, FALSE ); 45 maintabs->setTabEnabled ( tab_2, FALSE );
46 46
47 // create a new account display object 47 // create a new account display object
48 accountdisplay = new AccountDisplay ( maintabs ); 48 accountdisplay = new AccountDisplay ( maintabs );
49 accountdisplay->setTabs ( tab_2, maintabs ); 49 accountdisplay->setTabs ( tab_2, maintabs );
50 connect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( setTransactionTab () ) ); 50 connect ( accountdisplay->listview, SIGNAL ( selectionChanged() ), this, SLOT ( setTransactionTab() ) );
51 51
52 // set the connection to disable the one touch account viewing if we are transfering money 52 // set the connection to disable the one touch account viewing if we are transfering money
53 connect ( accountdisplay->transferbutton, SIGNAL ( toggled ( bool ) ), this, SLOT ( toggleOneTouchViewing ( bool ) ) ); 53 connect ( accountdisplay->transferbutton, SIGNAL ( toggled(bool) ), this, SLOT ( toggleOneTouchViewing(bool) ) );
54 54
55 // create a new transactiondisplay object 55 // create a new transactiondisplay object
56 transactiondisplay = new TransactionDisplay ( maintabs ); 56 transactiondisplay = new TransactionDisplay ( maintabs );
57 transactiondisplay->hide(); 57 transactiondisplay->hide();
58 58
59 // create new budgetdisplay object 59 // create new budgetdisplay object
60 budgetdisplay = new BudgetDisplay ( maintabs ); 60 budgetdisplay = new BudgetDisplay ( maintabs );
61 budgetdisplay->hide(); 61 budgetdisplay->hide();
62 62
63 tabslayout = new QVBoxLayout ( maintabs, 4, 2 ); 63 tabslayout = new QVBoxLayout ( maintabs, 4, 2 );
64 tabslayout->addSpacing ( tabheight ); 64 tabslayout->addSpacing ( tabheight );
65 tabslayout->addWidget ( accountdisplay ); 65 tabslayout->addWidget ( accountdisplay );
66 tabslayout->addWidget ( transactiondisplay ); 66 tabslayout->addWidget ( transactiondisplay );
67 tabslayout->addWidget ( budgetdisplay ); 67 tabslayout->addWidget ( budgetdisplay );
68 68
69 // connect a change in the maintabs with changing the tab display 69 // connect a change in the maintabs with changing the tab display
70 connect ( maintabs, SIGNAL ( currentChanged ( QWidget * ) ), this, SLOT ( changeTabDisplay () ) ); 70 connect ( maintabs, SIGNAL ( currentChanged(QWidget*) ), this, SLOT ( changeTabDisplay() ) );
71 71
72 // create layout that will contain the menubar and the maintabs 72 // create layout that will contain the menubar and the maintabs
73 layout = new QVBoxLayout ( this, 2, 2 ); 73 layout = new QVBoxLayout ( this, 2, 2 );
74 layout->setMenuBar ( mainmenu ); 74 layout->setMenuBar ( mainmenu );
75 layout->addWidget ( maintabs ); 75 layout->addWidget ( maintabs );
76 } 76 }
77 77
78QashMoney::~QashMoney () 78QashMoney::~QashMoney ()
79 { 79 {
80 delete budget; 80 delete budget;
81 delete preferences; 81 delete preferences;
82 delete account; 82 delete account;
83 delete transaction; 83 delete transaction;
84 delete transfer; 84 delete transfer;
85 delete memory; 85 delete memory;
86 } 86 }
87 87
88void QashMoney::changeTabDisplay () 88void QashMoney::changeTabDisplay ()
89 { 89 {
90 // if the user pressed the transactions tab, hide the account display 90 // if the user pressed the transactions tab, hide the account display
91 // object and create a new transaction display 91 // object and create a new transaction display
92 if ( maintabs->currentPageIndex() == 1 ) 92 if ( maintabs->currentPageIndex() == 1 )
93 { 93 {
94 // initialize variables 94 // initialize variables
95 bool children = FALSE; 95 bool children = FALSE;
96 96
97 // hide the account display and define accountid 97 // hide the account display and define accountid
98 int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt(); 98 int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt();
99 99
100 //remove all the columns from the transactiondisplay 100 //remove all the columns from the transactiondisplay
101 int columns = transactiondisplay->listview->columns(); 101 int columns = transactiondisplay->listview->columns();
102 int counter; 102 int counter;
103 for ( counter = 0; counter <= columns; counter++ ) 103 for ( counter = 0; counter <= columns; counter++ )
104 transactiondisplay->listview->removeColumn ( 0 ); 104 transactiondisplay->listview->removeColumn ( 0 );
105 105
106 // set the account name and account balance 106 // set the account name and account balance
107 QString name = account->getAccountName ( accountid ); 107 QString name = account->getAccountName ( accountid );
108 QString balance = account->getAccountBalance ( accountid ); 108 QString balance = account->getAccountBalance ( accountid );
109 transactiondisplay->name->setText ( name ); 109 transactiondisplay->name->setText ( name );
110 transactiondisplay->balance->setText ( balance ); 110 transactiondisplay->balance->setText ( balance );
111 111
112 // clear the limitbox 112 // clear the limitbox
113 transactiondisplay->limitbox->clear(); 113 transactiondisplay->limitbox->clear();
114 114
115 // get parent account id 115 // get parent account id
116 int parentaccountid = account->getParentAccountID ( accountid ); 116 int parentaccountid = account->getParentAccountID ( accountid );
117 117
118 // add columns based on which account is selected 118 // add columns based on which account is selected
119 // this first if determines if we selected a parent with no children or a child 119 // this first if determines if we selected a parent with no children or a child
120 // in these cases, we add standard three columns for date, transaction, amount 120 // in these cases, we add standard three columns for date, transaction, amount
121 transactiondisplay->listview->addColumn ( "Date", 0 ); 121 transactiondisplay->listview->addColumn ( "Date", 0 );
122 transactiondisplay->listview->addColumn ( "Transaction", 0 ); 122 transactiondisplay->listview->addColumn ( "Transaction", 0 );
123 transactiondisplay->listview->addColumn ( "Amt", 0); 123 transactiondisplay->listview->addColumn ( "Amt", 0);
124 transactiondisplay->listview->setColumnAlignment ( 2, Qt::AlignRight ); 124 transactiondisplay->listview->setColumnAlignment ( 2, Qt::AlignRight );
125 transactiondisplay->listview->addColumn ( "", 0 ); 125 transactiondisplay->listview->addColumn ( "", 0 );
126 126
127 if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) // we selected a parent with children 127 if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) // we selected a parent with children
128 { 128 {
129 // add an extra column for the account name for eac child transaction 129 // add an extra column for the account name for eac child transaction
130 transactiondisplay->listview->addColumn ( "Acct", 0 ); 130 transactiondisplay->listview->addColumn ( "Acct", 0 );
131 children = TRUE; 131 children = TRUE;
132 132
133 // hide the new transaction button 133 // hide the new transaction button
134 transactiondisplay->newtransaction->setEnabled ( FALSE ); 134 transactiondisplay->newtransaction->setEnabled ( FALSE );
135 } 135 }
136 else //we selected a parent without children or a child 136 else //we selected a parent without children or a child
137 transactiondisplay->newtransaction->setEnabled ( TRUE ); 137 transactiondisplay->newtransaction->setEnabled ( TRUE );
138 138
139 // disable the transactionid column so it can't be red 139 // disable the transactionid column so it can't be red
140 transactiondisplay->listview->header()->setResizeEnabled ( FALSE, 3 ); 140 transactiondisplay->listview->header()->setResizeEnabled ( FALSE, 3 );
141 141
142 // set the accountid and children variables 142 // set the accountid and children variables
143 transactiondisplay->setChildren ( children ); 143 transactiondisplay->setChildren ( children );
144 transactiondisplay->setAccountID ( accountid ); 144 transactiondisplay->setAccountID ( accountid );
145 145
146 setTransactionDisplayDate (); 146 setTransactionDisplayDate ();
147 147
148 // display transactions 148 // display transactions
149 transactiondisplay->listview->clear(); 149 transactiondisplay->listview->clear();
150 QString displaytext = "%"; 150 QString displaytext = "%";
151 displaytext.prepend ( transactiondisplay->limitbox->text() ); 151 displaytext.prepend ( transactiondisplay->limitbox->text() );
152 if ( transaction->getNumberOfTransactions() > 0 ) 152 if ( transaction->getNumberOfTransactions() > 0 )
153 transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate ); 153 transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate );
154 154
155 // display transfers 155 // display transfers
156 transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate ); 156 transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate );
157 157
158 // open a new preferences object and resize the transaction display columns 158 // open a new preferences object and resize the transaction display columns
159 // each column will have a different size based on whether we are looking at a child 159 // each column will have a different size based on whether we are looking at a child
160 // account or children through a parent 160 // account or children through a parent
161 if ( parentaccountid != -1 || accountdisplay->listview->selectedItem()->childCount() == 0 ) // a parent with no children or a child - three columns 161 if ( parentaccountid != -1 || accountdisplay->listview->selectedItem()->childCount() == 0 ) // a parent with no children or a child - three columns
162 { 162 {
163 transactiondisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 3 ) ); // normal transaction date width 163 transactiondisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 3 ) ); // normal transaction date width
164 transactiondisplay->listview->setColumnWidthMode ( 0, QListView::Manual ); 164 transactiondisplay->listview->setColumnWidthMode ( 0, QListView::Manual );
165 transactiondisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 4 ) ); // normal transaction name width 165 transactiondisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 4 ) ); // normal transaction name width
166 transactiondisplay->listview->setColumnWidthMode ( 1, QListView::Manual ); 166 transactiondisplay->listview->setColumnWidthMode ( 1, QListView::Manual );
167 transactiondisplay->listview->setColumnWidth ( 2, preferences->getColumnPreference ( 5 ) ); // normal transaction amount width 167 transactiondisplay->listview->setColumnWidth ( 2, preferences->getColumnPreference ( 5 ) ); // normal transaction amount width
168 transactiondisplay->listview->setColumnWidthMode ( 2, QListView::Manual ); 168 transactiondisplay->listview->setColumnWidthMode ( 2, QListView::Manual );
169 } 169 }
170 else 170 else
171 { 171 {
172 transactiondisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 6 ) ); // extended transaction date width 172 transactiondisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 6 ) ); // extended transaction date width
173 transactiondisplay->listview->setColumnWidthMode ( 0, QListView::Manual ); 173 transactiondisplay->listview->setColumnWidthMode ( 0, QListView::Manual );
174 transactiondisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 7 ) ); // extended transaction name width 174 transactiondisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 7 ) ); // extended transaction name width
175 transactiondisplay->listview->setColumnWidthMode ( 1, QListView::Manual ); 175 transactiondisplay->listview->setColumnWidthMode ( 1, QListView::Manual );
176 transactiondisplay->listview->setColumnWidth ( 2, preferences->getColumnPreference ( 8 ) ); // extended transaction amount width 176 transactiondisplay->listview->setColumnWidth ( 2, preferences->getColumnPreference ( 8 ) ); // extended transaction amount width
177 transactiondisplay->listview->setColumnWidthMode ( 2, QListView::Manual ); 177 transactiondisplay->listview->setColumnWidthMode ( 2, QListView::Manual );
178 transactiondisplay->listview->setColumnWidth ( 4, preferences->getColumnPreference ( 9 ) ); // transaction account width 178 transactiondisplay->listview->setColumnWidth ( 4, preferences->getColumnPreference ( 9 ) ); // transaction account width
179 transactiondisplay->listview->setColumnWidthMode ( 4, QListView::Manual ); 179 transactiondisplay->listview->setColumnWidthMode ( 4, QListView::Manual );
180 } 180 }
181 181
182 // pull the column sorting preference from the preferences table, and configure the listview accordingly 182 // pull the column sorting preference from the preferences table, and configure the listview accordingly
183 int column = 0; 183 int column = 0;
184 int direction = 0; 184 int direction = 0;
185 preferences->getSortingPreference ( 2, &column, &direction ); 185 preferences->getSortingPreference ( 2, &column, &direction );
186 transactiondisplay->listview->setSorting ( column, direction ); 186 transactiondisplay->listview->setSorting ( column, direction );
187 187
188 // show the window 188 // show the window
189 transactiondisplay->show(); 189 transactiondisplay->show();
190 // hide the account display and define accountid 190 // hide the account display and define accountid
191 accountdisplay->hide(); 191 accountdisplay->hide();
192 // hide the budget display 192 // hide the budget display
193 budgetdisplay->hide(); 193 budgetdisplay->hide();
194 } 194 }
195 else if ( maintabs->currentPageIndex() == 0 ) 195 else if ( maintabs->currentPageIndex() == 0 )
196 { 196 {
197 disableOneTouchViewing(); 197 disableOneTouchViewing();
198 198
199 // clear the account display selection 199 // clear the account display selection
200 accountdisplay->listview->clearSelection(); 200 accountdisplay->listview->clearSelection();
201 201
202 // resize the account display columns 202 // resize the account display columns
203 accountdisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 1 ) ); 203 accountdisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 1 ) );
204 accountdisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 2 ) ); 204 accountdisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 2 ) );
205 205
206 // set sorting preference on account display columns 206 // set sorting preference on account display columns
207 int column = 0; 207 int column = 0;
208 int direction = 0; 208 int direction = 0;
209 preferences->getSortingPreference ( 1, &column, &direction ); 209 preferences->getSortingPreference ( 1, &column, &direction );
210 accountdisplay->listview->setSorting ( column, direction ); 210 accountdisplay->listview->setSorting ( column, direction );
211 211
212 // display the accounts 212 // display the accounts
213 if ( account->getNumberOfAccounts() != 0 ) 213 if ( account->getNumberOfAccounts() != 0 )
214 account->displayAccounts ( accountdisplay->listview ); 214 account->displayAccounts ( accountdisplay->listview );
215 maintabs->setTabEnabled ( tab_2, FALSE ); 215 maintabs->setTabEnabled ( tab_2, FALSE );
216 216
217 // set the toggle button 217 // set the toggle button
218 accountdisplay->setToggleButton (); 218 accountdisplay->setToggleButton ();
219 219
220 // show the account display 220 // show the account display
221 accountdisplay->show(); 221 accountdisplay->show();
222 222
223 // hide the transaction display 223 // hide the transaction display
224 transactiondisplay->hide(); 224 transactiondisplay->hide();
225 225
226 // hide the budget display 226 // hide the budget display
227 budgetdisplay->hide(); 227 budgetdisplay->hide();
228 228
229 229
230 enableOneTouchViewing (); 230 enableOneTouchViewing ();
231 } 231 }
232 else 232 else
233 { 233 {
234 budgetdisplay->displayLineItems(); 234 budgetdisplay->displayLineItems();
235 budgetdisplay->show(); 235 budgetdisplay->show();
236 transactiondisplay->hide(); 236 transactiondisplay->hide();
237 accountdisplay->hide(); 237 accountdisplay->hide();
238 } 238 }
239 } 239 }
240 240
241void QashMoney::setTransactionTab () 241void QashMoney::setTransactionTab ()
242 { 242 {
243 if ( accountdisplay->listview->selectedItem() == 0 ) 243 if ( accountdisplay->listview->selectedItem() == 0 )
244 maintabs->setTabEnabled ( tab_2, FALSE ); 244 maintabs->setTabEnabled ( tab_2, FALSE );
245 else 245 else
246 maintabs->setTabEnabled ( tab_2, TRUE ); 246 maintabs->setTabEnabled ( tab_2, TRUE );
247 } 247 }
248 248
249void QashMoney::displayDatePreferencesDialog () 249void QashMoney::displayDatePreferencesDialog ()
250 { 250 {
251 // this shows a dialog to set preferences for formatting the date 251 // this shows a dialog to set preferences for formatting the date
252 DatePreferences *pd = new DatePreferences ( this ); 252 DatePreferences *pd = new DatePreferences ( this );
253 pd->exec (); 253 pd->exec ();
254 if ( transactiondisplay->isVisible() ) 254 if ( transactiondisplay->isVisible() )
255 { 255 {
256 // set the account id 256 // set the account id
257 int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt(); 257 int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt();
258 258
259 // set children so we can let displayTransfers know if there are children for the selected account 259 // set children so we can let displayTransfers know if there are children for the selected account
260 bool children; 260 bool children;
261 if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) 261 if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 )
262 children = TRUE; 262 children = TRUE;
263 else 263 else
264 children = FALSE; 264 children = FALSE;
265 265
266 // redisplay transactions if they are visible incorporating 266 // redisplay transactions if they are visible incorporating
267 // any changes to the date format 267 // any changes to the date format
268 transactiondisplay->listview->clear(); 268 transactiondisplay->listview->clear();
269 QString displaytext = "%"; 269 QString displaytext = "%";
270 displaytext.prepend ( transactiondisplay->limitbox->text() ); 270 displaytext.prepend ( transactiondisplay->limitbox->text() );
271 271
272 setTransactionDisplayDate(); 272 setTransactionDisplayDate();
273 if ( transaction->getNumberOfTransactions() > 0 ) 273 if ( transaction->getNumberOfTransactions() > 0 )
274 transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate ); 274 transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate );
275 275
276 if ( transfer->getNumberOfTransfers() != 0 ) 276 if ( transfer->getNumberOfTransfers() != 0 )
277 transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate ); 277 transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate );
278 } 278 }
279 else if ( accountdisplay->isVisible() ) 279 else if ( accountdisplay->isVisible() )
280 { 280 {
281 accountdisplay->listview->clearSelection(); 281 accountdisplay->listview->clearSelection();
282 maintabs->setTabEnabled ( tab_2, FALSE ); 282 maintabs->setTabEnabled ( tab_2, FALSE );
283 } 283 }
284 else 284 else
285 budgetdisplay->updateBudgetInformation(); 285 budgetdisplay->updateBudgetInformation();
286 } 286 }
287 287
288void QashMoney::displayTransactionPreferencesDialog () 288void QashMoney::displayTransactionPreferencesDialog ()
289 { 289 {
290 // display a dialog for setting preferences for transactions 290 // display a dialog for setting preferences for transactions
291 TransactionPreferences *td = new TransactionPreferences ( this ); 291 TransactionPreferences *td = new TransactionPreferences ( this );
292 td->exec (); 292 td->exec ();
293 if ( transactiondisplay->isVisible() ) 293 if ( transactiondisplay->isVisible() )
294 { 294 {
295 // set the account id 295 // set the account id
296 int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt(); 296 int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt();
297 297
298 // set children so we can let displayTransfers know if there are children for the selected account 298 // set children so we can let displayTransfers know if there are children for the selected account
299 bool children; 299 bool children;
300 if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) 300 if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 )
301 children = TRUE; 301 children = TRUE;
302 else 302 else
303 children = FALSE; 303 children = FALSE;
304 304
305 // redisplay transactions incorporating any transaction preference changes 305 // redisplay transactions incorporating any transaction preference changes
306 transactiondisplay->listview->clear(); 306 transactiondisplay->listview->clear();
307 QString displaytext = "%"; 307 QString displaytext = "%";
308 displaytext.prepend ( transactiondisplay->limitbox->text() ); 308 displaytext.prepend ( transactiondisplay->limitbox->text() );
309 309
310 setTransactionDisplayDate(); 310 setTransactionDisplayDate();
311 if ( transaction->getNumberOfTransactions() > 0 ) 311 if ( transaction->getNumberOfTransactions() > 0 )
312 transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate ); 312 transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate );
313 313
314 if ( transfer->getNumberOfTransfers() != 0 ) 314 if ( transfer->getNumberOfTransfers() != 0 )
315 transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate ); 315 transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate );
316 } 316 }
317 else 317 else
318 { 318 {
319 accountdisplay->listview->clearSelection(); 319 accountdisplay->listview->clearSelection();
320 maintabs->setTabEnabled ( tab_2, FALSE ); 320 maintabs->setTabEnabled ( tab_2, FALSE );
321 } 321 }
322 } 322 }
323 323
324void QashMoney::displayAccountPreferencesDialog () 324void QashMoney::displayAccountPreferencesDialog ()
325 { 325 {
326 // display a dialog for setting preferences for accounts 326 // display a dialog for setting preferences for accounts
327 AccountPreferences *ap = new AccountPreferences ( this ); 327 AccountPreferences *ap = new AccountPreferences ( this );
328 ap->exec (); 328 ap->exec ();
329 329
330 if ( accountdisplay->isVisible() && account->getNumberOfAccounts() != 0 ) 330 if ( accountdisplay->isVisible() && account->getNumberOfAccounts() != 0 )
331 { 331 {
332 accountdisplay->listview->clear(); 332 accountdisplay->listview->clear();
333 account->displayAccounts ( accountdisplay->listview ); 333 account->displayAccounts ( accountdisplay->listview );
334 accountdisplay->listview->clearSelection(); 334 accountdisplay->listview->clearSelection();
335 maintabs->setTabEnabled ( tab_2, FALSE ); 335 maintabs->setTabEnabled ( tab_2, FALSE );
336 } 336 }
337 changeTabDisplay(); 337 changeTabDisplay();
338 } 338 }
339 339
340void QashMoney::displayMemoryDialog () 340void QashMoney::displayMemoryDialog ()
341 { 341 {
342 // opens a dialog to add, edit and delete memory items 342 // opens a dialog to add, edit and delete memory items
343 MemoryDialog *md = new MemoryDialog (); 343 MemoryDialog *md = new MemoryDialog ();
344 md->exec(); 344 md->exec();
345 } 345 }
346 346
347void QashMoney::showTransactions () 347void QashMoney::showTransactions ()
348 { 348 {
349 maintabs->setCurrentPage ( 1 ); 349 maintabs->setCurrentPage ( 1 );
350 } 350 }
351 351
352void QashMoney::enableOneTouchViewing () 352void QashMoney::enableOneTouchViewing ()
353 { 353 {
354 if ( preferences->getPreference ( 5 ) == 1 ) 354 if ( preferences->getPreference ( 5 ) == 1 )
355 connect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( showTransactions () ) ); 355 connect ( accountdisplay->listview, SIGNAL ( selectionChanged() ), this, SLOT ( showTransactions() ) );
356 else 356 else
357 disconnect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( showTransactions () ) ); 357 disconnect ( accountdisplay->listview, SIGNAL ( selectionChanged() ), this, SLOT ( showTransactions() ) );
358 } 358 }
359 359
360void QashMoney::disableOneTouchViewing () 360void QashMoney::disableOneTouchViewing ()
361 { 361 {
362 disconnect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( showTransactions () ) ); 362 disconnect ( accountdisplay->listview, SIGNAL ( selectionChanged() ), this, SLOT ( showTransactions() ) );
363 } 363 }
364 364
365void QashMoney::toggleOneTouchViewing ( bool state ) 365void QashMoney::toggleOneTouchViewing ( bool state )
366 { 366 {
367 if ( state == TRUE ) 367 if ( state == TRUE )
368 disableOneTouchViewing(); 368 disableOneTouchViewing();
369 else 369 else
370 enableOneTouchViewing(); 370 enableOneTouchViewing();
371 } 371 }
372 372
373void QashMoney::setTransactionDisplayDate () 373void QashMoney::setTransactionDisplayDate ()
374 { 374 {
375 // determine how many days of transactions to show 375 // determine how many days of transactions to show
376 int limittype = preferences->getPreference ( 7 ); 376 int limittype = preferences->getPreference ( 7 );
377 if ( limittype != 5 ) // set today's date if we are not showing all transactions 377 if ( limittype != 5 ) // set today's date if we are not showing all transactions
378 { 378 {
379 QDate today = QDate::currentDate (); 379 QDate today = QDate::currentDate ();
380 switch ( limittype ) // if we are not showing all transactions 380 switch ( limittype ) // if we are not showing all transactions
381 { 381 {
382 case 0: // viewing two weeks 382 case 0: // viewing two weeks
383 newdate = today.addDays ( -14 ); 383 newdate = today.addDays ( -14 );
384 break; 384 break;
385 case 1: // viewing one month 385 case 1: // viewing one month
386 newdate = today.addDays ( -30 ); 386 newdate = today.addDays ( -30 );
387 break; 387 break;
388 case 2: // three months 388 case 2: // three months
389 newdate = today.addDays ( -90 ); 389 newdate = today.addDays ( -90 );
390 break; 390 break;
391 case 3: // six months 391 case 3: // six months
392 newdate = today.addDays ( -180 ); 392 newdate = today.addDays ( -180 );
393 break; 393 break;
394 case 4: // one year 394 case 4: // one year
395 newdate = today.addDays ( -365 ); 395 newdate = today.addDays ( -365 );
396 break; 396 break;
397 } 397 }
398 } 398 }
399 else 399 else
400 newdate = QDate ( 1900, 1, 1 ); 400 newdate = QDate ( 1900, 1, 1 );
401 } 401 }
402 402
diff --git a/noncore/apps/qashmoney/transactiondisplay.cpp b/noncore/apps/qashmoney/transactiondisplay.cpp
index 474f11e..0b94d62 100755
--- a/noncore/apps/qashmoney/transactiondisplay.cpp
+++ b/noncore/apps/qashmoney/transactiondisplay.cpp
@@ -1,625 +1,625 @@
1#include "transactiondisplay.h" 1#include "transactiondisplay.h"
2#include "newtransaction.h" 2#include "newtransaction.h"
3#include "account.h" 3#include "account.h"
4#include "budget.h" 4#include "budget.h"
5#include "memory.h" 5#include "memory.h"
6#include "transfer.h" 6#include "transfer.h"
7#include "calculator.h" 7#include "calculator.h"
8#include "datepicker.h" 8#include "datepicker.h"
9 9
10#include <qmessagebox.h> 10#include <qmessagebox.h>
11#include <qheader.h> 11#include <qheader.h>
12#include <qmultilineedit.h> 12#include <qmultilineedit.h>
13 13
14extern Transaction *transaction; 14extern Transaction *transaction;
15extern Budget *budget; 15extern Budget *budget;
16extern Account *account; 16extern Account *account;
17extern Preferences *preferences; 17extern Preferences *preferences;
18extern Memory *memory; 18extern Memory *memory;
19extern Transfer *transfer; 19extern Transfer *transfer;
20 20
21TransactionDisplay::TransactionDisplay ( QWidget* parent ) : QWidget ( parent ) 21TransactionDisplay::TransactionDisplay ( QWidget* parent ) : QWidget ( parent )
22 { 22 {
23 // set transactiondisplay variables; 23 // set transactiondisplay variables;
24 accountid = 0; 24 accountid = 0;
25 children = TRUE; 25 children = TRUE;
26 26
27 firstline = new QHBox ( this ); 27 firstline = new QHBox ( this );
28 firstline->setSpacing ( 2 ); 28 firstline->setSpacing ( 2 );
29 29
30 newtransaction = new QPushButton ( firstline ); 30 newtransaction = new QPushButton ( firstline );
31 newtransaction->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") ); 31 newtransaction->setPixmap ( QPixmap ("/opt/QtPalmtop/pics/new.png") );
32 connect ( newtransaction, SIGNAL ( released () ), this, SLOT ( addTransaction () ) ); 32 connect ( newtransaction, SIGNAL ( released() ), this, SLOT ( addTransaction() ) );
33 33
34 edittransaction = new QPushButton ( firstline ); 34 edittransaction = new QPushButton ( firstline );
35 edittransaction->setPixmap( QPixmap ("/opt/QtPalmtop/pics/edit.png") ); 35 edittransaction->setPixmap( QPixmap ("/opt/QtPalmtop/pics/edit.png") );
36 connect ( edittransaction, SIGNAL ( released () ), this, SLOT ( checkListViewEdit () ) ); 36 connect ( edittransaction, SIGNAL ( released() ), this, SLOT ( checkListViewEdit() ) );
37 37
38 deletetransaction = new QPushButton ( firstline ); 38 deletetransaction = new QPushButton ( firstline );
39 deletetransaction->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") ); 39 deletetransaction->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/delete.png") );
40 connect ( deletetransaction, SIGNAL ( released () ), this, SLOT ( checkListViewDelete () ) ); 40 connect ( deletetransaction, SIGNAL ( released() ), this, SLOT ( checkListViewDelete() ) );
41 41
42 toggletransaction = new QPushButton ( firstline ); 42 toggletransaction = new QPushButton ( firstline );
43 toggletransaction->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/redo.png") ); 43 toggletransaction->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/redo.png") );
44 connect ( toggletransaction, SIGNAL ( released () ), this, SLOT ( checkListViewToggle () ) ); 44 connect ( toggletransaction, SIGNAL ( released() ), this, SLOT ( checkListViewToggle() ) );
45 45
46 viewtransactionnotes = new QPushButton ( firstline ); 46 viewtransactionnotes = new QPushButton ( firstline );
47 viewtransactionnotes->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/info.png") ); 47 viewtransactionnotes->setPixmap( QPixmap ( "/opt/QtPalmtop/pics/info.png") );
48 connect ( viewtransactionnotes, SIGNAL ( released () ), this, SLOT ( showTransactionNotes () ) ); 48 connect ( viewtransactionnotes, SIGNAL ( released() ), this, SLOT ( showTransactionNotes() ) );
49 49
50 secondline = new QHBox ( this ); 50 secondline = new QHBox ( this );
51 secondline->setSpacing ( 5 ); 51 secondline->setSpacing ( 5 );
52 52
53 name = new QLabel ( secondline ); 53 name = new QLabel ( secondline );
54 balance = new QLabel ( secondline ); 54 balance = new QLabel ( secondline );
55 55
56 QLabel *limit = new QLabel ( "Limit", secondline ); 56 QLabel *limit = new QLabel ( "Limit", secondline );
57 limitbox = new QLineEdit ( secondline ); 57 limitbox = new QLineEdit ( secondline );
58 limitbox->setMinimumWidth ( ( int ) ( this->width() / 6 ) ); 58 limitbox->setMinimumWidth ( ( int ) ( this->width() / 6 ) );
59 connect ( limitbox, SIGNAL ( textChanged ( const QString & ) ), this, SLOT ( limitDisplay ( const QString & ) ) ); 59 connect ( limitbox, SIGNAL ( textChanged(const QString&) ), this, SLOT ( limitDisplay(const QString&) ) );
60 60
61 listview = new QListView ( this ); 61 listview = new QListView ( this );
62 listview->setAllColumnsShowFocus ( TRUE ); 62 listview->setAllColumnsShowFocus ( TRUE );
63 listview->setShowSortIndicator ( TRUE ); 63 listview->setShowSortIndicator ( TRUE );
64 listview->header()->setTracking ( FALSE ); 64 listview->header()->setTracking ( FALSE );
65 connect ( listview->header(), SIGNAL ( sizeChange ( int, int, int ) ), this, SLOT ( saveColumnSize ( int, int, int ) ) ); 65 connect ( listview->header(), SIGNAL ( sizeChange(int,int,int) ), this, SLOT ( saveColumnSize(int,int,int) ) );
66 connect ( listview->header(), SIGNAL ( clicked ( int ) ), this, SLOT ( saveSortingPreference ( int ) ) ); 66 connect ( listview->header(), SIGNAL ( clicked(int) ), this, SLOT ( saveSortingPreference(int) ) );
67 67
68 layout = new QVBoxLayout ( this, 2, 2 ); 68 layout = new QVBoxLayout ( this, 2, 2 );
69 layout->addWidget ( firstline ); 69 layout->addWidget ( firstline );
70 layout->addWidget ( secondline ); 70 layout->addWidget ( secondline );
71 layout->addWidget ( listview ); 71 layout->addWidget ( listview );
72 } 72 }
73 73
74void TransactionDisplay::addTransaction () 74void TransactionDisplay::addTransaction ()
75 { 75 {
76 // create local variables 76 // create local variables
77 int cleared = -1; 77 int cleared = -1;
78 78
79 // create new transaction window 79 // create new transaction window
80 NewTransaction *newtransaction = new NewTransaction ( this ); 80 NewTransaction *newtransaction = new NewTransaction ( this );
81 int width = this->size().width(); 81 int width = this->size().width();
82 newtransaction->transactionname->setMaximumWidth ( ( int ) ( width * 0.45 ) ); 82 newtransaction->transactionname->setMaximumWidth ( ( int ) ( width * 0.45 ) );
83 newtransaction->transactionname->setMinimumWidth ( ( int ) ( width * 0.35 ) ); 83 newtransaction->transactionname->setMinimumWidth ( ( int ) ( width * 0.35 ) );
84 newtransaction->lineitembox->setMaximumWidth ( ( int ) ( width * 0.45 ) ); 84 newtransaction->lineitembox->setMaximumWidth ( ( int ) ( width * 0.45 ) );
85 newtransaction->transactiondatebox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 85 newtransaction->transactiondatebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
86 newtransaction->transactionamountbox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 86 newtransaction->transactionamountbox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
87 newtransaction->transactionnumber->setMaximumWidth ( ( int ) ( width * 0.25 ) ); 87 newtransaction->transactionnumber->setMaximumWidth ( ( int ) ( width * 0.25 ) );
88 88
89 // enter today's date in the date box as defaul 89 // enter today's date in the date box as defaul
90 QDate today = QDate::currentDate (); 90 QDate today = QDate::currentDate ();
91 int defaultday = today.day(); 91 int defaultday = today.day();
92 int defaultmonth = today.month(); 92 int defaultmonth = today.month();
93 int defaultyear = today.year(); 93 int defaultyear = today.year();
94 newtransaction->transactiondate->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) ); 94 newtransaction->transactiondate->setText ( preferences->getDate ( defaultyear, defaultmonth, defaultday ) );
95 95
96 // add memory items to the transactionname combobox 96 // add memory items to the transactionname combobox
97 memory->displayMemoryItems ( newtransaction->transactionname ); 97 memory->displayMemoryItems ( newtransaction->transactionname );
98 newtransaction->transactionname->insertItem ( "", 0 ); 98 newtransaction->transactionname->insertItem ( "", 0 );
99 99
100 if ( newtransaction->exec () == QDialog::Accepted ) 100 if ( newtransaction->exec () == QDialog::Accepted )
101 { 101 {
102 if ( newtransaction->clearedcheckbox->isChecked () == TRUE ) // set a parent id and type for a child transaction 102 if ( newtransaction->clearedcheckbox->isChecked () == TRUE ) // set a parent id and type for a child transaction
103 cleared = 1; 103 cleared = 1;
104 else 104 else
105 cleared = 0; 105 cleared = 0;
106 106
107 float amount = newtransaction->transactionamount->text().toFloat(); 107 float amount = newtransaction->transactionamount->text().toFloat();
108 if ( newtransaction->depositbox->isChecked() == FALSE ) 108 if ( newtransaction->depositbox->isChecked() == FALSE )
109 amount = amount * -1; 109 amount = amount * -1;
110 110
111 // add the transaction name to the memory items 111 // add the transaction name to the memory items
112 memory->addMemoryItem ( newtransaction->transactionname->currentText() ); 112 memory->addMemoryItem ( newtransaction->transactionname->currentText() );
113 113
114 // add the transaction 114 // add the transaction
115 if ( newtransaction->getDateEdited () == TRUE ) 115 if ( newtransaction->getDateEdited () == TRUE )
116 transaction->addTransaction ( newtransaction->getDescription(), newtransaction->transactionname->currentText(), accountid, account->getParentAccountID ( accountid ), 116 transaction->addTransaction ( newtransaction->getDescription(), newtransaction->transactionname->currentText(), accountid, account->getParentAccountID ( accountid ),
117 newtransaction->transactionnumber->text().toInt(), newtransaction->getDay(), newtransaction->getMonth(), newtransaction->getYear(), amount, cleared, newtransaction->getCurrentBudget(), 117 newtransaction->transactionnumber->text().toInt(), newtransaction->getDay(), newtransaction->getMonth(), newtransaction->getYear(), amount, cleared, newtransaction->getCurrentBudget(),
118 newtransaction->getCurrentLineItem() ); 118 newtransaction->getCurrentLineItem() );
119 else 119 else
120 transaction->addTransaction ( newtransaction->getDescription(), newtransaction->transactionname->currentText(), accountid, account->getParentAccountID ( accountid ), 120 transaction->addTransaction ( newtransaction->getDescription(), newtransaction->transactionname->currentText(), accountid, account->getParentAccountID ( accountid ),
121 newtransaction->transactionnumber->text().toInt(), defaultday, defaultmonth, defaultyear, amount, cleared, newtransaction->getCurrentBudget(), newtransaction->getCurrentLineItem() ); 121 newtransaction->transactionnumber->text().toInt(), defaultday, defaultmonth, defaultyear, amount, cleared, newtransaction->getCurrentBudget(), newtransaction->getCurrentLineItem() );
122 122
123 // redisplay transactions 123 // redisplay transactions
124 listview->clear(); 124 listview->clear();
125 QString displaytext = "%"; 125 QString displaytext = "%";
126 displaytext.prepend ( limitbox->text() ); 126 displaytext.prepend ( limitbox->text() );
127 setTransactionDisplayDate (); 127 setTransactionDisplayDate ();
128 if ( transaction->getNumberOfTransactions() > 0 ) 128 if ( transaction->getNumberOfTransactions() > 0 )
129 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate ); 129 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate );
130 130
131 // redisplay transfers 131 // redisplay transfers
132 if ( transfer->getNumberOfTransfers() > 0 ) 132 if ( transfer->getNumberOfTransfers() > 0 )
133 transfer->displayTransfers ( listview, accountid, children, displaydate ); 133 transfer->displayTransfers ( listview, accountid, children, displaydate );
134 134
135 // add the transaction amount to the account it's associated with 135 // add the transaction amount to the account it's associated with
136 // and update its parent account balance if necessary 136 // and update its parent account balance if necessary
137 account->updateAccountBalance ( accountid ); 137 account->updateAccountBalance ( accountid );
138 if ( account->getParentAccountID ( accountid ) != -1 ) 138 if ( account->getParentAccountID ( accountid ) != -1 )
139 account->changeParentAccountBalance ( account->getParentAccountID ( accountid ) ); 139 account->changeParentAccountBalance ( account->getParentAccountID ( accountid ) );
140 140
141 // format then reset the account balance 141 // format then reset the account balance
142 redisplayAccountBalance (); 142 redisplayAccountBalance ();
143 } 143 }
144 } 144 }
145 145
146void TransactionDisplay::checkListViewEdit () 146void TransactionDisplay::checkListViewEdit ()
147 { 147 {
148 if ( listview->selectedItem() == 0 ) 148 if ( listview->selectedItem() == 0 )
149 QMessageBox::warning ( this, "QashMoney", "Please select a transaction\nto edit."); 149 QMessageBox::warning ( this, "QashMoney", "Please select a transaction\nto edit.");
150 else if ( listview->currentItem()->text ( getIDColumn() ).toInt() < 0 ) 150 else if ( listview->currentItem()->text ( getIDColumn() ).toInt() < 0 )
151 editTransfer (); 151 editTransfer ();
152 else 152 else
153 editTransaction(); 153 editTransaction();
154 } 154 }
155 155
156void TransactionDisplay::showCalculator () 156void TransactionDisplay::showCalculator ()
157 { 157 {
158 Calculator *calculator = new Calculator ( this ); 158 Calculator *calculator = new Calculator ( this );
159 if ( calculator->exec () == QDialog::Accepted ) 159 if ( calculator->exec () == QDialog::Accepted )
160 amount->setText ( calculator->display->text() ); 160 amount->setText ( calculator->display->text() );
161 } 161 }
162 162
163void TransactionDisplay::showCalendar () 163void TransactionDisplay::showCalendar ()
164 { 164 {
165 QDate newDate = QDate::currentDate (); 165 QDate newDate = QDate::currentDate ();
166 DatePicker *dp = new DatePicker ( newDate ); 166 DatePicker *dp = new DatePicker ( newDate );
167 if ( dp->exec () == QDialog::Accepted ) 167 if ( dp->exec () == QDialog::Accepted )
168 { 168 {
169 year = dp->getYear(); 169 year = dp->getYear();
170 month = dp->getMonth(); 170 month = dp->getMonth();
171 day = dp->getDay(); 171 day = dp->getDay();
172 date->setText ( preferences->getDate ( year, month, day ) ); 172 date->setText ( preferences->getDate ( year, month, day ) );
173 } 173 }
174 } 174 }
175 175
176void TransactionDisplay::editTransfer () 176void TransactionDisplay::editTransfer ()
177 { 177 {
178 transferid = listview->currentItem()->text ( getIDColumn() ).toInt(); 178 transferid = listview->currentItem()->text ( getIDColumn() ).toInt();
179 fromaccount = transfer->getFromAccountID ( transferid ); 179 fromaccount = transfer->getFromAccountID ( transferid );
180 toaccount = transfer->getToAccountID ( transferid ); 180 toaccount = transfer->getToAccountID ( transferid );
181 year = transfer->getYear ( transferid ); 181 year = transfer->getYear ( transferid );
182 month = transfer->getMonth ( transferid ); 182 month = transfer->getMonth ( transferid );
183 day = transfer->getDay ( transferid ); 183 day = transfer->getDay ( transferid );
184 184
185 QDialog *editransfer = new QDialog ( this, "edittransfer", TRUE ); 185 QDialog *editransfer = new QDialog ( this, "edittransfer", TRUE );
186 editransfer->setCaption ( "Transfer" ); 186 editransfer->setCaption ( "Transfer" );
187 187
188 QStringList accountnames = account->getAccountNames(); 188 QStringList accountnames = account->getAccountNames();
189 QStringList accountids = account->getAccountIDs(); 189 QStringList accountids = account->getAccountIDs();
190 190
191 QLabel *fromaccountlabel = new QLabel ( "From Account:", editransfer ); 191 QLabel *fromaccountlabel = new QLabel ( "From Account:", editransfer );
192 QFont f = this->font(); 192 QFont f = this->font();
193 f.setWeight ( QFont::Bold ); 193 f.setWeight ( QFont::Bold );
194 fromaccountlabel->setFont ( f ); 194 fromaccountlabel->setFont ( f );
195 195
196 QComboBox *fromaccountbox = new QComboBox ( editransfer ); 196 QComboBox *fromaccountbox = new QComboBox ( editransfer );
197 fromaccountbox->insertStringList ( accountnames ); 197 fromaccountbox->insertStringList ( accountnames );
198 fromaccountbox->setCurrentItem ( accountids.findIndex ( QString::number ( fromaccount ) ) ); 198 fromaccountbox->setCurrentItem ( accountids.findIndex ( QString::number ( fromaccount ) ) );
199 199
200 QLabel *toaccountlabel = new QLabel ( "To Account:", editransfer ); 200 QLabel *toaccountlabel = new QLabel ( "To Account:", editransfer );
201 toaccountlabel->setFont ( f ); 201 toaccountlabel->setFont ( f );
202 202
203 QComboBox *toaccountbox = new QComboBox ( editransfer ); 203 QComboBox *toaccountbox = new QComboBox ( editransfer );
204 toaccountbox->insertStringList ( accountnames ); 204 toaccountbox->insertStringList ( accountnames );
205 toaccountbox->setCurrentItem ( accountids.findIndex ( QString::number ( toaccount ) ) ); 205 toaccountbox->setCurrentItem ( accountids.findIndex ( QString::number ( toaccount ) ) );
206 206
207 QLabel *datelabel = new QLabel ( "Date", editransfer ); 207 QLabel *datelabel = new QLabel ( "Date", editransfer );
208 QHBox *datebox = new QHBox ( editransfer ); 208 QHBox *datebox = new QHBox ( editransfer );
209 datebox->setSpacing ( 2 ); 209 datebox->setSpacing ( 2 );
210 date = new QLineEdit ( datebox ); 210 date = new QLineEdit ( datebox );
211 date->setAlignment ( Qt::AlignRight ); 211 date->setAlignment ( Qt::AlignRight );
212 date->setDisabled ( TRUE ); 212 date->setDisabled ( TRUE );
213 date->setText ( preferences->getDate ( year, month, day ) ); 213 date->setText ( preferences->getDate ( year, month, day ) );
214 QPushButton *datebutton = new QPushButton ( datebox ); 214 QPushButton *datebutton = new QPushButton ( datebox );
215 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) ); 215 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) );
216 connect ( datebutton, SIGNAL ( released () ), this, SLOT ( showCalendar () ) ); 216 connect ( datebutton, SIGNAL ( released() ), this, SLOT ( showCalendar() ) );
217 217
218 QLabel *amounttlabel = new QLabel ( "Amount", editransfer ); 218 QLabel *amounttlabel = new QLabel ( "Amount", editransfer );
219 219
220 QHBox *amountbox = new QHBox ( editransfer ); 220 QHBox *amountbox = new QHBox ( editransfer );
221 amountbox->setSpacing ( 2 ); 221 amountbox->setSpacing ( 2 );
222 amount = new QLineEdit ( amountbox ); 222 amount = new QLineEdit ( amountbox );
223 amount->setAlignment ( Qt::AlignRight ); 223 amount->setAlignment ( Qt::AlignRight );
224 amount->setText ( transfer->getAmount ( transferid ) ); 224 amount->setText ( transfer->getAmount ( transferid ) );
225 QPushButton *calculatorbutton = new QPushButton( amountbox ); 225 QPushButton *calculatorbutton = new QPushButton( amountbox );
226 calculatorbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) ); 226 calculatorbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) );
227 connect ( calculatorbutton, SIGNAL ( released() ), this, SLOT ( showCalculator() ) ); 227 connect ( calculatorbutton, SIGNAL ( released() ), this, SLOT ( showCalculator() ) );
228 228
229 QCheckBox *clearedcheckbox = new QCheckBox ( "Cleared", editransfer ); 229 QCheckBox *clearedcheckbox = new QCheckBox ( "Cleared", editransfer );
230 230
231 QBoxLayout *layout = new QVBoxLayout ( editransfer, 4, 2 ); 231 QBoxLayout *layout = new QVBoxLayout ( editransfer, 4, 2 );
232 layout->addWidget ( fromaccountlabel, Qt::AlignLeft ); 232 layout->addWidget ( fromaccountlabel, Qt::AlignLeft );
233 layout->addWidget ( fromaccountbox, Qt::AlignLeft ); 233 layout->addWidget ( fromaccountbox, Qt::AlignLeft );
234 layout->addWidget ( toaccountlabel, Qt::AlignLeft ); 234 layout->addWidget ( toaccountlabel, Qt::AlignLeft );
235 layout->addWidget ( toaccountbox, Qt::AlignLeft ); 235 layout->addWidget ( toaccountbox, Qt::AlignLeft );
236 layout->addSpacing ( 5 ); 236 layout->addSpacing ( 5 );
237 layout->addWidget ( datelabel, Qt::AlignLeft ); 237 layout->addWidget ( datelabel, Qt::AlignLeft );
238 layout->addWidget ( datebox, Qt::AlignLeft ); 238 layout->addWidget ( datebox, Qt::AlignLeft );
239 layout->addWidget ( amounttlabel, Qt::AlignLeft ); 239 layout->addWidget ( amounttlabel, Qt::AlignLeft );
240 layout->addWidget ( amountbox, Qt::AlignLeft ); 240 layout->addWidget ( amountbox, Qt::AlignLeft );
241 layout->addWidget ( clearedcheckbox, Qt::AlignLeft ); 241 layout->addWidget ( clearedcheckbox, Qt::AlignLeft );
242 242
243 if ( editransfer->exec() == QDialog::Accepted ) 243 if ( editransfer->exec() == QDialog::Accepted )
244 { 244 {
245 //get fromaccount 245 //get fromaccount
246 fromaccount = ( accountids.operator[] ( fromaccountbox->currentItem() ) ).toInt(); 246 fromaccount = ( accountids.operator[] ( fromaccountbox->currentItem() ) ).toInt();
247 247
248 //get to account 248 //get to account
249 toaccount = ( accountids.operator[] ( toaccountbox->currentItem() ) ).toInt(); 249 toaccount = ( accountids.operator[] ( toaccountbox->currentItem() ) ).toInt();
250 250
251 //set cleared flag 251 //set cleared flag
252 int cleared = 0; 252 int cleared = 0;
253 if ( clearedcheckbox->isChecked() == TRUE ) 253 if ( clearedcheckbox->isChecked() == TRUE )
254 cleared = 1; 254 cleared = 1;
255 255
256 //update transfer 256 //update transfer
257 transfer->updateTransfer ( fromaccount, account->getParentAccountID ( fromaccount ), toaccount, account->getParentAccountID ( toaccount ), 257 transfer->updateTransfer ( fromaccount, account->getParentAccountID ( fromaccount ), toaccount, account->getParentAccountID ( toaccount ),
258 day, month, year, amount->text().toFloat(), cleared, transferid ); 258 day, month, year, amount->text().toFloat(), cleared, transferid );
259 259
260 account->updateAccountBalance ( fromaccount ); 260 account->updateAccountBalance ( fromaccount );
261 if ( account->getParentAccountID ( fromaccount ) != -1 ) 261 if ( account->getParentAccountID ( fromaccount ) != -1 )
262 account->changeParentAccountBalance ( account->getParentAccountID ( fromaccount ) ); 262 account->changeParentAccountBalance ( account->getParentAccountID ( fromaccount ) );
263 263
264 updateAndDisplay ( toaccount ); 264 updateAndDisplay ( toaccount );
265 } 265 }
266 } 266 }
267 267
268void TransactionDisplay::editTransaction () 268void TransactionDisplay::editTransaction ()
269 { 269 {
270 int cleared; 270 int cleared;
271 271
272 // set the transaction id and budgetid 272 // set the transaction id and budgetid
273 int transactionid = listview->currentItem()->text ( getIDColumn() ).toInt(); 273 int transactionid = listview->currentItem()->text ( getIDColumn() ).toInt();
274 int budgetid = transaction->getBudgetID ( transactionid ); 274 int budgetid = transaction->getBudgetID ( transactionid );
275 int lineitemid = transaction->getLineItemID ( transactionid ); 275 int lineitemid = transaction->getLineItemID ( transactionid );
276 276
277 // create edit transaction window 277 // create edit transaction window
278 NewTransaction *newtransaction = new NewTransaction ( this ); 278 NewTransaction *newtransaction = new NewTransaction ( this );
279 int width = this->width(); 279 int width = this->width();
280 newtransaction->transactionname->setMaximumWidth ( ( int ) ( width * 0.45 ) ); 280 newtransaction->transactionname->setMaximumWidth ( ( int ) ( width * 0.45 ) );
281 newtransaction->transactionname->setMinimumWidth ( ( int ) ( width * 0.35 ) ); 281 newtransaction->transactionname->setMinimumWidth ( ( int ) ( width * 0.35 ) );
282 newtransaction->lineitembox->setMaximumWidth ( ( int ) ( width * 0.45 ) ); 282 newtransaction->lineitembox->setMaximumWidth ( ( int ) ( width * 0.45 ) );
283 newtransaction->transactiondatebox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 283 newtransaction->transactiondatebox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
284 newtransaction->transactionamountbox->setMaximumWidth ( ( int ) ( width * 0.4 ) ); 284 newtransaction->transactionamountbox->setMaximumWidth ( ( int ) ( width * 0.4 ) );
285 newtransaction->transactionnumber->setMaximumWidth ( ( int ) ( width * 0.25 ) ); 285 newtransaction->transactionnumber->setMaximumWidth ( ( int ) ( width * 0.25 ) );
286 286
287 // enter the date in the date box 287 // enter the date in the date box
288 newtransaction->year = transaction->getYear ( transactionid ); 288 newtransaction->year = transaction->getYear ( transactionid );
289 newtransaction->month = transaction->getMonth ( transactionid ); 289 newtransaction->month = transaction->getMonth ( transactionid );
290 newtransaction->day = transaction->getDay ( transactionid ); 290 newtransaction->day = transaction->getDay ( transactionid );
291 newtransaction->transactiondate->setText ( preferences->getDate ( newtransaction->year, newtransaction->month, newtransaction->day ) ); 291 newtransaction->transactiondate->setText ( preferences->getDate ( newtransaction->year, newtransaction->month, newtransaction->day ) );
292 292
293 // set the description 293 // set the description
294 newtransaction->setDescription ( transaction->getTransactionDescription ( transactionid ) ); 294 newtransaction->setDescription ( transaction->getTransactionDescription ( transactionid ) );
295 295
296 // add memory items to the transactionname combobox 296 // add memory items to the transactionname combobox
297 memory->displayMemoryItems ( newtransaction->transactionname ); 297 memory->displayMemoryItems ( newtransaction->transactionname );
298 298
299 // add correct transaction name 299 // add correct transaction name
300 newtransaction->transactionname->setEditText ( transaction->getPayee ( transactionid ) ); 300 newtransaction->transactionname->setEditText ( transaction->getPayee ( transactionid ) );
301 301
302 // add transaction number 302 // add transaction number
303 newtransaction->transactionnumber->setText ( transaction->getNumber ( transactionid ) ); 303 newtransaction->transactionnumber->setText ( transaction->getNumber ( transactionid ) );
304 304
305 // add transaction amount 305 // add transaction amount
306 newtransaction->transactionamount->setText ( transaction->getAbsoluteAmount ( transactionid ) ); 306 newtransaction->transactionamount->setText ( transaction->getAbsoluteAmount ( transactionid ) );
307 307
308 // check for and set the correct budget 308 // check for and set the correct budget
309 if ( budgetid >= 1 ) // only do it if this transaction has a budget and line item 309 if ( budgetid >= 1 ) // only do it if this transaction has a budget and line item
310 { 310 {
311 newtransaction->budgetbox->setCurrentItem ( newtransaction->getBudgetIndex ( budgetid ) + 1 ); 311 newtransaction->budgetbox->setCurrentItem ( newtransaction->getBudgetIndex ( budgetid ) + 1 );
312 if ( lineitemid >= 1 ) 312 if ( lineitemid >= 1 )
313 { 313 {
314 newtransaction->setLineItems (); 314 newtransaction->setLineItems ();
315 newtransaction->lineitembox->setCurrentItem ( newtransaction->getLineItemIndex ( lineitemid ) ); 315 newtransaction->lineitembox->setCurrentItem ( newtransaction->getLineItemIndex ( lineitemid ) );
316 } 316 }
317 else 317 else
318 { 318 {
319 newtransaction->lineitemlabel->setEnabled ( FALSE ); 319 newtransaction->lineitemlabel->setEnabled ( FALSE );
320 newtransaction->lineitembox->setEnabled ( FALSE ); 320 newtransaction->lineitembox->setEnabled ( FALSE );
321 } 321 }
322 } 322 }
323 else 323 else
324 { 324 {
325 newtransaction->lineitemlabel->setEnabled ( FALSE ); 325 newtransaction->lineitemlabel->setEnabled ( FALSE );
326 newtransaction->lineitembox->setEnabled ( FALSE ); 326 newtransaction->lineitembox->setEnabled ( FALSE );
327 } 327 }
328 328
329 // check cleared checkbox if necessary 329 // check cleared checkbox if necessary
330 if ( transaction->getCleared ( transactionid ) == 1 ) 330 if ( transaction->getCleared ( transactionid ) == 1 )
331 newtransaction->clearedcheckbox->setChecked ( TRUE ); 331 newtransaction->clearedcheckbox->setChecked ( TRUE );
332 332
333 // check deposit box if necessary 333 // check deposit box if necessary
334 if ( transaction->getAmount ( transactionid ).toFloat() > 0 ) 334 if ( transaction->getAmount ( transactionid ).toFloat() > 0 )
335 newtransaction->depositbox->setChecked ( TRUE ); 335 newtransaction->depositbox->setChecked ( TRUE );
336 336
337 if ( newtransaction->exec () == QDialog::Accepted ) 337 if ( newtransaction->exec () == QDialog::Accepted )
338 { 338 {
339 if ( newtransaction->clearedcheckbox->isChecked () == TRUE ) 339 if ( newtransaction->clearedcheckbox->isChecked () == TRUE )
340 cleared = 1; 340 cleared = 1;
341 else 341 else
342 cleared = 0; 342 cleared = 0;
343 343
344 float amount = newtransaction->transactionamount->text().toFloat(); 344 float amount = newtransaction->transactionamount->text().toFloat();
345 if ( newtransaction->depositbox->isChecked() == FALSE ) 345 if ( newtransaction->depositbox->isChecked() == FALSE )
346 amount = amount * -1; 346 amount = amount * -1;
347 347
348 // add the transaction name to the memory items 348 // add the transaction name to the memory items
349 memory->addMemoryItem ( newtransaction->transactionname->currentText() ); 349 memory->addMemoryItem ( newtransaction->transactionname->currentText() );
350 350
351 // update the transaction 351 // update the transaction
352 transaction->updateTransaction ( newtransaction->getDescription(), newtransaction->transactionname->currentText(), newtransaction->transactionnumber->text().toInt(), 352 transaction->updateTransaction ( newtransaction->getDescription(), newtransaction->transactionname->currentText(), newtransaction->transactionnumber->text().toInt(),
353 newtransaction->getDay(), newtransaction->getMonth(), newtransaction->getYear(), 353 newtransaction->getDay(), newtransaction->getMonth(), newtransaction->getYear(),
354 amount, cleared, newtransaction->getCurrentBudget(), newtransaction->getCurrentLineItem(), transactionid ); 354 amount, cleared, newtransaction->getCurrentBudget(), newtransaction->getCurrentLineItem(), transactionid );
355 355
356 updateAndDisplay ( transaction->getAccountID ( transactionid ) ); 356 updateAndDisplay ( transaction->getAccountID ( transactionid ) );
357 } 357 }
358 } 358 }
359 359
360void TransactionDisplay::updateAndDisplay ( int id ) 360void TransactionDisplay::updateAndDisplay ( int id )
361 { 361 {
362 // redisplay transactions 362 // redisplay transactions
363 listview->clear(); 363 listview->clear();
364 QString displaytext = "%"; 364 QString displaytext = "%";
365 displaytext.prepend ( limitbox->text() ); 365 displaytext.prepend ( limitbox->text() );
366 setTransactionDisplayDate (); 366 setTransactionDisplayDate ();
367 if ( transaction->getNumberOfTransactions() > 0 ) 367 if ( transaction->getNumberOfTransactions() > 0 )
368 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate ); 368 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate );
369 369
370 // redisplay transfers 370 // redisplay transfers
371 if ( transfer->getNumberOfTransfers() > 0 ) 371 if ( transfer->getNumberOfTransfers() > 0 )
372 transfer->displayTransfers ( listview, accountid, children, displaydate ); 372 transfer->displayTransfers ( listview, accountid, children, displaydate );
373 373
374 // add the transaction amount to the account it's associated with 374 // add the transaction amount to the account it's associated with
375 // and update its parent account balance if necessary 375 // and update its parent account balance if necessary
376 account->updateAccountBalance ( id ); 376 account->updateAccountBalance ( id );
377 if ( account->getParentAccountID ( id ) != -1 ) 377 if ( account->getParentAccountID ( id ) != -1 )
378 account->changeParentAccountBalance ( account->getParentAccountID ( id ) ); 378 account->changeParentAccountBalance ( account->getParentAccountID ( id ) );
379 379
380 // format then reset the account balance 380 // format then reset the account balance
381 redisplayAccountBalance (); 381 redisplayAccountBalance ();
382 } 382 }
383 383
384void TransactionDisplay::checkListViewDelete () 384void TransactionDisplay::checkListViewDelete ()
385 { 385 {
386 if ( listview->selectedItem() == 0 ) 386 if ( listview->selectedItem() == 0 )
387 QMessageBox::warning ( this, "QashMoney", "Please select a transaction to\ndelete."); 387 QMessageBox::warning ( this, "QashMoney", "Please select a transaction to\ndelete.");
388 else 388 else
389 deleteTransaction (); 389 deleteTransaction ();
390 } 390 }
391 391
392void TransactionDisplay::deleteTransaction () 392void TransactionDisplay::deleteTransaction ()
393 { 393 {
394 int transactionid = listview->currentItem()->text ( getIDColumn() ).toInt(); 394 int transactionid = listview->currentItem()->text ( getIDColumn() ).toInt();
395 395
396 if ( transactionid > 0 ) // takes care of deleting transactions 396 if ( transactionid > 0 ) // takes care of deleting transactions
397 { 397 {
398 // check if we are viewing child transactions through a parent 398 // check if we are viewing child transactions through a parent
399 // in that case we will have to update balances for the parent 399 // in that case we will have to update balances for the parent
400 // which is represented by accountid and the child account 400 // which is represented by accountid and the child account
401 // which will be represented by childaccountid 401 // which will be represented by childaccountid
402 int childaccountid = -1; 402 int childaccountid = -1;
403 if ( listview->columns() == 5 ) 403 if ( listview->columns() == 5 )
404 childaccountid = transaction->getAccountID ( transactionid ); 404 childaccountid = transaction->getAccountID ( transactionid );
405 405
406 transaction->deleteTransaction ( transactionid ); 406 transaction->deleteTransaction ( transactionid );
407 407
408 listview->clear(); 408 listview->clear();
409 QString displaytext = "%"; 409 QString displaytext = "%";
410 displaytext.prepend ( limitbox->text() ); 410 displaytext.prepend ( limitbox->text() );
411 setTransactionDisplayDate (); 411 setTransactionDisplayDate ();
412 if ( transaction->getNumberOfTransactions() > 0 ) 412 if ( transaction->getNumberOfTransactions() > 0 )
413 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate ); 413 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate );
414 414
415 if ( transfer->getNumberOfTransfers() > 0 ) 415 if ( transfer->getNumberOfTransfers() > 0 )
416 transfer->displayTransfers ( listview, accountid, children, displaydate ); 416 transfer->displayTransfers ( listview, accountid, children, displaydate );
417 417
418 // if we are viewing different child accounts through the parent account 418 // if we are viewing different child accounts through the parent account
419 // ie if there are five columns and the parentid is -1 419 // ie if there are five columns and the parentid is -1
420 // update the accountid ( which is the parent ) and update the child account 420 // update the accountid ( which is the parent ) and update the child account
421 // balance. Get its accountid from the transactionid 421 // balance. Get its accountid from the transactionid
422 account->updateAccountBalance ( accountid ); // will update either a parent or child 422 account->updateAccountBalance ( accountid ); // will update either a parent or child
423 if ( account->getParentAccountID ( accountid ) != -1 ) // update its parent if there is one 423 if ( account->getParentAccountID ( accountid ) != -1 ) // update its parent if there is one
424 account->changeParentAccountBalance ( account->getParentAccountID ( accountid ) ); 424 account->changeParentAccountBalance ( account->getParentAccountID ( accountid ) );
425 if ( childaccountid != -1 ) // we've set childaccountid 425 if ( childaccountid != -1 ) // we've set childaccountid
426 account->updateAccountBalance ( childaccountid ); 426 account->updateAccountBalance ( childaccountid );
427 427
428 // format then reset the account balance 428 // format then reset the account balance
429 redisplayAccountBalance (); 429 redisplayAccountBalance ();
430 } 430 }
431 else // takes care of deleting transfers 431 else // takes care of deleting transfers
432 { 432 {
433 // get the accountids before we delete the transfer 433 // get the accountids before we delete the transfer
434 int fromaccountid = transfer->getFromAccountID ( transactionid ); 434 int fromaccountid = transfer->getFromAccountID ( transactionid );
435 int toaccountid = transfer->getToAccountID ( transactionid ); 435 int toaccountid = transfer->getToAccountID ( transactionid );
436 436
437 // delete the transfer and redisplay transactions 437 // delete the transfer and redisplay transactions
438 transfer->deleteTransfer ( transactionid ); 438 transfer->deleteTransfer ( transactionid );
439 439
440 listview->clear(); 440 listview->clear();
441 QString displaytext = "%"; 441 QString displaytext = "%";
442 displaytext.prepend ( limitbox->text() ); 442 displaytext.prepend ( limitbox->text() );
443 setTransactionDisplayDate (); 443 setTransactionDisplayDate ();
444 if ( transaction->getNumberOfTransactions() > 0 ) 444 if ( transaction->getNumberOfTransactions() > 0 )
445 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate ); 445 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate );
446 446
447 if ( transfer->getNumberOfTransfers() > 0 ) 447 if ( transfer->getNumberOfTransfers() > 0 )
448 transfer->displayTransfers ( listview, accountid, children, displaydate ); 448 transfer->displayTransfers ( listview, accountid, children, displaydate );
449 449
450 // for the from account 450 // for the from account
451 account->updateAccountBalance ( fromaccountid ); 451 account->updateAccountBalance ( fromaccountid );
452 if ( account->getParentAccountID ( fromaccountid ) != -1 ) 452 if ( account->getParentAccountID ( fromaccountid ) != -1 )
453 account->changeParentAccountBalance ( account->getParentAccountID ( fromaccountid ) ); 453 account->changeParentAccountBalance ( account->getParentAccountID ( fromaccountid ) );
454 454
455 // for the to account 455 // for the to account
456 account->updateAccountBalance ( toaccountid ); 456 account->updateAccountBalance ( toaccountid );
457 if ( account->getParentAccountID ( toaccountid ) != -1 ) 457 if ( account->getParentAccountID ( toaccountid ) != -1 )
458 account->changeParentAccountBalance ( account->getParentAccountID ( toaccountid ) ); 458 account->changeParentAccountBalance ( account->getParentAccountID ( toaccountid ) );
459 459
460 // format then reset the account balance 460 // format then reset the account balance
461 redisplayAccountBalance (); 461 redisplayAccountBalance ();
462 } 462 }
463 } 463 }
464 464
465void TransactionDisplay::checkListViewToggle () 465void TransactionDisplay::checkListViewToggle ()
466 { 466 {
467 if ( listview->selectedItem() == 0 ) 467 if ( listview->selectedItem() == 0 )
468 QMessageBox::warning ( this, "QashMoney", "Please select a transaction to\nclear or reset."); 468 QMessageBox::warning ( this, "QashMoney", "Please select a transaction to\nclear or reset.");
469 else 469 else
470 toggleTransaction (); 470 toggleTransaction ();
471 } 471 }
472 472
473void TransactionDisplay::toggleTransaction () 473void TransactionDisplay::toggleTransaction ()
474 { 474 {
475 //get the transaction of the selected transaction to determine if its a transaction or transfer 475 //get the transaction of the selected transaction to determine if its a transaction or transfer
476 int transactionid = listview->currentItem()->text ( getIDColumn() ).toInt(); 476 int transactionid = listview->currentItem()->text ( getIDColumn() ).toInt();
477 477
478 if ( transactionid > 0 ) // if this is a transaction 478 if ( transactionid > 0 ) // if this is a transaction
479 { 479 {
480 if ( transaction->getCleared ( transactionid ) == 0 ) 480 if ( transaction->getCleared ( transactionid ) == 0 )
481 transaction->setCleared ( transactionid, 1 ); 481 transaction->setCleared ( transactionid, 1 );
482 else 482 else
483 transaction->setCleared ( transactionid, 0 ); 483 transaction->setCleared ( transactionid, 0 );
484 } 484 }
485 else 485 else
486 { 486 {
487 if ( transfer->getCleared ( transactionid ) == 0 ) 487 if ( transfer->getCleared ( transactionid ) == 0 )
488 transfer->setCleared ( transactionid, 1 ); 488 transfer->setCleared ( transactionid, 1 );
489 else 489 else
490 transfer->setCleared ( transactionid, 0 ); 490 transfer->setCleared ( transactionid, 0 );
491 } 491 }
492 492
493 listview->clear(); 493 listview->clear();
494 QString displaytext = "%"; 494 QString displaytext = "%";
495 displaytext.prepend ( limitbox->text() ); 495 displaytext.prepend ( limitbox->text() );
496 setTransactionDisplayDate (); 496 setTransactionDisplayDate ();
497 if ( transaction->getNumberOfTransactions() > 0 ) 497 if ( transaction->getNumberOfTransactions() > 0 )
498 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate ); 498 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate );
499 499
500 if ( transfer->getNumberOfTransfers() != 0 ) 500 if ( transfer->getNumberOfTransfers() != 0 )
501 transfer->displayTransfers ( listview, accountid, children, displaydate ); 501 transfer->displayTransfers ( listview, accountid, children, displaydate );
502 } 502 }
503 503
504void TransactionDisplay::redisplayAccountBalance () 504void TransactionDisplay::redisplayAccountBalance ()
505 { 505 {
506 QString accountbalance = account->getAccountBalance ( accountid ); 506 QString accountbalance = account->getAccountBalance ( accountid );
507 balance->setText ( accountbalance ); 507 balance->setText ( accountbalance );
508 } 508 }
509 509
510void TransactionDisplay::setChildren ( bool c ) 510void TransactionDisplay::setChildren ( bool c )
511 { 511 {
512 children = c; 512 children = c;
513 } 513 }
514 514
515void TransactionDisplay::setAccountID ( int id ) 515void TransactionDisplay::setAccountID ( int id )
516 { 516 {
517 accountid = id; 517 accountid = id;
518 } 518 }
519 519
520ColorListItem::ColorListItem ( QListView *parent ) : QListViewItem ( parent ) 520ColorListItem::ColorListItem ( QListView *parent ) : QListViewItem ( parent )
521 { 521 {
522 } 522 }
523 523
524ColorListItem::ColorListItem ( QListView *parent, QString label1, QString label2, QString label3, QString label4 ) 524ColorListItem::ColorListItem ( QListView *parent, QString label1, QString label2, QString label3, QString label4 )
525 : QListViewItem ( parent, label1, label2, label3, label4 ) 525 : QListViewItem ( parent, label1, label2, label3, label4 )
526 { 526 {
527 } 527 }
528 528
529ColorListItem::ColorListItem ( QListView *parent, QString label1, QString label2, QString label3, QString label4, QString label5 ) 529ColorListItem::ColorListItem ( QListView *parent, QString label1, QString label2, QString label3, QString label4, QString label5 )
530 : QListViewItem ( parent, label1, label2, label3, label4, label5 ) 530 : QListViewItem ( parent, label1, label2, label3, label4, label5 )
531 { 531 {
532 } 532 }
533 533
534void ColorListItem::paintCell ( QPainter *p, const QColorGroup &cg, int column, int width, int alignment ) 534void ColorListItem::paintCell ( QPainter *p, const QColorGroup &cg, int column, int width, int alignment )
535 { 535 {
536 QColorGroup _cg ( cg ); 536 QColorGroup _cg ( cg );
537 _cg.setColor ( QColorGroup::Text, Qt::red ); 537 _cg.setColor ( QColorGroup::Text, Qt::red );
538 QListViewItem::paintCell ( p, _cg, column, width, alignment ); 538 QListViewItem::paintCell ( p, _cg, column, width, alignment );
539 } 539 }
540 540
541void TransactionDisplay::saveColumnSize ( int column, int oldsize, int newsize ) 541void TransactionDisplay::saveColumnSize ( int column, int oldsize, int newsize )
542 { 542 {
543 if ( listview->columns() == 4 ) 543 if ( listview->columns() == 4 )
544 preferences->changeColumnPreference ( column + 3, newsize ); 544 preferences->changeColumnPreference ( column + 3, newsize );
545 else if ( listview->columns() == 5 && column != 4 ) 545 else if ( listview->columns() == 5 && column != 4 )
546 preferences->changeColumnPreference ( column + 6, newsize ); 546 preferences->changeColumnPreference ( column + 6, newsize );
547 else 547 else
548 preferences->changeColumnPreference ( 9, newsize ); 548 preferences->changeColumnPreference ( 9, newsize );
549 } 549 }
550 550
551void TransactionDisplay::saveSortingPreference ( int column ) 551void TransactionDisplay::saveSortingPreference ( int column )
552 { 552 {
553 preferences->changeSortingPreference ( 2, column ); 553 preferences->changeSortingPreference ( 2, column );
554 } 554 }
555 555
556void TransactionDisplay::limitDisplay ( const QString &text ) 556void TransactionDisplay::limitDisplay ( const QString &text )
557 { 557 {
558 listview->clear (); 558 listview->clear ();
559 QString displaytext = "%"; 559 QString displaytext = "%";
560 displaytext.prepend ( text ); 560 displaytext.prepend ( text );
561 setTransactionDisplayDate (); 561 setTransactionDisplayDate ();
562 if ( transaction->getNumberOfTransactions() > 0 ) 562 if ( transaction->getNumberOfTransactions() > 0 )
563 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate ); 563 transaction->displayTransactions ( listview, accountid, children, displaytext, displaydate );
564 564
565 if ( displaytext.length() == 1 || preferences->getPreference ( 6 ) == 1 ) 565 if ( displaytext.length() == 1 || preferences->getPreference ( 6 ) == 1 )
566 transfer->displayTransfers ( listview, accountid, children, displaydate ); 566 transfer->displayTransfers ( listview, accountid, children, displaydate );
567 } 567 }
568 568
569int TransactionDisplay::getIDColumn () 569int TransactionDisplay::getIDColumn ()
570 { 570 {
571 int counter; 571 int counter;
572 int columns = listview->columns(); 572 int columns = listview->columns();
573 for ( counter = 0; counter <= columns; counter++ ) 573 for ( counter = 0; counter <= columns; counter++ )
574 if ( listview->header()->label ( counter ).length() == 0 ) 574 if ( listview->header()->label ( counter ).length() == 0 )
575 return counter; 575 return counter;
576 } 576 }
577 577
578void TransactionDisplay::showTransactionNotes () 578void TransactionDisplay::showTransactionNotes ()
579 { 579 {
580 if ( listview->selectedItem() == 0 || listview->currentItem()->text ( getIDColumn() ).toInt() < 0 ) 580 if ( listview->selectedItem() == 0 || listview->currentItem()->text ( getIDColumn() ).toInt() < 0 )
581 QMessageBox::warning ( this, "QashMoney", "Please select a valid\ntransaction to view notes."); 581 QMessageBox::warning ( this, "QashMoney", "Please select a valid\ntransaction to view notes.");
582 else 582 else
583 { 583 {
584 int transactionid = listview->selectedItem()->text ( getIDColumn() ).toInt (); 584 int transactionid = listview->selectedItem()->text ( getIDColumn() ).toInt ();
585 QDialog *description = new QDialog ( this, "description", TRUE ); 585 QDialog *description = new QDialog ( this, "description", TRUE );
586 description->setCaption ( "Notes" ); 586 description->setCaption ( "Notes" );
587 QMultiLineEdit *notes = new QMultiLineEdit ( description ); 587 QMultiLineEdit *notes = new QMultiLineEdit ( description );
588 notes->setFixedSize ( ( int ) (this->width() * 0.75 ), ( int ) ( this->height() * 0.5 ) ); 588 notes->setFixedSize ( ( int ) (this->width() * 0.75 ), ( int ) ( this->height() * 0.5 ) );
589 notes->setWrapColumnOrWidth ( ( int ) (this->width() * 0.75 ) ); 589 notes->setWrapColumnOrWidth ( ( int ) (this->width() * 0.75 ) );
590 notes->setWordWrap ( QMultiLineEdit::WidgetWidth ); 590 notes->setWordWrap ( QMultiLineEdit::WidgetWidth );
591 notes->setEnabled ( FALSE ); 591 notes->setEnabled ( FALSE );
592 notes->setText ( transaction->getTransactionDescription ( transactionid ) ); 592 notes->setText ( transaction->getTransactionDescription ( transactionid ) );
593 description->show(); 593 description->show();
594 } 594 }
595 } 595 }
596 596
597void TransactionDisplay::setTransactionDisplayDate () 597void TransactionDisplay::setTransactionDisplayDate ()
598 { 598 {
599 // determine how many days of transactions to show 599 // determine how many days of transactions to show
600 int limittype = preferences->getPreference ( 7 ); 600 int limittype = preferences->getPreference ( 7 );
601 if ( limittype != 5 ) // set today's date if we are not showing all transactions 601 if ( limittype != 5 ) // set today's date if we are not showing all transactions
602 { 602 {
603 QDate today = QDate::currentDate (); 603 QDate today = QDate::currentDate ();
604 switch ( limittype ) // if we are not showing all transactions 604 switch ( limittype ) // if we are not showing all transactions
605 { 605 {
606 case 0: // viewing two weeks 606 case 0: // viewing two weeks
607 displaydate = today.addDays ( -14 ); 607 displaydate = today.addDays ( -14 );
608 break; 608 break;
609 case 1: // viewing one month 609 case 1: // viewing one month
610 displaydate = today.addDays ( -30 ); 610 displaydate = today.addDays ( -30 );
611 break; 611 break;
612 case 2: // three months 612 case 2: // three months
613 displaydate = today.addDays ( -90 ); 613 displaydate = today.addDays ( -90 );
614 break; 614 break;
615 case 3: // six months 615 case 3: // six months
616 displaydate = today.addDays ( -180 ); 616 displaydate = today.addDays ( -180 );
617 break; 617 break;
618 case 4: // one year 618 case 4: // one year
619 displaydate = today.addDays ( -365 ); 619 displaydate = today.addDays ( -365 );
620 break; 620 break;
621 } 621 }
622 } 622 }
623 else 623 else
624 displaydate = QDate ( 1900, 1, 1 ); 624 displaydate = QDate ( 1900, 1, 1 );
625 } 625 }
diff --git a/noncore/apps/qashmoney/transferdialog.cpp b/noncore/apps/qashmoney/transferdialog.cpp
index 558abec..7a12fbf 100755
--- a/noncore/apps/qashmoney/transferdialog.cpp
+++ b/noncore/apps/qashmoney/transferdialog.cpp
@@ -1,112 +1,112 @@
1#include "transferdialog.h" 1#include "transferdialog.h"
2#include "datepicker.h" 2#include "datepicker.h"
3#include "calculator.h" 3#include "calculator.h"
4 4
5 5
6extern Preferences *preferences; 6extern Preferences *preferences;
7extern Account *account; 7extern Account *account;
8 8
9TransferDialog::TransferDialog ( QWidget *parent, int fromaccountid, int toaccountid ) : QDialog ( parent, 0, TRUE ) 9TransferDialog::TransferDialog ( QWidget *parent, int fromaccountid, int toaccountid ) : QDialog ( parent, 0, TRUE )
10 { 10 {
11 dateedited = FALSE; 11 dateedited = FALSE;
12 setCaption ( "Transfer" ); 12 setCaption ( "Transfer" );
13 13
14 fromaccountlabel = new QLabel ( "From account:", this ); 14 fromaccountlabel = new QLabel ( "From account:", this );
15 QFont f = this->font(); 15 QFont f = this->font();
16 f.setWeight ( QFont::Bold ); 16 f.setWeight ( QFont::Bold );
17 fromaccountlabel->setFont ( f ); 17 fromaccountlabel->setFont ( f );
18 fromaccount = new QLabel ( account->getAccountName ( fromaccountid ), this ); 18 fromaccount = new QLabel ( account->getAccountName ( fromaccountid ), this );
19 19
20 toaccountlabel = new QLabel ( "To Account:", this ); 20 toaccountlabel = new QLabel ( "To Account:", this );
21 toaccountlabel->setFont ( f ); 21 toaccountlabel->setFont ( f );
22 toaccount = new QLabel ( account->getAccountName ( toaccountid ), this ); 22 toaccount = new QLabel ( account->getAccountName ( toaccountid ), this );
23 23
24 datelabel = new QLabel ( "Date", this ); 24 datelabel = new QLabel ( "Date", this );
25 25
26 datebox = new QHBox ( this ); 26 datebox = new QHBox ( this );
27 datebox->setSpacing ( 2 ); 27 datebox->setSpacing ( 2 );
28 date = new QLineEdit ( datebox ); 28 date = new QLineEdit ( datebox );
29 date->setAlignment ( Qt::AlignRight ); 29 date->setAlignment ( Qt::AlignRight );
30 date->setDisabled ( TRUE ); 30 date->setDisabled ( TRUE );
31 datebutton = new QPushButton ( datebox ); 31 datebutton = new QPushButton ( datebox );
32 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) ); 32 datebutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/date.png" ) );
33 connect ( datebutton, SIGNAL ( released () ), this, SLOT ( showCalendar () ) ); 33 connect ( datebutton, SIGNAL ( released() ), this, SLOT ( showCalendar() ) );
34 34
35 amounttlabel = new QLabel ( "Amount", this ); 35 amounttlabel = new QLabel ( "Amount", this );
36 36
37 amountbox = new QHBox ( this ); 37 amountbox = new QHBox ( this );
38 amountbox->setSpacing ( 2 ); 38 amountbox->setSpacing ( 2 );
39 amount = new QLineEdit ( amountbox ); 39 amount = new QLineEdit ( amountbox );
40 amount->setAlignment ( Qt::AlignRight ); 40 amount->setAlignment ( Qt::AlignRight );
41 calculatorbutton = new QPushButton( amountbox ); 41 calculatorbutton = new QPushButton( amountbox );
42 calculatorbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) ); 42 calculatorbutton->setPixmap ( QPixmap ( "/opt/QtPalmtop/pics/kcalc.png" ) );
43 connect ( calculatorbutton, SIGNAL ( released() ), this, SLOT ( showCalculator() ) ); 43 connect ( calculatorbutton, SIGNAL ( released() ), this, SLOT ( showCalculator() ) );
44 44
45 clearedcheckbox = new QCheckBox ( "Cleared", this ); 45 clearedcheckbox = new QCheckBox ( "Cleared", this );
46 46
47 layout = new QVBoxLayout ( this, 4, 2 ); 47 layout = new QVBoxLayout ( this, 4, 2 );
48 layout->addWidget ( fromaccountlabel, Qt::AlignLeft ); 48 layout->addWidget ( fromaccountlabel, Qt::AlignLeft );
49 layout->addWidget ( fromaccount, Qt::AlignLeft ); 49 layout->addWidget ( fromaccount, Qt::AlignLeft );
50 layout->addWidget ( toaccountlabel, Qt::AlignLeft ); 50 layout->addWidget ( toaccountlabel, Qt::AlignLeft );
51 layout->addWidget ( toaccount, Qt::AlignLeft ); 51 layout->addWidget ( toaccount, Qt::AlignLeft );
52 layout->addSpacing ( 5 ); 52 layout->addSpacing ( 5 );
53 layout->addWidget ( datelabel, Qt::AlignLeft ); 53 layout->addWidget ( datelabel, Qt::AlignLeft );
54 layout->addWidget ( datebox, Qt::AlignLeft ); 54 layout->addWidget ( datebox, Qt::AlignLeft );
55 layout->addWidget ( amounttlabel, Qt::AlignLeft ); 55 layout->addWidget ( amounttlabel, Qt::AlignLeft );
56 layout->addWidget ( amountbox, Qt::AlignLeft ); 56 layout->addWidget ( amountbox, Qt::AlignLeft );
57 layout->addWidget ( clearedcheckbox, Qt::AlignLeft ); 57 layout->addWidget ( clearedcheckbox, Qt::AlignLeft );
58 } 58 }
59 59
60bool TransferDialog::getDateEdited () 60bool TransferDialog::getDateEdited ()
61 { 61 {
62 return dateedited; 62 return dateedited;
63 } 63 }
64 64
65void TransferDialog::showCalendar () 65void TransferDialog::showCalendar ()
66 { 66 {
67 QDate newDate = QDate::currentDate (); 67 QDate newDate = QDate::currentDate ();
68 DatePicker *dp = new DatePicker ( newDate ); 68 DatePicker *dp = new DatePicker ( newDate );
69 if ( dp->exec () == QDialog::Accepted ) 69 if ( dp->exec () == QDialog::Accepted )
70 { 70 {
71 // Set date integers 71 // Set date integers
72 year = dp->getYear(); 72 year = dp->getYear();
73 month = dp->getMonth(); 73 month = dp->getMonth();
74 day = dp->getDay(); 74 day = dp->getDay();
75 75
76 // Set dateedited to TRUE 76 // Set dateedited to TRUE
77 // This tells the accountdisplay object that the user edited an account 77 // This tells the accountdisplay object that the user edited an account
78 // and did change the date 78 // and did change the date
79 dateedited = TRUE; 79 dateedited = TRUE;
80 80
81 // Display date with our selected format 81 // Display date with our selected format
82 date->setText ( preferences->getDate ( year, month, day ) ); 82 date->setText ( preferences->getDate ( year, month, day ) );
83 } 83 }
84 } 84 }
85 85
86int TransferDialog::getDay () 86int TransferDialog::getDay ()
87 { 87 {
88 return day; 88 return day;
89 } 89 }
90 90
91int TransferDialog::getMonth () 91int TransferDialog::getMonth ()
92 { 92 {
93 return month; 93 return month;
94 } 94 }
95 95
96int TransferDialog::getYear () 96int TransferDialog::getYear ()
97 { 97 {
98 return year; 98 return year;
99 } 99 }
100 100
101void TransferDialog::showCalculator () 101void TransferDialog::showCalculator ()
102 { 102 {
103 Calculator *calculator = new Calculator ( this ); 103 Calculator *calculator = new Calculator ( this );
104 if ( calculator->exec () == QDialog::Accepted ) 104 if ( calculator->exec () == QDialog::Accepted )
105 amount->setText ( calculator->display->text() ); 105 amount->setText ( calculator->display->text() );
106 } 106 }
107 107
108 108
109 109
110 110
111 111
112 112
diff --git a/noncore/apps/tableviewer/tableviewer.cpp b/noncore/apps/tableviewer/tableviewer.cpp
index f35dfcd..4c6d809 100644
--- a/noncore/apps/tableviewer/tableviewer.cpp
+++ b/noncore/apps/tableviewer/tableviewer.cpp
@@ -1,480 +1,480 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21/* local includes */ 21/* local includes */
22#include "tableviewer.h" 22#include "tableviewer.h"
23#include "ui/tvbrowseview.h" 23#include "ui/tvbrowseview.h"
24#include "ui/tvfilterview.h" 24#include "ui/tvfilterview.h"
25#include "ui/tvlistview.h" 25#include "ui/tvlistview.h"
26#include "ui/tveditview.h" 26#include "ui/tveditview.h"
27#include "ui/tvkeyedit.h" 27#include "ui/tvkeyedit.h"
28#include "db/datacache.h" 28#include "db/datacache.h"
29 29
30/* QPE includes */ 30/* QPE includes */
31#include <qpe/fileselector.h> 31#include <qpe/fileselector.h>
32#include <qpe/resource.h> 32#include <qpe/resource.h>
33#include <qpe/qpetoolbar.h> 33#include <qpe/qpetoolbar.h>
34 34
35/* QTE includes */ 35/* QTE includes */
36#include <qmenubar.h> 36#include <qmenubar.h>
37#include <qpopupmenu.h> 37#include <qpopupmenu.h>
38#include <qapplication.h> 38#include <qapplication.h>
39#include <qwidgetstack.h> 39#include <qwidgetstack.h>
40#include <qlayout.h> 40#include <qlayout.h>
41#include <qbuffer.h> 41#include <qbuffer.h>
42/*! 42/*!
43 \class TableViewerWindow 43 \class TableViewerWindow
44 \brief The main window widget of the application 44 \brief The main window widget of the application
45 45
46 This is the main widget of the table viewer application. 46 This is the main widget of the table viewer application.
47 It is the co-ordination point. 47 It is the co-ordination point.
48*/ 48*/
49 49
50/*! 50/*!
51 Constructs a new TableViewerWindow 51 Constructs a new TableViewerWindow
52*/ 52*/
53TableViewerWindow::TableViewerWindow(QWidget *parent, const char *name, WFlags f) 53TableViewerWindow::TableViewerWindow(QWidget *parent, const char *name, WFlags f)
54 : QMainWindow(parent, name, f) 54 : QMainWindow(parent, name, f)
55{ 55{
56 setCaption(tr("Table Viewer")); 56 setCaption(tr("Table Viewer"));
57 57
58/* Build data */ 58/* Build data */
59 ds = new DBStore(); 59 ds = new DBStore();
60 doc.setType("text/x-xml-tableviewer"); 60 doc.setType("text/x-xml-tableviewer");
61 doc.setName("table"); 61 doc.setName("table");
62 62
63 dirty = FALSE; 63 dirty = FALSE;
64 ts.current_column = 0; 64 ts.current_column = 0;
65 ts.kRep = ds->getKeys(); 65 ts.kRep = ds->getKeys();
66 66
67/* build menus */ 67/* build menus */
68 menu = new QMenuBar(this, 0); 68 menu = new QMenuBar(this, 0);
69 69
70 QPopupMenu *file_menu = new QPopupMenu; 70 QPopupMenu *file_menu = new QPopupMenu;
71 file_menu->insertItem("New", this, SLOT(newDocument())); 71 file_menu->insertItem("New", this, SLOT(newDocument()));
72 72
73 file_menu->insertItem("Open", this, SLOT(selectDocument())); 73 file_menu->insertItem("Open", this, SLOT(selectDocument()));
74 file_menu->insertSeparator(); 74 file_menu->insertSeparator();
75 file_menu->insertItem("Properties"); 75 file_menu->insertItem("Properties");
76 76
77 /* later will want to set this up to clean up first via this, SLOT(quit) */ 77 /* later will want to set this up to clean up first via this, SLOT(quit) */
78 menu->insertItem("Document", file_menu); 78 menu->insertItem("Document", file_menu);
79 79
80 QPopupMenu *edit_menu = new QPopupMenu; 80 QPopupMenu *edit_menu = new QPopupMenu;
81 edit_menu->insertItem("Edit Item", this, SLOT(editItemSlot())); 81 edit_menu->insertItem("Edit Item", this, SLOT(editItemSlot()));
82 edit_menu->insertItem("Edit Keys", this, SLOT(editKeysSlot())); 82 edit_menu->insertItem("Edit Keys", this, SLOT(editKeysSlot()));
83 edit_menu->insertItem("Edit filters", this, SLOT(filterViewSlot())); 83 edit_menu->insertItem("Edit filters", this, SLOT(filterViewSlot()));
84 menu->insertItem("Edit", edit_menu); 84 menu->insertItem("Edit", edit_menu);
85 85
86 QPopupMenu *view_menu = new QPopupMenu; 86 QPopupMenu *view_menu = new QPopupMenu;
87 view_menu->insertItem("Browse View", this, SLOT(browseViewSlot())); 87 view_menu->insertItem("Browse View", this, SLOT(browseViewSlot()));
88 view_menu->insertItem("List View", this, SLOT(listViewSlot())); 88 view_menu->insertItem("List View", this, SLOT(listViewSlot()));
89 menu->insertItem("View", view_menu); 89 menu->insertItem("View", view_menu);
90 90
91 QVBoxLayout *main_layout = new QVBoxLayout; 91 QVBoxLayout *main_layout = new QVBoxLayout;
92 92
93 /* Build tool bar */ 93 /* Build tool bar */
94 navigation = new QToolBar(this, "navigation"); 94 navigation = new QToolBar(this, "navigation");
95 QToolButton *newItemButton = new QToolButton( 95 QToolButton *newItemButton = new QToolButton(
96 QIconSet(Resource::loadPixmap("new")), "New Item", QString::null, 96 QIconSet(Resource::loadPixmap("new")), "New Item", QString::null,
97 this, SLOT(newItemSlot()), navigation, "New Item"); 97 this, SLOT(newItemSlot()), navigation, "New Item");
98 QToolButton *editItemButton = new QToolButton( 98 QToolButton *editItemButton = new QToolButton(
99 QIconSet(Resource::loadPixmap("edit")), "Edit Item", QString::null, 99 QIconSet(Resource::loadPixmap("edit")), "Edit Item", QString::null,
100 this, SLOT(editItemSlot()), navigation, "Edit Item"); 100 this, SLOT(editItemSlot()), navigation, "Edit Item");
101 QToolButton *deleteItemButton = new QToolButton( 101 QToolButton *deleteItemButton = new QToolButton(
102 QIconSet(Resource::loadPixmap("trash")), "Delete Item", 102 QIconSet(Resource::loadPixmap("trash")), "Delete Item",
103 QString::null, this, 103 QString::null, this,
104 SLOT(deleteItemSlot()), navigation, "Delete Item"); 104 SLOT(deleteItemSlot()), navigation, "Delete Item");
105 105
106 navigation->addSeparator(); 106 navigation->addSeparator();
107 107
108 QToolButton *firstItemButton = new QToolButton( 108 QToolButton *firstItemButton = new QToolButton(
109 QIconSet(Resource::loadPixmap("fastback")), "First Item", 109 QIconSet(Resource::loadPixmap("fastback")), "First Item",
110 QString::null, this, 110 QString::null, this,
111 SLOT(firstItem()), navigation, "First Item"); 111 SLOT(firstItem()), navigation, "First Item");
112 QToolButton *previousItemButton = new QToolButton( 112 QToolButton *previousItemButton = new QToolButton(
113 QIconSet(Resource::loadPixmap("back")), "Previous Item", 113 QIconSet(Resource::loadPixmap("back")), "Previous Item",
114 QString::null, this, 114 QString::null, this,
115 SLOT(previousItem()), navigation, "Previous Item"); 115 SLOT(previousItem()), navigation, "Previous Item");
116 QToolButton *nextItemButton = new QToolButton( 116 QToolButton *nextItemButton = new QToolButton(
117 QIconSet(Resource::loadPixmap("forward")), "Next Item", 117 QIconSet(Resource::loadPixmap("forward")), "Next Item",
118 QString::null, this, 118 QString::null, this,
119 SLOT(nextItem()), navigation, "Next Item"); 119 SLOT(nextItem()), navigation, "Next Item");
120 QToolButton *lastItemButton = new QToolButton( 120 QToolButton *lastItemButton = new QToolButton(
121 QIconSet(Resource::loadPixmap("fastforward")), "Last Item", 121 QIconSet(Resource::loadPixmap("fastforward")), "Last Item",
122 QString::null, this, 122 QString::null, this,
123 SLOT(lastItem()), navigation, "Last Item"); 123 SLOT(lastItem()), navigation, "Last Item");
124 124
125 navigation->addSeparator(); 125 navigation->addSeparator();
126 QToolButton *browseButton = new QToolButton( 126 QToolButton *browseButton = new QToolButton(
127 QIconSet(Resource::loadPixmap("day")), "View Single Item", 127 QIconSet(Resource::loadPixmap("day")), "View Single Item",
128 QString::null, this, 128 QString::null, this,
129 SLOT(browseViewSlot()), navigation, "View Single Item"); 129 SLOT(browseViewSlot()), navigation, "View Single Item");
130 QToolButton *listButton = new QToolButton( 130 QToolButton *listButton = new QToolButton(
131 QIconSet(Resource::loadPixmap("month")), "View Multiple Items", 131 QIconSet(Resource::loadPixmap("month")), "View Multiple Items",
132 QString::null, this, 132 QString::null, this,
133 SLOT(listViewSlot()), navigation, "View Multiple Items"); 133 SLOT(listViewSlot()), navigation, "View Multiple Items");
134 134
135 setToolBarsMovable(FALSE); 135 setToolBarsMovable(FALSE);
136 setToolBarsMovable(FALSE); 136 setToolBarsMovable(FALSE);
137 setToolBarsMovable(FALSE); 137 setToolBarsMovable(FALSE);
138 138
139/* Build widgets */ 139/* Build widgets */
140 browseView = new TVBrowseView(&ts, this, 0); 140 browseView = new TVBrowseView(&ts, this, 0);
141 listView = new TVListView(&ts, this, 0); 141 listView = new TVListView(&ts, this, 0);
142 filterView = new TVFilterView(&ts, this, 0); 142 filterView = new TVFilterView(&ts, this, 0);
143 fileSelector = new FileSelector("text/csv;text/x-xml-tableviewer", 143 fileSelector = new FileSelector("text/csv;text/x-xml-tableviewer",
144 this, "fileselector"); 144 this, "fileselector");
145 fileSelector->setNewVisible(FALSE); 145 fileSelector->setNewVisible(FALSE);
146 fileSelector->setCloseVisible(FALSE); 146 fileSelector->setCloseVisible(FALSE);
147 147
148 cw = new QWidgetStack(this, 0); 148 cw = new QWidgetStack(this, 0);
149 cw->addWidget(listView, ListState); 149 cw->addWidget(listView, ListState);
150 cw->addWidget(browseView, BrowseState); 150 cw->addWidget(browseView, BrowseState);
151 cw->addWidget(filterView, FilterState); 151 cw->addWidget(filterView, FilterState);
152 cw->addWidget(fileSelector, FileState); 152 cw->addWidget(fileSelector, FileState);
153 153
154 current_view = FileState; 154 current_view = FileState;
155 cw->raiseWidget(current_view); 155 cw->raiseWidget(current_view);
156 fileSelector->reread(); 156 fileSelector->reread();
157 157
158 connect(browseView, SIGNAL(searchOnKey(int, TVVariant)), 158 connect(browseView, SIGNAL(searchOnKey(int,TVVariant)),
159 this, SLOT(searchOnKey(int, TVVariant))); 159 this, SLOT(searchOnKey(int,TVVariant)));
160 connect(browseView, SIGNAL(sortChanged(int)), 160 connect(browseView, SIGNAL(sortChanged(int)),
161 this, SLOT(setPrimaryKey(int))); 161 this, SLOT(setPrimaryKey(int)));
162 162
163 connect(fileSelector, SIGNAL(closeMe()), this, SLOT(browseViewSlot())); 163 connect(fileSelector, SIGNAL(closeMe()), this, SLOT(browseViewSlot()));
164 connect(fileSelector, SIGNAL(fileSelected(const DocLnk &)), 164 connect(fileSelector, SIGNAL(fileSelected(const DocLnk&)),
165 this, SLOT(openDocument(const DocLnk &))); 165 this, SLOT(openDocument(const DocLnk&)));
166 166
167 main_layout->addWidget(menu); 167 main_layout->addWidget(menu);
168 main_layout->addWidget(cw); 168 main_layout->addWidget(cw);
169 169
170 setCentralWidget(cw); 170 setCentralWidget(cw);
171 171
172} 172}
173 173
174/*! 174/*!
175 Destroys the TableViewerWindow 175 Destroys the TableViewerWindow
176*/ 176*/
177TableViewerWindow::~TableViewerWindow() 177TableViewerWindow::~TableViewerWindow()
178{ 178{
179 if(dirty) 179 if(dirty)
180 saveDocument(); 180 saveDocument();
181} 181}
182 182
183/*! 183/*!
184 Opens a file dialog and loads the file specified by the dialog 184 Opens a file dialog and loads the file specified by the dialog
185*/ 185*/
186void TableViewerWindow::selectDocument() 186void TableViewerWindow::selectDocument()
187{ 187{
188 if(dirty) 188 if(dirty)
189 saveDocument(); 189 saveDocument();
190 current_view = FileState; 190 current_view = FileState;
191 cw->raiseWidget(current_view); 191 cw->raiseWidget(current_view);
192 fileSelector->reread(); 192 fileSelector->reread();
193} 193}
194 194
195void TableViewerWindow::saveDocument() 195void TableViewerWindow::saveDocument()
196{ 196{
197 if(!dirty) 197 if(!dirty)
198 return; 198 return;
199 199
200 FileManager fm; 200 FileManager fm;
201 QIODevice *dev = fm.saveFile(doc); 201 QIODevice *dev = fm.saveFile(doc);
202 202
203 if(!ds->saveSource(dev, doc.type())){ 203 if(!ds->saveSource(dev, doc.type())){
204 qWarning("Save unsuccessful"); 204 qWarning("Save unsuccessful");
205 return; 205 return;
206 } 206 }
207 dev->close(); 207 dev->close();
208 dirty = FALSE; 208 dirty = FALSE;
209} 209}
210 210
211void TableViewerWindow::newDocument() 211void TableViewerWindow::newDocument()
212{ 212{
213 DocLnk nf; 213 DocLnk nf;
214 nf.setType("text/x-xml-tableviewer"); 214 nf.setType("text/x-xml-tableviewer");
215 nf.setName("table"); 215 nf.setName("table");
216 216
217 delete ds; 217 delete ds;
218 ds = new DBStore(); 218 ds = new DBStore();
219 219
220 ts.current_column = 0; 220 ts.current_column = 0;
221 ts.kRep = ds->getKeys(); 221 ts.kRep = ds->getKeys();
222 browseView->reset(); 222 browseView->reset();
223 listView->reset(); 223 listView->reset();
224 filterView->reset(); 224 filterView->reset();
225 225
226 doc = nf; 226 doc = nf;
227 dirty = FALSE; 227 dirty = FALSE;
228 228
229 current_view = BrowseState; 229 current_view = BrowseState;
230 cw->raiseWidget(current_view); 230 cw->raiseWidget(current_view);
231 231
232 /* now set up for editing the keys */ 232 /* now set up for editing the keys */
233 ts.kRep->addKey("key", TVVariant::String); 233 ts.kRep->addKey("key", TVVariant::String);
234 editKeysSlot(); 234 editKeysSlot();
235} 235}
236 236
237void TableViewerWindow::setDocument(const QString &f) 237void TableViewerWindow::setDocument(const QString &f)
238{ 238{
239 openDocument(DocLnk(f, TRUE)); 239 openDocument(DocLnk(f, TRUE));
240} 240}
241 241
242void TableViewerWindow::openDocument(const DocLnk &f) 242void TableViewerWindow::openDocument(const DocLnk &f)
243{ 243{
244 244
245 if (!f.isValid()) 245 if (!f.isValid())
246 return; 246 return;
247 247
248 FileManager fm; 248 FileManager fm;
249 QIODevice *dev = fm.openFile(f); 249 QIODevice *dev = fm.openFile(f);
250 doc = f; 250 doc = f;
251 251
252 if(ds->openSource(dev, doc.type())) { 252 if(ds->openSource(dev, doc.type())) {
253 DataElem *d; 253 DataElem *d;
254 254
255 browseView->reset(); 255 browseView->reset();
256 listView->reset(); 256 listView->reset();
257 filterView->reset(); 257 filterView->reset();
258 258
259 current_view = BrowseState; 259 current_view = BrowseState;
260 cw->raiseWidget(current_view); 260 cw->raiseWidget(current_view);
261 261
262 /* set up new table state and ensure sub widgets have a reference */ 262 /* set up new table state and ensure sub widgets have a reference */
263 ts.current_column = 0; 263 ts.current_column = 0;
264 ts.kRep = ds->getKeys(); 264 ts.kRep = ds->getKeys();
265 browseView->rebuildKeys(); 265 browseView->rebuildKeys();
266 listView->rebuildKeys(); 266 listView->rebuildKeys();
267 filterView->rebuildKeys(); 267 filterView->rebuildKeys();
268 268
269 ds->first(); 269 ds->first();
270 /* set up the list view */ 270 /* set up the list view */
271 listView->clearItems(); 271 listView->clearItems();
272 do { 272 do {
273 d = ds->getCurrentData(); 273 d = ds->getCurrentData();
274 if(d) 274 if(d)
275 listView->addItem(d); 275 listView->addItem(d);
276 } while(ds->next()); 276 } while(ds->next());
277 277
278 /* Set up browse view, Will be based of structure of listView */ 278 /* Set up browse view, Will be based of structure of listView */
279 listView->first(); 279 listView->first();
280 ts.current_elem = listView->getCurrentData(); 280 ts.current_elem = listView->getCurrentData();
281 browseView->rebuildData(); 281 browseView->rebuildData();
282 listView->rebuildData(); 282 listView->rebuildData();
283 283
284 QString scratch = "Table Viewer";/* later take from constant */ 284 QString scratch = "Table Viewer";/* later take from constant */
285 scratch += " - "; 285 scratch += " - ";
286 scratch += ds->getName(); 286 scratch += ds->getName();
287 setCaption(tr(scratch)); 287 setCaption(tr(scratch));
288 288
289 dirty = FALSE; 289 dirty = FALSE;
290 } else { 290 } else {
291 qWarning(tr("could not load Document")); 291 qWarning(tr("could not load Document"));
292 } 292 }
293 dev->close(); 293 dev->close();
294} 294}
295 295
296/*! 296/*!
297 Moves to the first item of the current table 297 Moves to the first item of the current table
298*/ 298*/
299void TableViewerWindow::firstItem() 299void TableViewerWindow::firstItem()
300{ 300{
301 listView->first(); 301 listView->first();
302 ts.current_elem = listView->getCurrentData(); 302 ts.current_elem = listView->getCurrentData();
303 browseView->rebuildData(); 303 browseView->rebuildData();
304} 304}
305 305
306/*! 306/*!
307 Moves to the lat item of the current table 307 Moves to the lat item of the current table
308*/ 308*/
309void TableViewerWindow::lastItem() 309void TableViewerWindow::lastItem()
310{ 310{
311 listView->last(); 311 listView->last();
312 ts.current_elem = listView->getCurrentData(); 312 ts.current_elem = listView->getCurrentData();
313 browseView->rebuildData(); 313 browseView->rebuildData();
314} 314}
315 315
316/*! 316/*!
317 Moves to the next item of the current table 317 Moves to the next item of the current table
318*/ 318*/
319void TableViewerWindow::nextItem() 319void TableViewerWindow::nextItem()
320{ 320{
321 listView->next(); 321 listView->next();
322 ts.current_elem = listView->getCurrentData(); 322 ts.current_elem = listView->getCurrentData();
323 browseView->rebuildData(); 323 browseView->rebuildData();
324} 324}
325 325
326/*! 326/*!
327 Moves to the previous item of the current table 327 Moves to the previous item of the current table
328*/ 328*/
329void TableViewerWindow::previousItem() 329void TableViewerWindow::previousItem()
330{ 330{
331 listView->previous(); 331 listView->previous();
332 ts.current_elem = listView->getCurrentData(); 332 ts.current_elem = listView->getCurrentData();
333 browseView->rebuildData(); 333 browseView->rebuildData();
334} 334}
335 335
336/*! 336/*!
337 Raises the List View. This is a mode change for the application. 337 Raises the List View. This is a mode change for the application.
338*/ 338*/
339void TableViewerWindow::listViewSlot() 339void TableViewerWindow::listViewSlot()
340{ 340{
341 if(current_view == FilterState) 341 if(current_view == FilterState)
342 applyFilter(); 342 applyFilter();
343 current_view = ListState; 343 current_view = ListState;
344 cw->raiseWidget(current_view); 344 cw->raiseWidget(current_view);
345} 345}
346 346
347void TableViewerWindow::applyFilter() 347void TableViewerWindow::applyFilter()
348{ 348{
349 DataElem *d; 349 DataElem *d;
350 350
351 listView->clearItems(); 351 listView->clearItems();
352 ds->first(); 352 ds->first();
353 do { 353 do {
354 d = ds->getCurrentData(); 354 d = ds->getCurrentData();
355 if(d) 355 if(d)
356 if(filterView->passesFilter(d)) 356 if(filterView->passesFilter(d))
357 listView->addItem(d); 357 listView->addItem(d);
358 } while(ds->next()); 358 } while(ds->next());
359 listView->first(); 359 listView->first();
360 listView->rebuildData(); 360 listView->rebuildData();
361} 361}
362 362
363/*! 363/*!
364 Raises the Browse View. This is a mode change for the application. 364 Raises the Browse View. This is a mode change for the application.
365*/ 365*/
366void TableViewerWindow::browseViewSlot() 366void TableViewerWindow::browseViewSlot()
367{ 367{
368 if(current_view == FilterState) 368 if(current_view == FilterState)
369 applyFilter(); 369 applyFilter();
370 370
371 ts.current_elem = listView->getCurrentData(); 371 ts.current_elem = listView->getCurrentData();
372 browseView->rebuildData(); 372 browseView->rebuildData();
373 373
374 current_view = BrowseState; 374 current_view = BrowseState;
375 cw->raiseWidget(current_view); 375 cw->raiseWidget(current_view);
376} 376}
377 377
378/*! 378/*!
379 Raises the List View. This is a mode change for the application. 379 Raises the List View. This is a mode change for the application.
380*/ 380*/
381void TableViewerWindow::filterViewSlot() 381void TableViewerWindow::filterViewSlot()
382{ 382{
383 current_view = FilterState; 383 current_view = FilterState;
384 cw->raiseWidget(current_view); 384 cw->raiseWidget(current_view);
385} 385}
386 386
387 387
388 388
389 389
390void TableViewerWindow::editItemSlot() 390void TableViewerWindow::editItemSlot()
391{ 391{
392 if(TVEditView::openEditItemDialog(&ts, ts.current_elem, this)) { 392 if(TVEditView::openEditItemDialog(&ts, ts.current_elem, this)) {
393 listView->rebuildData(); 393 listView->rebuildData();
394 browseView->rebuildData(); 394 browseView->rebuildData();
395 dirty = TRUE; 395 dirty = TRUE;
396 } 396 }
397} 397}
398 398
399void TableViewerWindow::newItemSlot() 399void TableViewerWindow::newItemSlot()
400{ 400{
401 DataElem *d = new DataElem(ds); 401 DataElem *d = new DataElem(ds);
402 if (TVEditView::openEditItemDialog(&ts, d, this)) { 402 if (TVEditView::openEditItemDialog(&ts, d, this)) {
403 403
404 ds->addItem(d); 404 ds->addItem(d);
405 ts.current_elem = d; 405 ts.current_elem = d;
406 applyFilter(); 406 applyFilter();
407 listView->rebuildData(); 407 listView->rebuildData();
408 browseView->rebuildData(); 408 browseView->rebuildData();
409 dirty = TRUE; 409 dirty = TRUE;
410 } 410 }
411} 411}
412 412
413void TableViewerWindow::deleteItemSlot() 413void TableViewerWindow::deleteItemSlot()
414{ 414{
415 /* delete the actual item, then do a 'filter' */ 415 /* delete the actual item, then do a 'filter' */
416 DataElem *to_remove = ts.current_elem; 416 DataElem *to_remove = ts.current_elem;
417 417
418 if(!to_remove) 418 if(!to_remove)
419 return; 419 return;
420 420
421 listView->removeItem(); 421 listView->removeItem();
422 ds->removeItem(to_remove); 422 ds->removeItem(to_remove);
423 423
424 applyFilter(); 424 applyFilter();
425 listView->rebuildData(); 425 listView->rebuildData();
426 browseView->rebuildData(); 426 browseView->rebuildData();
427 dirty = TRUE; 427 dirty = TRUE;
428} 428}
429 429
430void TableViewerWindow::editKeysSlot() 430void TableViewerWindow::editKeysSlot()
431{ 431{
432 DataElem *d; 432 DataElem *d;
433 KeyList *k = TVKeyEdit::openEditKeysDialog(&ts, this); 433 KeyList *k = TVKeyEdit::openEditKeysDialog(&ts, this);
434 434
435 if(k) { 435 if(k) {
436 /* set as new keys */ 436 /* set as new keys */
437 ds->setKeys(k); 437 ds->setKeys(k);
438 438
439 ts.current_column = 0; 439 ts.current_column = 0;
440 ts.kRep = k; 440 ts.kRep = k;
441 441
442 browseView->reset(); 442 browseView->reset();
443 listView->reset(); 443 listView->reset();
444 filterView->reset(); 444 filterView->reset();
445 445
446 browseView->rebuildKeys(); 446 browseView->rebuildKeys();
447 listView->rebuildKeys(); 447 listView->rebuildKeys();
448 filterView->rebuildKeys(); 448 filterView->rebuildKeys();
449 449
450 ds->first(); 450 ds->first();
451 /* set up the list view */ 451 /* set up the list view */
452 listView->clearItems(); 452 listView->clearItems();
453 do { 453 do {
454 d = ds->getCurrentData(); 454 d = ds->getCurrentData();
455 if(d) 455 if(d)
456 listView->addItem(d); 456 listView->addItem(d);
457 } while(ds->next()); 457 } while(ds->next());
458 458
459 /* Set up browse view, Will be based of structure of listView */ 459 /* Set up browse view, Will be based of structure of listView */
460 dirty = TRUE; 460 dirty = TRUE;
461 } 461 }
462} 462}
463 463
464/*! 464/*!
465 A Slot that allows for widgets above to indicate a search should be 465 A Slot that allows for widgets above to indicate a search should be
466 done on a specified key index for a specified value 466 done on a specified key index for a specified value
467*/ 467*/
468void TableViewerWindow::searchOnKey(int i, TVVariant v) 468void TableViewerWindow::searchOnKey(int i, TVVariant v)
469{ 469{
470 listView->findItem(i, v); 470 listView->findItem(i, v);
471 ts.current_elem = listView->getCurrentData(); 471 ts.current_elem = listView->getCurrentData();
472 browseView->rebuildData(); 472 browseView->rebuildData();
473} 473}
474 474
475void TableViewerWindow::setPrimaryKey(int i) 475void TableViewerWindow::setPrimaryKey(int i)
476{ 476{
477 ts.current_column = i; 477 ts.current_column = i;
478 listView->rebuildData(); 478 listView->rebuildData();
479 browseView->rebuildData(); 479 browseView->rebuildData();
480} 480}
diff --git a/noncore/apps/tableviewer/ui/commonwidgets.cpp b/noncore/apps/tableviewer/ui/commonwidgets.cpp
index 4c47951..e82018c 100644
--- a/noncore/apps/tableviewer/ui/commonwidgets.cpp
+++ b/noncore/apps/tableviewer/ui/commonwidgets.cpp
@@ -1,210 +1,210 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include <qlineedit.h> 21#include <qlineedit.h>
22#include <qlayout.h> 22#include <qlayout.h>
23#include <qlabel.h> 23#include <qlabel.h>
24#include <qcombobox.h> 24#include <qcombobox.h>
25 25
26#include <qpe/datebookmonth.h> 26#include <qpe/datebookmonth.h>
27#include <qpopupmenu.h> 27#include <qpopupmenu.h>
28#include <qspinbox.h> 28#include <qspinbox.h>
29#include "commonwidgets.h" 29#include "commonwidgets.h"
30 30
31DateEdit::DateEdit( QWidget *parent, const char *name, WFlags f ) 31DateEdit::DateEdit( QWidget *parent, const char *name, WFlags f )
32 : QToolButton(parent, name) 32 : QToolButton(parent, name)
33{ 33{
34 QPopupMenu *m1 = new QPopupMenu(this); 34 QPopupMenu *m1 = new QPopupMenu(this);
35 dateSelector = new DateBookMonth(m1, 0, TRUE); 35 dateSelector = new DateBookMonth(m1, 0, TRUE);
36 m1->insertItem(dateSelector); 36 m1->insertItem(dateSelector);
37 setPopup(m1); 37 setPopup(m1);
38 setPopupDelay(0); 38 setPopupDelay(0);
39 39
40 connect(dateSelector, SIGNAL(dateClicked(int, int, int)), 40 connect(dateSelector, SIGNAL(dateClicked(int,int,int)),
41 this, SLOT(subValueChanged())); 41 this, SLOT(subValueChanged()));
42 42
43 setText(dateSelector->selectedDate().toString()); 43 setText(dateSelector->selectedDate().toString());
44} 44}
45 45
46 46
47DateEdit::~DateEdit() {} 47DateEdit::~DateEdit() {}
48 48
49QDate DateEdit::date() const 49QDate DateEdit::date() const
50{ 50{
51 return dateSelector->selectedDate(); 51 return dateSelector->selectedDate();
52} 52}
53 53
54void DateEdit::setDate(QDate d) 54void DateEdit::setDate(QDate d)
55{ 55{
56 dateSelector->setDate(d.year(), d.month(), d.day()); 56 dateSelector->setDate(d.year(), d.month(), d.day());
57 setText(d.toString()); 57 setText(d.toString());
58} 58}
59 59
60QSizePolicy DateEdit::sizePolicy() const 60QSizePolicy DateEdit::sizePolicy() const
61{ 61{
62 QSizePolicy sp; 62 QSizePolicy sp;
63 sp.setHorData(QToolButton::sizePolicy().horData()); 63 sp.setHorData(QToolButton::sizePolicy().horData());
64 sp.setVerData(QSizePolicy::Fixed); 64 sp.setVerData(QSizePolicy::Fixed);
65 65
66 return sp; 66 return sp;
67} 67}
68 68
69void DateEdit::clear() 69void DateEdit::clear()
70{ 70{
71 QDate today = QDate::currentDate(); 71 QDate today = QDate::currentDate();
72 72
73 dateSelector->setDate(today.year(), today.month(), today.day()); 73 dateSelector->setDate(today.year(), today.month(), today.day());
74 setText(today.toString()); 74 setText(today.toString());
75} 75}
76 76
77void DateEdit::subValueChanged() 77void DateEdit::subValueChanged()
78{ 78{
79 QDate current = dateSelector->selectedDate(); 79 QDate current = dateSelector->selectedDate();
80 80
81 setText(current.toString()); 81 setText(current.toString());
82 emit valueChanged(current); 82 emit valueChanged(current);
83} 83}
84 84
85TimeEdit::TimeEdit( QWidget *parent, const char *name, WFlags f ) 85TimeEdit::TimeEdit( QWidget *parent, const char *name, WFlags f )
86 : QWidget(parent, name, f) 86 : QWidget(parent, name, f)
87{ 87{
88 QHBoxLayout *layout = new QHBoxLayout(this, 0); 88 QHBoxLayout *layout = new QHBoxLayout(this, 0);
89 89
90 layout->addWidget(hourKey = new QSpinBox(1, 12, 1, this)); 90 layout->addWidget(hourKey = new QSpinBox(1, 12, 1, this));
91 hourKey->setWrapping(true); 91 hourKey->setWrapping(true);
92 hourKey->setMinimumWidth(30); 92 hourKey->setMinimumWidth(30);
93 hourKey->setMaximumWidth(35); 93 hourKey->setMaximumWidth(35);
94 94
95 layout->addWidget(new QLabel(" : ", this)); 95 layout->addWidget(new QLabel(" : ", this));
96 layout->addWidget(minuteKey = new QSpinBox(0, 59, 1, this)); 96 layout->addWidget(minuteKey = new QSpinBox(0, 59, 1, this));
97 minuteKey->setWrapping(true); 97 minuteKey->setWrapping(true);
98 minuteKey->setMinimumWidth(30); 98 minuteKey->setMinimumWidth(30);
99 minuteKey->setMaximumWidth(35); 99 minuteKey->setMaximumWidth(35);
100 100
101 layout->addWidget(new QLabel(" : ", this)); 101 layout->addWidget(new QLabel(" : ", this));
102 layout->addWidget(secondKey = new QSpinBox(0, 59, 1, this, 0)); 102 layout->addWidget(secondKey = new QSpinBox(0, 59, 1, this, 0));
103 secondKey->setWrapping(true); 103 secondKey->setWrapping(true);
104 secondKey->setMinimumWidth(30); 104 secondKey->setMinimumWidth(30);
105 secondKey->setMaximumWidth(35); 105 secondKey->setMaximumWidth(35);
106 106
107 layout->addWidget(ampm = new QComboBox(this)); 107 layout->addWidget(ampm = new QComboBox(this));
108 ampm->insertItem("AM"); 108 ampm->insertItem("AM");
109 ampm->insertItem("PM"); 109 ampm->insertItem("PM");
110 110
111 layout->addStretch(-1); 111 layout->addStretch(-1);
112 112
113 clear(); 113 clear();
114 114
115 connect(secondKey, SIGNAL(valueChanged(const QString&)), 115 connect(secondKey, SIGNAL(valueChanged(const QString&)),
116 this, SLOT(subValueChanged())); 116 this, SLOT(subValueChanged()));
117 connect(minuteKey, SIGNAL(valueChanged(const QString&)), 117 connect(minuteKey, SIGNAL(valueChanged(const QString&)),
118 this, SLOT(subValueChanged())); 118 this, SLOT(subValueChanged()));
119 connect(hourKey, SIGNAL(valueChanged(const QString&)), 119 connect(hourKey, SIGNAL(valueChanged(const QString&)),
120 this, SLOT(subValueChanged())); 120 this, SLOT(subValueChanged()));
121 connect(ampm, SIGNAL(activated(int)), 121 connect(ampm, SIGNAL(activated(int)),
122 this, SLOT(subValueChanged())); 122 this, SLOT(subValueChanged()));
123} 123}
124 124
125 125
126TimeEdit::~TimeEdit() {} 126TimeEdit::~TimeEdit() {}
127 127
128QTime TimeEdit::time() const 128QTime TimeEdit::time() const
129{ 129{
130 int s,m,h; 130 int s,m,h;
131 131
132 s = secondKey->text().toInt(); 132 s = secondKey->text().toInt();
133 m = minuteKey->text().toInt(); 133 m = minuteKey->text().toInt();
134 h = hourKey->text().toInt(); 134 h = hourKey->text().toInt();
135 135
136 if(ampm->currentItem() == 1) { 136 if(ampm->currentItem() == 1) {
137 /* pm */ 137 /* pm */
138 h = h + 12; 138 h = h + 12;
139 } 139 }
140 /* hour now ranges 1->24 */ 140 /* hour now ranges 1->24 */
141 141
142 if (h == 12) 142 if (h == 12)
143 h = 0; 143 h = 0;
144 if (h == 24) 144 if (h == 24)
145 h = 12; 145 h = 12;
146 146
147 if(QTime::isValid(h, m, s)) 147 if(QTime::isValid(h, m, s))
148 return QTime(h, m, s); 148 return QTime(h, m, s);
149 return QTime(0, 0, 0); 149 return QTime(0, 0, 0);
150} 150}
151 151
152void TimeEdit::setTime(QTime t) 152void TimeEdit::setTime(QTime t)
153{ 153{
154 int h = t.hour(); 154 int h = t.hour();
155 secondKey->setValue(t.second()); 155 secondKey->setValue(t.second());
156 minuteKey->setValue(t.minute()); 156 minuteKey->setValue(t.minute());
157 157
158 /* h 0..23 */ 158 /* h 0..23 */
159 if (h > 11) { 159 if (h > 11) {
160 h -= 12; 160 h -= 12;
161 ampm->setCurrentItem(1); 161 ampm->setCurrentItem(1);
162 } else { 162 } else {
163 ampm->setCurrentItem(0); 163 ampm->setCurrentItem(0);
164 } 164 }
165 165
166 if (h == 0) h = 12; 166 if (h == 0) h = 12;
167 hourKey->setValue(h); 167 hourKey->setValue(h);
168} 168}
169 169
170QSizePolicy TimeEdit::sizePolicy() const 170QSizePolicy TimeEdit::sizePolicy() const
171{ 171{
172 QSizePolicy sp; 172 QSizePolicy sp;
173 sp.setHorData(QSizePolicy::Preferred); 173 sp.setHorData(QSizePolicy::Preferred);
174 sp.setVerData(QSizePolicy::Fixed); 174 sp.setVerData(QSizePolicy::Fixed);
175 175
176 return sp; 176 return sp;
177} 177}
178 178
179void TimeEdit::clear() 179void TimeEdit::clear()
180{ 180{
181 secondKey->setValue(0); 181 secondKey->setValue(0);
182 minuteKey->setValue(0); 182 minuteKey->setValue(0);
183 hourKey->setValue(12); 183 hourKey->setValue(12);
184 184
185 ampm->setCurrentItem(0); 185 ampm->setCurrentItem(0);
186} 186}
187 187
188void TimeEdit::subValueChanged() 188void TimeEdit::subValueChanged()
189{ 189{
190 emit valueChanged(time()); 190 emit valueChanged(time());
191} 191}
192 192
193IntEdit::IntEdit( QWidget *parent, const char *name, WFlags f ) 193IntEdit::IntEdit( QWidget *parent, const char *name, WFlags f )
194 : QSpinBox(INT_MIN, INT_MAX, 1, parent, name) 194 : QSpinBox(INT_MIN, INT_MAX, 1, parent, name)
195{ 195{
196 setValue(0); 196 setValue(0);
197} 197}
198 198
199 199
200IntEdit::~IntEdit() {} 200IntEdit::~IntEdit() {}
201 201
202int IntEdit::value() 202int IntEdit::value()
203{ 203{
204 return cleanText().toInt(); 204 return cleanText().toInt();
205} 205}
206 206
207void IntEdit::clear() 207void IntEdit::clear()
208{ 208{
209 setValue(0); 209 setValue(0);
210} 210}
diff --git a/noncore/apps/tableviewer/ui/tvbrowseview.cpp b/noncore/apps/tableviewer/ui/tvbrowseview.cpp
index 22bac55..8a65ed1 100644
--- a/noncore/apps/tableviewer/ui/tvbrowseview.cpp
+++ b/noncore/apps/tableviewer/ui/tvbrowseview.cpp
@@ -1,123 +1,123 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include "tvbrowseview.h" 20#include "tvbrowseview.h"
21#include "browsekeyentry.h" 21#include "browsekeyentry.h"
22#include <qtoolbutton.h> 22#include <qtoolbutton.h>
23#include <qtextview.h> 23#include <qtextview.h>
24#include <qtextbrowser.h> 24#include <qtextbrowser.h>
25#include <qlayout.h> 25#include <qlayout.h>
26#include "../xmlencodeattr.h" 26#include "../xmlencodeattr.h"
27 27
28/*! 28/*!
29 \class TVBrowseView 29 \class TVBrowseView
30 \brief The widget describing how to draw the browse view user interface 30 \brief The widget describing how to draw the browse view user interface
31 31
32 This widget allows for the user to browse through the table, one element 32 This widget allows for the user to browse through the table, one element
33 at a time, or search on a single key. Its main goal is to show a 33 at a time, or search on a single key. Its main goal is to show a
34 single element in a readable format and make it easy for the user to 34 single element in a readable format and make it easy for the user to
35 rapidly find specific elements in the table. 35 rapidly find specific elements in the table.
36*/ 36*/
37 37
38/*! 38/*!
39 Constructs a new TVBrowseView widget 39 Constructs a new TVBrowseView widget
40*/ 40*/
41TVBrowseView::TVBrowseView(TableState *t, QWidget* parent, const char *name, 41TVBrowseView::TVBrowseView(TableState *t, QWidget* parent, const char *name,
42 WFlags fl ) 42 WFlags fl )
43{ 43{
44 if (!name) 44 if (!name)
45 setName("BrowseView"); 45 setName("BrowseView");
46 46
47// setSizePolicy(QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding, 0, 0, sizePolicy().hasHeightForWidth() ) ); 47// setSizePolicy(QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding, 0, 0, sizePolicy().hasHeightForWidth() ) );
48 QVBoxLayout *vlayout = new QVBoxLayout(this); 48 QVBoxLayout *vlayout = new QVBoxLayout(this);
49 textViewDisplay = new QTextBrowser(this, "textViewDisplay"); 49 textViewDisplay = new QTextBrowser(this, "textViewDisplay");
50 vlayout->addWidget( textViewDisplay ); 50 vlayout->addWidget( textViewDisplay );
51 51
52 keyEntry = new TVBrowseKeyEntry(this, "keyEntry"); 52 keyEntry = new TVBrowseKeyEntry(this, "keyEntry");
53 vlayout->addWidget( keyEntry ); 53 vlayout->addWidget( keyEntry );
54 54
55 /* connect the signals down */ 55 /* connect the signals down */
56 56
57 connect(keyEntry, SIGNAL(searchOnKey(int, TVVariant)), 57 connect(keyEntry, SIGNAL(searchOnKey(int,TVVariant)),
58 this, SIGNAL(searchOnKey(int, TVVariant))); 58 this, SIGNAL(searchOnKey(int,TVVariant)));
59 connect(keyEntry, SIGNAL(sortChanged(int)), 59 connect(keyEntry, SIGNAL(sortChanged(int)),
60 this, SIGNAL(sortChanged(int))); 60 this, SIGNAL(sortChanged(int)));
61 61
62 ts = t; 62 ts = t;
63 keyEntry->setTableState(t); 63 keyEntry->setTableState(t);
64} 64}
65 65
66/*! 66/*!
67 Destroys the TVBrowseView widget 67 Destroys the TVBrowseView widget
68*/ 68*/
69TVBrowseView::~TVBrowseView() 69TVBrowseView::~TVBrowseView()
70{ 70{
71} 71}
72 72
73void TVBrowseView::rebuildData() 73void TVBrowseView::rebuildData()
74{ 74{
75 if(!ts) 75 if(!ts)
76 return; 76 return;
77 if(!ts->current_elem) { 77 if(!ts->current_elem) {
78 /* also disable buttons */ 78 /* also disable buttons */
79 textViewDisplay->setText(""); 79 textViewDisplay->setText("");
80 return; 80 return;
81 } 81 }
82 82
83 setDisplayText(ts->current_elem); 83 setDisplayText(ts->current_elem);
84} 84}
85 85
86/* Reset to initial state */ 86/* Reset to initial state */
87void TVBrowseView::reset() 87void TVBrowseView::reset()
88{ 88{
89 textViewDisplay->setText(""); 89 textViewDisplay->setText("");
90 keyEntry->reset(); 90 keyEntry->reset();
91} 91}
92 92
93/*! 93/*!
94 sets the data element to be displayed to element 94 sets the data element to be displayed to element
95*/ 95*/
96void TVBrowseView::setDisplayText(const DataElem *element) 96void TVBrowseView::setDisplayText(const DataElem *element)
97{ 97{
98 QString rep = ""; 98 QString rep = "";
99 99
100 KeyListIterator it(*ts->kRep); 100 KeyListIterator it(*ts->kRep);
101 101
102 while (it.current()) { 102 while (it.current()) {
103 if (element->hasValidValue(it.currentKey())) { 103 if (element->hasValidValue(it.currentKey())) {
104 if(it.currentKey() == ts->current_column) { 104 if(it.currentKey() == ts->current_column) {
105 rep += "<A name=\"ckey\"></A><B><FONT COLOR=#FF0000>" 105 rep += "<A name=\"ckey\"></A><B><FONT COLOR=#FF0000>"
106 + encodeAttr(it.current()->name()) 106 + encodeAttr(it.current()->name())
107 + ":</FONT></B> "; 107 + ":</FONT></B> ";
108 } else { 108 } else {
109 rep += "<B>" + encodeAttr(it.current()->name()) + ":</B> "; 109 rep += "<B>" + encodeAttr(it.current()->name()) + ":</B> ";
110 } 110 }
111 rep += encodeAttr(element->toQString(it.currentKey())) + "<BR>"; 111 rep += encodeAttr(element->toQString(it.currentKey())) + "<BR>";
112 } 112 }
113 ++it; 113 ++it;
114 } 114 }
115 115
116 textViewDisplay->setText(rep); 116 textViewDisplay->setText(rep);
117 textViewDisplay->scrollToAnchor("ckey"); 117 textViewDisplay->scrollToAnchor("ckey");
118} 118}
119 119
120void TVBrowseView::rebuildKeys() 120void TVBrowseView::rebuildKeys()
121{ 121{
122 keyEntry->rebuildKeys(); 122 keyEntry->rebuildKeys();
123} 123}
diff --git a/noncore/apps/tableviewer/ui/tvfilterview.cpp b/noncore/apps/tableviewer/ui/tvfilterview.cpp
index b03e846..22f1fb7 100644
--- a/noncore/apps/tableviewer/ui/tvfilterview.cpp
+++ b/noncore/apps/tableviewer/ui/tvfilterview.cpp
@@ -1,306 +1,306 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include "tvfilterview.h" 20#include "tvfilterview.h"
21#include <qtoolbutton.h> 21#include <qtoolbutton.h>
22#include <qcombobox.h> 22#include <qcombobox.h>
23#include <qlistview.h> 23#include <qlistview.h>
24#include <qlayout.h> 24#include <qlayout.h>
25#include <qheader.h> 25#include <qheader.h>
26#include <qpushbutton.h> 26#include <qpushbutton.h>
27#include <qlabel.h> 27#include <qlabel.h>
28 28
29#include <qpe/qpeapplication.h> 29#include <qpe/qpeapplication.h>
30 30
31TVFilterView::TVFilterView(TableState *t, QWidget* parent, 31TVFilterView::TVFilterView(TableState *t, QWidget* parent,
32 const char *name, WFlags fl ) : QDialog(parent, name, TRUE, fl) 32 const char *name, WFlags fl ) : QDialog(parent, name, TRUE, fl)
33{ 33{
34 if ( !name ) 34 if ( !name )
35 setName( "Filter View" ); 35 setName( "Filter View" );
36 36
37 QVBoxLayout *vlayout = new QVBoxLayout(this); 37 QVBoxLayout *vlayout = new QVBoxLayout(this);
38 38
39 display = new QListView(this, "display"); 39 display = new QListView(this, "display");
40 display->addColumn("Key"); 40 display->addColumn("Key");
41 display->addColumn("Constraint"); 41 display->addColumn("Constraint");
42 display->addColumn("Value"); 42 display->addColumn("Value");
43 display->header()->setClickEnabled(FALSE); 43 display->header()->setClickEnabled(FALSE);
44 display->header()->setResizeEnabled(FALSE); 44 display->header()->setResizeEnabled(FALSE);
45 45
46 vlayout->addWidget(display); 46 vlayout->addWidget(display);
47 47
48 QHBoxLayout *hlayout = new QHBoxLayout; 48 QHBoxLayout *hlayout = new QHBoxLayout;
49 hlayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); 49 hlayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
50 50
51 newFilterButton = new QPushButton(this, "new Filter"); 51 newFilterButton = new QPushButton(this, "new Filter");
52 newFilterButton->setMaximumSize(QSize(50, 32767)); 52 newFilterButton->setMaximumSize(QSize(50, 32767));
53 newFilterButton->setText("New"); 53 newFilterButton->setText("New");
54 hlayout->addWidget(newFilterButton); 54 hlayout->addWidget(newFilterButton);
55 55
56 deleteFilterButton = new QPushButton(this, "delete Filter"); 56 deleteFilterButton = new QPushButton(this, "delete Filter");
57 deleteFilterButton->setMaximumSize(QSize(50, 32767)); 57 deleteFilterButton->setMaximumSize(QSize(50, 32767));
58 deleteFilterButton->setText("Delete"); 58 deleteFilterButton->setText("Delete");
59 hlayout->addWidget(deleteFilterButton); 59 hlayout->addWidget(deleteFilterButton);
60 60
61 clearFilterButton = new QPushButton(this, "delete Filter"); 61 clearFilterButton = new QPushButton(this, "delete Filter");
62 clearFilterButton->setMaximumSize(QSize(60, 32767)); 62 clearFilterButton->setMaximumSize(QSize(60, 32767));
63 clearFilterButton->setText("Clear All"); 63 clearFilterButton->setText("Clear All");
64 hlayout->addWidget(clearFilterButton); 64 hlayout->addWidget(clearFilterButton);
65 65
66 vlayout->addLayout(hlayout); 66 vlayout->addLayout(hlayout);
67 67
68 QHBoxLayout *hlayout2 = new QHBoxLayout; 68 QHBoxLayout *hlayout2 = new QHBoxLayout;
69 69
70 keyNameCombo = new QComboBox(FALSE, this, "key name"); 70 keyNameCombo = new QComboBox(FALSE, this, "key name");
71 keyNameCombo->setEnabled(FALSE); 71 keyNameCombo->setEnabled(FALSE);
72 hlayout2->addWidget(keyNameCombo); 72 hlayout2->addWidget(keyNameCombo);
73 73
74 QLabel *label = new QLabel(this); 74 QLabel *label = new QLabel(this);
75 label->setText("has value"); 75 label->setText("has value");
76 hlayout2->addWidget(label); 76 hlayout2->addWidget(label);
77 77
78 keyEntry = new TVFilterKeyEntry(this, "key entry"); 78 keyEntry = new TVFilterKeyEntry(this, "key entry");
79 keyEntry->setEnabled(FALSE); 79 keyEntry->setEnabled(FALSE);
80 80
81 vlayout->addLayout(hlayout2); 81 vlayout->addLayout(hlayout2);
82 vlayout->addWidget(keyEntry); 82 vlayout->addWidget(keyEntry);
83 83
84 connect(newFilterButton, SIGNAL( clicked() ), this, SLOT( newTerm() )); 84 connect(newFilterButton, SIGNAL( clicked() ), this, SLOT( newTerm() ));
85 connect(deleteFilterButton, SIGNAL( clicked() ), this, SLOT( deleteTerm())); 85 connect(deleteFilterButton, SIGNAL( clicked() ), this, SLOT( deleteTerm()));
86 connect(clearFilterButton, SIGNAL( clicked() ), this, SLOT( clearTerms())); 86 connect(clearFilterButton, SIGNAL( clicked() ), this, SLOT( clearTerms()));
87 87
88 connect(keyEntry, SIGNAL(valueChanged()), this, SLOT( updateTerm() )); 88 connect(keyEntry, SIGNAL(valueChanged()), this, SLOT( updateTerm() ));
89 connect(keyNameCombo, SIGNAL(activated(int)), this, SLOT( updateTerm() )); 89 connect(keyNameCombo, SIGNAL(activated(int)), this, SLOT( updateTerm() ));
90 90
91 connect(display, SIGNAL(selectionChanged(QListViewItem*)), this, 91 connect(display, SIGNAL(selectionChanged(QListViewItem*)), this,
92 SLOT(setTerm(QListViewItem *))); 92 SLOT(setTerm(QListViewItem*)));
93 93
94 ts = t; 94 ts = t;
95 current = 0; 95 current = 0;
96 terms.setAutoDelete(true); 96 terms.setAutoDelete(true);
97 do_filter = false; 97 do_filter = false;
98 98
99#ifdef Q_WS_QWS 99#ifdef Q_WS_QWS
100 QPEApplication::showDialog( this ); 100 QPEApplication::showDialog( this );
101#endif 101#endif
102} 102}
103 103
104/*! 104/*!
105 Destroys the TVFilterView widget 105 Destroys the TVFilterView widget
106*/ 106*/
107TVFilterView::~TVFilterView() 107TVFilterView::~TVFilterView()
108{ 108{
109} 109}
110 110
111void TVFilterView::rebuildData() 111void TVFilterView::rebuildData()
112{ 112{
113} 113}
114 114
115void TVFilterView::reset() 115void TVFilterView::reset()
116{ 116{
117 keyNameCombo->clear(); 117 keyNameCombo->clear();
118 keyIds.clear(); 118 keyIds.clear();
119} 119}
120 120
121void TVFilterView::rebuildKeys() 121void TVFilterView::rebuildKeys()
122{ 122{
123 int i; 123 int i;
124 124
125 if (!ts) return; 125 if (!ts) return;
126 if(!ts->kRep) return; 126 if(!ts->kRep) return;
127 keyEntry->setTableState(ts); 127 keyEntry->setTableState(ts);
128 128
129 /* set up the list of keys that can be compared on */ 129 /* set up the list of keys that can be compared on */
130 keyNameCombo->clear(); 130 keyNameCombo->clear();
131 KeyListIterator it(*ts->kRep); 131 KeyListIterator it(*ts->kRep);
132 132
133 i = 0; 133 i = 0;
134 while(it.current()) { 134 while(it.current()) {
135 if(ts->kRep->validIndex(it.currentKey())) { 135 if(ts->kRep->validIndex(it.currentKey())) {
136 keyNameCombo->insertItem(it.current()->name()); 136 keyNameCombo->insertItem(it.current()->name());
137 keyIds.insert(i, it.currentKey()); 137 keyIds.insert(i, it.currentKey());
138 ++i; 138 ++i;
139 } 139 }
140 ++it; 140 ++it;
141 } 141 }
142} 142}
143 143
144bool TVFilterView::passesFilter(DataElem *d) { 144bool TVFilterView::passesFilter(DataElem *d) {
145 if (!filterActive()) return true; 145 if (!filterActive()) return true;
146 146
147 147
148 FilterTerm *t; 148 FilterTerm *t;
149 149
150 for (t = terms.first(); t != 0; t = terms.next() ) { 150 for (t = terms.first(); t != 0; t = terms.next() ) {
151 /* check against filter */ 151 /* check against filter */
152 switch(t->ct) { 152 switch(t->ct) {
153 case ct_less: 153 case ct_less:
154 if (!d->lessThan(t->keyIndex, t->value)) 154 if (!d->lessThan(t->keyIndex, t->value))
155 return false; 155 return false;
156 break; 156 break;
157 case ct_more: 157 case ct_more:
158 if (!d->moreThan(t->keyIndex, t->value)) 158 if (!d->moreThan(t->keyIndex, t->value))
159 return false; 159 return false;
160 break; 160 break;
161 case ct_equal: 161 case ct_equal:
162 if (!d->equalTo(t->keyIndex, t->value)) 162 if (!d->equalTo(t->keyIndex, t->value))
163 return false; 163 return false;
164 break; 164 break;
165 case ct_contains: 165 case ct_contains:
166 if (!d->contains(t->keyIndex, t->value)) 166 if (!d->contains(t->keyIndex, t->value))
167 return false; 167 return false;
168 break; 168 break;
169 case ct_startswith: 169 case ct_startswith:
170 if (!d->startsWith(t->keyIndex, t->value)) 170 if (!d->startsWith(t->keyIndex, t->value))
171 return false; 171 return false;
172 break; 172 break;
173 case ct_endswith: 173 case ct_endswith:
174 if (!d->endsWith(t->keyIndex, t->value)) 174 if (!d->endsWith(t->keyIndex, t->value))
175 return false; 175 return false;
176 break; 176 break;
177 default: 177 default:
178 qWarning("TVFilterView::passesFilter() " 178 qWarning("TVFilterView::passesFilter() "
179 "unrecognized filter type"); 179 "unrecognized filter type");
180 return false; 180 return false;
181 } 181 }
182 } 182 }
183 return true; 183 return true;
184} 184}
185 185
186bool TVFilterView::filterActive() const 186bool TVFilterView::filterActive() const
187{ 187{
188 /* when button operated, also check the do_filter value 188 /* when button operated, also check the do_filter value
189 return do_filter; 189 return do_filter;
190 */ 190 */
191 if (terms.isEmpty()) 191 if (terms.isEmpty())
192 return false; 192 return false;
193 return true; 193 return true;
194} 194}
195 195
196/* SLOTS */ 196/* SLOTS */
197void TVFilterView::newTerm() 197void TVFilterView::newTerm()
198{ 198{
199 if (!ts) return; 199 if (!ts) return;
200 200
201 FilterTerm *term = new FilterTerm; 201 FilterTerm *term = new FilterTerm;
202 current = term; 202 current = term;
203 203
204 term->view = 0; 204 term->view = 0;
205 205
206 updateTerm(); 206 updateTerm();
207 207
208 display->setSelected(term->view, true); 208 display->setSelected(term->view, true);
209 terms.append(term); 209 terms.append(term);
210 210
211 keyEntry->setEnabled(true); 211 keyEntry->setEnabled(true);
212 keyNameCombo->setEnabled(true); 212 keyNameCombo->setEnabled(true);
213} 213}
214 214
215void TVFilterView::updateTerm() 215void TVFilterView::updateTerm()
216{ 216{
217 FilterTerm *term; 217 FilterTerm *term;
218 /* Read the widget values (keyname, compare type, value) 218 /* Read the widget values (keyname, compare type, value)
219 * and build the lists */ 219 * and build the lists */
220 if (!ts) return; 220 if (!ts) return;
221 if (!current) return; 221 if (!current) return;
222 222
223 QString keyString; 223 QString keyString;
224 QString cmpString; 224 QString cmpString;
225 QString vString; 225 QString vString;
226 226
227 term = current; 227 term = current;
228 228
229 /* create new list item, set initial values, enable widgets */ 229 /* create new list item, set initial values, enable widgets */
230 term->keyIndex = keyIds[keyNameCombo->currentItem()]; 230 term->keyIndex = keyIds[keyNameCombo->currentItem()];
231 keyEntry->setKey(term->keyIndex); /* so the next two items make sense */ 231 keyEntry->setKey(term->keyIndex); /* so the next two items make sense */
232 term->ct = keyEntry->getCompareType(), 232 term->ct = keyEntry->getCompareType(),
233 term->value = keyEntry->getCompareValue(); 233 term->value = keyEntry->getCompareValue();
234 234
235 keyString = keyNameCombo->currentText(); 235 keyString = keyNameCombo->currentText();
236 236
237 switch(term->ct) { 237 switch(term->ct) {
238 case ct_less: 238 case ct_less:
239 cmpString = " less than "; 239 cmpString = " less than ";
240 break; 240 break;
241 case ct_more: 241 case ct_more:
242 cmpString = " more than "; 242 cmpString = " more than ";
243 break; 243 break;
244 case ct_equal: 244 case ct_equal:
245 cmpString = " equal to "; 245 cmpString = " equal to ";
246 break; 246 break;
247 case ct_contains: 247 case ct_contains:
248 cmpString = " containing "; 248 cmpString = " containing ";
249 break; 249 break;
250 case ct_startswith: 250 case ct_startswith:
251 cmpString = " starting with "; 251 cmpString = " starting with ";
252 break; 252 break;
253 case ct_endswith: 253 case ct_endswith:
254 cmpString = " ending with "; 254 cmpString = " ending with ";
255 break; 255 break;
256 default: 256 default:
257 cmpString = " ERROR "; 257 cmpString = " ERROR ";
258 } 258 }
259 259
260 vString = term->value.toString(); 260 vString = term->value.toString();
261 261
262 /* remove old view */ 262 /* remove old view */
263 if (term->view) 263 if (term->view)
264 delete(term->view); 264 delete(term->view);
265 term->view = new QListViewItem(display, 0, keyString, cmpString, vString); 265 term->view = new QListViewItem(display, 0, keyString, cmpString, vString);
266 display->setSelected(term->view, true); 266 display->setSelected(term->view, true);
267} 267}
268 268
269/* deletes current term */ 269/* deletes current term */
270void TVFilterView::deleteTerm() 270void TVFilterView::deleteTerm()
271{ 271{
272 if(!current) return; 272 if(!current) return;
273 if (current->view) 273 if (current->view)
274 delete(current->view); 274 delete(current->view);
275 275
276 terms.removeRef(current); 276 terms.removeRef(current);
277 277
278 current = terms.first(); 278 current = terms.first();
279 279
280 if(terms.isEmpty()) { 280 if(terms.isEmpty()) {
281 keyEntry->setEnabled(false); 281 keyEntry->setEnabled(false);
282 keyNameCombo->setEnabled(false); 282 keyNameCombo->setEnabled(false);
283 } 283 }
284} 284}
285 285
286/* clears all terminations */ 286/* clears all terminations */
287void TVFilterView::clearTerms() 287void TVFilterView::clearTerms()
288{ 288{
289 while(current) 289 while(current)
290 deleteTerm(); 290 deleteTerm();
291} 291}
292 292
293void TVFilterView::setTerm(QListViewItem *target) 293void TVFilterView::setTerm(QListViewItem *target)
294{ 294{
295 /* Iterate through the list to find item with view=target.. 295 /* Iterate through the list to find item with view=target..
296 * set as current, delete */ 296 * set as current, delete */
297 FilterTerm *term = current; 297 FilterTerm *term = current;
298 298
299 for (current = terms.first(); current != 0; current = terms.next() ) 299 for (current = terms.first(); current != 0; current = terms.next() )
300 if (current->view == target) 300 if (current->view == target)
301 break; 301 break;
302 302
303 if (!current) { 303 if (!current) {
304 current = term; 304 current = term;
305 } 305 }
306} 306}
diff --git a/noncore/apps/tableviewer/ui/tvlistview.cpp b/noncore/apps/tableviewer/ui/tvlistview.cpp
index b25e813..b10ff1d 100644
--- a/noncore/apps/tableviewer/ui/tvlistview.cpp
+++ b/noncore/apps/tableviewer/ui/tvlistview.cpp
@@ -1,315 +1,315 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include "tvlistview.h" 20#include "tvlistview.h"
21#include "../db/common.h" 21#include "../db/common.h"
22#include <qtoolbutton.h> 22#include <qtoolbutton.h>
23#include <qlistview.h> 23#include <qlistview.h>
24#include <qlayout.h> 24#include <qlayout.h>
25 25
26void TVListViewPrivate::setColumnWidth(int column, int width) 26void TVListViewPrivate::setColumnWidth(int column, int width)
27{ 27{
28 if(width > 70) width = 70; 28 if(width > 70) width = 70;
29 QListView::setColumnWidth(column, width); 29 QListView::setColumnWidth(column, width);
30} 30}
31 31
32void TVListViewPrivate::setSorting(int column, bool increasing) 32void TVListViewPrivate::setSorting(int column, bool increasing)
33{ 33{
34 emit sortChanged(column); 34 emit sortChanged(column);
35 QListView::setSorting(column, increasing); 35 QListView::setSorting(column, increasing);
36} 36}
37 37
38TVListViewPrivate::TVListViewPrivate(QWidget *parent, const char* name, 38TVListViewPrivate::TVListViewPrivate(QWidget *parent, const char* name,
39 WFlags fl) : QListView(parent, name, fl) { 39 WFlags fl) : QListView(parent, name, fl) {
40 ; 40 ;
41} 41}
42 42
43class TVListViewItem : public QListViewItem 43class TVListViewItem : public QListViewItem
44{ 44{
45public: 45public:
46 46
47 TVListViewItem(QListView *parent, DataElem *d); 47 TVListViewItem(QListView *parent, DataElem *d);
48 ~TVListViewItem(); 48 ~TVListViewItem();
49 49
50 QString text(int i) const 50 QString text(int i) const
51 { 51 {
52 return data_reference->toQString(i); 52 return data_reference->toQString(i);
53 } 53 }
54 54
55 /* Do nothing... all data for this item should be generated */ 55 /* Do nothing... all data for this item should be generated */
56 void setText(int i, const QString &) 56 void setText(int i, const QString &)
57 { 57 {
58 ; 58 ;
59 } 59 }
60 QString key(int i, bool a) const 60 QString key(int i, bool a) const
61 { 61 {
62 return data_reference->toSortableQString(i); 62 return data_reference->toSortableQString(i);
63 } 63 }
64 64
65 void setDataElem(DataElem *d) 65 void setDataElem(DataElem *d)
66 { 66 {
67 data_reference = d; 67 data_reference = d;
68 } 68 }
69 69
70 DataElem *getDataElem() { 70 DataElem *getDataElem() {
71 return data_reference; 71 return data_reference;
72 } 72 }
73private: 73private:
74 DataElem *data_reference; 74 DataElem *data_reference;
75}; 75};
76 76
77TVListViewItem::TVListViewItem(QListView *parent, DataElem *d) 77TVListViewItem::TVListViewItem(QListView *parent, DataElem *d)
78 : QListViewItem(parent) 78 : QListViewItem(parent)
79{ 79{
80 data_reference = d; 80 data_reference = d;
81} 81}
82 82
83TVListViewItem::~TVListViewItem() 83TVListViewItem::~TVListViewItem()
84{ 84{
85 data_reference = 0; 85 data_reference = 0;
86} 86}
87 87
88TVListView::TVListView(TableState *t, QWidget* parent, 88TVListView::TVListView(TableState *t, QWidget* parent,
89 const char *name, WFlags fl ) : QWidget(parent, name, fl) 89 const char *name, WFlags fl ) : QWidget(parent, name, fl)
90{ 90{
91 if (!name) 91 if (!name)
92 setName("TVListView"); 92 setName("TVListView");
93 93
94 // the next two lines need to be rationalized. 94 // the next two lines need to be rationalized.
95 resize(318,457); 95 resize(318,457);
96 setSizePolicy(QSizePolicy((QSizePolicy::SizeType)7, 96 setSizePolicy(QSizePolicy((QSizePolicy::SizeType)7,
97 (QSizePolicy::SizeType)7, sizePolicy().hasHeightForWidth())); 97 (QSizePolicy::SizeType)7, sizePolicy().hasHeightForWidth()));
98 setCaption(tr("List View")); 98 setCaption(tr("List View"));
99 99
100 QVBoxLayout *layout = new QVBoxLayout(this); 100 QVBoxLayout *layout = new QVBoxLayout(this);
101 layout->setSpacing(0); 101 layout->setSpacing(0);
102 layout->setMargin(0); 102 layout->setMargin(0);
103 103
104 listViewDisplay = new TVListViewPrivate(this, "listViewDisplay"); 104 listViewDisplay = new TVListViewPrivate(this, "listViewDisplay");
105 layout->addWidget(listViewDisplay); 105 layout->addWidget(listViewDisplay);
106 106
107 connect(listViewDisplay, SIGNAL(currentChanged(QListViewItem *)), this, 107 connect(listViewDisplay, SIGNAL(currentChanged(QListViewItem*)), this,
108 SLOT(setCurrent(QListViewItem *))); 108 SLOT(setCurrent(QListViewItem*)));
109 connect(listViewDisplay, SIGNAL(sortChanged(int)), this, 109 connect(listViewDisplay, SIGNAL(sortChanged(int)), this,
110 SLOT(setSorting(int))); 110 SLOT(setSorting(int)));
111 111
112 listViewDisplay->setShowSortIndicator(true); 112 listViewDisplay->setShowSortIndicator(true);
113 113
114 it = new QListViewItemIterator(listViewDisplay); 114 it = new QListViewItemIterator(listViewDisplay);
115 ts = t; 115 ts = t;
116} 116}
117 117
118TVListView::~TVListView() 118TVListView::~TVListView()
119{ 119{
120} 120}
121 121
122void TVListView::addItem(DataElem *d) 122void TVListView::addItem(DataElem *d)
123{ 123{
124 TVListViewItem *i = new TVListViewItem(listViewDisplay, d); 124 TVListViewItem *i = new TVListViewItem(listViewDisplay, d);
125 125
126 delete it; 126 delete it;
127 it = new QListViewItemIterator(i); 127 it = new QListViewItemIterator(i);
128} 128}
129 129
130/* remove current (it) item */ 130/* remove current (it) item */
131void TVListView::removeItem() 131void TVListView::removeItem()
132{ 132{
133 QListViewItemIterator other(*it); 133 QListViewItemIterator other(*it);
134 134
135 QListViewItemIterator tmp = *it; 135 QListViewItemIterator tmp = *it;
136 (*it)++; 136 (*it)++;
137 if (!it->current()) { 137 if (!it->current()) {
138 *it = tmp; 138 *it = tmp;
139 (*it)--; 139 (*it)--;
140 if (!it->current()) { 140 if (!it->current()) {
141 delete it; 141 delete it;
142 it = 0; 142 it = 0;
143 } 143 }
144 } 144 }
145 145
146 delete other.current(); 146 delete other.current();
147} 147}
148 148
149void TVListView::clearItems() 149void TVListView::clearItems()
150{ 150{
151 /* This is ok since the destructor for TVListItem does not know about 151 /* This is ok since the destructor for TVListItem does not know about
152 the data_reference pointer.. and hence will leave it alone */ 152 the data_reference pointer.. and hence will leave it alone */
153 listViewDisplay->clear(); 153 listViewDisplay->clear();
154 delete it; 154 delete it;
155 it = new QListViewItemIterator(listViewDisplay); 155 it = new QListViewItemIterator(listViewDisplay);
156} 156}
157 157
158void TVListView::first() 158void TVListView::first()
159{ 159{
160 delete it; 160 delete it;
161 it = new QListViewItemIterator(listViewDisplay); 161 it = new QListViewItemIterator(listViewDisplay);
162} 162}
163 163
164void TVListView::last() 164void TVListView::last()
165{ 165{
166 qWarning("TVListView::last not yet implemented"); 166 qWarning("TVListView::last not yet implemented");
167} 167}
168 168
169void TVListView::next() 169void TVListView::next()
170{ 170{
171 QListViewItemIterator tmp = *it; 171 QListViewItemIterator tmp = *it;
172 (*it)++; 172 (*it)++;
173 if (!it->current()) { 173 if (!it->current()) {
174 *it = tmp; 174 *it = tmp;
175 } 175 }
176} 176}
177 177
178void TVListView::previous() 178void TVListView::previous()
179{ 179{
180 QListViewItemIterator tmp = *it; 180 QListViewItemIterator tmp = *it;
181 (*it)--; 181 (*it)--;
182 if (!it->current()) { 182 if (!it->current()) {
183 *it = tmp; 183 *it = tmp;
184 } 184 }
185} 185}
186 186
187DataElem *TVListView::getCurrentData() { 187DataElem *TVListView::getCurrentData() {
188 if (it->current()) { 188 if (it->current()) {
189 return ((TVListViewItem *)it->current())->getDataElem(); 189 return ((TVListViewItem *)it->current())->getDataElem();
190 } 190 }
191 return NULL; 191 return NULL;
192} 192}
193 193
194/*! Now to implement the closest match function */ 194/*! Now to implement the closest match function */
195void TVListView::findItem(int keyId, TVVariant value) 195void TVListView::findItem(int keyId, TVVariant value)
196{ 196{
197 QListViewItem *i; 197 QListViewItem *i;
198 TVListViewItem *best_so_far = NULL; 198 TVListViewItem *best_so_far = NULL;
199 /* start at the beginning... go through till find the closest elem */ 199 /* start at the beginning... go through till find the closest elem */
200 i = listViewDisplay->firstChild(); 200 i = listViewDisplay->firstChild();
201 while (i) { 201 while (i) {
202 /* search stuff */ 202 /* search stuff */
203 if(best_so_far) { 203 if(best_so_far) {
204 if (DataElem::closer( 204 if (DataElem::closer(
205 ((TVListViewItem *)i)->getDataElem(), 205 ((TVListViewItem *)i)->getDataElem(),
206 best_so_far->getDataElem(), value, keyId)) 206 best_so_far->getDataElem(), value, keyId))
207 best_so_far = (TVListViewItem *)i; 207 best_so_far = (TVListViewItem *)i;
208 } else { 208 } else {
209 if (DataElem::closer( 209 if (DataElem::closer(
210 ((TVListViewItem *)i)->getDataElem(), 210 ((TVListViewItem *)i)->getDataElem(),
211 NULL, value, keyId)) 211 NULL, value, keyId))
212 best_so_far = (TVListViewItem *)i; 212 best_so_far = (TVListViewItem *)i;
213 } 213 }
214 214
215 i = i->itemBelow(); 215 i = i->itemBelow();
216 } 216 }
217 if (best_so_far) { 217 if (best_so_far) {
218 /* set best_so_far to current element */ 218 /* set best_so_far to current element */
219 delete it; 219 delete it;
220 it = new QListViewItemIterator(best_so_far); 220 it = new QListViewItemIterator(best_so_far);
221 } 221 }
222} 222}
223 223
224void TVListView::rebuildKeys() 224void TVListView::rebuildKeys()
225{ 225{
226 int i; 226 int i;
227 if(!ts) return; 227 if(!ts) return;
228 if(!ts->kRep) return; 228 if(!ts->kRep) return;
229 229
230 i = listViewDisplay->columns(); 230 i = listViewDisplay->columns();
231 231
232 while(i > 0) 232 while(i > 0)
233 listViewDisplay->removeColumn(--i); 233 listViewDisplay->removeColumn(--i);
234 234
235 KeyListIterator kit(*ts->kRep); 235 KeyListIterator kit(*ts->kRep);
236 i = 0; 236 i = 0;
237 while(kit.current()) { 237 while(kit.current()) {
238 if(!kit.current()->delFlag()) { 238 if(!kit.current()->delFlag()) {
239 listViewDisplay->addColumn(kit.current()->name()); 239 listViewDisplay->addColumn(kit.current()->name());
240 keyIds.insert(i, kit.currentKey()); 240 keyIds.insert(i, kit.currentKey());
241 ++i; 241 ++i;
242 } 242 }
243 ++kit; 243 ++kit;
244 } 244 }
245} 245}
246 246
247 247
248void TVListView::setSorting(int column) 248void TVListView::setSorting(int column)
249{ 249{
250 /* Without table state can't do anything */ 250 /* Without table state can't do anything */
251 if (ts == 0) 251 if (ts == 0)
252 return; 252 return;
253 if (keyIds[column] != ts->current_column) { 253 if (keyIds[column] != ts->current_column) {
254 ts->current_column = keyIds[column]; 254 ts->current_column = keyIds[column];
255 } 255 }
256} 256}
257 257
258void TVListView::rebuildData() { 258void TVListView::rebuildData() {
259 int i; 259 int i;
260 QMap<int, int>::Iterator kit; 260 QMap<int, int>::Iterator kit;
261 /* Need to set sort order */ 261 /* Need to set sort order */
262 if(!ts) 262 if(!ts)
263 return; 263 return;
264 264
265 /* revers lookup the column */ 265 /* revers lookup the column */
266 i = -1; 266 i = -1;
267 for(kit = keyIds.begin(); kit != keyIds.end(); ++kit) { 267 for(kit = keyIds.begin(); kit != keyIds.end(); ++kit) {
268 if (kit.data() == ts->current_column) { 268 if (kit.data() == ts->current_column) {
269 i = kit.key(); 269 i = kit.key();
270 break; 270 break;
271 } 271 }
272 } 272 }
273 if (i == -1) 273 if (i == -1)
274 return; 274 return;
275 275
276 listViewDisplay->setSorting(i); 276 listViewDisplay->setSorting(i);
277 listViewDisplay->sort(); 277 listViewDisplay->sort();
278 278
279 /* reset current element */ 279 /* reset current element */
280 listViewDisplay->setCurrentItem(it->current()); 280 listViewDisplay->setCurrentItem(it->current());
281 listViewDisplay->setSelected(it->current(), true); 281 listViewDisplay->setSelected(it->current(), true);
282 listViewDisplay->ensureItemVisible(it->current()); 282 listViewDisplay->ensureItemVisible(it->current());
283} 283}
284 284
285void TVListView::reset() 285void TVListView::reset()
286{ 286{
287 int i; 287 int i;
288 listViewDisplay->clear(); 288 listViewDisplay->clear();
289 289
290 i = listViewDisplay->columns(); 290 i = listViewDisplay->columns();
291 while (i > 0) 291 while (i > 0)
292 listViewDisplay->removeColumn(--i); 292 listViewDisplay->removeColumn(--i);
293 293
294 keyIds.clear(); 294 keyIds.clear();
295} 295}
296 296
297void TVListView::setCurrent(QListViewItem *i) 297void TVListView::setCurrent(QListViewItem *i)
298{ 298{
299 /* cast */ 299 /* cast */
300 TVListViewItem *t = (TVListViewItem *)i; 300 TVListViewItem *t = (TVListViewItem *)i;
301 301
302 if(!t) { 302 if(!t) {
303 /* set current to null */ 303 /* set current to null */
304 ts->current_elem = 0; 304 ts->current_elem = 0;
305 return; 305 return;
306 } 306 }
307 307
308 ts->current_elem = t->getDataElem(); 308 ts->current_elem = t->getDataElem();
309 /* now also set up the iterator */ 309 /* now also set up the iterator */
310 310
311 delete it; 311 delete it;
312 it = new QListViewItemIterator(i); 312 it = new QListViewItemIterator(i);
313 313
314 //emit browseView(); 314 //emit browseView();
315} 315}
diff --git a/noncore/apps/tinykate/libkate/document/katedialogs.cpp b/noncore/apps/tinykate/libkate/document/katedialogs.cpp
index 2f0ed7b..f4edd7e 100644
--- a/noncore/apps/tinykate/libkate/document/katedialogs.cpp
+++ b/noncore/apps/tinykate/libkate/document/katedialogs.cpp
@@ -1,588 +1,588 @@
1/*************************************************************************** 1/***************************************************************************
2 katedialogs.cpp - description 2 katedialogs.cpp - description
3 ------------------- 3 -------------------
4 copyright : (C) 2001 by The Kate Team 4 copyright : (C) 2001 by The Kate Team
5 (C) 2002 by Joseph Wenninger 5 (C) 2002 by Joseph Wenninger
6 email : kwrite-devel@kde.org 6 email : kwrite-devel@kde.org
7 jowenn@kde.org 7 jowenn@kde.org
8 8
9 ***************************************************************************/ 9 ***************************************************************************/
10 10
11/*************************************************************************** 11/***************************************************************************
12 * * 12 * *
13 * This program is free software; you can redistribute it and/or modify * 13 * This program is free software; you can redistribute it and/or modify *
14 * it under the terms of the GNU General Public License as published by * 14 * it under the terms of the GNU General Public License as published by *
15 * the Free Software Foundation; either version 2 of the License, or * 15 * the Free Software Foundation; either version 2 of the License, or *
16 * (at your option) any later version. * 16 * (at your option) any later version. *
17 * * 17 * *
18 ***************************************************************************/ 18 ***************************************************************************/
19#include "katedialogs.h" 19#include "katedialogs.h"
20#include <klocale.h> 20#include <klocale.h>
21#include <kdebug.h> 21#include <kdebug.h>
22#include <qgroupbox.h> 22#include <qgroupbox.h>
23#include <qvgroupbox.h> 23#include <qvgroupbox.h>
24#include <qhgroupbox.h> 24#include <qhgroupbox.h>
25#include <qhbox.h> 25#include <qhbox.h>
26#include <qvbox.h> 26#include <qvbox.h>
27#include <qlayout.h> 27#include <qlayout.h>
28#include <qpushbutton.h> 28#include <qpushbutton.h>
29#include <qwidgetstack.h> 29#include <qwidgetstack.h>
30#include <qlabel.h> 30#include <qlabel.h>
31#include <qlistview.h> 31#include <qlistview.h>
32#include <qlineedit.h> 32#include <qlineedit.h>
33#include <qcombobox.h> 33#include <qcombobox.h>
34#include <qcheckbox.h> 34#include <qcheckbox.h>
35//FIXME #include <kcharsets.h> 35//FIXME #include <kcharsets.h>
36#include <kglobal.h> 36#include <kglobal.h>
37#include <qmap.h> 37#include <qmap.h>
38#include <kmessagebox.h> 38#include <kmessagebox.h>
39#include <kstddirs.h> 39#include <kstddirs.h>
40 40
41 41
42/******************************************************************************************************************* 42/*******************************************************************************************************************
43* Context Editor * 43* Context Editor *
44*******************************************************************************************************************/ 44*******************************************************************************************************************/
45 45
46StyleChanger::StyleChanger( QWidget *parent ) 46StyleChanger::StyleChanger( QWidget *parent )
47 : QWidget(parent) 47 : QWidget(parent)
48{ 48{
49 QLabel *label; 49 QLabel *label;
50 50
51 QGridLayout *glay = new QGridLayout( this, 4, 3, 0, KDialog::spacingHint() ); 51 QGridLayout *glay = new QGridLayout( this, 4, 3, 0, KDialog::spacingHint() );
52 CHECK_PTR(glay); 52 CHECK_PTR(glay);
53 glay->addColSpacing( 1, KDialog::spacingHint() ); // Looks better 53 glay->addColSpacing( 1, KDialog::spacingHint() ); // Looks better
54 glay->setColStretch( 2, 10 ); 54 glay->setColStretch( 2, 10 );
55 55
56 col = new KColorButton(this); 56 col = new KColorButton(this);
57 CHECK_PTR(col); 57 CHECK_PTR(col);
58 connect(col,SIGNAL(changed(const QColor &)),this,SLOT(changed())); 58 connect(col,SIGNAL(changed(const QColor&)),this,SLOT(changed()));
59 label = new QLabel(col,i18n("Normal:"),this); 59 label = new QLabel(col,i18n("Normal:"),this);
60 CHECK_PTR(label); 60 CHECK_PTR(label);
61 glay->addWidget(label,0,0); 61 glay->addWidget(label,0,0);
62 glay->addWidget(col,1,0); 62 glay->addWidget(col,1,0);
63 63
64 selCol = new KColorButton(this); 64 selCol = new KColorButton(this);
65 CHECK_PTR(selCol); 65 CHECK_PTR(selCol);
66 connect(selCol,SIGNAL(changed(const QColor &)),this,SLOT(changed())); 66 connect(selCol,SIGNAL(changed(const QColor&)),this,SLOT(changed()));
67 label = new QLabel(selCol,i18n("Selected:"),this); 67 label = new QLabel(selCol,i18n("Selected:"),this);
68 CHECK_PTR(label); 68 CHECK_PTR(label);
69 glay->addWidget(label,2,0); 69 glay->addWidget(label,2,0);
70 glay->addWidget(selCol,3,0); 70 glay->addWidget(selCol,3,0);
71 71
72 bold = new QCheckBox(i18n("Bold"),this); 72 bold = new QCheckBox(i18n("Bold"),this);
73 CHECK_PTR(bold); 73 CHECK_PTR(bold);
74 connect(bold,SIGNAL(clicked()),SLOT(changed())); 74 connect(bold,SIGNAL(clicked()),SLOT(changed()));
75 glay->addWidget(bold,1,2); 75 glay->addWidget(bold,1,2);
76 76
77 italic = new QCheckBox(i18n("Italic"),this); 77 italic = new QCheckBox(i18n("Italic"),this);
78 CHECK_PTR(italic); 78 CHECK_PTR(italic);
79 connect(italic,SIGNAL(clicked()),SLOT(changed())); 79 connect(italic,SIGNAL(clicked()),SLOT(changed()));
80 glay->addWidget(italic,2,2); 80 glay->addWidget(italic,2,2);
81} 81}
82 82
83void StyleChanger::setRef(ItemStyle *s) { 83void StyleChanger::setRef(ItemStyle *s) {
84 84
85 style = s; 85 style = s;
86 col->setColor(style->col); 86 col->setColor(style->col);
87 selCol->setColor(style->selCol); 87 selCol->setColor(style->selCol);
88 bold->setChecked(style->bold); 88 bold->setChecked(style->bold);
89 italic->setChecked(style->italic); 89 italic->setChecked(style->italic);
90 90
91} 91}
92 92
93void StyleChanger::setEnabled(bool enable) { 93void StyleChanger::setEnabled(bool enable) {
94 94
95 col->setEnabled(enable); 95 col->setEnabled(enable);
96 selCol->setEnabled(enable); 96 selCol->setEnabled(enable);
97 bold->setEnabled(enable); 97 bold->setEnabled(enable);
98 italic->setEnabled(enable); 98 italic->setEnabled(enable);
99} 99}
100 100
101void StyleChanger::changed() { 101void StyleChanger::changed() {
102 102
103 if (style) { 103 if (style) {
104 style->col = col->color(); 104 style->col = col->color();
105 style->selCol = selCol->color(); 105 style->selCol = selCol->color();
106 style->bold = bold->isChecked(); 106 style->bold = bold->isChecked();
107 style->italic = italic->isChecked(); 107 style->italic = italic->isChecked();
108 } 108 }
109} 109}
110 110
111HighlightDialog::HighlightDialog( HlManager *hlManager, ItemStyleList *styleList, 111HighlightDialog::HighlightDialog( HlManager *hlManager, ItemStyleList *styleList,
112 HlDataList *highlightDataList, 112 HlDataList *highlightDataList,
113 int hlNumber, QWidget *parent, 113 int hlNumber, QWidget *parent,
114 const char *name, bool modal ) 114 const char *name, bool modal )
115 :KDialogBase(parent,name,modal,i18n("Highlight Settings"), Ok|Cancel, Ok) 115 :KDialogBase(parent,name,modal,i18n("Highlight Settings"), Ok|Cancel, Ok)
116{ 116{
117// QVBox *page = makeVBoxMainWidget(); 117// QVBox *page = makeVBoxMainWidget();
118 QFrame *page=addPage("FIXME"); 118 QFrame *page=addPage("FIXME");
119 (new QVBoxLayout(page))->setAutoAdd(true); 119 (new QVBoxLayout(page))->setAutoAdd(true);
120 content=new HighlightDialogPage(hlManager,styleList,highlightDataList,hlNumber,page); 120 content=new HighlightDialogPage(hlManager,styleList,highlightDataList,hlNumber,page);
121} 121}
122 122
123void HighlightDialog::done(int r) 123void HighlightDialog::done(int r)
124{ 124{
125 kdDebug(13010)<<"HighlightDialod done"<<endl; 125 kdDebug(13010)<<"HighlightDialod done"<<endl;
126 content->saveData(); 126 content->saveData();
127 KDialogBase::done(r); 127 KDialogBase::done(r);
128} 128}
129 129
130HighlightDialogPage::HighlightDialogPage(HlManager *hlManager, ItemStyleList *styleList, 130HighlightDialogPage::HighlightDialogPage(HlManager *hlManager, ItemStyleList *styleList,
131 HlDataList* highlightDataList, 131 HlDataList* highlightDataList,
132 int hlNumber,QWidget *parent, const char *name) 132 int hlNumber,QWidget *parent, const char *name)
133 :QTabWidget(parent,name),defaultItemStyleList(styleList),hlData(0L) 133 :QTabWidget(parent,name),defaultItemStyleList(styleList),hlData(0L)
134 134
135{ 135{
136 136
137 // defaults ========================================================= 137 // defaults =========================================================
138 138
139 QFrame *page1 = new QFrame(this); 139 QFrame *page1 = new QFrame(this);
140 addTab(page1,i18n("&Defaults")); 140 addTab(page1,i18n("&Defaults"));
141 QGridLayout *grid = new QGridLayout(page1, 1, 1); 141 QGridLayout *grid = new QGridLayout(page1, 1, 1);
142 142
143 QVGroupBox *dvbox1 = new QVGroupBox( i18n("Default Item Styles"), page1 ); 143 QVGroupBox *dvbox1 = new QVGroupBox( i18n("Default Item Styles"), page1 );
144 /*QLabel *label = */new QLabel( i18n("Item:"), dvbox1 ); 144 /*QLabel *label = */new QLabel( i18n("Item:"), dvbox1 );
145 QComboBox *styleCombo = new QComboBox( false, dvbox1 ); 145 QComboBox *styleCombo = new QComboBox( false, dvbox1 );
146 defaultStyleChanger = new StyleChanger( dvbox1 ); 146 defaultStyleChanger = new StyleChanger( dvbox1 );
147 for( int i = 0; i < hlManager->defaultStyles(); i++ ) { 147 for( int i = 0; i < hlManager->defaultStyles(); i++ ) {
148 styleCombo->insertItem(hlManager->defaultStyleName(i)); 148 styleCombo->insertItem(hlManager->defaultStyleName(i));
149 } 149 }
150 connect(styleCombo, SIGNAL(activated(int)), this, SLOT(defaultChanged(int))); 150 connect(styleCombo, SIGNAL(activated(int)), this, SLOT(defaultChanged(int)));
151 grid->addWidget(dvbox1, 0,0); 151 grid->addWidget(dvbox1, 0,0);
152 152
153 defaultChanged(0); 153 defaultChanged(0);
154 154
155 // highlight modes ===================================================== 155 // highlight modes =====================================================
156 156
157 QFrame *page2 = new QFrame(this); 157 QFrame *page2 = new QFrame(this);
158 addTab(page2,i18n("&Highlight Modes")); 158 addTab(page2,i18n("&Highlight Modes"));
159 //grid = new QGridLayout(page2,2,2); 159 //grid = new QGridLayout(page2,2,2);
160 QVBoxLayout *bl=new QVBoxLayout(page2); 160 QVBoxLayout *bl=new QVBoxLayout(page2);
161 bl->setAutoAdd(true); 161 bl->setAutoAdd(true);
162 QHGroupBox *hbox1 = new QHGroupBox( i18n("Config Select"), page2 ); 162 QHGroupBox *hbox1 = new QHGroupBox( i18n("Config Select"), page2 );
163 hbox1->layout()->setMargin(5); 163 hbox1->layout()->setMargin(5);
164 QVBox *vbox1=new QVBox(hbox1); 164 QVBox *vbox1=new QVBox(hbox1);
165// grid->addMultiCellWidget(vbox1,0,0,0,1); 165// grid->addMultiCellWidget(vbox1,0,0,0,1);
166 QVGroupBox *vbox2 = new QVGroupBox( i18n("Item Style"), page2 ); 166 QVGroupBox *vbox2 = new QVGroupBox( i18n("Item Style"), page2 );
167// grid->addWidget(vbox2,1,0); 167// grid->addWidget(vbox2,1,0);
168 QVGroupBox *vbox3 = new QVGroupBox( i18n("Highlight Auto Select"), hbox1 ); 168 QVGroupBox *vbox3 = new QVGroupBox( i18n("Highlight Auto Select"), hbox1 );
169 //grid->addWidget(vbox3,1,1); 169 //grid->addWidget(vbox3,1,1);
170 170
171 QLabel *label = new QLabel( i18n("Highlight:"), vbox1 ); 171 QLabel *label = new QLabel( i18n("Highlight:"), vbox1 );
172 hlCombo = new QComboBox( false, vbox1 ); 172 hlCombo = new QComboBox( false, vbox1 );
173 QHBox *modHl = new QHBox(vbox1); 173 QHBox *modHl = new QHBox(vbox1);
174// connect(new QPushButton(i18n("New"),modHl),SIGNAL(clicked()),this,SLOT(hlNew())); 174// connect(new QPushButton(i18n("New"),modHl),SIGNAL(clicked()),this,SLOT(hlNew()));
175// connect(new QPushButton(i18n("Edit"),modHl),SIGNAL(clicked()),this,SLOT(hlEdit())); 175// connect(new QPushButton(i18n("Edit"),modHl),SIGNAL(clicked()),this,SLOT(hlEdit()));
176 connect( hlCombo, SIGNAL(activated(int)), 176 connect( hlCombo, SIGNAL(activated(int)),
177 this, SLOT(hlChanged(int)) ); 177 this, SLOT(hlChanged(int)) );
178 for( int i = 0; i < hlManager->highlights(); i++) { 178 for( int i = 0; i < hlManager->highlights(); i++) {
179 hlCombo->insertItem(hlManager->hlName(i)); 179 hlCombo->insertItem(hlManager->hlName(i));
180 } 180 }
181 hlCombo->setCurrentItem(hlNumber); 181 hlCombo->setCurrentItem(hlNumber);
182 182
183 183
184 label = new QLabel( i18n("Item:"), vbox2 ); 184 label = new QLabel( i18n("Item:"), vbox2 );
185 itemCombo = new QComboBox( false, vbox2 ); 185 itemCombo = new QComboBox( false, vbox2 );
186 connect( itemCombo, SIGNAL(activated(int)), this, SLOT(itemChanged(int)) ); 186 connect( itemCombo, SIGNAL(activated(int)), this, SLOT(itemChanged(int)) );
187 187
188 label = new QLabel( i18n("File Extensions:"), vbox3 ); 188 label = new QLabel( i18n("File Extensions:"), vbox3 );
189 wildcards = new QLineEdit( vbox3 ); 189 wildcards = new QLineEdit( vbox3 );
190 label = new QLabel( i18n("Mime Types:"), vbox3 ); 190 label = new QLabel( i18n("Mime Types:"), vbox3 );
191 mimetypes = new QLineEdit( vbox3 ); 191 mimetypes = new QLineEdit( vbox3 );
192 192
193 193
194 styleDefault = new QCheckBox(i18n("Default"), vbox2 ); 194 styleDefault = new QCheckBox(i18n("Default"), vbox2 );
195 connect(styleDefault,SIGNAL(clicked()),SLOT(changed())); 195 connect(styleDefault,SIGNAL(clicked()),SLOT(changed()));
196 styleChanger = new StyleChanger( vbox2 ); 196 styleChanger = new StyleChanger( vbox2 );
197 197
198 hlDataList = highlightDataList; 198 hlDataList = highlightDataList;
199 hlChanged(hlNumber); 199 hlChanged(hlNumber);
200} 200}
201 201
202 202
203void HighlightDialogPage::defaultChanged(int z) 203void HighlightDialogPage::defaultChanged(int z)
204{ 204{
205 defaultStyleChanger->setRef(defaultItemStyleList->at(z)); 205 defaultStyleChanger->setRef(defaultItemStyleList->at(z));
206} 206}
207 207
208 208
209void HighlightDialogPage::hlChanged(int z) 209void HighlightDialogPage::hlChanged(int z)
210{ 210{
211 writeback(); 211 writeback();
212 212
213 hlData = hlDataList->at(z); 213 hlData = hlDataList->at(z);
214 214
215 wildcards->setText(hlData->wildcards); 215 wildcards->setText(hlData->wildcards);
216 mimetypes->setText(hlData->mimetypes); 216 mimetypes->setText(hlData->mimetypes);
217 217
218 itemCombo->clear(); 218 itemCombo->clear();
219 for (ItemData *itemData = hlData->itemDataList.first(); itemData != 0L; 219 for (ItemData *itemData = hlData->itemDataList.first(); itemData != 0L;
220 itemData = hlData->itemDataList.next()) { 220 itemData = hlData->itemDataList.next()) {
221 kdDebug(13010) << itemData->name << endl; 221 kdDebug(13010) << itemData->name << endl;
222 itemCombo->insertItem(i18n(itemData->name.latin1())); 222 itemCombo->insertItem(i18n(itemData->name.latin1()));
223 } 223 }
224 224
225 itemChanged(0); 225 itemChanged(0);
226} 226}
227 227
228void HighlightDialogPage::itemChanged(int z) 228void HighlightDialogPage::itemChanged(int z)
229{ 229{
230 itemData = hlData->itemDataList.at(z); 230 itemData = hlData->itemDataList.at(z);
231 231
232 styleDefault->setChecked(itemData->defStyle); 232 styleDefault->setChecked(itemData->defStyle);
233 styleChanger->setRef(itemData); 233 styleChanger->setRef(itemData);
234} 234}
235 235
236void HighlightDialogPage::changed() 236void HighlightDialogPage::changed()
237{ 237{
238 itemData->defStyle = styleDefault->isChecked(); 238 itemData->defStyle = styleDefault->isChecked();
239} 239}
240 240
241void HighlightDialogPage::writeback() { 241void HighlightDialogPage::writeback() {
242 if (hlData) { 242 if (hlData) {
243 hlData->wildcards = wildcards->text(); 243 hlData->wildcards = wildcards->text();
244 hlData->mimetypes = mimetypes->text(); 244 hlData->mimetypes = mimetypes->text();
245 } 245 }
246} 246}
247 247
248void HighlightDialogPage::saveData() { 248void HighlightDialogPage::saveData() {
249 kdDebug(13010)<<"HighlightDialogPage::saveData()"<<endl; 249 kdDebug(13010)<<"HighlightDialogPage::saveData()"<<endl;
250 writeback(); 250 writeback();
251} 251}
252 252
253 253
254void HighlightDialogPage::hlEdit() { 254void HighlightDialogPage::hlEdit() {
255 HlEditDialog diag(0,0,"hlEdit", true,hlData); 255 HlEditDialog diag(0,0,"hlEdit", true,hlData);
256 diag.show(); 256 diag.show();
257} 257}
258 258
259void HighlightDialogPage::hlNew() { 259void HighlightDialogPage::hlNew() {
260 HlEditDialog diag(0,0,"hlEdit",true,0); 260 HlEditDialog diag(0,0,"hlEdit",true,0);
261 diag.show(); 261 diag.show();
262} 262}
263 263
264 264
265HlEditDialog::HlEditDialog(HlManager *,QWidget *parent, const char *name, bool modal,HlData *data) 265HlEditDialog::HlEditDialog(HlManager *,QWidget *parent, const char *name, bool modal,HlData *data)
266 :KDialogBase(KDialogBase::Swallow, i18n("Highlight Conditions"), Ok|Cancel, Ok, parent, name, modal) 266 :KDialogBase(KDialogBase::Swallow, i18n("Highlight Conditions"), Ok|Cancel, Ok, parent, name, modal)
267{ 267{
268 currentItem=0; 268 currentItem=0;
269 transTableCnt=0; 269 transTableCnt=0;
270 QHBox *wid=new QHBox(this); 270 QHBox *wid=new QHBox(this);
271 QVBox *lbox=new QVBox(wid); 271 QVBox *lbox=new QVBox(wid);
272 contextList=new KListView(lbox); 272 contextList=new KListView(lbox);
273 contextList->setRootIsDecorated(true); 273 contextList->setRootIsDecorated(true);
274 contextList->addColumn(i18n("Syntax structure")); 274 contextList->addColumn(i18n("Syntax structure"));
275 contextList->setSorting(-1); 275 contextList->setSorting(-1);
276 QHBox *bbox=new QHBox(lbox); 276 QHBox *bbox=new QHBox(lbox);
277 QPushButton *addContext=new QPushButton(i18n("New Context"),bbox); 277 QPushButton *addContext=new QPushButton(i18n("New Context"),bbox);
278 QPushButton *addItem=new QPushButton(i18n("New Item"),bbox); 278 QPushButton *addItem=new QPushButton(i18n("New Item"),bbox);
279 QVGroupBox *opt = new QVGroupBox( i18n("Options"), wid); 279 QVGroupBox *opt = new QVGroupBox( i18n("Options"), wid);
280 stack=new QWidgetStack(opt); 280 stack=new QWidgetStack(opt);
281 initContextOptions(contextOptions=new QVBox(stack)); 281 initContextOptions(contextOptions=new QVBox(stack));
282 stack->addWidget(contextOptions,HlEContext); 282 stack->addWidget(contextOptions,HlEContext);
283 initItemOptions(itemOptions=new QVBox(stack)); 283 initItemOptions(itemOptions=new QVBox(stack));
284 stack->addWidget(itemOptions,HlEItem); 284 stack->addWidget(itemOptions,HlEItem);
285 stack->raiseWidget(HlEContext); 285 stack->raiseWidget(HlEContext);
286 setMainWidget(wid); 286 setMainWidget(wid);
287 if (data!=0) loadFromDocument(data); 287 if (data!=0) loadFromDocument(data);
288 else newDocument(); 288 else newDocument();
289 connect(contextList,SIGNAL(currentChanged( QListViewItem*)),this,SLOT(currentSelectionChanged ( QListViewItem * ))); 289 connect(contextList,SIGNAL(currentChanged(QListViewItem*)),this,SLOT(currentSelectionChanged(QListViewItem*)));
290 connect(addContext,SIGNAL(clicked()),this,SLOT(contextAddNew())); 290 connect(addContext,SIGNAL(clicked()),this,SLOT(contextAddNew()));
291 connect(addItem,SIGNAL(clicked()),this,SLOT(ItemAddNew())); 291 connect(addItem,SIGNAL(clicked()),this,SLOT(ItemAddNew()));
292 } 292 }
293 293
294void HlEditDialog::newDocument() 294void HlEditDialog::newDocument()
295{ 295{
296 KStandardDirs *dirs = KGlobal::dirs(); 296 KStandardDirs *dirs = KGlobal::dirs();
297 QStringList list=dirs->findAllResources("data","kate/syntax/syntax.template",false,true); 297 QStringList list=dirs->findAllResources("data","kate/syntax/syntax.template",false,true);
298 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) 298 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
299 { 299 {
300 HlData data("","",*it); 300 HlData data("","",*it);
301 loadFromDocument(&data); 301 loadFromDocument(&data);
302 return; 302 return;
303 } 303 }
304 KMessageBox::error(this,i18n("Can't find template file")); 304 KMessageBox::error(this,i18n("Can't find template file"));
305} 305}
306 306
307 307
308void HlEditDialog::initContextOptions(QVBox *co) 308void HlEditDialog::initContextOptions(QVBox *co)
309{ 309{
310 if( co!=0) 310 if( co!=0)
311 { 311 {
312 QHBox *tmp = new QHBox(co); 312 QHBox *tmp = new QHBox(co);
313 (void) new QLabel(i18n("Description:"),tmp); 313 (void) new QLabel(i18n("Description:"),tmp);
314 ContextDescr=new QLineEdit(tmp); 314 ContextDescr=new QLineEdit(tmp);
315 tmp= new QHBox(co); 315 tmp= new QHBox(co);
316 (void) new QLabel(i18n("Attribute:"),tmp); 316 (void) new QLabel(i18n("Attribute:"),tmp);
317 ContextAttribute=new QComboBox(tmp); 317 ContextAttribute=new QComboBox(tmp);
318 tmp= new QHBox(co); 318 tmp= new QHBox(co);
319 (void) new QLabel(i18n("LineEnd:"),tmp); 319 (void) new QLabel(i18n("LineEnd:"),tmp);
320 ContextLineEnd = new QComboBox(tmp); 320 ContextLineEnd = new QComboBox(tmp);
321 connect(ContextDescr,SIGNAL(textChanged(const QString&)),this,SLOT(contextDescrChanged(const QString&))); 321 connect(ContextDescr,SIGNAL(textChanged(const QString&)),this,SLOT(contextDescrChanged(const QString&)));
322 connect(ContextLineEnd,SIGNAL(activated(int)),this,SLOT(contextLineEndChanged(int))); 322 connect(ContextLineEnd,SIGNAL(activated(int)),this,SLOT(contextLineEndChanged(int)));
323 connect(ContextAttribute,SIGNAL(activated(int)),this,SLOT(contextAttributeChanged(int))); 323 connect(ContextAttribute,SIGNAL(activated(int)),this,SLOT(contextAttributeChanged(int)));
324 } 324 }
325 else 325 else
326 kdDebug(13010)<<"initContextOptions: Widget is 0"<<endl; 326 kdDebug(13010)<<"initContextOptions: Widget is 0"<<endl;
327} 327}
328 328
329 329
330void HlEditDialog::insertTranslationList(QString tag, QString trans,int length) 330void HlEditDialog::insertTranslationList(QString tag, QString trans,int length)
331 { 331 {
332 ItemInfo data(trans,length); 332 ItemInfo data(trans,length);
333 id2tag.insert(transTableCnt,tag); 333 id2tag.insert(transTableCnt,tag);
334 id2info.insert(transTableCnt,data); 334 id2info.insert(transTableCnt,data);
335 tag2id.insert(tag,transTableCnt); 335 tag2id.insert(tag,transTableCnt);
336 transTableCnt++; 336 transTableCnt++;
337 } 337 }
338 338
339 339
340void HlEditDialog::initItemOptions(QVBox *co) 340void HlEditDialog::initItemOptions(QVBox *co)
341{ 341{
342 if (co!=0) 342 if (co!=0)
343 { 343 {
344 QHBox *tmp = new QHBox(co); 344 QHBox *tmp = new QHBox(co);
345 (void) new QLabel(i18n("Type:"),tmp); 345 (void) new QLabel(i18n("Type:"),tmp);
346 ItemType = new QComboBox(tmp); 346 ItemType = new QComboBox(tmp);
347 tmp= new QHBox(co); 347 tmp= new QHBox(co);
348 (void) new QLabel(i18n("Parameter:"),tmp); 348 (void) new QLabel(i18n("Parameter:"),tmp);
349 ItemParameter= new QLineEdit(tmp); 349 ItemParameter= new QLineEdit(tmp);
350 tmp= new QHBox(co); 350 tmp= new QHBox(co);
351 (void) new QLabel(i18n("Attribute:"),tmp); 351 (void) new QLabel(i18n("Attribute:"),tmp);
352 ItemAttribute= new QComboBox(tmp); 352 ItemAttribute= new QComboBox(tmp);
353 (void) new QLabel(i18n("Context switch:"),tmp); 353 (void) new QLabel(i18n("Context switch:"),tmp);
354 ItemContext = new QComboBox(tmp); 354 ItemContext = new QComboBox(tmp);
355 co->setSpacing(15); 355 co->setSpacing(15);
356 QPushButton *delItem=new QPushButton(i18n("Delete this item"),co); 356 QPushButton *delItem=new QPushButton(i18n("Delete this item"),co);
357 357
358 /* init translation lists */ 358 /* init translation lists */
359 insertTranslationList("CharDetect","CharDetect",1); 359 insertTranslationList("CharDetect","CharDetect",1);
360 insertTranslationList("2CharDetect","2CharDetect",2); 360 insertTranslationList("2CharDetect","2CharDetect",2);
361 insertTranslationList("RangeDetect","RangeDetect",2); 361 insertTranslationList("RangeDetect","RangeDetect",2);
362 insertTranslationList("StringDetect","StringDetect",-1); 362 insertTranslationList("StringDetect","StringDetect",-1);
363 insertTranslationList("AnyChar","AnyChar",-1); 363 insertTranslationList("AnyChar","AnyChar",-1);
364 insertTranslationList("RegExpr","RegExpr",-1); 364 insertTranslationList("RegExpr","RegExpr",-1);
365 insertTranslationList("Int","Int",0); 365 insertTranslationList("Int","Int",0);
366 insertTranslationList("Float","Float",0); 366 insertTranslationList("Float","Float",0);
367 insertTranslationList("keyword","keyword",0); 367 insertTranslationList("keyword","keyword",0);
368 insertTranslationList("dataType","dataType",0); 368 insertTranslationList("dataType","dataType",0);
369 ItemType->clear(); 369 ItemType->clear();
370 for (int i=0; i<transTableCnt; i++) ItemType->insertItem(id2info[i].trans_i18n); 370 for (int i=0; i<transTableCnt; i++) ItemType->insertItem(id2info[i].trans_i18n);
371 connect(ItemType,SIGNAL(activated(int)),this,SLOT(ItemTypeChanged(int))); 371 connect(ItemType,SIGNAL(activated(int)),this,SLOT(ItemTypeChanged(int)));
372 connect(ItemParameter,SIGNAL(textChanged(const QString&)),this,SLOT(ItemParameterChanged(const QString&))); 372 connect(ItemParameter,SIGNAL(textChanged(const QString&)),this,SLOT(ItemParameterChanged(const QString&)));
373 connect(ItemAttribute,SIGNAL(activated(int)),this,SLOT(ItemAttributeChanged(int))); 373 connect(ItemAttribute,SIGNAL(activated(int)),this,SLOT(ItemAttributeChanged(int)));
374 connect(ItemContext,SIGNAL(activated(int)),this,SLOT(ItemContextChanged(int))); 374 connect(ItemContext,SIGNAL(activated(int)),this,SLOT(ItemContextChanged(int)));
375 } 375 }
376 else 376 else
377 kdDebug(13010)<<"initItemOptions: Widget is 0"<<endl; 377 kdDebug(13010)<<"initItemOptions: Widget is 0"<<endl;
378} 378}
379 379
380void HlEditDialog::loadFromDocument(HlData *hl) 380void HlEditDialog::loadFromDocument(HlData *hl)
381{ 381{
382 struct syntaxContextData *data; 382 struct syntaxContextData *data;
383 QListViewItem *last=0,*lastsub=0; 383 QListViewItem *last=0,*lastsub=0;
384 384
385 HlManager::self()->syntax->setIdentifier(hl->identifier); 385 HlManager::self()->syntax->setIdentifier(hl->identifier);
386 data=HlManager::self()->syntax->getGroupInfo("highlighting","context"); 386 data=HlManager::self()->syntax->getGroupInfo("highlighting","context");
387 int i=0; 387 int i=0;
388 if (data) 388 if (data)
389 { 389 {
390 while (HlManager::self()->syntax->nextGroup(data)) //<context tags> 390 while (HlManager::self()->syntax->nextGroup(data)) //<context tags>
391 { 391 {
392 kdDebug(13010)<< "Adding context to list"<<endl; 392 kdDebug(13010)<< "Adding context to list"<<endl;
393 last= new QListViewItem(contextList,last, 393 last= new QListViewItem(contextList,last,
394 HlManager::self()->syntax->groupData(data,QString("name")), 394 HlManager::self()->syntax->groupData(data,QString("name")),
395 QString("%1").arg(i), 395 QString("%1").arg(i),
396 HlManager::self()->syntax->groupData(data,QString("attribute")), 396 HlManager::self()->syntax->groupData(data,QString("attribute")),
397 HlManager::self()->syntax->groupData(data,QString("lineEndContext"))); 397 HlManager::self()->syntax->groupData(data,QString("lineEndContext")));
398 i++; 398 i++;
399 lastsub=0; 399 lastsub=0;
400 while (HlManager::self()->syntax->nextItem(data)) 400 while (HlManager::self()->syntax->nextItem(data))
401 { 401 {
402 kdDebug(13010)<< "Adding item to list"<<endl; 402 kdDebug(13010)<< "Adding item to list"<<endl;
403 lastsub=addContextItem(last,lastsub,data); 403 lastsub=addContextItem(last,lastsub,data);
404 } 404 }
405 405
406 406
407 } 407 }
408 if (data) HlManager::self()->syntax->freeGroupInfo(data); 408 if (data) HlManager::self()->syntax->freeGroupInfo(data);
409 } 409 }
410 ContextAttribute->clear(); 410 ContextAttribute->clear();
411 ItemAttribute->clear(); 411 ItemAttribute->clear();
412 data=HlManager::self()->syntax->getGroupInfo("highlighting","itemData"); 412 data=HlManager::self()->syntax->getGroupInfo("highlighting","itemData");
413 while (HlManager::self()->syntax->nextGroup(data)) 413 while (HlManager::self()->syntax->nextGroup(data))
414 { 414 {
415 ContextAttribute->insertItem(HlManager::self()->syntax->groupData(data,QString("name"))); 415 ContextAttribute->insertItem(HlManager::self()->syntax->groupData(data,QString("name")));
416 ItemAttribute->insertItem(HlManager::self()->syntax->groupData(data,QString("name"))); 416 ItemAttribute->insertItem(HlManager::self()->syntax->groupData(data,QString("name")));
417 } 417 }
418 if (data) HlManager::self()->syntax->freeGroupInfo(data); 418 if (data) HlManager::self()->syntax->freeGroupInfo(data);
419} 419}
420 420
421QListViewItem *HlEditDialog::addContextItem(QListViewItem *_parent,QListViewItem *prev,struct syntaxContextData *data) 421QListViewItem *HlEditDialog::addContextItem(QListViewItem *_parent,QListViewItem *prev,struct syntaxContextData *data)
422 { 422 {
423 423
424 kdDebug(13010)<<HlManager::self()->syntax->groupItemData(data,QString("name")) << endl; 424 kdDebug(13010)<<HlManager::self()->syntax->groupItemData(data,QString("name")) << endl;
425 425
426 QString dataname=HlManager::self()->syntax->groupItemData(data,QString("")); 426 QString dataname=HlManager::self()->syntax->groupItemData(data,QString(""));
427 QString attr=(HlManager::self()->syntax->groupItemData(data,QString("attribute"))); 427 QString attr=(HlManager::self()->syntax->groupItemData(data,QString("attribute")));
428 QString context=(HlManager::self()->syntax->groupItemData(data,QString("context"))); 428 QString context=(HlManager::self()->syntax->groupItemData(data,QString("context")));
429 char chr; 429 char chr;
430 if (! HlManager::self()->syntax->groupItemData(data,QString("char")).isEmpty()) 430 if (! HlManager::self()->syntax->groupItemData(data,QString("char")).isEmpty())
431 chr= (HlManager::self()->syntax->groupItemData(data,QString("char")).latin1())[0]; 431 chr= (HlManager::self()->syntax->groupItemData(data,QString("char")).latin1())[0];
432 else 432 else
433 chr=0; 433 chr=0;
434 QString stringdata=HlManager::self()->syntax->groupItemData(data,QString("String")); 434 QString stringdata=HlManager::self()->syntax->groupItemData(data,QString("String"));
435 char chr1; 435 char chr1;
436 if (! HlManager::self()->syntax->groupItemData(data,QString("char1")).isEmpty()) 436 if (! HlManager::self()->syntax->groupItemData(data,QString("char1")).isEmpty())
437 chr1= (HlManager::self()->syntax->groupItemData(data,QString("char1")).latin1())[0]; 437 chr1= (HlManager::self()->syntax->groupItemData(data,QString("char1")).latin1())[0];
438 else 438 else
439 chr1=0; 439 chr1=0;
440 bool insensitive=(HlManager::self()->syntax->groupItemData(data,QString("insensitive"))==QString("TRUE")); 440 bool insensitive=(HlManager::self()->syntax->groupItemData(data,QString("insensitive"))==QString("TRUE"));
441 QString param(""); 441 QString param("");
442 if ((dataname=="keyword") || (dataname=="dataType")) param=dataname; 442 if ((dataname=="keyword") || (dataname=="dataType")) param=dataname;
443 else if (dataname=="CharDetect") param=chr; 443 else if (dataname=="CharDetect") param=chr;
444 else if ((dataname=="2CharDetect") || (dataname=="RangeDetect")) param=QString("%1%2").arg(chr).arg(chr1); 444 else if ((dataname=="2CharDetect") || (dataname=="RangeDetect")) param=QString("%1%2").arg(chr).arg(chr1);
445 else if ((dataname=="StringDetect") || (dataname=="AnyChar") || (dataname=="RegExpr")) param=stringdata; 445 else if ((dataname=="StringDetect") || (dataname=="AnyChar") || (dataname=="RegExpr")) param=stringdata;
446 else kdDebug(13010)<<"***********************************"<<endl<<"Unknown entry for Context:"<<dataname<<endl; 446 else kdDebug(13010)<<"***********************************"<<endl<<"Unknown entry for Context:"<<dataname<<endl;
447 kdDebug(13010)<<dataname << endl; 447 kdDebug(13010)<<dataname << endl;
448 return new QListViewItem(_parent,prev,i18n(dataname.latin1())+" "+param,dataname,param,attr,context); 448 return new QListViewItem(_parent,prev,i18n(dataname.latin1())+" "+param,dataname,param,attr,context);
449 } 449 }
450 450
451 451
452void HlEditDialog::currentSelectionChanged ( QListViewItem *it) 452void HlEditDialog::currentSelectionChanged ( QListViewItem *it)
453 { 453 {
454 kdDebug(13010)<<"Update data view"<<endl<<"Depth:"<<it->depth()<<endl; 454 kdDebug(13010)<<"Update data view"<<endl<<"Depth:"<<it->depth()<<endl;
455 currentItem=it; 455 currentItem=it;
456 if (it->depth()==0) showContext(); 456 if (it->depth()==0) showContext();
457 else showItem(); 457 else showItem();
458 } 458 }
459 459
460 460
461/****************************************************************************/ 461/****************************************************************************/
462/* CONTEXTS */ 462/* CONTEXTS */
463/****************************************************************************/ 463/****************************************************************************/
464 464
465 465
466void HlEditDialog::showContext() 466void HlEditDialog::showContext()
467 { 467 {
468 stack->raiseWidget(HlEContext); 468 stack->raiseWidget(HlEContext);
469 ContextDescr->setText(currentItem->text(0)); 469 ContextDescr->setText(currentItem->text(0));
470 ContextAttribute->setCurrentItem(currentItem->text(2).toInt()); 470 ContextAttribute->setCurrentItem(currentItem->text(2).toInt());
471 ContextLineEnd->clear(); 471 ContextLineEnd->clear();
472 for (QListViewItem *it=contextList->firstChild();it;it=it->nextSibling()) 472 for (QListViewItem *it=contextList->firstChild();it;it=it->nextSibling())
473 ContextLineEnd->insertItem(it->text(0)); 473 ContextLineEnd->insertItem(it->text(0));
474 ContextLineEnd->setCurrentItem(currentItem->text(3).toInt()); 474 ContextLineEnd->setCurrentItem(currentItem->text(3).toInt());
475// ContextAttribute->setText(currentItem->text(1)); 475// ContextAttribute->setText(currentItem->text(1));
476// ContextLineEnd->setText(currentItem->text(2)); 476// ContextLineEnd->setText(currentItem->text(2));
477 } 477 }
478 478
479void HlEditDialog::contextDescrChanged(const QString& name) 479void HlEditDialog::contextDescrChanged(const QString& name)
480 { 480 {
481 if (currentItem) 481 if (currentItem)
482 { 482 {
483 currentItem->setText(0,name); 483 currentItem->setText(0,name);
484 ContextLineEnd->changeItem(name,currentItem->text(3).toInt()); 484 ContextLineEnd->changeItem(name,currentItem->text(3).toInt());
485 } 485 }
486 } 486 }
487 487
488void HlEditDialog::contextAttributeChanged(int id) 488void HlEditDialog::contextAttributeChanged(int id)
489{ 489{
490 if (currentItem) 490 if (currentItem)
491 { 491 {
492 currentItem->setText(2,QString("%1").arg(id)); 492 currentItem->setText(2,QString("%1").arg(id));
493 } 493 }
494} 494}
495 495
496void HlEditDialog::contextLineEndChanged(int id) 496void HlEditDialog::contextLineEndChanged(int id)
497{ 497{
498 kdDebug(13010)<<"contextLineEndChanged"<<endl; 498 kdDebug(13010)<<"contextLineEndChanged"<<endl;
499 if (currentItem) 499 if (currentItem)
500 { 500 {
501 currentItem->setText(3,QString("%1").arg(id)); 501 currentItem->setText(3,QString("%1").arg(id));
502 } 502 }
503} 503}
504 504
505void HlEditDialog::contextAddNew() 505void HlEditDialog::contextAddNew()
506{ 506{
507 QListViewItem *it=contextList->firstChild(); 507 QListViewItem *it=contextList->firstChild();
508 for (;it->nextSibling()!=0;it=it->nextSibling()); 508 for (;it->nextSibling()!=0;it=it->nextSibling());
509 it=new QListViewItem(contextList,it,i18n("New Context"),QString("%1").arg(it->text(1).toInt()),"0","0"); 509 it=new QListViewItem(contextList,it,i18n("New Context"),QString("%1").arg(it->text(1).toInt()),"0","0");
510 contextList->setSelected(it,true); 510 contextList->setSelected(it,true);
511} 511}
512 512
513/****************************************************************************/ 513/****************************************************************************/
514/* ITEMS */ 514/* ITEMS */
515/****************************************************************************/ 515/****************************************************************************/
516 516
517void HlEditDialog::showItem() 517void HlEditDialog::showItem()
518 { 518 {
519 stack->raiseWidget(HlEItem); 519 stack->raiseWidget(HlEItem);
520 ItemContext->clear(); 520 ItemContext->clear();
521 for (QListViewItem *it=contextList->firstChild();it;it=it->nextSibling()) 521 for (QListViewItem *it=contextList->firstChild();it;it=it->nextSibling())
522 ItemContext->insertItem(it->text(0)); 522 ItemContext->insertItem(it->text(0));
523 ItemContext->setCurrentItem(currentItem->text(4).toInt()); 523 ItemContext->setCurrentItem(currentItem->text(4).toInt());
524 ItemAttribute->setCurrentItem(currentItem->text(3).toInt()); 524 ItemAttribute->setCurrentItem(currentItem->text(3).toInt());
525 QMap<QString,int>::Iterator iter=tag2id.find(currentItem->text(1)); 525 QMap<QString,int>::Iterator iter=tag2id.find(currentItem->text(1));
526 if (iter==tag2id.end()) 526 if (iter==tag2id.end())
527 kdDebug(13010)<<"Oops, unknown itemtype in showItem: "<<currentItem->text(1)<<endl; 527 kdDebug(13010)<<"Oops, unknown itemtype in showItem: "<<currentItem->text(1)<<endl;
528 else 528 else
529 { 529 {
530 ItemType->setCurrentItem(*iter); 530 ItemType->setCurrentItem(*iter);
531 if (id2info[*iter].length==0) ItemParameter->hide(); 531 if (id2info[*iter].length==0) ItemParameter->hide();
532 else 532 else
533 { 533 {
534 ItemParameter->setMaxLength(id2info[*iter].length); 534 ItemParameter->setMaxLength(id2info[*iter].length);
535 ItemParameter->show(); 535 ItemParameter->show();
536 ItemParameter->setText(currentItem->text(2)); 536 ItemParameter->setText(currentItem->text(2));
537 } 537 }
538 } 538 }
539 539
540 } 540 }
541 541
542void HlEditDialog::ItemTypeChanged(int id) 542void HlEditDialog::ItemTypeChanged(int id)
543{ 543{
544 if (currentItem) 544 if (currentItem)
545 { 545 {
546 currentItem->setText(1,id2tag[id]); 546 currentItem->setText(1,id2tag[id]);
547 ItemParameter->setMaxLength(id2info[id].length); 547 ItemParameter->setMaxLength(id2info[id].length);
548 ItemParameterChanged(ItemParameter->text()); 548 ItemParameterChanged(ItemParameter->text());
549 } 549 }
550} 550}
551 551
552void HlEditDialog::ItemParameterChanged(const QString& name) 552void HlEditDialog::ItemParameterChanged(const QString& name)
553{ 553{
554 if (currentItem) 554 if (currentItem)
555 { 555 {
556 currentItem->setText(2,name); 556 currentItem->setText(2,name);
557 currentItem->setText(0,id2info[ItemType->currentItem()].trans_i18n+" "+currentItem->text(2)); 557 currentItem->setText(0,id2info[ItemType->currentItem()].trans_i18n+" "+currentItem->text(2));
558 } 558 }
559} 559}
560 560
561void HlEditDialog::ItemAttributeChanged(int attr) 561void HlEditDialog::ItemAttributeChanged(int attr)
562{ 562{
563 if (currentItem) 563 if (currentItem)
564 { 564 {
565 currentItem->setText(3,QString("%1").arg(attr)); 565 currentItem->setText(3,QString("%1").arg(attr));
566 } 566 }
567} 567}
568 568
569void HlEditDialog::ItemContextChanged(int cont) 569void HlEditDialog::ItemContextChanged(int cont)
570{ 570{
571 if (currentItem) 571 if (currentItem)
572 { 572 {
573 currentItem->setText(4,QString("%1").arg(cont)); 573 currentItem->setText(4,QString("%1").arg(cont));
574 } 574 }
575} 575}
576 576
577void HlEditDialog::ItemAddNew() 577void HlEditDialog::ItemAddNew()
578{ 578{
579 QListViewItem *it; 579 QListViewItem *it;
580 if (currentItem) 580 if (currentItem)
581 { 581 {
582 if (currentItem->depth()==0) it=currentItem->firstChild(); 582 if (currentItem->depth()==0) it=currentItem->firstChild();
583 else 583 else
584 it=currentItem; 584 it=currentItem;
585 if (it) for (;it->nextSibling();it=it->nextSibling()); 585 if (it) for (;it->nextSibling();it=it->nextSibling());
586 (void) new QListViewItem(it ? it->parent() : currentItem,it,"StringDetect "+i18n("New Item"),"StringDetect",i18n("New Item"),0,it ? it->parent()->text(1) : currentItem->text(1)); 586 (void) new QListViewItem(it ? it->parent() : currentItem,it,"StringDetect "+i18n("New Item"),"StringDetect",i18n("New Item"),0,it ? it->parent()->text(1) : currentItem->text(1));
587 } 587 }
588} 588}
diff --git a/noncore/apps/tinykate/libkate/document/katedocument.cpp b/noncore/apps/tinykate/libkate/document/katedocument.cpp
index f05e21a..0c742d7 100644
--- a/noncore/apps/tinykate/libkate/document/katedocument.cpp
+++ b/noncore/apps/tinykate/libkate/document/katedocument.cpp
@@ -1,3174 +1,3174 @@
1/*************************************************************************** 1/***************************************************************************
2 katedocument.cpp - description 2 katedocument.cpp - description
3 ------------------- 3 -------------------
4 begin : Mon Jan 15 2001 4 begin : Mon Jan 15 2001
5 copyright : (C) 2001 by Christoph "Crossfire" Cullmann 5 copyright : (C) 2001 by Christoph "Crossfire" Cullmann
6 (C) 2002 by Joseph Wenninger 6 (C) 2002 by Joseph Wenninger
7 email : crossfire@babylon2k.de 7 email : crossfire@babylon2k.de
8 jowenn@kde.org 8 jowenn@kde.org
9 9
10***************************************************************************/ 10***************************************************************************/
11 11
12/*************************************************************************** 12/***************************************************************************
13 * * 13 * *
14 * This program is free software; you can redistribute it and/or modify * 14 * This program is free software; you can redistribute it and/or modify *
15 * it under the terms of the GNU General Public License as published by * 15 * it under the terms of the GNU General Public License as published by *
16 * the Free Software Foundation; either version 2 of the License, or * 16 * the Free Software Foundation; either version 2 of the License, or *
17 * (at your option) any later version. * 17 * (at your option) any later version. *
18 * * 18 * *
19 ***************************************************************************/ 19 ***************************************************************************/
20 20
21/* 21/*
22 Copyright (C) 1998, 1999 Jochen Wilhelmy 22 Copyright (C) 1998, 1999 Jochen Wilhelmy
23 digisnap@cs.tu-berlin.de 23 digisnap@cs.tu-berlin.de
24 24
25 This library is free software; you can redistribute it and/or 25 This library is free software; you can redistribute it and/or
26 modify it under the terms of the GNU Library General Public 26 modify it under the terms of the GNU Library General Public
27 License as published by the Free Software Foundation; either 27 License as published by the Free Software Foundation; either
28 version 2 of the License, or (at your option) any later version. 28 version 2 of the License, or (at your option) any later version.
29 29
30 This library is distributed in the hope that it will be useful, 30 This library is distributed in the hope that it will be useful,
31 but WITHOUT ANY WARRANTY; without even the implied warranty of 31 but WITHOUT ANY WARRANTY; without even the implied warranty of
32 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 32 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
33 Library General Public License for more details. 33 Library General Public License for more details.
34 34
35 You should have received a copy of the GNU Library General Public License 35 You should have received a copy of the GNU Library General Public License
36 along with this library; see the file COPYING.LIB. If not, write to 36 along with this library; see the file COPYING.LIB. If not, write to
37 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 37 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
38 Boston, MA 02111-1307, USA. 38 Boston, MA 02111-1307, USA.
39*/ 39*/
40 40
41#include "katedocument.h" 41#include "katedocument.h"
42 42
43 43
44#include <qfileinfo.h> 44#include <qfileinfo.h>
45#include <qdatetime.h> 45#include <qdatetime.h>
46 46
47#include <kmessagebox.h> 47#include <kmessagebox.h>
48#include <qpe/config.h> 48#include <qpe/config.h>
49#include <qstring.h> 49#include <qstring.h>
50 50
51#include <sys/time.h> 51#include <sys/time.h>
52#include <unistd.h> 52#include <unistd.h>
53 53
54#include <stdio.h> 54#include <stdio.h>
55 55
56#include <qtimer.h> 56#include <qtimer.h>
57#include <qobject.h> 57#include <qobject.h>
58#include <qapplication.h> 58#include <qapplication.h>
59#include <qclipboard.h> 59#include <qclipboard.h>
60#include <qfont.h> 60#include <qfont.h>
61#include <qpainter.h> 61#include <qpainter.h>
62#include <qfile.h> 62#include <qfile.h>
63#include <qtextstream.h> 63#include <qtextstream.h>
64#include <qtextcodec.h> 64#include <qtextcodec.h>
65#include <kglobal.h> 65#include <kglobal.h>
66 66
67//#include <kcharsets.h> 67//#include <kcharsets.h>
68#include <kdebug.h> 68#include <kdebug.h>
69//#include <kinstance.h> 69//#include <kinstance.h>
70 70
71#include <kglobalsettings.h> 71#include <kglobalsettings.h>
72//#include <kaction.h> 72//#include <kaction.h>
73//#include <kstdaction.h> 73//#include <kstdaction.h>
74 74
75#include "../view/kateview.h" 75#include "../view/kateview.h"
76#include "katebuffer.h" 76#include "katebuffer.h"
77#include "katetextline.h" 77#include "katetextline.h"
78 78
79#include "katecmd.h" 79#include "katecmd.h"
80 80
81KateAction::KateAction(Action a, PointStruc &cursor, int len, const QString &text) 81KateAction::KateAction(Action a, PointStruc &cursor, int len, const QString &text)
82 : action(a), cursor(cursor), len(len), text(text) { 82 : action(a), cursor(cursor), len(len), text(text) {
83} 83}
84 84
85KateActionGroup::KateActionGroup(PointStruc &aStart, int type) 85KateActionGroup::KateActionGroup(PointStruc &aStart, int type)
86 : start(aStart), action(0L), undoType(type) { 86 : start(aStart), action(0L), undoType(type) {
87} 87}
88 88
89KateActionGroup::~KateActionGroup() { 89KateActionGroup::~KateActionGroup() {
90 KateAction *current, *next; 90 KateAction *current, *next;
91 91
92 current = action; 92 current = action;
93 while (current) { 93 while (current) {
94 next = current->next; 94 next = current->next;
95 delete current; 95 delete current;
96 current = next; 96 current = next;
97 } 97 }
98} 98}
99 99
100void KateActionGroup::insertAction(KateAction *a) { 100void KateActionGroup::insertAction(KateAction *a) {
101 a->next = action; 101 a->next = action;
102 action = a; 102 action = a;
103} 103}
104 104
105const char * KateActionGroup::typeName(int type) 105const char * KateActionGroup::typeName(int type)
106{ 106{
107 // return a short text description of the given undo group type suitable for a menu 107 // return a short text description of the given undo group type suitable for a menu
108 // not the lack of i18n's, the caller is expected to handle translation 108 // not the lack of i18n's, the caller is expected to handle translation
109 switch (type) { 109 switch (type) {
110 case ugPaste : return "Paste Text"; 110 case ugPaste : return "Paste Text";
111 case ugDelBlock : return "Selection Overwrite"; 111 case ugDelBlock : return "Selection Overwrite";
112 case ugIndent : return "Indent"; 112 case ugIndent : return "Indent";
113 case ugUnindent : return "Unindent"; 113 case ugUnindent : return "Unindent";
114 case ugComment : return "Comment"; 114 case ugComment : return "Comment";
115 case ugUncomment : return "Uncomment"; 115 case ugUncomment : return "Uncomment";
116 case ugReplace : return "Text Replace"; 116 case ugReplace : return "Text Replace";
117 case ugSpell : return "Spell Check"; 117 case ugSpell : return "Spell Check";
118 case ugInsChar : return "Typing"; 118 case ugInsChar : return "Typing";
119 case ugDelChar : return "Delete Text"; 119 case ugDelChar : return "Delete Text";
120 case ugInsLine : return "New Line"; 120 case ugInsLine : return "New Line";
121 case ugDelLine : return "Delete Line"; 121 case ugDelLine : return "Delete Line";
122 } 122 }
123 return ""; 123 return "";
124} 124}
125 125
126const int KateDocument::maxAttribs = 32; 126const int KateDocument::maxAttribs = 32;
127 127
128QStringList KateDocument::searchForList = QStringList(); 128QStringList KateDocument::searchForList = QStringList();
129QStringList KateDocument::replaceWithList = QStringList(); 129QStringList KateDocument::replaceWithList = QStringList();
130 130
131uint KateDocument::uniqueID = 0; 131uint KateDocument::uniqueID = 0;
132 132
133QPtrDict<KateDocument::KateDocPrivate>* KateDocument::d_ptr = 0; 133QPtrDict<KateDocument::KateDocPrivate>* KateDocument::d_ptr = 0;
134 134
135 135
136KateDocument::KateDocument(bool bSingleViewMode, bool bBrowserView, 136KateDocument::KateDocument(bool bSingleViewMode, bool bBrowserView,
137 QWidget *parentWidget, const char *widgetName, 137 QWidget *parentWidget, const char *widgetName,
138 QObject *, const char *) 138 QObject *, const char *)
139 : Kate::Document (), 139 : Kate::Document (),
140 myFont(KGlobalSettings::generalFont()), myFontBold(KGlobalSettings::generalFont()), myFontItalic(KGlobalSettings::generalFont()), myFontBI(KGlobalSettings::generalFont()), 140 myFont(KGlobalSettings::generalFont()), myFontBold(KGlobalSettings::generalFont()), myFontItalic(KGlobalSettings::generalFont()), myFontBI(KGlobalSettings::generalFont()),
141 myFontMetrics (myFont), myFontMetricsBold (myFontBold), myFontMetricsItalic (myFontItalic), myFontMetricsBI (myFontBI), 141 myFontMetrics (myFont), myFontMetricsBold (myFontBold), myFontMetricsItalic (myFontItalic), myFontMetricsBI (myFontBI),
142 hlManager(HlManager::self ()) 142 hlManager(HlManager::self ())
143{ 143{
144 144
145 d(this)->hlSetByUser = false; 145 d(this)->hlSetByUser = false;
146 PreHighlightedTill=0; 146 PreHighlightedTill=0;
147 RequestPreHighlightTill=0; 147 RequestPreHighlightTill=0;
148 148
149 m_bSingleViewMode=bSingleViewMode; 149 m_bSingleViewMode=bSingleViewMode;
150 m_bBrowserView = bBrowserView; 150 m_bBrowserView = bBrowserView;
151 151
152 m_url = QString::null; 152 m_url = QString::null;
153 153
154 // NOTE: QFont::CharSet doesn't provide all the charsets KDE supports 154 // NOTE: QFont::CharSet doesn't provide all the charsets KDE supports
155 // (esp. it doesn't distinguish between UTF-8 and iso10646-1) 155 // (esp. it doesn't distinguish between UTF-8 and iso10646-1)
156 156
157 myEncoding = QString::fromLatin1(QTextCodec::codecForLocale()->name()); 157 myEncoding = QString::fromLatin1(QTextCodec::codecForLocale()->name());
158 158
159 maxLength = -1; 159 maxLength = -1;
160 160
161 setFont (KGlobalSettings::generalFont()); 161 setFont (KGlobalSettings::generalFont());
162 162
163 myDocID = uniqueID; 163 myDocID = uniqueID;
164 uniqueID++; 164 uniqueID++;
165 165
166 myDocName = QString (""); 166 myDocName = QString ("");
167 fileInfo = new QFileInfo (); 167 fileInfo = new QFileInfo ();
168 168
169 myCmd = new KateCmd (this); 169 myCmd = new KateCmd (this);
170 170
171 connect(this,SIGNAL(modifiedChanged ()),this,SLOT(slotModChanged ())); 171 connect(this,SIGNAL(modifiedChanged()),this,SLOT(slotModChanged()));
172 172
173 buffer = new KWBuffer; 173 buffer = new KWBuffer;
174 connect(buffer, SIGNAL(linesChanged(int)), this, SLOT(slotBufferChanged())); 174 connect(buffer, SIGNAL(linesChanged(int)), this, SLOT(slotBufferChanged()));
175// connect(buffer, SIGNAL(textChanged()), this, SIGNAL(textChanged())); 175// connect(buffer, SIGNAL(textChanged()), this, SIGNAL(textChanged()));
176 connect(buffer, SIGNAL(needHighlight(long,long)),this,SLOT(slotBufferHighlight(long,long))); 176 connect(buffer, SIGNAL(needHighlight(long,long)),this,SLOT(slotBufferHighlight(long,long)));
177 177
178 colors[0] = KGlobalSettings::baseColor(); 178 colors[0] = KGlobalSettings::baseColor();
179 colors[1] = KGlobalSettings::highlightColor(); 179 colors[1] = KGlobalSettings::highlightColor();
180 180
181 m_attribs = new Attribute[maxAttribs]; 181 m_attribs = new Attribute[maxAttribs];
182 182
183 m_highlight = 0L; 183 m_highlight = 0L;
184 tabChars = 8; 184 tabChars = 8;
185 185
186 m_singleSelection = false; 186 m_singleSelection = false;
187 187
188 newDocGeometry = false; 188 newDocGeometry = false;
189 readOnly = false; 189 readOnly = false;
190 newDoc = false; 190 newDoc = false;
191 191
192 modified = false; 192 modified = false;
193 193
194 undoList.setAutoDelete(true); 194 undoList.setAutoDelete(true);
195 undoState = 0; 195 undoState = 0;
196 undoSteps = 50; 196 undoSteps = 50;
197 197
198 pseudoModal = 0L; 198 pseudoModal = 0L;
199 clear(); 199 clear();
200 200
201 setHighlight(0); //calls updateFontData() 201 setHighlight(0); //calls updateFontData()
202 // if the user changes the highlight with the dialog, notify the doc 202 // if the user changes the highlight with the dialog, notify the doc
203 connect(hlManager,SIGNAL(changed()),SLOT(hlChanged())); 203 connect(hlManager,SIGNAL(changed()),SLOT(hlChanged()));
204 204
205 newDocGeometry = false; 205 newDocGeometry = false;
206 206
207 readConfig(); 207 readConfig();
208 208
209 setReadOnly(false); 209 setReadOnly(false);
210} 210}
211 211
212void KateDocument::setDontChangeHlOnSave() 212void KateDocument::setDontChangeHlOnSave()
213{ 213{
214 d(this)->hlSetByUser = true; 214 d(this)->hlSetByUser = true;
215} 215}
216 216
217void KateDocument::setFont (QFont font) 217void KateDocument::setFont (QFont font)
218{ 218{
219 kdDebug()<<"Kate:: setFont"<<endl; 219 kdDebug()<<"Kate:: setFont"<<endl;
220 int oldwidth=myFontMetrics.width('W'); //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0 220 int oldwidth=myFontMetrics.width('W'); //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0
221 myFont = font; 221 myFont = font;
222 myFontBold = QFont (font); 222 myFontBold = QFont (font);
223 myFontBold.setBold (true); 223 myFontBold.setBold (true);
224 224
225 myFontItalic = QFont (font); 225 myFontItalic = QFont (font);
226 myFontItalic.setItalic (true); 226 myFontItalic.setItalic (true);
227 227
228 myFontBI = QFont (font); 228 myFontBI = QFont (font);
229 myFontBI.setBold (true); 229 myFontBI.setBold (true);
230 myFontBI.setItalic (true); 230 myFontBI.setItalic (true);
231 231
232 myFontMetrics = CachedFontMetrics (myFont); 232 myFontMetrics = CachedFontMetrics (myFont);
233 myFontMetricsBold = CachedFontMetrics (myFontBold); 233 myFontMetricsBold = CachedFontMetrics (myFontBold);
234 myFontMetricsItalic = CachedFontMetrics (myFontItalic); 234 myFontMetricsItalic = CachedFontMetrics (myFontItalic);
235 myFontMetricsBI = CachedFontMetrics (myFontBI); 235 myFontMetricsBI = CachedFontMetrics (myFontBI);
236 int newwidth=myFontMetrics.width('W'); //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0 236 int newwidth=myFontMetrics.width('W'); //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0
237 maxLength=maxLength*(float)newwidth/(float)oldwidth; //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0 237 maxLength=maxLength*(float)newwidth/(float)oldwidth; //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0
238 238
239 updateFontData(); 239 updateFontData();
240 updateViews(); //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0 240 updateViews(); //Quick & Dirty Hack (by JoWenn) //Remove in KDE 3.0
241 241
242} 242}
243 243
244long KateDocument::needPreHighlight(long till) 244long KateDocument::needPreHighlight(long till)
245{ 245{
246 int max=numLines()-1; 246 int max=numLines()-1;
247 if (till>max) 247 if (till>max)
248 { 248 {
249 till=max; 249 till=max;
250 } 250 }
251 if (PreHighlightedTill>=till) return -1; 251 if (PreHighlightedTill>=till) return -1;
252 252
253 long tmp=RequestPreHighlightTill; 253 long tmp=RequestPreHighlightTill;
254 if (RequestPreHighlightTill<till) 254 if (RequestPreHighlightTill<till)
255 { 255 {
256 RequestPreHighlightTill=till; 256 RequestPreHighlightTill=till;
257 if (tmp<=PreHighlightedTill) QTimer::singleShot(10,this,SLOT(doPreHighlight())); 257 if (tmp<=PreHighlightedTill) QTimer::singleShot(10,this,SLOT(doPreHighlight()));
258 } 258 }
259 return RequestPreHighlightTill; 259 return RequestPreHighlightTill;
260} 260}
261 261
262void KateDocument::doPreHighlight() 262void KateDocument::doPreHighlight()
263{ 263{
264 int from = PreHighlightedTill; 264 int from = PreHighlightedTill;
265 int till = PreHighlightedTill+200; 265 int till = PreHighlightedTill+200;
266 int max = numLines()-1; 266 int max = numLines()-1;
267 if (till > max) 267 if (till > max)
268 { 268 {
269 till = max; 269 till = max;
270 } 270 }
271 PreHighlightedTill = till; 271 PreHighlightedTill = till;
272 updateLines(from,till); 272 updateLines(from,till);
273 emit preHighlightChanged(PreHighlightedTill); 273 emit preHighlightChanged(PreHighlightedTill);
274 if (PreHighlightedTill<RequestPreHighlightTill) 274 if (PreHighlightedTill<RequestPreHighlightTill)
275 QTimer::singleShot(10,this,SLOT(doPreHighlight())); 275 QTimer::singleShot(10,this,SLOT(doPreHighlight()));
276} 276}
277 277
278KateDocument::~KateDocument() 278KateDocument::~KateDocument()
279{ 279{
280 m_highlight->release(); 280 m_highlight->release();
281 writeConfig(); 281 writeConfig();
282 282
283 if ( !m_bSingleViewMode ) 283 if ( !m_bSingleViewMode )
284 { 284 {
285 m_views.setAutoDelete( true ); 285 m_views.setAutoDelete( true );
286 m_views.clear(); 286 m_views.clear();
287 m_views.setAutoDelete( false ); 287 m_views.setAutoDelete( false );
288 } 288 }
289 delete_d(this); 289 delete_d(this);
290} 290}
291 291
292void KateDocument::openURL(const QString &filename) 292void KateDocument::openURL(const QString &filename)
293{ 293{
294 294
295 m_file=filename; 295 m_file=filename;
296 fileInfo->setFile (m_file); 296 fileInfo->setFile (m_file);
297 setMTime(); 297 setMTime();
298 298
299 if (!fileInfo->exists() || !fileInfo->isReadable()) 299 if (!fileInfo->exists() || !fileInfo->isReadable())
300 { 300 {
301 qDebug("File doesn't exit or couldn't be read"); 301 qDebug("File doesn't exit or couldn't be read");
302 return ; 302 return ;
303 } 303 }
304 304
305 buffer->clear(); 305 buffer->clear();
306#warning fixme 306#warning fixme
307// buffer->insertFile(0, m_file, KGlobal::charsets()->codecForName(myEncoding)); 307// buffer->insertFile(0, m_file, KGlobal::charsets()->codecForName(myEncoding));
308 qDebug("Telling buffer to open file"); 308 qDebug("Telling buffer to open file");
309 buffer->insertFile(0, m_file, QTextCodec::codecForLocale()); 309 buffer->insertFile(0, m_file, QTextCodec::codecForLocale());
310 310
311 setMTime(); 311 setMTime();
312 312
313 if (myWordWrap) 313 if (myWordWrap)
314 wrapText (myWordWrapAt); 314 wrapText (myWordWrapAt);
315 315
316 int hl = hlManager->wildcardFind( m_file ); 316 int hl = hlManager->wildcardFind( m_file );
317 317
318 setHighlight(hl); 318 setHighlight(hl);
319 319
320 updateLines(); 320 updateLines();
321 updateViews(); 321 updateViews();
322 322
323 emit fileNameChanged(); 323 emit fileNameChanged();
324 324
325 return ; 325 return ;
326} 326}
327 327
328bool KateDocument::saveFile() 328bool KateDocument::saveFile()
329{ 329{
330 330
331 QFile f( m_file ); 331 QFile f( m_file );
332 if ( !f.open( IO_WriteOnly ) ) 332 if ( !f.open( IO_WriteOnly ) )
333 return false; // Error 333 return false; // Error
334 334
335 QTextStream stream(&f); 335 QTextStream stream(&f);
336 336
337 stream.setEncoding(QTextStream::RawUnicode); // disable Unicode headers 337 stream.setEncoding(QTextStream::RawUnicode); // disable Unicode headers
338#warning fixme 338#warning fixme
339// stream.setCodec(KGlobal::charsets()->codecForName(myEncoding)); 339// stream.setCodec(KGlobal::charsets()->codecForName(myEncoding));
340 stream.setCodec(QTextCodec::codecForLocale()); // this line sets the mapper to the correct codec 340 stream.setCodec(QTextCodec::codecForLocale()); // this line sets the mapper to the correct codec
341 341
342 int maxLine = numLines(); 342 int maxLine = numLines();
343 int line = 0; 343 int line = 0;
344 while(true) 344 while(true)
345 { 345 {
346 stream << getTextLine(line)->getString(); 346 stream << getTextLine(line)->getString();
347 line++; 347 line++;
348 if (line >= maxLine) break; 348 if (line >= maxLine) break;
349 349
350 if (eolMode == KateDocument::eolUnix) stream << "\n"; 350 if (eolMode == KateDocument::eolUnix) stream << "\n";
351 else if (eolMode == KateDocument::eolDos) stream << "\r\n"; 351 else if (eolMode == KateDocument::eolDos) stream << "\r\n";
352 else if (eolMode == KateDocument::eolMacintosh) stream << '\r'; 352 else if (eolMode == KateDocument::eolMacintosh) stream << '\r';
353 }; 353 };
354 f.close(); 354 f.close();
355 355
356 fileInfo->setFile (m_file); 356 fileInfo->setFile (m_file);
357 setMTime(); 357 setMTime();
358 358
359 if (!(d(this)->hlSetByUser)) 359 if (!(d(this)->hlSetByUser))
360 { 360 {
361 int hl = hlManager->wildcardFind( m_file ); 361 int hl = hlManager->wildcardFind( m_file );
362 362
363 setHighlight(hl); 363 setHighlight(hl);
364 } 364 }
365 emit fileNameChanged (); 365 emit fileNameChanged ();
366 366
367 return (f.status() == IO_Ok); 367 return (f.status() == IO_Ok);
368} 368}
369 369
370KTextEditor::View *KateDocument::createView( QWidget *parent, const char *name ) 370KTextEditor::View *KateDocument::createView( QWidget *parent, const char *name )
371{ 371{
372 return new KateView( this, parent, name); 372 return new KateView( this, parent, name);
373} 373}
374 374
375QString KateDocument::textLine( int line ) const 375QString KateDocument::textLine( int line ) const
376{ 376{
377 TextLine::Ptr l = getTextLine( line ); 377 TextLine::Ptr l = getTextLine( line );
378 if ( !l ) 378 if ( !l )
379 return QString(); 379 return QString();
380 380
381 return l->getString(); 381 return l->getString();
382} 382}
383 383
384void KateDocument::replaceLine(const QString& s,int line) 384void KateDocument::replaceLine(const QString& s,int line)
385{ 385{
386 remove_Line(line,false); 386 remove_Line(line,false);
387 insert_Line(s,line,true); 387 insert_Line(s,line,true);
388} 388}
389 389
390void KateDocument::insertLine( const QString &str, int l ) { 390void KateDocument::insertLine( const QString &str, int l ) {
391 insert_Line(str,l,true); 391 insert_Line(str,l,true);
392} 392}
393 393
394void KateDocument::insert_Line(const QString& s,int line, bool update) 394void KateDocument::insert_Line(const QString& s,int line, bool update)
395{ 395{
396 kdDebug(13020)<<"KateDocument::insertLine "<<s<<QString(" %1").arg(line)<<endl; 396 kdDebug(13020)<<"KateDocument::insertLine "<<s<<QString(" %1").arg(line)<<endl;
397 TextLine::Ptr TL=new TextLine(); 397 TextLine::Ptr TL=new TextLine();
398 TL->append(s.unicode(),s.length()); 398 TL->append(s.unicode(),s.length());
399 buffer->insertLine(line,TL); 399 buffer->insertLine(line,TL);
400 if (update) 400 if (update)
401 { 401 {
402 newDocGeometry=true; 402 newDocGeometry=true;
403 updateLines(line); 403 updateLines(line);
404 updateViews(); 404 updateViews();
405 } 405 }
406} 406}
407 407
408void KateDocument::insertAt( const QString &s, int line, int col, bool ) 408void KateDocument::insertAt( const QString &s, int line, int col, bool )
409{ 409{
410 VConfig c; 410 VConfig c;
411 c.view = 0; // ### FIXME 411 c.view = 0; // ### FIXME
412 c.cursor.x = col; 412 c.cursor.x = col;
413 c.cursor.y = line; 413 c.cursor.y = line;
414 c.cXPos = 0; // ### FIXME 414 c.cXPos = 0; // ### FIXME
415 c.flags = 0; // ### FIXME 415 c.flags = 0; // ### FIXME
416 insert( c, s ); 416 insert( c, s );
417} 417}
418 418
419void KateDocument::removeLine( int line ) { 419void KateDocument::removeLine( int line ) {
420 remove_Line(line,true); 420 remove_Line(line,true);
421} 421}
422 422
423void KateDocument::remove_Line(int line,bool update) 423void KateDocument::remove_Line(int line,bool update)
424{ 424{
425 kdDebug(13020)<<"KateDocument::removeLine "<<QString("%1").arg(line)<<endl; 425 kdDebug(13020)<<"KateDocument::removeLine "<<QString("%1").arg(line)<<endl;
426 buffer->removeLine(line); 426 buffer->removeLine(line);
427// newDocGeometry=true; 427// newDocGeometry=true;
428// if line==0) 428// if line==0)
429 if (update) 429 if (update)
430 { 430 {
431 updateLines(line); 431 updateLines(line);
432 updateViews(); 432 updateViews();
433 } 433 }
434} 434}
435 435
436int KateDocument::length() const 436int KateDocument::length() const
437{ 437{
438 return text().length(); 438 return text().length();
439} 439}
440 440
441void KateDocument::setSelection( int , int , int , int ) 441void KateDocument::setSelection( int , int , int , int )
442{ 442{
443} 443}
444 444
445bool KateDocument::hasSelection() const 445bool KateDocument::hasSelection() const
446{ 446{
447 return (selectEnd >= selectStart); 447 return (selectEnd >= selectStart);
448} 448}
449 449
450QString KateDocument::selection() const 450QString KateDocument::selection() const
451{ 451{
452 uint flags = 0; 452 uint flags = 0;
453 TextLine::Ptr textLine; 453 TextLine::Ptr textLine;
454 int len, z, start, end, i; 454 int len, z, start, end, i;
455 455
456 len = 1; 456 len = 1;
457 if (!(flags & KateView::cfVerticalSelect)) { 457 if (!(flags & KateView::cfVerticalSelect)) {
458 for (z = selectStart; z <= selectEnd; z++) { 458 for (z = selectStart; z <= selectEnd; z++) {
459 textLine = getTextLine(z); 459 textLine = getTextLine(z);
460 len += textLine->numSelected(); 460 len += textLine->numSelected();
461 if (textLine->isSelected()) len++; 461 if (textLine->isSelected()) len++;
462 } 462 }
463 QString s; 463 QString s;
464 len = 0; 464 len = 0;
465 for (z = selectStart; z <= selectEnd; z++) { 465 for (z = selectStart; z <= selectEnd; z++) {
466 textLine = getTextLine(z); 466 textLine = getTextLine(z);
467 end = 0; 467 end = 0;
468 do { 468 do {
469 start = textLine->findUnselected(end); 469 start = textLine->findUnselected(end);
470 end = textLine->findSelected(start); 470 end = textLine->findSelected(start);
471 for (i = start; i < end; i++) { 471 for (i = start; i < end; i++) {
472 s[len] = textLine->getChar(i); 472 s[len] = textLine->getChar(i);
473 len++; 473 len++;
474 } 474 }
475 } while (start < end); 475 } while (start < end);
476 if (textLine->isSelected()) { 476 if (textLine->isSelected()) {
477 s[len] = '\n'; 477 s[len] = '\n';
478 len++; 478 len++;
479 } 479 }
480 } 480 }
481// s[len] = '\0'; 481// s[len] = '\0';
482 return s; 482 return s;
483 } else { 483 } else {
484 for (z = selectStart; z <= selectEnd; z++) { 484 for (z = selectStart; z <= selectEnd; z++) {
485 textLine = getTextLine(z); 485 textLine = getTextLine(z);
486 len += textLine->numSelected() + 1; 486 len += textLine->numSelected() + 1;
487 } 487 }
488 QString s; 488 QString s;
489 len = 0; 489 len = 0;
490 for (z = selectStart; z <= selectEnd; z++) { 490 for (z = selectStart; z <= selectEnd; z++) {
491 textLine = getTextLine(z); 491 textLine = getTextLine(z);
492 end = 0; 492 end = 0;
493 do { 493 do {
494 start = textLine->findUnselected(end); 494 start = textLine->findUnselected(end);
495 end = textLine->findSelected(start); 495 end = textLine->findSelected(start);
496 for (i = start; i < end; i++) { 496 for (i = start; i < end; i++) {
497 s[len] = textLine->getChar(i); 497 s[len] = textLine->getChar(i);
498 len++; 498 len++;
499 } 499 }
500 } while (start < end); 500 } while (start < end);
501 s[len] = '\n'; 501 s[len] = '\n';
502 len++; 502 len++;
503 } 503 }
504// s[len] = '\0'; // the final \0 is not counted in length() 504// s[len] = '\0'; // the final \0 is not counted in length()
505 return s; 505 return s;
506 } 506 }
507} 507}
508 508
509int KateDocument::numLines() const 509int KateDocument::numLines() const
510{ 510{
511 return buffer->count(); 511 return buffer->count();
512} 512}
513 513
514 514
515TextLine::Ptr KateDocument::getTextLine(int line) const 515TextLine::Ptr KateDocument::getTextLine(int line) const
516{ 516{
517 // This is a hack to get this stuff working. 517 // This is a hack to get this stuff working.
518 return buffer->line(line); 518 return buffer->line(line);
519} 519}
520 520
521int KateDocument::textLength(int line) { 521int KateDocument::textLength(int line) {
522 TextLine::Ptr textLine = getTextLine(line); 522 TextLine::Ptr textLine = getTextLine(line);
523 if (!textLine) return 0; 523 if (!textLine) return 0;
524 return textLine->length(); 524 return textLine->length();
525} 525}
526 526
527void KateDocument::setTabWidth(int chars) { 527void KateDocument::setTabWidth(int chars) {
528 if (tabChars == chars) return; 528 if (tabChars == chars) return;
529 if (chars < 1) chars = 1; 529 if (chars < 1) chars = 1;
530 if (chars > 16) chars = 16; 530 if (chars > 16) chars = 16;
531 tabChars = chars; 531 tabChars = chars;
532 updateFontData(); 532 updateFontData();
533 533
534 maxLength = -1; 534 maxLength = -1;
535 for (int i=0; i < buffer->count(); i++) 535 for (int i=0; i < buffer->count(); i++)
536 { 536 {
537 TextLine::Ptr textLine = buffer->line(i); 537 TextLine::Ptr textLine = buffer->line(i);
538 int len = textWidth(textLine,textLine->length()); 538 int len = textWidth(textLine,textLine->length());
539 if (len > maxLength) { 539 if (len > maxLength) {
540 maxLength = len; 540 maxLength = len;
541 longestLine = textLine; 541 longestLine = textLine;
542 } 542 }
543 } 543 }
544} 544}
545 545
546void KateDocument::setReadOnly(bool m) { 546void KateDocument::setReadOnly(bool m) {
547 KTextEditor::View *view; 547 KTextEditor::View *view;
548 548
549 if (m != readOnly) { 549 if (m != readOnly) {
550 readOnly = m; 550 readOnly = m;
551// if (readOnly) recordReset(); 551// if (readOnly) recordReset();
552 for (view = m_views.first(); view != 0L; view = m_views.next() ) { 552 for (view = m_views.first(); view != 0L; view = m_views.next() ) {
553 emit static_cast<KateView *>( view )->newStatus(); 553 emit static_cast<KateView *>( view )->newStatus();
554 } 554 }
555 } 555 }
556} 556}
557 557
558bool KateDocument::isReadOnly() const { 558bool KateDocument::isReadOnly() const {
559 return readOnly; 559 return readOnly;
560} 560}
561 561
562void KateDocument::setNewDoc( bool m ) 562void KateDocument::setNewDoc( bool m )
563{ 563{
564// KTextEditor::View *view; 564// KTextEditor::View *view;
565 565
566 if ( m != newDoc ) 566 if ( m != newDoc )
567 { 567 {
568 newDoc = m; 568 newDoc = m;
569//// if (readOnly) recordReset(); 569//// if (readOnly) recordReset();
570// for (view = m_views.first(); view != 0L; view = m_views.next() ) { 570// for (view = m_views.first(); view != 0L; view = m_views.next() ) {
571// emit static_cast<KateView *>( view )->newStatus(); 571// emit static_cast<KateView *>( view )->newStatus();
572// } 572// }
573 } 573 }
574} 574}
575 575
576bool KateDocument::isNewDoc() const { 576bool KateDocument::isNewDoc() const {
577 return newDoc; 577 return newDoc;
578} 578}
579 579
580void KateDocument::setModified(bool m) { 580void KateDocument::setModified(bool m) {
581 KTextEditor::View *view; 581 KTextEditor::View *view;
582 582
583 if (m != modified) { 583 if (m != modified) {
584 modified = m; 584 modified = m;
585 for (view = m_views.first(); view != 0L; view = m_views.next() ) { 585 for (view = m_views.first(); view != 0L; view = m_views.next() ) {
586 emit static_cast<KateView *>( view )->newStatus(); 586 emit static_cast<KateView *>( view )->newStatus();
587 } 587 }
588 emit modifiedChanged (); 588 emit modifiedChanged ();
589 } 589 }
590} 590}
591 591
592bool KateDocument::isModified() const { 592bool KateDocument::isModified() const {
593 return modified; 593 return modified;
594} 594}
595 595
596void KateDocument::readConfig() 596void KateDocument::readConfig()
597{ 597{
598 KateConfig *config = KGlobal::config(); 598 KateConfig *config = KGlobal::config();
599 config->setGroup("Kate Document"); 599 config->setGroup("Kate Document");
600 600
601 myWordWrap = config->readBoolEntry("Word Wrap On", false); 601 myWordWrap = config->readBoolEntry("Word Wrap On", false);
602 myWordWrapAt = config->readNumEntry("Word Wrap At", 80); 602 myWordWrapAt = config->readNumEntry("Word Wrap At", 80);
603 if (myWordWrap) 603 if (myWordWrap)
604 wrapText (myWordWrapAt); 604 wrapText (myWordWrapAt);
605 605
606 setTabWidth(config->readNumEntry("TabWidth", 8)); 606 setTabWidth(config->readNumEntry("TabWidth", 8));
607 setUndoSteps(config->readNumEntry("UndoSteps", 50)); 607 setUndoSteps(config->readNumEntry("UndoSteps", 50));
608 m_singleSelection = config->readBoolEntry("SingleSelection", false); 608 m_singleSelection = config->readBoolEntry("SingleSelection", false);
609 myEncoding = config->readEntry("Encoding", QString::fromLatin1(QTextCodec::codecForLocale()->name())); 609 myEncoding = config->readEntry("Encoding", QString::fromLatin1(QTextCodec::codecForLocale()->name()));
610 setFont (config->readFontEntry("Font", myFont)); 610 setFont (config->readFontEntry("Font", myFont));
611 611
612 colors[0] = config->readColorEntry("Color Background", colors[0]); 612 colors[0] = config->readColorEntry("Color Background", colors[0]);
613 colors[1] = config->readColorEntry("Color Selected", colors[1]); 613 colors[1] = config->readColorEntry("Color Selected", colors[1]);
614 614
615// config->sync(); 615// config->sync();
616} 616}
617 617
618void KateDocument::writeConfig() 618void KateDocument::writeConfig()
619{ 619{
620 KateConfig *config = KGlobal::config(); 620 KateConfig *config = KGlobal::config();
621 config->setGroup("Kate Document"); 621 config->setGroup("Kate Document");
622 config->writeEntry("Word Wrap On", myWordWrap); 622 config->writeEntry("Word Wrap On", myWordWrap);
623 config->writeEntry("Word Wrap At", myWordWrapAt); 623 config->writeEntry("Word Wrap At", myWordWrapAt);
624 config->writeEntry("TabWidth", tabChars); 624 config->writeEntry("TabWidth", tabChars);
625 config->writeEntry("UndoSteps", undoSteps); 625 config->writeEntry("UndoSteps", undoSteps);
626 config->writeEntry("SingleSelection", m_singleSelection); 626 config->writeEntry("SingleSelection", m_singleSelection);
627 config->writeEntry("Encoding", myEncoding); 627 config->writeEntry("Encoding", myEncoding);
628 config->writeEntry("Font", myFont); 628 config->writeEntry("Font", myFont);
629 config->writeEntry("Color Background", colors[0]); 629 config->writeEntry("Color Background", colors[0]);
630 config->writeEntry("Color Selected", colors[1]); 630 config->writeEntry("Color Selected", colors[1]);
631// config->sync(); 631// config->sync();
632} 632}
633 633
634void KateDocument::readSessionConfig(KateConfig *config) 634void KateDocument::readSessionConfig(KateConfig *config)
635{ 635{
636 m_url = config->readEntry("URL"); // ### doesn't this break the encoding? (Simon) 636 m_url = config->readEntry("URL"); // ### doesn't this break the encoding? (Simon)
637 setHighlight(hlManager->nameFind(config->readEntry("Highlight"))); 637 setHighlight(hlManager->nameFind(config->readEntry("Highlight")));
638 // anders: restore bookmarks if possible 638 // anders: restore bookmarks if possible
639 QValueList<int> l = config->readIntListEntry("Bookmarks"); 639 QValueList<int> l = config->readIntListEntry("Bookmarks");
640 if ( l.count() ) { 640 if ( l.count() ) {
641 for (uint i=0; i < l.count(); i++) { 641 for (uint i=0; i < l.count(); i++) {
642 if ( numLines() < l[i] ) break; 642 if ( numLines() < l[i] ) break;
643 getTextLine( l[i] )->addMark( Bookmark ); 643 getTextLine( l[i] )->addMark( Bookmark );
644 } 644 }
645 } 645 }
646} 646}
647 647
648void KateDocument::writeSessionConfig(KateConfig *config) 648void KateDocument::writeSessionConfig(KateConfig *config)
649{ 649{
650#if 0 650#if 0
651 config->writeEntry("URL", m_url); // ### encoding?? (Simon) 651 config->writeEntry("URL", m_url); // ### encoding?? (Simon)
652 config->writeEntry("Highlight", m_highlight->name()); 652 config->writeEntry("Highlight", m_highlight->name());
653 // anders: save bookmarks 653 // anders: save bookmarks
654 QList<Kate::Mark> l = marks(); 654 QList<Kate::Mark> l = marks();
655 QValueList<int> ml; 655 QValueList<int> ml;
656 for (uint i=0; i < l.count(); i++) { 656 for (uint i=0; i < l.count(); i++) {
657 if ( l.at(i)->type == 1) // only save bookmarks 657 if ( l.at(i)->type == 1) // only save bookmarks
658 ml << l.at(i)->line; 658 ml << l.at(i)->line;
659 } 659 }
660 if ( ml.count() ) 660 if ( ml.count() )
661 config->writeEntry("Bookmarks", ml); 661 config->writeEntry("Bookmarks", ml);
662#endif 662#endif
663} 663}
664 664
665 665
666void KateDocument::setHighlight(int n) { 666void KateDocument::setHighlight(int n) {
667 Highlight *h; 667 Highlight *h;
668 668
669// hlNumber = n; 669// hlNumber = n;
670 670
671 h = hlManager->getHl(n); 671 h = hlManager->getHl(n);
672 if (h == m_highlight) { 672 if (h == m_highlight) {
673 updateLines(); 673 updateLines();
674 } else { 674 } else {
675 if (m_highlight != 0L) m_highlight->release(); 675 if (m_highlight != 0L) m_highlight->release();
676 h->use(); 676 h->use();
677 m_highlight = h; 677 m_highlight = h;
678 makeAttribs(); 678 makeAttribs();
679 } 679 }
680 PreHighlightedTill=0; 680 PreHighlightedTill=0;
681 RequestPreHighlightTill=0; 681 RequestPreHighlightTill=0;
682 emit(highlightChanged()); 682 emit(highlightChanged());
683} 683}
684 684
685void KateDocument::makeAttribs() { 685void KateDocument::makeAttribs() {
686 qDebug("KateDocument::makeAttribs()"); 686 qDebug("KateDocument::makeAttribs()");
687 m_numAttribs = hlManager->makeAttribs(m_highlight, m_attribs, maxAttribs); 687 m_numAttribs = hlManager->makeAttribs(m_highlight, m_attribs, maxAttribs);
688 updateFontData(); 688 updateFontData();
689 updateLines(); 689 updateLines();
690} 690}
691 691
692void KateDocument::updateFontData() { 692void KateDocument::updateFontData() {
693 int maxAscent, maxDescent; 693 int maxAscent, maxDescent;
694 int tabWidth; 694 int tabWidth;
695 KateView *view; 695 KateView *view;
696 696
697 maxAscent = myFontMetrics.ascent(); 697 maxAscent = myFontMetrics.ascent();
698 maxDescent = myFontMetrics.descent(); 698 maxDescent = myFontMetrics.descent();
699 tabWidth = myFontMetrics.width(' '); 699 tabWidth = myFontMetrics.width(' ');
700 700
701 fontHeight = maxAscent + maxDescent + 1; 701 fontHeight = maxAscent + maxDescent + 1;
702 fontAscent = maxAscent; 702 fontAscent = maxAscent;
703 m_tabWidth = tabChars*tabWidth; 703 m_tabWidth = tabChars*tabWidth;
704 704
705 for (view = views.first(); view != 0L; view = views.next() ) { 705 for (view = views.first(); view != 0L; view = views.next() ) {
706 view->myViewInternal->drawBuffer->resize(view->width(),fontHeight); 706 view->myViewInternal->drawBuffer->resize(view->width(),fontHeight);
707 view->tagAll(); 707 view->tagAll();
708 view->updateCursor(); 708 view->updateCursor();
709 } 709 }
710} 710}
711 711
712void KateDocument::hlChanged() { //slot 712void KateDocument::hlChanged() { //slot
713 makeAttribs(); 713 makeAttribs();
714 updateViews(); 714 updateViews();
715} 715}
716 716
717 717
718void KateDocument::addView(KTextEditor::View *view) { 718void KateDocument::addView(KTextEditor::View *view) {
719 views.append( static_cast<KateView *>( view ) ); 719 views.append( static_cast<KateView *>( view ) );
720 KTextEditor::Document::addView( view ); 720 KTextEditor::Document::addView( view );
721 connect( static_cast<KateView *>( view ), SIGNAL( destroyed() ), this, SLOT( slotViewDestroyed() ) ); 721 connect( static_cast<KateView *>( view ), SIGNAL( destroyed() ), this, SLOT( slotViewDestroyed() ) );
722} 722}
723 723
724void KateDocument::removeView(KTextEditor::View *view) { 724void KateDocument::removeView(KTextEditor::View *view) {
725// if (undoView == view) recordReset(); 725// if (undoView == view) recordReset();
726 disconnect( static_cast<KateView *>( view ), SIGNAL( destroyed() ), this, SLOT( slotViewDestroyed() ) ); 726 disconnect( static_cast<KateView *>( view ), SIGNAL( destroyed() ), this, SLOT( slotViewDestroyed() ) );
727 views.removeRef( static_cast<KateView *>( view ) ); 727 views.removeRef( static_cast<KateView *>( view ) );
728 KTextEditor::Document::removeView( view ); 728 KTextEditor::Document::removeView( view );
729} 729}
730 730
731void KateDocument::slotViewDestroyed() 731void KateDocument::slotViewDestroyed()
732{ 732{
733 views.removeRef( static_cast<const KateView *>( sender() ) ); 733 views.removeRef( static_cast<const KateView *>( sender() ) );
734} 734}
735 735
736bool KateDocument::ownedView(KateView *view) { 736bool KateDocument::ownedView(KateView *view) {
737 // do we own the given view? 737 // do we own the given view?
738 return (views.containsRef(view) > 0); 738 return (views.containsRef(view) > 0);
739} 739}
740 740
741bool KateDocument::isLastView(int numViews) { 741bool KateDocument::isLastView(int numViews) {
742 return ((int) views.count() == numViews); 742 return ((int) views.count() == numViews);
743} 743}
744 744
745int KateDocument::textWidth(const TextLine::Ptr &textLine, int cursorX) { 745int KateDocument::textWidth(const TextLine::Ptr &textLine, int cursorX) {
746 int x; 746 int x;
747 int z; 747 int z;
748 QChar ch; 748 QChar ch;
749 Attribute *a; 749 Attribute *a;
750 750
751 x = 0; 751 x = 0;
752 for (z = 0; z < cursorX; z++) { 752 for (z = 0; z < cursorX; z++) {
753 ch = textLine->getChar(z); 753 ch = textLine->getChar(z);
754 a = &m_attribs[textLine->getAttr(z)]; 754 a = &m_attribs[textLine->getAttr(z)];
755 755
756 if (ch == '\t') 756 if (ch == '\t')
757 x += m_tabWidth - (x % m_tabWidth); 757 x += m_tabWidth - (x % m_tabWidth);
758 else if (a->bold && a->italic) 758 else if (a->bold && a->italic)
759 x += myFontMetricsBI.width(ch); 759 x += myFontMetricsBI.width(ch);
760 else if (a->bold) 760 else if (a->bold)
761 x += myFontMetricsBold.width(ch); 761 x += myFontMetricsBold.width(ch);
762 else if (a->italic) 762 else if (a->italic)
763 x += myFontMetricsItalic.width(ch); 763 x += myFontMetricsItalic.width(ch);
764 else 764 else
765 x += myFontMetrics.width(ch); 765 x += myFontMetrics.width(ch);
766 } 766 }
767 return x; 767 return x;
768} 768}
769 769
770int KateDocument::textWidth(PointStruc &cursor) { 770int KateDocument::textWidth(PointStruc &cursor) {
771 if (cursor.x < 0) 771 if (cursor.x < 0)
772 cursor.x = 0; 772 cursor.x = 0;
773 if (cursor.y < 0) 773 if (cursor.y < 0)
774 cursor.y = 0; 774 cursor.y = 0;
775 if (cursor.y >= numLines()) 775 if (cursor.y >= numLines())
776 cursor.y = lastLine(); 776 cursor.y = lastLine();
777 return textWidth(getTextLine(cursor.y),cursor.x); 777 return textWidth(getTextLine(cursor.y),cursor.x);
778} 778}
779 779
780int KateDocument::textWidth(bool wrapCursor, PointStruc &cursor, int xPos) { 780int KateDocument::textWidth(bool wrapCursor, PointStruc &cursor, int xPos) {
781 int len; 781 int len;
782 int x, oldX; 782 int x, oldX;
783 int z; 783 int z;
784 QChar ch; 784 QChar ch;
785 Attribute *a; 785 Attribute *a;
786 786
787 if (cursor.y < 0) cursor.y = 0; 787 if (cursor.y < 0) cursor.y = 0;
788 if (cursor.y > lastLine()) cursor.y = lastLine(); 788 if (cursor.y > lastLine()) cursor.y = lastLine();
789 TextLine::Ptr textLine = getTextLine(cursor.y); 789 TextLine::Ptr textLine = getTextLine(cursor.y);
790 len = textLine->length(); 790 len = textLine->length();
791 791
792 x = oldX = z = 0; 792 x = oldX = z = 0;
793 while (x < xPos && (!wrapCursor || z < len)) { 793 while (x < xPos && (!wrapCursor || z < len)) {
794 oldX = x; 794 oldX = x;
795 ch = textLine->getChar(z); 795 ch = textLine->getChar(z);
796 a = &m_attribs[textLine->getAttr(z)]; 796 a = &m_attribs[textLine->getAttr(z)];
797 797
798 if (ch == '\t') 798 if (ch == '\t')
799 x += m_tabWidth - (x % m_tabWidth); 799 x += m_tabWidth - (x % m_tabWidth);
800 else if (a->bold && a->italic) 800 else if (a->bold && a->italic)
801 x += myFontMetricsBI.width(ch); 801 x += myFontMetricsBI.width(ch);
802 else if (a->bold) 802 else if (a->bold)
803 x += myFontMetricsBold.width(ch); 803 x += myFontMetricsBold.width(ch);
804 else if (a->italic) 804 else if (a->italic)
805 x += myFontMetricsItalic.width(ch); 805 x += myFontMetricsItalic.width(ch);
806 else 806 else
807 x += myFontMetrics.width(ch); 807 x += myFontMetrics.width(ch);
808 808
809 z++; 809 z++;
810 } 810 }
811 if (xPos - oldX < x - xPos && z > 0) { 811 if (xPos - oldX < x - xPos && z > 0) {
812 z--; 812 z--;
813 x = oldX; 813 x = oldX;
814 } 814 }
815 cursor.x = z; 815 cursor.x = z;
816 return x; 816 return x;
817} 817}
818 818
819 819
820int KateDocument::textPos(const TextLine::Ptr &textLine, int xPos) { 820int KateDocument::textPos(const TextLine::Ptr &textLine, int xPos) {
821 int x, oldX; 821 int x, oldX;
822 int z; 822 int z;
823 QChar ch; 823 QChar ch;
824 Attribute *a; 824 Attribute *a;
825 825
826 x = oldX = z = 0; 826 x = oldX = z = 0;
827 while (x < xPos) { // && z < len) { 827 while (x < xPos) { // && z < len) {
828 oldX = x; 828 oldX = x;
829 ch = textLine->getChar(z); 829 ch = textLine->getChar(z);
830 a = &m_attribs[textLine->getAttr(z)]; 830 a = &m_attribs[textLine->getAttr(z)];
831 831
832 if (ch == '\t') 832 if (ch == '\t')
833 x += m_tabWidth - (x % m_tabWidth); 833 x += m_tabWidth - (x % m_tabWidth);
834 else if (a->bold && a->italic) 834 else if (a->bold && a->italic)
835 x += myFontMetricsBI.width(ch); 835 x += myFontMetricsBI.width(ch);
836 else if (a->bold) 836 else if (a->bold)
837 x += myFontMetricsBold.width(ch); 837 x += myFontMetricsBold.width(ch);
838 else if (a->italic) 838 else if (a->italic)
839 x += myFontMetricsItalic.width(ch); 839 x += myFontMetricsItalic.width(ch);
840 else 840 else
841 x += myFontMetrics.width(ch); 841 x += myFontMetrics.width(ch);
842 842
843 z++; 843 z++;
844 } 844 }
845 if (xPos - oldX < x - xPos && z > 0) { 845 if (xPos - oldX < x - xPos && z > 0) {
846 z--; 846 z--;
847 // newXPos = oldX; 847 // newXPos = oldX;
848 }// else newXPos = x; 848 }// else newXPos = x;
849 return z; 849 return z;
850} 850}
851 851
852int KateDocument::textWidth() { 852int KateDocument::textWidth() {
853 return int(maxLength + 8); 853 return int(maxLength + 8);
854} 854}
855 855
856int KateDocument::textHeight() { 856int KateDocument::textHeight() {
857 return numLines()*fontHeight; 857 return numLines()*fontHeight;
858} 858}
859 859
860void KateDocument::insert(VConfig &c, const QString &s) { 860void KateDocument::insert(VConfig &c, const QString &s) {
861 int pos; 861 int pos;
862 QChar ch; 862 QChar ch;
863 QString buf; 863 QString buf;
864 864
865 if (s.isEmpty()) return; 865 if (s.isEmpty()) return;
866 866
867 recordStart(c, KateActionGroup::ugPaste); 867 recordStart(c, KateActionGroup::ugPaste);
868 868
869 pos = 0; 869 pos = 0;
870 if (!(c.flags & KateView::cfVerticalSelect)) { 870 if (!(c.flags & KateView::cfVerticalSelect)) {
871 do { 871 do {
872 ch = s[pos]; 872 ch = s[pos];
873 if (ch.isPrint() || ch == '\t') { 873 if (ch.isPrint() || ch == '\t') {
874 buf += ch; // append char to buffer 874 buf += ch; // append char to buffer
875 } else if (ch == '\n') { 875 } else if (ch == '\n') {
876 recordAction(KateAction::newLine, c.cursor); // wrap contents behind cursor to new line 876 recordAction(KateAction::newLine, c.cursor); // wrap contents behind cursor to new line
877 recordInsert(c, buf); // append to old line 877 recordInsert(c, buf); // append to old line
878// c.cursor.x += buf.length(); 878// c.cursor.x += buf.length();
879 buf.truncate(0); // clear buffer 879 buf.truncate(0); // clear buffer
880 c.cursor.y++; 880 c.cursor.y++;
881 c.cursor.x = 0; 881 c.cursor.x = 0;
882 } 882 }
883 pos++; 883 pos++;
884 } while (pos < (int) s.length()); 884 } while (pos < (int) s.length());
885 } else { 885 } else {
886 int xPos; 886 int xPos;
887 887
888 xPos = textWidth(c.cursor); 888 xPos = textWidth(c.cursor);
889 do { 889 do {
890 ch = s[pos]; 890 ch = s[pos];
891 if (ch.isPrint() || ch == '\t') { 891 if (ch.isPrint() || ch == '\t') {
892 buf += ch; 892 buf += ch;
893 } else if (ch == '\n') { 893 } else if (ch == '\n') {
894 recordInsert(c, buf); 894 recordInsert(c, buf);
895 c.cursor.x += buf.length(); 895 c.cursor.x += buf.length();
896 buf.truncate(0); 896 buf.truncate(0);
897 c.cursor.y++; 897 c.cursor.y++;
898 if (c.cursor.y >= numLines()) 898 if (c.cursor.y >= numLines())
899 recordAction(KateAction::insLine, c.cursor); 899 recordAction(KateAction::insLine, c.cursor);
900 c.cursor.x = textPos(getTextLine(c.cursor.y), xPos); 900 c.cursor.x = textPos(getTextLine(c.cursor.y), xPos);
901 } 901 }
902 pos++; 902 pos++;
903 } while (pos < (int) s.length()); 903 } while (pos < (int) s.length());
904 } 904 }
905 recordInsert(c, buf); 905 recordInsert(c, buf);
906 c.cursor.x += buf.length(); 906 c.cursor.x += buf.length();
907 recordEnd(c); 907 recordEnd(c);
908} 908}
909 909
910void KateDocument::insertFile(VConfig &c, QIODevice &dev) 910void KateDocument::insertFile(VConfig &c, QIODevice &dev)
911{ 911{
912 recordStart(c, KateActionGroup::ugPaste); 912 recordStart(c, KateActionGroup::ugPaste);
913 913
914 QString buf; 914 QString buf;
915 QChar ch, last; 915 QChar ch, last;
916 916
917 QTextStream stream( &dev ); 917 QTextStream stream( &dev );
918 918
919 while ( !stream.atEnd() ) { 919 while ( !stream.atEnd() ) {
920 stream >> ch; 920 stream >> ch;
921 921
922 if (ch.isPrint() || ch == '\t') { 922 if (ch.isPrint() || ch == '\t') {
923 buf += ch; 923 buf += ch;
924 } else if (ch == '\n' || ch == '\r') { 924 } else if (ch == '\n' || ch == '\r') {
925 if (last != '\r' || ch != '\n') { 925 if (last != '\r' || ch != '\n') {
926 recordAction(KateAction::newLine, c.cursor); 926 recordAction(KateAction::newLine, c.cursor);
927 recordInsert(c, buf); 927 recordInsert(c, buf);
928 buf.truncate(0); 928 buf.truncate(0);
929 c.cursor.y++; 929 c.cursor.y++;
930 c.cursor.x = 0; 930 c.cursor.x = 0;
931 } 931 }
932 last = ch; 932 last = ch;
933 } 933 }
934 } 934 }
935 935
936 recordInsert(c, buf); 936 recordInsert(c, buf);
937 recordEnd(c); 937 recordEnd(c);
938} 938}
939 939
940int KateDocument::currentColumn(PointStruc &cursor) { 940int KateDocument::currentColumn(PointStruc &cursor) {
941 return getTextLine(cursor.y)->cursorX(cursor.x,tabChars); 941 return getTextLine(cursor.y)->cursorX(cursor.x,tabChars);
942} 942}
943 943
944bool KateDocument::insertChars(VConfig &c, const QString &chars) { 944bool KateDocument::insertChars(VConfig &c, const QString &chars) {
945 int z, pos, l; 945 int z, pos, l;
946 bool onlySpaces; 946 bool onlySpaces;
947 QChar ch; 947 QChar ch;
948 QString buf; 948 QString buf;
949 949
950 TextLine::Ptr textLine = getTextLine(c.cursor.y); 950 TextLine::Ptr textLine = getTextLine(c.cursor.y);
951 951
952 pos = 0; 952 pos = 0;
953 onlySpaces = true; 953 onlySpaces = true;
954 for (z = 0; z < (int) chars.length(); z++) { 954 for (z = 0; z < (int) chars.length(); z++) {
955 ch = chars[z]; 955 ch = chars[z];
956 if (ch == '\t' && c.flags & KateView::cfReplaceTabs) { 956 if (ch == '\t' && c.flags & KateView::cfReplaceTabs) {
957 l = tabChars - (textLine->cursorX(c.cursor.x, tabChars) % tabChars); 957 l = tabChars - (textLine->cursorX(c.cursor.x, tabChars) % tabChars);
958 while (l > 0) { 958 while (l > 0) {
959 buf.insert(pos, ' '); 959 buf.insert(pos, ' ');
960 pos++; 960 pos++;
961 l--; 961 l--;
962 } 962 }
963 } else if (ch.isPrint() || ch == '\t') { 963 } else if (ch.isPrint() || ch == '\t') {
964 buf.insert(pos, ch); 964 buf.insert(pos, ch);
965 pos++; 965 pos++;
966 if (ch != ' ') onlySpaces = false; 966 if (ch != ' ') onlySpaces = false;
967 if (c.flags & KateView::cfAutoBrackets) { 967 if (c.flags & KateView::cfAutoBrackets) {
968 if (ch == '(') buf.insert(pos, ')'); 968 if (ch == '(') buf.insert(pos, ')');
969 if (ch == '[') buf.insert(pos, ']'); 969 if (ch == '[') buf.insert(pos, ']');
970 if (ch == '{') buf.insert(pos, '}'); 970 if (ch == '{') buf.insert(pos, '}');
971 } 971 }
972 } 972 }
973 } 973 }
974 //pos = cursor increment 974 //pos = cursor increment
975 975
976 //return false if nothing has to be inserted 976 //return false if nothing has to be inserted
977 if (buf.isEmpty()) return false; 977 if (buf.isEmpty()) return false;
978 978
979 //auto deletion of the marked text occurs not very often and can therefore 979 //auto deletion of the marked text occurs not very often and can therefore
980 // be recorded separately 980 // be recorded separately
981 if (c.flags &KateView:: cfDelOnInput) delMarkedText(c); 981 if (c.flags &KateView:: cfDelOnInput) delMarkedText(c);
982 982
983 recordStart(c, KateActionGroup::ugInsChar); 983 recordStart(c, KateActionGroup::ugInsChar);
984 recordReplace(c/*.cursor*/, (c.flags & KateView::cfOvr) ? buf.length() : 0, buf); 984 recordReplace(c/*.cursor*/, (c.flags & KateView::cfOvr) ? buf.length() : 0, buf);
985 c.cursor.x += pos; 985 c.cursor.x += pos;
986 986
987 if (myWordWrap && myWordWrapAt > 0) { 987 if (myWordWrap && myWordWrapAt > 0) {
988 int line; 988 int line;
989 const QChar *s; 989 const QChar *s;
990// int pos; 990// int pos;
991 PointStruc actionCursor; 991 PointStruc actionCursor;
992 992
993 line = c.cursor.y; 993 line = c.cursor.y;
994 do { 994 do {
995 textLine = getTextLine(line); 995 textLine = getTextLine(line);
996 s = textLine->getText(); 996 s = textLine->getText();
997 l = textLine->length(); 997 l = textLine->length();
998 for (z = myWordWrapAt; z < l; z++) if (!s[z].isSpace()) break; //search for text to wrap 998 for (z = myWordWrapAt; z < l; z++) if (!s[z].isSpace()) break; //search for text to wrap
999 if (z >= l) break; // nothing more to wrap 999 if (z >= l) break; // nothing more to wrap
1000 pos = myWordWrapAt; 1000 pos = myWordWrapAt;
1001 for (; z >= 0; z--) { //find wrap position 1001 for (; z >= 0; z--) { //find wrap position
1002 if (s[z].isSpace()) { 1002 if (s[z].isSpace()) {
1003 pos = z + 1; 1003 pos = z + 1;
1004 break; 1004 break;
1005 } 1005 }
1006 } 1006 }
1007 //pos = wrap position 1007 //pos = wrap position
1008 1008
1009 if (line == c.cursor.y && pos <= c.cursor.x) { 1009 if (line == c.cursor.y && pos <= c.cursor.x) {
1010 //wrap cursor 1010 //wrap cursor
1011 c.cursor.y++; 1011 c.cursor.y++;
1012 c.cursor.x -= pos; 1012 c.cursor.x -= pos;
1013 } 1013 }
1014 1014
1015 if (line == lastLine() || (getTextLine(line+1)->length() == 0) ) { 1015 if (line == lastLine() || (getTextLine(line+1)->length() == 0) ) {
1016 //at end of doc: create new line 1016 //at end of doc: create new line
1017 actionCursor.x = pos; 1017 actionCursor.x = pos;
1018 actionCursor.y = line; 1018 actionCursor.y = line;
1019 recordAction(KateAction::newLine,actionCursor); 1019 recordAction(KateAction::newLine,actionCursor);
1020 } else { 1020 } else {
1021 //wrap 1021 //wrap
1022 actionCursor.y = line + 1; 1022 actionCursor.y = line + 1;
1023 if (!s[l - 1].isSpace()) { //add space in next line if necessary 1023 if (!s[l - 1].isSpace()) { //add space in next line if necessary
1024 actionCursor.x = 0; 1024 actionCursor.x = 0;
1025 recordInsert(actionCursor, " "); 1025 recordInsert(actionCursor, " ");
1026 } 1026 }
1027 actionCursor.x = textLine->length() - pos; 1027 actionCursor.x = textLine->length() - pos;
1028 recordAction(KateAction::wordWrap, actionCursor); 1028 recordAction(KateAction::wordWrap, actionCursor);
1029 } 1029 }
1030 line++; 1030 line++;
1031 } while (true); 1031 } while (true);
1032 } 1032 }
1033 recordEnd(c); 1033 recordEnd(c);
1034 return true; 1034 return true;
1035} 1035}
1036 1036
1037QString tabString(int pos, int tabChars) { 1037QString tabString(int pos, int tabChars) {
1038 QString s; 1038 QString s;
1039 while (pos >= tabChars) { 1039 while (pos >= tabChars) {
1040 s += '\t'; 1040 s += '\t';
1041 pos -= tabChars; 1041 pos -= tabChars;
1042 } 1042 }
1043 while (pos > 0) { 1043 while (pos > 0) {
1044 s += ' '; 1044 s += ' ';
1045 pos--; 1045 pos--;
1046 } 1046 }
1047 return s; 1047 return s;
1048} 1048}
1049 1049
1050void KateDocument::newLine(VConfig &c) { 1050void KateDocument::newLine(VConfig &c) {
1051 1051
1052 //auto deletion of marked text is done by the view to have a more 1052 //auto deletion of marked text is done by the view to have a more
1053 // "low level" KateDocument::newLine method 1053 // "low level" KateDocument::newLine method
1054 recordStart(c, KateActionGroup::ugInsLine); 1054 recordStart(c, KateActionGroup::ugInsLine);
1055 1055
1056 if (!(c.flags & KateView::cfAutoIndent)) { 1056 if (!(c.flags & KateView::cfAutoIndent)) {
1057 recordAction(KateAction::newLine,c.cursor); 1057 recordAction(KateAction::newLine,c.cursor);
1058 c.cursor.y++; 1058 c.cursor.y++;
1059 c.cursor.x = 0; 1059 c.cursor.x = 0;
1060 } else { 1060 } else {
1061 TextLine::Ptr textLine = getTextLine(c.cursor.y); 1061 TextLine::Ptr textLine = getTextLine(c.cursor.y);
1062 int pos = textLine->firstChar(); 1062 int pos = textLine->firstChar();
1063 if (c.cursor.x < pos) c.cursor.x = pos; // place cursor on first char if before 1063 if (c.cursor.x < pos) c.cursor.x = pos; // place cursor on first char if before
1064 1064
1065 int y = c.cursor.y; 1065 int y = c.cursor.y;
1066 while ((y > 0) && (pos < 0)) { // search a not empty text line 1066 while ((y > 0) && (pos < 0)) { // search a not empty text line
1067 textLine = getTextLine(--y); 1067 textLine = getTextLine(--y);
1068 pos = textLine->firstChar(); 1068 pos = textLine->firstChar();
1069 } 1069 }
1070 recordAction(KateAction::newLine, c.cursor); 1070 recordAction(KateAction::newLine, c.cursor);
1071 c.cursor.y++; 1071 c.cursor.y++;
1072 c.cursor.x = 0; 1072 c.cursor.x = 0;
1073 if (pos > 0) { 1073 if (pos > 0) {
1074 pos = textLine->cursorX(pos, tabChars); 1074 pos = textLine->cursorX(pos, tabChars);
1075// if (getTextLine(c.cursor.y)->length() > 0) { 1075// if (getTextLine(c.cursor.y)->length() > 0) {
1076 QString s = tabString(pos, (c.flags & KateView::cfSpaceIndent) ? 0xffffff : tabChars); 1076 QString s = tabString(pos, (c.flags & KateView::cfSpaceIndent) ? 0xffffff : tabChars);
1077 recordInsert(c.cursor, s); 1077 recordInsert(c.cursor, s);
1078 pos = s.length(); 1078 pos = s.length();
1079// } 1079// }
1080// recordInsert(c.cursor, QString(textLine->getText(), pos)); 1080// recordInsert(c.cursor, QString(textLine->getText(), pos));
1081 c.cursor.x = pos; 1081 c.cursor.x = pos;
1082 } 1082 }
1083 } 1083 }
1084 1084
1085 recordEnd(c); 1085 recordEnd(c);
1086} 1086}
1087 1087
1088void KateDocument::killLine(VConfig &c) { 1088void KateDocument::killLine(VConfig &c) {
1089 1089
1090 recordStart(c, KateActionGroup::ugDelLine); 1090 recordStart(c, KateActionGroup::ugDelLine);
1091 c.cursor.x = 0; 1091 c.cursor.x = 0;
1092 recordDelete(c.cursor, 0xffffff); 1092 recordDelete(c.cursor, 0xffffff);
1093 if (c.cursor.y < lastLine()) { 1093 if (c.cursor.y < lastLine()) {
1094 recordAction(KateAction::killLine, c.cursor); 1094 recordAction(KateAction::killLine, c.cursor);
1095 } 1095 }
1096 recordEnd(c); 1096 recordEnd(c);
1097} 1097}
1098 1098
1099void KateDocument::backspace(VConfig &c) { 1099void KateDocument::backspace(VConfig &c) {
1100 1100
1101 if (c.cursor.x <= 0 && c.cursor.y <= 0) return; 1101 if (c.cursor.x <= 0 && c.cursor.y <= 0) return;
1102 1102
1103 if (c.cursor.x > 0) { 1103 if (c.cursor.x > 0) {
1104 recordStart(c, KateActionGroup::ugDelChar); 1104 recordStart(c, KateActionGroup::ugDelChar);
1105 if (!(c.flags & KateView::cfBackspaceIndents)) { 1105 if (!(c.flags & KateView::cfBackspaceIndents)) {
1106 // ordinary backspace 1106 // ordinary backspace
1107 c.cursor.x--; 1107 c.cursor.x--;
1108 recordDelete(c.cursor, 1); 1108 recordDelete(c.cursor, 1);
1109 } else { 1109 } else {
1110 // backspace indents: erase to next indent position 1110 // backspace indents: erase to next indent position
1111 int l = 1; // del one char 1111 int l = 1; // del one char
1112 1112
1113 TextLine::Ptr textLine = getTextLine(c.cursor.y); 1113 TextLine::Ptr textLine = getTextLine(c.cursor.y);
1114 int pos = textLine->firstChar(); 1114 int pos = textLine->firstChar();
1115 if (pos < 0 || pos >= c.cursor.x) { 1115 if (pos < 0 || pos >= c.cursor.x) {
1116 // only spaces on left side of cursor 1116 // only spaces on left side of cursor
1117 // search a line with less spaces 1117 // search a line with less spaces
1118 int y = c.cursor.y; 1118 int y = c.cursor.y;
1119 while (y > 0) { 1119 while (y > 0) {
1120 textLine = getTextLine(--y); 1120 textLine = getTextLine(--y);
1121 pos = textLine->firstChar(); 1121 pos = textLine->firstChar();
1122 if (pos >= 0 && pos < c.cursor.x) { 1122 if (pos >= 0 && pos < c.cursor.x) {
1123 l = c.cursor.x - pos; // del more chars 1123 l = c.cursor.x - pos; // del more chars
1124 break; 1124 break;
1125 } 1125 }
1126 } 1126 }
1127 } 1127 }
1128 // break effectively jumps here 1128 // break effectively jumps here
1129 c.cursor.x -= l; 1129 c.cursor.x -= l;
1130 recordDelete(c.cursor, l); 1130 recordDelete(c.cursor, l);
1131 } 1131 }
1132 } else { 1132 } else {
1133 // c.cursor.x == 0: wrap to previous line 1133 // c.cursor.x == 0: wrap to previous line
1134 recordStart(c, KateActionGroup::ugDelLine); 1134 recordStart(c, KateActionGroup::ugDelLine);
1135 c.cursor.y--; 1135 c.cursor.y--;
1136 c.cursor.x = getTextLine(c.cursor.y)->length(); 1136 c.cursor.x = getTextLine(c.cursor.y)->length();
1137 recordAction(KateAction::delLine,c.cursor); 1137 recordAction(KateAction::delLine,c.cursor);
1138 } 1138 }
1139 recordEnd(c); 1139 recordEnd(c);
1140} 1140}
1141 1141
1142 1142
1143void KateDocument::del(VConfig &c) { 1143void KateDocument::del(VConfig &c) {
1144 TextLine::Ptr textLine = getTextLine(c.cursor.y); 1144 TextLine::Ptr textLine = getTextLine(c.cursor.y);
1145 int len = (c.flags & KateView::cfRemoveSpaces) ? textLine->lastChar() : textLine->length(); 1145 int len = (c.flags & KateView::cfRemoveSpaces) ? textLine->lastChar() : textLine->length();
1146 if (c.cursor.x < len/*getTextLine(c.cursor.y)->length()*/) { 1146 if (c.cursor.x < len/*getTextLine(c.cursor.y)->length()*/) {
1147 // delete one character 1147 // delete one character
1148 recordStart(c, KateActionGroup::ugDelChar); 1148 recordStart(c, KateActionGroup::ugDelChar);
1149 recordDelete(c.cursor, 1); 1149 recordDelete(c.cursor, 1);
1150 recordEnd(c); 1150 recordEnd(c);
1151 } else { 1151 } else {
1152 if (c.cursor.y < lastLine()) { 1152 if (c.cursor.y < lastLine()) {
1153 // wrap next line to this line 1153 // wrap next line to this line
1154 textLine->truncate(c.cursor.x); // truncate spaces 1154 textLine->truncate(c.cursor.x); // truncate spaces
1155 recordStart(c, KateActionGroup::ugDelLine); 1155 recordStart(c, KateActionGroup::ugDelLine);
1156 recordAction(KateAction::delLine,c.cursor); 1156 recordAction(KateAction::delLine,c.cursor);
1157 recordEnd(c); 1157 recordEnd(c);
1158 } 1158 }
1159 } 1159 }
1160} 1160}
1161 1161
1162void KateDocument::clear() { 1162void KateDocument::clear() {
1163 PointStruc cursor; 1163 PointStruc cursor;
1164 KateView *view; 1164 KateView *view;
1165 1165
1166 setPseudoModal(0L); 1166 setPseudoModal(0L);
1167 cursor.x = cursor.y = 0; 1167 cursor.x = cursor.y = 0;
1168 for (view = views.first(); view != 0L; view = views.next() ) { 1168 for (view = views.first(); view != 0L; view = views.next() ) {
1169 view->updateCursor(cursor); 1169 view->updateCursor(cursor);
1170 view->tagAll(); 1170 view->tagAll();
1171 } 1171 }
1172 1172
1173 eolMode = KateDocument::eolUnix; 1173 eolMode = KateDocument::eolUnix;
1174 1174
1175 buffer->clear(); 1175 buffer->clear();
1176 longestLine = buffer->line(0); 1176 longestLine = buffer->line(0);
1177 1177
1178 maxLength = 0; 1178 maxLength = 0;
1179 1179
1180 select.x = -1; 1180 select.x = -1;
1181 1181
1182 selectStart = 0xffffff; 1182 selectStart = 0xffffff;
1183 selectEnd = 0; 1183 selectEnd = 0;
1184 oldMarkState = false; 1184 oldMarkState = false;
1185 1185
1186 setModified(false); 1186 setModified(false);
1187 1187
1188 undoList.clear(); 1188 undoList.clear();
1189 currentUndo = 0; 1189 currentUndo = 0;
1190 newUndo(); 1190 newUndo();
1191} 1191}
1192 1192
1193void KateDocument::cut(VConfig &c) { 1193void KateDocument::cut(VConfig &c) {
1194 1194
1195 if (selectEnd < selectStart) return; 1195 if (selectEnd < selectStart) return;
1196 1196
1197 copy(c.flags); 1197 copy(c.flags);
1198 delMarkedText(c); 1198 delMarkedText(c);
1199} 1199}
1200 1200
1201void KateDocument::copy(int flags) { 1201void KateDocument::copy(int flags) {
1202 1202
1203 if (selectEnd < selectStart) return; 1203 if (selectEnd < selectStart) return;
1204 1204
1205 QString s = markedText(flags); 1205 QString s = markedText(flags);
1206 if (!s.isEmpty()) { 1206 if (!s.isEmpty()) {
1207//#if defined(_WS_X11_) 1207//#if defined(_WS_X11_)
1208 if (m_singleSelection) 1208 if (m_singleSelection)
1209 disconnect(QApplication::clipboard(), SIGNAL(dataChanged()), this, 0); 1209 disconnect(QApplication::clipboard(), SIGNAL(dataChanged()), this, 0);
1210//#endif 1210//#endif
1211 QApplication::clipboard()->setText(s); 1211 QApplication::clipboard()->setText(s);
1212//#if defined(_WS_X11_) 1212//#if defined(_WS_X11_)
1213 if (m_singleSelection) { 1213 if (m_singleSelection) {
1214 connect(QApplication::clipboard(), SIGNAL(dataChanged()), 1214 connect(QApplication::clipboard(), SIGNAL(dataChanged()),
1215 this, SLOT(clipboardChanged())); 1215 this, SLOT(clipboardChanged()));
1216 } 1216 }
1217//#endif 1217//#endif
1218 } 1218 }
1219} 1219}
1220 1220
1221void KateDocument::paste(VConfig &c) { 1221void KateDocument::paste(VConfig &c) {
1222 QString s = QApplication::clipboard()->text(); 1222 QString s = QApplication::clipboard()->text();
1223 if (!s.isEmpty()) { 1223 if (!s.isEmpty()) {
1224 insert(c, s); 1224 insert(c, s);
1225 } 1225 }
1226} 1226}
1227 1227
1228void KateDocument::toggleRect(int start, int end, int x1, int x2) { 1228void KateDocument::toggleRect(int start, int end, int x1, int x2) {
1229 int z, line; 1229 int z, line;
1230 bool t; 1230 bool t;
1231 1231
1232 if (x1 > x2) { 1232 if (x1 > x2) {
1233 z = x1; 1233 z = x1;
1234 x1 = x2; 1234 x1 = x2;
1235 x2 = z; 1235 x2 = z;
1236 } 1236 }
1237 if (start > end) { 1237 if (start > end) {
1238 z = start; 1238 z = start;
1239 start = end; 1239 start = end;
1240 end = z; 1240 end = z;
1241 } 1241 }
1242 1242
1243 t = false; 1243 t = false;
1244 for (line = start; line < end; line++) { 1244 for (line = start; line < end; line++) {
1245 int x, oldX, s, e, newX1, newX2; 1245 int x, oldX, s, e, newX1, newX2;
1246 QChar ch; 1246 QChar ch;
1247 Attribute *a; 1247 Attribute *a;
1248 1248
1249 TextLine::Ptr textLine = getTextLine(line); 1249 TextLine::Ptr textLine = getTextLine(line);
1250 1250
1251 //--- speed optimization 1251 //--- speed optimization
1252 //s = textPos(textLine, x1, newX1); 1252 //s = textPos(textLine, x1, newX1);
1253 x = oldX = z = 0; 1253 x = oldX = z = 0;
1254 while (x < x1) { // && z < len) { 1254 while (x < x1) { // && z < len) {
1255 oldX = x; 1255 oldX = x;
1256 ch = textLine->getChar(z); 1256 ch = textLine->getChar(z);
1257 a = &m_attribs[textLine->getAttr(z)]; 1257 a = &m_attribs[textLine->getAttr(z)];
1258 1258
1259 if (ch == '\t') 1259 if (ch == '\t')
1260 x += m_tabWidth - (x % m_tabWidth); 1260 x += m_tabWidth - (x % m_tabWidth);
1261 else if (a->bold && a->italic) 1261 else if (a->bold && a->italic)
1262 x += myFontMetricsBI.width(ch); 1262 x += myFontMetricsBI.width(ch);
1263 else if (a->bold) 1263 else if (a->bold)
1264 x += myFontMetricsBold.width(ch); 1264 x += myFontMetricsBold.width(ch);
1265 else if (a->italic) 1265 else if (a->italic)
1266 x += myFontMetricsItalic.width(ch); 1266 x += myFontMetricsItalic.width(ch);
1267 else 1267 else
1268 x += myFontMetrics.width(ch); 1268 x += myFontMetrics.width(ch);
1269 1269
1270 z++; 1270 z++;
1271 } 1271 }
1272 s = z; 1272 s = z;
1273 if (x1 - oldX < x - x1 && z > 0) { 1273 if (x1 - oldX < x - x1 && z > 0) {
1274 s--; 1274 s--;
1275 newX1 = oldX; 1275 newX1 = oldX;
1276 } else newX1 = x; 1276 } else newX1 = x;
1277 //e = textPos(textLine, x2, newX2); 1277 //e = textPos(textLine, x2, newX2);
1278 while (x < x2) { // && z < len) { 1278 while (x < x2) { // && z < len) {
1279 oldX = x; 1279 oldX = x;
1280 ch = textLine->getChar(z); 1280 ch = textLine->getChar(z);
1281 a = &m_attribs[textLine->getAttr(z)]; 1281 a = &m_attribs[textLine->getAttr(z)];
1282 1282
1283 if (ch == '\t') 1283 if (ch == '\t')
1284 x += m_tabWidth - (x % m_tabWidth); 1284 x += m_tabWidth - (x % m_tabWidth);
1285 else if (a->bold && a->italic) 1285 else if (a->bold && a->italic)
1286 x += myFontMetricsBI.width(ch); 1286 x += myFontMetricsBI.width(ch);
1287 else if (a->bold) 1287 else if (a->bold)
1288 x += myFontMetricsBold.width(ch); 1288 x += myFontMetricsBold.width(ch);
1289 else if (a->italic) 1289 else if (a->italic)
1290 x += myFontMetricsItalic.width(ch); 1290 x += myFontMetricsItalic.width(ch);
1291 else 1291 else
1292 x += myFontMetrics.width(ch); 1292 x += myFontMetrics.width(ch);
1293 1293
1294 z++; 1294 z++;
1295 } 1295 }
1296 e = z; 1296 e = z;
1297 if (x2 - oldX < x - x2 && z > 0) { 1297 if (x2 - oldX < x - x2 && z > 0) {
1298 e--; 1298 e--;
1299 newX2 = oldX; 1299 newX2 = oldX;
1300 } else newX2 = x; 1300 } else newX2 = x;
1301 //--- 1301 //---
1302 1302
1303 if (e > s) { 1303 if (e > s) {
1304 textLine->toggleSelect(s, e); 1304 textLine->toggleSelect(s, e);
1305 tagLineRange(line, newX1, newX2); 1305 tagLineRange(line, newX1, newX2);
1306 t = true; 1306 t = true;
1307 } 1307 }
1308 } 1308 }
1309 if (t) { 1309 if (t) {
1310 end--; 1310 end--;
1311// tagLines(start, end); 1311// tagLines(start, end);
1312 1312
1313 if (start < selectStart) selectStart = start; 1313 if (start < selectStart) selectStart = start;
1314 if (end > selectEnd) selectEnd = end; 1314 if (end > selectEnd) selectEnd = end;
1315 emit selectionChanged(); 1315 emit selectionChanged();
1316 } 1316 }
1317} 1317}
1318 1318
1319void KateDocument::selectTo(VConfig &c, PointStruc &cursor, int cXPos) { 1319void KateDocument::selectTo(VConfig &c, PointStruc &cursor, int cXPos) {
1320 //c.cursor = old cursor position 1320 //c.cursor = old cursor position
1321 //cursor = new cursor position 1321 //cursor = new cursor position
1322 1322
1323 if (c.cursor.x != select.x || c.cursor.y != select.y) { 1323 if (c.cursor.x != select.x || c.cursor.y != select.y) {
1324 //new selection 1324 //new selection
1325 1325
1326 if (!(c.flags & KateView::cfKeepSelection)) deselectAll(); 1326 if (!(c.flags & KateView::cfKeepSelection)) deselectAll();
1327// else recordReset(); 1327// else recordReset();
1328 1328
1329 anchor = c.cursor; 1329 anchor = c.cursor;
1330 aXPos = c.cXPos; 1330 aXPos = c.cXPos;
1331 } 1331 }
1332 1332
1333 if (!(c.flags & KateView::cfVerticalSelect)) { 1333 if (!(c.flags & KateView::cfVerticalSelect)) {
1334 //horizontal selections 1334 //horizontal selections
1335 int x, y, sXPos; 1335 int x, y, sXPos;
1336 int ex, ey, eXPos; 1336 int ex, ey, eXPos;
1337 bool sel; 1337 bool sel;
1338 1338
1339 if (cursor.y > c.cursor.y || (cursor.y == c.cursor.y && cursor.x > c.cursor.x)) { 1339 if (cursor.y > c.cursor.y || (cursor.y == c.cursor.y && cursor.x > c.cursor.x)) {
1340 x = c.cursor.x; 1340 x = c.cursor.x;
1341 y = c.cursor.y; 1341 y = c.cursor.y;
1342 sXPos = c.cXPos; 1342 sXPos = c.cXPos;
1343 ex = cursor.x; 1343 ex = cursor.x;
1344 ey = cursor.y; 1344 ey = cursor.y;
1345 eXPos = cXPos; 1345 eXPos = cXPos;
1346 sel = true; 1346 sel = true;
1347 } else { 1347 } else {
1348 x = cursor.x; 1348 x = cursor.x;
1349 y = cursor.y; 1349 y = cursor.y;
1350 sXPos = cXPos; 1350 sXPos = cXPos;
1351 ex = c.cursor.x; 1351 ex = c.cursor.x;
1352 ey = c.cursor.y; 1352 ey = c.cursor.y;
1353 eXPos = c.cXPos; 1353 eXPos = c.cXPos;
1354 sel = false; 1354 sel = false;
1355 } 1355 }
1356 1356
1357// tagLines(y, ye); 1357// tagLines(y, ye);
1358 if (y < ey) { 1358 if (y < ey) {
1359 //tagLineRange(y, sXPos, 0xffffff); 1359 //tagLineRange(y, sXPos, 0xffffff);
1360 tagLines(y, ey -1); 1360 tagLines(y, ey -1);
1361 tagLineRange(ey, 0, eXPos); 1361 tagLineRange(ey, 0, eXPos);
1362 } else tagLineRange(y, sXPos, eXPos); 1362 } else tagLineRange(y, sXPos, eXPos);
1363 1363
1364 if (y < selectStart) selectStart = y; 1364 if (y < selectStart) selectStart = y;
1365 if (ey > selectEnd) selectEnd = ey; 1365 if (ey > selectEnd) selectEnd = ey;
1366 1366
1367 TextLine::Ptr textLine = getTextLine(y); 1367 TextLine::Ptr textLine = getTextLine(y);
1368 1368
1369 if (c.flags & KateView::cfXorSelect) { 1369 if (c.flags & KateView::cfXorSelect) {
1370 //xor selection with old selection 1370 //xor selection with old selection
1371 while (y < ey) { 1371 while (y < ey) {
1372 textLine->toggleSelectEol(x); 1372 textLine->toggleSelectEol(x);
1373 x = 0; 1373 x = 0;
1374 y++; 1374 y++;
1375 textLine = getTextLine(y); 1375 textLine = getTextLine(y);
1376 } 1376 }
1377 textLine->toggleSelect(x, ex); 1377 textLine->toggleSelect(x, ex);
1378 } else { 1378 } else {
1379 //set selection over old selection 1379 //set selection over old selection
1380 1380
1381 if (anchor.y > y || (anchor.y == y && anchor.x > x)) { 1381 if (anchor.y > y || (anchor.y == y && anchor.x > x)) {
1382 if (anchor.y < ey || (anchor.y == ey && anchor.x < ex)) { 1382 if (anchor.y < ey || (anchor.y == ey && anchor.x < ex)) {
1383 sel = !sel; 1383 sel = !sel;
1384 while (y < anchor.y) { 1384 while (y < anchor.y) {
1385 textLine->selectEol(sel, x); 1385 textLine->selectEol(sel, x);
1386 x = 0; 1386 x = 0;
1387 y++; 1387 y++;
1388 textLine = getTextLine(y); 1388 textLine = getTextLine(y);
1389 } 1389 }
1390 textLine->select(sel, x, anchor.x); 1390 textLine->select(sel, x, anchor.x);
1391 x = anchor.x; 1391 x = anchor.x;
1392 } 1392 }
1393 sel = !sel; 1393 sel = !sel;
1394 } 1394 }
1395 while (y < ey) { 1395 while (y < ey) {
1396 textLine->selectEol(sel, x); 1396 textLine->selectEol(sel, x);
1397 x = 0; 1397 x = 0;
1398 y++; 1398 y++;
1399 textLine = getTextLine(y); 1399 textLine = getTextLine(y);
1400 } 1400 }
1401 textLine->select(sel, x, ex); 1401 textLine->select(sel, x, ex);
1402 } 1402 }
1403 } else { 1403 } else {
1404 //vertical (block) selections 1404 //vertical (block) selections
1405// int ax, sx, ex; 1405// int ax, sx, ex;
1406 1406
1407// ax = textWidth(anchor); 1407// ax = textWidth(anchor);
1408// sx = textWidth(start); 1408// sx = textWidth(start);
1409// ex = textWidth(end); 1409// ex = textWidth(end);
1410 1410
1411 toggleRect(c.cursor.y + 1, cursor.y + 1, aXPos, c.cXPos); 1411 toggleRect(c.cursor.y + 1, cursor.y + 1, aXPos, c.cXPos);
1412 toggleRect(anchor.y, cursor.y + 1, c.cXPos, cXPos); 1412 toggleRect(anchor.y, cursor.y + 1, c.cXPos, cXPos);
1413 } 1413 }
1414 select = cursor; 1414 select = cursor;
1415 optimizeSelection(); 1415 optimizeSelection();
1416 emit selectionChanged(); 1416 emit selectionChanged();
1417} 1417}
1418 1418
1419 1419
1420void KateDocument::selectAll() { 1420void KateDocument::selectAll() {
1421 int z; 1421 int z;
1422 TextLine::Ptr textLine; 1422 TextLine::Ptr textLine;
1423 1423
1424 select.x = -1; 1424 select.x = -1;
1425 1425
1426// if (selectStart != 0 || selectEnd != lastLine()) recordReset(); 1426// if (selectStart != 0 || selectEnd != lastLine()) recordReset();
1427 1427
1428 selectStart = 0; 1428 selectStart = 0;
1429 selectEnd = lastLine(); 1429 selectEnd = lastLine();
1430 1430
1431 tagLines(selectStart,selectEnd); 1431 tagLines(selectStart,selectEnd);
1432 1432
1433 for (z = selectStart; z < selectEnd; z++) { 1433 for (z = selectStart; z < selectEnd; z++) {
1434 textLine = getTextLine(z); 1434 textLine = getTextLine(z);
1435 textLine->selectEol(true,0); 1435 textLine->selectEol(true,0);
1436 } 1436 }
1437 textLine = getTextLine(z); 1437 textLine = getTextLine(z);
1438 textLine->select(true,0,textLine->length()); 1438 textLine->select(true,0,textLine->length());
1439 emit selectionChanged(); 1439 emit selectionChanged();
1440} 1440}
1441 1441
1442void KateDocument::deselectAll() { 1442void KateDocument::deselectAll() {
1443 select.x = -1; 1443 select.x = -1;
1444 if (selectEnd < selectStart) return; 1444 if (selectEnd < selectStart) return;
1445 1445
1446// recordReset(); 1446// recordReset();
1447 1447
1448 tagLines(selectStart,selectEnd); 1448 tagLines(selectStart,selectEnd);
1449 1449
1450 for (int z = selectStart; z <= selectEnd; z++) { 1450 for (int z = selectStart; z <= selectEnd; z++) {
1451 TextLine::Ptr textLine = getTextLine(z); 1451 TextLine::Ptr textLine = getTextLine(z);
1452 textLine->selectEol(false,0); 1452 textLine->selectEol(false,0);
1453 } 1453 }
1454 selectStart = 0xffffff; 1454 selectStart = 0xffffff;
1455 selectEnd = 0; 1455 selectEnd = 0;
1456 emit selectionChanged(); 1456 emit selectionChanged();
1457} 1457}
1458 1458
1459void KateDocument::invertSelection() { 1459void KateDocument::invertSelection() {
1460 TextLine::Ptr textLine; 1460 TextLine::Ptr textLine;
1461 1461
1462 select.x = -1; 1462 select.x = -1;
1463 1463
1464// if (selectStart != 0 || selectEnd != lastLine()) recordReset(); 1464// if (selectStart != 0 || selectEnd != lastLine()) recordReset();
1465 1465
1466 selectStart = 0; 1466 selectStart = 0;
1467 selectEnd = lastLine(); 1467 selectEnd = lastLine();
1468 1468
1469 tagLines(selectStart,selectEnd); 1469 tagLines(selectStart,selectEnd);
1470 1470
1471 for (int z = selectStart; z < selectEnd; z++) { 1471 for (int z = selectStart; z < selectEnd; z++) {
1472 textLine = getTextLine(z); 1472 textLine = getTextLine(z);
1473 textLine->toggleSelectEol(0); 1473 textLine->toggleSelectEol(0);
1474 } 1474 }
1475 textLine = getTextLine(selectEnd); 1475 textLine = getTextLine(selectEnd);
1476 textLine->toggleSelect(0,textLine->length()); 1476 textLine->toggleSelect(0,textLine->length());
1477 optimizeSelection(); 1477 optimizeSelection();
1478 emit selectionChanged(); 1478 emit selectionChanged();
1479} 1479}
1480 1480
1481void KateDocument::selectWord(PointStruc &cursor, int flags) { 1481void KateDocument::selectWord(PointStruc &cursor, int flags) {
1482 int start, end, len; 1482 int start, end, len;
1483 1483
1484 TextLine::Ptr textLine = getTextLine(cursor.y); 1484 TextLine::Ptr textLine = getTextLine(cursor.y);
1485 len = textLine->length(); 1485 len = textLine->length();
1486 start = end = cursor.x; 1486 start = end = cursor.x;
1487 while (start > 0 && m_highlight->isInWord(textLine->getChar(start - 1))) start--; 1487 while (start > 0 && m_highlight->isInWord(textLine->getChar(start - 1))) start--;
1488 while (end < len && m_highlight->isInWord(textLine->getChar(end))) end++; 1488 while (end < len && m_highlight->isInWord(textLine->getChar(end))) end++;
1489 if (end <= start) return; 1489 if (end <= start) return;
1490 if (!(flags & KateView::cfKeepSelection)) deselectAll(); 1490 if (!(flags & KateView::cfKeepSelection)) deselectAll();
1491// else recordReset(); 1491// else recordReset();
1492 1492
1493 textLine->select(true, start, end); 1493 textLine->select(true, start, end);
1494 1494
1495 anchor.x = start; 1495 anchor.x = start;
1496 select.x = end; 1496 select.x = end;
1497 anchor.y = select.y = cursor.y; 1497 anchor.y = select.y = cursor.y;
1498 tagLines(cursor.y, cursor.y); 1498 tagLines(cursor.y, cursor.y);
1499 if (cursor.y < selectStart) selectStart = cursor.y; 1499 if (cursor.y < selectStart) selectStart = cursor.y;
1500 if (cursor.y > selectEnd) selectEnd = cursor.y; 1500 if (cursor.y > selectEnd) selectEnd = cursor.y;
1501 emit selectionChanged(); 1501 emit selectionChanged();
1502} 1502}
1503 1503
1504void KateDocument::selectLength(PointStruc &cursor, int length, int flags) { 1504void KateDocument::selectLength(PointStruc &cursor, int length, int flags) {
1505 int start, end; 1505 int start, end;
1506 1506
1507 TextLine::Ptr textLine = getTextLine(cursor.y); 1507 TextLine::Ptr textLine = getTextLine(cursor.y);
1508 start = cursor.x; 1508 start = cursor.x;
1509 end = start + length; 1509 end = start + length;
1510 if (end <= start) return; 1510 if (end <= start) return;
1511 if (!(flags & KateView::cfKeepSelection)) deselectAll(); 1511 if (!(flags & KateView::cfKeepSelection)) deselectAll();
1512 1512
1513 textLine->select(true, start, end); 1513 textLine->select(true, start, end);
1514 1514
1515 anchor.x = start; 1515 anchor.x = start;
1516 select.x = end; 1516 select.x = end;
1517 anchor.y = select.y = cursor.y; 1517 anchor.y = select.y = cursor.y;
1518 tagLines(cursor.y, cursor.y); 1518 tagLines(cursor.y, cursor.y);
1519 if (cursor.y < selectStart) selectStart = cursor.y; 1519 if (cursor.y < selectStart) selectStart = cursor.y;
1520 if (cursor.y > selectEnd) selectEnd = cursor.y; 1520 if (cursor.y > selectEnd) selectEnd = cursor.y;
1521 emit selectionChanged(); 1521 emit selectionChanged();
1522} 1522}
1523 1523
1524void KateDocument::doIndent(VConfig &c, int change) { 1524void KateDocument::doIndent(VConfig &c, int change) {
1525 1525
1526 c.cursor.x = 0; 1526 c.cursor.x = 0;
1527 1527
1528 recordStart(c, (change < 0) ? KateActionGroup::ugUnindent 1528 recordStart(c, (change < 0) ? KateActionGroup::ugUnindent
1529 : KateActionGroup::ugIndent); 1529 : KateActionGroup::ugIndent);
1530 1530
1531 if (selectEnd < selectStart) { 1531 if (selectEnd < selectStart) {
1532 // single line 1532 // single line
1533 optimizeLeadingSpace(c.cursor.y, c.flags, change); 1533 optimizeLeadingSpace(c.cursor.y, c.flags, change);
1534 } else { 1534 } else {
1535 // entire selection 1535 // entire selection
1536 TextLine::Ptr textLine; 1536 TextLine::Ptr textLine;
1537 int line, z; 1537 int line, z;
1538 QChar ch; 1538 QChar ch;
1539 1539
1540 if (c.flags & KateView::cfKeepIndentProfile && change < 0) { 1540 if (c.flags & KateView::cfKeepIndentProfile && change < 0) {
1541 // unindent so that the existing indent profile doesn´t get screwed 1541 // unindent so that the existing indent profile doesn´t get screwed
1542 // if any line we may unindent is already full left, don't do anything 1542 // if any line we may unindent is already full left, don't do anything
1543 for (line = selectStart; line <= selectEnd; line++) { 1543 for (line = selectStart; line <= selectEnd; line++) {
1544 textLine = getTextLine(line); 1544 textLine = getTextLine(line);
1545 if (textLine->isSelected() || textLine->numSelected()) { 1545 if (textLine->isSelected() || textLine->numSelected()) {
1546 for (z = 0; z < tabChars; z++) { 1546 for (z = 0; z < tabChars; z++) {
1547 ch = textLine->getChar(z); 1547 ch = textLine->getChar(z);
1548 if (ch == '\t') break; 1548 if (ch == '\t') break;
1549 if (ch != ' ') { 1549 if (ch != ' ') {
1550 change = 0; 1550 change = 0;
1551 goto jumpOut; 1551 goto jumpOut;
1552 } 1552 }
1553 } 1553 }
1554 } 1554 }
1555 } 1555 }
1556 jumpOut:; 1556 jumpOut:;
1557 } 1557 }
1558 1558
1559 for (line = selectStart; line <= selectEnd; line++) { 1559 for (line = selectStart; line <= selectEnd; line++) {
1560 textLine = getTextLine(line); 1560 textLine = getTextLine(line);
1561 if (textLine->isSelected() || textLine->numSelected()) { 1561 if (textLine->isSelected() || textLine->numSelected()) {
1562 optimizeLeadingSpace(line, c.flags, change); 1562 optimizeLeadingSpace(line, c.flags, change);
1563 } 1563 }
1564 } 1564 }
1565 } 1565 }
1566 // recordEnd now removes empty undo records 1566 // recordEnd now removes empty undo records
1567 recordEnd(c.view, c.cursor, c.flags | KateView::cfPersistent); 1567 recordEnd(c.view, c.cursor, c.flags | KateView::cfPersistent);
1568} 1568}
1569 1569
1570/* 1570/*
1571 Optimize the leading whitespace for a single line. 1571 Optimize the leading whitespace for a single line.
1572 If change is > 0, it adds indentation units (tabChars) 1572 If change is > 0, it adds indentation units (tabChars)
1573 if change is == 0, it only optimizes 1573 if change is == 0, it only optimizes
1574 If change is < 0, it removes indentation units 1574 If change is < 0, it removes indentation units
1575 This will be used to indent, unindent, and optimal-fill a line. 1575 This will be used to indent, unindent, and optimal-fill a line.
1576 If excess space is removed depends on the flag cfKeepExtraSpaces 1576 If excess space is removed depends on the flag cfKeepExtraSpaces
1577 which has to be set by the user 1577 which has to be set by the user
1578*/ 1578*/
1579void KateDocument::optimizeLeadingSpace(int line, int flags, int change) { 1579void KateDocument::optimizeLeadingSpace(int line, int flags, int change) {
1580 int len; 1580 int len;
1581 int chars, space, okLen; 1581 int chars, space, okLen;
1582 QChar ch; 1582 QChar ch;
1583 int extra; 1583 int extra;
1584 QString s; 1584 QString s;
1585 PointStruc cursor; 1585 PointStruc cursor;
1586 1586
1587 TextLine::Ptr textLine = getTextLine(line); 1587 TextLine::Ptr textLine = getTextLine(line);
1588 len = textLine->length(); 1588 len = textLine->length();
1589 space = 0; // length of space at the beginning of the textline 1589 space = 0; // length of space at the beginning of the textline
1590 okLen = 0; // length of space which does not have to be replaced 1590 okLen = 0; // length of space which does not have to be replaced
1591 for (chars = 0; chars < len; chars++) { 1591 for (chars = 0; chars < len; chars++) {
1592 ch = textLine->getChar(chars); 1592 ch = textLine->getChar(chars);
1593 if (ch == ' ') { 1593 if (ch == ' ') {
1594 space++; 1594 space++;
1595 if (flags & KateView::cfSpaceIndent && okLen == chars) okLen++; 1595 if (flags & KateView::cfSpaceIndent && okLen == chars) okLen++;
1596 } else if (ch == '\t') { 1596 } else if (ch == '\t') {
1597 space += tabChars - space % tabChars; 1597 space += tabChars - space % tabChars;
1598 if (!(flags & KateView::cfSpaceIndent) && okLen == chars) okLen++; 1598 if (!(flags & KateView::cfSpaceIndent) && okLen == chars) okLen++;
1599 } else break; 1599 } else break;
1600 } 1600 }
1601 1601
1602 space += change*tabChars; // modify space width 1602 space += change*tabChars; // modify space width
1603 // if line contains only spaces it will be cleared 1603 // if line contains only spaces it will be cleared
1604 if (space < 0 || chars == len) space = 0; 1604 if (space < 0 || chars == len) space = 0;
1605 1605
1606 extra = space % tabChars; // extra spaces which don´t fit the indentation pattern 1606 extra = space % tabChars; // extra spaces which don´t fit the indentation pattern
1607 if (flags & KateView::cfKeepExtraSpaces) chars -= extra; 1607 if (flags & KateView::cfKeepExtraSpaces) chars -= extra;
1608 1608
1609 if (flags & KateView::cfSpaceIndent) { 1609 if (flags & KateView::cfSpaceIndent) {
1610 space -= extra; 1610 space -= extra;
1611 ch = ' '; 1611 ch = ' ';
1612 } else { 1612 } else {
1613 space /= tabChars; 1613 space /= tabChars;
1614 ch = '\t'; 1614 ch = '\t';
1615 } 1615 }
1616 1616
1617 // don´t replace chars which are already ok 1617 // don´t replace chars which are already ok
1618 cursor.x = QMIN(okLen, QMIN(chars, space)); 1618 cursor.x = QMIN(okLen, QMIN(chars, space));
1619 chars -= cursor.x; 1619 chars -= cursor.x;
1620 space -= cursor.x; 1620 space -= cursor.x;
1621 if (chars == 0 && space == 0) return; //nothing to do 1621 if (chars == 0 && space == 0) return; //nothing to do
1622 1622
1623 s.fill(ch, space); 1623 s.fill(ch, space);
1624 1624
1625//printf("chars %d insert %d cursor.x %d\n", chars, insert, cursor.x); 1625//printf("chars %d insert %d cursor.x %d\n", chars, insert, cursor.x);
1626 cursor.y = line; 1626 cursor.y = line;
1627 recordReplace(cursor, chars, s); 1627 recordReplace(cursor, chars, s);
1628} 1628}
1629 1629
1630void KateDocument::doComment(VConfig &c, int change) 1630void KateDocument::doComment(VConfig &c, int change)
1631{ 1631{
1632 c.flags |=KateView:: cfPersistent; 1632 c.flags |=KateView:: cfPersistent;
1633 1633
1634 recordStart(c, (change < 0) ? KateActionGroup::ugUncomment 1634 recordStart(c, (change < 0) ? KateActionGroup::ugUncomment
1635 : KateActionGroup::ugComment); 1635 : KateActionGroup::ugComment);
1636 1636
1637 QString startComment = m_highlight->getCommentStart(); 1637 QString startComment = m_highlight->getCommentStart();
1638 QString startLineComment = m_highlight->getCommentSingleLineStart(); 1638 QString startLineComment = m_highlight->getCommentSingleLineStart();
1639 QString endComment = m_highlight->getCommentEnd(); 1639 QString endComment = m_highlight->getCommentEnd();
1640 1640
1641 int startCommentLen = startComment.length(); 1641 int startCommentLen = startComment.length();
1642 int startLineCommentLen = startLineComment.length(); 1642 int startLineCommentLen = startLineComment.length();
1643 int endCommentLen = endComment.length(); 1643 int endCommentLen = endComment.length();
1644 1644
1645 if (change > 0) 1645 if (change > 0)
1646 { 1646 {
1647 if ( !hasMarkedText() ) 1647 if ( !hasMarkedText() )
1648 { 1648 {
1649 if (startLineComment != "") 1649 if (startLineComment != "")
1650 { 1650 {
1651 // Add a start comment mark 1651 // Add a start comment mark
1652 c.cursor.x = 0; 1652 c.cursor.x = 0;
1653 recordReplace(c.cursor, 0, startLineComment); 1653 recordReplace(c.cursor, 0, startLineComment);
1654 } 1654 }
1655 else if ((startComment != "") && (endComment != "")) 1655 else if ((startComment != "") && (endComment != ""))
1656 { 1656 {
1657 // Add a start comment mark 1657 // Add a start comment mark
1658 c.cursor.x = 0; 1658 c.cursor.x = 0;
1659 recordReplace(c.cursor, 0, startComment); 1659 recordReplace(c.cursor, 0, startComment);
1660 1660
1661 // Add an end comment mark 1661 // Add an end comment mark
1662 TextLine* textline = getTextLine(c.cursor.y); 1662 TextLine* textline = getTextLine(c.cursor.y);
1663 c.cursor.x = textline->length(); 1663 c.cursor.x = textline->length();
1664 recordReplace(c.cursor, 0, endComment); 1664 recordReplace(c.cursor, 0, endComment);
1665 c.cursor.x = 0; 1665 c.cursor.x = 0;
1666 } 1666 }
1667 } 1667 }
1668 else if ((startComment != "") && (endComment != "")) 1668 else if ((startComment != "") && (endComment != ""))
1669 { 1669 {
1670 QString marked (c.view->markedText ()); 1670 QString marked (c.view->markedText ());
1671 int preDeleteLine = -1, preDeleteCol = -1; 1671 int preDeleteLine = -1, preDeleteCol = -1;
1672 c.view->getCursorPosition (&preDeleteLine, &preDeleteCol); 1672 c.view->getCursorPosition (&preDeleteLine, &preDeleteCol);
1673 1673
1674 if (marked.length() > 0) 1674 if (marked.length() > 0)
1675 c.view->keyDelete (); 1675 c.view->keyDelete ();
1676 1676
1677 int line = -1, col = -1; 1677 int line = -1, col = -1;
1678 c.view->getCursorPosition (&line, &col); 1678 c.view->getCursorPosition (&line, &col);
1679 1679
1680 c.view->insertText (startComment + marked + endComment); 1680 c.view->insertText (startComment + marked + endComment);
1681 } 1681 }
1682 } 1682 }
1683 else 1683 else
1684 { 1684 {
1685 if ( !hasMarkedText() ) 1685 if ( !hasMarkedText() )
1686 { 1686 {
1687 TextLine* textline = getTextLine(c.cursor.y); 1687 TextLine* textline = getTextLine(c.cursor.y);
1688 1688
1689 if(textline->startingWith(startLineComment)) 1689 if(textline->startingWith(startLineComment))
1690 { 1690 {
1691 // Remove start comment mark 1691 // Remove start comment mark
1692 c.cursor.x = 0; 1692 c.cursor.x = 0;
1693 recordReplace(c.cursor, startLineCommentLen, ""); 1693 recordReplace(c.cursor, startLineCommentLen, "");
1694 } 1694 }
1695 else if (textline->startingWith(startComment) && textline->endingWith(endComment)) 1695 else if (textline->startingWith(startComment) && textline->endingWith(endComment))
1696 { 1696 {
1697 // Remove start comment mark 1697 // Remove start comment mark
1698 c.cursor.x = 0; 1698 c.cursor.x = 0;
1699 recordReplace(c.cursor, startCommentLen, ""); 1699 recordReplace(c.cursor, startCommentLen, "");
1700 1700
1701 // Remove end comment mark 1701 // Remove end comment mark
1702 if(endComment != "") 1702 if(endComment != "")
1703 { 1703 {
1704 c.cursor.x = textline->length() - endCommentLen; 1704 c.cursor.x = textline->length() - endCommentLen;
1705 recordReplace(c.cursor, endCommentLen, ""); 1705 recordReplace(c.cursor, endCommentLen, "");
1706 c.cursor.x = 0; 1706 c.cursor.x = 0;
1707 } 1707 }
1708 } 1708 }
1709 } 1709 }
1710 else 1710 else
1711 { 1711 {
1712 QString marked (c.view->markedText ()); 1712 QString marked (c.view->markedText ());
1713 int preDeleteLine = -1, preDeleteCol = -1; 1713 int preDeleteLine = -1, preDeleteCol = -1;
1714 c.view->getCursorPosition (&preDeleteLine, &preDeleteCol); 1714 c.view->getCursorPosition (&preDeleteLine, &preDeleteCol);
1715 1715
1716 int start = marked.find (startComment); 1716 int start = marked.find (startComment);
1717 int end = marked.findRev (endComment); 1717 int end = marked.findRev (endComment);
1718 1718
1719 if ((start > -1) && (end > -1)) 1719 if ((start > -1) && (end > -1))
1720 { 1720 {
1721 marked.remove (start, startCommentLen); 1721 marked.remove (start, startCommentLen);
1722 marked.remove (end-startCommentLen, endCommentLen); 1722 marked.remove (end-startCommentLen, endCommentLen);
1723 1723
1724 c.view->keyDelete (); 1724 c.view->keyDelete ();
1725 1725
1726 int line = -1, col = -1; 1726 int line = -1, col = -1;
1727 c.view->getCursorPosition (&line, &col); 1727 c.view->getCursorPosition (&line, &col);
1728 c.view->insertText (marked); 1728 c.view->insertText (marked);
1729 } 1729 }
1730 } 1730 }
1731 } 1731 }
1732 1732
1733 recordEnd(c.view, c.cursor, c.flags | KateView::cfPersistent); 1733 recordEnd(c.view, c.cursor, c.flags | KateView::cfPersistent);
1734} 1734}
1735 1735
1736 1736
1737QString KateDocument::text() const 1737QString KateDocument::text() const
1738{ 1738{
1739 QString s; 1739 QString s;
1740 1740
1741 for (int i=0; i < buffer->count(); i++) 1741 for (int i=0; i < buffer->count(); i++)
1742 { 1742 {
1743 TextLine::Ptr textLine = buffer->line(i); 1743 TextLine::Ptr textLine = buffer->line(i);
1744 s.insert(s.length(), textLine->getText(), textLine->length()); 1744 s.insert(s.length(), textLine->getText(), textLine->length());
1745 if ( (i < (buffer->count()-1)) ) 1745 if ( (i < (buffer->count()-1)) )
1746 s.append('\n'); 1746 s.append('\n');
1747 } 1747 }
1748 1748
1749 return s; 1749 return s;
1750} 1750}
1751 1751
1752QString KateDocument::getWord(PointStruc &cursor) { 1752QString KateDocument::getWord(PointStruc &cursor) {
1753 int start, end, len; 1753 int start, end, len;
1754 1754
1755 TextLine::Ptr textLine = getTextLine(cursor.y); 1755 TextLine::Ptr textLine = getTextLine(cursor.y);
1756 len = textLine->length(); 1756 len = textLine->length();
1757 start = end = cursor.x; 1757 start = end = cursor.x;
1758 while (start > 0 && m_highlight->isInWord(textLine->getChar(start - 1))) start--; 1758 while (start > 0 && m_highlight->isInWord(textLine->getChar(start - 1))) start--;
1759 while (end < len && m_highlight->isInWord(textLine->getChar(end))) end++; 1759 while (end < len && m_highlight->isInWord(textLine->getChar(end))) end++;
1760 len = end - start; 1760 len = end - start;
1761 return QString(&textLine->getText()[start], len); 1761 return QString(&textLine->getText()[start], len);
1762} 1762}
1763 1763
1764void KateDocument::setText(const QString &s) { 1764void KateDocument::setText(const QString &s) {
1765 int pos; 1765 int pos;
1766 QChar ch; 1766 QChar ch;
1767 1767
1768 clear(); 1768 clear();
1769 1769
1770 int line=1; 1770 int line=1;
1771 1771
1772 TextLine::Ptr textLine = buffer->line(0); 1772 TextLine::Ptr textLine = buffer->line(0);
1773 for (pos = 0; pos <= (int) s.length(); pos++) { 1773 for (pos = 0; pos <= (int) s.length(); pos++) {
1774 ch = s[pos]; 1774 ch = s[pos];
1775 if (ch.isPrint() || ch == '\t') { 1775 if (ch.isPrint() || ch == '\t') {
1776 textLine->append(&ch, 1); 1776 textLine->append(&ch, 1);
1777 } else if (ch == '\n') 1777 } else if (ch == '\n')
1778 { 1778 {
1779 textLine = new TextLine(); 1779 textLine = new TextLine();
1780 buffer->insertLine (line, textLine); 1780 buffer->insertLine (line, textLine);
1781 line++; 1781 line++;
1782 } 1782 }
1783 } 1783 }
1784 updateLines(); 1784 updateLines();
1785} 1785}
1786 1786
1787 1787
1788QString KateDocument::markedText(int flags) { 1788QString KateDocument::markedText(int flags) {
1789 TextLine::Ptr textLine; 1789 TextLine::Ptr textLine;
1790 int len, z, start, end, i; 1790 int len, z, start, end, i;
1791 1791
1792 len = 1; 1792 len = 1;
1793 if (!(flags & KateView::cfVerticalSelect)) { 1793 if (!(flags & KateView::cfVerticalSelect)) {
1794 for (z = selectStart; z <= selectEnd; z++) { 1794 for (z = selectStart; z <= selectEnd; z++) {
1795 textLine = getTextLine(z); 1795 textLine = getTextLine(z);
1796 len += textLine->numSelected(); 1796 len += textLine->numSelected();
1797 if (textLine->isSelected()) len++; 1797 if (textLine->isSelected()) len++;
1798 } 1798 }
1799 QString s; 1799 QString s;
1800 len = 0; 1800 len = 0;
1801 for (z = selectStart; z <= selectEnd; z++) { 1801 for (z = selectStart; z <= selectEnd; z++) {
1802 textLine = getTextLine(z); 1802 textLine = getTextLine(z);
1803 end = 0; 1803 end = 0;
1804 do { 1804 do {
1805 start = textLine->findUnselected(end); 1805 start = textLine->findUnselected(end);
1806 end = textLine->findSelected(start); 1806 end = textLine->findSelected(start);
1807 for (i = start; i < end; i++) { 1807 for (i = start; i < end; i++) {
1808 s[len] = textLine->getChar(i); 1808 s[len] = textLine->getChar(i);
1809 len++; 1809 len++;
1810 } 1810 }
1811 } while (start < end); 1811 } while (start < end);
1812 if (textLine->isSelected()) { 1812 if (textLine->isSelected()) {
1813 s[len] = '\n'; 1813 s[len] = '\n';
1814 len++; 1814 len++;
1815 } 1815 }
1816 } 1816 }
1817// s[len] = '\0'; 1817// s[len] = '\0';
1818 return s; 1818 return s;
1819 } else { 1819 } else {
1820 for (z = selectStart; z <= selectEnd; z++) { 1820 for (z = selectStart; z <= selectEnd; z++) {
1821 textLine = getTextLine(z); 1821 textLine = getTextLine(z);
1822 len += textLine->numSelected() + 1; 1822 len += textLine->numSelected() + 1;
1823 } 1823 }
1824 QString s; 1824 QString s;
1825 len = 0; 1825 len = 0;
1826 for (z = selectStart; z <= selectEnd; z++) { 1826 for (z = selectStart; z <= selectEnd; z++) {
1827 textLine = getTextLine(z); 1827 textLine = getTextLine(z);
1828 end = 0; 1828 end = 0;
1829 do { 1829 do {
1830 start = textLine->findUnselected(end); 1830 start = textLine->findUnselected(end);
1831 end = textLine->findSelected(start); 1831 end = textLine->findSelected(start);
1832 for (i = start; i < end; i++) { 1832 for (i = start; i < end; i++) {
1833 s[len] = textLine->getChar(i); 1833 s[len] = textLine->getChar(i);
1834 len++; 1834 len++;
1835 } 1835 }
1836 } while (start < end); 1836 } while (start < end);
1837 s[len] = '\n'; 1837 s[len] = '\n';
1838 len++; 1838 len++;
1839 } 1839 }
1840// s[len] = '\0'; // the final \0 is not counted in length() 1840// s[len] = '\0'; // the final \0 is not counted in length()
1841 return s; 1841 return s;
1842 } 1842 }
1843} 1843}
1844 1844
1845void KateDocument::delMarkedText(VConfig &c/*, bool undo*/) { 1845void KateDocument::delMarkedText(VConfig &c/*, bool undo*/) {
1846 int end = 0; 1846 int end = 0;
1847 1847
1848 if (selectEnd < selectStart) return; 1848 if (selectEnd < selectStart) return;
1849 1849
1850 // the caller may have already started an undo record for the current action 1850 // the caller may have already started an undo record for the current action
1851// if (undo) 1851// if (undo)
1852 1852
1853 //auto deletion of the marked text occurs not very often and can therefore 1853 //auto deletion of the marked text occurs not very often and can therefore
1854 // be recorded separately 1854 // be recorded separately
1855 recordStart(c, KateActionGroup::ugDelBlock); 1855 recordStart(c, KateActionGroup::ugDelBlock);
1856 1856
1857 for (c.cursor.y = selectEnd; c.cursor.y >= selectStart; c.cursor.y--) { 1857 for (c.cursor.y = selectEnd; c.cursor.y >= selectStart; c.cursor.y--) {
1858 TextLine::Ptr textLine = getTextLine(c.cursor.y); 1858 TextLine::Ptr textLine = getTextLine(c.cursor.y);
1859 1859
1860 c.cursor.x = textLine->length(); 1860 c.cursor.x = textLine->length();
1861 do { 1861 do {
1862 end = textLine->findRevUnselected(c.cursor.x); 1862 end = textLine->findRevUnselected(c.cursor.x);
1863 if (end == 0) break; 1863 if (end == 0) break;
1864 c.cursor.x = textLine->findRevSelected(end); 1864 c.cursor.x = textLine->findRevSelected(end);
1865 recordDelete(c.cursor, end - c.cursor.x); 1865 recordDelete(c.cursor, end - c.cursor.x);
1866 } while (true); 1866 } while (true);
1867 end = c.cursor.x; 1867 end = c.cursor.x;
1868 c.cursor.x = textLine->length(); 1868 c.cursor.x = textLine->length();
1869 if (textLine->isSelected()) recordAction(KateAction::delLine,c.cursor); 1869 if (textLine->isSelected()) recordAction(KateAction::delLine,c.cursor);
1870 } 1870 }
1871 c.cursor.y++; 1871 c.cursor.y++;
1872 /*if (end < c.cursor.x)*/ c.cursor.x = end; 1872 /*if (end < c.cursor.x)*/ c.cursor.x = end;
1873 1873
1874 selectEnd = -1; 1874 selectEnd = -1;
1875 select.x = -1; 1875 select.x = -1;
1876 1876
1877 /*if (undo)*/ recordEnd(c); 1877 /*if (undo)*/ recordEnd(c);
1878} 1878}
1879 1879
1880void KateDocument::tagLineRange(int line, int x1, int x2) { 1880void KateDocument::tagLineRange(int line, int x1, int x2) {
1881 int z; 1881 int z;
1882 1882
1883 for (z = 0; z < (int) views.count(); z++) { 1883 for (z = 0; z < (int) views.count(); z++) {
1884 views.at(z)->tagLines(line, line, x1, x2); 1884 views.at(z)->tagLines(line, line, x1, x2);
1885 } 1885 }
1886} 1886}
1887 1887
1888void KateDocument::tagLines(int start, int end) { 1888void KateDocument::tagLines(int start, int end) {
1889 int z; 1889 int z;
1890 1890
1891 for (z = 0; z < (int) views.count(); z++) { 1891 for (z = 0; z < (int) views.count(); z++) {
1892 views.at(z)->tagLines(start, end, 0, 0xffffff); 1892 views.at(z)->tagLines(start, end, 0, 0xffffff);
1893 } 1893 }
1894} 1894}
1895 1895
1896void KateDocument::tagAll() { 1896void KateDocument::tagAll() {
1897 int z; 1897 int z;
1898 1898
1899 for (z = 0; z < (int) views.count(); z++) { 1899 for (z = 0; z < (int) views.count(); z++) {
1900 views.at(z)->tagAll(); 1900 views.at(z)->tagAll();
1901 } 1901 }
1902} 1902}
1903 1903
1904void KateDocument::updateLines(int startLine, int endLine, int flags, int cursorY) { 1904void KateDocument::updateLines(int startLine, int endLine, int flags, int cursorY) {
1905 TextLine::Ptr textLine; 1905 TextLine::Ptr textLine;
1906 int line, last_line; 1906 int line, last_line;
1907 int ctxNum, endCtx; 1907 int ctxNum, endCtx;
1908// kdDebug(13020)<<"******************KateDocument::updateLines Checkpoint 1"<<endl; 1908// kdDebug(13020)<<"******************KateDocument::updateLines Checkpoint 1"<<endl;
1909 if (buffer->line(startLine)==0) {kdDebug(13020)<<"********************No buffer for line " << startLine << " found**************"<<endl; return;}; 1909 if (buffer->line(startLine)==0) {kdDebug(13020)<<"********************No buffer for line " << startLine << " found**************"<<endl; return;};
1910// kdDebug(13020)<<"KateDocument::updateLines Checkpoint 2"<<endl; 1910// kdDebug(13020)<<"KateDocument::updateLines Checkpoint 2"<<endl;
1911 last_line = lastLine(); 1911 last_line = lastLine();
1912// if (endLine >= last_line) endLine = last_line; 1912// if (endLine >= last_line) endLine = last_line;
1913 1913
1914 line = startLine; 1914 line = startLine;
1915 ctxNum = 0; 1915 ctxNum = 0;
1916 if (line > 0) ctxNum = getTextLine(line - 1)->getContext(); 1916 if (line > 0) ctxNum = getTextLine(line - 1)->getContext();
1917 do { 1917 do {
1918// kdDebug(13020)<<QString("**************Working on line: %1").arg(line)<<endl; 1918// kdDebug(13020)<<QString("**************Working on line: %1").arg(line)<<endl;
1919 textLine = getTextLine(line); 1919 textLine = getTextLine(line);
1920 if (textLine==0) kdDebug(13020)<<"****updateLines()>> error textLine==0"<<endl; 1920 if (textLine==0) kdDebug(13020)<<"****updateLines()>> error textLine==0"<<endl;
1921 if (line <= endLine && line != cursorY) { 1921 if (line <= endLine && line != cursorY) {
1922 if (flags & KateView::cfRemoveSpaces) textLine->removeSpaces(); 1922 if (flags & KateView::cfRemoveSpaces) textLine->removeSpaces();
1923 updateMaxLength(textLine); 1923 updateMaxLength(textLine);
1924 } 1924 }
1925 endCtx = textLine->getContext(); 1925 endCtx = textLine->getContext();
1926// qDebug("DOHIGHLIGHT"); 1926// qDebug("DOHIGHLIGHT");
1927 1927
1928 ctxNum = m_highlight->doHighlight(ctxNum,textLine); 1928 ctxNum = m_highlight->doHighlight(ctxNum,textLine);
1929 textLine->setContext(ctxNum); 1929 textLine->setContext(ctxNum);
1930 line++; 1930 line++;
1931 } while ((buffer->line(line)!=0) && (line <= endLine || endCtx != ctxNum)); 1931 } while ((buffer->line(line)!=0) && (line <= endLine || endCtx != ctxNum));
1932// kdDebug(13020)<<"updateLines :: while loop left"<<endl; 1932// kdDebug(13020)<<"updateLines :: while loop left"<<endl;
1933 tagLines(startLine, line - 1); 1933 tagLines(startLine, line - 1);
1934} 1934}
1935 1935
1936 1936
1937void KateDocument::updateMaxLength(TextLine::Ptr &textLine) { 1937void KateDocument::updateMaxLength(TextLine::Ptr &textLine) {
1938 int len; 1938 int len;
1939 1939
1940 len = textWidth(textLine,textLine->length()); 1940 len = textWidth(textLine,textLine->length());
1941 1941
1942 if (len > maxLength) { 1942 if (len > maxLength) {
1943 longestLine = textLine; 1943 longestLine = textLine;
1944 maxLength = len; 1944 maxLength = len;
1945 newDocGeometry = true; 1945 newDocGeometry = true;
1946 } else { 1946 } else {
1947 if (!longestLine || (textLine == longestLine && len <= maxLength*3/4)) { 1947 if (!longestLine || (textLine == longestLine && len <= maxLength*3/4)) {
1948 maxLength = -1; 1948 maxLength = -1;
1949 for (int i = 0; i < numLines();i++) { 1949 for (int i = 0; i < numLines();i++) {
1950 textLine = getTextLine(i); 1950 textLine = getTextLine(i);
1951 len = textWidth(textLine,textLine->length()); 1951 len = textWidth(textLine,textLine->length());
1952 if (len > maxLength) { 1952 if (len > maxLength) {
1953 maxLength = len; 1953 maxLength = len;
1954 longestLine = textLine; 1954 longestLine = textLine;
1955 } 1955 }
1956 } 1956 }
1957 newDocGeometry = true; 1957 newDocGeometry = true;
1958 } 1958 }
1959 } 1959 }
1960} 1960}
1961 1961
1962void KateDocument::slotBufferChanged() { 1962void KateDocument::slotBufferChanged() {
1963 newDocGeometry = true; 1963 newDocGeometry = true;
1964 //updateLines();//JW 1964 //updateLines();//JW
1965 updateViews(); 1965 updateViews();
1966} 1966}
1967 1967
1968void KateDocument::slotBufferHighlight(long start,long stop) { 1968void KateDocument::slotBufferHighlight(long start,long stop) {
1969 kdDebug(13020)<<"KateDocument::slotBufferHighlight"<<QString("%1-%2").arg(start).arg(stop)<<endl; 1969 kdDebug(13020)<<"KateDocument::slotBufferHighlight"<<QString("%1-%2").arg(start).arg(stop)<<endl;
1970 updateLines(start,stop); 1970 updateLines(start,stop);
1971// buffer->startLoadTimer(); 1971// buffer->startLoadTimer();
1972} 1972}
1973 1973
1974void KateDocument::updateViews(KateView *exclude) { 1974void KateDocument::updateViews(KateView *exclude) {
1975 KateView *view; 1975 KateView *view;
1976 int flags; 1976 int flags;
1977 bool markState = hasMarkedText(); 1977 bool markState = hasMarkedText();
1978 1978
1979 flags = (newDocGeometry) ? KateView::ufDocGeometry : 0; 1979 flags = (newDocGeometry) ? KateView::ufDocGeometry : 0;
1980 for (view = views.first(); view != 0L; view = views.next() ) { 1980 for (view = views.first(); view != 0L; view = views.next() ) {
1981 if (view != exclude) view->updateView(flags); 1981 if (view != exclude) view->updateView(flags);
1982 1982
1983 // notify every view about the changed mark state.... 1983 // notify every view about the changed mark state....
1984 if (oldMarkState != markState) emit view->newMarkStatus(); 1984 if (oldMarkState != markState) emit view->newMarkStatus();
1985 } 1985 }
1986 oldMarkState = markState; 1986 oldMarkState = markState;
1987 newDocGeometry = false; 1987 newDocGeometry = false;
1988} 1988}
1989 1989
1990QColor &KateDocument::cursorCol(int x, int y) { 1990QColor &KateDocument::cursorCol(int x, int y) {
1991 int attr; 1991 int attr;
1992 Attribute *a; 1992 Attribute *a;
1993 1993
1994 TextLine::Ptr textLine = getTextLine(y); 1994 TextLine::Ptr textLine = getTextLine(y);
1995 attr = textLine->getRawAttr(x); 1995 attr = textLine->getRawAttr(x);
1996 a = &m_attribs[attr & taAttrMask]; 1996 a = &m_attribs[attr & taAttrMask];
1997 if (attr & taSelected) return a->selCol; else return a->col; 1997 if (attr & taSelected) return a->selCol; else return a->col;
1998} 1998}
1999 1999
2000void KateDocument::paintTextLine(QPainter &paint, int line, int xStart, int xEnd, bool showTabs) 2000void KateDocument::paintTextLine(QPainter &paint, int line, int xStart, int xEnd, bool showTabs)
2001{ 2001{
2002 paintTextLine (paint, line, 0, xStart, xEnd, showTabs); 2002 paintTextLine (paint, line, 0, xStart, xEnd, showTabs);
2003} 2003}
2004 2004
2005void KateDocument::paintTextLine(QPainter &paint, int line, int y, int xStart, int xEnd, bool showTabs) 2005void KateDocument::paintTextLine(QPainter &paint, int line, int y, int xStart, int xEnd, bool showTabs)
2006{ 2006{
2007 TextLine::Ptr textLine; 2007 TextLine::Ptr textLine;
2008 int len; 2008 int len;
2009 const QChar *s; 2009 const QChar *s;
2010 int z, x; 2010 int z, x;
2011 QChar ch; 2011 QChar ch;
2012 Attribute *a = 0L; 2012 Attribute *a = 0L;
2013 int attr, nextAttr; 2013 int attr, nextAttr;
2014 int xs; 2014 int xs;
2015 int xc, zc; 2015 int xc, zc;
2016 2016
2017 if (line > lastLine()) { 2017 if (line > lastLine()) {
2018 paint.fillRect(0, y, xEnd - xStart,fontHeight, colors[0]); 2018 paint.fillRect(0, y, xEnd - xStart,fontHeight, colors[0]);
2019 return; 2019 return;
2020 } 2020 }
2021 2021
2022 textLine = getTextLine(line); 2022 textLine = getTextLine(line);
2023 len = textLine->length(); 2023 len = textLine->length();
2024 s = textLine->getText(); 2024 s = textLine->getText();
2025 2025
2026 // skip to first visible character 2026 // skip to first visible character
2027 x = 0; 2027 x = 0;
2028 z = 0; 2028 z = 0;
2029 do { 2029 do {
2030 xc = x; 2030 xc = x;
2031 zc = z; 2031 zc = z;
2032 if (z == len) break; 2032 if (z == len) break;
2033 ch = s[z];//textLine->getChar(z); 2033 ch = s[z];//textLine->getChar(z);
2034 if (ch == '\t') { 2034 if (ch == '\t') {
2035 x += m_tabWidth - (x % m_tabWidth); 2035 x += m_tabWidth - (x % m_tabWidth);
2036 } else { 2036 } else {
2037 a = &m_attribs[textLine->getAttr(z)]; 2037 a = &m_attribs[textLine->getAttr(z)];
2038 2038
2039 if (a->bold && a->italic) 2039 if (a->bold && a->italic)
2040 x += myFontMetricsBI.width(ch); 2040 x += myFontMetricsBI.width(ch);
2041 else if (a->bold) 2041 else if (a->bold)
2042 x += myFontMetricsBold.width(ch); 2042 x += myFontMetricsBold.width(ch);
2043 else if (a->italic) 2043 else if (a->italic)
2044 x += myFontMetricsItalic.width(ch); 2044 x += myFontMetricsItalic.width(ch);
2045 else 2045 else
2046 x += myFontMetrics.width(ch); 2046 x += myFontMetrics.width(ch);
2047 } 2047 }
2048 z++; 2048 z++;
2049 } while (x <= xStart); 2049 } while (x <= xStart);
2050 2050
2051 // draw background 2051 // draw background
2052 xs = xStart; 2052 xs = xStart;
2053 attr = textLine->getRawAttr(zc); 2053 attr = textLine->getRawAttr(zc);
2054 while (x < xEnd) 2054 while (x < xEnd)
2055 { 2055 {
2056 nextAttr = textLine->getRawAttr(z); 2056 nextAttr = textLine->getRawAttr(z);
2057 if ((nextAttr ^ attr) & taSelected) 2057 if ((nextAttr ^ attr) & taSelected)
2058 { 2058 {
2059 if (attr & taSelected) 2059 if (attr & taSelected)
2060 paint.fillRect(xs - xStart, y, x - xs, fontHeight, colors[1]); 2060 paint.fillRect(xs - xStart, y, x - xs, fontHeight, colors[1]);
2061 else 2061 else
2062 paint.fillRect(xs - xStart, y, x - xs, fontHeight, colors[0]); 2062 paint.fillRect(xs - xStart, y, x - xs, fontHeight, colors[0]);
2063 2063
2064 xs = x; 2064 xs = x;
2065 attr = nextAttr; 2065 attr = nextAttr;
2066 } 2066 }
2067 2067
2068 if (z == len) break; 2068 if (z == len) break;
2069 2069
2070 ch = s[z];//textLine->getChar(z); 2070 ch = s[z];//textLine->getChar(z);
2071 2071
2072 if (ch == '\t') 2072 if (ch == '\t')
2073 x += m_tabWidth - (x % m_tabWidth); 2073 x += m_tabWidth - (x % m_tabWidth);
2074 else 2074 else
2075 { 2075 {
2076 a = &m_attribs[textLine->getAttr(z)]; 2076 a = &m_attribs[textLine->getAttr(z)];
2077 2077
2078 if (a->bold && a->italic) 2078 if (a->bold && a->italic)
2079 x += myFontMetricsBI.width(ch); 2079 x += myFontMetricsBI.width(ch);
2080 else if (a->bold) 2080 else if (a->bold)
2081 x += myFontMetricsBold.width(ch); 2081 x += myFontMetricsBold.width(ch);
2082 else if (a->italic) 2082 else if (a->italic)
2083 x += myFontMetricsItalic.width(ch); 2083 x += myFontMetricsItalic.width(ch);
2084 else 2084 else
2085 x += myFontMetrics.width(ch); 2085 x += myFontMetrics.width(ch);
2086 } 2086 }
2087 z++; 2087 z++;
2088 } 2088 }
2089 2089
2090 if (attr & taSelected) 2090 if (attr & taSelected)
2091 paint.fillRect(xs - xStart, y, xEnd - xs, fontHeight, colors[1]); 2091 paint.fillRect(xs - xStart, y, xEnd - xs, fontHeight, colors[1]);
2092 else 2092 else
2093 paint.fillRect(xs - xStart, y, xEnd - xs, fontHeight, colors[0]); 2093 paint.fillRect(xs - xStart, y, xEnd - xs, fontHeight, colors[0]);
2094 2094
2095 len = z; //reduce length to visible length 2095 len = z; //reduce length to visible length
2096 2096
2097 // draw text 2097 // draw text
2098 x = xc; 2098 x = xc;
2099 z = zc; 2099 z = zc;
2100 y += fontAscent;// -1; 2100 y += fontAscent;// -1;
2101 attr = -1; 2101 attr = -1;
2102 while (z < len) { 2102 while (z < len) {
2103 ch = s[z];//textLine->getChar(z); 2103 ch = s[z];//textLine->getChar(z);
2104 if (ch == '\t') { 2104 if (ch == '\t') {
2105 if (z > zc) { 2105 if (z > zc) {
2106 //this should cause no copy at all 2106 //this should cause no copy at all
2107 QConstString str((QChar *) &s[zc], z - zc /*+1*/); 2107 QConstString str((QChar *) &s[zc], z - zc /*+1*/);
2108 QString s = str.string(); 2108 QString s = str.string();
2109 paint.drawText(x - xStart, y, s); 2109 paint.drawText(x - xStart, y, s);
2110 2110
2111 if (a->bold && a->italic) 2111 if (a->bold && a->italic)
2112 x += myFontMetricsBI.width(s); 2112 x += myFontMetricsBI.width(s);
2113 else if (a->bold) 2113 else if (a->bold)
2114 x += myFontMetricsBold.width(s); 2114 x += myFontMetricsBold.width(s);
2115 else if (a->italic) 2115 else if (a->italic)
2116 x += myFontMetricsItalic.width(s); 2116 x += myFontMetricsItalic.width(s);
2117 else 2117 else
2118 x += myFontMetrics.width(s); 2118 x += myFontMetrics.width(s);
2119 } 2119 }
2120 zc = z +1; 2120 zc = z +1;
2121 2121
2122 if (showTabs) { 2122 if (showTabs) {
2123 nextAttr = textLine->getRawAttr(z); 2123 nextAttr = textLine->getRawAttr(z);
2124 if (nextAttr != attr) { 2124 if (nextAttr != attr) {
2125 attr = nextAttr; 2125 attr = nextAttr;
2126 a = &m_attribs[attr & taAttrMask]; 2126 a = &m_attribs[attr & taAttrMask];
2127 2127
2128 if (attr & taSelected) paint.setPen(a->selCol); 2128 if (attr & taSelected) paint.setPen(a->selCol);
2129 else paint.setPen(a->col); 2129 else paint.setPen(a->col);
2130 2130
2131 if (a->bold && a->italic) 2131 if (a->bold && a->italic)
2132 paint.setFont(myFontBI); 2132 paint.setFont(myFontBI);
2133 else if (a->bold) 2133 else if (a->bold)
2134 paint.setFont(myFontBold); 2134 paint.setFont(myFontBold);
2135 else if (a->italic) 2135 else if (a->italic)
2136 paint.setFont(myFontItalic); 2136 paint.setFont(myFontItalic);
2137 else 2137 else
2138 paint.setFont(myFont); 2138 paint.setFont(myFont);
2139 } 2139 }
2140 2140
2141// paint.drawLine(x - xStart, y -2, x - xStart, y); 2141// paint.drawLine(x - xStart, y -2, x - xStart, y);
2142// paint.drawLine(x - xStart, y, x - xStart + 2, y); 2142// paint.drawLine(x - xStart, y, x - xStart + 2, y);
2143 paint.drawPoint(x - xStart, y); 2143 paint.drawPoint(x - xStart, y);
2144 paint.drawPoint(x - xStart +1, y); 2144 paint.drawPoint(x - xStart +1, y);
2145 paint.drawPoint(x - xStart, y -1); 2145 paint.drawPoint(x - xStart, y -1);
2146 } 2146 }
2147 x += m_tabWidth - (x % m_tabWidth); 2147 x += m_tabWidth - (x % m_tabWidth);
2148 } else { 2148 } else {
2149 nextAttr = textLine->getRawAttr(z); 2149 nextAttr = textLine->getRawAttr(z);
2150 if (nextAttr != attr) { 2150 if (nextAttr != attr) {
2151 if (z > zc) { 2151 if (z > zc) {
2152 QConstString str((QChar *) &s[zc], z - zc /*+1*/); 2152 QConstString str((QChar *) &s[zc], z - zc /*+1*/);
2153 QString s = str.string(); 2153 QString s = str.string();
2154 paint.drawText(x - xStart, y, s); 2154 paint.drawText(x - xStart, y, s);
2155 2155
2156 if (a->bold && a->italic) 2156 if (a->bold && a->italic)
2157 x += myFontMetricsBI.width(s); 2157 x += myFontMetricsBI.width(s);
2158 else if (a->bold) 2158 else if (a->bold)
2159 x += myFontMetricsBold.width(s); 2159 x += myFontMetricsBold.width(s);
2160 else if (a->italic) 2160 else if (a->italic)
2161 x += myFontMetricsItalic.width(s); 2161 x += myFontMetricsItalic.width(s);
2162 else 2162 else
2163 x += myFontMetrics.width(s); 2163 x += myFontMetrics.width(s);
2164 zc = z; 2164 zc = z;
2165 } 2165 }
2166 attr = nextAttr; 2166 attr = nextAttr;
2167 a = &m_attribs[attr & taAttrMask]; 2167 a = &m_attribs[attr & taAttrMask];
2168 2168
2169 if (attr & taSelected) paint.setPen(a->selCol); 2169 if (attr & taSelected) paint.setPen(a->selCol);
2170 else paint.setPen(a->col); 2170 else paint.setPen(a->col);
2171 2171
2172 if (a->bold && a->italic) 2172 if (a->bold && a->italic)
2173 paint.setFont(myFontBI); 2173 paint.setFont(myFontBI);
2174 else if (a->bold) 2174 else if (a->bold)
2175 paint.setFont(myFontBold); 2175 paint.setFont(myFontBold);
2176 else if (a->italic) 2176 else if (a->italic)
2177 paint.setFont(myFontItalic); 2177 paint.setFont(myFontItalic);
2178 else 2178 else
2179 paint.setFont(myFont); 2179 paint.setFont(myFont);
2180 } 2180 }
2181 } 2181 }
2182 z++; 2182 z++;
2183 } 2183 }
2184 if (z > zc) { 2184 if (z > zc) {
2185 QConstString str((QChar *) &s[zc], z - zc /*+1*/); 2185 QConstString str((QChar *) &s[zc], z - zc /*+1*/);
2186 paint.drawText(x - xStart, y, str.string()); 2186 paint.drawText(x - xStart, y, str.string());
2187 } 2187 }
2188} 2188}
2189 2189
2190// Applies the search context, and returns whether a match was found. If one is, 2190// Applies the search context, and returns whether a match was found. If one is,
2191// the length of the string matched is also returned. 2191// the length of the string matched is also returned.
2192bool KateDocument::doSearch(SConfig &sc, const QString &searchFor) { 2192bool KateDocument::doSearch(SConfig &sc, const QString &searchFor) {
2193 int line, col; 2193 int line, col;
2194 int searchEnd; 2194 int searchEnd;
2195 int bufLen, tlen; 2195 int bufLen, tlen;
2196 QChar *t; 2196 QChar *t;
2197 TextLine::Ptr textLine; 2197 TextLine::Ptr textLine;
2198 int pos, newPos; 2198 int pos, newPos;
2199 2199
2200 if (searchFor.isEmpty()) return false; 2200 if (searchFor.isEmpty()) return false;
2201 2201
2202 bufLen = 0; 2202 bufLen = 0;
2203 t = 0L; 2203 t = 0L;
2204 2204
2205 line = sc.cursor.y; 2205 line = sc.cursor.y;
2206 col = sc.cursor.x; 2206 col = sc.cursor.x;
2207 if (!(sc.flags & KateView::sfBackward)) { 2207 if (!(sc.flags & KateView::sfBackward)) {
2208 //forward search 2208 //forward search
2209 if (sc.flags & KateView::sfSelected) { 2209 if (sc.flags & KateView::sfSelected) {
2210 if (line < selectStart) { 2210 if (line < selectStart) {
2211 line = selectStart; 2211 line = selectStart;
2212 col = 0; 2212 col = 0;
2213 } 2213 }
2214 searchEnd = selectEnd; 2214 searchEnd = selectEnd;
2215 } else searchEnd = lastLine(); 2215 } else searchEnd = lastLine();
2216 2216
2217 while (line <= searchEnd) { 2217 while (line <= searchEnd) {
2218 textLine = getTextLine(line); 2218 textLine = getTextLine(line);
2219 tlen = textLine->length(); 2219 tlen = textLine->length();
2220 if (tlen > bufLen) { 2220 if (tlen > bufLen) {
2221 delete t; 2221 delete t;
2222 bufLen = (tlen + 255) & (~255); 2222 bufLen = (tlen + 255) & (~255);
2223 t = new QChar[bufLen]; 2223 t = new QChar[bufLen];
2224 } 2224 }
2225 memcpy(t, textLine->getText(), tlen*sizeof(QChar)); 2225 memcpy(t, textLine->getText(), tlen*sizeof(QChar));
2226 if (sc.flags & KateView::sfSelected) { 2226 if (sc.flags & KateView::sfSelected) {
2227 pos = 0; 2227 pos = 0;
2228 do { 2228 do {
2229 pos = textLine->findSelected(pos); 2229 pos = textLine->findSelected(pos);
2230 newPos = textLine->findUnselected(pos); 2230 newPos = textLine->findUnselected(pos);
2231 memset(&t[pos], 0, (newPos - pos)*sizeof(QChar)); 2231 memset(&t[pos], 0, (newPos - pos)*sizeof(QChar));
2232 pos = newPos; 2232 pos = newPos;
2233 } while (pos < tlen); 2233 } while (pos < tlen);
2234 } 2234 }
2235 2235
2236 QString text(t, tlen); 2236 QString text(t, tlen);
2237 if (sc.flags & KateView::sfWholeWords) { 2237 if (sc.flags & KateView::sfWholeWords) {
2238 // Until the end of the line... 2238 // Until the end of the line...
2239 while (col < tlen) { 2239 while (col < tlen) {
2240 // ...find the next match. 2240 // ...find the next match.
2241 col = sc.search(text, col); 2241 col = sc.search(text, col);
2242 if (col != -1) { 2242 if (col != -1) {
2243 // Is the match delimited correctly? 2243 // Is the match delimited correctly?
2244 if (((col == 0) || (!m_highlight->isInWord(t[col]))) && 2244 if (((col == 0) || (!m_highlight->isInWord(t[col]))) &&
2245 ((col + sc.matchedLength == tlen) || (!m_highlight->isInWord(t[col + sc.matchedLength])))) { 2245 ((col + sc.matchedLength == tlen) || (!m_highlight->isInWord(t[col + sc.matchedLength])))) {
2246 goto found; 2246 goto found;
2247 } 2247 }
2248 else { 2248 else {
2249 // Start again from the next character. 2249 // Start again from the next character.
2250 col++; 2250 col++;
2251 } 2251 }
2252 } 2252 }
2253 else { 2253 else {
2254 // No match. 2254 // No match.
2255 break; 2255 break;
2256 } 2256 }
2257 } 2257 }
2258 } 2258 }
2259 else { 2259 else {
2260 // Non-whole-word search. 2260 // Non-whole-word search.
2261 col = sc.search(text, col); 2261 col = sc.search(text, col);
2262 if (col != -1) 2262 if (col != -1)
2263 goto found; 2263 goto found;
2264 } 2264 }
2265 col = 0; 2265 col = 0;
2266 line++; 2266 line++;
2267 } 2267 }
2268 } else { 2268 } else {
2269 // backward search 2269 // backward search
2270 if (sc.flags & KateView::sfSelected) { 2270 if (sc.flags & KateView::sfSelected) {
2271 if (line > selectEnd) { 2271 if (line > selectEnd) {
2272 line = selectEnd; 2272 line = selectEnd;
2273 col = -1; 2273 col = -1;
2274 } 2274 }
2275 searchEnd = selectStart; 2275 searchEnd = selectStart;
2276 } else searchEnd = 0; 2276 } else searchEnd = 0;
2277 2277
2278 while (line >= searchEnd) { 2278 while (line >= searchEnd) {
2279 textLine = getTextLine(line); 2279 textLine = getTextLine(line);
2280 tlen = textLine->length(); 2280 tlen = textLine->length();
2281 if (tlen > bufLen) { 2281 if (tlen > bufLen) {
2282 delete t; 2282 delete t;
2283 bufLen = (tlen + 255) & (~255); 2283 bufLen = (tlen + 255) & (~255);
2284 t = new QChar[bufLen]; 2284 t = new QChar[bufLen];
2285 } 2285 }
2286 memcpy(t, textLine->getText(), tlen*sizeof(QChar)); 2286 memcpy(t, textLine->getText(), tlen*sizeof(QChar));
2287 if (sc.flags & KateView::sfSelected) { 2287 if (sc.flags & KateView::sfSelected) {
2288 pos = 0; 2288 pos = 0;
2289 do { 2289 do {
2290 pos = textLine->findSelected(pos); 2290 pos = textLine->findSelected(pos);
2291 newPos = textLine->findUnselected(pos); 2291 newPos = textLine->findUnselected(pos);
2292 memset(&t[pos], 0, (newPos - pos)*sizeof(QChar)); 2292 memset(&t[pos], 0, (newPos - pos)*sizeof(QChar));
2293 pos = newPos; 2293 pos = newPos;
2294 } while (pos < tlen); 2294 } while (pos < tlen);
2295 } 2295 }
2296 2296
2297 if (col < 0 || col > tlen) col = tlen; 2297 if (col < 0 || col > tlen) col = tlen;
2298 2298
2299 QString text(t, tlen); 2299 QString text(t, tlen);
2300 if (sc.flags & KateView::sfWholeWords) { 2300 if (sc.flags & KateView::sfWholeWords) {
2301 // Until the beginning of the line... 2301 // Until the beginning of the line...
2302 while (col >= 0) { 2302 while (col >= 0) {
2303 // ...find the next match. 2303 // ...find the next match.
2304 col = sc.search(text, col); 2304 col = sc.search(text, col);
2305 if (col != -1) { 2305 if (col != -1) {
2306 // Is the match delimited correctly? 2306 // Is the match delimited correctly?
2307 if (((col == 0) || (!m_highlight->isInWord(t[col]))) && 2307 if (((col == 0) || (!m_highlight->isInWord(t[col]))) &&
2308 ((col + sc.matchedLength == tlen) || (!m_highlight->isInWord(t[col + sc.matchedLength])))) { 2308 ((col + sc.matchedLength == tlen) || (!m_highlight->isInWord(t[col + sc.matchedLength])))) {
2309 goto found; 2309 goto found;
2310 } 2310 }
2311 else { 2311 else {
2312 // Start again from the previous character. 2312 // Start again from the previous character.
2313 col--; 2313 col--;
2314 } 2314 }
2315 } 2315 }
2316 else { 2316 else {
2317 // No match. 2317 // No match.
2318 break; 2318 break;
2319 } 2319 }
2320 } 2320 }
2321 } 2321 }
2322 else { 2322 else {
2323 // Non-whole-word search. 2323 // Non-whole-word search.
2324 col = sc.search(text, col); 2324 col = sc.search(text, col);
2325 if (col != -1) 2325 if (col != -1)
2326 goto found; 2326 goto found;
2327 } 2327 }
2328 col = -1; 2328 col = -1;
2329 line--; 2329 line--;
2330 } 2330 }
2331 } 2331 }
2332 sc.flags |= KateView::sfWrapped; 2332 sc.flags |= KateView::sfWrapped;
2333 return false; 2333 return false;
2334found: 2334found:
2335 if (sc.flags & KateView::sfWrapped) { 2335 if (sc.flags & KateView::sfWrapped) {
2336 if ((line > sc.startCursor.y || (line == sc.startCursor.y && col >= sc.startCursor.x)) 2336 if ((line > sc.startCursor.y || (line == sc.startCursor.y && col >= sc.startCursor.x))
2337 ^ ((sc.flags & KateView::sfBackward) != 0)) return false; 2337 ^ ((sc.flags & KateView::sfBackward) != 0)) return false;
2338 } 2338 }
2339 sc.cursor.x = col; 2339 sc.cursor.x = col;
2340 sc.cursor.y = line; 2340 sc.cursor.y = line;
2341 return true; 2341 return true;
2342} 2342}
2343 2343
2344void KateDocument::tagLine(int line) { 2344void KateDocument::tagLine(int line) {
2345 2345
2346 if (tagStart > line) tagStart = line; 2346 if (tagStart > line) tagStart = line;
2347 if (tagEnd < line) tagEnd = line; 2347 if (tagEnd < line) tagEnd = line;
2348} 2348}
2349 2349
2350void KateDocument::insLine(int line) { 2350void KateDocument::insLine(int line) {
2351 KateView *view; 2351 KateView *view;
2352 2352
2353 if (selectStart >= line) selectStart++; 2353 if (selectStart >= line) selectStart++;
2354 if (selectEnd >= line) selectEnd++; 2354 if (selectEnd >= line) selectEnd++;
2355 if (tagStart >= line) tagStart++; 2355 if (tagStart >= line) tagStart++;
2356 if (tagEnd >= line) tagEnd++; 2356 if (tagEnd >= line) tagEnd++;
2357 2357
2358 newDocGeometry = true; 2358 newDocGeometry = true;
2359 for (view = views.first(); view != 0L; view = views.next() ) { 2359 for (view = views.first(); view != 0L; view = views.next() ) {
2360 view->insLine(line); 2360 view->insLine(line);
2361 } 2361 }
2362} 2362}
2363 2363
2364void KateDocument::delLine(int line) { 2364void KateDocument::delLine(int line) {
2365 KateView *view; 2365 KateView *view;
2366 2366
2367 if (selectStart >= line && selectStart > 0) selectStart--; 2367 if (selectStart >= line && selectStart > 0) selectStart--;
2368 if (selectEnd >= line) selectEnd--; 2368 if (selectEnd >= line) selectEnd--;
2369 if (tagStart >= line && tagStart > 0) tagStart--; 2369 if (tagStart >= line && tagStart > 0) tagStart--;
2370 if (tagEnd >= line) tagEnd--; 2370 if (tagEnd >= line) tagEnd--;
2371 2371
2372 newDocGeometry = true; 2372 newDocGeometry = true;
2373 for (view = views.first(); view != 0L; view = views.next() ) { 2373 for (view = views.first(); view != 0L; view = views.next() ) {
2374 view->delLine(line); 2374 view->delLine(line);
2375 } 2375 }
2376} 2376}
2377 2377
2378void KateDocument::optimizeSelection() { 2378void KateDocument::optimizeSelection() {
2379 TextLine::Ptr textLine; 2379 TextLine::Ptr textLine;
2380 2380
2381 while (selectStart <= selectEnd) { 2381 while (selectStart <= selectEnd) {
2382 textLine = getTextLine(selectStart); 2382 textLine = getTextLine(selectStart);
2383 if (textLine->isSelected() || textLine->numSelected() > 0) break; 2383 if (textLine->isSelected() || textLine->numSelected() > 0) break;
2384 selectStart++; 2384 selectStart++;
2385 } 2385 }
2386 while (selectEnd >= selectStart) { 2386 while (selectEnd >= selectStart) {
2387 textLine = getTextLine(selectEnd); 2387 textLine = getTextLine(selectEnd);
2388 if (textLine->isSelected() || textLine->numSelected() > 0) break; 2388 if (textLine->isSelected() || textLine->numSelected() > 0) break;
2389 selectEnd--; 2389 selectEnd--;
2390 } 2390 }
2391 if (selectStart > selectEnd) { 2391 if (selectStart > selectEnd) {
2392 selectStart = 0xffffff; 2392 selectStart = 0xffffff;
2393 selectEnd = 0; 2393 selectEnd = 0;
2394 } 2394 }
2395} 2395}
2396 2396
2397void KateDocument::doAction(KateAction *a) { 2397void KateDocument::doAction(KateAction *a) {
2398 2398
2399 switch (a->action) { 2399 switch (a->action) {
2400 case KateAction::replace: 2400 case KateAction::replace:
2401 doReplace(a); 2401 doReplace(a);
2402 break; 2402 break;
2403 case KateAction::wordWrap: 2403 case KateAction::wordWrap:
2404 doWordWrap(a); 2404 doWordWrap(a);
2405 break; 2405 break;
2406 case KateAction::wordUnWrap: 2406 case KateAction::wordUnWrap:
2407 doWordUnWrap(a); 2407 doWordUnWrap(a);
2408 break; 2408 break;
2409 case KateAction::newLine: 2409 case KateAction::newLine:
2410 doNewLine(a); 2410 doNewLine(a);
2411 break; 2411 break;
2412 case KateAction::delLine: 2412 case KateAction::delLine:
2413 doDelLine(a); 2413 doDelLine(a);
2414 break; 2414 break;
2415 case KateAction::insLine: 2415 case KateAction::insLine:
2416 doInsLine(a); 2416 doInsLine(a);
2417 break; 2417 break;
2418 case KateAction::killLine: 2418 case KateAction::killLine:
2419 doKillLine(a); 2419 doKillLine(a);
2420 break; 2420 break;
2421/* case KateAction::doubleLine: 2421/* case KateAction::doubleLine:
2422 break; 2422 break;
2423 case KateAction::removeLine: 2423 case KateAction::removeLine:
2424 break;*/ 2424 break;*/
2425 } 2425 }
2426} 2426}
2427 2427
2428void KateDocument::doReplace(KateAction *a) { 2428void KateDocument::doReplace(KateAction *a) {
2429 TextLine::Ptr textLine; 2429 TextLine::Ptr textLine;
2430 int l; 2430 int l;
2431 2431
2432 //exchange current text with stored text in KateAction *a 2432 //exchange current text with stored text in KateAction *a
2433 2433
2434 textLine = getTextLine(a->cursor.y); 2434 textLine = getTextLine(a->cursor.y);
2435 l = textLine->length() - a->cursor.x; 2435 l = textLine->length() - a->cursor.x;
2436 if (l > a->len) l = a->len; 2436 if (l > a->len) l = a->len;
2437 2437
2438 QString oldText(&textLine->getText()[a->cursor.x], (l < 0) ? 0 : l); 2438 QString oldText(&textLine->getText()[a->cursor.x], (l < 0) ? 0 : l);
2439 textLine->replace(a->cursor.x, a->len, a->text.unicode(), a->text.length()); 2439 textLine->replace(a->cursor.x, a->len, a->text.unicode(), a->text.length());
2440 2440
2441 a->len = a->text.length(); 2441 a->len = a->text.length();
2442 a->text = oldText; 2442 a->text = oldText;
2443 2443
2444 buffer->changeLine(a->cursor.y); 2444 buffer->changeLine(a->cursor.y);
2445 2445
2446 tagLine(a->cursor.y); 2446 tagLine(a->cursor.y);
2447} 2447}
2448 2448
2449void KateDocument::doWordWrap(KateAction *a) { 2449void KateDocument::doWordWrap(KateAction *a) {
2450 TextLine::Ptr textLine; 2450 TextLine::Ptr textLine;
2451 2451
2452 textLine = getTextLine(a->cursor.y - 1); 2452 textLine = getTextLine(a->cursor.y - 1);
2453 a->len = textLine->length() - a->cursor.x; 2453 a->len = textLine->length() - a->cursor.x;
2454 textLine->wrap(getTextLine(a->cursor.y),a->len); 2454 textLine->wrap(getTextLine(a->cursor.y),a->len);
2455 2455
2456 buffer->changeLine(a->cursor.y - 1); 2456 buffer->changeLine(a->cursor.y - 1);
2457 buffer->changeLine(a->cursor.y); 2457 buffer->changeLine(a->cursor.y);
2458 2458
2459 tagLine(a->cursor.y - 1); 2459 tagLine(a->cursor.y - 1);
2460 tagLine(a->cursor.y); 2460 tagLine(a->cursor.y);
2461 if (selectEnd == a->cursor.y - 1) selectEnd++; 2461 if (selectEnd == a->cursor.y - 1) selectEnd++;
2462 2462
2463 a->action = KateAction::wordUnWrap; 2463 a->action = KateAction::wordUnWrap;
2464} 2464}
2465 2465
2466void KateDocument::doWordUnWrap(KateAction *a) { 2466void KateDocument::doWordUnWrap(KateAction *a) {
2467 TextLine::Ptr textLine; 2467 TextLine::Ptr textLine;
2468 2468
2469 textLine = getTextLine(a->cursor.y - 1); 2469 textLine = getTextLine(a->cursor.y - 1);
2470// textLine->setLength(a->len); 2470// textLine->setLength(a->len);
2471 textLine->unWrap(a->len, getTextLine(a->cursor.y),a->cursor.x); 2471 textLine->unWrap(a->len, getTextLine(a->cursor.y),a->cursor.x);
2472 2472
2473 buffer->changeLine(a->cursor.y - 1); 2473 buffer->changeLine(a->cursor.y - 1);
2474 buffer->changeLine(a->cursor.y); 2474 buffer->changeLine(a->cursor.y);
2475 2475
2476 tagLine(a->cursor.y - 1); 2476 tagLine(a->cursor.y - 1);
2477 tagLine(a->cursor.y); 2477 tagLine(a->cursor.y);
2478 2478
2479 a->action = KateAction::wordWrap; 2479 a->action = KateAction::wordWrap;
2480} 2480}
2481 2481
2482void KateDocument::doNewLine(KateAction *a) { 2482void KateDocument::doNewLine(KateAction *a) {
2483 TextLine::Ptr textLine, newLine; 2483 TextLine::Ptr textLine, newLine;
2484 2484
2485 textLine = getTextLine(a->cursor.y); 2485 textLine = getTextLine(a->cursor.y);
2486 newLine = new TextLine(textLine->getRawAttr(), textLine->getContext()); 2486 newLine = new TextLine(textLine->getRawAttr(), textLine->getContext());
2487 textLine->wrap(newLine,a->cursor.x); 2487 textLine->wrap(newLine,a->cursor.x);
2488 2488
2489 buffer->insertLine(a->cursor.y + 1, newLine); 2489 buffer->insertLine(a->cursor.y + 1, newLine);
2490 buffer->changeLine(a->cursor.y); 2490 buffer->changeLine(a->cursor.y);
2491 2491
2492 insLine(a->cursor.y + 1); 2492 insLine(a->cursor.y + 1);
2493 tagLine(a->cursor.y); 2493 tagLine(a->cursor.y);
2494 tagLine(a->cursor.y + 1); 2494 tagLine(a->cursor.y + 1);
2495 if (selectEnd == a->cursor.y) selectEnd++;//addSelection(a->cursor.y + 1); 2495 if (selectEnd == a->cursor.y) selectEnd++;//addSelection(a->cursor.y + 1);
2496 2496
2497 a->action = KateAction::delLine; 2497 a->action = KateAction::delLine;
2498} 2498}
2499 2499
2500void KateDocument::doDelLine(KateAction *a) { 2500void KateDocument::doDelLine(KateAction *a) {
2501 TextLine::Ptr textLine, nextLine; 2501 TextLine::Ptr textLine, nextLine;
2502 2502
2503 textLine = getTextLine(a->cursor.y); 2503 textLine = getTextLine(a->cursor.y);
2504 nextLine = getTextLine(a->cursor.y+1); 2504 nextLine = getTextLine(a->cursor.y+1);
2505// textLine->setLength(a->cursor.x); 2505// textLine->setLength(a->cursor.x);
2506 textLine->unWrap(a->cursor.x, nextLine,nextLine->length()); 2506 textLine->unWrap(a->cursor.x, nextLine,nextLine->length());
2507 textLine->setContext(nextLine->getContext()); 2507 textLine->setContext(nextLine->getContext());
2508 if (longestLine == nextLine) longestLine = 0L; 2508 if (longestLine == nextLine) longestLine = 0L;
2509 2509
2510 buffer->changeLine(a->cursor.y); 2510 buffer->changeLine(a->cursor.y);
2511 buffer->removeLine(a->cursor.y+1); 2511 buffer->removeLine(a->cursor.y+1);
2512 2512
2513 tagLine(a->cursor.y); 2513 tagLine(a->cursor.y);
2514 delLine(a->cursor.y + 1); 2514 delLine(a->cursor.y + 1);
2515 2515
2516 a->action = KateAction::newLine; 2516 a->action = KateAction::newLine;
2517} 2517}
2518 2518
2519void KateDocument::doInsLine(KateAction *a) { 2519void KateDocument::doInsLine(KateAction *a) {
2520 2520
2521 buffer->insertLine(a->cursor.y, new TextLine()); 2521 buffer->insertLine(a->cursor.y, new TextLine());
2522 2522
2523 insLine(a->cursor.y); 2523 insLine(a->cursor.y);
2524 2524
2525 a->action = KateAction::killLine; 2525 a->action = KateAction::killLine;
2526} 2526}
2527 2527
2528void KateDocument::doKillLine(KateAction *a) { 2528void KateDocument::doKillLine(KateAction *a) {
2529 TextLine::Ptr textLine = getTextLine(a->cursor.y); 2529 TextLine::Ptr textLine = getTextLine(a->cursor.y);
2530 if (longestLine == textLine) longestLine = 0L; 2530 if (longestLine == textLine) longestLine = 0L;
2531 2531
2532 buffer->removeLine(a->cursor.y); 2532 buffer->removeLine(a->cursor.y);
2533 2533
2534 delLine(a->cursor.y); 2534 delLine(a->cursor.y);
2535 tagLine(a->cursor.y); 2535 tagLine(a->cursor.y);
2536 2536
2537 a->action = KateAction::insLine; 2537 a->action = KateAction::insLine;
2538} 2538}
2539 2539
2540void KateDocument::newUndo() { 2540void KateDocument::newUndo() {
2541 KTextEditor::View *view; 2541 KTextEditor::View *view;
2542 int state; 2542 int state;
2543 2543
2544 state = 0; 2544 state = 0;
2545 if (currentUndo > 0) state |= 1; 2545 if (currentUndo > 0) state |= 1;
2546 if (currentUndo < (int) undoList.count()) state |= 2; 2546 if (currentUndo < (int) undoList.count()) state |= 2;
2547 undoState = state; 2547 undoState = state;
2548 for (view = m_views.first(); view != 0L; view = m_views.next() ) { 2548 for (view = m_views.first(); view != 0L; view = m_views.next() ) {
2549 emit static_cast<KateView *>( view )->newUndo(); 2549 emit static_cast<KateView *>( view )->newUndo();
2550 } 2550 }
2551} 2551}
2552 2552
2553void KateDocument::recordStart(VConfig &c, int newUndoType) { 2553void KateDocument::recordStart(VConfig &c, int newUndoType) {
2554 recordStart(c.view, c.cursor, c.flags, newUndoType); 2554 recordStart(c.view, c.cursor, c.flags, newUndoType);
2555} 2555}
2556 2556
2557void KateDocument::recordStart(KateView *, PointStruc &cursor, int flags, 2557void KateDocument::recordStart(KateView *, PointStruc &cursor, int flags,
2558 int newUndoType, bool keepModal, bool mergeUndo) { 2558 int newUndoType, bool keepModal, bool mergeUndo) {
2559 2559
2560 KateActionGroup *g; 2560 KateActionGroup *g;
2561 2561
2562// if (newUndoType == KateActionGroup::ugNone) { 2562// if (newUndoType == KateActionGroup::ugNone) {
2563 // only a bug would cause this 2563 // only a bug would cause this
2564//why should someone do this? we can't prevent all programming errors :) (jochen whilhelmy) 2564//why should someone do this? we can't prevent all programming errors :) (jochen whilhelmy)
2565// debug("KateDocument::recordStart() called with no undo group type!"); 2565// debug("KateDocument::recordStart() called with no undo group type!");
2566// return; 2566// return;
2567// } 2567// }
2568 2568
2569 if (!keepModal) setPseudoModal(0L); 2569 if (!keepModal) setPseudoModal(0L);
2570 2570
2571 //i optimized the group undo stuff a bit (jochen wilhelmy) 2571 //i optimized the group undo stuff a bit (jochen wilhelmy)
2572 // recordReset() is not needed any more 2572 // recordReset() is not needed any more
2573 g = undoList.getLast(); 2573 g = undoList.getLast();
2574 if (g != 0L && ((undoCount < 1024 && flags & KateView::cfGroupUndo 2574 if (g != 0L && ((undoCount < 1024 && flags & KateView::cfGroupUndo
2575 && g->end.x == cursor.x && g->end.y == cursor.y) || mergeUndo)) { 2575 && g->end.x == cursor.x && g->end.y == cursor.y) || mergeUndo)) {
2576 2576
2577 //undo grouping : same actions are put into one undo step 2577 //undo grouping : same actions are put into one undo step
2578 //precondition : new action starts where old stops or mergeUndo flag 2578 //precondition : new action starts where old stops or mergeUndo flag
2579 if (g->undoType == newUndoType 2579 if (g->undoType == newUndoType
2580 || (g->undoType == KateActionGroup::ugInsChar 2580 || (g->undoType == KateActionGroup::ugInsChar
2581 && newUndoType == KateActionGroup::ugInsLine) 2581 && newUndoType == KateActionGroup::ugInsLine)
2582 || (g->undoType == KateActionGroup::ugDelChar 2582 || (g->undoType == KateActionGroup::ugDelChar
2583 && newUndoType == KateActionGroup::ugDelLine)) { 2583 && newUndoType == KateActionGroup::ugDelLine)) {
2584 2584
2585 undoCount++; 2585 undoCount++;
2586 if (g->undoType != newUndoType) undoCount = 0xffffff; 2586 if (g->undoType != newUndoType) undoCount = 0xffffff;
2587 return; 2587 return;
2588 } 2588 }
2589 } 2589 }
2590 undoCount = 0; 2590 undoCount = 0;
2591/* 2591/*
2592 if (undoView != view) { 2592 if (undoView != view) {
2593 // always kill the current undo group if the editing view changes 2593 // always kill the current undo group if the editing view changes
2594 recordReset(); 2594 recordReset();
2595 undoType = newUndoType; 2595 undoType = newUndoType;
2596 } else if (newUndoType == undoType) { 2596 } else if (newUndoType == undoType) {
2597printf("bla!!!\n"); 2597printf("bla!!!\n");
2598 // same as current type, keep using it 2598 // same as current type, keep using it
2599 return; 2599 return;
2600 } else if ( (undoType == KateActionGroup::ugInsChar && newUndoType == KateActionGroup::ugInsLine) || 2600 } else if ( (undoType == KateActionGroup::ugInsChar && newUndoType == KateActionGroup::ugInsLine) ||
2601 (undoType == KateActionGroup::ugDelChar && newUndoType == KateActionGroup::ugDelLine) ) { 2601 (undoType == KateActionGroup::ugDelChar && newUndoType == KateActionGroup::ugDelLine) ) {
2602 // some type combinations can run together... 2602 // some type combinations can run together...
2603 undoType += 1000; 2603 undoType += 1000;
2604 return; 2604 return;
2605 } else { 2605 } else {
2606 recordReset(); 2606 recordReset();
2607 undoType = newUndoType; 2607 undoType = newUndoType;
2608 } 2608 }
2609 2609
2610 undoView = view; 2610 undoView = view;
2611*/ 2611*/
2612 while ((int) undoList.count() > currentUndo) undoList.removeLast(); 2612 while ((int) undoList.count() > currentUndo) undoList.removeLast();
2613 while ((int) undoList.count() > undoSteps) { 2613 while ((int) undoList.count() > undoSteps) {
2614 undoList.removeFirst(); 2614 undoList.removeFirst();
2615 currentUndo--; 2615 currentUndo--;
2616 } 2616 }
2617 2617
2618 g = new KateActionGroup(cursor, newUndoType); 2618 g = new KateActionGroup(cursor, newUndoType);
2619 undoList.append(g); 2619 undoList.append(g);
2620// currentUndo++; 2620// currentUndo++;
2621 2621
2622 tagEnd = 0; 2622 tagEnd = 0;
2623 tagStart = 0xffffff; 2623 tagStart = 0xffffff;
2624} 2624}
2625 2625
2626void KateDocument::recordAction(KateAction::Action action, PointStruc &cursor) { 2626void KateDocument::recordAction(KateAction::Action action, PointStruc &cursor) {
2627 KateAction *a; 2627 KateAction *a;
2628 2628
2629 a = new KateAction(action, cursor); 2629 a = new KateAction(action, cursor);
2630 doAction(a); 2630 doAction(a);
2631 undoList.getLast()->insertAction(a); 2631 undoList.getLast()->insertAction(a);
2632} 2632}
2633 2633
2634void KateDocument::recordInsert(VConfig &c, const QString &text) { 2634void KateDocument::recordInsert(VConfig &c, const QString &text) {
2635 recordReplace(c, 0, text); 2635 recordReplace(c, 0, text);
2636} 2636}
2637 2637
2638void KateDocument::recordReplace(VConfig &c, int len, const QString &text) { 2638void KateDocument::recordReplace(VConfig &c, int len, const QString &text) {
2639 if (c.cursor.x > 0 && !(c.flags & KateView::cfSpaceIndent)) { 2639 if (c.cursor.x > 0 && !(c.flags & KateView::cfSpaceIndent)) {
2640 TextLine::Ptr textLine = getTextLine(c.cursor.y); 2640 TextLine::Ptr textLine = getTextLine(c.cursor.y);
2641 if (textLine->length() == 0) { 2641 if (textLine->length() == 0) {
2642 QString s = tabString(c.cursor.x, tabChars); 2642 QString s = tabString(c.cursor.x, tabChars);
2643 int len = s.length(); 2643 int len = s.length();
2644 s += text; 2644 s += text;
2645 c.cursor.x = 0; 2645 c.cursor.x = 0;
2646 recordReplace(c.cursor, len, s); 2646 recordReplace(c.cursor, len, s);
2647 c.cursor.x = len; 2647 c.cursor.x = len;
2648 return; 2648 return;
2649 } 2649 }
2650 } 2650 }
2651 recordReplace(c.cursor, len, text); 2651 recordReplace(c.cursor, len, text);
2652} 2652}
2653 2653
2654void KateDocument::recordInsert(PointStruc &cursor, const QString &text) { 2654void KateDocument::recordInsert(PointStruc &cursor, const QString &text) {
2655 recordReplace(cursor, 0, text); 2655 recordReplace(cursor, 0, text);
2656} 2656}
2657 2657
2658void KateDocument::recordDelete(PointStruc &cursor, int len) { 2658void KateDocument::recordDelete(PointStruc &cursor, int len) {
2659 recordReplace(cursor, len, QString::null); 2659 recordReplace(cursor, len, QString::null);
2660} 2660}
2661 2661
2662void KateDocument::recordReplace(PointStruc &cursor, int len, const QString &text) { 2662void KateDocument::recordReplace(PointStruc &cursor, int len, const QString &text) {
2663 KateAction *a; 2663 KateAction *a;
2664 TextLine::Ptr textLine; 2664 TextLine::Ptr textLine;
2665 int l; 2665 int l;
2666 2666
2667 if (len == 0 && text.isEmpty()) return; 2667 if (len == 0 && text.isEmpty()) return;
2668 2668
2669 //try to append to last replace action 2669 //try to append to last replace action
2670 a = undoList.getLast()->action; 2670 a = undoList.getLast()->action;
2671 if (a == 0L || a->action != KateAction::replace 2671 if (a == 0L || a->action != KateAction::replace
2672 || a->cursor.x + a->len != cursor.x || a->cursor.y != cursor.y) { 2672 || a->cursor.x + a->len != cursor.x || a->cursor.y != cursor.y) {
2673 2673
2674//if (a != 0L) printf("new %d %d\n", a->cursor.x + a->len, cursor.x); 2674//if (a != 0L) printf("new %d %d\n", a->cursor.x + a->len, cursor.x);
2675 a = new KateAction(KateAction::replace, cursor); 2675 a = new KateAction(KateAction::replace, cursor);
2676 undoList.getLast()->insertAction(a); 2676 undoList.getLast()->insertAction(a);
2677 } 2677 }
2678 2678
2679 //replace 2679 //replace
2680 textLine = getTextLine(cursor.y); 2680 textLine = getTextLine(cursor.y);
2681 l = textLine->length() - cursor.x; 2681 l = textLine->length() - cursor.x;
2682 if (l > len) l = len; 2682 if (l > len) l = len;
2683 a->text.insert(a->text.length(), &textLine->getText()[cursor.x], (l < 0) ? 0 : l); 2683 a->text.insert(a->text.length(), &textLine->getText()[cursor.x], (l < 0) ? 0 : l);
2684 textLine->replace(cursor.x, len, text.unicode(), text.length()); 2684 textLine->replace(cursor.x, len, text.unicode(), text.length());
2685 a->len += text.length(); 2685 a->len += text.length();
2686 2686
2687 buffer->changeLine(a->cursor.y); 2687 buffer->changeLine(a->cursor.y);
2688 updateMaxLength(textLine); 2688 updateMaxLength(textLine);
2689 tagLine(a->cursor.y); 2689 tagLine(a->cursor.y);
2690} 2690}
2691 2691
2692void KateDocument::recordEnd(VConfig &c) { 2692void KateDocument::recordEnd(VConfig &c) {
2693 recordEnd(c.view, c.cursor, c.flags); 2693 recordEnd(c.view, c.cursor, c.flags);
2694} 2694}
2695 2695
2696void KateDocument::recordEnd(KateView *view, PointStruc &cursor, int flags) { 2696void KateDocument::recordEnd(KateView *view, PointStruc &cursor, int flags) {
2697 KateActionGroup *g; 2697 KateActionGroup *g;
2698 2698
2699 // clear selection if option "persistent selections" is off 2699 // clear selection if option "persistent selections" is off
2700// if (!(flags & cfPersistent)) deselectAll(); 2700// if (!(flags & cfPersistent)) deselectAll();
2701 2701
2702 g = undoList.getLast(); 2702 g = undoList.getLast();
2703 if (g->action == 0L) { 2703 if (g->action == 0L) {
2704 // no action has been done: remove empty undo record 2704 // no action has been done: remove empty undo record
2705 undoList.removeLast(); 2705 undoList.removeLast();
2706 return; 2706 return;
2707 } 2707 }
2708 // store end cursor position for redo 2708 // store end cursor position for redo
2709 g->end = cursor; 2709 g->end = cursor;
2710 currentUndo = undoList.count(); 2710 currentUndo = undoList.count();
2711 2711
2712 if (tagStart <= tagEnd) { 2712 if (tagStart <= tagEnd) {
2713 optimizeSelection(); 2713 optimizeSelection();
2714 updateLines(tagStart, tagEnd, flags, cursor.y); 2714 updateLines(tagStart, tagEnd, flags, cursor.y);
2715 setModified(true); 2715 setModified(true);
2716 } 2716 }
2717 2717
2718 view->updateCursor(cursor, flags); 2718 view->updateCursor(cursor, flags);
2719 2719
2720// newUndo(); 2720// newUndo();
2721/* 2721/*
2722 undoCount++; 2722 undoCount++;
2723 // we limit the number of individual undo operations for sanity - is 1K reasonable? 2723 // we limit the number of individual undo operations for sanity - is 1K reasonable?
2724 // this is also where we handle non-group undo preference 2724 // this is also where we handle non-group undo preference
2725 // if the undo type is singlular, we always finish it now 2725 // if the undo type is singlular, we always finish it now
2726 if ( undoType == KateActionGroup::ugPaste || 2726 if ( undoType == KateActionGroup::ugPaste ||
2727 undoType == KateActionGroup::ugDelBlock || 2727 undoType == KateActionGroup::ugDelBlock ||
2728 undoType > 1000 || 2728 undoType > 1000 ||
2729 undoCount > 1024 || !(flags & cfGroupUndo) ) { 2729 undoCount > 1024 || !(flags & cfGroupUndo) ) {
2730printf("recordend %d %d\n", undoType, undoCount); 2730printf("recordend %d %d\n", undoType, undoCount);
2731 recordReset(); 2731 recordReset();
2732 } 2732 }
2733*/ 2733*/
2734 2734
2735 // this should keep the flood of signals down a little... 2735 // this should keep the flood of signals down a little...
2736 if (undoCount == 0) newUndo(); 2736 if (undoCount == 0) newUndo();
2737 emit textChanged(); 2737 emit textChanged();
2738} 2738}
2739/* 2739/*
2740void KateDocument::recordReset() 2740void KateDocument::recordReset()
2741{ 2741{
2742 if (pseudoModal) 2742 if (pseudoModal)
2743 return; 2743 return;
2744 2744
2745 // forces the next call of recordStart() to begin a new undo group 2745 // forces the next call of recordStart() to begin a new undo group
2746 // not used in normal editing, but used by markFound(), etc. 2746 // not used in normal editing, but used by markFound(), etc.
2747 undoType = KateActionGroup::ugNone; 2747 undoType = KateActionGroup::ugNone;
2748 undoCount = 0; 2748 undoCount = 0;
2749 undoView = NULL; 2749 undoView = NULL;
2750 undoReported = false; 2750 undoReported = false;
2751printf("recordreset\n"); 2751printf("recordreset\n");
2752} 2752}
2753*/ 2753*/
2754 2754
2755/* 2755/*
2756void KateDocument::recordDel(PointStruc &cursor, TextLine::Ptr &textLine, int l) { 2756void KateDocument::recordDel(PointStruc &cursor, TextLine::Ptr &textLine, int l) {
2757 int len; 2757 int len;
2758 2758
2759 len = textLine->length() - cursor.x; 2759 len = textLine->length() - cursor.x;
2760 if (len > l) len = l; 2760 if (len > l) len = l;
2761 if (len > 0) { 2761 if (len > 0) {
2762 insertUndo(new KateAction(KateAction::replace,cursor,&textLine->getText()[cursor.x],len)); 2762 insertUndo(new KateAction(KateAction::replace,cursor,&textLine->getText()[cursor.x],len));
2763 } 2763 }
2764} 2764}
2765*/ 2765*/
2766 2766
2767 2767
2768void KateDocument::doActionGroup(KateActionGroup *g, int flags, bool undo) { 2768void KateDocument::doActionGroup(KateActionGroup *g, int flags, bool undo) {
2769 KateAction *a, *next; 2769 KateAction *a, *next;
2770 2770
2771 setPseudoModal(0L); 2771 setPseudoModal(0L);
2772 if (!(flags & KateView::cfPersistent)) deselectAll(); 2772 if (!(flags & KateView::cfPersistent)) deselectAll();
2773 tagEnd = 0; 2773 tagEnd = 0;
2774 tagStart = 0xffffff; 2774 tagStart = 0xffffff;
2775 2775
2776 a = g->action; 2776 a = g->action;
2777 g->action = 0L; 2777 g->action = 0L;
2778 while (a) { 2778 while (a) {
2779 doAction(a); 2779 doAction(a);
2780 next = a->next; 2780 next = a->next;
2781 g->insertAction(a); 2781 g->insertAction(a);
2782 a = next; 2782 a = next;
2783 } 2783 }
2784 optimizeSelection(); 2784 optimizeSelection();
2785 if (tagStart <= tagEnd) updateLines(tagStart, tagEnd, flags); 2785 if (tagStart <= tagEnd) updateLines(tagStart, tagEnd, flags);
2786 2786
2787 // the undo/redo functions set undo to true, all others should leave it 2787 // the undo/redo functions set undo to true, all others should leave it
2788 // alone (default) 2788 // alone (default)
2789 if (!undo) { 2789 if (!undo) {
2790 setModified(true); 2790 setModified(true);
2791 newUndo(); 2791 newUndo();
2792 } 2792 }
2793} 2793}
2794 2794
2795int KateDocument::nextUndoType() 2795int KateDocument::nextUndoType()
2796{ 2796{
2797 KateActionGroup *g; 2797 KateActionGroup *g;
2798 2798
2799 if (currentUndo <= 0) return KateActionGroup::ugNone; 2799 if (currentUndo <= 0) return KateActionGroup::ugNone;
2800 g = undoList.at(currentUndo - 1); 2800 g = undoList.at(currentUndo - 1);
2801 return g->undoType; 2801 return g->undoType;
2802} 2802}
2803 2803
2804int KateDocument::nextRedoType() 2804int KateDocument::nextRedoType()
2805{ 2805{
2806 KateActionGroup *g; 2806 KateActionGroup *g;
2807 2807
2808 if (currentUndo >= (int) undoList.count()) return KateActionGroup::ugNone; 2808 if (currentUndo >= (int) undoList.count()) return KateActionGroup::ugNone;
2809 g = undoList.at(currentUndo); 2809 g = undoList.at(currentUndo);
2810// if (!g) return KateActionGroup::ugNone; 2810// if (!g) return KateActionGroup::ugNone;
2811 return g->undoType; 2811 return g->undoType;
2812} 2812}
2813 2813
2814void KateDocument::undoTypeList(QValueList<int> &lst) 2814void KateDocument::undoTypeList(QValueList<int> &lst)
2815{ 2815{
2816 lst.clear(); 2816 lst.clear();
2817 for (int i = currentUndo-1; i>=0 ;i--) 2817 for (int i = currentUndo-1; i>=0 ;i--)
2818 lst.append(undoList.at(i)->undoType); 2818 lst.append(undoList.at(i)->undoType);
2819} 2819}
2820 2820
2821void KateDocument::redoTypeList(QValueList<int> &lst) 2821void KateDocument::redoTypeList(QValueList<int> &lst)
2822{ 2822{
2823 lst.clear(); 2823 lst.clear();
2824 for (int i = currentUndo+1; i<(int)undoList.count(); i++) 2824 for (int i = currentUndo+1; i<(int)undoList.count(); i++)
2825 lst.append(undoList.at(i)->undoType); 2825 lst.append(undoList.at(i)->undoType);
2826} 2826}
2827 2827
2828void KateDocument::undo(VConfig &c, int count) { 2828void KateDocument::undo(VConfig &c, int count) {
2829 KateActionGroup *g = 0L; 2829 KateActionGroup *g = 0L;
2830 int num; 2830 int num;
2831 bool needUpdate = false; // don't update the cursor until completely done 2831 bool needUpdate = false; // don't update the cursor until completely done
2832 2832
2833 if (count <= 0) return; 2833 if (count <= 0) return;
2834 2834
2835 for (num = 0 ; num < count ; num++) { 2835 for (num = 0 ; num < count ; num++) {
2836 if (currentUndo <= 0) break; 2836 if (currentUndo <= 0) break;
2837 currentUndo--; 2837 currentUndo--;
2838 g = undoList.at(currentUndo); 2838 g = undoList.at(currentUndo);
2839 doActionGroup(g, c.flags, true); // do not setModified() or newUndo() 2839 doActionGroup(g, c.flags, true); // do not setModified() or newUndo()
2840 needUpdate = true; 2840 needUpdate = true;
2841 2841
2842// if (num == 0) recordReset(); 2842// if (num == 0) recordReset();
2843 } 2843 }
2844 2844
2845 if (needUpdate) { 2845 if (needUpdate) {
2846 // since we told doActionGroup() not to do this stuff, we need to do it now 2846 // since we told doActionGroup() not to do this stuff, we need to do it now
2847 c.view->updateCursor(g->start); 2847 c.view->updateCursor(g->start);
2848 setModified(true); 2848 setModified(true);
2849 newUndo(); 2849 newUndo();
2850 } 2850 }
2851} 2851}
2852 2852
2853void KateDocument::redo(VConfig &c, int count) { 2853void KateDocument::redo(VConfig &c, int count) {
2854 KateActionGroup *g = 0L; 2854 KateActionGroup *g = 0L;
2855 int num; 2855 int num;
2856 bool needUpdate = false; // don't update the cursor until completely done 2856 bool needUpdate = false; // don't update the cursor until completely done
2857 2857
2858 if (count <= 0) return; 2858 if (count <= 0) return;
2859 2859
2860 for (num = 0 ; num < count ; num++) { 2860 for (num = 0 ; num < count ; num++) {
2861 if (currentUndo+1 > (int)undoList.count()) break; 2861 if (currentUndo+1 > (int)undoList.count()) break;
2862 g = undoList.at(currentUndo); 2862 g = undoList.at(currentUndo);
2863 currentUndo++; 2863 currentUndo++;
2864 doActionGroup(g, c.flags, true); // do not setModified() or newUndo() 2864 doActionGroup(g, c.flags, true); // do not setModified() or newUndo()
2865 needUpdate = true; 2865 needUpdate = true;
2866 2866
2867// if (num == 0) recordReset(); 2867// if (num == 0) recordReset();
2868 } 2868 }
2869 2869
2870 if (needUpdate) { 2870 if (needUpdate) {
2871 // since we told doActionGroup() not to do this stuff, we need to do it now 2871 // since we told doActionGroup() not to do this stuff, we need to do it now
2872 c.view->updateCursor(g->end); 2872 c.view->updateCursor(g->end);
2873 setModified(true); 2873 setModified(true);
2874 newUndo(); 2874 newUndo();
2875 } 2875 }
2876} 2876}
2877 2877
2878void KateDocument::clearRedo() { 2878void KateDocument::clearRedo() {
2879 // disable redos 2879 // disable redos
2880 // this was added as an assist to the spell checker 2880 // this was added as an assist to the spell checker
2881 bool deleted = false; 2881 bool deleted = false;
2882 2882
2883 while ((int) undoList.count() > currentUndo) { 2883 while ((int) undoList.count() > currentUndo) {
2884 deleted = true; 2884 deleted = true;
2885 undoList.removeLast(); 2885 undoList.removeLast();
2886 } 2886 }
2887 2887
2888 if (deleted) newUndo(); 2888 if (deleted) newUndo();
2889} 2889}
2890 2890
2891void KateDocument::setUndoSteps(int steps) { 2891void KateDocument::setUndoSteps(int steps) {
2892 if (steps < 5) steps = 5; 2892 if (steps < 5) steps = 5;
2893 undoSteps = steps; 2893 undoSteps = steps;
2894} 2894}
2895 2895
2896void KateDocument::setPseudoModal(QWidget *w) { 2896void KateDocument::setPseudoModal(QWidget *w) {
2897// QWidget *old = pseudoModal; 2897// QWidget *old = pseudoModal;
2898 2898
2899 // (glenebob) 2899 // (glenebob)
2900 // this is a temporary hack to make the spell checker work a little 2900 // this is a temporary hack to make the spell checker work a little
2901 // better - as kspell progresses, this sort of thing should become 2901 // better - as kspell progresses, this sort of thing should become
2902 // obsolete or worked around more cleanly 2902 // obsolete or worked around more cleanly
2903 // this is relied upon *only* by the spell-check code 2903 // this is relied upon *only* by the spell-check code
2904 if (pseudoModal && pseudoModal != (QWidget*)1L) 2904 if (pseudoModal && pseudoModal != (QWidget*)1L)
2905 delete pseudoModal; 2905 delete pseudoModal;
2906 2906
2907// pseudoModal = 0L; 2907// pseudoModal = 0L;
2908// if (old || w) recordReset(); 2908// if (old || w) recordReset();
2909 2909
2910 pseudoModal = w; 2910 pseudoModal = w;
2911} 2911}
2912 2912
2913 2913
2914void KateDocument::newBracketMark(PointStruc &cursor, BracketMark &bm) 2914void KateDocument::newBracketMark(PointStruc &cursor, BracketMark &bm)
2915{ 2915{
2916 TextLine::Ptr textLine; 2916 TextLine::Ptr textLine;
2917 int x, line, count, attr; 2917 int x, line, count, attr;
2918 QChar bracket, opposite, ch; 2918 QChar bracket, opposite, ch;
2919 Attribute *a; 2919 Attribute *a;
2920 2920
2921 bm.eXPos = -1; //mark bracked mark as invalid 2921 bm.eXPos = -1; //mark bracked mark as invalid
2922 x = cursor.x -1; // -1 to look at left side of cursor 2922 x = cursor.x -1; // -1 to look at left side of cursor
2923 if (x < 0) return; 2923 if (x < 0) return;
2924 line = cursor.y; //current line 2924 line = cursor.y; //current line
2925 count = 0; //bracket counter for nested brackets 2925 count = 0; //bracket counter for nested brackets
2926 2926
2927 textLine = getTextLine(line); 2927 textLine = getTextLine(line);
2928 if (!textLine) return; 2928 if (!textLine) return;
2929 2929
2930 bracket = textLine->getChar(x); 2930 bracket = textLine->getChar(x);
2931 attr = textLine->getAttr(x); 2931 attr = textLine->getAttr(x);
2932 2932
2933 if (bracket == '(' || bracket == '[' || bracket == '{') 2933 if (bracket == '(' || bracket == '[' || bracket == '{')
2934 { 2934 {
2935 //get opposite bracket 2935 //get opposite bracket
2936 opposite = ')'; 2936 opposite = ')';
2937 if (bracket == '[') opposite = ']'; 2937 if (bracket == '[') opposite = ']';
2938 if (bracket == '{') opposite = '}'; 2938 if (bracket == '{') opposite = '}';
2939 //get attribute of bracket (opposite bracket must have the same attribute) 2939 //get attribute of bracket (opposite bracket must have the same attribute)
2940 x++; 2940 x++;
2941 while (line - cursor.y < 40) { 2941 while (line - cursor.y < 40) {
2942 //go to next line on end of line 2942 //go to next line on end of line
2943 while (x >= (int) textLine->length()) { 2943 while (x >= (int) textLine->length()) {
2944 line++; 2944 line++;
2945 if (line > lastLine()) return; 2945 if (line > lastLine()) return;
2946 textLine = getTextLine(line); 2946 textLine = getTextLine(line);
2947 x = 0; 2947 x = 0;
2948 } 2948 }
2949 if (textLine->getAttr(x) == attr) { 2949 if (textLine->getAttr(x) == attr) {
2950 //try to find opposite bracked 2950 //try to find opposite bracked
2951 ch = textLine->getChar(x); 2951 ch = textLine->getChar(x);
2952 if (ch == bracket) count++; //same bracket : increase counter 2952 if (ch == bracket) count++; //same bracket : increase counter
2953 if (ch == opposite) { 2953 if (ch == opposite) {
2954 count--; 2954 count--;
2955 if (count < 0) goto found; 2955 if (count < 0) goto found;
2956 } 2956 }
2957 } 2957 }
2958 x++; 2958 x++;
2959 } 2959 }
2960 } 2960 }
2961 else if (bracket == ')' || bracket == ']' || bracket == '}') 2961 else if (bracket == ')' || bracket == ']' || bracket == '}')
2962 { 2962 {
2963 opposite = '('; 2963 opposite = '(';
2964 if (bracket == ']') opposite = '['; 2964 if (bracket == ']') opposite = '[';
2965 if (bracket == '}') opposite = '{'; 2965 if (bracket == '}') opposite = '{';
2966 x--; 2966 x--;
2967 while (cursor.y - line < 20) { 2967 while (cursor.y - line < 20) {
2968 2968
2969 while (x < 0) { 2969 while (x < 0) {
2970 line--; 2970 line--;
2971 if (line < 0) return; 2971 if (line < 0) return;
2972 textLine = getTextLine(line); 2972 textLine = getTextLine(line);
2973 x = textLine->length() -1; 2973 x = textLine->length() -1;
2974 } 2974 }
2975 if (textLine->getAttr(x) == attr) { 2975 if (textLine->getAttr(x) == attr) {
2976 ch = textLine->getChar(x); 2976 ch = textLine->getChar(x);
2977 if (ch == bracket) count++; 2977 if (ch == bracket) count++;
2978 if (ch == opposite) { 2978 if (ch == opposite) {
2979 count--; 2979 count--;
2980 if (count < 0) goto found; 2980 if (count < 0) goto found;
2981 } 2981 }
2982 } 2982 }
2983 x--; 2983 x--;
2984 } 2984 }
2985 } 2985 }
2986 return; 2986 return;
2987 2987
2988found: 2988found:
2989 //cursor position of opposite bracket 2989 //cursor position of opposite bracket
2990 bm.cursor.x = x; 2990 bm.cursor.x = x;
2991 bm.cursor.y = line; 2991 bm.cursor.y = line;
2992 //x position (start and end) of related bracket 2992 //x position (start and end) of related bracket
2993 bm.sXPos = textWidth(textLine, x); 2993 bm.sXPos = textWidth(textLine, x);
2994 a = &m_attribs[attr]; 2994 a = &m_attribs[attr];
2995 2995
2996 if (a->bold && a->italic) 2996 if (a->bold && a->italic)
2997 bm.eXPos = bm.sXPos + myFontMetricsBI.width(bracket); 2997 bm.eXPos = bm.sXPos + myFontMetricsBI.width(bracket);
2998 else if (a->bold) 2998 else if (a->bold)
2999 bm.eXPos = bm.sXPos + myFontMetricsBold.width(bracket); 2999 bm.eXPos = bm.sXPos + myFontMetricsBold.width(bracket);
3000 else if (a->italic) 3000 else if (a->italic)
3001 bm.eXPos = bm.sXPos + myFontMetricsItalic.width(bracket); 3001 bm.eXPos = bm.sXPos + myFontMetricsItalic.width(bracket);
3002 else 3002 else
3003 bm.eXPos = bm.sXPos + myFontMetrics.width(bracket); 3003 bm.eXPos = bm.sXPos + myFontMetrics.width(bracket);
3004} 3004}
3005 3005
3006void KateDocument::clipboardChanged() { //slot 3006void KateDocument::clipboardChanged() { //slot
3007//#if defined(_WS_X11_) 3007//#if defined(_WS_X11_)
3008 if (m_singleSelection) { 3008 if (m_singleSelection) {
3009 disconnect(QApplication::clipboard(), SIGNAL(dataChanged()), 3009 disconnect(QApplication::clipboard(), SIGNAL(dataChanged()),
3010 this, SLOT(clipboardChanged())); 3010 this, SLOT(clipboardChanged()));
3011 deselectAll(); 3011 deselectAll();
3012 updateViews(); 3012 updateViews();
3013 } 3013 }
3014//#endif 3014//#endif
3015} 3015}
3016 3016
3017#if 0 3017#if 0
3018void KateDocument::guiActivateEvent( KParts::GUIActivateEvent *ev ) 3018void KateDocument::guiActivateEvent( KParts::GUIActivateEvent *ev )
3019{ 3019{
3020 KParts::ReadWritePart::guiActivateEvent( ev ); 3020 KParts::ReadWritePart::guiActivateEvent( ev );
3021 if ( ev->activated() ) 3021 if ( ev->activated() )
3022 emit selectionChanged(); 3022 emit selectionChanged();
3023} 3023}
3024#endif 3024#endif
3025 3025
3026void KateDocument::setDocName (QString docName) 3026void KateDocument::setDocName (QString docName)
3027{ 3027{
3028 myDocName = docName; 3028 myDocName = docName;
3029 emit nameChanged (this); 3029 emit nameChanged (this);
3030} 3030}
3031 3031
3032void KateDocument::setDocFile (QString docFile) 3032void KateDocument::setDocFile (QString docFile)
3033{ 3033{
3034 m_file = docFile; 3034 m_file = docFile;
3035 emit fileNameChanged (); 3035 emit fileNameChanged ();
3036} 3036}
3037 3037
3038void KateDocument::setMTime() 3038void KateDocument::setMTime()
3039{ 3039{
3040 if (fileInfo && !fileInfo->fileName().isEmpty()) { 3040 if (fileInfo && !fileInfo->fileName().isEmpty()) {
3041 fileInfo->refresh(); 3041 fileInfo->refresh();
3042 mTime = fileInfo->lastModified(); 3042 mTime = fileInfo->lastModified();
3043 } 3043 }
3044} 3044}
3045 3045
3046void KateDocument::isModOnHD(bool forceReload) 3046void KateDocument::isModOnHD(bool forceReload)
3047{ 3047{
3048 if (fileInfo && !fileInfo->fileName().isEmpty()) { 3048 if (fileInfo && !fileInfo->fileName().isEmpty()) {
3049 fileInfo->refresh(); 3049 fileInfo->refresh();
3050 if (fileInfo->lastModified() > mTime) { 3050 if (fileInfo->lastModified() > mTime) {
3051 if ( forceReload || 3051 if ( forceReload ||
3052 (KMessageBox::warningContinueCancel(0, 3052 (KMessageBox::warningContinueCancel(0,
3053 (i18n("The file %1 has changed on disk.\nDo you want to reload it?\n\nIf you cancel you will lose these changes next time you save this file")).arg(m_url), 3053 (i18n("The file %1 has changed on disk.\nDo you want to reload it?\n\nIf you cancel you will lose these changes next time you save this file")).arg(m_url),
3054 i18n("File has changed on Disk"), 3054 i18n("File has changed on Disk"),
3055 i18n("Yes") ) == KMessageBox::Continue) 3055 i18n("Yes") ) == KMessageBox::Continue)
3056 ) 3056 )
3057 reloadFile(); 3057 reloadFile();
3058 else 3058 else
3059 setMTime(); 3059 setMTime();
3060 } 3060 }
3061 } 3061 }
3062} 3062}
3063 3063
3064void KateDocument::reloadFile() 3064void KateDocument::reloadFile()
3065{ 3065{
3066#warning fixme 3066#warning fixme
3067#if 0 3067#if 0
3068 if (fileInfo && !fileInfo->fileName().isEmpty()) { 3068 if (fileInfo && !fileInfo->fileName().isEmpty()) {
3069 KateDocument::openFile(); 3069 KateDocument::openFile();
3070 setMTime(); 3070 setMTime();
3071 } 3071 }
3072#endif 3072#endif
3073} 3073}
3074 3074
3075void KateDocument::slotModChanged() 3075void KateDocument::slotModChanged()
3076{ 3076{
3077 emit modStateChanged (this); 3077 emit modStateChanged (this);
3078} 3078}
3079 3079
3080QList<Kate::Mark> KateDocument::marks () 3080QList<Kate::Mark> KateDocument::marks ()
3081{ 3081{
3082 QList<Kate::Mark> list; 3082 QList<Kate::Mark> list;
3083 TextLine::Ptr line; 3083 TextLine::Ptr line;
3084 3084
3085 for (int i=0; i < numLines(); i++) 3085 for (int i=0; i < numLines(); i++)
3086 { 3086 {
3087 line = getTextLine(i); 3087 line = getTextLine(i);
3088 if (line->mark() != 0) 3088 if (line->mark() != 0)
3089 { 3089 {
3090 Kate::Mark *mark=new Kate::Mark; 3090 Kate::Mark *mark=new Kate::Mark;
3091 mark->line = i; 3091 mark->line = i;
3092 mark->type = line->mark(); 3092 mark->type = line->mark();
3093 list.append (mark); 3093 list.append (mark);
3094 } 3094 }
3095 } 3095 }
3096 3096
3097 return list; 3097 return list;
3098} 3098}
3099 3099
3100void KateDocument::flush () 3100void KateDocument::flush ()
3101{ 3101{
3102 if (isReadOnly()) 3102 if (isReadOnly())
3103 return; 3103 return;
3104 3104
3105 m_url = QString::null; 3105 m_url = QString::null;
3106 fileInfo->setFile (QString()); 3106 fileInfo->setFile (QString());
3107 setMTime(); 3107 setMTime();
3108 3108
3109 clear(); 3109 clear();
3110 updateViews(); 3110 updateViews();
3111 3111
3112 emit fileNameChanged (); 3112 emit fileNameChanged ();
3113} 3113}
3114 3114
3115void KateDocument::open (const QString &name) 3115void KateDocument::open (const QString &name)
3116{ 3116{
3117 openURL (name); 3117 openURL (name);
3118} 3118}
3119 3119
3120void KateDocument::wrapText (uint col) 3120void KateDocument::wrapText (uint col)
3121{ 3121{
3122 int line = 0; 3122 int line = 0;
3123 int z = 0; 3123 int z = 0;
3124 3124
3125 while(true) 3125 while(true)
3126 { 3126 {
3127 TextLine::Ptr l = getTextLine(line); 3127 TextLine::Ptr l = getTextLine(line);
3128 3128
3129 if (l->length() > col) 3129 if (l->length() > col)
3130 { 3130 {
3131 TextLine::Ptr tl = new TextLine(); 3131 TextLine::Ptr tl = new TextLine();
3132 buffer->insertLine(line+1,tl); 3132 buffer->insertLine(line+1,tl);
3133 const QChar *text = l->getText(); 3133 const QChar *text = l->getText();
3134 3134
3135 for (z=col; z>0; z--) 3135 for (z=col; z>0; z--)
3136 { 3136 {
3137 if (z < 1) break; 3137 if (z < 1) break;
3138 if (text[z].isSpace()) break; 3138 if (text[z].isSpace()) break;
3139 } 3139 }
3140 3140
3141 if (z < 1) z=col; 3141 if (z < 1) z=col;
3142 3142
3143 l->wrap (tl, z); 3143 l->wrap (tl, z);
3144 } 3144 }
3145 3145
3146 line++; 3146 line++;
3147 if (line >= numLines()) break; 3147 if (line >= numLines()) break;
3148 }; 3148 };
3149 3149
3150 newDocGeometry=true; 3150 newDocGeometry=true;
3151 updateLines(); 3151 updateLines();
3152 updateViews(); 3152 updateViews();
3153} 3153}
3154 3154
3155void KateDocument::setWordWrap (bool on) 3155void KateDocument::setWordWrap (bool on)
3156{ 3156{
3157 if (on != myWordWrap && on) 3157 if (on != myWordWrap && on)
3158 wrapText (myWordWrapAt); 3158 wrapText (myWordWrapAt);
3159 3159
3160 myWordWrap = on; 3160 myWordWrap = on;
3161} 3161}
3162 3162
3163void KateDocument::setWordWrapAt (uint col) 3163void KateDocument::setWordWrapAt (uint col)
3164{ 3164{
3165 if (myWordWrapAt != col && myWordWrap) 3165 if (myWordWrapAt != col && myWordWrap)
3166 wrapText (myWordWrapAt); 3166 wrapText (myWordWrapAt);
3167 3167
3168 myWordWrapAt = col; 3168 myWordWrapAt = col;
3169} 3169}
3170 3170
3171void KateDocument::applyWordWrap () 3171void KateDocument::applyWordWrap ()
3172{ 3172{
3173 wrapText (myWordWrapAt); 3173 wrapText (myWordWrapAt);
3174} 3174}
diff --git a/noncore/apps/tinykate/libkate/view/kateviewdialog.cpp b/noncore/apps/tinykate/libkate/view/kateviewdialog.cpp
index a85fb87..8e68262 100644
--- a/noncore/apps/tinykate/libkate/view/kateviewdialog.cpp
+++ b/noncore/apps/tinykate/libkate/view/kateviewdialog.cpp
@@ -1,571 +1,571 @@
1/*************************************************************************** 1/***************************************************************************
2 kateviewdialog.cpp - description 2 kateviewdialog.cpp - description
3 ------------------- 3 -------------------
4 copyright : (C) 2001 by The Kate Team 4 copyright : (C) 2001 by The Kate Team
5 (C) 2002 by Joseph Wenninger 5 (C) 2002 by Joseph Wenninger
6 email : kwrite-devel@kde.org 6 email : kwrite-devel@kde.org
7 jowenn@kde.org 7 jowenn@kde.org
8 8
9 ***************************************************************************/ 9 ***************************************************************************/
10 10
11/*************************************************************************** 11/***************************************************************************
12 * * 12 * *
13 * This program is free software; you can redistribute it and/or modify * 13 * This program is free software; you can redistribute it and/or modify *
14 * it under the terms of the GNU General Public License as published by * 14 * it under the terms of the GNU General Public License as published by *
15 * the Free Software Foundation; either version 2 of the License, or * 15 * the Free Software Foundation; either version 2 of the License, or *
16 * (at your option) any later version. * 16 * (at your option) any later version. *
17 * * 17 * *
18 ***************************************************************************/ 18 ***************************************************************************/
19// Dialogs 19// Dialogs
20 20
21#include <stdio.h> 21#include <stdio.h>
22#include <stdlib.h> 22#include <stdlib.h>
23 23
24#include <qgrid.h> 24#include <qgrid.h>
25#include <qlabel.h> 25#include <qlabel.h>
26#include <qlayout.h> 26#include <qlayout.h>
27#include <qlistbox.h> 27#include <qlistbox.h>
28#include <qgroupbox.h> 28#include <qgroupbox.h>
29#include <qlineedit.h> 29#include <qlineedit.h>
30#include <qcheckbox.h> 30#include <qcheckbox.h>
31#include <qcollection.h> 31#include <qcollection.h>
32#include <qpushbutton.h> 32#include <qpushbutton.h>
33#include <qobjectlist.h> 33#include <qobjectlist.h>
34#include <qradiobutton.h> 34#include <qradiobutton.h>
35#include <qwhatsthis.h> 35#include <qwhatsthis.h>
36#include <qstringlist.h> 36#include <qstringlist.h>
37#include <klocale.h> 37#include <klocale.h>
38#include <kcolorbtn.h> 38#include <kcolorbtn.h>
39#include <kglobal.h> 39#include <kglobal.h>
40#include <qvbox.h> 40#include <qvbox.h>
41#include <qspinbox.h> 41#include <qspinbox.h>
42#include <qcombobox.h> 42#include <qcombobox.h>
43#include <kfontdialog.h> 43#include <kfontdialog.h>
44 44
45#include "../document/katedocument.h" 45#include "../document/katedocument.h"
46#include "kateviewdialog.h" 46#include "kateviewdialog.h"
47#include <opie2/ofontselector.h> 47#include <opie2/ofontselector.h>
48 48
49 49
50SearchDialog::SearchDialog( QWidget *parent, QStringList &searchFor, QStringList &replaceWith, int flags ) 50SearchDialog::SearchDialog( QWidget *parent, QStringList &searchFor, QStringList &replaceWith, int flags )
51 : KDialogBase( parent, 0L, true, i18n( "Find Text" ), Ok | Cancel, Ok ) 51 : KDialogBase( parent, 0L, true, i18n( "Find Text" ), Ok | Cancel, Ok )
52 , m_replace( 0L ) 52 , m_replace( 0L )
53{ 53{
54 QWidget *page = new QWidget( this ); 54 QWidget *page = new QWidget( this );
55 setMainWidget( page ); 55 setMainWidget( page );
56 56
57 QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); 57 QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() );
58 58
59 m_search = new QComboBox( true, page ); 59 m_search = new QComboBox( true, page );
60 m_search->insertStringList( searchFor ); 60 m_search->insertStringList( searchFor );
61 m_search->setMinimumWidth( m_search->sizeHint().width() ); 61 m_search->setMinimumWidth( m_search->sizeHint().width() );
62 m_search->lineEdit()->selectAll(); 62 m_search->lineEdit()->selectAll();
63 QLabel *label = new QLabel( m_search, i18n( "&Text To Find:" ), page ); 63 QLabel *label = new QLabel( m_search, i18n( "&Text To Find:" ), page );
64 m_optRegExp = new QCheckBox( i18n( "Regular Expression" ), page ); 64 m_optRegExp = new QCheckBox( i18n( "Regular Expression" ), page );
65 topLayout->addWidget( label ); 65 topLayout->addWidget( label );
66 topLayout->addWidget( m_search ); 66 topLayout->addWidget( m_search );
67 topLayout->addWidget( m_optRegExp ); 67 topLayout->addWidget( m_optRegExp );
68 68
69 if( flags & KateView::sfReplace ) 69 if( flags & KateView::sfReplace )
70 { 70 {
71 // make it a replace dialog 71 // make it a replace dialog
72 setCaption( i18n( "Replace Text" ) ); 72 setCaption( i18n( "Replace Text" ) );
73 m_replace = new QComboBox( true, page ); 73 m_replace = new QComboBox( true, page );
74 m_replace->insertStringList( replaceWith ); 74 m_replace->insertStringList( replaceWith );
75 m_replace->setMinimumWidth( m_search->sizeHint().width() ); 75 m_replace->setMinimumWidth( m_search->sizeHint().width() );
76 label = new QLabel( m_replace, i18n( "&Replace With:" ), page ); 76 label = new QLabel( m_replace, i18n( "&Replace With:" ), page );
77 //m_optPlaceholders = new QCheckBox( i18n( "&Use Placeholders" ), page ); 77 //m_optPlaceholders = new QCheckBox( i18n( "&Use Placeholders" ), page );
78 topLayout->addWidget( label ); 78 topLayout->addWidget( label );
79 topLayout->addWidget( m_replace ); 79 topLayout->addWidget( m_replace );
80 //topLayout->addWidget( m_optPlaceholders ); 80 //topLayout->addWidget( m_optPlaceholders );
81 } 81 }
82 82
83 QGroupBox *group = new QGroupBox( i18n( "Options" ), page ); 83 QGroupBox *group = new QGroupBox( i18n( "Options" ), page );
84 topLayout->addWidget( group, 10 ); 84 topLayout->addWidget( group, 10 );
85 85
86 QGridLayout *gbox = new QGridLayout( group, 5, 2, spacingHint() ); 86 QGridLayout *gbox = new QGridLayout( group, 5, 2, spacingHint() );
87 gbox->addRowSpacing( 0, fontMetrics().lineSpacing() ); 87 gbox->addRowSpacing( 0, fontMetrics().lineSpacing() );
88 gbox->setRowStretch( 4, 10 ); 88 gbox->setRowStretch( 4, 10 );
89 89
90 m_opt1 = new QCheckBox( i18n( "C&ase Sensitive" ), group ); 90 m_opt1 = new QCheckBox( i18n( "C&ase Sensitive" ), group );
91 gbox->addWidget( m_opt1, 1, 0 ); 91 gbox->addWidget( m_opt1, 1, 0 );
92 92
93 m_opt2 = new QCheckBox(i18n("&Whole Words Only" ), group ); 93 m_opt2 = new QCheckBox(i18n("&Whole Words Only" ), group );
94 gbox->addWidget( m_opt2, 2, 0 ); 94 gbox->addWidget( m_opt2, 2, 0 );
95 95
96 m_opt3 = new QCheckBox(i18n("&From Beginning" ), group ); 96 m_opt3 = new QCheckBox(i18n("&From Beginning" ), group );
97 gbox->addWidget( m_opt3, 3, 0 ); 97 gbox->addWidget( m_opt3, 3, 0 );
98 98
99 m_opt4 = new QCheckBox(i18n("Find &Backwards" ), group ); 99 m_opt4 = new QCheckBox(i18n("Find &Backwards" ), group );
100 gbox->addWidget( m_opt4, 1, 1 ); 100 gbox->addWidget( m_opt4, 1, 1 );
101 101
102 m_opt5 = new QCheckBox(i18n("&Selected Text" ), group ); 102 m_opt5 = new QCheckBox(i18n("&Selected Text" ), group );
103 gbox->addWidget( m_opt5, 2, 1 ); 103 gbox->addWidget( m_opt5, 2, 1 );
104 104
105 m_opt1->setChecked( flags & KateView::sfCaseSensitive ); 105 m_opt1->setChecked( flags & KateView::sfCaseSensitive );
106 m_opt2->setChecked( flags & KateView::sfWholeWords ); 106 m_opt2->setChecked( flags & KateView::sfWholeWords );
107 m_opt3->setChecked( flags & KateView::sfFromBeginning ); 107 m_opt3->setChecked( flags & KateView::sfFromBeginning );
108 m_optRegExp->setChecked( flags & KateView::sfRegularExpression ); 108 m_optRegExp->setChecked( flags & KateView::sfRegularExpression );
109 m_opt4->setChecked( flags & KateView::sfBackward ); 109 m_opt4->setChecked( flags & KateView::sfBackward );
110 m_opt5->setChecked( flags & KateView::sfSelected ); 110 m_opt5->setChecked( flags & KateView::sfSelected );
111 111
112 if( m_replace ) 112 if( m_replace )
113 { 113 {
114 m_opt6 = new QCheckBox( i18n( "&Prompt On Replace" ), group ); 114 m_opt6 = new QCheckBox( i18n( "&Prompt On Replace" ), group );
115 m_opt6->setChecked( flags & KateView::sfPrompt ); 115 m_opt6->setChecked( flags & KateView::sfPrompt );
116 gbox->addWidget( m_opt6, 3, 1 ); 116 gbox->addWidget( m_opt6, 3, 1 );
117 } 117 }
118 118
119 m_search->setFocus(); 119 m_search->setFocus();
120} 120}
121 121
122QString SearchDialog::getSearchFor() 122QString SearchDialog::getSearchFor()
123{ 123{
124 return m_search->currentText(); 124 return m_search->currentText();
125} 125}
126 126
127QString SearchDialog::getReplaceWith() 127QString SearchDialog::getReplaceWith()
128{ 128{
129 return m_replace->currentText(); 129 return m_replace->currentText();
130} 130}
131 131
132int SearchDialog::getFlags() 132int SearchDialog::getFlags()
133{ 133{
134 int flags = 0; 134 int flags = 0;
135 135
136 if( m_opt1->isChecked() ) flags |= KateView::sfCaseSensitive; 136 if( m_opt1->isChecked() ) flags |= KateView::sfCaseSensitive;
137 if( m_opt2->isChecked() ) flags |= KateView::sfWholeWords; 137 if( m_opt2->isChecked() ) flags |= KateView::sfWholeWords;
138 if( m_opt3->isChecked() ) flags |= KateView::sfFromBeginning; 138 if( m_opt3->isChecked() ) flags |= KateView::sfFromBeginning;
139 if( m_opt4->isChecked() ) flags |= KateView::sfBackward; 139 if( m_opt4->isChecked() ) flags |= KateView::sfBackward;
140 if( m_opt5->isChecked() ) flags |= KateView::sfSelected; 140 if( m_opt5->isChecked() ) flags |= KateView::sfSelected;
141 if( m_optRegExp->isChecked() ) flags |= KateView::sfRegularExpression; 141 if( m_optRegExp->isChecked() ) flags |= KateView::sfRegularExpression;
142 if( m_replace ) 142 if( m_replace )
143 { 143 {
144 if( m_opt6->isChecked() ) 144 if( m_opt6->isChecked() )
145 flags |= KateView::sfPrompt; 145 flags |= KateView::sfPrompt;
146 146
147 flags |= KateView::sfReplace; 147 flags |= KateView::sfReplace;
148 } 148 }
149 149
150 return flags; 150 return flags;
151} 151}
152 152
153void SearchDialog::slotOk() 153void SearchDialog::slotOk()
154{ 154{
155 if ( !m_search->currentText().isEmpty() ) 155 if ( !m_search->currentText().isEmpty() )
156 { 156 {
157 if ( !m_optRegExp->isChecked() ) 157 if ( !m_optRegExp->isChecked() )
158 { 158 {
159 accept(); 159 accept();
160 } 160 }
161 else 161 else
162 { 162 {
163 // Check for a valid regular expression. 163 // Check for a valid regular expression.
164 164
165 QRegExp regExp( m_search->currentText() ); 165 QRegExp regExp( m_search->currentText() );
166 166
167 if ( regExp.isValid() ) 167 if ( regExp.isValid() )
168 accept(); 168 accept();
169 } 169 }
170 } 170 }
171} 171}
172 172
173void SearchDialog::setSearchText( const QString &searchstr ) 173void SearchDialog::setSearchText( const QString &searchstr )
174 { 174 {
175 m_search->insertItem( searchstr, 0 ); 175 m_search->insertItem( searchstr, 0 );
176 m_search->setCurrentItem( 0 ); 176 m_search->setCurrentItem( 0 );
177 m_search->lineEdit()->selectAll(); 177 m_search->lineEdit()->selectAll();
178 } 178 }
179 179
180// this dialog is not modal 180// this dialog is not modal
181ReplacePrompt::ReplacePrompt( QWidget *parent ) 181ReplacePrompt::ReplacePrompt( QWidget *parent )
182 : KDialogBase(parent, 0L, false, i18n( "Replace Text" ), 182 : KDialogBase(parent, 0L, false, i18n( "Replace Text" ),
183 User3 | User2 | User1 | Close, User3, true, 183 User3 | User2 | User1 | Close, User3, true,
184 i18n("&All"), i18n("&No"), i18n("&Yes")) { 184 i18n("&All"), i18n("&No"), i18n("&Yes")) {
185 185
186 QWidget *page = new QWidget(this); 186 QWidget *page = new QWidget(this);
187 setMainWidget(page); 187 setMainWidget(page);
188 188
189 QBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); 189 QBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() );
190 QLabel *label = new QLabel(i18n("Replace this occurence?"),page); 190 QLabel *label = new QLabel(i18n("Replace this occurence?"),page);
191 topLayout->addWidget(label ); 191 topLayout->addWidget(label );
192} 192}
193 193
194void ReplacePrompt::slotUser1( void ) { // All 194void ReplacePrompt::slotUser1( void ) { // All
195 done(KateView::srAll); 195 done(KateView::srAll);
196} 196}
197 197
198void ReplacePrompt::slotUser2( void ) { // No 198void ReplacePrompt::slotUser2( void ) { // No
199 done(KateView::srNo); 199 done(KateView::srNo);
200} 200}
201 201
202void ReplacePrompt::slotUser3( void ) { // Yes 202void ReplacePrompt::slotUser3( void ) { // Yes
203 accept(); 203 accept();
204} 204}
205 205
206void ReplacePrompt::done(int r) { 206void ReplacePrompt::done(int r) {
207 setResult(r); 207 setResult(r);
208 emit clicked(); 208 emit clicked();
209} 209}
210 210
211void ReplacePrompt::closeEvent(QCloseEvent *) { 211void ReplacePrompt::closeEvent(QCloseEvent *) {
212 reject(); 212 reject();
213} 213}
214 214
215GotoLineDialog::GotoLineDialog(QWidget *parent, int line, int max) 215GotoLineDialog::GotoLineDialog(QWidget *parent, int line, int max)
216 : KDialogBase(parent, 0L, true, i18n("Goto Line"), Ok | Cancel, Ok) { 216 : KDialogBase(parent, 0L, true, i18n("Goto Line"), Ok | Cancel, Ok) {
217 217
218 QWidget *page = new QWidget(this); 218 QWidget *page = new QWidget(this);
219 setMainWidget(page); 219 setMainWidget(page);
220 220
221 QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() ); 221 QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() );
222 e1 = new QSpinBox(page); 222 e1 = new QSpinBox(page);
223 e1->setMinValue(1); 223 e1->setMinValue(1);
224 e1->setMaxValue(max); 224 e1->setMaxValue(max);
225 e1->setValue((int)line); 225 e1->setValue((int)line);
226 226
227 QLabel *label = new QLabel( e1,i18n("&Goto Line:"), page ); 227 QLabel *label = new QLabel( e1,i18n("&Goto Line:"), page );
228 topLayout->addWidget(label); 228 topLayout->addWidget(label);
229 topLayout->addWidget(e1); 229 topLayout->addWidget(e1);
230 topLayout->addSpacing(spacingHint()); // A little bit extra space 230 topLayout->addSpacing(spacingHint()); // A little bit extra space
231 topLayout->addStretch(10); 231 topLayout->addStretch(10);
232 e1->setFocus(); 232 e1->setFocus();
233} 233}
234 234
235int GotoLineDialog::getLine() { 235int GotoLineDialog::getLine() {
236 return e1->value(); 236 return e1->value();
237} 237}
238 238
239const int IndentConfigTab::flags[] = {KateView::cfAutoIndent, KateView::cfSpaceIndent, 239const int IndentConfigTab::flags[] = {KateView::cfAutoIndent, KateView::cfSpaceIndent,
240 KateView::cfBackspaceIndents,KateView::cfTabIndents, KateView::cfKeepIndentProfile, KateView::cfKeepExtraSpaces}; 240 KateView::cfBackspaceIndents,KateView::cfTabIndents, KateView::cfKeepIndentProfile, KateView::cfKeepExtraSpaces};
241 241
242IndentConfigTab::IndentConfigTab(QWidget *parent, KateView *view) 242IndentConfigTab::IndentConfigTab(QWidget *parent, KateView *view)
243 : QWidget(parent, 0L) 243 : QWidget(parent, 0L)
244{ 244{
245 QVBoxLayout *layout = new QVBoxLayout(this, 0, KDialog::spacingHint() ); 245 QVBoxLayout *layout = new QVBoxLayout(this, 0, KDialog::spacingHint() );
246 int configFlags = view->config(); 246 int configFlags = view->config();
247 247
248 opt[0] = new QCheckBox(i18n("&Auto Indent"), this); 248 opt[0] = new QCheckBox(i18n("&Auto Indent"), this);
249 layout->addWidget(opt[0], 0, AlignLeft); 249 layout->addWidget(opt[0], 0, AlignLeft);
250 opt[0]->setChecked(configFlags & flags[0]); 250 opt[0]->setChecked(configFlags & flags[0]);
251 251
252 opt[1] = new QCheckBox(i18n("Indent With &Spaces"), this); 252 opt[1] = new QCheckBox(i18n("Indent With &Spaces"), this);
253 layout->addWidget(opt[1], 0, AlignLeft); 253 layout->addWidget(opt[1], 0, AlignLeft);
254 opt[1]->setChecked(configFlags & flags[1]); 254 opt[1]->setChecked(configFlags & flags[1]);
255 255
256 opt[2] = new QCheckBox(i18n("&Backspace Key Indents"), this); 256 opt[2] = new QCheckBox(i18n("&Backspace Key Indents"), this);
257 layout->addWidget(opt[2], 0, AlignLeft); 257 layout->addWidget(opt[2], 0, AlignLeft);
258 opt[2]->setChecked(configFlags & flags[2]); 258 opt[2]->setChecked(configFlags & flags[2]);
259 259
260 opt[3] = new QCheckBox(i18n("&Tab Key Indents"), this); 260 opt[3] = new QCheckBox(i18n("&Tab Key Indents"), this);
261 layout->addWidget(opt[3], 0, AlignLeft); 261 layout->addWidget(opt[3], 0, AlignLeft);
262 opt[3]->setChecked(configFlags & flags[3]); 262 opt[3]->setChecked(configFlags & flags[3]);
263 263
264 opt[4] = new QCheckBox(i18n("Keep Indent &Profile"), this); 264 opt[4] = new QCheckBox(i18n("Keep Indent &Profile"), this);
265 layout->addWidget(opt[4], 0, AlignLeft); 265 layout->addWidget(opt[4], 0, AlignLeft);
266// opt[4]->setChecked(configFlags & flags[4]); 266// opt[4]->setChecked(configFlags & flags[4]);
267 opt[4]->setChecked(true); 267 opt[4]->setChecked(true);
268 opt[4]->hide(); 268 opt[4]->hide();
269 269
270 opt[5] = new QCheckBox(i18n("&Keep Extra Spaces"), this); 270 opt[5] = new QCheckBox(i18n("&Keep Extra Spaces"), this);
271 layout->addWidget(opt[5], 0, AlignLeft); 271 layout->addWidget(opt[5], 0, AlignLeft);
272 opt[5]->setChecked(configFlags & flags[5]); 272 opt[5]->setChecked(configFlags & flags[5]);
273 273
274 layout->addStretch(); 274 layout->addStretch();
275 275
276 // What is this? help 276 // What is this? help
277 QWhatsThis::add(opt[0], i18n("When <b>Auto indent</b> is on, KateView will indent new lines to equal the indent on the previous line.<p>If the previous line is blank, the nearest line above with text is used")); 277 QWhatsThis::add(opt[0], i18n("When <b>Auto indent</b> is on, KateView will indent new lines to equal the indent on the previous line.<p>If the previous line is blank, the nearest line above with text is used"));
278 QWhatsThis::add(opt[1], i18n("Check this if you want to indent with spaces rather than tabs.<br>A Tab will be converted to <u>Tab-width</u> as set in the <b>edit</b> options")); 278 QWhatsThis::add(opt[1], i18n("Check this if you want to indent with spaces rather than tabs.<br>A Tab will be converted to <u>Tab-width</u> as set in the <b>edit</b> options"));
279 QWhatsThis::add(opt[2], i18n("This allows the <b>backspace</b> key to be used to indent.")); 279 QWhatsThis::add(opt[2], i18n("This allows the <b>backspace</b> key to be used to indent."));
280 QWhatsThis::add(opt[3], i18n("This allows the <b>tab</b> key to be used to indent.")); 280 QWhatsThis::add(opt[3], i18n("This allows the <b>tab</b> key to be used to indent."));
281 QWhatsThis::add(opt[4], i18n("This retains current indentation settings for future documents.")); 281 QWhatsThis::add(opt[4], i18n("This retains current indentation settings for future documents."));
282 QWhatsThis::add(opt[5], i18n("Indentations of more than the selected number of spaces will not be shortened.")); 282 QWhatsThis::add(opt[5], i18n("Indentations of more than the selected number of spaces will not be shortened."));
283} 283}
284 284
285void IndentConfigTab::getData(KateView *view) { 285void IndentConfigTab::getData(KateView *view) {
286 int configFlags, z; 286 int configFlags, z;
287 287
288 configFlags = view->config(); 288 configFlags = view->config();
289 for (z = 0; z < numFlags; z++) { 289 for (z = 0; z < numFlags; z++) {
290 configFlags &= ~flags[z]; 290 configFlags &= ~flags[z];
291 if (opt[z]->isChecked()) configFlags |= flags[z]; 291 if (opt[z]->isChecked()) configFlags |= flags[z];
292 } 292 }
293 view->setConfig(configFlags); 293 view->setConfig(configFlags);
294} 294}
295 295
296const int SelectConfigTab::flags[] = {KateView::cfPersistent, KateView::cfDelOnInput, 296const int SelectConfigTab::flags[] = {KateView::cfPersistent, KateView::cfDelOnInput,
297 KateView::cfMouseAutoCopy, KateView::cfSingleSelection, KateView::cfVerticalSelect, KateView::cfXorSelect}; 297 KateView::cfMouseAutoCopy, KateView::cfSingleSelection, KateView::cfVerticalSelect, KateView::cfXorSelect};
298 298
299SelectConfigTab::SelectConfigTab(QWidget *parent, KateView *view) 299SelectConfigTab::SelectConfigTab(QWidget *parent, KateView *view)
300 : QWidget(parent, 0L) 300 : QWidget(parent, 0L)
301{ 301{
302 QVBoxLayout *layout = new QVBoxLayout(this, 0, KDialog::spacingHint() ); 302 QVBoxLayout *layout = new QVBoxLayout(this, 0, KDialog::spacingHint() );
303 int configFlags = view->config(); 303 int configFlags = view->config();
304 304
305 opt[0] = new QCheckBox(i18n("&Persistent Selections"), this); 305 opt[0] = new QCheckBox(i18n("&Persistent Selections"), this);
306 layout->addWidget(opt[0], 0, AlignLeft); 306 layout->addWidget(opt[0], 0, AlignLeft);
307 opt[0]->setChecked(configFlags & flags[0]); 307 opt[0]->setChecked(configFlags & flags[0]);
308 308
309 opt[1] = new QCheckBox(i18n("&Overwrite Selections"), this); 309 opt[1] = new QCheckBox(i18n("&Overwrite Selections"), this);
310 layout->addWidget(opt[1], 0, AlignLeft); 310 layout->addWidget(opt[1], 0, AlignLeft);
311 opt[1]->setChecked(configFlags & flags[1]); 311 opt[1]->setChecked(configFlags & flags[1]);
312 312
313 opt[2] = new QCheckBox(i18n("Mouse &Autocopy"), this); 313 opt[2] = new QCheckBox(i18n("Mouse &Autocopy"), this);
314 layout->addWidget(opt[2], 0, AlignLeft); 314 layout->addWidget(opt[2], 0, AlignLeft);
315 opt[2]->setChecked(configFlags & flags[2]); 315 opt[2]->setChecked(configFlags & flags[2]);
316 316
317 opt[3] = new QCheckBox(i18n("&X11-like Single Selection"), this); 317 opt[3] = new QCheckBox(i18n("&X11-like Single Selection"), this);
318 layout->addWidget(opt[3], 0, AlignLeft); 318 layout->addWidget(opt[3], 0, AlignLeft);
319 opt[3]->setChecked(configFlags & flags[3]); 319 opt[3]->setChecked(configFlags & flags[3]);
320 320
321 opt[4] = new QCheckBox(i18n("&Vertical Selections"), this); 321 opt[4] = new QCheckBox(i18n("&Vertical Selections"), this);
322 layout->addWidget(opt[4], 0, AlignLeft); 322 layout->addWidget(opt[4], 0, AlignLeft);
323 opt[4]->setChecked(configFlags & flags[4]); 323 opt[4]->setChecked(configFlags & flags[4]);
324 324
325 opt[5] = new QCheckBox(i18n("&Toggle Old"), this); 325 opt[5] = new QCheckBox(i18n("&Toggle Old"), this);
326 layout->addWidget(opt[5], 0, AlignLeft); 326 layout->addWidget(opt[5], 0, AlignLeft);
327 opt[5]->setChecked(configFlags & flags[5]); 327 opt[5]->setChecked(configFlags & flags[5]);
328 328
329 layout->addStretch(); 329 layout->addStretch();
330 330
331 // What is this? help 331 // What is this? help
332 QWhatsThis::add(opt[0], i18n("Enabling this prevents key input or cursor movement by way of the arrow keys from causing the elimination of text selection.<p><b>Note:</b> If the Overwrite Selections option is activated then any typed character input or paste operation will replace the selected text.")); 332 QWhatsThis::add(opt[0], i18n("Enabling this prevents key input or cursor movement by way of the arrow keys from causing the elimination of text selection.<p><b>Note:</b> If the Overwrite Selections option is activated then any typed character input or paste operation will replace the selected text."));
333 QWhatsThis::add(opt[1], i18n("When this is on, any keyed character input or paste operation will replace the selected text.")); 333 QWhatsThis::add(opt[1], i18n("When this is on, any keyed character input or paste operation will replace the selected text."));
334 QWhatsThis::add(opt[2], i18n("When this is on, any text selected with the mouse will be automatically copied to the clipboard.")); 334 QWhatsThis::add(opt[2], i18n("When this is on, any text selected with the mouse will be automatically copied to the clipboard."));
335 QWhatsThis::add(opt[3], i18n("Not implemented yet.")); 335 QWhatsThis::add(opt[3], i18n("Not implemented yet."));
336 QWhatsThis::add(opt[4], i18n("Enabling this allows you to make vertical selections.")); 336 QWhatsThis::add(opt[4], i18n("Enabling this allows you to make vertical selections."));
337 QWhatsThis::add(opt[5], i18n("Not yet implemented.")); 337 QWhatsThis::add(opt[5], i18n("Not yet implemented."));
338} 338}
339 339
340void SelectConfigTab::getData(KateView *view) { 340void SelectConfigTab::getData(KateView *view) {
341 int configFlags, z; 341 int configFlags, z;
342 342
343 configFlags = view->config(); 343 configFlags = view->config();
344 for (z = 0; z < numFlags; z++) { 344 for (z = 0; z < numFlags; z++) {
345 configFlags &= ~flags[z]; // clear flag 345 configFlags &= ~flags[z]; // clear flag
346 if (opt[z]->isChecked()) configFlags |= flags[z]; // set flag if checked 346 if (opt[z]->isChecked()) configFlags |= flags[z]; // set flag if checked
347 } 347 }
348 view->setConfig(configFlags); 348 view->setConfig(configFlags);
349} 349}
350 350
351const int EditConfigTab::flags[] = {KateView::cfWordWrap, KateView::cfReplaceTabs, KateView::cfRemoveSpaces, 351const int EditConfigTab::flags[] = {KateView::cfWordWrap, KateView::cfReplaceTabs, KateView::cfRemoveSpaces,
352 KateView::cfAutoBrackets, KateView::cfGroupUndo, KateView::cfShowTabs, KateView::cfSmartHome, 352 KateView::cfAutoBrackets, KateView::cfGroupUndo, KateView::cfShowTabs, KateView::cfSmartHome,
353 KateView::cfPageUDMovesCursor, KateView::cfWrapCursor}; 353 KateView::cfPageUDMovesCursor, KateView::cfWrapCursor};
354 354
355EditConfigTab::EditConfigTab(QWidget *parent, KateView *view) 355EditConfigTab::EditConfigTab(QWidget *parent, KateView *view)
356 : QWidget(parent, 0L) { 356 : QWidget(parent, 0L) {
357 357
358 QHBoxLayout *mainLayout; 358 QHBoxLayout *mainLayout;
359 QVBoxLayout *cbLayout, *leLayout; 359 QVBoxLayout *cbLayout, *leLayout;
360 int configFlags; 360 int configFlags;
361 361
362 mainLayout = new QHBoxLayout(this, 0, KDialog::spacingHint() ); 362 mainLayout = new QHBoxLayout(this, 0, KDialog::spacingHint() );
363 363
364 // checkboxes 364 // checkboxes
365 cbLayout = new QVBoxLayout( mainLayout ); 365 cbLayout = new QVBoxLayout( mainLayout );
366 configFlags = view->config(); 366 configFlags = view->config();
367 367
368 opt[0] = new QCheckBox(i18n("&Word wrap"), this); 368 opt[0] = new QCheckBox(i18n("&Word wrap"), this);
369 cbLayout->addWidget(opt[0], 0, AlignLeft); 369 cbLayout->addWidget(opt[0], 0, AlignLeft);
370 opt[0]->setChecked(view->doc()->wordWrap()); 370 opt[0]->setChecked(view->doc()->wordWrap());
371 371
372 opt[1] = new QCheckBox(i18n("Replace &tabs with spaces"), this); 372 opt[1] = new QCheckBox(i18n("Replace &tabs with spaces"), this);
373 cbLayout->addWidget(opt[1], 0, AlignLeft); 373 cbLayout->addWidget(opt[1], 0, AlignLeft);
374 opt[1]->setChecked(configFlags & flags[1]); 374 opt[1]->setChecked(configFlags & flags[1]);
375 375
376 opt[2] = new QCheckBox(i18n("&Remove trailing spaces"), this); 376 opt[2] = new QCheckBox(i18n("&Remove trailing spaces"), this);
377 cbLayout->addWidget(opt[2], 0, AlignLeft); 377 cbLayout->addWidget(opt[2], 0, AlignLeft);
378 opt[2]->setChecked(configFlags & flags[2]); 378 opt[2]->setChecked(configFlags & flags[2]);
379 379
380 opt[3] = new QCheckBox(i18n("&Auto brackets"), this); 380 opt[3] = new QCheckBox(i18n("&Auto brackets"), this);
381 cbLayout->addWidget(opt[3], 0, AlignLeft); 381 cbLayout->addWidget(opt[3], 0, AlignLeft);
382 opt[3]->setChecked(configFlags & flags[3]); 382 opt[3]->setChecked(configFlags & flags[3]);
383 383
384 opt[4] = new QCheckBox(i18n("Group &undos"), this); 384 opt[4] = new QCheckBox(i18n("Group &undos"), this);
385 cbLayout->addWidget(opt[4], 0, AlignLeft); 385 cbLayout->addWidget(opt[4], 0, AlignLeft);
386 opt[4]->setChecked(configFlags & flags[4]); 386 opt[4]->setChecked(configFlags & flags[4]);
387 387
388 opt[5] = new QCheckBox(i18n("&Show tabs"), this); 388 opt[5] = new QCheckBox(i18n("&Show tabs"), this);
389 cbLayout->addWidget(opt[5], 0, AlignLeft); 389 cbLayout->addWidget(opt[5], 0, AlignLeft);
390 opt[5]->setChecked(configFlags & flags[5]); 390 opt[5]->setChecked(configFlags & flags[5]);
391 391
392 opt[6] = new QCheckBox(i18n("Smart &home"), this); 392 opt[6] = new QCheckBox(i18n("Smart &home"), this);
393 cbLayout->addWidget(opt[6], 0, AlignLeft); 393 cbLayout->addWidget(opt[6], 0, AlignLeft);
394 opt[6]->setChecked(configFlags & flags[6]); 394 opt[6]->setChecked(configFlags & flags[6]);
395 395
396 opt[7] = new QCheckBox(i18n("&Page up/down moves cursor"), this); 396 opt[7] = new QCheckBox(i18n("&Page up/down moves cursor"), this);
397 cbLayout->addWidget(opt[7], 0, AlignLeft); 397 cbLayout->addWidget(opt[7], 0, AlignLeft);
398 opt[7]->setChecked(configFlags & flags[7]); 398 opt[7]->setChecked(configFlags & flags[7]);
399 399
400 opt[8] = new QCheckBox(i18n("Wrap &cursor"), this); 400 opt[8] = new QCheckBox(i18n("Wrap &cursor"), this);
401 cbLayout->addWidget(opt[8], 0, AlignLeft); 401 cbLayout->addWidget(opt[8], 0, AlignLeft);
402 opt[8]->setChecked(configFlags & flags[8]); 402 opt[8]->setChecked(configFlags & flags[8]);
403 403
404 cbLayout->addStretch(); 404 cbLayout->addStretch();
405 405
406 // edit lines 406 // edit lines
407 leLayout = new QVBoxLayout(); 407 leLayout = new QVBoxLayout();
408 mainLayout->addLayout(leLayout,10); 408 mainLayout->addLayout(leLayout,10);
409 409
410 e1 = new QSpinBox(this); 410 e1 = new QSpinBox(this);
411 e1->setMinValue(20); 411 e1->setMinValue(20);
412 e1->setMaxValue( 200); 412 e1->setMaxValue( 200);
413 e1->setValue((int)(view->doc()->wordWrapAt())); 413 e1->setValue((int)(view->doc()->wordWrapAt()));
414#warning fixme e1->setLabel(i18n("Wrap Words At:")); 414#warning fixme e1->setLabel(i18n("Wrap Words At:"));
415 415
416 e2 = new QSpinBox(this); 416 e2 = new QSpinBox(this);
417 e2->setMinValue(1); 417 e2->setMinValue(1);
418 e2->setMaxValue(16); 418 e2->setMaxValue(16);
419 e2->setValue((int)view->tabWidth()); 419 e2->setValue((int)view->tabWidth());
420 420
421#warning fixme e2->setLabel(i18n("Tab/Indent Width:")); 421#warning fixme e2->setLabel(i18n("Tab/Indent Width:"));
422 422
423 e3 = new QSpinBox(this); 423 e3 = new QSpinBox(this);
424 e3->setMinValue(5); 424 e3->setMinValue(5);
425 e3->setMaxValue( 30000); 425 e3->setMaxValue( 30000);
426#warning fixme e3->setLabel(i18n("Undo steps:")); 426#warning fixme e3->setLabel(i18n("Undo steps:"));
427 e3->setValue((int)view->undoSteps()); 427 e3->setValue((int)view->undoSteps());
428 428
429 leLayout->addWidget(e1, 0, AlignLeft); 429 leLayout->addWidget(e1, 0, AlignLeft);
430 leLayout->addWidget(e2, 0, AlignLeft); 430 leLayout->addWidget(e2, 0, AlignLeft);
431 leLayout->addWidget(e3, 0, AlignLeft); 431 leLayout->addWidget(e3, 0, AlignLeft);
432 432
433 433
434 QVBox *box = new QVBox (this); 434 QVBox *box = new QVBox (this);
435 leLayout->addWidget (box, 0, AlignLeft); 435 leLayout->addWidget (box, 0, AlignLeft);
436 436
437 new QLabel (i18n("Encoding:"), box); 437 new QLabel (i18n("Encoding:"), box);
438 438
439 encoding = new QComboBox(box); 439 encoding = new QComboBox(box);
440#warning fixme 440#warning fixme
441#if 0 441#if 0
442 encoding->insertStringList (KGlobal::charsets()->availableEncodingNames()); 442 encoding->insertStringList (KGlobal::charsets()->availableEncodingNames());
443 encoding->setCurrentItem (KGlobal::charsets()->availableEncodingNames().findIndex(view->doc()->encoding())); 443 encoding->setCurrentItem (KGlobal::charsets()->availableEncodingNames().findIndex(view->doc()->encoding()));
444#endif 444#endif
445 leLayout->addStretch(); 445 leLayout->addStretch();
446 446
447 // What is this? help 447 // What is this? help
448 QWhatsThis::add(opt[0], i18n("Word wrap is a feature that causes the editor to automatically start a new line of text and move (wrap) the cursor to the beginning of that new line. KateView will automatically start a new line of text when the current line reaches the length specified by the Wrap Words At: option.<p><b>NOTE:<b> Word Wrap will not change existing lines or wrap them for easy reading as in some applications.")); 448 QWhatsThis::add(opt[0], i18n("Word wrap is a feature that causes the editor to automatically start a new line of text and move (wrap) the cursor to the beginning of that new line. KateView will automatically start a new line of text when the current line reaches the length specified by the Wrap Words At: option.<p><b>NOTE:<b> Word Wrap will not change existing lines or wrap them for easy reading as in some applications."));
449 QWhatsThis::add(e1, i18n("If the Word Wrap option is selected this entry determines the length (in characters) at which the editor will automatically start a new line.")); 449 QWhatsThis::add(e1, i18n("If the Word Wrap option is selected this entry determines the length (in characters) at which the editor will automatically start a new line."));
450 QWhatsThis::add(opt[1], i18n("KateView will replace any tabs with the number of spaces indicated in the Tab Width: entry.")); 450 QWhatsThis::add(opt[1], i18n("KateView will replace any tabs with the number of spaces indicated in the Tab Width: entry."));
451 QWhatsThis::add(e2, i18n("If the Replace Tabs By Spaces option is selected this entry determines the number of spaces with which the editor will automatically replace tabs.")); 451 QWhatsThis::add(e2, i18n("If the Replace Tabs By Spaces option is selected this entry determines the number of spaces with which the editor will automatically replace tabs."));
452 QWhatsThis::add(opt[2], i18n("KateView will automatically eliminate extra spaces at the ends of lines of text.")); 452 QWhatsThis::add(opt[2], i18n("KateView will automatically eliminate extra spaces at the ends of lines of text."));
453 QWhatsThis::add(opt[3], i18n("When the user types a left bracket ([,(, or {) KateView automatically enters the right bracket (}, ), or ]) to the right of the cursor.")); 453 QWhatsThis::add(opt[3], i18n("When the user types a left bracket ([,(, or {) KateView automatically enters the right bracket (}, ), or ]) to the right of the cursor."));
454 QWhatsThis::add(opt[4], i18n("Checking this will cause sequences of similar actions to be undone at once.")); 454 QWhatsThis::add(opt[4], i18n("Checking this will cause sequences of similar actions to be undone at once."));
455 QWhatsThis::add(opt[5], i18n("The editor will display a symbol to indicate the presence of a tab in the text.")); 455 QWhatsThis::add(opt[5], i18n("The editor will display a symbol to indicate the presence of a tab in the text."));
456 QWhatsThis::add(opt[6], i18n("Not yet implemented.")); 456 QWhatsThis::add(opt[6], i18n("Not yet implemented."));
457 QWhatsThis::add(opt[7], i18n("If this is selected, the insertion cursor will be moved to the first/last line when pressing the page up/down buttons.<p>If not selected, it will remain at it's relative position in the visible text.")); 457 QWhatsThis::add(opt[7], i18n("If this is selected, the insertion cursor will be moved to the first/last line when pressing the page up/down buttons.<p>If not selected, it will remain at it's relative position in the visible text."));
458 QWhatsThis::add(e3, i18n("Sets the number of undo/redo steps to record. More steps uses more memory.")); 458 QWhatsThis::add(e3, i18n("Sets the number of undo/redo steps to record. More steps uses more memory."));
459 QWhatsThis::add(opt[8], i18n("When on, moving the insertion cursor using the <b>Left</b> and <b>Right</b> keys will go on to previous/next line at beginning/end of the line, similar to most editors.<p>When off, the insertion cursor cannot be moved left of the line start, but it can be moved off the line end, which can be very handy for programmers.")); 459 QWhatsThis::add(opt[8], i18n("When on, moving the insertion cursor using the <b>Left</b> and <b>Right</b> keys will go on to previous/next line at beginning/end of the line, similar to most editors.<p>When off, the insertion cursor cannot be moved left of the line start, but it can be moved off the line end, which can be very handy for programmers."));
460} 460}
461 461
462void EditConfigTab::getData(KateView *view) 462void EditConfigTab::getData(KateView *view)
463{ 463{
464 int configFlags, z; 464 int configFlags, z;
465 465
466 configFlags = view->config(); 466 configFlags = view->config();
467 for (z = 1; z < numFlags; z++) { 467 for (z = 1; z < numFlags; z++) {
468 configFlags &= ~flags[z]; 468 configFlags &= ~flags[z];
469 if (opt[z]->isChecked()) configFlags |= flags[z]; 469 if (opt[z]->isChecked()) configFlags |= flags[z];
470 } 470 }
471 view->setConfig(configFlags); 471 view->setConfig(configFlags);
472 472
473 view->setEncoding (encoding->currentText()); 473 view->setEncoding (encoding->currentText());
474 view->doc()->setWordWrapAt(e1->value()); 474 view->doc()->setWordWrapAt(e1->value());
475 view->doc()->setWordWrap (opt[0]->isChecked()); 475 view->doc()->setWordWrap (opt[0]->isChecked());
476 view->setTabWidth(e2->value()); 476 view->setTabWidth(e2->value());
477 view->setUndoSteps(e3->value()); 477 view->setUndoSteps(e3->value());
478} 478}
479 479
480ColorConfig::ColorConfig( QWidget *parent, char *name ) 480ColorConfig::ColorConfig( QWidget *parent, char *name )
481 : QWidget( parent, name ) 481 : QWidget( parent, name )
482{ 482{
483 QGridLayout *glay = new QGridLayout( this, 6, 2, 0, KDialog::spacingHint()); 483 QGridLayout *glay = new QGridLayout( this, 6, 2, 0, KDialog::spacingHint());
484 glay->setColStretch(1,1); 484 glay->setColStretch(1,1);
485 glay->setRowStretch(5,1); 485 glay->setRowStretch(5,1);
486 486
487 QLabel *label; 487 QLabel *label;
488 488
489 label = new QLabel( i18n("Background:"), this); 489 label = new QLabel( i18n("Background:"), this);
490 label->setAlignment( AlignRight|AlignVCenter ); 490 label->setAlignment( AlignRight|AlignVCenter );
491 m_back = new KColorButton( this ); 491 m_back = new KColorButton( this );
492 glay->addWidget( label, 0, 0 ); 492 glay->addWidget( label, 0, 0 );
493 glay->addWidget( m_back, 0, 1 ); 493 glay->addWidget( m_back, 0, 1 );
494 494
495 label = new QLabel( i18n("Selected:"), this); 495 label = new QLabel( i18n("Selected:"), this);
496 label->setAlignment( AlignRight|AlignVCenter ); 496 label->setAlignment( AlignRight|AlignVCenter );
497 m_selected = new KColorButton( this ); 497 m_selected = new KColorButton( this );
498 glay->addWidget( label, 2, 0 ); 498 glay->addWidget( label, 2, 0 );
499 glay->addWidget( m_selected, 2, 1 ); 499 glay->addWidget( m_selected, 2, 1 );
500 500
501 // QWhatsThis help 501 // QWhatsThis help
502 QWhatsThis::add(m_back, i18n("Sets the background color of the editing area")); 502 QWhatsThis::add(m_back, i18n("Sets the background color of the editing area"));
503 QWhatsThis::add(m_selected, i18n("Sets the background color of the selection. To set the text color for selected text, use the &quot;<b>Configure Highlighting</b>&quot; dialog.")); 503 QWhatsThis::add(m_selected, i18n("Sets the background color of the selection. To set the text color for selected text, use the &quot;<b>Configure Highlighting</b>&quot; dialog."));
504} 504}
505 505
506 506
507ColorConfig::~ColorConfig() 507ColorConfig::~ColorConfig()
508{ 508{
509} 509}
510 510
511void ColorConfig::setColors(QColor *colors) 511void ColorConfig::setColors(QColor *colors)
512{ 512{
513 m_back->setColor( colors[0] ); 513 m_back->setColor( colors[0] );
514 m_selected->setColor( colors[1] ); 514 m_selected->setColor( colors[1] );
515} 515}
516 516
517void ColorConfig::getColors(QColor *colors) 517void ColorConfig::getColors(QColor *colors)
518{ 518{
519 colors[0] = m_back->color(); 519 colors[0] = m_back->color();
520 colors[1] = m_selected->color(); 520 colors[1] = m_selected->color();
521} 521}
522 522
523FontConfig::FontConfig( QWidget *parent, char *name ) 523FontConfig::FontConfig( QWidget *parent, char *name )
524 : QWidget( parent, name ) 524 : QWidget( parent, name )
525{ 525{
526 // sizemanagment 526 // sizemanagment
527 QGridLayout *grid = new QGridLayout( this, 1, 1 ); 527 QGridLayout *grid = new QGridLayout( this, 1, 1 );
528// QString familyStr = cfg. readEntry ( "FontFamily", "Helvetica" ); 528// QString familyStr = cfg. readEntry ( "FontFamily", "Helvetica" );
529// QString styleStr = cfg. readEntry ( "FontStyle", "Regular" ); 529// QString styleStr = cfg. readEntry ( "FontStyle", "Regular" );
530// int size = cfg. readNumEntry ( "FontSize", 10 ); 530// int size = cfg. readNumEntry ( "FontSize", 10 );
531// OFontSelector *m_fontselect; 531// OFontSelector *m_fontselect;
532 532
533 m_fontselect = new Opie::OFontSelector ( false, this, "FontTab" ); 533 m_fontselect = new Opie::OFontSelector ( false, this, "FontTab" );
534// m_fontselect-> setSelectedFont ( familyStr, styleStr, size ); 534// m_fontselect-> setSelectedFont ( familyStr, styleStr, size );
535// QWhatsThis::add( m_fontselect, 535// QWhatsThis::add( m_fontselect,
536// tr( "Select the desired name, style and size of the default font applications will use." ) ); 536// tr( "Select the desired name, style and size of the default font applications will use." ) );
537 537
538 connect( m_fontselect, SIGNAL( fontSelected ( const QFont & )), 538 connect( m_fontselect, SIGNAL( fontSelected(const QFont&)),
539 this, SLOT( slotFontSelected( const QFont & ))); 539 this, SLOT( slotFontSelected(const QFont&)));
540 grid->addWidget( m_fontselect, 0, 0); 540 grid->addWidget( m_fontselect, 0, 0);
541 541
542 542
543// #if 0 543// #if 0
544// m_fontchooser = new KFontChooser ( this ); 544// m_fontchooser = new KFontChooser ( this );
545// m_fontchooser->enableColumn(KFontChooser::StyleList, false); 545// m_fontchooser->enableColumn(KFontChooser::StyleList, false);
546// grid->addWidget( m_fontchooser, 0, 0); 546// grid->addWidget( m_fontchooser, 0, 0);
547 547
548// connect (m_fontchooser, SIGNAL (fontSelected( const QFont & )), this, SLOT (slotFontSelected( const QFont & ))); 548// connect (m_fontchooser, SIGNAL (fontSelected(const QFont&)), this, SLOT (slotFontSelected(const QFont&)));
549// #endif 549// #endif
550} 550}
551 551
552FontConfig::~FontConfig() 552FontConfig::~FontConfig()
553{ 553{
554} 554}
555 555
556void FontConfig::setFont ( const QFont &font ) 556void FontConfig::setFont ( const QFont &font )
557{ 557{
558//#if 0 558//#if 0
559m_fontselect->setFont (font); 559m_fontselect->setFont (font);
560 myFont = font; 560 myFont = font;
561//#endif 561//#endif
562} 562}
563 563
564void FontConfig::slotFontSelected( const QFont &font ) 564void FontConfig::slotFontSelected( const QFont &font )
565{ 565{
566 myFont = font; 566 myFont = font;
567} 567}
568 568
569 569
570 570
571 571
diff --git a/noncore/apps/tinykate/tinykate.cpp b/noncore/apps/tinykate/tinykate.cpp
index 19a0127..32c1eab 100644
--- a/noncore/apps/tinykate/tinykate.cpp
+++ b/noncore/apps/tinykate/tinykate.cpp
@@ -1,278 +1,278 @@
1/*************************************************************************** 1/***************************************************************************
2 tinykate.cpp 2 tinykate.cpp
3 Tiny KATE mainwindow 3 Tiny KATE mainwindow
4 ------------------- 4 -------------------
5 begin : November 2002 5 begin : November 2002
6 copyright : (C) 2002 by Joseph Wenninger <jowenn@kde.org> 6 copyright : (C) 2002 by Joseph Wenninger <jowenn@kde.org>
7 ***************************************************************************/ 7 ***************************************************************************/
8 8
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free softwaSre; you can redistribute it and/or modify * 11 * This program is free softwaSre; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation. * 13 * the Free Software Foundation. *
14 * ONLY VERSION 2 OF THE LICENSE IS APPLICABLE * 14 * ONLY VERSION 2 OF THE LICENSE IS APPLICABLE *
15 * * 15 * *
16 ***************************************************************************/ 16 ***************************************************************************/
17#include <qaction.h> 17#include <qaction.h>
18#include <qtoolbutton.h> 18#include <qtoolbutton.h>
19#include <qmenubar.h> 19#include <qmenubar.h>
20#include <qpe/resource.h> 20#include <qpe/resource.h>
21#include <qpe/qpeapplication.h> 21#include <qpe/qpeapplication.h>
22 22
23#include <opie2/ofiledialog.h> 23#include <opie2/ofiledialog.h>
24 24
25#include "tinykate.h" 25#include "tinykate.h"
26 26
27#include <katedocument.h> 27#include <katedocument.h>
28#include <kglobal.h> 28#include <kglobal.h>
29 29
30TinyKate::TinyKate( QWidget *parent, const char *name, WFlags f) : 30TinyKate::TinyKate( QWidget *parent, const char *name, WFlags f) :
31 QMainWindow( parent, name, f ) 31 QMainWindow( parent, name, f )
32{ 32{
33 shutDown=false; 33 shutDown=false;
34 nextUnnamed=0; 34 nextUnnamed=0;
35 currentView=0; 35 currentView=0;
36 viewCount=0; 36 viewCount=0;
37 setCaption(tr("TinyKATE")); 37 setCaption(tr("TinyKATE"));
38 KGlobal::setAppName("TinyKATE"); 38 KGlobal::setAppName("TinyKATE");
39 39
40 QMenuBar *mb = new QMenuBar( this ); 40 QMenuBar *mb = new QMenuBar( this );
41 mb->setMargin( 0 ); 41 mb->setMargin( 0 );
42 42
43 tabwidget=new OTabWidget(this); 43 tabwidget=new OTabWidget(this);
44 setCentralWidget(tabwidget); 44 setCentralWidget(tabwidget);
45 connect(tabwidget,SIGNAL(currentChanged( QWidget *)),this,SLOT(slotCurrentChanged(QWidget *))); 45 connect(tabwidget,SIGNAL(currentChanged(QWidget*)),this,SLOT(slotCurrentChanged(QWidget*)));
46 46
47//FILE ACTIONS 47//FILE ACTIONS
48 QPopupMenu *popup = new QPopupMenu( this ); 48 QPopupMenu *popup = new QPopupMenu( this );
49 49
50 // Action for creating a new document 50 // Action for creating a new document
51 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); 51 QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 );
52 a->addTo( popup ); 52 a->addTo( popup );
53 connect(a, SIGNAL(activated()), this, SLOT(slotNew())); 53 connect(a, SIGNAL(activated()), this, SLOT(slotNew()));
54 54
55 // Action for opening an exisiting document 55 // Action for opening an exisiting document
56 a = new QAction( tr( "Open" ),Resource::loadPixmap( "fileopen" ) , QString::null, 0, this, 0 ); 56 a = new QAction( tr( "Open" ),Resource::loadPixmap( "fileopen" ) , QString::null, 0, this, 0 );
57 a->addTo(popup); 57 a->addTo(popup);
58 connect(a, SIGNAL(activated()), this, SLOT(slotOpen())); 58 connect(a, SIGNAL(activated()), this, SLOT(slotOpen()));
59 59
60 60
61 // Action for saving document 61 // Action for saving document
62 a = new QAction( tr( "Save" ), Resource::loadPixmap( "save" ) , QString::null, 0, this, 0 ); 62 a = new QAction( tr( "Save" ), Resource::loadPixmap( "save" ) , QString::null, 0, this, 0 );
63 a->addTo(popup); 63 a->addTo(popup);
64 connect(a, SIGNAL(activated()), this, SLOT(slotSave())); 64 connect(a, SIGNAL(activated()), this, SLOT(slotSave()));
65 65
66 // Action for saving document to a new name 66 // Action for saving document to a new name
67 a = new QAction( tr( "Save As" ),Resource::loadPixmap( "save" ) , QString::null, 0, this, 0 ); 67 a = new QAction( tr( "Save As" ),Resource::loadPixmap( "save" ) , QString::null, 0, this, 0 );
68 a->addTo(popup); 68 a->addTo(popup);
69 connect(a, SIGNAL(activated()), this, SLOT(slotSaveAs())); 69 connect(a, SIGNAL(activated()), this, SLOT(slotSaveAs()));
70 70
71 // Action for closing the currently active document 71 // Action for closing the currently active document
72 a = new QAction( tr( "Close" ), Resource::loadPixmap( "quit_icon" ) , QString::null, 0, this, 0 ); 72 a = new QAction( tr( "Close" ), Resource::loadPixmap( "quit_icon" ) , QString::null, 0, this, 0 );
73 a->addTo(popup); 73 a->addTo(popup);
74 connect(a, SIGNAL(activated()), this, SLOT(slotClose())); 74 connect(a, SIGNAL(activated()), this, SLOT(slotClose()));
75 75
76 76
77 mb->insertItem(tr("File"),popup); 77 mb->insertItem(tr("File"),popup);
78 78
79//EDIT ACTIONS 79//EDIT ACTIONS
80 80
81 // Action for cutting text 81 // Action for cutting text
82 editCut = new QToolButton( 0 ); 82 editCut = new QToolButton( 0 );
83 editCut->setAutoRaise( true ); 83 editCut->setAutoRaise( true );
84 editCut->setIconSet( Resource::loadPixmap( "cut" ) ); 84 editCut->setIconSet( Resource::loadPixmap( "cut" ) );
85 85
86 // Action for Copying text 86 // Action for Copying text
87 editCopy = new QToolButton( 0 ); 87 editCopy = new QToolButton( 0 );
88 editCopy->setAutoRaise( true ); 88 editCopy->setAutoRaise( true );
89 editCopy->setIconSet( Resource::loadPixmap( "copy" ) ); 89 editCopy->setIconSet( Resource::loadPixmap( "copy" ) );
90 90
91 // Action for pasting text 91 // Action for pasting text
92 editPaste = new QToolButton( 0 ); 92 editPaste = new QToolButton( 0 );
93 editPaste->setAutoRaise( true ); 93 editPaste->setAutoRaise( true );
94 editPaste->setIconSet( Resource::loadPixmap( "paste" ) ); 94 editPaste->setIconSet( Resource::loadPixmap( "paste" ) );
95 95
96 // Action for finding / replacing text 96 // Action for finding / replacing text
97 editFindReplace = new QToolButton( 0 ); 97 editFindReplace = new QToolButton( 0 );
98 editFindReplace->setAutoRaise( true ); 98 editFindReplace->setAutoRaise( true );
99 editFindReplace->setIconSet( Resource::loadPixmap("find") ); 99 editFindReplace->setIconSet( Resource::loadPixmap("find") );
100 100
101 // Action for undo 101 // Action for undo
102 editUndo = new QToolButton( 0 ); 102 editUndo = new QToolButton( 0 );
103 editUndo->setAutoRaise( true ); 103 editUndo->setAutoRaise( true );
104 editUndo->setIconSet( Resource::loadPixmap( "undo" ) ); 104 editUndo->setIconSet( Resource::loadPixmap( "undo" ) );
105 105
106 // Action for redo 106 // Action for redo
107 editRedo = new QToolButton( 0 ); 107 editRedo = new QToolButton( 0 );
108 editRedo->setAutoRaise( true ); 108 editRedo->setAutoRaise( true );
109 editRedo->setIconSet( Resource::loadPixmap( "redo" ) ); 109 editRedo->setIconSet( Resource::loadPixmap( "redo" ) );
110 110
111//VIEW ACITONS 111//VIEW ACITONS
112 popup = new QPopupMenu( this ); 112 popup = new QPopupMenu( this );
113 113
114 viewIncFontSizes = new QAction( tr( "Font +" ), QString::null, 0, this, 0 ); 114 viewIncFontSizes = new QAction( tr( "Font +" ), QString::null, 0, this, 0 );
115 viewIncFontSizes->addTo( popup ); 115 viewIncFontSizes->addTo( popup );
116 116
117 viewDecFontSizes = new QAction( tr( "Font -" ), QString::null, 0, this, 0 ); 117 viewDecFontSizes = new QAction( tr( "Font -" ), QString::null, 0, this, 0 );
118 viewDecFontSizes->addTo( popup ); 118 viewDecFontSizes->addTo( popup );
119 119
120 mb->insertItem(tr("View"),popup); 120 mb->insertItem(tr("View"),popup);
121 121
122 popup = new QPopupMenu( this ); 122 popup = new QPopupMenu( this );
123 mb->insertItem(tr("Utils"),popup); 123 mb->insertItem(tr("Utils"),popup);
124 124
125 125
126 mb->insertItem( editCut ); 126 mb->insertItem( editCut );
127 mb->insertItem( editCopy ); 127 mb->insertItem( editCopy );
128 mb->insertItem( editPaste ); 128 mb->insertItem( editPaste );
129 mb->insertItem( editFindReplace ); 129 mb->insertItem( editFindReplace );
130 mb->insertItem( editUndo ); 130 mb->insertItem( editUndo );
131 mb->insertItem( editRedo ); 131 mb->insertItem( editRedo );
132 132
133 133
134//Highlight management 134//Highlight management
135 hlmenu=new QPopupMenu(this); 135 hlmenu=new QPopupMenu(this);
136 HlManager *hlm=HlManager::self(); 136 HlManager *hlm=HlManager::self();
137 for (int i=0;i<hlm->highlights();i++) 137 for (int i=0;i<hlm->highlights();i++)
138 { 138 {
139 hlmenu->insertItem(hlm->hlName(i),i); 139 hlmenu->insertItem(hlm->hlName(i),i);
140 } 140 }
141 popup->insertItem(tr("Highlighting"),hlmenu); 141 popup->insertItem(tr("Highlighting"),hlmenu);
142 142
143 143
144 utilSettings = new QAction( tr( "Settings" ), QString::null, 0, this, 0 ); 144 utilSettings = new QAction( tr( "Settings" ), QString::null, 0, this, 0 );
145 utilSettings->addTo( popup); 145 utilSettings->addTo( popup);
146 146
147 if( qApp->argc() > 1) open(qApp->argv()[1]); 147 if( qApp->argc() > 1) open(qApp->argv()[1]);
148 else slotNew(); 148 else slotNew();
149 149
150} 150}
151 151
152TinyKate::~TinyKate( ) 152TinyKate::~TinyKate( )
153{ 153{
154 qWarning("TinyKate destructor\n"); 154 qWarning("TinyKate destructor\n");
155 155
156 shutDown=true; 156 shutDown=true;
157 while (currentView!=0) { 157 while (currentView!=0) {
158 slotClose(); 158 slotClose();
159 } 159 }
160 160
161 if( KGlobal::config() != 0 ) { 161 if( KGlobal::config() != 0 ) {
162 qWarning("deleting KateConfig object..\n"); 162 qWarning("deleting KateConfig object..\n");
163 delete KGlobal::config(); 163 delete KGlobal::config();
164 } 164 }
165} 165}
166 166
167void TinyKate::slotOpen( ) 167void TinyKate::slotOpen( )
168{ 168{
169 QString filename = Opie::OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 169 QString filename = Opie::OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
170 QString::null); 170 QString::null);
171 if (!filename.isEmpty()) { 171 if (!filename.isEmpty()) {
172 open(filename); 172 open(filename);
173 } 173 }
174} 174}
175 175
176void TinyKate::open(const QString & filename) 176void TinyKate::open(const QString & filename)
177{ 177{
178 KateDocument *kd= new KateDocument(false, false, this,0,this); 178 KateDocument *kd= new KateDocument(false, false, this,0,this);
179 KTextEditor::View *kv; 179 KTextEditor::View *kv;
180 QFileInfo fi(filename); 180 QFileInfo fi(filename);
181 QString filenamed = fi.fileName(); 181 QString filenamed = fi.fileName();
182 tabwidget->addTab(kv=kd->createView(tabwidget,"bLAH"),"tinykate/tinykate", filenamed ); 182 tabwidget->addTab(kv=kd->createView(tabwidget,"bLAH"),"tinykate/tinykate", filenamed );
183 qDebug(filename); 183 qDebug(filename);
184 184
185 kd->setDocName( filenamed); 185 kd->setDocName( filenamed);
186 kd->open( filename ); 186 kd->open( filename );
187 viewCount++; 187 viewCount++;
188} 188}
189 189
190void TinyKate::setDocument(const QString& fileref) 190void TinyKate::setDocument(const QString& fileref)
191{ 191{
192 open( fileref ); 192 open( fileref );
193} 193}
194 194
195void TinyKate::slotCurrentChanged( QWidget * view) 195void TinyKate::slotCurrentChanged( QWidget * view)
196{ 196{
197 if (currentView) { 197 if (currentView) {
198 198
199 disconnect(editCopy,SIGNAL(activated()),currentView,SLOT(copy())); 199 disconnect(editCopy,SIGNAL(activated()),currentView,SLOT(copy()));
200 disconnect(editCut,SIGNAL(activated()),currentView,SLOT(cut())); 200 disconnect(editCut,SIGNAL(activated()),currentView,SLOT(cut()));
201 disconnect(editPaste,SIGNAL(activated()),currentView,SLOT(paste())); 201 disconnect(editPaste,SIGNAL(activated()),currentView,SLOT(paste()));
202 disconnect(editUndo,SIGNAL(activated()),currentView,SLOT(undo())); 202 disconnect(editUndo,SIGNAL(activated()),currentView,SLOT(undo()));
203 disconnect(editRedo,SIGNAL(activated()),currentView,SLOT(redo())); 203 disconnect(editRedo,SIGNAL(activated()),currentView,SLOT(redo()));
204 disconnect(viewIncFontSizes,SIGNAL(activated()), currentView,SLOT(slotIncFontSizes())); 204 disconnect(viewIncFontSizes,SIGNAL(activated()), currentView,SLOT(slotIncFontSizes()));
205 disconnect(viewDecFontSizes,SIGNAL(activated()), currentView,SLOT(slotDecFontSizes())); 205 disconnect(viewDecFontSizes,SIGNAL(activated()), currentView,SLOT(slotDecFontSizes()));
206 disconnect(hlmenu,SIGNAL(activated(int)), currentView,SLOT(setHl(int))); 206 disconnect(hlmenu,SIGNAL(activated(int)), currentView,SLOT(setHl(int)));
207 disconnect(utilSettings,SIGNAL(activated()), currentView,SLOT(configDialog())); 207 disconnect(utilSettings,SIGNAL(activated()), currentView,SLOT(configDialog()));
208 } 208 }
209 209
210 currentView=(KTextEditor::View*)view; 210 currentView=(KTextEditor::View*)view;
211 211
212 connect(editCopy,SIGNAL(clicked()),currentView,SLOT(copy())); 212 connect(editCopy,SIGNAL(clicked()),currentView,SLOT(copy()));
213 connect(editCut,SIGNAL(clicked()),currentView,SLOT(cut())); 213 connect(editCut,SIGNAL(clicked()),currentView,SLOT(cut()));
214 connect(editPaste,SIGNAL(clicked()),currentView,SLOT(paste())); 214 connect(editPaste,SIGNAL(clicked()),currentView,SLOT(paste()));
215 connect(editUndo,SIGNAL(clicked()),currentView,SLOT(undo())); 215 connect(editUndo,SIGNAL(clicked()),currentView,SLOT(undo()));
216 connect(editRedo,SIGNAL(clicked()),currentView,SLOT(redo())); 216 connect(editRedo,SIGNAL(clicked()),currentView,SLOT(redo()));
217 connect(viewIncFontSizes,SIGNAL(activated()), currentView,SLOT(slotIncFontSizes())); 217 connect(viewIncFontSizes,SIGNAL(activated()), currentView,SLOT(slotIncFontSizes()));
218 connect(viewDecFontSizes,SIGNAL(activated()), currentView,SLOT(slotDecFontSizes())); 218 connect(viewDecFontSizes,SIGNAL(activated()), currentView,SLOT(slotDecFontSizes()));
219 connect(hlmenu,SIGNAL(activated(int)), currentView,SLOT(setHl(int))); 219 connect(hlmenu,SIGNAL(activated(int)), currentView,SLOT(setHl(int)));
220 connect(utilSettings,SIGNAL(activated()), currentView,SLOT(configDialog())); 220 connect(utilSettings,SIGNAL(activated()), currentView,SLOT(configDialog()));
221 221
222} 222}
223 223
224void TinyKate::slotNew( ) 224void TinyKate::slotNew( )
225{ 225{
226 KateDocument *kd= new KateDocument(false, false, this,0,this); 226 KateDocument *kd= new KateDocument(false, false, this,0,this);
227 KTextEditor::View *kv; 227 KTextEditor::View *kv;
228 tabwidget->addTab(kv=kd->createView(tabwidget,"BLAH"), 228 tabwidget->addTab(kv=kd->createView(tabwidget,"BLAH"),
229 "tinykate/tinykate", 229 "tinykate/tinykate",
230 tr("Unnamed %1").arg(nextUnnamed++)); 230 tr("Unnamed %1").arg(nextUnnamed++));
231 viewCount++; 231 viewCount++;
232} 232}
233 233
234void TinyKate::slotClose( ) 234void TinyKate::slotClose( )
235{ 235{
236 if (currentView==0) return; 236 if (currentView==0) return;
237 KTextEditor::View *dv=currentView; 237 KTextEditor::View *dv=currentView;
238 currentView=0; 238 currentView=0;
239 tabwidget->removePage(dv); 239 tabwidget->removePage(dv);
240 delete dv->document(); 240 delete dv->document();
241 viewCount--; 241 viewCount--;
242 if ((!viewCount) && (!shutDown)) slotNew(); 242 if ((!viewCount) && (!shutDown)) slotNew();
243} 243}
244 244
245void TinyKate::slotSave() { 245void TinyKate::slotSave() {
246 // feel free to make this how you want 246 // feel free to make this how you want
247 if (currentView==0) return; 247 if (currentView==0) return;
248 248
249 // KateView *kv = (KateView*) currentView; 249 // KateView *kv = (KateView*) currentView;
250 KateDocument *kd = (KateDocument*) currentView->document(); 250 KateDocument *kd = (KateDocument*) currentView->document();
251 // qDebug("saving file "+kd->docName()); 251 // qDebug("saving file "+kd->docName());
252 if( kd->docName().isEmpty()) 252 if( kd->docName().isEmpty())
253 slotSaveAs(); 253 slotSaveAs();
254 else 254 else
255 kd->saveFile(); 255 kd->saveFile();
256 // kv->save(); 256 // kv->save();
257 // kd->saveFile(); 257 // kd->saveFile();
258} 258}
259 259
260void TinyKate::slotSaveAs() { 260void TinyKate::slotSaveAs() {
261 if (currentView==0) return; 261 if (currentView==0) return;
262 KateDocument *kd = (KateDocument*) currentView->document(); 262 KateDocument *kd = (KateDocument*) currentView->document();
263 263
264 QString filename= Opie::OFileDialog::getSaveFileName(OFileSelector::EXTENDED_ALL, 264 QString filename= Opie::OFileDialog::getSaveFileName(OFileSelector::EXTENDED_ALL,
265 QString::null); 265 QString::null);
266 if (!filename.isEmpty()) { 266 if (!filename.isEmpty()) {
267 qDebug("saving file "+filename); 267 qDebug("saving file "+filename);
268 QFileInfo fi(filename); 268 QFileInfo fi(filename);
269 QString filenamed = fi.fileName(); 269 QString filenamed = fi.fileName();
270 kd->setDocFile( filename); 270 kd->setDocFile( filename);
271 kd->setDocName( filenamed); 271 kd->setDocName( filenamed);
272 kd->saveFile(); 272 kd->saveFile();
273// KTextEditor::View *dv = currentView; 273// KTextEditor::View *dv = currentView;
274// tabwidget->changeTab( dv, filenamed); 274// tabwidget->changeTab( dv, filenamed);
275 // need to change tab label here 275 // need to change tab label here
276 } 276 }
277 277
278} 278}
diff --git a/noncore/apps/zsafe/scqtfiledlg.cpp b/noncore/apps/zsafe/scqtfiledlg.cpp
index dd72fdf..52b8d0d 100644
--- a/noncore/apps/zsafe/scqtfiledlg.cpp
+++ b/noncore/apps/zsafe/scqtfiledlg.cpp
@@ -1,256 +1,256 @@
1/**************************************************************************** 1/****************************************************************************
2** Form implementation generated from reading ui file 'scqtfiledlg.ui' 2** Form implementation generated from reading ui file 'scqtfiledlg.ui'
3** 3**
4** Created: Sun Jun 8 15:51:12 2003 4** Created: Sun Jun 8 15:51:12 2003
5** by: The User Interface Compiler (uic) 5** by: The User Interface Compiler (uic)
6** 6**
7** WARNING! All changes made in this file will be lost! 7** WARNING! All changes made in this file will be lost!
8****************************************************************************/ 8****************************************************************************/
9#include "scqtfiledlg.h" 9#include "scqtfiledlg.h"
10 10
11#include <qcombobox.h> 11#include <qcombobox.h>
12#include <qlineedit.h> 12#include <qlineedit.h>
13#include <qlistview.h> 13#include <qlistview.h>
14#include <qtoolbutton.h> 14#include <qtoolbutton.h>
15#include <qlayout.h> 15#include <qlayout.h>
16#include <qtooltip.h> 16#include <qtooltip.h>
17#include <qwhatsthis.h> 17#include <qwhatsthis.h>
18 18
19static const char* const image0_data[] = { 19static const char* const image0_data[] = {
20"24 16 3 1", 20"24 16 3 1",
21". c None", 21". c None",
22"# c #000040", 22"# c #000040",
23"a c #808080", 23"a c #808080",
24"........................", 24"........................",
25"........................", 25"........................",
26".................####...", 26".................####...",
27".................####...", 27".................####...",
28".......##........#aa#...", 28".......##........#aa#...",
29"......###........#aa#...", 29"......###........#aa#...",
30".....####........#aa#...", 30".....####........#aa#...",
31"....##############aa#...", 31"....##############aa#...",
32"...###aaaaaaaaaaaaaa#...", 32"...###aaaaaaaaaaaaaa#...",
33"..####aaaaaaaaaaaaaa#...", 33"..####aaaaaaaaaaaaaa#...",
34"...###aaaaaaaaaaaaaa#...", 34"...###aaaaaaaaaaaaaa#...",
35"....#################...", 35"....#################...",
36".....####...............", 36".....####...............",
37"......###...............", 37"......###...............",
38".......##...............", 38".......##...............",
39"........................"}; 39"........................"};
40 40
41static const char* const image1_data[] = { 41static const char* const image1_data[] = {
42"24 16 4 1", 42"24 16 4 1",
43". c None", 43". c None",
44"a c #008080", 44"a c #008080",
45"b c #808080", 45"b c #808080",
46"# c #ff0000", 46"# c #ff0000",
47"........................", 47"........................",
48"........................", 48"........................",
49"...####..........####...", 49"...####..........####...",
50"...#####........#####...", 50"...#####........#####...",
51"....######.....#####a...", 51"....######.....#####a...",
52".....######...#####ba...", 52".....######...#####ba...",
53".....aa###########bba...", 53".....aa###########bba...",
54"....aaaaa#######aabba...", 54"....aaaaa#######aabba...",
55"...aaabbb######bbbbba...", 55"...aaabbb######bbbbba...",
56"..aaaabb########bbbba...", 56"..aaaabb########bbbba...",
57"...aaa############bba...", 57"...aaa############bba...",
58"....a######aaa#####aa...", 58"....a######aaa#####aa...",
59"....######.....######...", 59"....######.....######...",
60"...#####a........####...", 60"...#####a........####...",
61"...####aa.........###...", 61"...####aa.........###...",
62"........................"}; 62"........................"};
63 63
64static const char* const image2_data[] = { 64static const char* const image2_data[] = {
65"17 15 4 1", 65"17 15 4 1",
66"# c #000000", 66"# c #000000",
67". c #dcdcdc", 67". c #dcdcdc",
68"a c #ffff00", 68"a c #ffff00",
69"b c #ffffff", 69"b c #ffffff",
70".................", 70".................",
71"............#....", 71"............#....",
72".................", 72".................",
73"............#....", 73"............#....",
74".........#.....#.", 74".........#.....#.",
75"....####..#.#.#..", 75"....####..#.#.#..",
76"...#abab#..#.#...", 76"...#abab#..#.#...",
77"..##########..#.#", 77"..##########..#.#",
78"..#babababab##...", 78"..#babababab##...",
79"..#ababababa#.#..", 79"..#ababababa#.#..",
80"..#babababab#..#.", 80"..#babababab#..#.",
81"..#ababababa#....", 81"..#ababababa#....",
82"..#babababab#....", 82"..#babababab#....",
83"..#ababababa#....", 83"..#ababababa#....",
84"..###########...."}; 84"..###########...."};
85 85
86 86
87/* 87/*
88 * Constructs a ScQtFileDlg which is a child of 'parent', with the 88 * Constructs a ScQtFileDlg which is a child of 'parent', with the
89 * name 'name' and widget flags set to 'f' 89 * name 'name' and widget flags set to 'f'
90 * 90 *
91 * The dialog will by default be modeless, unless you set 'modal' to 91 * The dialog will by default be modeless, unless you set 'modal' to
92 * TRUE to construct a modal dialog. 92 * TRUE to construct a modal dialog.
93 */ 93 */
94ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags fl ) 94ScQtFileDlg::ScQtFileDlg( QWidget* parent, const char* name, bool modal, WFlags fl )
95 : QDialog( parent, name, modal, fl ) 95 : QDialog( parent, name, modal, fl )
96{ 96{
97 QPixmap image0( ( const char** ) image0_data ); 97 QPixmap image0( ( const char** ) image0_data );
98 QPixmap image1( ( const char** ) image1_data ); 98 QPixmap image1( ( const char** ) image1_data );
99 QPixmap image2( ( const char** ) image2_data ); 99 QPixmap image2( ( const char** ) image2_data );
100 if ( !name ) 100 if ( !name )
101 setName( "ScQtFileDlg" ); 101 setName( "ScQtFileDlg" );
102 resize( 196, 279 ); 102 resize( 196, 279 );
103 if (!name) 103 if (!name)
104 setCaption( tr( "FileDlg" ) ); 104 setCaption( tr( "FileDlg" ) );
105 else 105 else
106 setCaption(name); 106 setCaption(name);
107 ScQtFileDlgLayout = new QVBoxLayout( this ); 107 ScQtFileDlgLayout = new QVBoxLayout( this );
108 ScQtFileDlgLayout->setSpacing( 6 ); 108 ScQtFileDlgLayout->setSpacing( 6 );
109 ScQtFileDlgLayout->setMargin( 11 ); 109 ScQtFileDlgLayout->setMargin( 11 );
110 110
111 Layout5 = new QVBoxLayout; 111 Layout5 = new QVBoxLayout;
112 Layout5->setSpacing( 6 ); 112 Layout5->setSpacing( 6 );
113 Layout5->setMargin( 0 ); 113 Layout5->setMargin( 0 );
114 114
115 Layout4 = new QVBoxLayout; 115 Layout4 = new QVBoxLayout;
116 Layout4->setSpacing( 6 ); 116 Layout4->setSpacing( 6 );
117 Layout4->setMargin( 0 ); 117 Layout4->setMargin( 0 );
118 118
119 Layout3 = new QHBoxLayout; 119 Layout3 = new QHBoxLayout;
120 Layout3->setSpacing( 6 ); 120 Layout3->setSpacing( 6 );
121 Layout3->setMargin( 0 ); 121 Layout3->setMargin( 0 );
122 122
123 TypeComboBox = new QComboBox( FALSE, this, "TypeComboBox" ); 123 TypeComboBox = new QComboBox( FALSE, this, "TypeComboBox" );
124 TypeComboBox->setEditable( TRUE ); 124 TypeComboBox->setEditable( TRUE );
125 TypeComboBox->setInsertionPolicy( QComboBox::AtBottom ); 125 TypeComboBox->setInsertionPolicy( QComboBox::AtBottom );
126 TypeComboBox->setAutoCompletion( FALSE ); 126 TypeComboBox->setAutoCompletion( FALSE );
127 TypeComboBox->setDuplicatesEnabled( FALSE ); 127 TypeComboBox->setDuplicatesEnabled( FALSE );
128 QToolTip::add( TypeComboBox, tr( "file type filter" ) ); 128 QToolTip::add( TypeComboBox, tr( "file type filter" ) );
129 QWhatsThis::add( TypeComboBox, tr( "ComboBox FileTypeFilter\n" 129 QWhatsThis::add( TypeComboBox, tr( "ComboBox FileTypeFilter\n"
130"\n" 130"\n"
131"edit or select the filter" ) ); 131"edit or select the filter" ) );
132 Layout3->addWidget( TypeComboBox ); 132 Layout3->addWidget( TypeComboBox );
133 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ); 133 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
134 Layout3->addItem( spacer ); 134 Layout3->addItem( spacer );
135 135
136 OkButton = new QToolButton( this, "OkButton" ); 136 OkButton = new QToolButton( this, "OkButton" );
137 OkButton->setText( tr( "" ) ); 137 OkButton->setText( tr( "" ) );
138 OkButton->setPixmap( image0 ); 138 OkButton->setPixmap( image0 );
139 OkButton->setUsesBigPixmap( FALSE ); 139 OkButton->setUsesBigPixmap( FALSE );
140 QToolTip::add( OkButton, tr( "confirms the selection and closes the form" ) ); 140 QToolTip::add( OkButton, tr( "confirms the selection and closes the form" ) );
141 QWhatsThis::add( OkButton, tr( "OKButton" ) ); 141 QWhatsThis::add( OkButton, tr( "OKButton" ) );
142 Layout3->addWidget( OkButton ); 142 Layout3->addWidget( OkButton );
143 143
144 CancelButton = new QToolButton( this, "CancelButton" ); 144 CancelButton = new QToolButton( this, "CancelButton" );
145 CancelButton->setText( tr( "" ) ); 145 CancelButton->setText( tr( "" ) );
146 CancelButton->setPixmap( image1 ); 146 CancelButton->setPixmap( image1 );
147 CancelButton->setUsesBigPixmap( FALSE ); 147 CancelButton->setUsesBigPixmap( FALSE );
148 QToolTip::add( CancelButton, tr( "cancels the selection and closes the form" ) ); 148 QToolTip::add( CancelButton, tr( "cancels the selection and closes the form" ) );
149 QWhatsThis::add( CancelButton, tr( "CancelButton" ) ); 149 QWhatsThis::add( CancelButton, tr( "CancelButton" ) );
150 Layout3->addWidget( CancelButton ); 150 Layout3->addWidget( CancelButton );
151 Layout4->addLayout( Layout3 ); 151 Layout4->addLayout( Layout3 );
152 152
153 Layout3_2 = new QHBoxLayout; 153 Layout3_2 = new QHBoxLayout;
154 Layout3_2->setSpacing( 6 ); 154 Layout3_2->setSpacing( 6 );
155 Layout3_2->setMargin( 0 ); 155 Layout3_2->setMargin( 0 );
156 156
157 FNameLineEdit = new QLineEdit( this, "FNameLineEdit" ); 157 FNameLineEdit = new QLineEdit( this, "FNameLineEdit" );
158 QToolTip::add( FNameLineEdit, tr( "shows the selected filename" ) ); 158 QToolTip::add( FNameLineEdit, tr( "shows the selected filename" ) );
159 QWhatsThis::add( FNameLineEdit, tr( "Filename LineEdit\n" 159 QWhatsThis::add( FNameLineEdit, tr( "Filename LineEdit\n"
160"\n" 160"\n"
161"shows the selected file\n" 161"shows the selected file\n"
162"and allows the direct filename\n" 162"and allows the direct filename\n"
163"edit" ) ); 163"edit" ) );
164 Layout3_2->addWidget( FNameLineEdit ); 164 Layout3_2->addWidget( FNameLineEdit );
165 165
166 MkDirButton = new QToolButton( this, "MkDirButton" ); 166 MkDirButton = new QToolButton( this, "MkDirButton" );
167 MkDirButton->setText( tr( "" ) ); 167 MkDirButton->setText( tr( "" ) );
168 MkDirButton->setPixmap( image2 ); 168 MkDirButton->setPixmap( image2 );
169 MkDirButton->setUsesBigPixmap( FALSE ); 169 MkDirButton->setUsesBigPixmap( FALSE );
170 QToolTip::add( MkDirButton, tr( "confirms the selection and closes the form" ) ); 170 QToolTip::add( MkDirButton, tr( "confirms the selection and closes the form" ) );
171 QWhatsThis::add( MkDirButton, tr( "OKButton" ) ); 171 QWhatsThis::add( MkDirButton, tr( "OKButton" ) );
172 Layout3_2->addWidget( MkDirButton ); 172 Layout3_2->addWidget( MkDirButton );
173 Layout4->addLayout( Layout3_2 ); 173 Layout4->addLayout( Layout3_2 );
174 174
175 DirComboBox = new QComboBox( FALSE, this, "DirComboBox" ); 175 DirComboBox = new QComboBox( FALSE, this, "DirComboBox" );
176 DirComboBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)0, DirComboBox->sizePolicy().hasHeightForWidth() ) ); 176 DirComboBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)0, DirComboBox->sizePolicy().hasHeightForWidth() ) );
177 DirComboBox->setEditable( TRUE ); 177 DirComboBox->setEditable( TRUE );
178 DirComboBox->setDuplicatesEnabled( FALSE ); 178 DirComboBox->setDuplicatesEnabled( FALSE );
179 QWhatsThis::add( DirComboBox, tr( "ComboBox Directory \n" 179 QWhatsThis::add( DirComboBox, tr( "ComboBox Directory \n"
180"edit or select the directories name" ) ); 180"edit or select the directories name" ) );
181 Layout4->addWidget( DirComboBox ); 181 Layout4->addWidget( DirComboBox );
182 Layout5->addLayout( Layout4 ); 182 Layout5->addLayout( Layout4 );
183 183
184 ListView = new QListView( this, "ListView" ); 184 ListView = new QListView( this, "ListView" );
185 ListView->addColumn( tr( "Name" ) ); 185 ListView->addColumn( tr( "Name" ) );
186 ListView->addColumn( tr( "size" ) ); 186 ListView->addColumn( tr( "size" ) );
187 ListView->addColumn( tr( "type" ) ); 187 ListView->addColumn( tr( "type" ) );
188 ListView->setRootIsDecorated( TRUE ); 188 ListView->setRootIsDecorated( TRUE );
189 QToolTip::add( ListView, tr( "directory listview" ) ); 189 QToolTip::add( ListView, tr( "directory listview" ) );
190 QWhatsThis::add( ListView, tr( "Directory ListView\n" 190 QWhatsThis::add( ListView, tr( "Directory ListView\n"
191"\n" 191"\n"
192"shows the list of dirs and files" ) ); 192"shows the list of dirs and files" ) );
193 Layout5->addWidget( ListView ); 193 Layout5->addWidget( ListView );
194 ScQtFileDlgLayout->addLayout( Layout5 ); 194 ScQtFileDlgLayout->addLayout( Layout5 );
195 195
196 // signals and slots connections 196 // signals and slots connections
197 connect( OkButton, SIGNAL( clicked() ), this, SLOT( slotOK() ) ); 197 connect( OkButton, SIGNAL( clicked() ), this, SLOT( slotOK() ) );
198 connect( DirComboBox, SIGNAL( activated(int) ), this, SLOT( slotDirComboBoxChanged( int ) ) ); 198 connect( DirComboBox, SIGNAL( activated(int) ), this, SLOT( slotDirComboBoxChanged(int) ) );
199 connect( TypeComboBox, SIGNAL( activated(int) ), this, SLOT( slotTypeComboBoxChanged( int ) ) ); 199 connect( TypeComboBox, SIGNAL( activated(int) ), this, SLOT( slotTypeComboBoxChanged(int) ) );
200 connect( CancelButton, SIGNAL( clicked() ), this, SLOT( slotCancel() ) ); 200 connect( CancelButton, SIGNAL( clicked() ), this, SLOT( slotCancel() ) );
201 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem *) ) ); 201 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) );
202 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem *) ) ); 202 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( slotSelectionChanged(QListViewItem*) ) );
203 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( slotDoubleClicked(QListViewItem *) ) ); 203 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( slotDoubleClicked(QListViewItem*) ) );
204 connect( FNameLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotFileTextChanged( const QString & ) ) ); 204 connect( FNameLineEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( slotFileTextChanged(const QString&) ) );
205 connect( FNameLineEdit, SIGNAL( returnPressed() ), this, SLOT( slotOK() ) ); 205 connect( FNameLineEdit, SIGNAL( returnPressed() ), this, SLOT( slotOK() ) );
206 connect( MkDirButton, SIGNAL( clicked() ), this, SLOT( slotMkDir() ) ); 206 connect( MkDirButton, SIGNAL( clicked() ), this, SLOT( slotMkDir() ) );
207} 207}
208 208
209/* 209/*
210 * Destroys the object and frees any allocated resources 210 * Destroys the object and frees any allocated resources
211 */ 211 */
212ScQtFileDlg::~ScQtFileDlg() 212ScQtFileDlg::~ScQtFileDlg()
213{ 213{
214 // no need to delete child widgets, Qt does it all for us 214 // no need to delete child widgets, Qt does it all for us
215} 215}
216 216
217void ScQtFileDlg::slotCancel() 217void ScQtFileDlg::slotCancel()
218{ 218{
219 qWarning( "ScQtFileDlg::slotCancel(): Not implemented yet!" ); 219 qWarning( "ScQtFileDlg::slotCancel(): Not implemented yet!" );
220} 220}
221 221
222void ScQtFileDlg::slotDirComboBoxChanged( int ) 222void ScQtFileDlg::slotDirComboBoxChanged( int )
223{ 223{
224 qWarning( "ScQtFileDlg::slotDirComboBoxChanged( int ): Not implemented yet!" ); 224 qWarning( "ScQtFileDlg::slotDirComboBoxChanged( int ): Not implemented yet!" );
225} 225}
226 226
227void ScQtFileDlg::slotDoubleClicked(QListViewItem *) 227void ScQtFileDlg::slotDoubleClicked(QListViewItem *)
228{ 228{
229 qWarning( "ScQtFileDlg::slotDoubleClicked(QListViewItem *): Not implemented yet!" ); 229 qWarning( "ScQtFileDlg::slotDoubleClicked(QListViewItem *): Not implemented yet!" );
230} 230}
231 231
232void ScQtFileDlg::slotFileTextChanged( const QString & ) 232void ScQtFileDlg::slotFileTextChanged( const QString & )
233{ 233{
234 qWarning( "ScQtFileDlg::slotFileTextChanged( const QString & ): Not implemented yet!" ); 234 qWarning( "ScQtFileDlg::slotFileTextChanged( const QString & ): Not implemented yet!" );
235} 235}
236 236
237void ScQtFileDlg::slotMkDir() 237void ScQtFileDlg::slotMkDir()
238{ 238{
239 qWarning( "ScQtFileDlg::slotMkDir(): Not implemented yet!" ); 239 qWarning( "ScQtFileDlg::slotMkDir(): Not implemented yet!" );
240} 240}
241 241
242void ScQtFileDlg::slotOK() 242void ScQtFileDlg::slotOK()
243{ 243{
244 qWarning( "ScQtFileDlg::slotOK(): Not implemented yet!" ); 244 qWarning( "ScQtFileDlg::slotOK(): Not implemented yet!" );
245} 245}
246 246
247void ScQtFileDlg::slotSelectionChanged(QListViewItem *) 247void ScQtFileDlg::slotSelectionChanged(QListViewItem *)
248{ 248{
249 qWarning( "ScQtFileDlg::slotSelectionChanged(QListViewItem *): Not implemented yet!" ); 249 qWarning( "ScQtFileDlg::slotSelectionChanged(QListViewItem *): Not implemented yet!" );
250} 250}
251 251
252void ScQtFileDlg::slotTypeComboBoxChanged( int ) 252void ScQtFileDlg::slotTypeComboBoxChanged( int )
253{ 253{
254 qWarning( "ScQtFileDlg::slotTypeComboBoxChanged( int ): Not implemented yet!" ); 254 qWarning( "ScQtFileDlg::slotTypeComboBoxChanged( int ): Not implemented yet!" );
255} 255}
256 256
diff --git a/noncore/apps/zsafe/zsafe.cpp b/noncore/apps/zsafe/zsafe.cpp
index a3e805e..a3467e5 100644
--- a/noncore/apps/zsafe/zsafe.cpp
+++ b/noncore/apps/zsafe/zsafe.cpp
@@ -1,3733 +1,3733 @@
1/**************************************************************************** 1/****************************************************************************
2** 2**
3** Created: Sat Apr 6 17:57:45 2002 3** Created: Sat Apr 6 17:57:45 2002
4** 4**
5** Author: Carsten Schneider <CarstenSchneider@t-online.de> 5** Author: Carsten Schneider <CarstenSchneider@t-online.de>
6** 6**
7** $Id$ 7** $Id$
8** 8**
9** Homepage: http://home.t-online.de/home/CarstenSchneider/zsafe/index.html 9** Homepage: http://home.t-online.de/home/CarstenSchneider/zsafe/index.html
10** 10**
11** Compile Flags: 11** Compile Flags:
12** Zaurus arm : -DNO_OPIE 12** Zaurus arm : -DNO_OPIE
13** Zaurus Opie arm: none 13** Zaurus Opie arm: none
14** Linux Desktop : -DDESKTOP 14** Linux Desktop : -DDESKTOP
15** Windows Desktop: -DDESKTOP -DWIN32 15** Windows Desktop: -DDESKTOP -DWIN32
16** 16**
17** for japanese version additional use: -DJPATCH_HDE 17** for japanese version additional use: -DJPATCH_HDE
18** 18**
19****************************************************************************/ 19****************************************************************************/
20#include "zsafe.h" 20#include "zsafe.h"
21#include "newdialog.h" 21#include "newdialog.h"
22#include "searchdialog.h" 22#include "searchdialog.h"
23#include "categorydialog.h" 23#include "categorydialog.h"
24#include "passworddialog.h" 24#include "passworddialog.h"
25#include "infoform.h" 25#include "infoform.h"
26#include "zlistview.h" 26#include "zlistview.h"
27#include "shadedlistitem.h" 27#include "shadedlistitem.h"
28 28
29#ifndef DESKTOP 29#ifndef DESKTOP
30#ifndef NO_OPIE 30#ifndef NO_OPIE
31#include <opie2/ofiledialog.h> 31#include <opie2/ofiledialog.h>
32 32
33using Opie::OFileDialog; 33using Opie::OFileDialog;
34using Opie::OFileSelector; 34using Opie::OFileSelector;
35#else 35#else
36#include "scqtfileedit.h" 36#include "scqtfileedit.h"
37#endif 37#endif
38#endif 38#endif
39 39
40#include <qclipboard.h> 40#include <qclipboard.h>
41 41
42#include <stdio.h> 42#include <stdio.h>
43 43
44#include <sys/types.h> 44#include <sys/types.h>
45#include <sys/stat.h> 45#include <sys/stat.h>
46#include <fcntl.h> 46#include <fcntl.h>
47#include <stdlib.h> 47#include <stdlib.h>
48#ifndef WIN32 48#ifndef WIN32
49#include <unistd.h> 49#include <unistd.h>
50#endif 50#endif
51#include <string.h> 51#include <string.h>
52#include <errno.h> 52#include <errno.h>
53 53
54#include <qmenubar.h> 54#include <qmenubar.h>
55#include <qpopupmenu.h> 55#include <qpopupmenu.h>
56 56
57#ifdef DESKTOP 57#ifdef DESKTOP
58#include <qfiledialog.h> 58#include <qfiledialog.h>
59#ifndef WIN32 59#ifndef WIN32
60#include <qsettings.h> 60#include <qsettings.h>
61#else 61#else
62#include "qsettings.h" 62#include "qsettings.h"
63#endif 63#endif
64#include <qapplication.h> 64#include <qapplication.h>
65#else 65#else
66#include <qfile.h> 66#include <qfile.h>
67#include <qpe/fileselector.h> 67#include <qpe/fileselector.h>
68#include <qpe/global.h> 68#include <qpe/global.h>
69#include <qpe/qpeapplication.h> 69#include <qpe/qpeapplication.h>
70#include <qpe/resource.h> 70#include <qpe/resource.h>
71#include <qpe/config.h> 71#include <qpe/config.h>
72#endif 72#endif
73 73
74#include <qtimer.h> 74#include <qtimer.h>
75#include <qlayout.h> 75#include <qlayout.h>
76#include <qmessagebox.h> 76#include <qmessagebox.h>
77#include <qfile.h> 77#include <qfile.h>
78#include <qtextstream.h> 78#include <qtextstream.h>
79#include <qheader.h> 79#include <qheader.h>
80#include <qlistview.h> 80#include <qlistview.h>
81#include <qtoolbutton.h> 81#include <qtoolbutton.h>
82#include <qvariant.h> 82#include <qvariant.h>
83#include <qtooltip.h> 83#include <qtooltip.h>
84#include <qwhatsthis.h> 84#include <qwhatsthis.h>
85#include <qimage.h> 85#include <qimage.h>
86#include <qpixmap.h> 86#include <qpixmap.h>
87#include <qlineedit.h> 87#include <qlineedit.h>
88#include <qmultilineedit.h> 88#include <qmultilineedit.h>
89#include <qregexp.h> 89#include <qregexp.h>
90#include <qdir.h> 90#include <qdir.h>
91#include <qtextbrowser.h> 91#include <qtextbrowser.h>
92#include <qlabel.h> 92#include <qlabel.h>
93#include <qcombobox.h> 93#include <qcombobox.h>
94 94
95#include "krc2.h" 95#include "krc2.h"
96 96
97#include "wait.h" 97#include "wait.h"
98 98
99extern int DeskW, DeskH; 99extern int DeskW, DeskH;
100#ifdef DESKTOP 100#ifdef DESKTOP
101extern QApplication *appl; 101extern QApplication *appl;
102#else 102#else
103extern QPEApplication *appl; 103extern QPEApplication *appl;
104#endif 104#endif
105 105
106#ifdef JPATCH_HDE 106#ifdef JPATCH_HDE
107#define tr(arg) arg 107#define tr(arg) arg
108#endif 108#endif
109 109
110 110
111#ifdef DESKTOP 111#ifdef DESKTOP
112#ifndef WIN32 112#ifndef WIN32
113const QString APP_KEY="/.zsafe/"; 113const QString APP_KEY="/.zsafe/";
114#else 114#else
115const QString APP_KEY=""; 115const QString APP_KEY="";
116#endif 116#endif
117#else 117#else
118const QString APP_KEY=""; 118const QString APP_KEY="";
119#endif 119#endif
120 120
121// include xmp images 121// include xmp images
122#include "pics/zsafe/copy.xpm" 122#include "pics/zsafe/copy.xpm"
123#include "pics/zsafe/cut.xpm" 123#include "pics/zsafe/cut.xpm"
124#include "pics/zsafe/edit.xpm" 124#include "pics/zsafe/edit.xpm"
125#include "pics/zsafe/editdelete.xpm" 125#include "pics/zsafe/editdelete.xpm"
126#include "pics/zsafe/find.xpm" 126#include "pics/zsafe/find.xpm"
127#include "pics/zsafe/folder_open.xpm" 127#include "pics/zsafe/folder_open.xpm"
128#include "pics/zsafe/help_icon.xpm" 128#include "pics/zsafe/help_icon.xpm"
129#include "pics/zsafe/new.xpm" 129#include "pics/zsafe/new.xpm"
130#include "pics/zsafe/paste.xpm" 130#include "pics/zsafe/paste.xpm"
131#include "pics/zsafe/quit_icon.xpm" 131#include "pics/zsafe/quit_icon.xpm"
132#include "pics/zsafe/save.xpm" 132#include "pics/zsafe/save.xpm"
133#include "pics/zsafe/trash.xpm" 133#include "pics/zsafe/trash.xpm"
134#include "pics/zsafe/expand.xpm" 134#include "pics/zsafe/expand.xpm"
135#include "pics/zsafe/export.xpm" 135#include "pics/zsafe/export.xpm"
136#include "pics/zsafe/import.xpm" 136#include "pics/zsafe/import.xpm"
137#include "pics/zsafe/zsafe.xpm" 137#include "pics/zsafe/zsafe.xpm"
138 138
139static const char* const bank_cards_data[] = { 139static const char* const bank_cards_data[] = {
140"14 14 16 1", 140"14 14 16 1",
141". c None", 141". c None",
142"# c #000000", 142"# c #000000",
143"b c #0000de", 143"b c #0000de",
144"a c #0000e6", 144"a c #0000e6",
145"j c #41de83", 145"j c #41de83",
146"k c #4acecd", 146"k c #4acecd",
147"h c #4aced5", 147"h c #4aced5",
148"g c #5a40cd", 148"g c #5a40cd",
149"d c #5a44d5", 149"d c #5a44d5",
150"l c #9440d5", 150"l c #9440d5",
151"m c #b4ce4a", 151"m c #b4ce4a",
152"n c #cd4883", 152"n c #cd4883",
153"e c #d5ae10", 153"e c #d5ae10",
154"f c #de3ce6", 154"f c #de3ce6",
155"i c #e640e6", 155"i c #e640e6",
156"c c #ffffff", 156"c c #ffffff",
157"..............", 157"..............",
158".###########..", 158".###########..",
159".#ababababa#..", 159".#ababababa#..",
160".#babbbabbb#..", 160".#babbbabbb#..",
161".#ccccccccc#..", 161".#ccccccccc#..",
162".#cdcefcghc#..", 162".#cdcefcghc#..",
163".#ccccccccc#..", 163".#ccccccccc#..",
164".#cicjkclic#..", 164".#cicjkclic#..",
165".#ccccccccc#..", 165".#ccccccccc#..",
166".#cmchlcnec#..", 166".#cmchlcnec#..",
167".#ccccccccc#..", 167".#ccccccccc#..",
168".###########..", 168".###########..",
169"..............", 169"..............",
170".............."}; 170".............."};
171 171
172 172
173static const char* const passwords_data[] = { 173static const char* const passwords_data[] = {
174"16 16 20 1", 174"16 16 20 1",
175". c None", 175". c None",
176"# c #000000", 176"# c #000000",
177"r c #000083", 177"r c #000083",
178"p c #0000c5", 178"p c #0000c5",
179"q c #0000ff", 179"q c #0000ff",
180"n c #008100", 180"n c #008100",
181"l c #00c200", 181"l c #00c200",
182"m c #00ff00", 182"m c #00ff00",
183"j c #838100", 183"j c #838100",
184"a c #c55900", 184"a c #c55900",
185"h c #c5c200", 185"h c #c5c200",
186"o c #c5c2ff", 186"o c #c5c2ff",
187"k c #c5ffc5", 187"k c #c5ffc5",
188"f c #ff0000", 188"f c #ff0000",
189"d c #ff8100", 189"d c #ff8100",
190"b c #ffaa5a", 190"b c #ffaa5a",
191"e c #ffc2c5", 191"e c #ffc2c5",
192"c c #ffdeac", 192"c c #ffdeac",
193"i c #ffff00", 193"i c #ffff00",
194"g c #ffffc5", 194"g c #ffffc5",
195"............###.", 195"............###.",
196"...........#abb#", 196"...........#abb#",
197"..........#cbab#", 197"..........#cbab#",
198".........#cbdd#.", 198".........#cbdd#.",
199"######..#cbdd#..", 199"######..#cbdd#..",
200"#eeff#..#add#...", 200"#eeff#..#add#...",
201"#eeff#######....", 201"#eeff#######....",
202"#ccdbdd#........", 202"#ccdbdd#........",
203"#dddbdd###......", 203"#dddbdd###......",
204"#gghihhjj#......", 204"#gghihhjj#......",
205"#hhhihhjj###....", 205"#hhhihhjj###....",
206"#kklmllnnnn#....", 206"#kklmllnnnn#....",
207"#lllmllnnnn#....", 207"#lllmllnnnn#....",
208"#oopqpprprr#....", 208"#oopqpprprr#....",
209"#oopqpprprr#....", 209"#oopqpprprr#....",
210"############...."}; 210"############...."};
211 211
212static const char* const software_data[] = { 212static const char* const software_data[] = {
213"16 16 5 1", 213"16 16 5 1",
214". c None", 214". c None",
215"# c #000000", 215"# c #000000",
216"b c #838183", 216"b c #838183",
217"c c #c5ffff", 217"c c #c5ffff",
218"a c #ffffff", 218"a c #ffffff",
219"................", 219"................",
220".##############.", 220".##############.",
221"#aaaaaaaaaaaaaa#", 221"#aaaaaaaaaaaaaa#",
222"#abbbbbbbbbbbbb#", 222"#abbbbbbbbbbbbb#",
223"#ab##########ab#", 223"#ab##########ab#",
224"#ab#c########ab#", 224"#ab#c########ab#",
225"#ab#c#c######ab#", 225"#ab#c#c######ab#",
226"#ab##########ab#", 226"#ab##########ab#",
227"#ab##########ab#", 227"#ab##########ab#",
228"#ab##########ab#", 228"#ab##########ab#",
229"#ab##########ab#", 229"#ab##########ab#",
230"#ab##########ab#", 230"#ab##########ab#",
231"#aaaaaaaaaaaaab#", 231"#aaaaaaaaaaaaab#",
232"#bbbbbbbbbbbbbb#", 232"#bbbbbbbbbbbbbb#",
233".##############.", 233".##############.",
234"................"}; 234"................"};
235 235
236static const char* const general_data[] = { 236static const char* const general_data[] = {
237"14 14 98 2", 237"14 14 98 2",
238"Qt c None", 238"Qt c None",
239".k c #000000", 239".k c #000000",
240"#x c #080808", 240"#x c #080808",
241"#F c #101008", 241"#F c #101008",
242"#q c #101010", 242"#q c #101010",
243"#i c #101410", 243"#i c #101410",
244"## c #101810", 244"## c #101810",
245".m c #181818", 245".m c #181818",
246".3 c #181c18", 246".3 c #181c18",
247".I c #182018", 247".I c #182018",
248".T c #202420", 248".T c #202420",
249"#D c #202820", 249"#D c #202820",
250"#y c #292c29", 250"#y c #292c29",
251".c c #293029", 251".c c #293029",
252".d c #313031", 252".d c #313031",
253"#E c #313429", 253"#E c #313429",
254"#r c #313831", 254"#r c #313831",
255".j c #393c31", 255".j c #393c31",
256"#j c #394039", 256"#j c #394039",
257"#C c #414841", 257"#C c #414841",
258".w c #4a554a", 258".w c #4a554a",
259".a c #4a594a", 259".a c #4a594a",
260".# c #525052", 260".# c #525052",
261".l c #52594a", 261".l c #52594a",
262"#f c #525952", 262"#f c #525952",
263"#v c #525d52", 263"#v c #525d52",
264".O c #5a4c4a", 264".O c #5a4c4a",
265".9 c #5a595a", 265".9 c #5a595a",
266".A c #5a5d52", 266".A c #5a5d52",
267".B c #624c52", 267".B c #624c52",
268".0 c #625552", 268".0 c #625552",
269"#o c #626562", 269"#o c #626562",
270".R c #626962", 270".R c #626962",
271"#. c #626d5a", 271"#. c #626d5a",
272"#p c #626d62", 272"#p c #626d62",
273".2 c #627162", 273".2 c #627162",
274"#h c #6a6d62", 274"#h c #6a6d62",
275"#z c #6a7562", 275"#z c #6a7562",
276"#w c #6a756a", 276"#w c #6a756a",
277".C c #73656a", 277".C c #73656a",
278".P c #73696a", 278".P c #73696a",
279"#a c #737d6a", 279"#a c #737d6a",
280".U c #738573", 280".U c #738573",
281".E c #7b817b", 281".E c #7b817b",
282"#B c #7b857b", 282"#B c #7b857b",
283"#s c #7b897b", 283"#s c #7b897b",
284"#n c #7b917b", 284"#n c #7b917b",
285".b c #838d83", 285".b c #838d83",
286".7 c #839583", 286".7 c #839583",
287".n c #8b7d7b", 287".n c #8b7d7b",
288"#g c #8b8583", 288"#g c #8b8583",
289".g c #8b858b", 289".g c #8b858b",
290".r c #8b898b", 290".r c #8b898b",
291".s c #8b8d8b", 291".s c #8b8d8b",
292".i c #8b9183", 292".i c #8b9183",
293".8 c #8b918b", 293".8 c #8b918b",
294"#A c #8b9d8b", 294"#A c #8b9d8b",
295".S c #8ba183", 295".S c #8ba183",
296".Z c #94918b", 296".Z c #94918b",
297".N c #949994", 297".N c #949994",
298".F c #949d94", 298".F c #949d94",
299".x c #94a18b", 299".x c #94a18b",
300".v c #94a194", 300".v c #94a194",
301".Y c #94aa94", 301".Y c #94aa94",
302".h c #9c999c", 302".h c #9c999c",
303".Q c #9ca19c", 303".Q c #9ca19c",
304"#u c #9ca59c", 304"#u c #9ca59c",
305".H c #9caa9c", 305".H c #9caa9c",
306"#e c #9cb29c", 306"#e c #9cb29c",
307"#m c #a4b29c", 307"#m c #a4b29c",
308"#t c #a4b2a4", 308"#t c #a4b2a4",
309".M c #a4b69c", 309".M c #a4b69c",
310"#l c #a4b6a4", 310"#l c #a4b6a4",
311".z c #a4baa4", 311".z c #a4baa4",
312".f c #aca5ac", 312".f c #aca5ac",
313".q c #acaaac", 313".q c #acaaac",
314"#d c #acbeac", 314"#d c #acbeac",
315".6 c #acc2ac", 315".6 c #acc2ac",
316".o c #b4b2b4", 316".o c #b4b2b4",
317".t c #b4beb4", 317".t c #b4beb4",
318"#k c #b4c2ac", 318"#k c #b4c2ac",
319".5 c #b4cab4", 319".5 c #b4cab4",
320".D c #bdb6bd", 320".D c #bdb6bd",
321".G c #bdc6b4", 321".G c #bdc6b4",
322"#c c #bdceb4", 322"#c c #bdceb4",
323".X c #bdd2bd", 323".X c #bdd2bd",
324".4 c #bdd6bd", 324".4 c #bdd6bd",
325".1 c #c5bec5", 325".1 c #c5bec5",
326".e c #c5c2c5", 326".e c #c5c2c5",
327".u c #c5cac5", 327".u c #c5cac5",
328"#b c #c5d6c5", 328"#b c #c5d6c5",
329".J c #c5dec5", 329".J c #c5dec5",
330".p c #cdcacd", 330".p c #cdcacd",
331".W c #cddecd", 331".W c #cddecd",
332".L c #cde2cd", 332".L c #cde2cd",
333".K c #d5eacd", 333".K c #d5eacd",
334".V c #d5ead5", 334".V c #d5ead5",
335".y c #d5eed5", 335".y c #d5eed5",
336"QtQtQtQtQtQtQtQtQtQtQtQtQtQt", 336"QtQtQtQtQtQtQtQtQtQtQtQtQtQt",
337"QtQtQt.#.a.b.cQtQtQtQtQtQtQt", 337"QtQtQt.#.a.b.cQtQtQtQtQtQtQt",
338"QtQt.d.e.f.g.h.i.c.j.dQt.kQt", 338"QtQt.d.e.f.g.h.i.c.j.dQt.kQt",
339".a.l.m.n.o.p.q.r.s.t.u.v.wQt", 339".a.l.m.n.o.p.q.r.s.t.u.v.wQt",
340".x.y.z.A.B.C.D.p.q.E.F.G.H.I", 340".x.y.z.A.B.C.D.p.q.E.F.G.H.I",
341".I.J.K.L.M.N.O.P.o.p.Q.R.S.T", 341".I.J.K.L.M.N.O.P.o.p.Q.R.S.T",
342"Qt.U.V.L.W.X.Y.Z.0.P.1.s.2.3", 342"Qt.U.V.L.W.X.Y.Z.0.P.1.s.2.3",
343"Qt.3.X.W.4.X.5.6.7.8.9.s#.##", 343"Qt.3.X.W.4.X.5.6.7.8.9.s#.##",
344"QtQt#a.X#b#c.5.6#d#e#f#g#h#i", 344"QtQt#a.X#b#c.5.6#d#e#f#g#h#i",
345"QtQtQt#j.7#k.6#d#l#m#n#o#p#q", 345"QtQtQt#j.7#k.6#d#l#m#n#o#p#q",
346"QtQtQtQt.k#r#s#m#t.H#u#v#w#x", 346"QtQtQtQt.k#r#s#m#t.H#u#v#w#x",
347"QtQtQtQtQtQt.k#y#z.v#A#B#C#x", 347"QtQtQtQtQtQt.k#y#z.v#A#B#C#x",
348"QtQtQtQtQtQtQtQt.k#D.w#s#E.k", 348"QtQtQtQtQtQtQtQt.k#D.w#s#E.k",
349"QtQtQtQtQtQtQtQtQtQtQt#x#FQt"}; 349"QtQtQtQtQtQtQtQtQtQtQt#x#FQt"};
350 350
351// exit ZSafe and clear the clipboard for security reasons 351// exit ZSafe and clear the clipboard for security reasons
352 void ZSafe::exitZs (int ec) 352 void ZSafe::exitZs (int ec)
353 { 353 {
354 QClipboard *cb = QApplication::clipboard(); 354 QClipboard *cb = QApplication::clipboard();
355 cb->clear(); 355 cb->clear();
356 356
357 exit (ec); 357 exit (ec);
358 } 358 }
359 359
360 360
361// save the configuration into the file 361// save the configuration into the file
362 void ZSafe::saveConf () 362 void ZSafe::saveConf ()
363 { 363 {
364 if (conf) 364 if (conf)
365 { 365 {
366 delete conf; 366 delete conf;
367 367
368#ifdef DESKTOP 368#ifdef DESKTOP
369#ifndef WIN32 369#ifndef WIN32
370 conf = new QSettings (); 370 conf = new QSettings ();
371 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath()); 371 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath());
372#else 372#else
373 conf = new QSettings (cfgFile); 373 conf = new QSettings (cfgFile);
374 conf->insertSearchPath (QSettings::Unix, cfgFile); 374 conf->insertSearchPath (QSettings::Unix, cfgFile);
375#endif 375#endif
376#else 376#else
377 conf = new Config (cfgFile, Config::File); 377 conf = new Config (cfgFile, Config::File);
378 conf->setGroup ("zsafe"); 378 conf->setGroup ("zsafe");
379#endif 379#endif
380 } 380 }
381 } 381 }
382 382
383 383
384/* 384/*
385 * Constructs a ZSafe which is a child of 'parent', with the 385 * Constructs a ZSafe which is a child of 'parent', with the
386 * name 'name' and widget flags set to 'f' 386 * name 'name' and widget flags set to 'f'
387 * 387 *
388 * The dialog will by default be modeless, unless you set 'modal' to 388 * The dialog will by default be modeless, unless you set 'modal' to
389 * TRUE to construct a modal dialog. 389 * TRUE to construct a modal dialog.
390 */ 390 */
391ZSafe::ZSafe( QWidget* parent, const char* name, bool modal, WFlags fl ) 391ZSafe::ZSafe( QWidget* parent, const char* name, bool modal, WFlags fl )
392 : QDialog( parent, name, modal, fl ), 392 : QDialog( parent, name, modal, fl ),
393 Edit(0l), Delete(0l), Find(0l), New(0l), ListView(0l) 393 Edit(0l), Delete(0l), Find(0l), New(0l), ListView(0l)
394{ 394{
395 IsCut = false; 395 IsCut = false;
396 IsCopy = false; 396 IsCopy = false;
397 modified = false; 397 modified = false;
398 398
399 // set the config file 399 // set the config file
400 cfgFile=QDir::homeDirPath(); 400 cfgFile=QDir::homeDirPath();
401 cfgFile += "/.zsafe.cfg"; 401 cfgFile += "/.zsafe.cfg";
402 // set the icon path 402 // set the icon path
403#ifdef NO_OPIE 403#ifdef NO_OPIE
404 QString qpedir ((const char *)getenv("QPEDIR")); 404 QString qpedir ((const char *)getenv("QPEDIR"));
405#else 405#else
406 QString qpedir ((const char *)getenv("OPIEDIR")); 406 QString qpedir ((const char *)getenv("OPIEDIR"));
407#endif 407#endif
408 408
409#ifdef DESKTOP 409#ifdef DESKTOP
410 iconPath = QDir::homeDirPath() + "/pics/"; 410 iconPath = QDir::homeDirPath() + "/pics/";
411#else 411#else
412 if (qpedir.isEmpty()) 412 if (qpedir.isEmpty())
413 iconPath = "/home/QtPalmtop/pics/"; 413 iconPath = "/home/QtPalmtop/pics/";
414 else 414 else
415 iconPath = qpedir + "/pics/"; 415 iconPath = qpedir + "/pics/";
416#endif 416#endif
417 417
418 // create a zsafe configuration object 418 // create a zsafe configuration object
419#ifdef DESKTOP 419#ifdef DESKTOP
420#ifndef WIN32 420#ifndef WIN32
421 conf = new QSettings (); 421 conf = new QSettings ();
422 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath()); 422 conf->insertSearchPath (QSettings::Unix, QDir::homeDirPath());
423#else 423#else
424 conf = new QSettings (cfgFile); 424 conf = new QSettings (cfgFile);
425 conf->insertSearchPath (QSettings::Unix, cfgFile); 425 conf->insertSearchPath (QSettings::Unix, cfgFile);
426#endif 426#endif
427#else 427#else
428 conf = new Config (cfgFile, Config::File); 428 conf = new Config (cfgFile, Config::File);
429 conf->setGroup ("zsafePrefs"); 429 conf->setGroup ("zsafePrefs");
430#endif 430#endif
431#ifdef DESKTOP 431#ifdef DESKTOP
432// #ifndef WIN32 432// #ifndef WIN32
433 expandTree = conf->readBoolEntry(APP_KEY+"expandTree", false); 433 expandTree = conf->readBoolEntry(APP_KEY+"expandTree", false);
434// #endif 434// #endif
435#else 435#else
436 expandTree = conf->readNumEntry(APP_KEY+"expandTree", 0); 436 expandTree = conf->readNumEntry(APP_KEY+"expandTree", 0);
437#endif 437#endif
438#ifndef DESKTOP 438#ifndef DESKTOP
439 conf->setGroup ("zsafe"); 439 conf->setGroup ("zsafe");
440#endif 440#endif
441 441
442 QPixmap copy_img((const char**) copy_xpm); 442 QPixmap copy_img((const char**) copy_xpm);
443 QPixmap cut_img((const char**) cut_xpm); 443 QPixmap cut_img((const char**) cut_xpm);
444 QPixmap edit_img((const char**) edit_xpm); 444 QPixmap edit_img((const char**) edit_xpm);
445 QPixmap editdelete_img((const char**) editdelete_xpm); 445 QPixmap editdelete_img((const char**) editdelete_xpm);
446 QPixmap find_img((const char**) find_xpm); 446 QPixmap find_img((const char**) find_xpm);
447 QPixmap folder_open_img((const char**) folder_open_xpm); 447 QPixmap folder_open_img((const char**) folder_open_xpm);
448 QPixmap help_icon_img((const char**) help_icon_xpm); 448 QPixmap help_icon_img((const char**) help_icon_xpm);
449 QPixmap new_img((const char**) new_xpm); 449 QPixmap new_img((const char**) new_xpm);
450 QPixmap paste_img((const char**) paste_xpm); 450 QPixmap paste_img((const char**) paste_xpm);
451 QPixmap quit_icon_img((const char**) quit_icon_xpm); 451 QPixmap quit_icon_img((const char**) quit_icon_xpm);
452 QPixmap save_img((const char**) save_xpm); 452 QPixmap save_img((const char**) save_xpm);
453 QPixmap trash_img((const char**) trash_xpm); 453 QPixmap trash_img((const char**) trash_xpm);
454 QPixmap expand_img((const char**) expand_xpm); 454 QPixmap expand_img((const char**) expand_xpm);
455 QPixmap export_img((const char**) export_xpm); 455 QPixmap export_img((const char**) export_xpm);
456 QPixmap import_img((const char**) import_xpm); 456 QPixmap import_img((const char**) import_xpm);
457 457
458 QPixmap bank_cards( ( const char** ) bank_cards_data ); 458 QPixmap bank_cards( ( const char** ) bank_cards_data );
459 QPixmap passwords( ( const char** ) passwords_data ); 459 QPixmap passwords( ( const char** ) passwords_data );
460 QPixmap software( ( const char** ) software_data ); 460 QPixmap software( ( const char** ) software_data );
461 QPixmap general( ( const char** ) general_data ); 461 QPixmap general( ( const char** ) general_data );
462 if ( !name ) 462 if ( !name )
463 setName( "ZSafe" ); 463 setName( "ZSafe" );
464 464
465#ifdef DESKTOP 465#ifdef DESKTOP
466#ifdef WIN32 466#ifdef WIN32
467 setGeometry(100, 150, DeskW, DeskH-30 ); 467 setGeometry(100, 150, DeskW, DeskH-30 );
468#else 468#else
469 resize( DeskW, DeskH-30 ); 469 resize( DeskW, DeskH-30 );
470#endif 470#endif
471 471
472#else 472#else
473 473
474#ifdef JPATCH_HDE 474#ifdef JPATCH_HDE
475 int DeskS; 475 int DeskS;
476 if(DeskW > DeskH) 476 if(DeskW > DeskH)
477 { 477 {
478 DeskS = DeskW; 478 DeskS = DeskW;
479 } 479 }
480 else 480 else
481 { 481 {
482 DeskS = DeskH; 482 DeskS = DeskH;
483 } 483 }
484 resize( DeskW, DeskH ); 484 resize( DeskW, DeskH );
485 setMinimumSize( QSize( DeskS, DeskS ) ); 485 setMinimumSize( QSize( DeskS, DeskS ) );
486 setMaximumSize( QSize( DeskS, DeskS ) ); 486 setMaximumSize( QSize( DeskS, DeskS ) );
487#else 487#else
488 resize( DeskW, DeskH-30 ); 488 resize( DeskW, DeskH-30 );
489#endif 489#endif
490 490
491#endif 491#endif
492 // setCaption( tr( "ZSafe" ) ); 492 // setCaption( tr( "ZSafe" ) );
493 493
494 filename = conf->readEntry(APP_KEY+"document"); 494 filename = conf->readEntry(APP_KEY+"document");
495 if (filename.isEmpty() || filename.isNull()) 495 if (filename.isEmpty() || filename.isNull())
496 { 496 {
497 497
498 // check if the directory application exists, if not 498 // check if the directory application exists, if not
499 // create it 499 // create it
500// #ifndef WIN32 500// #ifndef WIN32
501 // QString d1("Documents/application"); 501 // QString d1("Documents/application");
502// #else 502// #else
503 QString d1(QDir::homeDirPath() + "/Documents/application"); 503 QString d1(QDir::homeDirPath() + "/Documents/application");
504// #endif 504// #endif
505 QDir pd1(d1); 505 QDir pd1(d1);
506 if (!pd1.exists()) 506 if (!pd1.exists())
507 { 507 {
508 QDir pd1("Documents"); 508 QDir pd1("Documents");
509 if (!pd1.mkdir("application", FALSE)) 509 if (!pd1.mkdir("application", FALSE))
510 { 510 {
511 QMessageBox::critical( 0, tr("ZSafe"), 511 QMessageBox::critical( 0, tr("ZSafe"),
512#ifdef JPATCH_HDE 512#ifdef JPATCH_HDE
513 tr("Can't create directory\n.../Documents/application\n\nZSafe will now exit.")); 513 tr("Can't create directory\n.../Documents/application\n\nZSafe will now exit."));
514#else 514#else
515 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d1)); 515 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d1));
516#endif 516#endif
517 exitZs (1); 517 exitZs (1);
518 } 518 }
519 } 519 }
520 QString d2(QDir::homeDirPath() + "/Documents/application/zsafe"); 520 QString d2(QDir::homeDirPath() + "/Documents/application/zsafe");
521 QDir pd2(d2); 521 QDir pd2(d2);
522 if (!pd2.exists()) 522 if (!pd2.exists())
523 { 523 {
524 QDir pd2(QDir::homeDirPath() + "Documents/application"); 524 QDir pd2(QDir::homeDirPath() + "Documents/application");
525 if (!pd2.mkdir("zsafe", FALSE)) 525 if (!pd2.mkdir("zsafe", FALSE))
526 { 526 {
527 QMessageBox::critical( 0, tr("ZSafe"), 527 QMessageBox::critical( 0, tr("ZSafe"),
528#ifdef JPATCH_HDE 528#ifdef JPATCH_HDE
529 tr("Can't create directory\n...//Documents/application/zsafe\n\nZSafe will now exit.")); 529 tr("Can't create directory\n...//Documents/application/zsafe\n\nZSafe will now exit."));
530#else 530#else
531 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d2)); 531 tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d2));
532#endif 532#endif
533 exitZs (1); 533 exitZs (1);
534 } 534 }
535 } 535 }
536 536
537 537
538 // set the default filename 538 // set the default filename
539 filename=d2 + "/passwords.zsf"; 539 filename=d2 + "/passwords.zsf";
540 540
541 // save the current filename to the config file 541 // save the current filename to the config file
542 conf->writeEntry(APP_KEY+"document", filename); 542 conf->writeEntry(APP_KEY+"document", filename);
543 saveConf(); 543 saveConf();
544 } 544 }
545 545
546 //if (filename == "INVALIDPWD") 546 //if (filename == "INVALIDPWD")
547 //filename = ""; 547 //filename = "";
548 548
549 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 549 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
550#ifdef WIN32 550#ifdef WIN32
551 this->setCaption("Qt ZSafe: " + ti); 551 this->setCaption("Qt ZSafe: " + ti);
552#else 552#else
553 this->setCaption("ZSafe: " + ti); 553 this->setCaption("ZSafe: " + ti);
554#endif 554#endif
555 555
556 selectedItem = NULL; 556 selectedItem = NULL;
557 lastSearchedCategory = NULL; 557 lastSearchedCategory = NULL;
558 lastSearchedItem = NULL; 558 lastSearchedItem = NULL;
559 lastSearchedName = ""; 559 lastSearchedName = "";
560 lastSearchedUsername = ""; 560 lastSearchedUsername = "";
561 lastSearchedComment = ""; 561 lastSearchedComment = "";
562 562
563 infoForm = new InfoForm(); 563 infoForm = new InfoForm();
564 categoryDialog = NULL; 564 categoryDialog = NULL;
565 565
566 // add a menu bar 566 // add a menu bar
567 QMenuBar *menu = new QMenuBar( this ); 567 QMenuBar *menu = new QMenuBar( this );
568 568
569 // add file menu 569 // add file menu
570 // QPopupMenu *file = new QPopupMenu( this ); 570 // QPopupMenu *file = new QPopupMenu( this );
571 file = new QPopupMenu( this ); 571 file = new QPopupMenu( this );
572 572
573// #ifdef DESKTOP 573// #ifdef DESKTOP
574 file->insertItem( new_img, tr("&New document"), this, SLOT(newDocument()) ); 574 file->insertItem( new_img, tr("&New document"), this, SLOT(newDocument()) );
575 file->insertItem( folder_open_img, tr("&Open document"), this, SLOT(loadDocument()) ); 575 file->insertItem( folder_open_img, tr("&Open document"), this, SLOT(loadDocument()) );
576 file->insertItem( save_img, tr("&Save document as .."), this, SLOT(saveDocumentAs()) ); 576 file->insertItem( save_img, tr("&Save document as .."), this, SLOT(saveDocumentAs()) );
577 file->insertSeparator(); 577 file->insertSeparator();
578// #endif 578// #endif
579 579
580 file->insertItem( save_img, tr("&Save document"), this, SLOT(saveDocumentWithoutPwd()) ); 580 file->insertItem( save_img, tr("&Save document"), this, SLOT(saveDocumentWithoutPwd()) );
581 file->insertItem( save_img, tr("S&ave document with new Password"), this, 581 file->insertItem( save_img, tr("S&ave document with new Password"), this,
582 SLOT(saveDocumentWithPwd()) ); 582 SLOT(saveDocumentWithPwd()) );
583 file->insertSeparator(); 583 file->insertSeparator();
584 file->insertItem( export_img, tr("&Export text file"), this, SLOT(writeAllEntries()) ); 584 file->insertItem( export_img, tr("&Export text file"), this, SLOT(writeAllEntries()) );
585 file->insertItem( import_img, tr("&Import text file"), this, SLOT(readAllEntries()) ); 585 file->insertItem( import_img, tr("&Import text file"), this, SLOT(readAllEntries()) );
586 file->insertItem( trash_img, tr("&Remove text file"), this, SLOT(removeAsciiFile()) ); 586 file->insertItem( trash_img, tr("&Remove text file"), this, SLOT(removeAsciiFile()) );
587 file->insertSeparator(); 587 file->insertSeparator();
588 file->insertItem( expand_img, tr("&Open entries expanded"), this, 588 file->insertItem( expand_img, tr("&Open entries expanded"), this,
589 SLOT(setExpandFlag()), 0, 'o'); 589 SLOT(setExpandFlag()), 0, 'o');
590 file->setItemChecked('o', expandTree); 590 file->setItemChecked('o', expandTree);
591 file->insertSeparator(); 591 file->insertSeparator();
592 file->insertItem( quit_icon_img, tr("E&xit"), this, SLOT(quitMe()) ); 592 file->insertItem( quit_icon_img, tr("E&xit"), this, SLOT(quitMe()) );
593 menu->insertItem( tr("&File"), file ); 593 menu->insertItem( tr("&File"), file );
594 594
595 QPopupMenu *cat = new QPopupMenu( this ); 595 QPopupMenu *cat = new QPopupMenu( this );
596 cat->insertItem( new_img, tr("&New"), this, SLOT(addCategory()) ); 596 cat->insertItem( new_img, tr("&New"), this, SLOT(addCategory()) );
597 cat->insertItem( edit_img, tr("&Edit"), this, SLOT(editCategory()) ); 597 cat->insertItem( edit_img, tr("&Edit"), this, SLOT(editCategory()) );
598 cat->insertItem( trash_img, tr("&Delete"), this, SLOT(delCategory()) ); 598 cat->insertItem( trash_img, tr("&Delete"), this, SLOT(delCategory()) );
599 menu->insertItem( tr("&Category"), cat ); 599 menu->insertItem( tr("&Category"), cat );
600 600
601 QPopupMenu *it = new QPopupMenu( this ); 601 QPopupMenu *it = new QPopupMenu( this );
602 it->insertItem( cut_img, tr("&Cut"), this, SLOT(cutItem()) ); 602 it->insertItem( cut_img, tr("&Cut"), this, SLOT(cutItem()) );
603 it->insertItem( copy_img, tr("C&opy"), this, SLOT(copyItem()) ); 603 it->insertItem( copy_img, tr("C&opy"), this, SLOT(copyItem()) );
604 it->insertItem( paste_img, tr("&Paste"), this, SLOT(pasteItem()) ); 604 it->insertItem( paste_img, tr("&Paste"), this, SLOT(pasteItem()) );
605 it->insertSeparator(); 605 it->insertSeparator();
606 it->insertItem( new_img, tr("&New"), this, SLOT(newPwd()) ); 606 it->insertItem( new_img, tr("&New"), this, SLOT(newPwd()) );
607 it->insertItem( edit_img, tr("&Edit"), this, SLOT(editPwd()) ); 607 it->insertItem( edit_img, tr("&Edit"), this, SLOT(editPwd()) );
608 it->insertItem( trash_img, tr("&Delete"), this, SLOT(deletePwd()) ); 608 it->insertItem( trash_img, tr("&Delete"), this, SLOT(deletePwd()) );
609 it->insertItem( find_img, tr("&Search"), this, SLOT(findPwd()) ); 609 it->insertItem( find_img, tr("&Search"), this, SLOT(findPwd()) );
610 menu->insertItem( tr("&Entry"), it ); 610 menu->insertItem( tr("&Entry"), it );
611 611
612 QPopupMenu *help = new QPopupMenu( this ); 612 QPopupMenu *help = new QPopupMenu( this );
613 help->insertItem( help_icon_img, tr("&About"), this, SLOT(about()) ); 613 help->insertItem( help_icon_img, tr("&About"), this, SLOT(about()) );
614 menu->insertItem( tr("&Help"), help ); 614 menu->insertItem( tr("&Help"), help );
615 615
616 // toolbar icons 616 // toolbar icons
617 617
618 New = new QToolButton( menu, "New" ); 618 New = new QToolButton( menu, "New" );
619 New->setGeometry( QRect( DeskW-84, 2, 20, 20 ) ); 619 New->setGeometry( QRect( DeskW-84, 2, 20, 20 ) );
620 New->setMouseTracking( TRUE ); 620 New->setMouseTracking( TRUE );
621 New->setText( tr( "" ) ); 621 New->setText( tr( "" ) );
622 New->setPixmap( new_img ); 622 New->setPixmap( new_img );
623 QToolTip::add( New, tr( "New entry" ) ); 623 QToolTip::add( New, tr( "New entry" ) );
624 624
625 Edit = new QToolButton( menu, "Edit" ); 625 Edit = new QToolButton( menu, "Edit" );
626 Edit->setGeometry( QRect( DeskW-64, 2, 20, 20 ) ); 626 Edit->setGeometry( QRect( DeskW-64, 2, 20, 20 ) );
627 Edit->setText( tr( "" ) ); 627 Edit->setText( tr( "" ) );
628 Edit->setPixmap( edit_img ); 628 Edit->setPixmap( edit_img );
629 QToolTip::add( Edit, tr( "Edit category or entry" ) ); 629 QToolTip::add( Edit, tr( "Edit category or entry" ) );
630 630
631 Delete = new QToolButton( menu, "Delete" ); 631 Delete = new QToolButton( menu, "Delete" );
632 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) ); 632 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) );
633 Delete->setText( tr( "" ) ); 633 Delete->setText( tr( "" ) );
634 Delete->setPixmap( trash_img ); 634 Delete->setPixmap( trash_img );
635 QToolTip::add( Delete, tr( "Delete category or entry" ) ); 635 QToolTip::add( Delete, tr( "Delete category or entry" ) );
636 636
637 Find = new QToolButton( menu, "Find" ); 637 Find = new QToolButton( menu, "Find" );
638 Find->setGeometry( QRect( DeskW-24, 2, 20, 20 ) ); 638 Find->setGeometry( QRect( DeskW-24, 2, 20, 20 ) );
639 Find->setText( tr( "" ) ); 639 Find->setText( tr( "" ) );
640 Find->setPixmap( find_img ); 640 Find->setPixmap( find_img );
641 QToolTip::add( Find, tr( "Find entry" ) ); 641 QToolTip::add( Find, tr( "Find entry" ) );
642 642
643/* 643/*
644 QBoxLayout * h = new QHBoxLayout( this ); 644 QBoxLayout * h = new QHBoxLayout( this );
645 h->addWidget (menu); 645 h->addWidget (menu);
646 h->addWidget (New); 646 h->addWidget (New);
647 h->addWidget (Edit); 647 h->addWidget (Edit);
648 h->addWidget (Delete); 648 h->addWidget (Delete);
649 h->addWidget (Find); 649 h->addWidget (Find);
650*/ 650*/
651 651
652 ListView = new ZListView( this, "ListView" ); 652 ListView = new ZListView( this, "ListView" );
653 ListView->addColumn( tr( "Name" ) ); 653 ListView->addColumn( tr( "Name" ) );
654 ListView->addColumn( tr( "Field 2" ) ); 654 ListView->addColumn( tr( "Field 2" ) );
655 ListView->addColumn( tr( "Field 3" ) ); 655 ListView->addColumn( tr( "Field 3" ) );
656 ListView->addColumn( tr( "Comment" ) ); 656 ListView->addColumn( tr( "Comment" ) );
657 ListView->addColumn( tr( "Field 4" ) ); 657 ListView->addColumn( tr( "Field 4" ) );
658 ListView->addColumn( tr( "Field 5" ) ); 658 ListView->addColumn( tr( "Field 5" ) );
659 ListView->setAllColumnsShowFocus(TRUE); 659 ListView->setAllColumnsShowFocus(TRUE);
660 660
661#ifdef DESKTOP 661#ifdef DESKTOP
662 ListView->setResizePolicy(QScrollView::AutoOneFit); 662 ListView->setResizePolicy(QScrollView::AutoOneFit);
663 // ListView->setGeometry( QRect( 0, 22, this->width(), this->height() - 30 ) ); 663 // ListView->setGeometry( QRect( 0, 22, this->width(), this->height() - 30 ) );
664#else 664#else
665 ListView->setResizePolicy(QScrollView::AutoOneFit); 665 ListView->setResizePolicy(QScrollView::AutoOneFit);
666 // ListView->setGeometry( QRect( 0, 22, 666 // ListView->setGeometry( QRect( 0, 22,
667 // this->width(), this->height() - 30 ) ); 667 // this->width(), this->height() - 30 ) );
668 // ListView->setMaximumSize( QSize( 440, 290 ) ); 668 // ListView->setMaximumSize( QSize( 440, 290 ) );
669#endif 669#endif
670 ListView->setVScrollBarMode( QListView::Auto ); 670 ListView->setVScrollBarMode( QListView::Auto );
671 671
672 QBoxLayout * l = new QVBoxLayout( this ); 672 QBoxLayout * l = new QVBoxLayout( this );
673 l->addWidget (menu); 673 l->addWidget (menu);
674 l->addWidget (ListView); 674 l->addWidget (ListView);
675 675
676#ifndef DESKTOP 676#ifndef DESKTOP
677 // start a timer (100 ms) to load the default document 677 // start a timer (100 ms) to load the default document
678 docuTimer.start( 100, true ); 678 docuTimer.start( 100, true );
679 connect( &docuTimer, SIGNAL(timeout()), SLOT( slotLoadDocu() ) ); 679 connect( &docuTimer, SIGNAL(timeout()), SLOT( slotLoadDocu() ) );
680 raiseFlag = true; 680 raiseFlag = true;
681 connect( &raiseTimer, SIGNAL(timeout()), SLOT( slotRaiseTimer() ) ); 681 connect( &raiseTimer, SIGNAL(timeout()), SLOT( slotRaiseTimer() ) );
682#else 682#else
683 // open the default document 683 // open the default document
684 openDocument(filename); 684 openDocument(filename);
685#endif 685#endif
686 686
687 // signals and slots connections for QTollButton 687 // signals and slots connections for QTollButton
688 connect( New, SIGNAL( clicked() ), this, SLOT( newPwd() ) ); 688 connect( New, SIGNAL( clicked() ), this, SLOT( newPwd() ) );
689 connect( Edit, SIGNAL( clicked() ), this, SLOT( editPwd() ) ); 689 connect( Edit, SIGNAL( clicked() ), this, SLOT( editPwd() ) );
690 connect( Delete, SIGNAL( clicked() ), this, SLOT( deletePwd() ) ); 690 connect( Delete, SIGNAL( clicked() ), this, SLOT( deletePwd() ) );
691 connect( Find, SIGNAL( clicked() ), this, SLOT( findPwd() ) ); 691 connect( Find, SIGNAL( clicked() ), this, SLOT( findPwd() ) );
692 // signals and slots connections for QListView 692 // signals and slots connections for QListView
693 connect( ListView, SIGNAL( selectionChanged( QListViewItem* ) ), 693 connect( ListView, SIGNAL( selectionChanged(QListViewItem*) ),
694 this, SLOT( listViewSelected( QListViewItem* ) ) ); 694 this, SLOT( listViewSelected(QListViewItem*) ) );
695 connect( ListView, SIGNAL( doubleClicked( QListViewItem* ) ), 695 connect( ListView, SIGNAL( doubleClicked(QListViewItem*) ),
696 this, SLOT( showInfo( QListViewItem* ) ) ); 696 this, SLOT( showInfo(QListViewItem*) ) );
697 connect( ListView, SIGNAL( returnPressed( QListViewItem* ) ), 697 connect( ListView, SIGNAL( returnPressed(QListViewItem*) ),
698 this, SLOT( showInfo( QListViewItem* ) ) ); 698 this, SLOT( showInfo(QListViewItem*) ) );
699 699
700} 700}
701 701
702const QColor *ZSafe::evenRowColor = &Qt::white; 702const QColor *ZSafe::evenRowColor = &Qt::white;
703// const QColor *ZSafe::oddRowColor = &Qt::lightGray; 703// const QColor *ZSafe::oddRowColor = &Qt::lightGray;
704const QColor *ZSafe::oddRowColor = new QColor(216,240,255); 704const QColor *ZSafe::oddRowColor = new QColor(216,240,255);
705 705
706/* 706/*
707 * Destroys the object and frees any allocated resources 707 * Destroys the object and frees any allocated resources
708 */ 708 */
709ZSafe::~ZSafe() 709ZSafe::~ZSafe()
710{ 710{
711 // no need to delete child widgets, Qt does it all for us 711 // no need to delete child widgets, Qt does it all for us
712 quitMe(); 712 quitMe();
713} 713}
714 714
715// load the default document 715// load the default document
716void ZSafe::slotLoadDocu() 716void ZSafe::slotLoadDocu()
717{ 717{
718 openDocument (filename); 718 openDocument (filename);
719} 719}
720 720
721void ZSafe::deletePwd() 721void ZSafe::deletePwd()
722{ 722{
723 723
724 if (!selectedItem) 724 if (!selectedItem)
725 return; 725 return;
726 if (!isCategory(selectedItem)) 726 if (!isCategory(selectedItem))
727 { 727 {
728 switch( QMessageBox::information( this, tr("ZSafe"), 728 switch( QMessageBox::information( this, tr("ZSafe"),
729 tr("Do you want to delete?"), 729 tr("Do you want to delete?"),
730 tr("&Delete"), tr("D&on't Delete"), 730 tr("&Delete"), tr("D&on't Delete"),
731 0 // Enter == button 0 731 0 // Enter == button 0
732 ) ) { // Escape == button 2 732 ) ) { // Escape == button 2
733 case 0: // Delete clicked, Alt-S or Enter pressed. 733 case 0: // Delete clicked, Alt-S or Enter pressed.
734 // Delete 734 // Delete
735 modified = true; 735 modified = true;
736 selectedItem->parent()->takeItem(selectedItem); 736 selectedItem->parent()->takeItem(selectedItem);
737 selectedItem = NULL; 737 selectedItem = NULL;
738 break; 738 break;
739 case 1: // Don't delete 739 case 1: // Don't delete
740 break; 740 break;
741 } 741 }
742 } 742 }
743 else 743 else
744 { 744 {
745 delCategory(); 745 delCategory();
746 } 746 }
747} 747}
748 748
749void ZSafe::editPwd() 749void ZSafe::editPwd()
750{ 750{
751 if (!selectedItem) 751 if (!selectedItem)
752 return; 752 return;
753 if (!isCategory(selectedItem)) 753 if (!isCategory(selectedItem))
754 { 754 {
755 // open the 'New Entry' dialog 755 // open the 'New Entry' dialog
756 NewDialog *dialog = new NewDialog(this, tr("Edit Entry"), TRUE); 756 NewDialog *dialog = new NewDialog(this, tr("Edit Entry"), TRUE);
757#ifdef WIN32 757#ifdef WIN32
758 dialog->setCaption ("Qt " + tr("Edit Entry")); 758 dialog->setCaption ("Qt " + tr("Edit Entry"));
759 dialog->setGeometry(200, 250, 220, 310 ); 759 dialog->setGeometry(200, 250, 220, 310 );
760#endif 760#endif
761 761
762 // set the labels 762 // set the labels
763 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name"))); 763 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name")));
764 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username"))); 764 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username")));
765 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password"))); 765 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password")));
766 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); 766 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment")));
767 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4"))); 767 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4")));
768 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5"))); 768 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5")));
769 769
770 // set the fields 770 // set the fields
771 dialog->NameField->setText(selectedItem->text (0)); 771 dialog->NameField->setText(selectedItem->text (0));
772 dialog->UsernameField->setText(selectedItem->text (1)); 772 dialog->UsernameField->setText(selectedItem->text (1));
773 dialog->PasswordField->setText(selectedItem->text (2)); 773 dialog->PasswordField->setText(selectedItem->text (2));
774 QString comment = selectedItem->text (3); 774 QString comment = selectedItem->text (3);
775 comment.replace (QRegExp("<br>"), "\n"); 775 comment.replace (QRegExp("<br>"), "\n");
776 dialog->Field5->setText(selectedItem->text (4)); 776 dialog->Field5->setText(selectedItem->text (4));
777 dialog->Field6->setText(selectedItem->text (5)); 777 dialog->Field6->setText(selectedItem->text (5));
778 dialog->CommentField->insertLine(comment); 778 dialog->CommentField->insertLine(comment);
779 dialog->CommentField->setCursorPosition(0,0); 779 dialog->CommentField->setCursorPosition(0,0);
780 780
781 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog ); 781 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog );
782 782
783#ifdef DESKTOP 783#ifdef DESKTOP
784 result = Accepted; 784 result = Accepted;
785#endif 785#endif
786 if (result == Accepted) 786 if (result == Accepted)
787 { 787 {
788 modified = true; 788 modified = true;
789 // edit the selected item 789 // edit the selected item
790 QString name = dialog->NameField->text(); 790 QString name = dialog->NameField->text();
791 selectedItem->setText (0, tr (name)); 791 selectedItem->setText (0, tr (name));
792 QString user = dialog->UsernameField->text(); 792 QString user = dialog->UsernameField->text();
793 selectedItem->setText (1, tr (user)); 793 selectedItem->setText (1, tr (user));
794 QString pwd = dialog->PasswordField->text(); 794 QString pwd = dialog->PasswordField->text();
795 selectedItem->setText (2, tr (pwd)); 795 selectedItem->setText (2, tr (pwd));
796 QString comment = dialog->CommentField->text(); 796 QString comment = dialog->CommentField->text();
797 comment.replace (QRegExp("\n"), "<br>"); 797 comment.replace (QRegExp("\n"), "<br>");
798 selectedItem->setText (3, tr (comment)); 798 selectedItem->setText (3, tr (comment));
799 QString f5 = dialog->Field5->text(); 799 QString f5 = dialog->Field5->text();
800 selectedItem->setText (4, tr (f5)); 800 selectedItem->setText (4, tr (f5));
801 QString f6 = dialog->Field6->text(); 801 QString f6 = dialog->Field6->text();
802 selectedItem->setText (5, tr (f6)); 802 selectedItem->setText (5, tr (f6));
803 } 803 }
804 804
805 delete dialog; 805 delete dialog;
806 } 806 }
807 else 807 else
808 { 808 {
809 editCategory(); 809 editCategory();
810 } 810 }
811} 811}
812 812
813void ZSafe::newPwd() 813void ZSafe::newPwd()
814{ 814{
815 if (!selectedItem) 815 if (!selectedItem)
816 return; 816 return;
817 817
818 if (!isCategory(selectedItem)) 818 if (!isCategory(selectedItem))
819 selectedItem = selectedItem->parent(); 819 selectedItem = selectedItem->parent();
820 820
821 if (isCategory(selectedItem)) 821 if (isCategory(selectedItem))
822 { 822 {
823 QString cat = selectedItem->text(0); 823 QString cat = selectedItem->text(0);
824 824
825 // open the 'New Entry' dialog 825 // open the 'New Entry' dialog
826 NewDialog *dialog = new NewDialog(this, tr("New Entry"), TRUE); 826 NewDialog *dialog = new NewDialog(this, tr("New Entry"), TRUE);
827#ifdef WIN32 827#ifdef WIN32
828 dialog->setCaption ("Qt " + tr("New Entry")); 828 dialog->setCaption ("Qt " + tr("New Entry"));
829 dialog->setGeometry(200, 250, 220, 310 ); 829 dialog->setGeometry(200, 250, 220, 310 );
830#endif 830#endif
831 // set the labels 831 // set the labels
832 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name"))); 832 dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name")));
833 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username"))); 833 dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username")));
834 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password"))); 834 dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password")));
835 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); 835 dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment")));
836 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4"))); 836 dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4")));
837 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5"))); 837 dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5")));
838retype: 838retype:
839 839
840 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog ); 840 DialogCode result = (DialogCode) QPEApplication::execDialog( dialog );
841#ifdef DESKTOP 841#ifdef DESKTOP
842 result = Accepted; 842 result = Accepted;
843#endif 843#endif
844 844
845 if (result == Accepted) 845 if (result == Accepted)
846 { 846 {
847 847
848 QString name = dialog->NameField->text(); 848 QString name = dialog->NameField->text();
849 if (cat == name) 849 if (cat == name)
850 { 850 {
851 QMessageBox::critical( 0, tr("ZSafe"), 851 QMessageBox::critical( 0, tr("ZSafe"),
852 tr("Entry name must be different\nfrom the category name.") ); 852 tr("Entry name must be different\nfrom the category name.") );
853 goto retype; // it's not a good programming style :-) 853 goto retype; // it's not a good programming style :-)
854 } 854 }
855 855
856 modified = true; 856 modified = true;
857 // add the new item 857 // add the new item
858 QListViewItem *i = new ShadedListItem (0, selectedItem); 858 QListViewItem *i = new ShadedListItem (0, selectedItem);
859 i->setOpen (TRUE); 859 i->setOpen (TRUE);
860 860
861 i->setText (0, tr (name)); 861 i->setText (0, tr (name));
862 QString user = dialog->UsernameField->text(); 862 QString user = dialog->UsernameField->text();
863 i->setText (1, tr (user)); 863 i->setText (1, tr (user));
864 QString pwd = dialog->PasswordField->text(); 864 QString pwd = dialog->PasswordField->text();
865 i->setText (2, tr (pwd)); 865 i->setText (2, tr (pwd));
866 QString comment = dialog->CommentField->text(); 866 QString comment = dialog->CommentField->text();
867 comment.replace (QRegExp("\n"), "<br>"); 867 comment.replace (QRegExp("\n"), "<br>");
868 i->setText (3, tr (comment)); 868 i->setText (3, tr (comment));
869 QString f5 = dialog->Field5->text(); 869 QString f5 = dialog->Field5->text();
870 i->setText (4, tr (f5)); 870 i->setText (4, tr (f5));
871 QString f6 = dialog->Field6->text(); 871 QString f6 = dialog->Field6->text();
872 i->setText (5, tr (f6)); 872 i->setText (5, tr (f6));
873 } 873 }
874 874
875 delete dialog; 875 delete dialog;
876 } 876 }
877} 877}
878 878
879void ZSafe::findPwd() 879void ZSafe::findPwd()
880{ 880{
881 881
882 // open the 'Search' dialog 882 // open the 'Search' dialog
883 SearchDialog *dialog = new SearchDialog(this, tr("Search"), TRUE); 883 SearchDialog *dialog = new SearchDialog(this, tr("Search"), TRUE);
884#ifdef WIN32 884#ifdef WIN32
885 dialog->setCaption ("Qt " + tr("Search")); 885 dialog->setCaption ("Qt " + tr("Search"));
886#endif 886#endif
887 887
888#ifdef DESKTOP 888#ifdef DESKTOP
889#endif 889#endif
890 if (lastSearchedName) 890 if (lastSearchedName)
891 dialog->NameField->setText(lastSearchedName); 891 dialog->NameField->setText(lastSearchedName);
892 else 892 else
893 dialog->NameField->setText(""); 893 dialog->NameField->setText("");
894 if (lastSearchedUsername) 894 if (lastSearchedUsername)
895 dialog->UsernameField->setText(lastSearchedUsername); 895 dialog->UsernameField->setText(lastSearchedUsername);
896 else 896 else
897 dialog->UsernameField->setText(""); 897 dialog->UsernameField->setText("");
898 if (lastSearchedComment) 898 if (lastSearchedComment)
899 dialog->CommentField->setText(lastSearchedComment); 899 dialog->CommentField->setText(lastSearchedComment);
900 else 900 else
901 dialog->CommentField->setText(""); 901 dialog->CommentField->setText("");
902 DialogCode result = (DialogCode) dialog->exec(); 902 DialogCode result = (DialogCode) dialog->exec();
903#ifdef DESKTOP 903#ifdef DESKTOP
904 result = Accepted; 904 result = Accepted;
905#endif 905#endif
906 906
907 QString name; 907 QString name;
908 QString username; 908 QString username;
909 QString comment; 909 QString comment;
910 if (result == Accepted) 910 if (result == Accepted)
911 { 911 {
912 name = dialog->NameField->text(); 912 name = dialog->NameField->text();
913 username = dialog->UsernameField->text(); 913 username = dialog->UsernameField->text();
914 comment = dialog->CommentField->text(); 914 comment = dialog->CommentField->text();
915 qWarning (name); 915 qWarning (name);
916 } 916 }
917 else 917 else
918 { 918 {
919 delete dialog; 919 delete dialog;
920 return; 920 return;
921 } 921 }
922 922
923 if (!name.isEmpty() && name != lastSearchedName || 923 if (!name.isEmpty() && name != lastSearchedName ||
924 lastSearchedName.isEmpty() && !name.isEmpty()) 924 lastSearchedName.isEmpty() && !name.isEmpty())
925 { 925 {
926 // set search at the beginning if a new name is given 926 // set search at the beginning if a new name is given
927 lastSearchedCategory = NULL; 927 lastSearchedCategory = NULL;
928 lastSearchedItem = NULL; 928 lastSearchedItem = NULL;
929 } 929 }
930 lastSearchedName = name; 930 lastSearchedName = name;
931 if (!username.isEmpty() && username != lastSearchedUsername || 931 if (!username.isEmpty() && username != lastSearchedUsername ||
932 lastSearchedUsername.isEmpty() && !username.isEmpty()) 932 lastSearchedUsername.isEmpty() && !username.isEmpty())
933 { 933 {
934 // set search at the beginning if a new name is given 934 // set search at the beginning if a new name is given
935 lastSearchedCategory = NULL; 935 lastSearchedCategory = NULL;
936 lastSearchedItem = NULL; 936 lastSearchedItem = NULL;
937 } 937 }
938 lastSearchedUsername = username; 938 lastSearchedUsername = username;
939 if (!comment.isEmpty() && comment != lastSearchedComment || 939 if (!comment.isEmpty() && comment != lastSearchedComment ||
940 lastSearchedComment.isEmpty() && !comment.isEmpty()) 940 lastSearchedComment.isEmpty() && !comment.isEmpty())
941 { 941 {
942 // set search at the beginning if a new name is given 942 // set search at the beginning if a new name is given
943 lastSearchedCategory = NULL; 943 lastSearchedCategory = NULL;
944 lastSearchedItem = NULL; 944 lastSearchedItem = NULL;
945 } 945 }
946 lastSearchedComment = comment; 946 lastSearchedComment = comment;
947 947
948 ListView->clearSelection(); 948 ListView->clearSelection();
949 949
950 bool found=FALSE; 950 bool found=FALSE;
951 // step through all categories 951 // step through all categories
952 QListViewItem *i; 952 QListViewItem *i;
953 if (lastSearchedCategory) 953 if (lastSearchedCategory)
954 i = lastSearchedCategory; 954 i = lastSearchedCategory;
955 else 955 else
956 i = ListView->firstChild(); 956 i = ListView->firstChild();
957 for (; 957 for (;
958 i != NULL; 958 i != NULL;
959 i = i->nextSibling()) 959 i = i->nextSibling())
960 { 960 {
961 qWarning (i->text(0)); 961 qWarning (i->text(0));
962 i->setSelected(FALSE); 962 i->setSelected(FALSE);
963 963
964 // step through all subitems 964 // step through all subitems
965 QListViewItem *si; 965 QListViewItem *si;
966 if (lastSearchedItem) 966 if (lastSearchedItem)
967 si = lastSearchedItem; 967 si = lastSearchedItem;
968 else 968 else
969 si = i->firstChild(); 969 si = i->firstChild();
970 // for (si = i->firstChild(); 970 // for (si = i->firstChild();
971 for (; 971 for (;
972 si != NULL; 972 si != NULL;
973 si = si->nextSibling()) 973 si = si->nextSibling())
974 { 974 {
975 qWarning (si->text(0)); 975 qWarning (si->text(0));
976 if (si->isSelected()) 976 if (si->isSelected())
977 si->setSelected(FALSE); 977 si->setSelected(FALSE);
978 // ListView->repaintItem(si); 978 // ListView->repaintItem(si);
979 979
980 bool n=TRUE; 980 bool n=TRUE;
981 bool u=TRUE; 981 bool u=TRUE;
982 bool c=TRUE; 982 bool c=TRUE;
983 if (!name.isEmpty()) 983 if (!name.isEmpty())
984 n = (si->text(0)).contains (name, FALSE); 984 n = (si->text(0)).contains (name, FALSE);
985 if (!username.isEmpty()) 985 if (!username.isEmpty())
986 u = (si->text(1)).contains (username, FALSE); 986 u = (si->text(1)).contains (username, FALSE);
987 if (!comment.isEmpty()) 987 if (!comment.isEmpty())
988 c = (si->text(3)).contains (comment, FALSE); 988 c = (si->text(3)).contains (comment, FALSE);
989 989
990 if ((n && u && c ) && !found) 990 if ((n && u && c ) && !found)
991 { 991 {
992 qWarning ("Found"); 992 qWarning ("Found");
993 selectedItem = si; 993 selectedItem = si;
994 si->setSelected(TRUE); 994 si->setSelected(TRUE);
995 ListView->setCurrentItem(si); 995 ListView->setCurrentItem(si);
996 ListView->ensureItemVisible(si); 996 ListView->ensureItemVisible(si);
997 ListView->triggerUpdate(); 997 ListView->triggerUpdate();
998 998
999 lastSearchedCategory = i; 999 lastSearchedCategory = i;
1000 // set to the next item 1000 // set to the next item
1001 lastSearchedItem = si->nextSibling(); 1001 lastSearchedItem = si->nextSibling();
1002 if (!lastSearchedItem) 1002 if (!lastSearchedItem)
1003 { 1003 {
1004 // no next item within category -> set next category 1004 // no next item within category -> set next category
1005 lastSearchedCategory = i->nextSibling(); 1005 lastSearchedCategory = i->nextSibling();
1006 if (!lastSearchedCategory) 1006 if (!lastSearchedCategory)
1007 lastSearchedItem = NULL; // END 1007 lastSearchedItem = NULL; // END
1008 } 1008 }
1009 1009
1010 found = TRUE; 1010 found = TRUE;
1011 delete dialog; 1011 delete dialog;
1012 update(); 1012 update();
1013 return; 1013 return;
1014 } 1014 }
1015 } 1015 }
1016 lastSearchedCategory = i->nextSibling(); 1016 lastSearchedCategory = i->nextSibling();
1017 lastSearchedItem = NULL; 1017 lastSearchedItem = NULL;
1018 } 1018 }
1019 lastSearchedCategory = NULL; 1019 lastSearchedCategory = NULL;
1020 lastSearchedItem = NULL; 1020 lastSearchedItem = NULL;
1021 delete dialog; 1021 delete dialog;
1022 update(); 1022 update();
1023 QMessageBox::information( this, tr("ZSafe"), 1023 QMessageBox::information( this, tr("ZSafe"),
1024 tr("Entry not found"), tr("&OK"), 0); 1024 tr("Entry not found"), tr("&OK"), 0);
1025 1025
1026} 1026}
1027 1027
1028QString ZSafe::getFieldLabel (QListViewItem *_item, QString field, QString def) 1028QString ZSafe::getFieldLabel (QListViewItem *_item, QString field, QString def)
1029{ 1029{
1030 QString category; 1030 QString category;
1031 if (_item) 1031 if (_item)
1032 { 1032 {
1033 if (isCategory(_item)) 1033 if (isCategory(_item))
1034 { 1034 {
1035 category = _item->text(0); 1035 category = _item->text(0);
1036 } 1036 }
1037 else 1037 else
1038 { 1038 {
1039 QListViewItem *cat = _item->parent(); 1039 QListViewItem *cat = _item->parent();
1040 category = cat->text(0); 1040 category = cat->text(0);
1041 } 1041 }
1042 } 1042 }
1043 else 1043 else
1044 { 1044 {
1045 return def; 1045 return def;
1046 } 1046 }
1047 1047
1048 QString app_key = APP_KEY; 1048 QString app_key = APP_KEY;
1049#ifndef DESKTOP 1049#ifndef DESKTOP
1050#ifndef WIN32 1050#ifndef WIN32
1051 conf->setGroup ("fieldDefs"); 1051 conf->setGroup ("fieldDefs");
1052#endif 1052#endif
1053#else 1053#else
1054#ifndef WIN32 1054#ifndef WIN32
1055 app_key += "/fieldDefs/"; 1055 app_key += "/fieldDefs/";
1056#endif 1056#endif
1057#endif 1057#endif
1058// #ifndef WIN32 1058// #ifndef WIN32
1059 QString label = conf->readEntry(app_key+category+"-field"+field,def); 1059 QString label = conf->readEntry(app_key+category+"-field"+field,def);
1060// #else 1060// #else
1061// QString label(def); 1061// QString label(def);
1062// #endif 1062// #endif
1063 1063
1064#ifndef DESKTOP 1064#ifndef DESKTOP
1065 conf->setGroup ("zsafe"); 1065 conf->setGroup ("zsafe");
1066#endif 1066#endif
1067 return label; 1067 return label;
1068} 1068}
1069 1069
1070QString ZSafe::getFieldLabel (QString category, QString field, QString def) 1070QString ZSafe::getFieldLabel (QString category, QString field, QString def)
1071{ 1071{
1072 QString app_key = APP_KEY; 1072 QString app_key = APP_KEY;
1073#ifndef DESKTOP 1073#ifndef DESKTOP
1074 conf->setGroup ("fieldDefs"); 1074 conf->setGroup ("fieldDefs");
1075#else 1075#else
1076#ifndef WIN32 1076#ifndef WIN32
1077 app_key += "/fieldDefs/"; 1077 app_key += "/fieldDefs/";
1078#endif 1078#endif
1079#endif 1079#endif
1080// #ifndef WIN32 1080// #ifndef WIN32
1081 QString label = conf->readEntry(app_key+category+"-field"+field, 1081 QString label = conf->readEntry(app_key+category+"-field"+field,
1082 def); 1082 def);
1083// #else 1083// #else
1084 // QString label(def); 1084 // QString label(def);
1085// #endif 1085// #endif
1086#ifndef DESKTOP 1086#ifndef DESKTOP
1087 conf->setGroup ("zsafe"); 1087 conf->setGroup ("zsafe");
1088#endif 1088#endif
1089 return label; 1089 return label;
1090} 1090}
1091 1091
1092void ZSafe::showInfo( QListViewItem *_item) 1092void ZSafe::showInfo( QListViewItem *_item)
1093{ 1093{
1094 if (!_item) 1094 if (!_item)
1095 return; 1095 return;
1096 if (selectedItem != NULL) 1096 if (selectedItem != NULL)
1097 selectedItem->setSelected(FALSE); 1097 selectedItem->setSelected(FALSE);
1098 1098
1099 selectedItem = _item; 1099 selectedItem = _item;
1100 selectedItem->setSelected(TRUE); 1100 selectedItem->setSelected(TRUE);
1101 1101
1102 if (!isCategory(_item)) 1102 if (!isCategory(_item))
1103 { 1103 {
1104/* 1104/*
1105 QString label=selectedItem->text(0); 1105 QString label=selectedItem->text(0);
1106 label+="\n"; 1106 label+="\n";
1107 label+=selectedItem->text(1); 1107 label+=selectedItem->text(1);
1108 label+="\n"; 1108 label+="\n";
1109 label+=selectedItem->text(2); 1109 label+=selectedItem->text(2);
1110 label+="\n"; 1110 label+="\n";
1111 label+=selectedItem->text(3); 1111 label+=selectedItem->text(3);
1112*/ 1112*/
1113 1113
1114 QString text; 1114 QString text;
1115 QString entry; 1115 QString entry;
1116 1116
1117 text = "<html><body><div align=""center""><u><b>"; 1117 text = "<html><body><div align=""center""><u><b>";
1118 text += selectedItem->text(0); 1118 text += selectedItem->text(0);
1119 text += "</b></u><br></div><br>"; 1119 text += "</b></u><br></div><br>";
1120 1120
1121 entry = selectedItem->text(1); 1121 entry = selectedItem->text(1);
1122 if (!entry.isEmpty() && entry.compare(" ")) 1122 if (!entry.isEmpty() && entry.compare(" "))
1123 { 1123 {
1124 text += "<u><b>"; 1124 text += "<u><b>";
1125 text += getFieldLabel (selectedItem, "2", tr("Username")); 1125 text += getFieldLabel (selectedItem, "2", tr("Username"));
1126 text += ":<br></b></u><blockquote>"; 1126 text += ":<br></b></u><blockquote>";
1127 text += entry; 1127 text += entry;
1128 text += "</blockquote>"; 1128 text += "</blockquote>";
1129 // text += "<br>"; 1129 // text += "<br>";
1130 } 1130 }
1131 1131
1132 entry = selectedItem->text(2); 1132 entry = selectedItem->text(2);
1133 if (!entry.isEmpty() && entry.compare(" ")) 1133 if (!entry.isEmpty() && entry.compare(" "))
1134 { 1134 {
1135 text += "<u><b>"; 1135 text += "<u><b>";
1136 text += getFieldLabel (selectedItem, "3", tr("Password")); 1136 text += getFieldLabel (selectedItem, "3", tr("Password"));
1137 text += ":<br> </b></u><blockquote>"; 1137 text += ":<br> </b></u><blockquote>";
1138 text += entry; 1138 text += entry;
1139 text += "</blockquote>"; 1139 text += "</blockquote>";
1140 // text += "<br>"; 1140 // text += "<br>";
1141 } 1141 }
1142 1142
1143 entry = selectedItem->text(4); 1143 entry = selectedItem->text(4);
1144 if (!entry.isEmpty() && entry.compare(" ")) 1144 if (!entry.isEmpty() && entry.compare(" "))
1145 { 1145 {
1146 text += "<u><b>"; 1146 text += "<u><b>";
1147 text += getFieldLabel (selectedItem, "5", tr("Field 4")); 1147 text += getFieldLabel (selectedItem, "5", tr("Field 4"));
1148 text += ":<br> </b></u><blockquote>"; 1148 text += ":<br> </b></u><blockquote>";
1149 text += entry; 1149 text += entry;
1150 text += "</blockquote>"; 1150 text += "</blockquote>";
1151 // text += "<br>"; 1151 // text += "<br>";
1152 } 1152 }
1153 1153
1154 entry = selectedItem->text(5); 1154 entry = selectedItem->text(5);
1155 if (!entry.isEmpty() && entry.compare(" ")) 1155 if (!entry.isEmpty() && entry.compare(" "))
1156 { 1156 {
1157 text += "<u><b>"; 1157 text += "<u><b>";
1158 text += getFieldLabel (selectedItem, "6", tr("Field 5")); 1158 text += getFieldLabel (selectedItem, "6", tr("Field 5"));
1159 text += ":<br> </b></u><blockquote>"; 1159 text += ":<br> </b></u><blockquote>";
1160 text += entry; 1160 text += entry;
1161 text += "</blockquote>"; 1161 text += "</blockquote>";
1162 // text += "<br>"; 1162 // text += "<br>";
1163 } 1163 }
1164 1164
1165 entry = selectedItem->text(3); 1165 entry = selectedItem->text(3);
1166 if (!entry.isEmpty() && entry.compare(" ")) 1166 if (!entry.isEmpty() && entry.compare(" "))
1167 { 1167 {
1168 text += "<u><b>"; 1168 text += "<u><b>";
1169 text += getFieldLabel (selectedItem, "4", tr("Comment")); 1169 text += getFieldLabel (selectedItem, "4", tr("Comment"));
1170 text += ":<br> </b></u>"; 1170 text += ":<br> </b></u>";
1171 QString comment = selectedItem->text(3); 1171 QString comment = selectedItem->text(3);
1172 comment.replace (QRegExp("\n"), "<br>"); 1172 comment.replace (QRegExp("\n"), "<br>");
1173 text += comment; 1173 text += comment;
1174 // text += "<br>"; 1174 // text += "<br>";
1175 } 1175 }
1176 1176
1177 text += "</body></html>"; 1177 text += "</body></html>";
1178 1178
1179 infoForm->InfoText->setText(text); 1179 infoForm->InfoText->setText(text);
1180 infoForm->hide(); 1180 infoForm->hide();
1181 QPEApplication::showDialog( infoForm ); 1181 QPEApplication::showDialog( infoForm );
1182 } 1182 }
1183} 1183}
1184 1184
1185void ZSafe::listViewSelected( QListViewItem *_item) 1185void ZSafe::listViewSelected( QListViewItem *_item)
1186{ 1186{
1187 if (!_item) 1187 if (!_item)
1188 return; 1188 return;
1189 if (selectedItem != NULL) 1189 if (selectedItem != NULL)
1190 selectedItem->setSelected(FALSE); 1190 selectedItem->setSelected(FALSE);
1191 1191
1192 selectedItem = _item; 1192 selectedItem = _item;
1193 1193
1194#ifndef DESKTOP 1194#ifndef DESKTOP
1195 // set the column text dependent on the selected item 1195 // set the column text dependent on the selected item
1196 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name"))); 1196 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name")));
1197 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2"))); 1197 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2")));
1198 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3"))); 1198 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3")));
1199 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment"))); 1199 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment")));
1200 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4"))); 1200 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4")));
1201 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5"))); 1201 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5")));
1202#endif 1202#endif
1203#ifdef WIN32 1203#ifdef WIN32
1204 // set the column text dependent on the selected item 1204 // set the column text dependent on the selected item
1205 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name"))); 1205 ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name")));
1206 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2"))); 1206 ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2")));
1207 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3"))); 1207 ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3")));
1208 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment"))); 1208 ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment")));
1209 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4"))); 1209 ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4")));
1210 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5"))); 1210 ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5")));
1211#endif 1211#endif
1212 1212
1213} 1213}
1214 1214
1215bool ZSafe::isCategory(QListViewItem *_item) 1215bool ZSafe::isCategory(QListViewItem *_item)
1216{ 1216{
1217 if (_item == NULL) 1217 if (_item == NULL)
1218 return FALSE; 1218 return FALSE;
1219 1219
1220 QString categoryName = _item->text (0); 1220 QString categoryName = _item->text (0);
1221 if (categories.find (categoryName)) 1221 if (categories.find (categoryName))
1222 return TRUE; 1222 return TRUE;
1223 else 1223 else
1224 return FALSE; 1224 return FALSE;
1225} 1225}
1226 1226
1227void ZSafe::removeAsciiFile() 1227void ZSafe::removeAsciiFile()
1228{ 1228{
1229 // QString fn = filename + ".txt"; 1229 // QString fn = filename + ".txt";
1230 // open the file dialog 1230 // open the file dialog
1231#ifndef DESKTOP 1231#ifndef DESKTOP
1232#ifndef NO_OPIE 1232#ifndef NO_OPIE
1233 QMap<QString, QStringList> mimeTypes; 1233 QMap<QString, QStringList> mimeTypes;
1234 mimeTypes.insert(tr("All"), QStringList() ); 1234 mimeTypes.insert(tr("All"), QStringList() );
1235 mimeTypes.insert(tr("Text"), "text/*" ); 1235 mimeTypes.insert(tr("Text"), "text/*" );
1236 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 1236 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
1237 QDir::homeDirPath() + "/Documents/application/zsafe", 1237 QDir::homeDirPath() + "/Documents/application/zsafe",
1238 QString::null, 1238 QString::null,
1239 mimeTypes, 1239 mimeTypes,
1240 this, 1240 this,
1241 tr ("Remove text file")); 1241 tr ("Remove text file"));
1242#else 1242#else
1243 QString fn = ScQtFileEdit::getOpenFileName(this, 1243 QString fn = ScQtFileEdit::getOpenFileName(this,
1244 tr ("Remove text file"), 1244 tr ("Remove text file"),
1245 QDir::homeDirPath() + "/Documents/application/zsafe", 1245 QDir::homeDirPath() + "/Documents/application/zsafe",
1246 "*.txt"); 1246 "*.txt");
1247#endif 1247#endif
1248#else 1248#else
1249 QString fn = QFileDialog::getOpenFileName( 1249 QString fn = QFileDialog::getOpenFileName(
1250 QDir::homeDirPath() + "/Documents/application/zsafe", 1250 QDir::homeDirPath() + "/Documents/application/zsafe",
1251 "ZSafe (*.txt)", 1251 "ZSafe (*.txt)",
1252 this, 1252 this,
1253 "ZSafe File Dialog" 1253 "ZSafe File Dialog"
1254 "Choose a text file" ); 1254 "Choose a text file" );
1255#endif 1255#endif
1256 1256
1257 if (fn && fn.length() > 0 ) 1257 if (fn && fn.length() > 0 )
1258 { 1258 {
1259 QFile f( fn ); 1259 QFile f( fn );
1260 if ( !f.remove() ) 1260 if ( !f.remove() )
1261 { 1261 {
1262 qWarning( QString("Could not remove file %1").arg(fn), 1262 qWarning( QString("Could not remove file %1").arg(fn),
1263 2000 ); 1263 2000 );
1264 QMessageBox::critical( 0, tr("ZSafe"), 1264 QMessageBox::critical( 0, tr("ZSafe"),
1265 tr("Could not remove text file.") ); 1265 tr("Could not remove text file.") );
1266 return; 1266 return;
1267 } 1267 }
1268 } 1268 }
1269} 1269}
1270 1270
1271void ZSafe::writeAllEntries() 1271void ZSafe::writeAllEntries()
1272{ 1272{
1273 if (filename.isEmpty()) 1273 if (filename.isEmpty())
1274 { 1274 {
1275 QMessageBox::critical( 0, tr("ZSafe"), 1275 QMessageBox::critical( 0, tr("ZSafe"),
1276 tr("No document defined.\nYou have to create a new document")); 1276 tr("No document defined.\nYou have to create a new document"));
1277 return; 1277 return;
1278 } 1278 }
1279 1279
1280 // open the file dialog 1280 // open the file dialog
1281#ifndef DESKTOP 1281#ifndef DESKTOP
1282#ifndef NO_OPIE 1282#ifndef NO_OPIE
1283 QMap<QString, QStringList> mimeTypes; 1283 QMap<QString, QStringList> mimeTypes;
1284 mimeTypes.insert(tr("All"), QStringList() ); 1284 mimeTypes.insert(tr("All"), QStringList() );
1285 mimeTypes.insert(tr("Text"), "text/*" ); 1285 mimeTypes.insert(tr("Text"), "text/*" );
1286 QString fn = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, 1286 QString fn = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL,
1287 QDir::homeDirPath() + "/Documents/application/zsafe", 1287 QDir::homeDirPath() + "/Documents/application/zsafe",
1288 QString::null, 1288 QString::null,
1289 mimeTypes, 1289 mimeTypes,
1290 this, 1290 this,
1291 tr ("Export text file")); 1291 tr ("Export text file"));
1292#else 1292#else
1293 QString fn = ScQtFileEdit::getSaveAsFileName(this, 1293 QString fn = ScQtFileEdit::getSaveAsFileName(this,
1294 tr ("Export text file"), 1294 tr ("Export text file"),
1295 QDir::homeDirPath() + "/Documents/application/zsafe", 1295 QDir::homeDirPath() + "/Documents/application/zsafe",
1296 "*.txt"); 1296 "*.txt");
1297#endif 1297#endif
1298#else 1298#else
1299 QString fn = QFileDialog::getSaveFileName( 1299 QString fn = QFileDialog::getSaveFileName(
1300 QDir::homeDirPath() + "/Documents/application/zsafe", 1300 QDir::homeDirPath() + "/Documents/application/zsafe",
1301 "ZSafe (*.txt)", 1301 "ZSafe (*.txt)",
1302 this, 1302 this,
1303 "ZSafe File Dialog" 1303 "ZSafe File Dialog"
1304 "Choose a text file" ); 1304 "Choose a text file" );
1305#endif 1305#endif
1306 1306
1307 // open the new document 1307 // open the new document
1308 if (fn && fn.length() > 0 ) 1308 if (fn && fn.length() > 0 )
1309 { 1309 {
1310 QFile f( fn ); 1310 QFile f( fn );
1311 if ( !f.open( IO_WriteOnly ) ) { 1311 if ( !f.open( IO_WriteOnly ) ) {
1312 qWarning( QString("Could not write to file %1").arg(fn), 1312 qWarning( QString("Could not write to file %1").arg(fn),
1313 2000 ); 1313 2000 );
1314 QMessageBox::critical( 0, "ZSafe", 1314 QMessageBox::critical( 0, "ZSafe",
1315 QString("Could not export to text file.") ); 1315 QString("Could not export to text file.") );
1316 return; 1316 return;
1317 } 1317 }
1318 QTextStream t( &f ); 1318 QTextStream t( &f );
1319 1319
1320 QListViewItem *i; 1320 QListViewItem *i;
1321 // step through all categories 1321 // step through all categories
1322 for (i = ListView->firstChild(); 1322 for (i = ListView->firstChild();
1323 i != NULL; 1323 i != NULL;
1324 i = i->nextSibling()) 1324 i = i->nextSibling())
1325 { 1325 {
1326 // step through all subitems 1326 // step through all subitems
1327 QListViewItem *si; 1327 QListViewItem *si;
1328 for (si = i->firstChild(); 1328 for (si = i->firstChild();
1329 si != NULL; 1329 si != NULL;
1330 si = si->nextSibling()) 1330 si = si->nextSibling())
1331 { 1331 {
1332 QString oneEntry; 1332 QString oneEntry;
1333 oneEntry += "\""; 1333 oneEntry += "\"";
1334 oneEntry += i->text(0); 1334 oneEntry += i->text(0);
1335 oneEntry += "\";"; 1335 oneEntry += "\";";
1336 oneEntry += "\""; 1336 oneEntry += "\"";
1337 oneEntry += si->text(0); 1337 oneEntry += si->text(0);
1338 oneEntry += "\";"; 1338 oneEntry += "\";";
1339 oneEntry += "\""; 1339 oneEntry += "\"";
1340 oneEntry += si->text(1); 1340 oneEntry += si->text(1);
1341 oneEntry += "\";"; 1341 oneEntry += "\";";
1342 oneEntry += "\""; 1342 oneEntry += "\"";
1343 oneEntry += si->text(2); 1343 oneEntry += si->text(2);
1344 oneEntry += "\";"; 1344 oneEntry += "\";";
1345 oneEntry += "\""; 1345 oneEntry += "\"";
1346 QString comment = si->text(3); 1346 QString comment = si->text(3);
1347 comment.replace (QRegExp("\n"), "<br>"); 1347 comment.replace (QRegExp("\n"), "<br>");
1348 oneEntry += comment; 1348 oneEntry += comment;
1349 oneEntry += "\";"; 1349 oneEntry += "\";";
1350 oneEntry += "\""; 1350 oneEntry += "\"";
1351 oneEntry += si->text(4); 1351 oneEntry += si->text(4);
1352 oneEntry += "\";"; 1352 oneEntry += "\";";
1353 oneEntry += "\""; 1353 oneEntry += "\"";
1354 oneEntry += si->text(5); 1354 oneEntry += si->text(5);
1355 oneEntry += "\""; 1355 oneEntry += "\"";
1356 // qWarning (oneEntry); 1356 // qWarning (oneEntry);
1357 t << oneEntry << endl; 1357 t << oneEntry << endl;
1358 1358
1359 // qWarning (si->text(0)); 1359 // qWarning (si->text(0));
1360 } 1360 }
1361 } 1361 }
1362 f.close(); 1362 f.close();
1363 } 1363 }
1364} 1364}
1365 1365
1366void ZSafe::readAllEntries() 1366void ZSafe::readAllEntries()
1367{ 1367{
1368 if (filename.isEmpty()) 1368 if (filename.isEmpty())
1369 { 1369 {
1370 QMessageBox::critical( 0, tr("ZSafe"), 1370 QMessageBox::critical( 0, tr("ZSafe"),
1371 tr("No document defined.\nYou have to create a new document")); 1371 tr("No document defined.\nYou have to create a new document"));
1372 return; 1372 return;
1373 } 1373 }
1374 1374
1375 // open the file dialog 1375 // open the file dialog
1376#ifndef DESKTOP 1376#ifndef DESKTOP
1377#ifndef NO_OPIE 1377#ifndef NO_OPIE
1378 QMap<QString, QStringList> mimeTypes; 1378 QMap<QString, QStringList> mimeTypes;
1379 mimeTypes.insert(tr("All"), QStringList() ); 1379 mimeTypes.insert(tr("All"), QStringList() );
1380 mimeTypes.insert(tr("Text"), "text/*" ); 1380 mimeTypes.insert(tr("Text"), "text/*" );
1381 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 1381 QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
1382 QDir::homeDirPath() + "/Documents/application/zsafe", 1382 QDir::homeDirPath() + "/Documents/application/zsafe",
1383 QString::null, 1383 QString::null,
1384 mimeTypes, 1384 mimeTypes,
1385 this, 1385 this,
1386 tr ("Import text file")); 1386 tr ("Import text file"));
1387#else 1387#else
1388 QString fn = ScQtFileEdit::getOpenFileName(this, 1388 QString fn = ScQtFileEdit::getOpenFileName(this,
1389 tr ("Import text file"), 1389 tr ("Import text file"),
1390 QDir::homeDirPath() + "/Documents/application/zsafe", 1390 QDir::homeDirPath() + "/Documents/application/zsafe",
1391 "*.txt"); 1391 "*.txt");
1392#endif 1392#endif
1393#else 1393#else
1394 QString fn = QFileDialog::getOpenFileName( 1394 QString fn = QFileDialog::getOpenFileName(
1395 QDir::homeDirPath() + "/Documents/application/zsafe", 1395 QDir::homeDirPath() + "/Documents/application/zsafe",
1396 "ZSafe (*.txt)", 1396 "ZSafe (*.txt)",
1397 this, 1397 this,
1398 "ZSafe File Dialog" 1398 "ZSafe File Dialog"
1399 "Choose a text file" ); 1399 "Choose a text file" );
1400#endif 1400#endif
1401 1401
1402 if (fn && fn.length() > 0 ) 1402 if (fn && fn.length() > 0 )
1403 { 1403 {
1404 QFile f( fn ); 1404 QFile f( fn );
1405 if ( !f.open( IO_ReadOnly ) ) 1405 if ( !f.open( IO_ReadOnly ) )
1406 { 1406 {
1407 qWarning( QString("Could not read file %1").arg(fn), 1407 qWarning( QString("Could not read file %1").arg(fn),
1408 2000 ); 1408 2000 );
1409 QMessageBox::critical( 0, "ZSafe", 1409 QMessageBox::critical( 0, "ZSafe",
1410 QString("Could not import text file.") ); 1410 QString("Could not import text file.") );
1411 return; 1411 return;
1412 } 1412 }
1413 1413
1414 modified = true; 1414 modified = true;
1415 1415
1416 // clear the password list 1416 // clear the password list
1417 selectedItem = NULL; 1417 selectedItem = NULL;
1418 QListViewItem *i; 1418 QListViewItem *i;
1419 // step through all categories 1419 // step through all categories
1420 for (i = ListView->firstChild(); 1420 for (i = ListView->firstChild();
1421 i != NULL; 1421 i != NULL;
1422 i = i->nextSibling()) 1422 i = i->nextSibling())
1423 { 1423 {
1424 // step through all subitems 1424 // step through all subitems
1425 QListViewItem *si; 1425 QListViewItem *si;
1426 for (si = i->firstChild(); 1426 for (si = i->firstChild();
1427 si != NULL; ) 1427 si != NULL; )
1428 // si = si->nextSibling()) 1428 // si = si->nextSibling())
1429 { 1429 {
1430 QListViewItem *_si = si; 1430 QListViewItem *_si = si;
1431 si = si->nextSibling(); 1431 si = si->nextSibling();
1432 i->takeItem(_si); // remove from view list 1432 i->takeItem(_si); // remove from view list
1433 if (_si) delete _si; 1433 if (_si) delete _si;
1434 } 1434 }
1435 } 1435 }
1436 1436
1437 qWarning ("ReadAllEntries(): "); 1437 qWarning ("ReadAllEntries(): ");
1438 1438
1439 QTextStream t(&f); 1439 QTextStream t(&f);
1440 while ( !t.eof() ) 1440 while ( !t.eof() )
1441 { 1441 {
1442 QString s = t.readLine(); 1442 QString s = t.readLine();
1443 s.replace (QRegExp("\";\""), "\"|\""); 1443 s.replace (QRegExp("\";\""), "\"|\"");
1444 // char buffer[1024]; 1444 // char buffer[1024];
1445#ifndef WIN32 1445#ifndef WIN32
1446 char buffer[s.length()+1]; 1446 char buffer[s.length()+1];
1447#else 1447#else
1448 char buffer[4048]; 1448 char buffer[4048];
1449#endif 1449#endif
1450 1450
1451 1451
1452 /* modify QString -> QCString::utf8 */ 1452 /* modify QString -> QCString::utf8 */
1453 1453
1454 strcpy (buffer, s.utf8()); 1454 strcpy (buffer, s.utf8());
1455 1455
1456 QString name; 1456 QString name;
1457 QString user; 1457 QString user;
1458 QString password; 1458 QString password;
1459 QString comment; 1459 QString comment;
1460 QString field5=""; 1460 QString field5="";
1461 QString field6=""; 1461 QString field6="";
1462 1462
1463 // separete the entries 1463 // separete the entries
1464 char *i = strtok (buffer, "|"); 1464 char *i = strtok (buffer, "|");
1465 QString category(QString::fromUtf8(&i[1])); 1465 QString category(QString::fromUtf8(&i[1]));
1466 category.truncate(category.length() -1); 1466 category.truncate(category.length() -1);
1467 1467
1468 int idx=0; 1468 int idx=0;
1469 while ((i = strtok (NULL, "|")) != NULL) 1469 while ((i = strtok (NULL, "|")) != NULL)
1470 { 1470 {
1471 switch (idx) 1471 switch (idx)
1472 { 1472 {
1473 case 0: 1473 case 0:
1474 name = QString::fromUtf8(&i[1]); 1474 name = QString::fromUtf8(&i[1]);
1475 name.truncate(name.length() -1); 1475 name.truncate(name.length() -1);
1476 // name 1476 // name
1477 break; 1477 break;
1478 case 1: 1478 case 1:
1479 // user 1479 // user
1480 user = QString::fromUtf8(&i[1]); 1480 user = QString::fromUtf8(&i[1]);
1481 user.truncate(user.length() -1); 1481 user.truncate(user.length() -1);
1482 break; 1482 break;
1483 case 2: 1483 case 2:
1484 // password 1484 // password
1485 password = QString::fromUtf8(&i[1]); 1485 password = QString::fromUtf8(&i[1]);
1486 password.truncate(password.length() -1); 1486 password.truncate(password.length() -1);
1487 break; 1487 break;
1488 case 3: 1488 case 3:
1489 // comment 1489 // comment
1490 comment = QString::fromUtf8(&i[1]); 1490 comment = QString::fromUtf8(&i[1]);
1491 comment.truncate(comment.length() -1); 1491 comment.truncate(comment.length() -1);
1492 break; 1492 break;
1493 case 4: 1493 case 4:
1494 // field5 1494 // field5
1495 field5 = QString::fromUtf8(&i[1]); 1495 field5 = QString::fromUtf8(&i[1]);
1496 field5.truncate(field5.length() -1); 1496 field5.truncate(field5.length() -1);
1497 break; 1497 break;
1498 case 5: 1498 case 5:
1499 // field6 1499 // field6
1500 field6 = QString::fromUtf8(&i[1]); 1500 field6 = QString::fromUtf8(&i[1]);
1501 field6.truncate(field6.length() -1); 1501 field6.truncate(field6.length() -1);
1502 break; 1502 break;
1503 } 1503 }
1504 idx++; 1504 idx++;
1505 } 1505 }
1506 1506
1507 Category *cat= categories.find (category); 1507 Category *cat= categories.find (category);
1508 if (cat) 1508 if (cat)
1509 { 1509 {
1510 // use the existend item 1510 // use the existend item
1511 QListViewItem *catItem = cat->getListItem(); 1511 QListViewItem *catItem = cat->getListItem();
1512 if (catItem) 1512 if (catItem)
1513 { 1513 {
1514 QListViewItem * item = new ShadedListItem( 0, catItem ); 1514 QListViewItem * item = new ShadedListItem( 0, catItem );
1515 item->setText( 0, tr( name ) ); 1515 item->setText( 0, tr( name ) );
1516 item->setText( 1, tr( user ) ); 1516 item->setText( 1, tr( user ) );
1517 item->setText( 2, tr( password ) ); 1517 item->setText( 2, tr( password ) );
1518 item->setText( 3, tr( comment ) ); 1518 item->setText( 3, tr( comment ) );
1519 item->setText( 4, tr( field5 ) ); 1519 item->setText( 4, tr( field5 ) );
1520 item->setText( 5, tr( field6 ) ); 1520 item->setText( 5, tr( field6 ) );
1521 catItem->setOpen( TRUE ); 1521 catItem->setOpen( TRUE );
1522 } 1522 }
1523 } 1523 }
1524 else 1524 else
1525 { 1525 {
1526 QListViewItem *catI = new ShadedListItem( 1, ListView ); 1526 QListViewItem *catI = new ShadedListItem( 1, ListView );
1527 // create and insert a new item 1527 // create and insert a new item
1528 QListViewItem * item = new ShadedListItem( 0, catI ); 1528 QListViewItem * item = new ShadedListItem( 0, catI );
1529 item->setText( 0, tr( name ) ); 1529 item->setText( 0, tr( name ) );
1530 item->setText( 1, tr( user ) ); 1530 item->setText( 1, tr( user ) );
1531 item->setText( 2, tr( password ) ); 1531 item->setText( 2, tr( password ) );
1532 item->setText( 3, tr( comment ) ); 1532 item->setText( 3, tr( comment ) );
1533 item->setText( 4, tr( field5 ) ); 1533 item->setText( 4, tr( field5 ) );
1534 item->setText( 5, tr( field6 ) ); 1534 item->setText( 5, tr( field6 ) );
1535 1535
1536 catI->setOpen( TRUE ); 1536 catI->setOpen( TRUE );
1537 1537
1538 Category *c1 = new Category(); 1538 Category *c1 = new Category();
1539 c1->setCategoryName(category); 1539 c1->setCategoryName(category);
1540 1540
1541 QString icon; 1541 QString icon;
1542 QString fullIconPath; 1542 QString fullIconPath;
1543 QPixmap *pix; 1543 QPixmap *pix;
1544// #ifndef WIN32 1544// #ifndef WIN32
1545 icon = conf->readEntry(APP_KEY+category); 1545 icon = conf->readEntry(APP_KEY+category);
1546// #endif 1546// #endif
1547 bool isIconAv = false; 1547 bool isIconAv = false;
1548 if (!icon.isEmpty() && !icon.isNull()) 1548 if (!icon.isEmpty() && !icon.isNull())
1549 { 1549 {
1550 // build the full path 1550 // build the full path
1551 fullIconPath = iconPath + icon; 1551 fullIconPath = iconPath + icon;
1552 pix = new QPixmap (fullIconPath); 1552 pix = new QPixmap (fullIconPath);
1553 if (pix) 1553 if (pix)
1554 { 1554 {
1555 QImage img = pix->convertToImage(); 1555 QImage img = pix->convertToImage();
1556 pix->convertFromImage(img.smoothScale(14,14)); 1556 pix->convertFromImage(img.smoothScale(14,14));
1557 c1->setIconName (icon); 1557 c1->setIconName (icon);
1558 c1->setIcon (*pix); 1558 c1->setIcon (*pix);
1559 isIconAv = true; 1559 isIconAv = true;
1560 } 1560 }
1561 } 1561 }
1562 if (!isIconAv) 1562 if (!isIconAv)
1563 { 1563 {
1564 c1->setIcon (*getPredefinedIcon(category)); 1564 c1->setIcon (*getPredefinedIcon(category));
1565 } 1565 }
1566 c1->setListItem (catI); 1566 c1->setListItem (catI);
1567 c1->initListItem(); 1567 c1->initListItem();
1568 categories.insert (c1->getCategoryName(), c1); 1568 categories.insert (c1->getCategoryName(), c1);
1569 } 1569 }
1570 1570
1571 } 1571 }
1572 f.close(); 1572 f.close();
1573 1573
1574 } 1574 }
1575 else 1575 else
1576 { 1576 {
1577 } 1577 }
1578 1578
1579} 1579}
1580 1580
1581#ifdef UNUSED 1581#ifdef UNUSED
1582void ZSafe::writeAllEntries() 1582void ZSafe::writeAllEntries()
1583{ 1583{
1584 // open the file for writing 1584 // open the file for writing
1585 QString fn = filename + ".txt"; 1585 QString fn = filename + ".txt";
1586 QFile f( fn ); 1586 QFile f( fn );
1587 if ( !f.open( IO_WriteOnly ) ) { 1587 if ( !f.open( IO_WriteOnly ) ) {
1588 qWarning( QString("Could not write to file %1").arg(fn), 1588 qWarning( QString("Could not write to file %1").arg(fn),
1589 2000 ); 1589 2000 );
1590 QMessageBox::critical( 0, tr("ZSafe"), 1590 QMessageBox::critical( 0, tr("ZSafe"),
1591 tr("Could not export to text file.") ); 1591 tr("Could not export to text file.") );
1592 return; 1592 return;
1593 } 1593 }
1594 QTextStream t( &f ); 1594 QTextStream t( &f );
1595 1595
1596 QListViewItem *i; 1596 QListViewItem *i;
1597 // step through all categories 1597 // step through all categories
1598 for (i = ListView->firstChild(); 1598 for (i = ListView->firstChild();
1599 i != NULL; 1599 i != NULL;
1600 i = i->nextSibling()) 1600 i = i->nextSibling())
1601 { 1601 {
1602 // step through all subitems 1602 // step through all subitems
1603 QListViewItem *si; 1603 QListViewItem *si;
1604 for (si = i->firstChild(); 1604 for (si = i->firstChild();
1605 si != NULL; 1605 si != NULL;
1606 si = si->nextSibling()) 1606 si = si->nextSibling())
1607 { 1607 {
1608 QString oneEntry; 1608 QString oneEntry;
1609 oneEntry += "\""; 1609 oneEntry += "\"";
1610 oneEntry += i->text(0); 1610 oneEntry += i->text(0);
1611 oneEntry += "\";"; 1611 oneEntry += "\";";
1612 oneEntry += "\""; 1612 oneEntry += "\"";
1613 oneEntry += si->text(0); 1613 oneEntry += si->text(0);
1614 oneEntry += "\";"; 1614 oneEntry += "\";";
1615 oneEntry += "\""; 1615 oneEntry += "\"";
1616 oneEntry += si->text(1); 1616 oneEntry += si->text(1);
1617 oneEntry += "\";"; 1617 oneEntry += "\";";
1618 oneEntry += "\""; 1618 oneEntry += "\"";
1619 oneEntry += si->text(2); 1619 oneEntry += si->text(2);
1620 oneEntry += "\";"; 1620 oneEntry += "\";";
1621 oneEntry += "\""; 1621 oneEntry += "\"";
1622 // oneEntry += si->text(3); 1622 // oneEntry += si->text(3);
1623 QString comment = si->text(3); 1623 QString comment = si->text(3);
1624 comment.replace (QRegExp("\n"), "<br>"); 1624 comment.replace (QRegExp("\n"), "<br>");
1625 oneEntry += comment; 1625 oneEntry += comment;
1626 oneEntry += "\""; 1626 oneEntry += "\"";
1627 // qWarning (oneEntry); 1627 // qWarning (oneEntry);
1628 t << oneEntry << endl; 1628 t << oneEntry << endl;
1629 1629
1630 // qWarning (si->text(0)); 1630 // qWarning (si->text(0));
1631 } 1631 }
1632 } 1632 }
1633 f.close(); 1633 f.close();
1634} 1634}
1635 1635
1636void ZSafe::readAllEntries() 1636void ZSafe::readAllEntries()
1637{ 1637{
1638 QString fn = filename + ".txt"; 1638 QString fn = filename + ".txt";
1639 QFile f( fn ); 1639 QFile f( fn );
1640 if ( !f.open( IO_ReadOnly ) ) 1640 if ( !f.open( IO_ReadOnly ) )
1641 { 1641 {
1642 qWarning( QString("Could not read file %1").arg(fn), 1642 qWarning( QString("Could not read file %1").arg(fn),
1643 2000 ); 1643 2000 );
1644 QMessageBox::critical( 0, tr("ZSafe"), 1644 QMessageBox::critical( 0, tr("ZSafe"),
1645 tr("Could not import text file.") ); 1645 tr("Could not import text file.") );
1646 return; 1646 return;
1647 } 1647 }
1648 1648
1649 modified = true; 1649 modified = true;
1650 1650
1651 // clear the password list 1651 // clear the password list
1652 selectedItem = NULL; 1652 selectedItem = NULL;
1653 QListViewItem *i; 1653 QListViewItem *i;
1654 // step through all categories 1654 // step through all categories
1655 for (i = ListView->firstChild(); 1655 for (i = ListView->firstChild();
1656 i != NULL; 1656 i != NULL;
1657 i = i->nextSibling()) 1657 i = i->nextSibling())
1658 { 1658 {
1659 // step through all subitems 1659 // step through all subitems
1660 QListViewItem *si; 1660 QListViewItem *si;
1661 for (si = i->firstChild(); 1661 for (si = i->firstChild();
1662 si != NULL; ) 1662 si != NULL; )
1663 // si = si->nextSibling()) 1663 // si = si->nextSibling())
1664 { 1664 {
1665 QListViewItem *_si = si; 1665 QListViewItem *_si = si;
1666 si = si->nextSibling(); 1666 si = si->nextSibling();
1667 i->takeItem(_si); // remove from view list 1667 i->takeItem(_si); // remove from view list
1668 if (_si) delete _si; 1668 if (_si) delete _si;
1669 } 1669 }
1670 } 1670 }
1671 1671
1672 qWarning ("ReadAllEntries(): "); 1672 qWarning ("ReadAllEntries(): ");
1673 1673
1674 QTextStream t(&f); 1674 QTextStream t(&f);
1675 while ( !t.eof() ) 1675 while ( !t.eof() )
1676 { 1676 {
1677 QString s = t.readLine(); 1677 QString s = t.readLine();
1678 s.replace (QRegExp("\";\""), "\"|\""); 1678 s.replace (QRegExp("\";\""), "\"|\"");
1679 // char buffer[1024]; 1679 // char buffer[1024];
1680 int len=s.length()+1; 1680 int len=s.length()+1;
1681#ifdef WIN32 1681#ifdef WIN32
1682 char buffer[512]; 1682 char buffer[512];
1683#else 1683#else
1684 char buffer[len]; 1684 char buffer[len];
1685#endif 1685#endif
1686 strcpy (buffer, s); 1686 strcpy (buffer, s);
1687 1687
1688 QString name; 1688 QString name;
1689 QString user; 1689 QString user;
1690 QString password; 1690 QString password;
1691 QString comment; 1691 QString comment;
1692 1692
1693 // separete the entries 1693 // separete the entries
1694 char *i = strtok (buffer, "|"); 1694 char *i = strtok (buffer, "|");
1695 QString category(&i[1]); 1695 QString category(&i[1]);
1696 category.truncate(category.length() -1); 1696 category.truncate(category.length() -1);
1697 1697
1698 int idx=0; 1698 int idx=0;
1699 while (i = strtok (NULL, "|")) 1699 while (i = strtok (NULL, "|"))
1700 { 1700 {
1701 switch (idx) 1701 switch (idx)
1702 { 1702 {
1703 case 0: 1703 case 0:
1704 name = &i[1]; 1704 name = &i[1];
1705 name.truncate(name.length() -1); 1705 name.truncate(name.length() -1);
1706 // name 1706 // name
1707 break; 1707 break;
1708 case 1: 1708 case 1:
1709 // user 1709 // user
1710 user = &i[1]; 1710 user = &i[1];
1711 user.truncate(user.length() -1); 1711 user.truncate(user.length() -1);
1712 break; 1712 break;
1713 case 2: 1713 case 2:
1714 // password 1714 // password
1715 password = &i[1]; 1715 password = &i[1];
1716 password.truncate(password.length() -1); 1716 password.truncate(password.length() -1);
1717 break; 1717 break;
1718 case 3: 1718 case 3:
1719 // comment 1719 // comment
1720 comment = &i[1]; 1720 comment = &i[1];
1721 comment.truncate(comment.length() -1); 1721 comment.truncate(comment.length() -1);
1722 break; 1722 break;
1723 } 1723 }
1724 idx++; 1724 idx++;
1725 } 1725 }
1726 1726
1727 Category *cat= categories.find (category); 1727 Category *cat= categories.find (category);
1728 if (cat) 1728 if (cat)
1729 { 1729 {
1730 // use the existend item 1730 // use the existend item
1731 QListViewItem *catItem = cat->getListItem(); 1731 QListViewItem *catItem = cat->getListItem();
1732 if (catItem) 1732 if (catItem)
1733 { 1733 {
1734 QListViewItem * item = new ShadedListItem( 0, catItem ); 1734 QListViewItem * item = new ShadedListItem( 0, catItem );
1735 item->setText( 0, tr( name ) ); 1735 item->setText( 0, tr( name ) );
1736 item->setText( 1, tr( user ) ); 1736 item->setText( 1, tr( user ) );
1737 item->setText( 2, tr( password ) ); 1737 item->setText( 2, tr( password ) );
1738 item->setText( 3, tr( comment ) ); 1738 item->setText( 3, tr( comment ) );
1739 1739
1740 catItem->setOpen( TRUE ); 1740 catItem->setOpen( TRUE );
1741 } 1741 }
1742 } 1742 }
1743 else 1743 else
1744 { 1744 {
1745 QListViewItem *catI = new ShadedListItem( 1, ListView ); 1745 QListViewItem *catI = new ShadedListItem( 1, ListView );
1746 // create and insert a new item 1746 // create and insert a new item
1747 QListViewItem * item = new ShadedListItem( 0, catI ); 1747 QListViewItem * item = new ShadedListItem( 0, catI );
1748 item->setText( 0, tr( name ) ); 1748 item->setText( 0, tr( name ) );
1749 item->setText( 1, tr( user ) ); 1749 item->setText( 1, tr( user ) );
1750 item->setText( 2, tr( password ) ); 1750 item->setText( 2, tr( password ) );
1751 item->setText( 3, tr( comment ) ); 1751 item->setText( 3, tr( comment ) );
1752 1752
1753 catI->setOpen( TRUE ); 1753 catI->setOpen( TRUE );
1754 1754
1755 Category *c1 = new Category(); 1755 Category *c1 = new Category();
1756 c1->setCategoryName(category); 1756 c1->setCategoryName(category);
1757 1757
1758 QString icon; 1758 QString icon;
1759 QString fullIconPath; 1759 QString fullIconPath;
1760 QPixmap *pix; 1760 QPixmap *pix;
1761// #ifndef WIN32 1761// #ifndef WIN32
1762 icon = conf->readEntry(APP_KEY+category); 1762 icon = conf->readEntry(APP_KEY+category);
1763// #endif 1763// #endif
1764 bool isIconAv = false; 1764 bool isIconAv = false;
1765 if (!icon.isEmpty() && !icon.isNull()) 1765 if (!icon.isEmpty() && !icon.isNull())
1766 { 1766 {
1767 // build the full path 1767 // build the full path
1768 fullIconPath = iconPath + icon; 1768 fullIconPath = iconPath + icon;
1769 pix = new QPixmap (fullIconPath); 1769 pix = new QPixmap (fullIconPath);
1770 if (pix) 1770 if (pix)
1771 { 1771 {
1772 QImage img = pix->convertToImage(); 1772 QImage img = pix->convertToImage();
1773 pix->convertFromImage(img.smoothScale(14,14)); 1773 pix->convertFromImage(img.smoothScale(14,14));
1774 c1->setIconName (icon); 1774 c1->setIconName (icon);
1775 c1->setIcon (*pix); 1775 c1->setIcon (*pix);
1776 isIconAv = true; 1776 isIconAv = true;
1777 } 1777 }
1778 } 1778 }
1779 if (!isIconAv) 1779 if (!isIconAv)
1780 { 1780 {
1781 c1->setIcon (*getPredefinedIcon(category)); 1781 c1->setIcon (*getPredefinedIcon(category));
1782 } 1782 }
1783 c1->setListItem (catI); 1783 c1->setListItem (catI);
1784 c1->initListItem(); 1784 c1->initListItem();
1785 categories.insert (c1->getCategoryName(), c1); 1785 categories.insert (c1->getCategoryName(), c1);
1786 } 1786 }
1787 1787
1788 } 1788 }
1789 f.close(); 1789 f.close();
1790 1790
1791} 1791}
1792#endif // UNUSED 1792#endif // UNUSED
1793 1793
1794void ZSafe::resume(int) 1794void ZSafe::resume(int)
1795{ 1795{
1796 qWarning ("Resume"); 1796 qWarning ("Resume");
1797 // hide the main window 1797 // hide the main window
1798 1798
1799 infoForm->hide(); 1799 infoForm->hide();
1800 // open zsafe again 1800 // open zsafe again
1801 m_password = ""; 1801 m_password = "";
1802 selectedItem = NULL; 1802 selectedItem = NULL;
1803 1803
1804 // clear the password list 1804 // clear the password list
1805 QListViewItem *i; 1805 QListViewItem *i;
1806 // step through all categories 1806 // step through all categories
1807 for (i = ListView->firstChild(); 1807 for (i = ListView->firstChild();
1808 i != NULL; 1808 i != NULL;
1809 i = i->nextSibling()) 1809 i = i->nextSibling())
1810 { 1810 {
1811 // step through all subitems 1811 // step through all subitems
1812 QListViewItem *si; 1812 QListViewItem *si;
1813 for (si = i->firstChild(); 1813 for (si = i->firstChild();
1814 si != NULL; ) 1814 si != NULL; )
1815 { 1815 {
1816 QListViewItem *_si = si; 1816 QListViewItem *_si = si;
1817 si = si->nextSibling(); 1817 si = si->nextSibling();
1818 i->takeItem(_si); // remove from view list 1818 i->takeItem(_si); // remove from view list
1819 if (_si) delete _si; 1819 if (_si) delete _si;
1820 } 1820 }
1821 } 1821 }
1822 1822
1823 // ask for password and read again 1823 // ask for password and read again
1824 openDocument(filename); 1824 openDocument(filename);
1825} 1825}
1826 1826
1827//--------------------------------------------- 1827//---------------------------------------------
1828 1828
1829 1829
1830bool ZSafe::openDocument(const char* _filename, const char* ) 1830bool ZSafe::openDocument(const char* _filename, const char* )
1831{ 1831{
1832 int retval; 1832 int retval;
1833 char* entry[FIELD_SIZE]; 1833 char* entry[FIELD_SIZE];
1834// #ifndef WIN32 1834// #ifndef WIN32
1835 int validationFlag = conf->readNumEntry(APP_KEY+"valzsafe", 1); 1835 int validationFlag = conf->readNumEntry(APP_KEY+"valzsafe", 1);
1836// #else 1836// #else
1837 // int validationFlag = 1; 1837 // int validationFlag = 1;
1838// #endif 1838// #endif
1839 1839
1840 int pwdOk = 0; 1840 int pwdOk = 0;
1841 int numberOfTries = 3; 1841 int numberOfTries = 3;
1842 for (int i=0; i < numberOfTries; i++) 1842 for (int i=0; i < numberOfTries; i++)
1843 { 1843 {
1844 QFile f(_filename); 1844 QFile f(_filename);
1845 if (f.exists()) 1845 if (f.exists())
1846 { 1846 {
1847 // ask with a dialog for the password 1847 // ask with a dialog for the password
1848 if (m_password.isEmpty()) 1848 if (m_password.isEmpty())
1849 getDocPassword(tr("Enter Password")); 1849 getDocPassword(tr("Enter Password"));
1850 if (m_password.isEmpty() && validationFlag == 0) 1850 if (m_password.isEmpty() && validationFlag == 0)
1851 { 1851 {
1852 qWarning ("Wrong password"); 1852 qWarning ("Wrong password");
1853 QMessageBox::critical( 0, tr("ZSafe"), 1853 QMessageBox::critical( 0, tr("ZSafe"),
1854 tr("Wrong password.\n\nZSafe will now exit.") ); 1854 tr("Wrong password.\n\nZSafe will now exit.") );
1855 exitZs (1); 1855 exitZs (1);
1856 } 1856 }
1857 1857
1858 retval = loadInit(_filename, m_password); 1858 retval = loadInit(_filename, m_password);
1859 if (retval != PWERR_GOOD) 1859 if (retval != PWERR_GOOD)
1860 { 1860 {
1861 qWarning ("Error loading Document"); 1861 qWarning ("Error loading Document");
1862 return false; 1862 return false;
1863 } 1863 }
1864 } 1864 }
1865 else 1865 else
1866 { 1866 {
1867#ifdef WIN32 1867#ifdef WIN32
1868 this->setCaption("Qt ZSafe"); 1868 this->setCaption("Qt ZSafe");
1869#else 1869#else
1870 this->setCaption("ZSafe"); 1870 this->setCaption("ZSafe");
1871#endif 1871#endif
1872 filename = ""; 1872 filename = "";
1873 return false; 1873 return false;
1874 } 1874 }
1875 1875
1876 1876
1877 // load the validation entry 1877 // load the validation entry
1878 if (validationFlag == 0) 1878 if (validationFlag == 0)
1879 { 1879 {
1880 pwdOk = 1; 1880 pwdOk = 1;
1881 break; 1881 break;
1882 } 1882 }
1883 1883
1884 retval = loadEntry(entry); 1884 retval = loadEntry(entry);
1885 if (retval == 1 && 1885 if (retval == 1 &&
1886 !strcmp (entry[0], "ZSAFECATEGORY") && 1886 !strcmp (entry[0], "ZSAFECATEGORY") &&
1887 !strcmp (entry[1], "name") && 1887 !strcmp (entry[1], "name") &&
1888 !strcmp (entry[2], "username") && 1888 !strcmp (entry[2], "username") &&
1889 !strcmp (entry[3], "password") && 1889 !strcmp (entry[3], "password") &&
1890 !strcmp (entry[4], "comment") ) 1890 !strcmp (entry[4], "comment") )
1891 { 1891 {
1892 for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]); 1892 for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]);
1893 pwdOk = 1; 1893 pwdOk = 1;
1894 break; 1894 break;
1895 } 1895 }
1896 else 1896 else
1897 // for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]); 1897 // for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]);
1898 fclose (fd); 1898 fclose (fd);
1899 m_password = ""; 1899 m_password = "";
1900 1900
1901 if (i < numberOfTries - 1) 1901 if (i < numberOfTries - 1)
1902 { 1902 {
1903 switch( QMessageBox::warning( this, tr("ZSafe"), 1903 switch( QMessageBox::warning( this, tr("ZSafe"),
1904 tr("Wrong password.\nEnter again?"), 1904 tr("Wrong password.\nEnter again?"),
1905 tr("&Yes"), tr("&No."), 1905 tr("&Yes"), tr("&No."),
1906 0 1906 0
1907 ) ) 1907 ) )
1908 { 1908 {
1909 case 1: // No 1909 case 1: // No
1910 exitZs (1); 1910 exitZs (1);
1911 break; 1911 break;
1912 case 0: // Yes 1912 case 0: // Yes
1913 continue; 1913 continue;
1914 } 1914 }
1915 } 1915 }
1916 } 1916 }
1917 if (pwdOk == 0) 1917 if (pwdOk == 0)
1918 { 1918 {
1919 // unset the document entry 1919 // unset the document entry
1920 conf->writeEntry(APP_KEY+"document", "INVALIDPWD"); 1920 conf->writeEntry(APP_KEY+"document", "INVALIDPWD");
1921 if (conf) 1921 if (conf)
1922 delete conf; 1922 delete conf;
1923 1923
1924 exitZs (1); 1924 exitZs (1);
1925 } 1925 }
1926 1926
1927 1927
1928 retval = loadEntry(entry); 1928 retval = loadEntry(entry);
1929 1929
1930 int numberOfEntries=0; 1930 int numberOfEntries=0;
1931 while (retval == 1) { 1931 while (retval == 1) {
1932 1932
1933 QString category( QString::fromUtf8(entry[0]) ); 1933 QString category( QString::fromUtf8(entry[0]) );
1934 QString name( QString::fromUtf8(entry[1]) ); 1934 QString name( QString::fromUtf8(entry[1]) );
1935 QString user( QString::fromUtf8(entry[2]) ); 1935 QString user( QString::fromUtf8(entry[2]) );
1936 QString password( QString::fromUtf8(entry[3]) ); 1936 QString password( QString::fromUtf8(entry[3]) );
1937 QString comment( QString::fromUtf8(entry[4]) ); 1937 QString comment( QString::fromUtf8(entry[4]) );
1938 QString field5( QString::fromUtf8(entry[5]) ); 1938 QString field5( QString::fromUtf8(entry[5]) );
1939 QString field6( QString::fromUtf8(entry[6]) ); 1939 QString field6( QString::fromUtf8(entry[6]) );
1940 // add the subitems to the categories 1940 // add the subitems to the categories
1941 1941
1942 Category *cat= categories.find (category); 1942 Category *cat= categories.find (category);
1943 if (cat) 1943 if (cat)
1944 { 1944 {
1945 // use the existend item 1945 // use the existend item
1946 QListViewItem *catItem = cat->getListItem(); 1946 QListViewItem *catItem = cat->getListItem();
1947 if (catItem) 1947 if (catItem)
1948 { 1948 {
1949 QListViewItem * item = new ShadedListItem( 0, catItem ); 1949 QListViewItem * item = new ShadedListItem( 0, catItem );
1950 item->setText( 0, tr( name ) ); 1950 item->setText( 0, tr( name ) );
1951 item->setText( 1, tr( user ) ); 1951 item->setText( 1, tr( user ) );
1952 item->setText( 2, tr( password ) ); 1952 item->setText( 2, tr( password ) );
1953 item->setText( 3, tr( comment ) ); 1953 item->setText( 3, tr( comment ) );
1954 item->setText( 4, tr( field5 ) ); 1954 item->setText( 4, tr( field5 ) );
1955 item->setText( 5, tr( field6 ) ); 1955 item->setText( 5, tr( field6 ) );
1956 1956
1957 if (expandTree) 1957 if (expandTree)
1958 catItem->setOpen( TRUE ); 1958 catItem->setOpen( TRUE );
1959 numberOfEntries++; 1959 numberOfEntries++;
1960 } 1960 }
1961 } 1961 }
1962 else 1962 else
1963 { 1963 {
1964 QListViewItem *catI = new ShadedListItem( 1, ListView ); 1964 QListViewItem *catI = new ShadedListItem( 1, ListView );
1965 // create and insert a new item 1965 // create and insert a new item
1966 QListViewItem * item = new ShadedListItem( 0, catI ); 1966 QListViewItem * item = new ShadedListItem( 0, catI );
1967 1967
1968 item->setText( 0, tr( name ) ); 1968 item->setText( 0, tr( name ) );
1969 item->setText( 1, tr( user ) ); 1969 item->setText( 1, tr( user ) );
1970 item->setText( 2, tr( password ) ); 1970 item->setText( 2, tr( password ) );
1971 item->setText( 3, tr( comment ) ); 1971 item->setText( 3, tr( comment ) );
1972 item->setText( 4, tr( field5 ) ); 1972 item->setText( 4, tr( field5 ) );
1973 item->setText( 5, tr( field6 ) ); 1973 item->setText( 5, tr( field6 ) );
1974 1974
1975 if (expandTree) 1975 if (expandTree)
1976 catI->setOpen( TRUE ); 1976 catI->setOpen( TRUE );
1977 1977
1978 Category *c1 = new Category(); 1978 Category *c1 = new Category();
1979 c1->setCategoryName(category); 1979 c1->setCategoryName(category);
1980 1980
1981 QString icon; 1981 QString icon;
1982 QString fullIconPath; 1982 QString fullIconPath;
1983 QPixmap *pix; 1983 QPixmap *pix;
1984// #ifndef WIN32 1984// #ifndef WIN32
1985 icon = conf->readEntry(APP_KEY+category); 1985 icon = conf->readEntry(APP_KEY+category);
1986// #endif 1986// #endif
1987 bool isIconAv = false; 1987 bool isIconAv = false;
1988 if (!icon.isEmpty() && !icon.isNull()) 1988 if (!icon.isEmpty() && !icon.isNull())
1989 { 1989 {
1990 // build the full path 1990 // build the full path
1991 fullIconPath = iconPath + icon; 1991 fullIconPath = iconPath + icon;
1992 pix = new QPixmap (fullIconPath); 1992 pix = new QPixmap (fullIconPath);
1993 if (pix) 1993 if (pix)
1994 { 1994 {
1995 QImage img = pix->convertToImage(); 1995 QImage img = pix->convertToImage();
1996 pix->convertFromImage(img.smoothScale(14,14)); 1996 pix->convertFromImage(img.smoothScale(14,14));
1997 c1->setIconName (icon); 1997 c1->setIconName (icon);
1998 c1->setIcon (*pix); 1998 c1->setIcon (*pix);
1999 isIconAv = true; 1999 isIconAv = true;
2000 } 2000 }
2001 } 2001 }
2002 if (!isIconAv) 2002 if (!isIconAv)
2003 { 2003 {
2004 c1->setIcon (*getPredefinedIcon(category)); 2004 c1->setIcon (*getPredefinedIcon(category));
2005 } 2005 }
2006 2006
2007 c1->setListItem (catI); 2007 c1->setListItem (catI);
2008 c1->initListItem(); 2008 c1->initListItem();
2009 categories.insert (c1->getCategoryName(), c1); 2009 categories.insert (c1->getCategoryName(), c1);
2010 numberOfEntries++; 2010 numberOfEntries++;
2011 } 2011 }
2012 2012
2013 for (int count = 0; count < FIELD_SIZE; count++) { 2013 for (int count = 0; count < FIELD_SIZE; count++) {
2014 free(entry[count]); 2014 free(entry[count]);
2015 } 2015 }
2016 retval = loadEntry(entry); 2016 retval = loadEntry(entry);
2017 if (retval == 2) { 2017 if (retval == 2) {
2018 // m_parent->slotStatusHelpMsg("Last entry loaded"); 2018 // m_parent->slotStatusHelpMsg("Last entry loaded");
2019 } 2019 }
2020 } // end while 2020 } // end while
2021 2021
2022 if (numberOfEntries == 0) 2022 if (numberOfEntries == 0)
2023 { 2023 {
2024 2024
2025 switch( QMessageBox::warning( this, tr("ZSafe"), 2025 switch( QMessageBox::warning( this, tr("ZSafe"),
2026 tr("Empty document or\nwrong password.\nContinue?"), 2026 tr("Empty document or\nwrong password.\nContinue?"),
2027 tr("&No"), tr("&Yes."), 2027 tr("&No"), tr("&Yes."),
2028 0 2028 0
2029 ) ) { 2029 ) ) {
2030 case 0: // No 2030 case 0: // No
2031 retval = loadFinalize(); 2031 retval = loadFinalize();
2032 exitZs (1); 2032 exitZs (1);
2033 break; 2033 break;
2034 case 1: // Yes 2034 case 1: // Yes
2035 break; 2035 break;
2036 } 2036 }
2037 } 2037 }
2038 2038
2039 retval = loadFinalize(); 2039 retval = loadFinalize();
2040 2040
2041 return true; 2041 return true;
2042} 2042}
2043 2043
2044int ZSafe::loadInit(const char* _filename, const char *password) 2044int ZSafe::loadInit(const char* _filename, const char *password)
2045{ 2045{
2046 unsigned int j = 0; 2046 unsigned int j = 0;
2047 unsigned int keylength=0; 2047 unsigned int keylength=0;
2048 int count=0, count2=0, count3=0; 2048 int count=0, count2=0, count3=0;
2049 unsigned char charbuf[8]; 2049 unsigned char charbuf[8];
2050 unsigned short ciphertext[4]; 2050 unsigned short ciphertext[4];
2051 char key[128]; 2051 char key[128];
2052 Krc2* krc2 = new Krc2(); 2052 Krc2* krc2 = new Krc2();
2053 2053
2054 fd = fopen (_filename, "rb"); 2054 fd = fopen (_filename, "rb");
2055 2055
2056 QFileInfo f (_filename); 2056 QFileInfo f (_filename);
2057 load_buffer_length = f.size(); 2057 load_buffer_length = f.size();
2058 load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2; 2058 load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2;
2059 2059
2060 if (fd == NULL) 2060 if (fd == NULL)
2061 return PWERR_OPEN; 2061 return PWERR_OPEN;
2062 2062
2063 buffer = (char *)malloc(load_buffer_length); 2063 buffer = (char *)malloc(load_buffer_length);
2064 for (j = 0; password[j] != '\0'; j++) { 2064 for (j = 0; password[j] != '\0'; j++) {
2065 key[j] = password[j]; 2065 key[j] = password[j];
2066 } 2066 }
2067 keylength = j; 2067 keylength = j;
2068 krc2->rc2_expandkey (key, keylength, 128); 2068 krc2->rc2_expandkey (key, keylength, 128);
2069 2069
2070#ifndef WIN32 2070#ifndef WIN32
2071 size = read(fileno (fd), (unsigned char *) (charbuf + count), 8); 2071 size = read(fileno (fd), (unsigned char *) (charbuf + count), 8);
2072#else 2072#else
2073 printf ("LoadInit() read1"); 2073 printf ("LoadInit() read1");
2074 size = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd); 2074 size = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
2075#endif 2075#endif
2076 2076
2077 if (size < 8) 2077 if (size < 8)
2078 return PWERR_DATA; 2078 return PWERR_DATA;
2079 2079
2080 for (count = 0; count < 4; count++) { 2080 for (count = 0; count < 4; count++) {
2081 count2 = count << 1; 2081 count2 = count << 1;
2082 iv[count] = charbuf[count2] << 8; 2082 iv[count] = charbuf[count2] << 8;
2083 iv[count] += charbuf[count2 + 1]; 2083 iv[count] += charbuf[count2 + 1];
2084 } 2084 }
2085 2085
2086 size = 0; 2086 size = 0;
2087 bufferIndex = 0; 2087 bufferIndex = 0;
2088#ifndef WIN32 2088#ifndef WIN32
2089 while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) { 2089 while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) {
2090 while (count < 8) { 2090 while (count < 8) {
2091 count2 = read (fileno (fd), (unsigned char *) (charbuf + count), 8); 2091 count2 = read (fileno (fd), (unsigned char *) (charbuf + count), 8);
2092#else 2092#else
2093 printf ("LoadInit() read2"); 2093 printf ("LoadInit() read2");
2094 while ((count = fread ((unsigned char *) (charbuf), sizeof(unsigned char), 8, fd)) > 0) { 2094 while ((count = fread ((unsigned char *) (charbuf), sizeof(unsigned char), 8, fd)) > 0) {
2095 while (count < 8) { 2095 while (count < 8) {
2096 count2 = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd); 2096 count2 = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
2097#endif 2097#endif
2098 if (count2 == 0) { 2098 if (count2 == 0) {
2099 return PWERR_DATA; 2099 return PWERR_DATA;
2100 } 2100 }
2101 count += count2; 2101 count += count2;
2102 } /* while (count < 8) */ 2102 } /* while (count < 8) */
2103 2103
2104 size += 8; 2104 size += 8;
2105 for (count2 = 0; count2 < 8; count2 += 2) { 2105 for (count2 = 0; count2 < 8; count2 += 2) {
2106 count3 = count2 >> 1; 2106 count3 = count2 >> 1;
2107 ciphertext[count3] = charbuf[count2] << 8; 2107 ciphertext[count3] = charbuf[count2] << 8;
2108 ciphertext[count3] += charbuf[count2 + 1]; 2108 ciphertext[count3] += charbuf[count2 + 1];
2109 2109
2110 plaintext[count3] = ciphertext[count3] ^ iv[count3]; 2110 plaintext[count3] = ciphertext[count3] ^ iv[count3];
2111 iv[count3] = plaintext[count3]; 2111 iv[count3] = plaintext[count3];
2112 } /* for (count2) */ 2112 } /* for (count2) */
2113 2113
2114 krc2->rc2_decrypt (plaintext); 2114 krc2->rc2_decrypt (plaintext);
2115 memcpy ((unsigned char *) (buffer + bufferIndex), plaintext, 8); 2115 memcpy ((unsigned char *) (buffer + bufferIndex), plaintext, 8);
2116 bufferIndex += 8; 2116 bufferIndex += 8;
2117 buffer[bufferIndex + 1] = '\0'; 2117 buffer[bufferIndex + 1] = '\0';
2118 } /* while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) */ 2118 } /* while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) */
2119 size -= buffer[size - 1]; 2119 size -= buffer[size - 1];
2120 lastcount = 0; 2120 lastcount = 0;
2121 2121
2122 /* This will point to the starting index */ 2122 /* This will point to the starting index */
2123 bufferIndex = 0; 2123 bufferIndex = 0;
2124 return PWERR_GOOD; 2124 return PWERR_GOOD;
2125} 2125}
2126 2126
2127int ZSafe::loadEntry(char *entry[FIELD_SIZE]) 2127int ZSafe::loadEntry(char *entry[FIELD_SIZE])
2128{ 2128{
2129 /* Strip off PKCS 5 padding 2129 /* Strip off PKCS 5 padding
2130 * Should check to make sure it's good here 2130 * Should check to make sure it's good here
2131 */ 2131 */
2132 int count, count1=0; 2132 int count, count1=0;
2133 2133
2134 for (count = lastcount; count < size; count++) { 2134 for (count = lastcount; count < size; count++) {
2135 if ((unsigned char) (buffer[count]) == 255) { 2135 if ((unsigned char) (buffer[count]) == 255) {
2136 if (buffer[bufferIndex] == '\0') { 2136 if (buffer[bufferIndex] == '\0') {
2137 bufferIndex++; 2137 bufferIndex++;
2138 } 2138 }
2139 entry[count1] = (char *) malloc (count - bufferIndex + 1); 2139 entry[count1] = (char *) malloc (count - bufferIndex + 1);
2140 memcpy (entry[count1], (unsigned char *) (buffer + bufferIndex), count - bufferIndex); 2140 memcpy (entry[count1], (unsigned char *) (buffer + bufferIndex), count - bufferIndex);
2141 entry[count1][count - bufferIndex] = '\0'; 2141 entry[count1][count - bufferIndex] = '\0';
2142 count++; 2142 count++;
2143 bufferIndex = count; 2143 bufferIndex = count;
2144 count1++; 2144 count1++;
2145 if (count1 == FIELD_SIZE) { 2145 if (count1 == FIELD_SIZE) {
2146 lastcount = count; 2146 lastcount = count;
2147 return 1; 2147 return 1;
2148 } 2148 }
2149 } /* if ((unsigned char) (buffer[count]) == 255) */ 2149 } /* if ((unsigned char) (buffer[count]) == 255) */
2150 } /* for (count = 0; count < size; count++) */ 2150 } /* for (count = 0; count < size; count++) */
2151 2151
2152 return 2; 2152 return 2;
2153} 2153}
2154 2154
2155int ZSafe::loadFinalize(void) 2155int ZSafe::loadFinalize(void)
2156{ 2156{
2157 fclose (fd); 2157 fclose (fd);
2158 if (buffer) free(buffer); 2158 if (buffer) free(buffer);
2159 return PWERR_GOOD; 2159 return PWERR_GOOD;
2160} 2160}
2161 2161
2162bool ZSafe::saveDocument(const char* _filename, 2162bool ZSafe::saveDocument(const char* _filename,
2163 bool withPwd, 2163 bool withPwd,
2164 const char* ) 2164 const char* )
2165{ 2165{
2166 if (filename.isEmpty()) 2166 if (filename.isEmpty())
2167 { 2167 {
2168 QMessageBox::critical( 0, tr("ZSafe"), 2168 QMessageBox::critical( 0, tr("ZSafe"),
2169 tr("No document defined.\nYou have to create a new document")); 2169 tr("No document defined.\nYou have to create a new document"));
2170 return false; 2170 return false;
2171 } 2171 }
2172 2172
2173 // if (m_password.isEmpty()) 2173 // if (m_password.isEmpty())
2174 // withPwd = true; // the document must be saved with a valid password 2174 // withPwd = true; // the document must be saved with a valid password
2175 if (withPwd) 2175 if (withPwd)
2176 { 2176 {
2177 bool pwdOk = FALSE; 2177 bool pwdOk = FALSE;
2178 while (!pwdOk) 2178 while (!pwdOk)
2179 { 2179 {
2180 getDocPassword(tr("Enter Password")); 2180 getDocPassword(tr("Enter Password"));
2181 if (m_password.isEmpty()) 2181 if (m_password.isEmpty())
2182 { 2182 {
2183 2183
2184 QMessageBox::critical( 0, tr("ZSafe"), 2184 QMessageBox::critical( 0, tr("ZSafe"),
2185 tr("Password is empty.\nPlease enter again.")); 2185 tr("Password is empty.\nPlease enter again."));
2186 continue; 2186 continue;
2187 } 2187 }
2188 2188
2189 QString firstPasswd = m_password; 2189 QString firstPasswd = m_password;
2190 2190
2191 getDocPassword(tr("Reenter Password")); 2191 getDocPassword(tr("Reenter Password"));
2192 if (m_password.isEmpty()) 2192 if (m_password.isEmpty())
2193 { 2193 {
2194 QMessageBox::critical( 0, tr("ZSafe"), 2194 QMessageBox::critical( 0, tr("ZSafe"),
2195 tr("Password is empty.\nPlease enter again.")); 2195 tr("Password is empty.\nPlease enter again."));
2196 continue; 2196 continue;
2197 } 2197 }
2198 if (firstPasswd != m_password) 2198 if (firstPasswd != m_password)
2199 { 2199 {
2200 2200
2201 QMessageBox::critical( 0, tr("ZSafe"), 2201 QMessageBox::critical( 0, tr("ZSafe"),
2202 tr("Passwords must be identical.\nPlease enter again.")); 2202 tr("Passwords must be identical.\nPlease enter again."));
2203 continue; 2203 continue;
2204 } 2204 }
2205 pwdOk = TRUE; 2205 pwdOk = TRUE;
2206 modified = false; 2206 modified = false;
2207 } 2207 }
2208 } 2208 }
2209 else if (modified) 2209 else if (modified)
2210 { 2210 {
2211 QString fns(_filename); 2211 QString fns(_filename);
2212 fns = fns.right (fns.length() - fns.findRev ('/') - 1); 2212 fns = fns.right (fns.length() - fns.findRev ('/') - 1);
2213 switch( QMessageBox::information( this, tr("ZSafe"), 2213 switch( QMessageBox::information( this, tr("ZSafe"),
2214 tr("Do you want to save ") + fns + tr("\nbefore continuing?"), 2214 tr("Do you want to save ") + fns + tr("\nbefore continuing?"),
2215 tr("&Save"), 2215 tr("&Save"),
2216 tr("&Don't Save"), 2216 tr("&Don't Save"),
2217 0 // Enter == button 0 2217 0 // Enter == button 0
2218 ) ) 2218 ) )
2219 { // Escape == button 2 2219 { // Escape == button 2
2220 case 0: // Save clicked, Alt-S or Enter pressed. 2220 case 0: // Save clicked, Alt-S or Enter pressed.
2221 modified = false; 2221 modified = false;
2222 break; 2222 break;
2223 case 1: // Don't Save clicked or Alt-D pressed 2223 case 1: // Don't Save clicked or Alt-D pressed
2224 modified = false; 2224 modified = false;
2225 return true; 2225 return true;
2226 } 2226 }
2227 } 2227 }
2228 modified = false; 2228 modified = false;
2229 2229
2230 if (m_password.isEmpty()) 2230 if (m_password.isEmpty())
2231 return false; 2231 return false;
2232 2232
2233 int retval = saveInit(_filename, m_password); 2233 int retval = saveInit(_filename, m_password);
2234 // int retval = saveInit(_filename, "test"); 2234 // int retval = saveInit(_filename, "test");
2235 if (retval != PWERR_GOOD) { 2235 if (retval != PWERR_GOOD) {
2236 return false; 2236 return false;
2237 } 2237 }
2238 2238
2239 char* entry[FIELD_SIZE]; 2239 char* entry[FIELD_SIZE];
2240 2240
2241 // save the validation entry 2241 // save the validation entry
2242 { 2242 {
2243 int i=0; 2243 int i=0;
2244 entry[i] = (char*)malloc(strlen("ZSAFECATEGORY")+1); 2244 entry[i] = (char*)malloc(strlen("ZSAFECATEGORY")+1);
2245 strcpy(entry[i++], "ZSAFECATEGORY"); 2245 strcpy(entry[i++], "ZSAFECATEGORY");
2246 entry[i] = (char*)malloc(strlen("name")+1); 2246 entry[i] = (char*)malloc(strlen("name")+1);
2247 strcpy(entry[i++], "name"); 2247 strcpy(entry[i++], "name");
2248 entry[i] = (char*)malloc(strlen("username")+1); 2248 entry[i] = (char*)malloc(strlen("username")+1);
2249 strcpy(entry[i++], "username"); 2249 strcpy(entry[i++], "username");
2250 entry[i] = (char*)malloc(strlen("password")+1); 2250 entry[i] = (char*)malloc(strlen("password")+1);
2251 strcpy(entry[i++], "password"); 2251 strcpy(entry[i++], "password");
2252 entry[i] = (char*)malloc(strlen("comment")+1); 2252 entry[i] = (char*)malloc(strlen("comment")+1);
2253 strcpy(entry[i++], "comment"); 2253 strcpy(entry[i++], "comment");
2254 2254
2255 entry[i] = (char*)malloc(strlen("field5")+1); 2255 entry[i] = (char*)malloc(strlen("field5")+1);
2256 strcpy(entry[i++], "field5"); 2256 strcpy(entry[i++], "field5");
2257 entry[i] = (char*)malloc(strlen("field6")+1); 2257 entry[i] = (char*)malloc(strlen("field6")+1);
2258 strcpy(entry[i++], "field6"); 2258 strcpy(entry[i++], "field6");
2259 2259
2260 retval = saveEntry(entry); 2260 retval = saveEntry(entry);
2261 for (int z=0; z<i; z++) free(entry[z]); 2261 for (int z=0; z<i; z++) free(entry[z]);
2262 if (retval == PWERR_DATA) { 2262 if (retval == PWERR_DATA) {
2263 qWarning("1: Error writing file, contents not saved"); 2263 qWarning("1: Error writing file, contents not saved");
2264 saveFinalize(); 2264 saveFinalize();
2265 return false; 2265 return false;
2266 } 2266 }
2267// #ifndef WIN32 2267// #ifndef WIN32
2268 conf->writeEntry(APP_KEY+"valzsafe", 1); 2268 conf->writeEntry(APP_KEY+"valzsafe", 1);
2269// #endif 2269// #endif
2270 saveConf(); 2270 saveConf();
2271 } 2271 }
2272 2272
2273 QListViewItem *i; 2273 QListViewItem *i;
2274 // step through all categories 2274 // step through all categories
2275 for (i = ListView->firstChild(); 2275 for (i = ListView->firstChild();
2276 i != NULL; 2276 i != NULL;
2277 i = i->nextSibling()) 2277 i = i->nextSibling())
2278 { 2278 {
2279 // step through all subitems 2279 // step through all subitems
2280 QListViewItem *si; 2280 QListViewItem *si;
2281 for (si = i->firstChild(); 2281 for (si = i->firstChild();
2282 si != NULL; 2282 si != NULL;
2283 si = si->nextSibling()) 2283 si = si->nextSibling())
2284 { 2284 {
2285 int j=0; 2285 int j=0;
2286 entry[j] = (char*)malloc(strlen(i->text(0).utf8())+1); 2286 entry[j] = (char*)malloc(strlen(i->text(0).utf8())+1);
2287 strcpy(entry[j++], i->text(0).utf8()); 2287 strcpy(entry[j++], i->text(0).utf8());
2288 entry[j] = (char*)malloc(strlen(si->text(0).utf8())+1); 2288 entry[j] = (char*)malloc(strlen(si->text(0).utf8())+1);
2289 strcpy(entry[j++], si->text(0).utf8()); 2289 strcpy(entry[j++], si->text(0).utf8());
2290 entry[j] = (char*)malloc(strlen(si->text(1).utf8())+1); 2290 entry[j] = (char*)malloc(strlen(si->text(1).utf8())+1);
2291 strcpy(entry[j++], si->text(1).utf8()); 2291 strcpy(entry[j++], si->text(1).utf8());
2292 entry[j] = (char*)malloc(strlen(si->text(2).utf8())+1); 2292 entry[j] = (char*)malloc(strlen(si->text(2).utf8())+1);
2293 strcpy(entry[j++], si->text(2).utf8()); 2293 strcpy(entry[j++], si->text(2).utf8());
2294 entry[j] = (char*)malloc(strlen(si->text(3).utf8())+1); 2294 entry[j] = (char*)malloc(strlen(si->text(3).utf8())+1);
2295 strcpy(entry[j++], si->text(3).utf8()); 2295 strcpy(entry[j++], si->text(3).utf8());
2296 entry[j] = (char*)malloc(strlen(si->text(4).utf8())+1); 2296 entry[j] = (char*)malloc(strlen(si->text(4).utf8())+1);
2297 strcpy(entry[j++], si->text(4).utf8()); 2297 strcpy(entry[j++], si->text(4).utf8());
2298 entry[j] = (char*)malloc(strlen(si->text(5).utf8())+1); 2298 entry[j] = (char*)malloc(strlen(si->text(5).utf8())+1);
2299 strcpy(entry[j++], si->text(5).utf8()); 2299 strcpy(entry[j++], si->text(5).utf8());
2300 2300
2301 retval = saveEntry(entry); 2301 retval = saveEntry(entry);
2302 for (int z=0; z<j; z++) 2302 for (int z=0; z<j; z++)
2303 { 2303 {
2304 free(entry[z]); 2304 free(entry[z]);
2305 } 2305 }
2306 if (retval == PWERR_DATA) { 2306 if (retval == PWERR_DATA) {
2307 qWarning("1: Error writing file, contents not saved"); 2307 qWarning("1: Error writing file, contents not saved");
2308 saveFinalize(); 2308 saveFinalize();
2309 return false; 2309 return false;
2310 } 2310 }
2311 2311
2312 } 2312 }
2313 } 2313 }
2314 2314
2315 if (saveFinalize() == PWERR_DATA) { 2315 if (saveFinalize() == PWERR_DATA) {
2316 qWarning("2: Error writing file, contents not saved"); 2316 qWarning("2: Error writing file, contents not saved");
2317 return false; 2317 return false;
2318 } else { 2318 } else {
2319#ifndef DESKTOP 2319#ifndef DESKTOP
2320 Global::statusMessage (tr("Password file saved.")); 2320 Global::statusMessage (tr("Password file saved."));
2321#endif 2321#endif
2322 modified = false; 2322 modified = false;
2323 return true; 2323 return true;
2324 } 2324 }
2325} 2325}
2326 2326
2327PasswordForm *newPwdDialog; 2327PasswordForm *newPwdDialog;
2328bool newPwdDialogResult = false; 2328bool newPwdDialogResult = false;
2329void ZSafe::setPasswordDialogDone() 2329void ZSafe::setPasswordDialogDone()
2330{ 2330{
2331 newPwdDialogResult = true; 2331 newPwdDialogResult = true;
2332 newPwdDialog->close(); 2332 newPwdDialog->close();
2333} 2333}
2334 2334
2335void ZSafe::getDocPassword(QString title) 2335void ZSafe::getDocPassword(QString title)
2336{ 2336{
2337qWarning ("getDocPassword"); 2337qWarning ("getDocPassword");
2338 // open the 'Password' dialog 2338 // open the 'Password' dialog
2339 PasswordForm *dialog = new PasswordForm(this, title, TRUE); 2339 PasswordForm *dialog = new PasswordForm(this, title, TRUE);
2340 newPwdDialog = dialog; 2340 newPwdDialog = dialog;
2341 newPwdDialogResult = false; 2341 newPwdDialogResult = false;
2342 2342
2343 connect( dialog->PasswordField, SIGNAL( returnPressed() ), 2343 connect( dialog->PasswordField, SIGNAL( returnPressed() ),
2344 this, SLOT( setPasswordDialogDone() ) ); 2344 this, SLOT( setPasswordDialogDone() ) );
2345 2345
2346 // CS: !!! 2346 // CS: !!!
2347 // int pos = filename.findRev ('/'); 2347 // int pos = filename.findRev ('/');
2348 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 2348 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
2349#ifdef WIN32 2349#ifdef WIN32
2350 dialog->setCaption("Qt " + ti); 2350 dialog->setCaption("Qt " + ti);
2351#else 2351#else
2352 dialog->setCaption(ti); 2352 dialog->setCaption(ti);
2353#endif 2353#endif
2354 // dialog->setCaption(title); 2354 // dialog->setCaption(title);
2355 2355
2356 dialog->PasswordField->setFocus(); 2356 dialog->PasswordField->setFocus();
2357 DialogCode result = (DialogCode) dialog->exec(); 2357 DialogCode result = (DialogCode) dialog->exec();
2358#ifdef DESKTOP 2358#ifdef DESKTOP
2359 result = Accepted; 2359 result = Accepted;
2360#endif 2360#endif
2361 2361
2362 QString password; 2362 QString password;
2363 if (result == Accepted || newPwdDialogResult) 2363 if (result == Accepted || newPwdDialogResult)
2364 { 2364 {
2365 m_password = dialog->PasswordField->text(); 2365 m_password = dialog->PasswordField->text();
2366 } 2366 }
2367 else 2367 else
2368 { 2368 {
2369 exitZs (1); 2369 exitZs (1);
2370 } 2370 }
2371} 2371}
2372 2372
2373int ZSafe::saveInit(const char *_filename, const char *password) 2373int ZSafe::saveInit(const char *_filename, const char *password)
2374{ 2374{
2375 char key[128]; 2375 char key[128];
2376 unsigned int j = 0; 2376 unsigned int j = 0;
2377 unsigned int keylength; 2377 unsigned int keylength;
2378 // int val; 2378 // int val;
2379 int count2; 2379 int count2;
2380 Krc2* krc2 = new Krc2(); 2380 Krc2* krc2 = new Krc2();
2381 2381
2382 /* first we should check the permissions of the filename */ 2382 /* first we should check the permissions of the filename */
2383/* 2383/*
2384 if (QFile::exists(_filename)) { 2384 if (QFile::exists(_filename)) {
2385 val = checkFile(_filename); 2385 val = checkFile(_filename);
2386 if (val != PWERR_GOOD) 2386 if (val != PWERR_GOOD)
2387 return val; 2387 return val;
2388 } else 2388 } else
2389 { 2389 {
2390 val = creat (_filename, (S_IRUSR | S_IWUSR)); 2390 val = creat (_filename, (S_IRUSR | S_IWUSR));
2391 if (val == -1) 2391 if (val == -1)
2392 return PWERR_OPEN; 2392 return PWERR_OPEN;
2393 else 2393 else
2394 close(val); 2394 close(val);
2395 } 2395 }
2396*/ 2396*/
2397 QFileInfo f (_filename); 2397 QFileInfo f (_filename);
2398 save_buffer_length = f.size(); 2398 save_buffer_length = f.size();
2399 save_buffer_length = ((save_buffer_length / 1024)+1) * 1024; 2399 save_buffer_length = ((save_buffer_length / 1024)+1) * 1024;
2400 2400
2401 fd = fopen (_filename, "wb"); 2401 fd = fopen (_filename, "wb");
2402 if (fd == NULL) 2402 if (fd == NULL)
2403 return PWERR_OPEN; 2403 return PWERR_OPEN;
2404 2404
2405 buffer = (char*)malloc(save_buffer_length); 2405 buffer = (char*)malloc(save_buffer_length);
2406 2406
2407 /* make the key ready */ 2407 /* make the key ready */
2408 for (j = 0; password[j] != '\0'; j++) { 2408 for (j = 0; password[j] != '\0'; j++) {
2409 key[j] = password[j]; 2409 key[j] = password[j];
2410 } 2410 }
2411 keylength = j; 2411 keylength = j;
2412 krc2->rc2_expandkey (key, keylength, 128); 2412 krc2->rc2_expandkey (key, keylength, 128);
2413 2413
2414 /* First, we make the IV */ 2414 /* First, we make the IV */
2415 for (count2 = 0; count2 < 4; count2++) { 2415 for (count2 = 0; count2 < 4; count2++) {
2416 iv[count2] = rand (); 2416 iv[count2] = rand ();
2417 putc ((unsigned char) (iv[count2] >> 8), fd); 2417 putc ((unsigned char) (iv[count2] >> 8), fd);
2418 putc ((unsigned char) (iv[count2] & 0xff), fd); 2418 putc ((unsigned char) (iv[count2] & 0xff), fd);
2419 } 2419 }
2420 2420
2421 bufferIndex = 0; 2421 bufferIndex = 0;
2422 return PWERR_GOOD; 2422 return PWERR_GOOD;
2423} 2423}
2424 2424
2425 2425
2426int ZSafe::saveEntry(char *entry[FIELD_SIZE]) 2426int ZSafe::saveEntry(char *entry[FIELD_SIZE])
2427{ 2427{
2428 char *text1; 2428 char *text1;
2429 int count2, count3; 2429 int count2, count3;
2430 unsigned short ciphertext[4]; 2430 unsigned short ciphertext[4];
2431 Krc2* krc2 = new Krc2(); 2431 Krc2* krc2 = new Krc2();
2432 2432
2433 buffer = (char*)memset(buffer, '\0', save_buffer_length); 2433 buffer = (char*)memset(buffer, '\0', save_buffer_length);
2434 2434
2435 for (count2 = 0; count2 < FIELD_SIZE; count2++) { 2435 for (count2 = 0; count2 < FIELD_SIZE; count2++) {
2436 text1 = entry[count2]; 2436 text1 = entry[count2];
2437 if (strlen (text1) == 0) { 2437 if (strlen (text1) == 0) {
2438 strncat(buffer, " ", strlen(" ")); 2438 strncat(buffer, " ", strlen(" "));
2439 } else { 2439 } else {
2440 strncat(buffer, text1, strlen(text1)); 2440 strncat(buffer, text1, strlen(text1));
2441 } 2441 }
2442 /* Use 255 as the marker. \n is too tough to test for */ 2442 /* Use 255 as the marker. \n is too tough to test for */
2443 buffer[strlen (buffer)] = 255; 2443 buffer[strlen (buffer)] = 255;
2444 } /*for (count2 = 0; count2 < 5; count2++)*/ 2444 } /*for (count2 = 0; count2 < 5; count2++)*/
2445 count2 = 0; 2445 count2 = 0;
2446 /* I'm using CBC mode and encrypting the data straight from top down. 2446 /* I'm using CBC mode and encrypting the data straight from top down.
2447 * At the bottom, encrypted, I will append an MD5 hash of the file, eventually. 2447 * At the bottom, encrypted, I will append an MD5 hash of the file, eventually.
2448 * PKCS 5 padding (explained at the code section 2448 * PKCS 5 padding (explained at the code section
2449 */ 2449 */
2450 while (count2 < (int)strlen (buffer)) { 2450 while (count2 < (int)strlen (buffer)) {
2451#ifndef WORDS_BIGENDIAN 2451#ifndef WORDS_BIGENDIAN
2452 plaintext[bufferIndex] = buffer[count2 + 1] << 8; 2452 plaintext[bufferIndex] = buffer[count2 + 1] << 8;
2453 plaintext[bufferIndex] += buffer[count2] & 0xff; 2453 plaintext[bufferIndex] += buffer[count2] & 0xff;
2454#endif 2454#endif
2455#ifdef WORDS_BIGENDIAN 2455#ifdef WORDS_BIGENDIAN
2456 plaintext[bufferIndex] = buffer[count2] << 8; 2456 plaintext[bufferIndex] = buffer[count2] << 8;
2457 plaintext[bufferIndex] += buffer[count2 + 1] & 0xff; 2457 plaintext[bufferIndex] += buffer[count2 + 1] & 0xff;
2458#endif 2458#endif
2459 bufferIndex++; 2459 bufferIndex++;
2460 if (bufferIndex == 4) { 2460 if (bufferIndex == 4) {
2461 krc2->rc2_encrypt (plaintext); 2461 krc2->rc2_encrypt (plaintext);
2462 2462
2463 for (count3 = 0; count3 < 4; count3++) { 2463 for (count3 = 0; count3 < 4; count3++) {
2464 ciphertext[count3] = iv[count3] ^ plaintext[count3]; 2464 ciphertext[count3] = iv[count3] ^ plaintext[count3];
2465 2465
2466 /* Now store the ciphertext as the iv */ 2466 /* Now store the ciphertext as the iv */
2467 iv[count3] = plaintext[count3]; 2467 iv[count3] = plaintext[count3];
2468 2468
2469 /* reset the buffer index */ 2469 /* reset the buffer index */
2470 bufferIndex = 0; 2470 bufferIndex = 0;
2471 if (putc ((unsigned char) (ciphertext[count3] >> 8), fd) == EOF) return PWERR_DATA; 2471 if (putc ((unsigned char) (ciphertext[count3] >> 8), fd) == EOF) return PWERR_DATA;
2472 if (putc ((unsigned char) (ciphertext[count3] & 0xff), fd) == EOF) return PWERR_DATA; 2472 if (putc ((unsigned char) (ciphertext[count3] & 0xff), fd) == EOF) return PWERR_DATA;
2473 } /*for (count3 = 0; count3 < 5; count3++)*/ 2473 } /*for (count3 = 0; count3 < 5; count3++)*/
2474 } /*if (bufferIndex == 5)*/ 2474 } /*if (bufferIndex == 5)*/
2475 /* increment a short, not a byte */ 2475 /* increment a short, not a byte */
2476 count2 += 2; 2476 count2 += 2;
2477 } /*while (count2 < strlen (buffer))*/ 2477 } /*while (count2 < strlen (buffer))*/
2478 int ret = PWERR_GOOD; 2478 int ret = PWERR_GOOD;
2479 return ret; 2479 return ret;
2480} 2480}
2481 2481
2482int ZSafe::saveFinalize(void) 2482int ZSafe::saveFinalize(void)
2483{ 2483{
2484 int count1, retval = PWERR_GOOD; 2484 int count1, retval = PWERR_GOOD;
2485 unsigned short ciphertext[4]; 2485 unsigned short ciphertext[4];
2486 Krc2* krc2 = new Krc2(); 2486 Krc2* krc2 = new Krc2();
2487 2487
2488 /* Tack on the PKCS 5 padding 2488 /* Tack on the PKCS 5 padding
2489 * How it works is we fill up the last n bytes with the value n 2489 * How it works is we fill up the last n bytes with the value n
2490 * 2490 *
2491 * So, if we have, say, 13 bytes, 8 of which are used, we have 5 left 2491 * So, if we have, say, 13 bytes, 8 of which are used, we have 5 left
2492 * over, leaving us 3 short, so we fill it in with 3's. 2492 * over, leaving us 3 short, so we fill it in with 3's.
2493 * 2493 *
2494 * If we come out even, we fill it with 8 8s 2494 * If we come out even, we fill it with 8 8s
2495 * 2495 *
2496 * um, except that in this instance we are using 4 shorts instead of 8 bytes. 2496 * um, except that in this instance we are using 4 shorts instead of 8 bytes.
2497 * so, half everything 2497 * so, half everything
2498 */ 2498 */
2499 for (count1 = bufferIndex; count1 < 4; count1++) { 2499 for (count1 = bufferIndex; count1 < 4; count1++) {
2500 plaintext[count1] = (4 - bufferIndex); 2500 plaintext[count1] = (4 - bufferIndex);
2501 } 2501 }
2502 krc2->rc2_encrypt (plaintext); 2502 krc2->rc2_encrypt (plaintext);
2503 for (count1 = 0; count1 < 4; count1++) { 2503 for (count1 = 0; count1 < 4; count1++) {
2504 ciphertext[count1] = iv[count1] ^ plaintext[count1]; 2504 ciphertext[count1] = iv[count1] ^ plaintext[count1];
2505 if (putc ((unsigned char) (ciphertext[count1] >> 8), fd) == EOF) retval = PWERR_DATA; 2505 if (putc ((unsigned char) (ciphertext[count1] >> 8), fd) == EOF) retval = PWERR_DATA;
2506 if (putc ((unsigned char) (ciphertext[count1] & 0xff), fd) == EOF) retval = PWERR_DATA; 2506 if (putc ((unsigned char) (ciphertext[count1] & 0xff), fd) == EOF) retval = PWERR_DATA;
2507 } 2507 }
2508 2508
2509 fclose (fd); 2509 fclose (fd);
2510 free(buffer); 2510 free(buffer);
2511 return retval; 2511 return retval;
2512} 2512}
2513 2513
2514void ZSafe::quitMe () 2514void ZSafe::quitMe ()
2515{ 2515{
2516 qWarning ("QUIT..."); 2516 qWarning ("QUIT...");
2517 2517
2518 if (modified) 2518 if (modified)
2519 { 2519 {
2520 switch( QMessageBox::information( this, tr("ZSafe"), 2520 switch( QMessageBox::information( this, tr("ZSafe"),
2521 tr("Do you want to save\nbefore exiting?"), 2521 tr("Do you want to save\nbefore exiting?"),
2522 tr("&Save"), 2522 tr("&Save"),
2523 tr("S&ave with\nnew\npassword"), 2523 tr("S&ave with\nnew\npassword"),
2524 tr("&Don't Save"), 2524 tr("&Don't Save"),
2525 0 // Enter == button 0 2525 0 // Enter == button 0
2526 ) ) 2526 ) )
2527 { // Escape == button 2 2527 { // Escape == button 2
2528 case 0: // Save clicked, Alt-S or Enter pressed. 2528 case 0: // Save clicked, Alt-S or Enter pressed.
2529 // save 2529 // save
2530 modified = false; 2530 modified = false;
2531 saveDocument(filename, FALSE); 2531 saveDocument(filename, FALSE);
2532 exitZs (1); 2532 exitZs (1);
2533 break; 2533 break;
2534 case 1: // 2534 case 1: //
2535 // Save with new password 2535 // Save with new password
2536 modified = false; 2536 modified = false;
2537 saveDocument(filename, TRUE); 2537 saveDocument(filename, TRUE);
2538 exitZs (1); 2538 exitZs (1);
2539 break; 2539 break;
2540 case 2: // Don't Save clicked or Alt-D pressed 2540 case 2: // Don't Save clicked or Alt-D pressed
2541 // don't save but exitZs 2541 // don't save but exitZs
2542 exitZs (1); 2542 exitZs (1);
2543 break; 2543 break;
2544 } 2544 }
2545 } 2545 }
2546 exitZs (1); 2546 exitZs (1);
2547 2547
2548} 2548}
2549 2549
2550void ZSafe::categoryFieldActivated( const QString& category) 2550void ZSafe::categoryFieldActivated( const QString& category)
2551{ 2551{
2552 if (categoryDialog) 2552 if (categoryDialog)
2553 setCategoryDialogFields(categoryDialog, category); 2553 setCategoryDialogFields(categoryDialog, category);
2554} 2554}
2555 2555
2556void ZSafe::addCategory() 2556void ZSafe::addCategory()
2557{ 2557{
2558 if (filename.isEmpty()) 2558 if (filename.isEmpty())
2559 { 2559 {
2560 QMessageBox::critical( 0, tr("ZSafe"), 2560 QMessageBox::critical( 0, tr("ZSafe"),
2561 tr("No document defined.\nYou have to create a new document")); 2561 tr("No document defined.\nYou have to create a new document"));
2562 return; 2562 return;
2563 } 2563 }
2564 else 2564 else
2565 { 2565 {
2566 // open the 'Category' dialog 2566 // open the 'Category' dialog
2567 bool initIcons = false; 2567 bool initIcons = false;
2568 // open the 'Category' dialog 2568 // open the 'Category' dialog
2569 CategoryDialog *dialog; 2569 CategoryDialog *dialog;
2570 if (categoryDialog) 2570 if (categoryDialog)
2571 { 2571 {
2572 dialog = categoryDialog; 2572 dialog = categoryDialog;
2573 } 2573 }
2574 else 2574 else
2575 { 2575 {
2576 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE); 2576 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE);
2577#ifdef WIN32 2577#ifdef WIN32
2578 categoryDialog->setCaption ("Qt " + tr("Category")); 2578 categoryDialog->setCaption ("Qt " + tr("Category"));
2579#endif 2579#endif
2580 dialog = categoryDialog; 2580 dialog = categoryDialog;
2581 connect( dialog->CategoryField, 2581 connect( dialog->CategoryField,
2582 SIGNAL( activated ( const QString &)), 2582 SIGNAL( activated(const QString&)),
2583 this, SLOT( categoryFieldActivated( const QString & ) ) ); 2583 this, SLOT( categoryFieldActivated(const QString&) ) );
2584 initIcons = true; 2584 initIcons = true;
2585 } 2585 }
2586 2586
2587#ifdef DESKTOP 2587#ifdef DESKTOP
2588#ifndef WIN32 2588#ifndef WIN32
2589 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" ); 2589 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" );
2590#else 2590#else
2591 // read all categories from the config file and store 2591 // read all categories from the config file and store
2592 // into a list 2592 // into a list
2593 QFile f (cfgFile); 2593 QFile f (cfgFile);
2594 QStringList list; 2594 QStringList list;
2595 if ( f.open(IO_ReadOnly) ) { // file opened successfully 2595 if ( f.open(IO_ReadOnly) ) { // file opened successfully
2596 QTextStream t( &f ); // use a text stream 2596 QTextStream t( &f ); // use a text stream
2597 QString s; 2597 QString s;
2598 int n = 1; 2598 int n = 1;
2599 while ( !t.eof() ) { // until end of file... 2599 while ( !t.eof() ) { // until end of file...
2600 s = t.readLine(); // line of text excluding '\n' 2600 s = t.readLine(); // line of text excluding '\n'
2601 list.append(s); 2601 list.append(s);
2602 } 2602 }
2603 f.close(); 2603 f.close();
2604 } 2604 }
2605#endif 2605#endif
2606#else 2606#else
2607 // read all categories from the config file and store 2607 // read all categories from the config file and store
2608 // into a list 2608 // into a list
2609 QFile f (cfgFile); 2609 QFile f (cfgFile);
2610 QStringList list; 2610 QStringList list;
2611 if ( f.open(IO_ReadOnly) ) { // file opened successfully 2611 if ( f.open(IO_ReadOnly) ) { // file opened successfully
2612 QTextStream t( &f ); // use a text stream 2612 QTextStream t( &f ); // use a text stream
2613 QString s; 2613 QString s;
2614 while ( !t.eof() ) { // until end of file... 2614 while ( !t.eof() ) { // until end of file...
2615 s = t.readLine(); // line of text excluding '\n' 2615 s = t.readLine(); // line of text excluding '\n'
2616 list.append(s); 2616 list.append(s);
2617 } 2617 }
2618 f.close(); 2618 f.close();
2619 } 2619 }
2620#endif 2620#endif
2621 QStringList::Iterator it = list.begin(); 2621 QStringList::Iterator it = list.begin();
2622 QString categ; 2622 QString categ;
2623 QString firstCategory; 2623 QString firstCategory;
2624 dialog->CategoryField->clear(); // remove all items 2624 dialog->CategoryField->clear(); // remove all items
2625 while( it != list.end() ) 2625 while( it != list.end() )
2626 { 2626 {
2627 QString *cat = new QString (*it); 2627 QString *cat = new QString (*it);
2628 if (cat->contains("-field1", FALSE)) 2628 if (cat->contains("-field1", FALSE))
2629 { 2629 {
2630#ifdef DESKTOP 2630#ifdef DESKTOP
2631#ifndef WIN32 2631#ifndef WIN32
2632 categ = cat->section ("-field1", 0, 0); 2632 categ = cat->section ("-field1", 0, 0);
2633#else 2633#else
2634 int pos = cat->find ("-field1"); 2634 int pos = cat->find ("-field1");
2635 categ = cat->left (pos); 2635 categ = cat->left (pos);
2636#endif 2636#endif
2637#else 2637#else
2638 int pos = cat->find ("-field1"); 2638 int pos = cat->find ("-field1");
2639 cat->truncate(pos); 2639 cat->truncate(pos);
2640 categ = *cat; 2640 categ = *cat;
2641#endif 2641#endif
2642 if (!categ.isEmpty()) 2642 if (!categ.isEmpty())
2643 { 2643 {
2644 dialog->CategoryField->insertItem (categ, -1); 2644 dialog->CategoryField->insertItem (categ, -1);
2645 if (firstCategory.isEmpty()) 2645 if (firstCategory.isEmpty())
2646 firstCategory = categ; 2646 firstCategory = categ;
2647 } 2647 }
2648 } 2648 }
2649 ++it; 2649 ++it;
2650 } 2650 }
2651 2651
2652 2652
2653 if (firstCategory.isEmpty()) 2653 if (firstCategory.isEmpty())
2654 setCategoryDialogFields(dialog); 2654 setCategoryDialogFields(dialog);
2655 else 2655 else
2656 setCategoryDialogFields(dialog, firstCategory); 2656 setCategoryDialogFields(dialog, firstCategory);
2657 2657
2658 // CategoryDialog *dialog = new CategoryDialog(this, "Category", TRUE); 2658 // CategoryDialog *dialog = new CategoryDialog(this, "Category", TRUE);
2659 2659
2660 if (initIcons) 2660 if (initIcons)
2661 { 2661 {
2662 Wait waitDialog(this, tr("Wait dialog")); 2662 Wait waitDialog(this, tr("Wait dialog"));
2663 waitDialog.waitLabel->setText(tr("Gathering icons...")); 2663 waitDialog.waitLabel->setText(tr("Gathering icons..."));
2664 waitDialog.show(); 2664 waitDialog.show();
2665 qApp->processEvents(); 2665 qApp->processEvents();
2666 2666
2667#ifdef DESKTOP 2667#ifdef DESKTOP
2668 QDir d(iconPath); 2668 QDir d(iconPath);
2669#else 2669#else
2670 QDir d(QPEApplication::qpeDir() + "/pics/"); 2670 QDir d(QPEApplication::qpeDir() + "/pics/");
2671#endif 2671#endif
2672 d.setFilter( QDir::Files); 2672 d.setFilter( QDir::Files);
2673 2673
2674 const QFileInfoList *list = d.entryInfoList(); 2674 const QFileInfoList *list = d.entryInfoList();
2675 QFileInfoListIterator it( *list ); // create list iterator 2675 QFileInfoListIterator it( *list ); // create list iterator
2676 QFileInfo *fi; // pointer for traversing 2676 QFileInfo *fi; // pointer for traversing
2677 2677
2678 dialog->IconField->insertItem("predefined"); 2678 dialog->IconField->insertItem("predefined");
2679 while ( (fi=it.current()) ) { // for each file... 2679 while ( (fi=it.current()) ) { // for each file...
2680 QString fileName = fi->fileName(); 2680 QString fileName = fi->fileName();
2681 if(fileName.right(4) == ".png"){ 2681 if(fileName.right(4) == ".png"){
2682 fileName = fileName.mid(0,fileName.length()-4); 2682 fileName = fileName.mid(0,fileName.length()-4);
2683#ifdef DESKTOP 2683#ifdef DESKTOP
2684 QPixmap imageOfFile; 2684 QPixmap imageOfFile;
2685 imageOfFile.load(iconPath + fi->fileName()); 2685 imageOfFile.load(iconPath + fi->fileName());
2686#else 2686#else
2687 QPixmap imageOfFile(Resource::loadPixmap(fileName)); 2687 QPixmap imageOfFile(Resource::loadPixmap(fileName));
2688#endif 2688#endif
2689 QImage foo = imageOfFile.convertToImage(); 2689 QImage foo = imageOfFile.convertToImage();
2690 foo = foo.smoothScale(16,16); 2690 foo = foo.smoothScale(16,16);
2691 imageOfFile.convertFromImage(foo); 2691 imageOfFile.convertFromImage(foo);
2692 dialog->IconField->insertItem(imageOfFile,fileName); 2692 dialog->IconField->insertItem(imageOfFile,fileName);
2693 } 2693 }
2694 ++it; 2694 ++it;
2695 } 2695 }
2696 waitDialog.hide(); 2696 waitDialog.hide();
2697 } 2697 }
2698 2698
2699#ifndef WIN32 2699#ifndef WIN32
2700 dialog->show(); 2700 dialog->show();
2701#endif 2701#endif
2702#ifndef DESKTOP 2702#ifndef DESKTOP
2703 // dialog->move (20, 100); 2703 // dialog->move (20, 100);
2704#endif 2704#endif
2705 DialogCode result = (DialogCode) dialog->exec(); 2705 DialogCode result = (DialogCode) dialog->exec();
2706#ifdef DESKTOP 2706#ifdef DESKTOP
2707 result = Accepted; 2707 result = Accepted;
2708#endif 2708#endif
2709 2709
2710 QString category; 2710 QString category;
2711 QString icon; 2711 QString icon;
2712 QString fullIconPath; 2712 QString fullIconPath;
2713 QPixmap *pix; 2713 QPixmap *pix;
2714 if (result == Accepted) 2714 if (result == Accepted)
2715 { 2715 {
2716 modified = true; 2716 modified = true;
2717 category = dialog->CategoryField->currentText(); 2717 category = dialog->CategoryField->currentText();
2718 icon = dialog->IconField->currentText()+".png"; 2718 icon = dialog->IconField->currentText()+".png";
2719 2719
2720 qWarning (category); 2720 qWarning (category);
2721 2721
2722 QListViewItem *li = new ShadedListItem( 1, ListView ); 2722 QListViewItem *li = new ShadedListItem( 1, ListView );
2723 Category *c1 = new Category(); 2723 Category *c1 = new Category();
2724 c1->setCategoryName(category); 2724 c1->setCategoryName(category);
2725 2725
2726 // if (!icon.isEmpty() && !icon.isNull()) 2726 // if (!icon.isEmpty() && !icon.isNull())
2727 if (icon != "predefined.png") 2727 if (icon != "predefined.png")
2728 { 2728 {
2729 // build the full path 2729 // build the full path
2730 fullIconPath = iconPath + icon; 2730 fullIconPath = iconPath + icon;
2731 pix = new QPixmap (fullIconPath); 2731 pix = new QPixmap (fullIconPath);
2732 // pix->resize(14, 14); 2732 // pix->resize(14, 14);
2733 if (pix) 2733 if (pix)
2734 { 2734 {
2735 // save the full pixmap name into the config file 2735 // save the full pixmap name into the config file
2736// #ifndef WIN32 2736// #ifndef WIN32
2737 conf->writeEntry(APP_KEY+category, icon); 2737 conf->writeEntry(APP_KEY+category, icon);
2738// #endif 2738// #endif
2739 saveConf(); 2739 saveConf();
2740 QImage img = pix->convertToImage(); 2740 QImage img = pix->convertToImage();
2741 pix->convertFromImage(img.smoothScale(14,14)); 2741 pix->convertFromImage(img.smoothScale(14,14));
2742 c1->setIcon (*pix); 2742 c1->setIcon (*pix);
2743 c1->setIconName(icon); 2743 c1->setIconName(icon);
2744 } 2744 }
2745 else 2745 else
2746 { 2746 {
2747 QPixmap folder( ( const char** ) general_data ); 2747 QPixmap folder( ( const char** ) general_data );
2748 c1->setIcon (folder); 2748 c1->setIcon (folder);
2749 } 2749 }
2750 } 2750 }
2751 else 2751 else
2752 { 2752 {
2753 c1->setIcon (*getPredefinedIcon(category)); 2753 c1->setIcon (*getPredefinedIcon(category));
2754 } 2754 }
2755 2755
2756 c1->setListItem (li); 2756 c1->setListItem (li);
2757 c1->initListItem(); 2757 c1->initListItem();
2758 categories.insert (c1->getCategoryName(), c1); 2758 categories.insert (c1->getCategoryName(), c1);
2759 2759
2760 saveCategoryDialogFields(dialog); 2760 saveCategoryDialogFields(dialog);
2761 } 2761 }
2762 else 2762 else
2763 { 2763 {
2764 // delete dialog; 2764 // delete dialog;
2765 dialog->hide(); 2765 dialog->hide();
2766 return; 2766 return;
2767 } 2767 }
2768 2768
2769 } 2769 }
2770 2770
2771} 2771}
2772 2772
2773void ZSafe::delCategory() 2773void ZSafe::delCategory()
2774{ 2774{
2775 if (!selectedItem) 2775 if (!selectedItem)
2776 return; 2776 return;
2777 if (isCategory(selectedItem)) 2777 if (isCategory(selectedItem))
2778 { 2778 {
2779 switch( QMessageBox::information( this, tr("ZSafe"), 2779 switch( QMessageBox::information( this, tr("ZSafe"),
2780 tr("Do you want to delete?"), 2780 tr("Do you want to delete?"),
2781 tr("&Delete"), tr("D&on't Delete"), 2781 tr("&Delete"), tr("D&on't Delete"),
2782 0 // Enter == button 0 2782 0 // Enter == button 0
2783 ) ) { // Escape == button 2 2783 ) ) { // Escape == button 2
2784 case 0: // Delete clicked, Alt-S or Enter pressed. 2784 case 0: // Delete clicked, Alt-S or Enter pressed.
2785 // Delete from the category list 2785 // Delete from the category list
2786 modified = true; 2786 modified = true;
2787 categories.remove (selectedItem->text(0)); 2787 categories.remove (selectedItem->text(0));
2788// #ifndef WIN32 2788// #ifndef WIN32
2789 conf->removeEntry (selectedItem->text(0)); 2789 conf->removeEntry (selectedItem->text(0));
2790// #endif 2790// #endif
2791 saveConf(); 2791 saveConf();
2792 2792
2793 // Delete the selected item and all subitems 2793 // Delete the selected item and all subitems
2794 // step through all subitems 2794 // step through all subitems
2795 QListViewItem *si; 2795 QListViewItem *si;
2796 for (si = selectedItem->firstChild(); 2796 for (si = selectedItem->firstChild();
2797 si != NULL; ) 2797 si != NULL; )
2798 { 2798 {
2799 QListViewItem *_si = si; 2799 QListViewItem *_si = si;
2800 si = si->nextSibling(); 2800 si = si->nextSibling();
2801 selectedItem->takeItem(_si); // remove from view list 2801 selectedItem->takeItem(_si); // remove from view list
2802 if (_si) delete _si; 2802 if (_si) delete _si;
2803 } 2803 }
2804 ListView->takeItem(selectedItem); 2804 ListView->takeItem(selectedItem);
2805 delete selectedItem; 2805 delete selectedItem;
2806 2806
2807 selectedItem = NULL; 2807 selectedItem = NULL;
2808 break; 2808 break;
2809 case 1: // Don't delete 2809 case 1: // Don't delete
2810 break; 2810 break;
2811 } 2811 }
2812 2812
2813 } 2813 }
2814} 2814}
2815 2815
2816void ZSafe::setCategoryDialogFields(CategoryDialog *dialog) 2816void ZSafe::setCategoryDialogFields(CategoryDialog *dialog)
2817{ 2817{
2818 if (!dialog) 2818 if (!dialog)
2819 return; 2819 return;
2820 2820
2821 QString icon; 2821 QString icon;
2822 if (selectedItem) 2822 if (selectedItem)
2823 { 2823 {
2824 dialog->Field1->setText(getFieldLabel (selectedItem, "1", tr("Name"))); 2824 dialog->Field1->setText(getFieldLabel (selectedItem, "1", tr("Name")));
2825 dialog->Field2->setText(getFieldLabel (selectedItem, "2", tr("Username"))); 2825 dialog->Field2->setText(getFieldLabel (selectedItem, "2", tr("Username")));
2826 dialog->Field3->setText(getFieldLabel (selectedItem, "3", tr("Password"))); 2826 dialog->Field3->setText(getFieldLabel (selectedItem, "3", tr("Password")));
2827 dialog->Field4->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); 2827 dialog->Field4->setText(getFieldLabel (selectedItem, "4", tr("Comment")));
2828 dialog->Field5->setText(getFieldLabel (selectedItem, "5", tr("Field 4"))); 2828 dialog->Field5->setText(getFieldLabel (selectedItem, "5", tr("Field 4")));
2829 dialog->Field6->setText(getFieldLabel (selectedItem, "6", tr("Field 5"))); 2829 dialog->Field6->setText(getFieldLabel (selectedItem, "6", tr("Field 5")));
2830 2830
2831 Category *cat= categories.find (selectedItem->text(0)); 2831 Category *cat= categories.find (selectedItem->text(0));
2832 if (cat) 2832 if (cat)
2833 { 2833 {
2834 icon = cat->getIconName(); 2834 icon = cat->getIconName();
2835 } 2835 }
2836 else 2836 else
2837 icon = conf->readEntry(APP_KEY+selectedItem->text(0)); 2837 icon = conf->readEntry(APP_KEY+selectedItem->text(0));
2838 } 2838 }
2839 else 2839 else
2840 { 2840 {
2841 dialog->Field1->setText(tr("Name")); 2841 dialog->Field1->setText(tr("Name"));
2842 dialog->Field2->setText(tr("Username")); 2842 dialog->Field2->setText(tr("Username"));
2843 dialog->Field3->setText(tr("Password")); 2843 dialog->Field3->setText(tr("Password"));
2844 dialog->Field4->setText(tr("Comment")); 2844 dialog->Field4->setText(tr("Comment"));
2845 dialog->Field5->setText(tr("Field 4")); 2845 dialog->Field5->setText(tr("Field 4"));
2846 dialog->Field6->setText(tr("Field 5")); 2846 dialog->Field6->setText(tr("Field 5"));
2847 } 2847 }
2848 2848
2849#ifdef DESKTOP 2849#ifdef DESKTOP
2850 QDir d(iconPath); 2850 QDir d(iconPath);
2851#else 2851#else
2852 QDir d(QPEApplication::qpeDir() + "/pics/"); 2852 QDir d(QPEApplication::qpeDir() + "/pics/");
2853#endif 2853#endif
2854 d.setFilter( QDir::Files); 2854 d.setFilter( QDir::Files);
2855 2855
2856 const QFileInfoList *list = d.entryInfoList(); 2856 const QFileInfoList *list = d.entryInfoList();
2857 int i=0; 2857 int i=0;
2858 QFileInfoListIterator it( *list ); // create list iterator 2858 QFileInfoListIterator it( *list ); // create list iterator
2859 QFileInfo *fi; // pointer for traversing 2859 QFileInfo *fi; // pointer for traversing
2860 if (icon.isEmpty() || icon.isNull()) 2860 if (icon.isEmpty() || icon.isNull())
2861 { 2861 {
2862 dialog->IconField->setCurrentItem(0); 2862 dialog->IconField->setCurrentItem(0);
2863 } 2863 }
2864 else 2864 else
2865 { 2865 {
2866 while ( (fi=it.current()) ) 2866 while ( (fi=it.current()) )
2867 { // for each file... 2867 { // for each file...
2868 QString fileName = fi->fileName(); 2868 QString fileName = fi->fileName();
2869 if(fileName.right(4) == ".png") 2869 if(fileName.right(4) == ".png")
2870 { 2870 {
2871 fileName = fileName.mid(0,fileName.length()-4); 2871 fileName = fileName.mid(0,fileName.length()-4);
2872 2872
2873 if(fileName+".png"==icon) 2873 if(fileName+".png"==icon)
2874 { 2874 {
2875 dialog->IconField->setCurrentItem(i+1); 2875 dialog->IconField->setCurrentItem(i+1);
2876 break; 2876 break;
2877 } 2877 }
2878 ++i; 2878 ++i;
2879 } 2879 }
2880 ++it; 2880 ++it;
2881 } 2881 }
2882 } 2882 }
2883} 2883}
2884 2884
2885void ZSafe::setCategoryDialogFields(CategoryDialog *dialog, QString category) 2885void ZSafe::setCategoryDialogFields(CategoryDialog *dialog, QString category)
2886{ 2886{
2887 if (!dialog) 2887 if (!dialog)
2888 return; 2888 return;
2889 2889
2890 dialog->Field1->setText(getFieldLabel (category, "1", tr("Name"))); 2890 dialog->Field1->setText(getFieldLabel (category, "1", tr("Name")));
2891 dialog->Field2->setText(getFieldLabel (category, "2", tr("Username"))); 2891 dialog->Field2->setText(getFieldLabel (category, "2", tr("Username")));
2892 dialog->Field3->setText(getFieldLabel (category, "3", tr("Password"))); 2892 dialog->Field3->setText(getFieldLabel (category, "3", tr("Password")));
2893 dialog->Field4->setText(getFieldLabel (category, "4", tr("Comment"))); 2893 dialog->Field4->setText(getFieldLabel (category, "4", tr("Comment")));
2894 dialog->Field5->setText(getFieldLabel (category, "5", tr("Field 4"))); 2894 dialog->Field5->setText(getFieldLabel (category, "5", tr("Field 4")));
2895 dialog->Field6->setText(getFieldLabel (category, "6", tr("Field 5"))); 2895 dialog->Field6->setText(getFieldLabel (category, "6", tr("Field 5")));
2896 2896
2897 QString icon; 2897 QString icon;
2898 Category *cat= categories.find (category); 2898 Category *cat= categories.find (category);
2899 if (cat) 2899 if (cat)
2900 { 2900 {
2901 icon = cat->getIconName(); 2901 icon = cat->getIconName();
2902 } 2902 }
2903 else 2903 else
2904 icon = conf->readEntry(APP_KEY+category); 2904 icon = conf->readEntry(APP_KEY+category);
2905 2905
2906#ifdef DESKTOP 2906#ifdef DESKTOP
2907 QDir d(iconPath); 2907 QDir d(iconPath);
2908#else 2908#else
2909 QDir d(QPEApplication::qpeDir() + "/pics/"); 2909 QDir d(QPEApplication::qpeDir() + "/pics/");
2910#endif 2910#endif
2911 d.setFilter( QDir::Files); 2911 d.setFilter( QDir::Files);
2912 2912
2913 const QFileInfoList *list = d.entryInfoList(); 2913 const QFileInfoList *list = d.entryInfoList();
2914 int i=0; 2914 int i=0;
2915 QFileInfoListIterator it( *list ); // create list iterator 2915 QFileInfoListIterator it( *list ); // create list iterator
2916 QFileInfo *fi; // pointer for traversing 2916 QFileInfo *fi; // pointer for traversing
2917 if (icon.isEmpty() || icon.isNull()) 2917 if (icon.isEmpty() || icon.isNull())
2918 { 2918 {
2919 dialog->IconField->setCurrentItem(0); 2919 dialog->IconField->setCurrentItem(0);
2920 } 2920 }
2921 else 2921 else
2922 { 2922 {
2923 while ( (fi=it.current()) ) 2923 while ( (fi=it.current()) )
2924 { // for each file... 2924 { // for each file...
2925 QString fileName = fi->fileName(); 2925 QString fileName = fi->fileName();
2926 if(fileName.right(4) == ".png") 2926 if(fileName.right(4) == ".png")
2927 { 2927 {
2928 fileName = fileName.mid(0,fileName.length()-4); 2928 fileName = fileName.mid(0,fileName.length()-4);
2929 2929
2930 if(fileName+".png"==icon) 2930 if(fileName+".png"==icon)
2931 { 2931 {
2932 dialog->IconField->setCurrentItem(i+1); 2932 dialog->IconField->setCurrentItem(i+1);
2933 break; 2933 break;
2934 } 2934 }
2935 ++i; 2935 ++i;
2936 } 2936 }
2937 ++it; 2937 ++it;
2938 } 2938 }
2939 } 2939 }
2940} 2940}
2941 2941
2942void ZSafe::saveCategoryDialogFields(CategoryDialog *dialog) 2942void ZSafe::saveCategoryDialogFields(CategoryDialog *dialog)
2943{ 2943{
2944 QString app_key = APP_KEY; 2944 QString app_key = APP_KEY;
2945#ifndef DESKTOP 2945#ifndef DESKTOP
2946 conf->setGroup ("fieldDefs"); 2946 conf->setGroup ("fieldDefs");
2947#else 2947#else
2948#ifndef WIN32 2948#ifndef WIN32
2949 app_key += "/fieldDefs/"; 2949 app_key += "/fieldDefs/";
2950#endif 2950#endif
2951#endif 2951#endif
2952 QString category = dialog->CategoryField->currentText(); 2952 QString category = dialog->CategoryField->currentText();
2953// #ifndef WIN32 2953// #ifndef WIN32
2954 conf->writeEntry(app_key+category+"-field1", dialog->Field1->text()); 2954 conf->writeEntry(app_key+category+"-field1", dialog->Field1->text());
2955 conf->writeEntry(app_key+category+"-field2", dialog->Field2->text()); 2955 conf->writeEntry(app_key+category+"-field2", dialog->Field2->text());
2956 conf->writeEntry(app_key+category+"-field3", dialog->Field3->text()); 2956 conf->writeEntry(app_key+category+"-field3", dialog->Field3->text());
2957 conf->writeEntry(app_key+category+"-field4", dialog->Field4->text()); 2957 conf->writeEntry(app_key+category+"-field4", dialog->Field4->text());
2958 conf->writeEntry(app_key+category+"-field5", dialog->Field5->text()); 2958 conf->writeEntry(app_key+category+"-field5", dialog->Field5->text());
2959 conf->writeEntry(app_key+category+"-field6", dialog->Field6->text()); 2959 conf->writeEntry(app_key+category+"-field6", dialog->Field6->text());
2960// #endif 2960// #endif
2961 saveConf(); 2961 saveConf();
2962#ifndef DESKTOP 2962#ifndef DESKTOP
2963 conf->setGroup ("zsafe"); 2963 conf->setGroup ("zsafe");
2964#endif 2964#endif
2965} 2965}
2966 2966
2967void ZSafe::editCategory() 2967void ZSafe::editCategory()
2968{ 2968{
2969 if (!selectedItem) 2969 if (!selectedItem)
2970 return; 2970 return;
2971 if (isCategory(selectedItem)) 2971 if (isCategory(selectedItem))
2972 { 2972 {
2973 QString category = selectedItem->text(0); 2973 QString category = selectedItem->text(0);
2974 bool initIcons = false; 2974 bool initIcons = false;
2975 // open the 'Category' dialog 2975 // open the 'Category' dialog
2976 CategoryDialog *dialog; 2976 CategoryDialog *dialog;
2977 if (categoryDialog) 2977 if (categoryDialog)
2978 { 2978 {
2979 dialog = categoryDialog; 2979 dialog = categoryDialog;
2980 } 2980 }
2981 else 2981 else
2982 { 2982 {
2983 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE); 2983 categoryDialog = new CategoryDialog(this, tr("Category"), TRUE);
2984#ifdef WIN32 2984#ifdef WIN32
2985 categoryDialog->setCaption ("Qt " + tr("Category")); 2985 categoryDialog->setCaption ("Qt " + tr("Category"));
2986#endif 2986#endif
2987 dialog = categoryDialog; 2987 dialog = categoryDialog;
2988 connect( dialog->CategoryField, 2988 connect( dialog->CategoryField,
2989 SIGNAL( activated ( const QString &)), 2989 SIGNAL( activated(const QString&)),
2990 this, SLOT( categoryFieldActivated( const QString & ) ) ); 2990 this, SLOT( categoryFieldActivated(const QString&) ) );
2991 initIcons = true; 2991 initIcons = true;
2992 } 2992 }
2993 setCategoryDialogFields(dialog); 2993 setCategoryDialogFields(dialog);
2994 2994
2995#ifdef DESKTOP 2995#ifdef DESKTOP
2996#ifndef WIN32 2996#ifndef WIN32
2997 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" ); 2997 QStringList list = conf->entryList( APP_KEY+"/fieldDefs" );
2998#else 2998#else
2999 // read all categories from the config file and store 2999 // read all categories from the config file and store
3000 // into a list 3000 // into a list
3001 QFile f (cfgFile); 3001 QFile f (cfgFile);
3002 QStringList list; 3002 QStringList list;
3003 if ( f.open(IO_ReadOnly) ) { // file opened successfully 3003 if ( f.open(IO_ReadOnly) ) { // file opened successfully
3004 QTextStream t( &f ); // use a text stream 3004 QTextStream t( &f ); // use a text stream
3005 QString s; 3005 QString s;
3006 int n = 1; 3006 int n = 1;
3007 while ( !t.eof() ) { // until end of file... 3007 while ( !t.eof() ) { // until end of file...
3008 s = t.readLine(); // line of text excluding '\n' 3008 s = t.readLine(); // line of text excluding '\n'
3009 list.append(s); 3009 list.append(s);
3010 } 3010 }
3011 f.close(); 3011 f.close();
3012 } 3012 }
3013#endif 3013#endif
3014#else 3014#else
3015 // read all categories from the config file and store 3015 // read all categories from the config file and store
3016 // into a list 3016 // into a list
3017 QFile f (cfgFile); 3017 QFile f (cfgFile);
3018 QStringList list; 3018 QStringList list;
3019 if ( f.open(IO_ReadOnly) ) { // file opened successfully 3019 if ( f.open(IO_ReadOnly) ) { // file opened successfully
3020 QTextStream t( &f ); // use a text stream 3020 QTextStream t( &f ); // use a text stream
3021 QString s; 3021 QString s;
3022 while ( !t.eof() ) { // until end of file... 3022 while ( !t.eof() ) { // until end of file...
3023 s = t.readLine(); // line of text excluding '\n' 3023 s = t.readLine(); // line of text excluding '\n'
3024 list.append(s); 3024 list.append(s);
3025 } 3025 }
3026 f.close(); 3026 f.close();
3027 } 3027 }
3028#endif 3028#endif
3029 QStringList::Iterator it = list.begin(); 3029 QStringList::Iterator it = list.begin();
3030 QString categ; 3030 QString categ;
3031 dialog->CategoryField->clear(); // remove all items 3031 dialog->CategoryField->clear(); // remove all items
3032 int i=0; 3032 int i=0;
3033 bool foundCategory = false; 3033 bool foundCategory = false;
3034 while( it != list.end() ) 3034 while( it != list.end() )
3035 { 3035 {
3036 QString *cat = new QString (*it); 3036 QString *cat = new QString (*it);
3037 if (cat->contains("-field1", FALSE)) 3037 if (cat->contains("-field1", FALSE))
3038 { 3038 {
3039#ifdef DESKTOP 3039#ifdef DESKTOP
3040#ifndef WIN32 3040#ifndef WIN32
3041 categ = cat->section ("-field1", 0, 0); 3041 categ = cat->section ("-field1", 0, 0);
3042#else 3042#else
3043 int pos = cat->find ("-field1"); 3043 int pos = cat->find ("-field1");
3044 categ = cat->left (pos); 3044 categ = cat->left (pos);
3045#endif 3045#endif
3046#else 3046#else
3047 int pos = cat->find ("-field1"); 3047 int pos = cat->find ("-field1");
3048 cat->truncate(pos); 3048 cat->truncate(pos);
3049 categ = *cat; 3049 categ = *cat;
3050#endif 3050#endif
3051 if (!categ.isEmpty()) 3051 if (!categ.isEmpty())
3052 { 3052 {
3053 dialog->CategoryField->insertItem (categ, i); 3053 dialog->CategoryField->insertItem (categ, i);
3054 if (category.compare(categ) == 0) 3054 if (category.compare(categ) == 0)
3055 { 3055 {
3056 dialog->CategoryField->setCurrentItem(i); 3056 dialog->CategoryField->setCurrentItem(i);
3057 foundCategory = true; 3057 foundCategory = true;
3058 } 3058 }
3059 i++; 3059 i++;
3060 } 3060 }
3061 } 3061 }
3062 ++it; 3062 ++it;
3063 } 3063 }
3064 if (!foundCategory) 3064 if (!foundCategory)
3065 { 3065 {
3066 dialog->CategoryField->insertItem (category, i); 3066 dialog->CategoryField->insertItem (category, i);
3067 dialog->CategoryField->setCurrentItem(i); 3067 dialog->CategoryField->setCurrentItem(i);
3068 } 3068 }
3069 3069
3070 QString icon; 3070 QString icon;
3071 Category *cat= categories.find (selectedItem->text(0)); 3071 Category *cat= categories.find (selectedItem->text(0));
3072 if (cat) 3072 if (cat)
3073 { 3073 {
3074 icon = cat->getIconName(); 3074 icon = cat->getIconName();
3075 } 3075 }
3076 3076
3077 if (initIcons) 3077 if (initIcons)
3078 { 3078 {
3079 3079
3080 Wait waitDialog(this, tr("Wait dialog")); 3080 Wait waitDialog(this, tr("Wait dialog"));
3081 waitDialog.waitLabel->setText(tr("Gathering icons...")); 3081 waitDialog.waitLabel->setText(tr("Gathering icons..."));
3082 waitDialog.show(); 3082 waitDialog.show();
3083 qApp->processEvents(); 3083 qApp->processEvents();
3084 3084
3085#ifdef DESKTOP 3085#ifdef DESKTOP
3086 QDir d(iconPath); 3086 QDir d(iconPath);
3087#else 3087#else
3088 QDir d(QPEApplication::qpeDir() + "/pics/"); 3088 QDir d(QPEApplication::qpeDir() + "/pics/");
3089#endif 3089#endif
3090 d.setFilter( QDir::Files); 3090 d.setFilter( QDir::Files);
3091 3091
3092 const QFileInfoList *list = d.entryInfoList(); 3092 const QFileInfoList *list = d.entryInfoList();
3093 int i=0; 3093 int i=0;
3094 QFileInfoListIterator it( *list ); // create list iterator 3094 QFileInfoListIterator it( *list ); // create list iterator
3095 QFileInfo *fi; // pointer for traversing 3095 QFileInfo *fi; // pointer for traversing
3096 if (icon.isEmpty() || icon.isNull()) 3096 if (icon.isEmpty() || icon.isNull())
3097 { 3097 {
3098 dialog->IconField->setCurrentItem(0); 3098 dialog->IconField->setCurrentItem(0);
3099 } 3099 }
3100 3100
3101 dialog->IconField->insertItem("predefined"); 3101 dialog->IconField->insertItem("predefined");
3102 while ( (fi=it.current()) ) { // for each file... 3102 while ( (fi=it.current()) ) { // for each file...
3103 QString fileName = fi->fileName(); 3103 QString fileName = fi->fileName();
3104 if(fileName.right(4) == ".png") 3104 if(fileName.right(4) == ".png")
3105 { 3105 {
3106 fileName = fileName.mid(0,fileName.length()-4); 3106 fileName = fileName.mid(0,fileName.length()-4);
3107#ifdef DESKTOP 3107#ifdef DESKTOP
3108 QPixmap imageOfFile; 3108 QPixmap imageOfFile;
3109 imageOfFile.load(iconPath + fi->fileName()); 3109 imageOfFile.load(iconPath + fi->fileName());
3110#else 3110#else
3111 QPixmap imageOfFile(Resource::loadPixmap(fileName)); 3111 QPixmap imageOfFile(Resource::loadPixmap(fileName));
3112#endif 3112#endif
3113 QImage foo = imageOfFile.convertToImage(); 3113 QImage foo = imageOfFile.convertToImage();
3114 foo = foo.smoothScale(16,16); 3114 foo = foo.smoothScale(16,16);
3115 imageOfFile.convertFromImage(foo); 3115 imageOfFile.convertFromImage(foo);
3116 dialog->IconField->insertItem(imageOfFile,fileName); 3116 dialog->IconField->insertItem(imageOfFile,fileName);
3117 if(fileName+".png"==icon) 3117 if(fileName+".png"==icon)
3118 dialog->IconField->setCurrentItem(i+1); 3118 dialog->IconField->setCurrentItem(i+1);
3119 ++i; 3119 ++i;
3120 } 3120 }
3121 ++it; 3121 ++it;
3122 } 3122 }
3123 waitDialog.hide(); 3123 waitDialog.hide();
3124 } 3124 }
3125 else 3125 else
3126 { 3126 {
3127#ifdef DESKTOP 3127#ifdef DESKTOP
3128 // QDir d(QDir::homeDirPath() + "/pics/"); 3128 // QDir d(QDir::homeDirPath() + "/pics/");
3129 QDir d(iconPath); 3129 QDir d(iconPath);
3130#else 3130#else
3131 QDir d(QPEApplication::qpeDir() + "/pics/"); 3131 QDir d(QPEApplication::qpeDir() + "/pics/");
3132#endif 3132#endif
3133 d.setFilter( QDir::Files); 3133 d.setFilter( QDir::Files);
3134 3134
3135 const QFileInfoList *list = d.entryInfoList(); 3135 const QFileInfoList *list = d.entryInfoList();
3136 int i=0; 3136 int i=0;
3137 QFileInfoListIterator it( *list ); // create list iterator 3137 QFileInfoListIterator it( *list ); // create list iterator
3138 QFileInfo *fi; // pointer for traversing 3138 QFileInfo *fi; // pointer for traversing
3139 if (icon.isEmpty() || icon.isNull()) 3139 if (icon.isEmpty() || icon.isNull())
3140 { 3140 {
3141 dialog->IconField->setCurrentItem(0); 3141 dialog->IconField->setCurrentItem(0);
3142 } 3142 }
3143 else 3143 else
3144 { 3144 {
3145 3145
3146 while ( (fi=it.current()) ) 3146 while ( (fi=it.current()) )
3147 { // for each file... 3147 { // for each file...
3148 QString fileName = fi->fileName(); 3148 QString fileName = fi->fileName();
3149 if(fileName.right(4) == ".png") 3149 if(fileName.right(4) == ".png")
3150 { 3150 {
3151 fileName = fileName.mid(0,fileName.length()-4); 3151 fileName = fileName.mid(0,fileName.length()-4);
3152 3152
3153 3153
3154 if(fileName+".png"==icon) 3154 if(fileName+".png"==icon)
3155 { 3155 {
3156 dialog->IconField->setCurrentItem(i+1); 3156 dialog->IconField->setCurrentItem(i+1);
3157 break; 3157 break;
3158 } 3158 }
3159 ++i; 3159 ++i;
3160 } 3160 }
3161 ++it; 3161 ++it;
3162 } 3162 }
3163 } 3163 }
3164 } 3164 }
3165 3165
3166 // dialog->show(); 3166 // dialog->show();
3167#ifndef DESKTOP 3167#ifndef DESKTOP
3168 // dialog->move (20, 100); 3168 // dialog->move (20, 100);
3169#endif 3169#endif
3170 DialogCode result = (DialogCode) dialog->exec(); 3170 DialogCode result = (DialogCode) dialog->exec();
3171#ifdef DESKTOP 3171#ifdef DESKTOP
3172 result = Accepted; 3172 result = Accepted;
3173#endif 3173#endif
3174 3174
3175 QString fullIconPath; 3175 QString fullIconPath;
3176 QPixmap *pix; 3176 QPixmap *pix;
3177 if (result == Accepted) 3177 if (result == Accepted)
3178 { 3178 {
3179 modified = true; 3179 modified = true;
3180 if (category != dialog->CategoryField->currentText()) 3180 if (category != dialog->CategoryField->currentText())
3181 { 3181 {
3182 categories.remove (category); 3182 categories.remove (category);
3183// #ifndef WIN32 3183// #ifndef WIN32
3184 conf->removeEntry(category); 3184 conf->removeEntry(category);
3185// #endif 3185// #endif
3186 saveConf(); 3186 saveConf();
3187 } 3187 }
3188 3188
3189 category = dialog->CategoryField->currentText(); 3189 category = dialog->CategoryField->currentText();
3190 icon = dialog->IconField->currentText()+".png"; 3190 icon = dialog->IconField->currentText()+".png";
3191 3191
3192 if (cat) 3192 if (cat)
3193 { 3193 {
3194 qWarning("Category found"); 3194 qWarning("Category found");
3195 3195
3196 // if (!icon.isEmpty() && !icon.isNull()) 3196 // if (!icon.isEmpty() && !icon.isNull())
3197 if (icon != "predefined.png") 3197 if (icon != "predefined.png")
3198 { 3198 {
3199 // build the full path 3199 // build the full path
3200 fullIconPath = iconPath + icon; 3200 fullIconPath = iconPath + icon;
3201 pix = new QPixmap (fullIconPath); 3201 pix = new QPixmap (fullIconPath);
3202 if (pix) 3202 if (pix)
3203 { 3203 {
3204 // save the full pixmap name into the config file 3204 // save the full pixmap name into the config file
3205// #ifndef WIN32 3205// #ifndef WIN32
3206 conf->writeEntry(APP_KEY+category, icon); 3206 conf->writeEntry(APP_KEY+category, icon);
3207// #endif 3207// #endif
3208 saveConf(); 3208 saveConf();
3209 QImage img = pix->convertToImage(); 3209 QImage img = pix->convertToImage();
3210 pix->convertFromImage(img.smoothScale(14,14)); 3210 pix->convertFromImage(img.smoothScale(14,14));
3211 cat->setIconName (icon); 3211 cat->setIconName (icon);
3212 cat->setIcon (*pix); 3212 cat->setIcon (*pix);
3213 } 3213 }
3214 } 3214 }
3215 else 3215 else
3216 { 3216 {
3217// #ifndef WIN32 3217// #ifndef WIN32
3218 conf->removeEntry (category); 3218 conf->removeEntry (category);
3219// #endif 3219// #endif
3220 saveConf(); 3220 saveConf();
3221 cat->setIcon (*getPredefinedIcon(category)); 3221 cat->setIcon (*getPredefinedIcon(category));
3222 } 3222 }
3223 3223
3224 // change the category name of the selected category 3224 // change the category name of the selected category
3225 QListViewItem *catItem = cat->getListItem(); 3225 QListViewItem *catItem = cat->getListItem();
3226 if (catItem) 3226 if (catItem)
3227 { 3227 {
3228 qWarning (category); 3228 qWarning (category);
3229 catItem->setText( 0, tr( category ) ); 3229 catItem->setText( 0, tr( category ) );
3230 cat->setCategoryName (tr(category)); 3230 cat->setCategoryName (tr(category));
3231 3231
3232 cat->initListItem(); 3232 cat->initListItem();
3233 categories.insert (category, cat); 3233 categories.insert (category, cat);
3234 } 3234 }
3235 } 3235 }
3236 saveCategoryDialogFields(dialog); 3236 saveCategoryDialogFields(dialog);
3237 } 3237 }
3238 else 3238 else
3239 { 3239 {
3240 // delete dialog; 3240 // delete dialog;
3241 dialog->hide(); 3241 dialog->hide();
3242 return; 3242 return;
3243 } 3243 }
3244 3244
3245 } 3245 }
3246} 3246}
3247 3247
3248void ZSafe::cutItem() 3248void ZSafe::cutItem()
3249{ 3249{
3250 if (!selectedItem) 3250 if (!selectedItem)
3251 return; 3251 return;
3252 if (!isCategory(selectedItem)) 3252 if (!isCategory(selectedItem))
3253 { 3253 {
3254 IsCut = true; 3254 IsCut = true;
3255 copiedItem = selectedItem; 3255 copiedItem = selectedItem;
3256 } 3256 }
3257} 3257}
3258 3258
3259void ZSafe::copyItem() 3259void ZSafe::copyItem()
3260{ 3260{
3261 if (!selectedItem) 3261 if (!selectedItem)
3262 return; 3262 return;
3263 if (!isCategory(selectedItem)) 3263 if (!isCategory(selectedItem))
3264 { 3264 {
3265 IsCopy = true; 3265 IsCopy = true;
3266 copiedItem = selectedItem; 3266 copiedItem = selectedItem;
3267 } 3267 }
3268} 3268}
3269 3269
3270// paste item into category 3270// paste item into category
3271void ZSafe::pasteItem() 3271void ZSafe::pasteItem()
3272{ 3272{
3273 if (!selectedItem) 3273 if (!selectedItem)
3274 return; 3274 return;
3275 if (isCategory(selectedItem)) 3275 if (isCategory(selectedItem))
3276 { 3276 {
3277 modified = true; 3277 modified = true;
3278 if (IsCut) 3278 if (IsCut)
3279 { 3279 {
3280 if (copiedItem) 3280 if (copiedItem)
3281 { 3281 {
3282 // add the new item 3282 // add the new item
3283 QListViewItem *i = new ShadedListItem (0, selectedItem); 3283 QListViewItem *i = new ShadedListItem (0, selectedItem);
3284 // i->setOpen (TRUE); 3284 // i->setOpen (TRUE);
3285 i->setText (0, copiedItem->text(0)); 3285 i->setText (0, copiedItem->text(0));
3286 i->setText (1, copiedItem->text(1)); 3286 i->setText (1, copiedItem->text(1));
3287 i->setText (2, copiedItem->text(2)); 3287 i->setText (2, copiedItem->text(2));
3288 i->setText (3, copiedItem->text(3)); 3288 i->setText (3, copiedItem->text(3));
3289 i->setText (4, copiedItem->text(4)); 3289 i->setText (4, copiedItem->text(4));
3290 i->setText (5, copiedItem->text(5)); 3290 i->setText (5, copiedItem->text(5));
3291 selectedItem->setOpen( TRUE ); 3291 selectedItem->setOpen( TRUE );
3292 3292
3293 // remove the cutted item 3293 // remove the cutted item
3294 copiedItem->parent()->takeItem(copiedItem); 3294 copiedItem->parent()->takeItem(copiedItem);
3295 selectedItem = NULL; 3295 selectedItem = NULL;
3296 } 3296 }
3297 } 3297 }
3298 else if (IsCopy) 3298 else if (IsCopy)
3299 { 3299 {
3300 if (copiedItem) 3300 if (copiedItem)
3301 { 3301 {
3302 // add the new item 3302 // add the new item
3303 QListViewItem *i = new ShadedListItem (0, selectedItem); 3303 QListViewItem *i = new ShadedListItem (0, selectedItem);
3304 // i->setOpen (TRUE); 3304 // i->setOpen (TRUE);
3305 i->setText (0, copiedItem->text(0)); 3305 i->setText (0, copiedItem->text(0));
3306 i->setText (1, copiedItem->text(1)); 3306 i->setText (1, copiedItem->text(1));
3307 i->setText (2, copiedItem->text(2)); 3307 i->setText (2, copiedItem->text(2));
3308 i->setText (3, copiedItem->text(3)); 3308 i->setText (3, copiedItem->text(3));
3309 i->setText (4, copiedItem->text(4)); 3309 i->setText (4, copiedItem->text(4));
3310 i->setText (5, copiedItem->text(5)); 3310 i->setText (5, copiedItem->text(5));
3311 selectedItem->setOpen( TRUE ); 3311 selectedItem->setOpen( TRUE );
3312 } 3312 }
3313 } 3313 }
3314 } 3314 }
3315 IsCut = false; 3315 IsCut = false;
3316 IsCopy = false; 3316 IsCopy = false;
3317} 3317}
3318 3318
3319void ZSafe::newDocument() 3319void ZSafe::newDocument()
3320{ 3320{
3321 3321
3322 // open the file dialog 3322 // open the file dialog
3323#ifndef DESKTOP 3323#ifndef DESKTOP
3324#ifndef NO_OPIE 3324#ifndef NO_OPIE
3325 QMap<QString, QStringList> mimeTypes; 3325 QMap<QString, QStringList> mimeTypes;
3326 mimeTypes.insert(tr("All"), QStringList() ); 3326 mimeTypes.insert(tr("All"), QStringList() );
3327 mimeTypes.insert(tr("ZSafe"), "zsafe/*" ); 3327 mimeTypes.insert(tr("ZSafe"), "zsafe/*" );
3328 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, 3328 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL,
3329 QDir::homeDirPath() + "/Documents/application/zsafe", 3329 QDir::homeDirPath() + "/Documents/application/zsafe",
3330 QString::null, 3330 QString::null,
3331 mimeTypes, 3331 mimeTypes,
3332 this, 3332 this,
3333 tr ("Create new ZSafe document")); 3333 tr ("Create new ZSafe document"));
3334#else 3334#else
3335 QString newFile = ScQtFileEdit::getSaveAsFileName(this, 3335 QString newFile = ScQtFileEdit::getSaveAsFileName(this,
3336 tr ("Create new ZSafe document"), 3336 tr ("Create new ZSafe document"),
3337 QDir::homeDirPath() + "/Documents/application/zsafe", 3337 QDir::homeDirPath() + "/Documents/application/zsafe",
3338 "*.zsf"); 3338 "*.zsf");
3339#endif 3339#endif
3340#else 3340#else
3341 QString newFile = QFileDialog::getSaveFileName( 3341 QString newFile = QFileDialog::getSaveFileName(
3342 QDir::homeDirPath() + "/Documents/application/zsafe", 3342 QDir::homeDirPath() + "/Documents/application/zsafe",
3343 "ZSafe (*.zsf)", 3343 "ZSafe (*.zsf)",
3344 this, 3344 this,
3345 "ZSafe File Dialog" 3345 "ZSafe File Dialog"
3346 "Choose a ZSafe file" ); 3346 "Choose a ZSafe file" );
3347#endif 3347#endif
3348 3348
3349 // open the new document 3349 // open the new document
3350 if (newFile && newFile.length() > 0 ) 3350 if (newFile && newFile.length() > 0 )
3351 { 3351 {
3352 // save the previous opened document 3352 // save the previous opened document
3353 if (!filename.isEmpty()) 3353 if (!filename.isEmpty())
3354 saveDocument(filename, FALSE); 3354 saveDocument(filename, FALSE);
3355 3355
3356 modified = true; 3356 modified = true;
3357 3357
3358 // clear the password list 3358 // clear the password list
3359 QListViewItem *i; 3359 QListViewItem *i;
3360 QListViewItem *c = NULL; 3360 QListViewItem *c = NULL;
3361 // step through all categories 3361 // step through all categories
3362 for (i = ListView->firstChild(); 3362 for (i = ListView->firstChild();
3363 i != NULL; 3363 i != NULL;
3364 i = i->nextSibling()) 3364 i = i->nextSibling())
3365 { 3365 {
3366 if (c) delete c; // delete the previous category 3366 if (c) delete c; // delete the previous category
3367 3367
3368 c = i; 3368 c = i;
3369 // step through all subitems 3369 // step through all subitems
3370 QListViewItem *si; 3370 QListViewItem *si;
3371 for (si = i->firstChild(); 3371 for (si = i->firstChild();
3372 si != NULL; ) 3372 si != NULL; )
3373 { 3373 {
3374 QListViewItem *_si = si; 3374 QListViewItem *_si = si;
3375 si = si->nextSibling(); 3375 si = si->nextSibling();
3376 i->takeItem(_si); // remove from view list 3376 i->takeItem(_si); // remove from view list
3377 if (_si) delete _si; 3377 if (_si) delete _si;
3378 } 3378 }
3379 } 3379 }
3380 if (c) delete c; // delete the previous category 3380 if (c) delete c; // delete the previous category
3381 categories.clear(); 3381 categories.clear();
3382 3382
3383 // m_password = ""; 3383 // m_password = "";
3384 selectedItem = NULL; 3384 selectedItem = NULL;
3385 3385
3386 filename = newFile; 3386 filename = newFile;
3387 3387
3388 // save the current filename to the config file 3388 // save the current filename to the config file
3389 conf->writeEntry(APP_KEY+"document", filename); 3389 conf->writeEntry(APP_KEY+"document", filename);
3390 saveConf(); 3390 saveConf();
3391 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3391 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3392#ifdef WIN32 3392#ifdef WIN32
3393 this->setCaption("Qt ZSafe: " + ti); 3393 this->setCaption("Qt ZSafe: " + ti);
3394#else 3394#else
3395 this->setCaption("ZSafe: " + ti); 3395 this->setCaption("ZSafe: " + ti);
3396#endif 3396#endif
3397 3397
3398 // openDocument(filename); 3398 // openDocument(filename);
3399 3399
3400 QMessageBox::information( this, tr("ZSafe"), 3400 QMessageBox::information( this, tr("ZSafe"),
3401 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0); 3401 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0);
3402 3402
3403 saveDocumentWithPwd(); 3403 saveDocumentWithPwd();
3404 } 3404 }
3405} 3405}
3406 3406
3407void ZSafe::loadDocument() 3407void ZSafe::loadDocument()
3408{ 3408{
3409 3409
3410 // open the file dialog 3410 // open the file dialog
3411#ifndef DESKTOP 3411#ifndef DESKTOP
3412#ifndef NO_OPIE 3412#ifndef NO_OPIE
3413 QMap<QString, QStringList> mimeTypes; 3413 QMap<QString, QStringList> mimeTypes;
3414 mimeTypes.insert(tr("All"), QStringList() ); 3414 mimeTypes.insert(tr("All"), QStringList() );
3415 mimeTypes.insert(tr("ZSafe"), "zsafe/*" ); 3415 mimeTypes.insert(tr("ZSafe"), "zsafe/*" );
3416 QString newFile = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, 3416 QString newFile = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL,
3417 QDir::homeDirPath() + "/Documents/application/zsafe", 3417 QDir::homeDirPath() + "/Documents/application/zsafe",
3418 QString::null, 3418 QString::null,
3419 mimeTypes, 3419 mimeTypes,
3420 this, 3420 this,
3421 tr ("Open ZSafe document")); 3421 tr ("Open ZSafe document"));
3422#else 3422#else
3423 QString newFile = ScQtFileEdit::getOpenFileName(this, 3423 QString newFile = ScQtFileEdit::getOpenFileName(this,
3424 tr ("Open ZSafe document"), 3424 tr ("Open ZSafe document"),
3425 QDir::homeDirPath() + "/Documents/application/zsafe", 3425 QDir::homeDirPath() + "/Documents/application/zsafe",
3426 "*.zsf"); 3426 "*.zsf");
3427#endif 3427#endif
3428#else 3428#else
3429 QString newFile = QFileDialog::getOpenFileName( 3429 QString newFile = QFileDialog::getOpenFileName(
3430 QDir::homeDirPath() + "/Documents/application/zsafe", 3430 QDir::homeDirPath() + "/Documents/application/zsafe",
3431 "ZSafe (*.zsf)", 3431 "ZSafe (*.zsf)",
3432 this, 3432 this,
3433 "ZSafe File Dialog" 3433 "ZSafe File Dialog"
3434 "Choose a ZSafe file" ); 3434 "Choose a ZSafe file" );
3435#endif 3435#endif
3436 3436
3437 // open the new document 3437 // open the new document
3438 if (newFile && newFile.length() > 0 ) 3438 if (newFile && newFile.length() > 0 )
3439 { 3439 {
3440 // save the previous opened document 3440 // save the previous opened document
3441 if (!filename.isEmpty()) 3441 if (!filename.isEmpty())
3442 saveDocument(filename, FALSE); 3442 saveDocument(filename, FALSE);
3443 3443
3444 // clear the password list 3444 // clear the password list
3445 QListViewItem *i; 3445 QListViewItem *i;
3446 QListViewItem *c = NULL; 3446 QListViewItem *c = NULL;
3447 // step through all categories 3447 // step through all categories
3448 for (i = ListView->firstChild(); 3448 for (i = ListView->firstChild();
3449 i != NULL; 3449 i != NULL;
3450 i = i->nextSibling()) 3450 i = i->nextSibling())
3451 { 3451 {
3452 if (c) delete c; // delete the previous category 3452 if (c) delete c; // delete the previous category
3453 3453
3454 c = i; 3454 c = i;
3455 // step through all subitems 3455 // step through all subitems
3456 QListViewItem *si; 3456 QListViewItem *si;
3457 for (si = i->firstChild(); 3457 for (si = i->firstChild();
3458 si != NULL; ) 3458 si != NULL; )
3459 { 3459 {
3460 QListViewItem *_si = si; 3460 QListViewItem *_si = si;
3461 si = si->nextSibling(); 3461 si = si->nextSibling();
3462 i->takeItem(_si); // remove from view list 3462 i->takeItem(_si); // remove from view list
3463 if (_si) delete _si; 3463 if (_si) delete _si;
3464 } 3464 }
3465 } 3465 }
3466 if (c) delete c; // delete the previous category 3466 if (c) delete c; // delete the previous category
3467 categories.clear(); 3467 categories.clear();
3468 m_password = ""; 3468 m_password = "";
3469 selectedItem = NULL; 3469 selectedItem = NULL;
3470 filename = newFile; 3470 filename = newFile;
3471 3471
3472 // save the current filename to the config file 3472 // save the current filename to the config file
3473 conf->writeEntry(APP_KEY+"document", filename); 3473 conf->writeEntry(APP_KEY+"document", filename);
3474 saveConf(); 3474 saveConf();
3475 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3475 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3476#ifdef WIN32 3476#ifdef WIN32
3477 this->setCaption("Qt ZSafe: " + ti); 3477 this->setCaption("Qt ZSafe: " + ti);
3478#else 3478#else
3479 this->setCaption("ZSafe: " + ti); 3479 this->setCaption("ZSafe: " + ti);
3480#endif 3480#endif
3481 3481
3482 openDocument(filename); 3482 openDocument(filename);
3483 } 3483 }
3484} 3484}
3485 3485
3486void ZSafe::saveDocumentAs() 3486void ZSafe::saveDocumentAs()
3487{ 3487{
3488 3488
3489#ifndef DESKTOP 3489#ifndef DESKTOP
3490#ifndef NO_OPIE 3490#ifndef NO_OPIE
3491 QMap<QString, QStringList> mimeTypes; 3491 QMap<QString, QStringList> mimeTypes;
3492 mimeTypes.insert(tr("All"), QStringList() ); 3492 mimeTypes.insert(tr("All"), QStringList() );
3493 mimeTypes.insert(tr("ZSafe"), "zsafe/*" ); 3493 mimeTypes.insert(tr("ZSafe"), "zsafe/*" );
3494 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, 3494 QString newFile = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL,
3495 QDir::homeDirPath() + "/Documents/application/zsafe", 3495 QDir::homeDirPath() + "/Documents/application/zsafe",
3496 QString::null, 3496 QString::null,
3497 mimeTypes, 3497 mimeTypes,
3498 this, 3498 this,
3499 tr ("Save ZSafe document as..")); 3499 tr ("Save ZSafe document as.."));
3500#else 3500#else
3501 QString newFile = ScQtFileEdit::getSaveAsFileName(this, 3501 QString newFile = ScQtFileEdit::getSaveAsFileName(this,
3502 tr ("Save ZSafe document as.."), 3502 tr ("Save ZSafe document as.."),
3503 QDir::homeDirPath() + "/Documents/application/zsafe", 3503 QDir::homeDirPath() + "/Documents/application/zsafe",
3504 "*.zsf"); 3504 "*.zsf");
3505#endif 3505#endif
3506#else 3506#else
3507 // open the file dialog 3507 // open the file dialog
3508 QString newFile = QFileDialog::getSaveFileName( 3508 QString newFile = QFileDialog::getSaveFileName(
3509 QDir::homeDirPath() + "/Documents/application/zsafe", 3509 QDir::homeDirPath() + "/Documents/application/zsafe",
3510 "ZSafe (*.zsf)", 3510 "ZSafe (*.zsf)",
3511 this, 3511 this,
3512 "ZSafe File Dialog" 3512 "ZSafe File Dialog"
3513 "Choose a ZSafe file" ); 3513 "Choose a ZSafe file" );
3514#endif 3514#endif
3515 3515
3516 // open the new document 3516 // open the new document
3517 if (newFile && newFile.length() > 0 ) 3517 if (newFile && newFile.length() > 0 )
3518 { 3518 {
3519 // save the previous opened document 3519 // save the previous opened document
3520 if (!filename.isEmpty()) 3520 if (!filename.isEmpty())
3521 saveDocument(filename, FALSE); 3521 saveDocument(filename, FALSE);
3522 3522
3523 selectedItem = NULL; 3523 selectedItem = NULL;
3524 filename = newFile; 3524 filename = newFile;
3525 3525
3526 // save the current filename to the config file 3526 // save the current filename to the config file
3527 conf->writeEntry(APP_KEY+"document", filename); 3527 conf->writeEntry(APP_KEY+"document", filename);
3528 saveConf(); 3528 saveConf();
3529 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3529 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3530#ifdef WIN32 3530#ifdef WIN32
3531 this->setCaption("Qt ZSafe: " + ti); 3531 this->setCaption("Qt ZSafe: " + ti);
3532#else 3532#else
3533 this->setCaption("ZSafe: " + ti); 3533 this->setCaption("ZSafe: " + ti);
3534#endif 3534#endif
3535 3535
3536 QMessageBox::information( this, tr("ZSafe"), 3536 QMessageBox::information( this, tr("ZSafe"),
3537 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0); 3537 tr("Now you have to enter\na password twice for your\nnewly created document."), tr("&OK"), 0);
3538 3538
3539 saveDocumentWithPwd(); 3539 saveDocumentWithPwd();
3540 } 3540 }
3541} 3541}
3542 3542
3543void ZSafe::saveDocumentWithoutPwd() 3543void ZSafe::saveDocumentWithoutPwd()
3544{ 3544{
3545 saveDocument(filename, FALSE); 3545 saveDocument(filename, FALSE);
3546} 3546}
3547 3547
3548void ZSafe::saveDocumentWithPwd() 3548void ZSafe::saveDocumentWithPwd()
3549{ 3549{
3550 saveDocument(filename, TRUE); 3550 saveDocument(filename, TRUE);
3551} 3551}
3552 3552
3553void ZSafe::about() 3553void ZSafe::about()
3554{ 3554{
3555 QString info; 3555 QString info;
3556#ifdef JPATCH_HDE 3556#ifdef JPATCH_HDE
3557 info = "<html><body><div align=""center"">"; 3557 info = "<html><body><div align=""center"">";
3558 info += "<b>"; 3558 info += "<b>";
3559 info += tr("Zaurus Password Manager<br>"); 3559 info += tr("Zaurus Password Manager<br>");
3560 info += tr("ZSafe version 2.1.2-jv01b<br>"); 3560 info += tr("ZSafe version 2.1.2-jv01b<br>");
3561 info += "</b>"; 3561 info += "</b>";
3562 info += tr("by Carsten Schneider<br>"); 3562 info += tr("by Carsten Schneider<br>");
3563 info += "zcarsten@gmx.net<br>"; 3563 info += "zcarsten@gmx.net<br>";
3564 info += "http://z-soft.z-portal.info/zsafe"; 3564 info += "http://z-soft.z-portal.info/zsafe";
3565 info += "<br>"; 3565 info += "<br>";
3566 info += tr("Translations by Robert Ernst<br>"); 3566 info += tr("Translations by Robert Ernst<br>");
3567 info += "robert.ernst@linux-solutions.at<br>"; 3567 info += "robert.ernst@linux-solutions.at<br>";
3568 3568
3569 info += "<br><br>"; 3569 info += "<br><br>";
3570 info += QString::fromUtf8("æ~W¥æ~\\¬èª~^/VGA Zaurus対å¿~\\ã~C~Qã~C~Cã~C~Aä½~\\æ ~H~P<br>"); 3570 info += QString::fromUtf8("æ~W¥æ~\\¬èª~^/VGA Zaurus対å¿~\\ã~C~Qã~C~Cã~C~Aä½~\\æ ~H~P<br>");
3571 info += "HADECO R&D<br>"; 3571 info += "HADECO R&D<br>";
3572 info += "r&d@hadeco.co.jp<br>"; 3572 info += "r&d@hadeco.co.jp<br>";
3573 info += "http://www.hadeco.co.jp/r&d/<br>"; 3573 info += "http://www.hadeco.co.jp/r&d/<br>";
3574 info += "<br></div>"; 3574 info += "<br></div>";
3575 info += "</body></html>"; 3575 info += "</body></html>";
3576#else 3576#else
3577 info = "<html><body><div align=""center"">"; 3577 info = "<html><body><div align=""center"">";
3578 info += "<b>"; 3578 info += "<b>";
3579 info += tr("Zaurus Password Manager<br>"); 3579 info += tr("Zaurus Password Manager<br>");
3580 info += tr("ZSafe version 2.1.2<br>"); 3580 info += tr("ZSafe version 2.1.2<br>");
3581 info += "</b>"; 3581 info += "</b>";
3582 info += tr("by Carsten Schneider<br>"); 3582 info += tr("by Carsten Schneider<br>");
3583 info += "zcarsten@gmx.net<br>"; 3583 info += "zcarsten@gmx.net<br>";
3584 info += "http://z-soft.z-portal.info/zsafe"; 3584 info += "http://z-soft.z-portal.info/zsafe";
3585 info += "<br>"; 3585 info += "<br>";
3586 info += tr("Translations by Robert Ernst<br>"); 3586 info += tr("Translations by Robert Ernst<br>");
3587 info += "robert.ernst@linux-solutions.at<br>"; 3587 info += "robert.ernst@linux-solutions.at<br>";
3588 info += "<br></div>"; 3588 info += "<br></div>";
3589 info += "</body></html>"; 3589 info += "</body></html>";
3590#endif 3590#endif
3591 3591
3592 // QMessageBox::information( this, tr("ZSafe"), info, tr("&OK"), 0); 3592 // QMessageBox::information( this, tr("ZSafe"), info, tr("&OK"), 0);
3593 3593
3594 QMessageBox mb( this, tr("ZSafe")); 3594 QMessageBox mb( this, tr("ZSafe"));
3595 mb.setText (info); 3595 mb.setText (info);
3596 mb.setButtonText (QMessageBox::Ok, tr ("&OK")); 3596 mb.setButtonText (QMessageBox::Ok, tr ("&OK"));
3597 QPixmap zsafe_img((const char**) zsafe_xpm); 3597 QPixmap zsafe_img((const char**) zsafe_xpm);
3598 mb.setIconPixmap (zsafe_img); 3598 mb.setIconPixmap (zsafe_img);
3599 mb.exec(); 3599 mb.exec();
3600} 3600}
3601 3601
3602void ZSafe::setExpandFlag() 3602void ZSafe::setExpandFlag()
3603{ 3603{
3604 expandTree = !expandTree; 3604 expandTree = !expandTree;
3605 file->setItemChecked('o', expandTree); 3605 file->setItemChecked('o', expandTree);
3606#ifndef DESKTOP 3606#ifndef DESKTOP
3607 conf->setGroup ("zsafePrefs"); 3607 conf->setGroup ("zsafePrefs");
3608#endif 3608#endif
3609// #ifndef WIN32 3609// #ifndef WIN32
3610 conf->writeEntry (APP_KEY+"expandTree", expandTree); 3610 conf->writeEntry (APP_KEY+"expandTree", expandTree);
3611// #endif 3611// #endif
3612 saveConf(); 3612 saveConf();
3613 3613
3614} 3614}
3615 3615
3616void ZSafe::paintEvent( QPaintEvent * ) 3616void ZSafe::paintEvent( QPaintEvent * )
3617{ 3617{
3618 if (raiseFlag) 3618 if (raiseFlag)
3619 { 3619 {
3620 raiseFlag = false; 3620 raiseFlag = false;
3621 raiseTimer.start (1, true); 3621 raiseTimer.start (1, true);
3622 if (infoForm->isVisible()) 3622 if (infoForm->isVisible())
3623 infoForm->raise(); 3623 infoForm->raise();
3624 } 3624 }
3625} 3625}
3626 3626
3627void ZSafe::resizeEvent ( QResizeEvent * ) 3627void ZSafe::resizeEvent ( QResizeEvent * )
3628{ 3628{
3629 // qWarning ("resizeEvent"); 3629 // qWarning ("resizeEvent");
3630#ifndef DESKTOP 3630#ifndef DESKTOP
3631 DeskW = appl->desktop()->width(); 3631 DeskW = appl->desktop()->width();
3632 DeskH = appl->desktop()->height(); 3632 DeskH = appl->desktop()->height();
3633#else 3633#else
3634 DeskW = this->width(); 3634 DeskW = this->width();
3635 DeskH = this->height(); 3635 DeskH = this->height();
3636#endif 3636#endif
3637 3637
3638 if (New) 3638 if (New)
3639 New->setGeometry ( QRect( DeskW-84, 2, 20, 20 ) ); 3639 New->setGeometry ( QRect( DeskW-84, 2, 20, 20 ) );
3640 if (Edit) 3640 if (Edit)
3641 Edit->setGeometry ( QRect( DeskW-64, 2, 20, 20 ) ); 3641 Edit->setGeometry ( QRect( DeskW-64, 2, 20, 20 ) );
3642 if (Delete) 3642 if (Delete)
3643 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) ); 3643 Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) );
3644 if (Find) 3644 if (Find)
3645 Find->setGeometry ( QRect( DeskW-24, 2, 20, 20 ) ); 3645 Find->setGeometry ( QRect( DeskW-24, 2, 20, 20 ) );
3646} 3646}
3647 3647
3648void ZSafe::slotRaiseTimer() 3648void ZSafe::slotRaiseTimer()
3649{ 3649{
3650 if (infoForm->isVisible()) 3650 if (infoForm->isVisible())
3651 infoForm->raise(); 3651 infoForm->raise();
3652 raiseFlag = true; 3652 raiseFlag = true;
3653} 3653}
3654 3654
3655QPixmap * ZSafe::getPredefinedIcon(QString category) 3655QPixmap * ZSafe::getPredefinedIcon(QString category)
3656{ 3656{
3657 QPixmap *pm; 3657 QPixmap *pm;
3658 if (category == "Bank cards") 3658 if (category == "Bank cards")
3659 pm = new QPixmap((const char**)bank_cards_data); 3659 pm = new QPixmap((const char**)bank_cards_data);
3660 else if (category == "Passwords") 3660 else if (category == "Passwords")
3661 pm = new QPixmap((const char**)passwords_data); 3661 pm = new QPixmap((const char**)passwords_data);
3662 else if (category == "Software") 3662 else if (category == "Software")
3663 pm = new QPixmap((const char**)software_data); 3663 pm = new QPixmap((const char**)software_data);
3664 else if (category == "General") 3664 else if (category == "General")
3665 pm = new QPixmap((const char**)general_data); 3665 pm = new QPixmap((const char**)general_data);
3666 else 3666 else
3667 pm = new QPixmap((const char**)general_data); 3667 pm = new QPixmap((const char**)general_data);
3668 return pm; 3668 return pm;
3669} 3669}
3670 3670
3671void ZSafe::setDocument(const QString& fileref) 3671void ZSafe::setDocument(const QString& fileref)
3672{ 3672{
3673#ifndef DESKTOP 3673#ifndef DESKTOP
3674 // stop the timer to prevent loading of the default document 3674 // stop the timer to prevent loading of the default document
3675 docuTimer.stop(); 3675 docuTimer.stop();
3676 3676
3677 DocLnk link(fileref); 3677 DocLnk link(fileref);
3678 if ( link.isValid() ) 3678 if ( link.isValid() )
3679 { 3679 {
3680 // if (filename != link.file()) 3680 // if (filename != link.file())
3681 // saveDocument(filename, FALSE); 3681 // saveDocument(filename, FALSE);
3682 filename = link.file(); 3682 filename = link.file();
3683 } 3683 }
3684 else 3684 else
3685 { 3685 {
3686 // if (filename != fileref) 3686 // if (filename != fileref)
3687 // saveDocument(filename, FALSE); 3687 // saveDocument(filename, FALSE);
3688 filename = fileref; 3688 filename = fileref;
3689 } 3689 }
3690 // save the current filename to the config file 3690 // save the current filename to the config file
3691 conf->writeEntry(APP_KEY+"document", filename); 3691 conf->writeEntry(APP_KEY+"document", filename);
3692 saveConf(); 3692 saveConf();
3693 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); 3693 QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
3694#ifdef WIN32 3694#ifdef WIN32
3695 this->setCaption("Qt ZSafe: " + ti); 3695 this->setCaption("Qt ZSafe: " + ti);
3696#else 3696#else
3697 this->setCaption("ZSafe: " + ti); 3697 this->setCaption("ZSafe: " + ti);
3698#endif 3698#endif
3699 3699
3700 // clear the password list 3700 // clear the password list
3701 QListViewItem *i; 3701 QListViewItem *i;
3702 QListViewItem *c = NULL; 3702 QListViewItem *c = NULL;
3703 // step through all categories 3703 // step through all categories
3704 for (i = ListView->firstChild(); 3704 for (i = ListView->firstChild();
3705 i != NULL; 3705 i != NULL;
3706 i = i->nextSibling()) 3706 i = i->nextSibling())
3707 { 3707 {
3708 if (c) delete c; // delete the previous category 3708 if (c) delete c; // delete the previous category
3709 3709
3710 c = i; 3710 c = i;
3711 // step through all subitems 3711 // step through all subitems
3712 QListViewItem *si; 3712 QListViewItem *si;
3713 for (si = i->firstChild(); 3713 for (si = i->firstChild();
3714 si != NULL; ) 3714 si != NULL; )
3715 { 3715 {
3716 QListViewItem *_si = si; 3716 QListViewItem *_si = si;
3717 si = si->nextSibling(); 3717 si = si->nextSibling();
3718 i->takeItem(_si); // remove from view list 3718 i->takeItem(_si); // remove from view list
3719 if (_si) delete _si; 3719 if (_si) delete _si;
3720 } 3720 }
3721 } 3721 }
3722 if (c) delete c; // delete the previous category 3722 if (c) delete c; // delete the previous category
3723 categories.clear(); 3723 categories.clear();
3724 3724
3725 m_password = ""; 3725 m_password = "";
3726 selectedItem = NULL; 3726 selectedItem = NULL;
3727 3727
3728 openDocument(filename); 3728 openDocument(filename);
3729#endif 3729#endif
3730} 3730}
3731 3731
3732 3732
3733 3733
diff --git a/noncore/comm/keypebble/krfbcanvas.cpp b/noncore/comm/keypebble/krfbcanvas.cpp
index 75cba68..cd1fda0 100644
--- a/noncore/comm/keypebble/krfbcanvas.cpp
+++ b/noncore/comm/keypebble/krfbcanvas.cpp
@@ -1,200 +1,200 @@
1#include "krfbconnection.h" 1#include "krfbconnection.h"
2#include "krfbcanvas.h" 2#include "krfbcanvas.h"
3#include "krfbbuffer.h" 3#include "krfbbuffer.h"
4 4
5#include <qpe/qpeapplication.h> 5#include <qpe/qpeapplication.h>
6 6
7#include <qclipboard.h> 7#include <qclipboard.h>
8 8
9KRFBCanvas::KRFBCanvas( QWidget *parent, const char *name ) 9KRFBCanvas::KRFBCanvas( QWidget *parent, const char *name )
10 : QScrollView( parent, name ) 10 : QScrollView( parent, name )
11{ 11{
12 connection_ = new KRFBConnection(); 12 connection_ = new KRFBConnection();
13 connect( connection_, SIGNAL( loggedIn() ), 13 connect( connection_, SIGNAL( loggedIn() ),
14 this, SLOT( loggedIn() ) ); 14 this, SLOT( loggedIn() ) );
15 15
16 loggedIn_ = false; 16 loggedIn_ = false;
17 17
18 //QPEApplication::setStylusOperation(viewport(), QPEApplication::RightOnHold); 18 //QPEApplication::setStylusOperation(viewport(), QPEApplication::RightOnHold);
19 19
20 viewport()->setFocusPolicy( QWidget::StrongFocus ); 20 viewport()->setFocusPolicy( QWidget::StrongFocus );
21 viewport()->setFocus(); 21 viewport()->setFocus();
22 22
23 nextRightClick=0; 23 nextRightClick=0;
24 nextDoubleClick=0; 24 nextDoubleClick=0;
25} 25}
26 26
27KRFBCanvas::~KRFBCanvas() 27KRFBCanvas::~KRFBCanvas()
28{ 28{
29} 29}
30 30
31 31
32void KRFBCanvas::openConnection(KRFBServer server) 32void KRFBCanvas::openConnection(KRFBServer server)
33{ 33{
34 34
35 35
36 QCString host = server.hostname.latin1(); 36 QCString host = server.hostname.latin1();
37 password=server.password; 37 password=server.password;
38 connection_->connectTo( server); 38 connection_->connectTo( server);
39} 39}
40 40
41 41
42void KRFBCanvas::openURL( const QUrl &url ) 42void KRFBCanvas::openURL( const QUrl &url )
43{ 43{
44 if ( loggedIn_ ) { 44 if ( loggedIn_ ) {
45 qWarning( "openURL invoked when logged in\n" ); 45 qWarning( "openURL invoked when logged in\n" );
46 return; 46 return;
47 } 47 }
48 48
49 QCString host = url.host().latin1(); 49 QCString host = url.host().latin1();
50 int display = url.port(); 50 int display = url.port();
51 51
52// connection_->connectTo( host, display ); 52// connection_->connectTo( host, display );
53} 53}
54 54
55void KRFBCanvas::closeConnection() 55void KRFBCanvas::closeConnection()
56{ 56{
57 loggedIn_ = false; 57 loggedIn_ = false;
58 connection_->disconnect(); 58 connection_->disconnect();
59 59
60 viewport()->setMouseTracking( false ); 60 viewport()->setMouseTracking( false );
61 viewport()->setBackgroundMode( PaletteDark ); 61 viewport()->setBackgroundMode( PaletteDark );
62 setBackgroundMode( PaletteDark ); 62 setBackgroundMode( PaletteDark );
63 update(); 63 update();
64} 64}
65 65
66 66
67void KRFBCanvas::bell() 67void KRFBCanvas::bell()
68{ 68{
69 if ( connection_->options()->deIconify ) { 69 if ( connection_->options()->deIconify ) {
70 topLevelWidget()->raise(); 70 topLevelWidget()->raise();
71 topLevelWidget()->show(); 71 topLevelWidget()->show();
72 } 72 }
73} 73}
74 74
75void KRFBCanvas::loggedIn() 75void KRFBCanvas::loggedIn()
76{ 76{
77 qWarning( "Ok, we're logged in" ); 77 qWarning( "Ok, we're logged in" );
78 78
79 // 79 //
80 // Get ready for action 80 // Get ready for action
81 // 81 //
82 loggedIn_ = true; 82 loggedIn_ = true;
83 viewport()->setMouseTracking( true ); 83 viewport()->setMouseTracking( true );
84 viewport()->setBackgroundMode( NoBackground ); 84 viewport()->setBackgroundMode( NoBackground );
85 setBackgroundMode( NoBackground ); 85 setBackgroundMode( NoBackground );
86 86
87 // Start using the buffer 87 // Start using the buffer
88 connect( connection_->buffer(), SIGNAL( sizeChanged( int, int ) ), 88 connect( connection_->buffer(), SIGNAL( sizeChanged(int,int) ),
89 this, SLOT( resizeContents(int,int) ) ); 89 this, SLOT( resizeContents(int,int) ) );
90 connect( connection_->buffer(), SIGNAL( updated( int, int, int, int ) ), 90 connect( connection_->buffer(), SIGNAL( updated(int,int,int,int) ),
91 this, SLOT( viewportUpdate(int,int,int,int) ) ); 91 this, SLOT( viewportUpdate(int,int,int,int) ) );
92 connect( connection_->buffer(), SIGNAL( bell() ), 92 connect( connection_->buffer(), SIGNAL( bell() ),
93 this, SLOT( bell() ) ); 93 this, SLOT( bell() ) );
94 connect( qApp->clipboard(), SIGNAL( dataChanged() ), 94 connect( qApp->clipboard(), SIGNAL( dataChanged() ),
95 this, SLOT( clipboardChanged() ) ); 95 this, SLOT( clipboardChanged() ) );
96} 96}
97 97
98void KRFBCanvas::viewportPaintEvent( QPaintEvent *e ) 98void KRFBCanvas::viewportPaintEvent( QPaintEvent *e )
99{ 99{
100 QRect r = e->rect(); 100 QRect r = e->rect();
101 101
102 if ( loggedIn_ ) { 102 if ( loggedIn_ ) {
103 QPixmap p; 103 QPixmap p;
104 104
105 bitBlt( viewport(), r.x(), r.y(), 105 bitBlt( viewport(), r.x(), r.y(),
106 connection_->buffer()->pixmap(), 106 connection_->buffer()->pixmap(),
107 r.x() + contentsX(), r.y() + contentsY(), 107 r.x() + contentsX(), r.y() + contentsY(),
108 r.width(), r.height() ); 108 r.width(), r.height() );
109 } 109 }
110 else { 110 else {
111 QScrollView::viewportPaintEvent( e ); 111 QScrollView::viewportPaintEvent( e );
112 } 112 }
113} 113}
114 114
115void KRFBCanvas::viewportUpdate( int x, int y, int w, int h ) 115void KRFBCanvas::viewportUpdate( int x, int y, int w, int h )
116{ 116{
117 updateContents( x, y, w, h ); 117 updateContents( x, y, w, h );
118} 118}
119 119
120void KRFBCanvas::contentsMousePressEvent( QMouseEvent *e ) 120void KRFBCanvas::contentsMousePressEvent( QMouseEvent *e )
121{ 121{
122 122
123 if (nextDoubleClick) { 123 if (nextDoubleClick) {
124 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),LeftButton,LeftButton)); 124 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),LeftButton,LeftButton));
125 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0)); 125 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0));
126 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0)); 126 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),LeftButton,0));
127 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton)); 127 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton));
128 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0)); 128 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0));
129 } if (nextRightClick) { 129 } if (nextRightClick) {
130 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),RightButton,RightButton)); 130 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),RightButton,RightButton));
131 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),RightButton,0)); 131 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),RightButton,0));
132 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton)); 132 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonPress, e->pos(),NoButton,NoButton));
133 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0)); 133 connection_->buffer()->mouseEvent( &QMouseEvent(QEvent::MouseButtonRelease, e->pos(),NoButton,0));
134 } else if ( loggedIn_ ) 134 } else if ( loggedIn_ )
135 connection_->buffer()->mouseEvent( e ); 135 connection_->buffer()->mouseEvent( e );
136 136
137} 137}
138 138
139void KRFBCanvas::contentsMouseReleaseEvent( QMouseEvent *e ) 139void KRFBCanvas::contentsMouseReleaseEvent( QMouseEvent *e )
140{ 140{
141 if ( loggedIn_ && !nextRightClick && !nextDoubleClick) { 141 if ( loggedIn_ && !nextRightClick && !nextDoubleClick) {
142 connection_->buffer()->mouseEvent( e ); 142 connection_->buffer()->mouseEvent( e );
143 } 143 }
144 144
145 nextRightClick=0; 145 nextRightClick=0;
146 nextDoubleClick=0; 146 nextDoubleClick=0;
147} 147}
148 148
149void KRFBCanvas::contentsMouseMoveEvent( QMouseEvent *e ) 149void KRFBCanvas::contentsMouseMoveEvent( QMouseEvent *e )
150{ 150{
151 if ( loggedIn_ ) 151 if ( loggedIn_ )
152 connection_->buffer()->mouseEvent( e ); 152 connection_->buffer()->mouseEvent( e );
153} 153}
154 154
155void KRFBCanvas::keyPressEvent( QKeyEvent *e ) 155void KRFBCanvas::keyPressEvent( QKeyEvent *e )
156{ 156{
157 if ( loggedIn_ ) 157 if ( loggedIn_ )
158 connection_->buffer()->keyPressEvent( e ); 158 connection_->buffer()->keyPressEvent( e );
159} 159}
160 160
161void KRFBCanvas::keyReleaseEvent( QKeyEvent *e ) 161void KRFBCanvas::keyReleaseEvent( QKeyEvent *e )
162{ 162{
163 if ( loggedIn_ ) 163 if ( loggedIn_ )
164 connection_->buffer()->keyReleaseEvent( e ); 164 connection_->buffer()->keyReleaseEvent( e );
165} 165}
166 166
167void KRFBCanvas::refresh() 167void KRFBCanvas::refresh()
168{ 168{
169 if ( loggedIn_ ) 169 if ( loggedIn_ )
170 connection_->refresh(); 170 connection_->refresh();
171} 171}
172 172
173void KRFBCanvas::clipboardChanged() 173void KRFBCanvas::clipboardChanged()
174{ 174{
175 if ( loggedIn_ ) { 175 if ( loggedIn_ ) {
176 connection_->sendCutText( qApp->clipboard()->text() ); 176 connection_->sendCutText( qApp->clipboard()->text() );
177 } 177 }
178} 178}
179void KRFBCanvas::sendCtlAltDel( void) 179void KRFBCanvas::sendCtlAltDel( void)
180{ 180{
181 181
182 if ( loggedIn_ ) { 182 if ( loggedIn_ ) {
183 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Control, 0,0)); 183 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Control, 0,0));
184 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Alt, 0,0)); 184 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Alt, 0,0));
185 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Delete, 0,0)); 185 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyPress,Qt::Key_Delete, 0,0));
186 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Control, 0,0)); 186 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Control, 0,0));
187 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Alt, 0,0)); 187 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Alt, 0,0));
188 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Delete, 0,0)); 188 connection_->buffer()->keyPressEvent( &QKeyEvent(QEvent::KeyRelease,Qt::Key_Delete, 0,0));
189 } 189 }
190} 190}
191 191
192void KRFBCanvas::markDoubleClick( void) 192void KRFBCanvas::markDoubleClick( void)
193{ 193{
194 nextRightClick=1; 194 nextRightClick=1;
195} 195}
196 196
197void KRFBCanvas::markRightClick( void) 197void KRFBCanvas::markRightClick( void)
198{ 198{
199 nextRightClick=1; 199 nextRightClick=1;
200} 200}
diff --git a/noncore/comm/keypebble/krfbconnection.cpp b/noncore/comm/keypebble/krfbconnection.cpp
index e6c33c6..b447046 100644
--- a/noncore/comm/keypebble/krfbconnection.cpp
+++ b/noncore/comm/keypebble/krfbconnection.cpp
@@ -1,233 +1,233 @@
1#include <assert.h> 1#include <assert.h>
2#include <qsocket.h> 2#include <qsocket.h>
3#include <qtimer.h> 3#include <qtimer.h>
4#include <string.h> 4#include <string.h>
5 5
6#include "krfbconnection.h" 6#include "krfbconnection.h"
7#include "krfblogin.h" 7#include "krfblogin.h"
8#include "krfbdecoder.h" 8#include "krfbdecoder.h"
9#include "krfbbuffer.h" 9#include "krfbbuffer.h"
10 10
11KRFBConnection::KRFBConnection( QObject *parent ) 11KRFBConnection::KRFBConnection( QObject *parent )
12 : QObject( parent, "KRFBConnection" ) 12 : QObject( parent, "KRFBConnection" )
13{ 13{
14 portBase_ = 5900; 14 portBase_ = 5900;
15 currentState_ = Disconnected; 15 currentState_ = Disconnected;
16 sock = 0; 16 sock = 0;
17 minData_ = 0; 17 minData_ = 0;
18 options_ = new KRFBServer(); 18 options_ = new KRFBServer();
19 updater = 0; 19 updater = 0;
20 decoder_ = 0; 20 decoder_ = 0;
21 buffer_ = 0; 21 buffer_ = 0;
22} 22}
23 23
24KRFBConnection::~KRFBConnection() 24KRFBConnection::~KRFBConnection()
25{ 25{
26 if ( ( currentState_ != Disconnected ) && ( currentState_ != Disconnecting ) && sock ) { 26 if ( ( currentState_ != Disconnected ) && ( currentState_ != Disconnecting ) && sock ) {
27 disconnectDone(); 27 disconnectDone();
28 } 28 }
29 delete options_; 29 delete options_;
30} 30}
31 31
32void KRFBConnection::connectTo( KRFBServer server) 32void KRFBConnection::connectTo( KRFBServer server)
33{ 33{
34 if ( currentState_ != Disconnected ) 34 if ( currentState_ != Disconnected )
35 disconnect(); 35 disconnect();
36 36
37 (*options_)=server; 37 (*options_)=server;
38 38
39 sock = new QSocket( this, "rfbSocket" ); 39 sock = new QSocket( this, "rfbSocket" );
40 CHECK_PTR( sock ); 40 CHECK_PTR( sock );
41 41
42 // Connect to something to notice connection or error 42 // Connect to something to notice connection or error
43 connect( sock, SIGNAL( error( int ) ), SLOT( gotSocketError( int ) ) ); 43 connect( sock, SIGNAL( error(int) ), SLOT( gotSocketError(int) ) );
44 connect( sock, SIGNAL( connected() ), SLOT( gotSocketConnection() ) ); 44 connect( sock, SIGNAL( connected() ), SLOT( gotSocketConnection() ) );
45 45
46 qWarning( "Connecting..." ); 46 qWarning( "Connecting..." );
47 47
48 currentState_ = Connecting; 48 currentState_ = Connecting;
49 sock->connectToHost( options_->hostname.latin1(), portBase_ + options_->display ); 49 sock->connectToHost( options_->hostname.latin1(), portBase_ + options_->display );
50} 50}
51 51
52void KRFBConnection::disconnect() 52void KRFBConnection::disconnect()
53{ 53{
54 qWarning( "Disconnecting from server" ); 54 qWarning( "Disconnecting from server" );
55 55
56 if ( ( currentState_ != Disconnected ) 56 if ( ( currentState_ != Disconnected )
57 && ( currentState_ != Disconnecting ) 57 && ( currentState_ != Disconnecting )
58 && sock ) { 58 && sock ) {
59 currentState_ = Disconnecting; 59 currentState_ = Disconnecting;
60 60
61 connect( sock, SIGNAL( delayedCloseFinished() ), SLOT( disconnectDone() ) ); 61 connect( sock, SIGNAL( delayedCloseFinished() ), SLOT( disconnectDone() ) );
62 sock->close(); 62 sock->close();
63 63
64 if ( sock->state() != QSocket::Closing ) 64 if ( sock->state() != QSocket::Closing )
65 disconnectDone(); 65 disconnectDone();
66 } 66 }
67} 67}
68 68
69void KRFBConnection::disconnectDone() 69void KRFBConnection::disconnectDone()
70{ 70{
71 currentState_ = Disconnected; 71 currentState_ = Disconnected;
72 delete sock; 72 delete sock;
73 sock = 0; 73 sock = 0;
74 minData_ = 0; 74 minData_ = 0;
75 delete updater; 75 delete updater;
76 delete decoder_; 76 delete decoder_;
77 delete buffer_; 77 delete buffer_;
78 emit disconnected(); 78 emit disconnected();
79} 79}
80 80
81void KRFBConnection::gotSocketConnection() 81void KRFBConnection::gotSocketConnection()
82{ 82{
83 currentState_ = LoggingIn; 83 currentState_ = LoggingIn;
84 84
85 qWarning( "Connected, logging in..." ); 85 qWarning( "Connected, logging in..." );
86 86
87 static QString statusMsg = tr( "Connected" ); 87 static QString statusMsg = tr( "Connected" );
88 emit statusChanged( statusMsg ); 88 emit statusChanged( statusMsg );
89 89
90 // Do some login stuff 90 // Do some login stuff
91 login = new KRFBLogin( this ); 91 login = new KRFBLogin( this );
92} 92}
93 93
94void KRFBConnection::gotRFBConnection() 94void KRFBConnection::gotRFBConnection()
95{ 95{
96 qWarning( "Logged into server" ); 96 qWarning( "Logged into server" );
97 97
98 currentState_ = Connected; 98 currentState_ = Connected;
99 emit connected(); 99 emit connected();
100 100
101 // Create the decoder and start doing stuff 101 // Create the decoder and start doing stuff
102 decoder_ = new KRFBDecoder( this ); 102 decoder_ = new KRFBDecoder( this );
103 CHECK_PTR( decoder_ ); 103 CHECK_PTR( decoder_ );
104 104
105 buffer_ = new KRFBBuffer( decoder_, this, "RFB Buffer" ); 105 buffer_ = new KRFBBuffer( decoder_, this, "RFB Buffer" );
106 CHECK_PTR( buffer_ ); 106 CHECK_PTR( buffer_ );
107 decoder_->setBuffer( buffer_ ); 107 decoder_->setBuffer( buffer_ );
108 108
109 connect( decoder_, SIGNAL( status( const QString & ) ), 109 connect( decoder_, SIGNAL( status(const QString&) ),
110 this, SIGNAL( statusChanged( const QString & ) ) ); 110 this, SIGNAL( statusChanged(const QString&) ) );
111 emit loggedIn(); 111 emit loggedIn();
112 112
113 decoder_->start(); 113 decoder_->start();
114 114
115 updater = new QTimer; 115 updater = new QTimer;
116 connect( updater, SIGNAL( timeout() ), SLOT( updateTimer() ) ); 116 connect( updater, SIGNAL( timeout() ), SLOT( updateTimer() ) );
117 updater->start( options_->updateRate ); 117 updater->start( options_->updateRate );
118} 118}
119 119
120void KRFBConnection::gotSocketError( int err ) 120void KRFBConnection::gotSocketError( int err )
121{ 121{
122 currentState_ = Error; 122 currentState_ = Error;
123 123
124 // Do some error handling stuff 124 // Do some error handling stuff
125 qWarning( "KRFBConnection: Socket error %d", err ); 125 qWarning( "KRFBConnection: Socket error %d", err );
126 126
127 static QString refused = tr( "Connection Refused" ); 127 static QString refused = tr( "Connection Refused" );
128 static QString host = tr( "Host not found" ); 128 static QString host = tr( "Host not found" );
129 static QString read = tr( "Read Error: QSocket reported an error reading\n" 129 static QString read = tr( "Read Error: QSocket reported an error reading\n"
130 "data, the remote host has probably dropped the\n" 130 "data, the remote host has probably dropped the\n"
131 "connection." ); 131 "connection." );
132 static QString confused = tr( "QSocket reported an invalid error code" ); 132 static QString confused = tr( "QSocket reported an invalid error code" );
133 133
134 QString msg; 134 QString msg;
135 switch ( err ) { 135 switch ( err ) {
136 case QSocket::ErrConnectionRefused: 136 case QSocket::ErrConnectionRefused:
137 msg = refused; 137 msg = refused;
138 break; 138 break;
139 case QSocket::ErrHostNotFound: 139 case QSocket::ErrHostNotFound:
140 msg = host; 140 msg = host;
141 break; 141 break;
142 case QSocket::ErrSocketRead: 142 case QSocket::ErrSocketRead:
143 msg = read; 143 msg = read;
144 break; 144 break;
145 default: 145 default:
146 msg = confused; 146 msg = confused;
147 }; 147 };
148 148
149 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) ); 149 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) );
150 delete sock; 150 delete sock;
151 sock = 0; 151 sock = 0;
152 currentState_ = Disconnected; 152 currentState_ = Disconnected;
153 153
154 emit error( msg ); 154 emit error( msg );
155} 155}
156 156
157void KRFBConnection::gotMoreData() 157void KRFBConnection::gotMoreData()
158{ 158{
159 assert( minData_ > 0 ); 159 assert( minData_ > 0 );
160 160
161 if ( sock->size() >= minData_ ) { 161 if ( sock->size() >= minData_ ) {
162 minData_ = 0; 162 minData_ = 0;
163 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) ); 163 QObject::disconnect( sock, SIGNAL( readyRead() ), this, SLOT( gotMoreData() ) );
164 emit gotEnoughData(); 164 emit gotEnoughData();
165 } 165 }
166} 166}
167 167
168void KRFBConnection::waitForData( unsigned int sz ) 168void KRFBConnection::waitForData( unsigned int sz )
169{ 169{
170 assert( minData_ == 0 ); 170 assert( minData_ == 0 );
171 assert( sz > 0 ); 171 assert( sz > 0 );
172 assert( currentState_ != Error ); 172 assert( currentState_ != Error );
173 173
174 if ( sock->size() >= sz ) { 174 if ( sock->size() >= sz ) {
175 // qWarning( "No need to wait for data" ); 175 // qWarning( "No need to wait for data" );
176 emit gotEnoughData(); 176 emit gotEnoughData();
177 } 177 }
178 else { 178 else {
179 // qWarning( "Waiting for %u bytes", sz ); 179 // qWarning( "Waiting for %u bytes", sz );
180 minData_ = sz; 180 minData_ = sz;
181 connect( sock, SIGNAL( readyRead() ), SLOT( gotMoreData() ) ); 181 connect( sock, SIGNAL( readyRead() ), SLOT( gotMoreData() ) );
182 } 182 }
183} 183}
184 184
185int KRFBConnection::read( void *buf, int sz ) 185int KRFBConnection::read( void *buf, int sz )
186{ 186{
187 return sock->readBlock( (char *) buf, sz ); 187 return sock->readBlock( (char *) buf, sz );
188} 188}
189 189
190int KRFBConnection::write( void *buf, int sz ) 190int KRFBConnection::write( void *buf, int sz )
191{ 191{
192 return sock->writeBlock( (const char *) buf, sz ); 192 return sock->writeBlock( (const char *) buf, sz );
193} 193}
194 194
195KRFBConnection::State KRFBConnection::state() const 195KRFBConnection::State KRFBConnection::state() const
196{ 196{
197 return currentState_; 197 return currentState_;
198} 198}
199 199
200void KRFBConnection::setPortBase( int base ) 200void KRFBConnection::setPortBase( int base )
201{ 201{
202 portBase_ = base; 202 portBase_ = base;
203} 203}
204 204
205int KRFBConnection::portBase() const 205int KRFBConnection::portBase() const
206{ 206{
207 return portBase_; 207 return portBase_;
208} 208}
209 209
210void KRFBConnection::updateTimer() 210void KRFBConnection::updateTimer()
211{ 211{
212 decoder_->sendUpdateRequest( true ); 212 decoder_->sendUpdateRequest( true );
213} 213}
214 214
215void KRFBConnection::refresh() 215void KRFBConnection::refresh()
216{ 216{
217 decoder_->sendUpdateRequest( false ); 217 decoder_->sendUpdateRequest( false );
218} 218}
219 219
220void KRFBConnection::sendCutText( const QString &text ) 220void KRFBConnection::sendCutText( const QString &text )
221{ 221{
222 decoder_->sendCutEvent( text ); 222 decoder_->sendCutEvent( text );
223} 223}
224 224
225const QUrl &KRFBConnection::url() 225const QUrl &KRFBConnection::url()
226{ 226{
227 url_.setProtocol( "vnc" ); 227 url_.setProtocol( "vnc" );
228 url_.setPort( display() ); 228 url_.setPort( display() );
229 url_.setHost( host() ); 229 url_.setHost( host() );
230 url_.setPath( "/" ); 230 url_.setPath( "/" );
231 231
232 return url_; 232 return url_;
233} 233}
diff --git a/noncore/comm/keypebble/krfblogin.cpp b/noncore/comm/keypebble/krfblogin.cpp
index 0b4a757..2bbd110 100644
--- a/noncore/comm/keypebble/krfblogin.cpp
+++ b/noncore/comm/keypebble/krfblogin.cpp
@@ -1,253 +1,253 @@
1#include <assert.h> 1#include <assert.h>
2 2
3 3
4extern "C" { 4extern "C" {
5#include "vncauth.h" 5#include "vncauth.h"
6} 6}
7 7
8#include "krfblogin.h" 8#include "krfblogin.h"
9#include "krfbconnection.h" 9#include "krfbconnection.h"
10#include <qtimer.h> 10#include <qtimer.h>
11 11
12// The length of the various messages (used to decide how many bytes to 12// The length of the various messages (used to decide how many bytes to
13// wait for). 13// wait for).
14const int ServerVersionLength = 12; 14const int ServerVersionLength = 12;
15const int ClientVersionLength = 12; 15const int ClientVersionLength = 12;
16const int AuthSchemeLength = 4; 16const int AuthSchemeLength = 4;
17const int FailureReasonSizeLength = 4; 17const int FailureReasonSizeLength = 4;
18const int ChallengeLength = 16; 18const int ChallengeLength = 16;
19const int AuthResultLength = 4; 19const int AuthResultLength = 4;
20 20
21// Authentication results 21// Authentication results
22enum AuthResult { 22enum AuthResult {
23 AuthOk, 23 AuthOk,
24 AuthFailed, 24 AuthFailed,
25 AuthTooMany 25 AuthTooMany
26}; 26};
27 27
28typedef unsigned char CARD8; 28typedef unsigned char CARD8;
29typedef unsigned short CARD16; 29typedef unsigned short CARD16;
30typedef unsigned long CARD32; 30typedef unsigned long CARD32;
31 31
32const int endianTest = 1; 32const int endianTest = 1;
33 33
34// Endian stuff 34// Endian stuff
35#define Swap16IfLE(s) \ 35#define Swap16IfLE(s) \
36 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s)) 36 (*(char *)&endianTest ? ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff)) : (s))
37 37
38#define Swap32IfLE(l) \ 38#define Swap32IfLE(l) \
39 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \ 39 (*(char *)&endianTest ? ((((l) & 0xff000000) >> 24) | \
40 (((l) & 0x00ff0000) >> 8) | \ 40 (((l) & 0x00ff0000) >> 8) | \
41 (((l) & 0x0000ff00) << 8) | \ 41 (((l) & 0x0000ff00) << 8) | \
42 (((l) & 0x000000ff) << 24)) : (l)) 42 (((l) & 0x000000ff) << 24)) : (l))
43 43
44KRFBLogin::KRFBLogin( KRFBConnection *con ) 44KRFBLogin::KRFBLogin( KRFBConnection *con )
45 : QObject( con, "RFB login manager" ) 45 : QObject( con, "RFB login manager" )
46{ 46{
47 assert( con ); 47 assert( con );
48 this->con = con; 48 this->con = con;
49 currentState = AwaitingServerVersion; 49 currentState = AwaitingServerVersion;
50 50
51 connect( this, SIGNAL( error( const QString & ) ), 51 connect( this, SIGNAL( error(const QString&) ),
52 con, SIGNAL( error( const QString & ) ) ); 52 con, SIGNAL( error(const QString&) ) );
53 53
54 54
55 qWarning( "Waiting for server version..." ); 55 qWarning( "Waiting for server version..." );
56 56
57 static QString statusMsg = tr( "Waiting for server version..." ); 57 static QString statusMsg = tr( "Waiting for server version..." );
58 emit status( statusMsg ); 58 emit status( statusMsg );
59 59
60 // Kick off the state machine 60 // Kick off the state machine
61 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerVersion() ) ); 61 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotServerVersion() ) );
62 con->waitForData( ServerVersionLength ); 62 con->waitForData( ServerVersionLength );
63} 63}
64 64
65KRFBLogin::~KRFBLogin() 65KRFBLogin::~KRFBLogin()
66{ 66{
67 67
68} 68}
69 69
70KRFBLogin::State KRFBLogin::state() const 70KRFBLogin::State KRFBLogin::state() const
71{ 71{
72 return currentState; 72 return currentState;
73} 73}
74 74
75void KRFBLogin::gotServerVersion() 75void KRFBLogin::gotServerVersion()
76{ 76{
77 qWarning( "Got server version" ); 77 qWarning( "Got server version" );
78 78
79 disconnect( con, SIGNAL( gotEnoughData() ), 79 disconnect( con, SIGNAL( gotEnoughData() ),
80 this, SLOT( gotServerVersion() ) ); 80 this, SLOT( gotServerVersion() ) );
81 81
82 // Read the server's version message 82 // Read the server's version message
83 char serverVersion[ ServerVersionLength + 1 ]; 83 char serverVersion[ ServerVersionLength + 1 ];
84 con->read( serverVersion, ServerVersionLength ); 84 con->read( serverVersion, ServerVersionLength );
85 serverVersion[ ServerVersionLength ] = '\0'; 85 serverVersion[ ServerVersionLength ] = '\0';
86 86
87 QCString rfbString( serverVersion, ServerVersionLength + 1 ); 87 QCString rfbString( serverVersion, ServerVersionLength + 1 );
88 versionString = rfbString; 88 versionString = rfbString;
89 89
90 QRegExp regexp( "RFB [0-9][0-9][0-9]\\.[0-9][0-9][0-9]\n" ); 90 QRegExp regexp( "RFB [0-9][0-9][0-9]\\.[0-9][0-9][0-9]\n" );
91 91
92 if ( rfbString.find( regexp ) == -1 ) { 92 if ( rfbString.find( regexp ) == -1 ) {
93 static QString msg = tr( "Error: Invalid server version, %1" ).arg( rfbString ); 93 static QString msg = tr( "Error: Invalid server version, %1" ).arg( rfbString );
94 94
95 qWarning( msg ); 95 qWarning( msg );
96 emit error( msg ); 96 emit error( msg );
97 currentState = Error; 97 currentState = Error;
98 return; 98 return;
99 } 99 }
100 100
101 // Calculate the actual version number 101 // Calculate the actual version number
102 serverMajor = (serverVersion[4] - '0') * 100 102 serverMajor = (serverVersion[4] - '0') * 100
103 + (serverVersion[5] - '0') * 10 103 + (serverVersion[5] - '0') * 10
104 + (serverVersion[6] - '0'); 104 + (serverVersion[6] - '0');
105 serverMinor = (serverVersion[8] - '0') * 100 105 serverMinor = (serverVersion[8] - '0') * 100
106 + (serverVersion[9] - '0') * 10 106 + (serverVersion[9] - '0') * 10
107 + (serverVersion[10] - '0'); 107 + (serverVersion[10] - '0');
108 108
109 qWarning("Server Version: %03d.%03d", serverMajor, serverMinor ); 109 qWarning("Server Version: %03d.%03d", serverMajor, serverMinor );
110 110
111 if ( serverMajor != 3 ) { 111 if ( serverMajor != 3 ) {
112 QString msg = tr( "Error: Unsupported server version, %1" ) 112 QString msg = tr( "Error: Unsupported server version, %1" )
113 .arg( rfbString ); 113 .arg( rfbString );
114 114
115 qWarning( msg ); 115 qWarning( msg );
116 emit error( msg ); 116 emit error( msg );
117 currentState = Error; 117 currentState = Error;
118 return; 118 return;
119 } 119 }
120 120
121 if ( serverMinor != 3 ) { 121 if ( serverMinor != 3 ) {
122 qWarning( "Minor version mismatch: %d", serverMinor ); 122 qWarning( "Minor version mismatch: %d", serverMinor );
123 } 123 }
124 124
125 // Setup for the next state 125 // Setup for the next state
126 sendClientVersion(); 126 sendClientVersion();
127 127
128 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthScheme() ) ); 128 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthScheme() ) );
129 con->waitForData( AuthSchemeLength ); 129 con->waitForData( AuthSchemeLength );
130} 130}
131 131
132void KRFBLogin::gotAuthScheme() 132void KRFBLogin::gotAuthScheme()
133{ 133{
134 disconnect( con, SIGNAL( gotEnoughData() ), 134 disconnect( con, SIGNAL( gotEnoughData() ),
135 this, SLOT( gotAuthScheme() ) ); 135 this, SLOT( gotAuthScheme() ) );
136 136
137 // Got data 137 // Got data
138 CARD32 scheme; 138 CARD32 scheme;
139 con->read( &scheme, AuthSchemeLength ); 139 con->read( &scheme, AuthSchemeLength );
140 scheme = Swap32IfLE( scheme ); 140 scheme = Swap32IfLE( scheme );
141 141
142 static QString statusMsgOk = tr( "Logged in" ); 142 static QString statusMsgOk = tr( "Logged in" );
143 143
144 switch ( scheme ) { 144 switch ( scheme ) {
145 case 0: 145 case 0:
146 qWarning( "Failed" ); 146 qWarning( "Failed" );
147 // Handle failure 147 // Handle failure
148 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotFailureReasonSize() ) ); 148 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotFailureReasonSize() ) );
149 con->waitForData( FailureReasonSizeLength ); 149 con->waitForData( FailureReasonSizeLength );
150 break; 150 break;
151 case 1: 151 case 1:
152 // Handle no auth 152 // Handle no auth
153 emit status( statusMsgOk ); 153 emit status( statusMsgOk );
154 con->gotRFBConnection(); 154 con->gotRFBConnection();
155 break; 155 break;
156 case 2: 156 case 2:
157 // Handle VNC auth 157 // Handle VNC auth
158 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotChallenge() ) ); 158 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotChallenge() ) );
159 con->waitForData( ChallengeLength ); 159 con->waitForData( ChallengeLength );
160 break; 160 break;
161 default: 161 default:
162 qWarning( "Unknown authentication scheme, 0x%08lx", scheme ); 162 qWarning( "Unknown authentication scheme, 0x%08lx", scheme );
163 currentState = Error; 163 currentState = Error;
164 break; 164 break;
165 }; 165 };
166} 166}
167 167
168void KRFBLogin::gotChallenge() 168void KRFBLogin::gotChallenge()
169{ 169{
170 disconnect( con, SIGNAL( gotEnoughData() ), 170 disconnect( con, SIGNAL( gotEnoughData() ),
171 this, SLOT( gotChallenge() ) ); 171 this, SLOT( gotChallenge() ) );
172 172
173 QTimer::singleShot( 0, this, SLOT(getPassword()) ); 173 QTimer::singleShot( 0, this, SLOT(getPassword()) );
174} 174}
175 175
176void KRFBLogin::getPassword() 176void KRFBLogin::getPassword()
177{ 177{
178 // Got data 178 // Got data
179 CARD8 challenge[ ChallengeLength ]; 179 CARD8 challenge[ ChallengeLength ];
180 con->read( challenge, ChallengeLength ); 180 con->read( challenge, ChallengeLength );
181 181
182 // Last chance to enter a password 182 // Last chance to enter a password
183 if ( con->options_->password.isNull() ) { 183 if ( con->options_->password.isNull() ) {
184 qWarning( "krfblogin needs a password" ); 184 qWarning( "krfblogin needs a password" );
185 emit passwordRequired( con ); 185 emit passwordRequired( con );
186 } 186 }
187 187
188 if ( con->options_->password.isNull() ) { 188 if ( con->options_->password.isNull() ) {
189 QString msg = tr( "Error: This server requires a password, but none " 189 QString msg = tr( "Error: This server requires a password, but none "
190 "has been specified.\n" ); 190 "has been specified.\n" );
191 191
192 emit error( msg ); 192 emit error( msg );
193 return; 193 return;
194 } 194 }
195 195
196 vncEncryptBytes( (unsigned char *) challenge, QCString(con->options_->password.latin1()).data() ); 196 vncEncryptBytes( (unsigned char *) challenge, QCString(con->options_->password.latin1()).data() );
197 con->write( challenge, ChallengeLength ); 197 con->write( challenge, ChallengeLength );
198 198
199 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthResult() ) ); 199 connect( con, SIGNAL( gotEnoughData() ), SLOT( gotAuthResult() ) );
200 con->waitForData( AuthResultLength ); 200 con->waitForData( AuthResultLength );
201} 201}
202 202
203void KRFBLogin::gotFailureReasonSize() 203void KRFBLogin::gotFailureReasonSize()
204{ 204{
205 disconnect( con, SIGNAL( gotEnoughData() ), this, 205 disconnect( con, SIGNAL( gotEnoughData() ), this,
206 SLOT( gotFailureReasonSize() ) ); 206 SLOT( gotFailureReasonSize() ) );
207} 207}
208 208
209void KRFBLogin::gotAuthResult() 209void KRFBLogin::gotAuthResult()
210{ 210{
211 // Got data 211 // Got data
212 disconnect( con, SIGNAL( gotEnoughData() ), this, 212 disconnect( con, SIGNAL( gotEnoughData() ), this,
213 SLOT( gotAuthResult() ) ); 213 SLOT( gotAuthResult() ) );
214 214
215 long result; 215 long result;
216 con->read( &result, AuthResultLength ); 216 con->read( &result, AuthResultLength );
217 result = Swap32IfLE( result ); 217 result = Swap32IfLE( result );
218 218
219 qWarning( "Authentication Result is 0x%08lx", result ); 219 qWarning( "Authentication Result is 0x%08lx", result );
220 220
221 static QString failed = tr( "Error: The password you specified was incorrect." ); 221 static QString failed = tr( "Error: The password you specified was incorrect." );
222 static QString tooMany = tr( "Error: Too many invalid login attempts have been made\n" 222 static QString tooMany = tr( "Error: Too many invalid login attempts have been made\n"
223 "to this account, please try later." ); 223 "to this account, please try later." );
224 224
225 static QString statusMsgOk = tr( "Logged in" ); 225 static QString statusMsgOk = tr( "Logged in" );
226 static QString statusMsgFailed = tr( "Login Failed" ); 226 static QString statusMsgFailed = tr( "Login Failed" );
227 static QString statusMsgTooMany = tr( "Too many failures" ); 227 static QString statusMsgTooMany = tr( "Too many failures" );
228 228
229 switch( result ) { 229 switch( result ) {
230 case AuthOk: 230 case AuthOk:
231 emit status( statusMsgOk ); 231 emit status( statusMsgOk );
232 con->gotRFBConnection(); 232 con->gotRFBConnection();
233 break; 233 break;
234 case AuthFailed: 234 case AuthFailed:
235 qWarning( "Dammit" ); 235 qWarning( "Dammit" );
236 emit status( statusMsgFailed ); 236 emit status( statusMsgFailed );
237 emit error( failed ); 237 emit error( failed );
238 break; 238 break;
239 case AuthTooMany: 239 case AuthTooMany:
240 emit status( statusMsgTooMany ); 240 emit status( statusMsgTooMany );
241 emit error( tooMany ); 241 emit error( tooMany );
242 break; 242 break;
243 default: 243 default:
244 qWarning( "Invalid authentication result, %lx", result ); 244 qWarning( "Invalid authentication result, %lx", result );
245 break; 245 break;
246 } 246 }
247} 247}
248 248
249void KRFBLogin::sendClientVersion() 249void KRFBLogin::sendClientVersion()
250{ 250{
251 qWarning( "Sending client version" ); 251 qWarning( "Sending client version" );
252 con->write( (void*)"RFB 003.003\n", ClientVersionLength ); 252 con->write( (void*)"RFB 003.003\n", ClientVersionLength );
253} 253}
diff --git a/noncore/comm/keypebble/kvnc.cpp b/noncore/comm/keypebble/kvnc.cpp
index c678edf..88cb50b 100644
--- a/noncore/comm/keypebble/kvnc.cpp
+++ b/noncore/comm/keypebble/kvnc.cpp
@@ -1,279 +1,279 @@
1#include <qaction.h> 1#include <qaction.h>
2#include <qpopupmenu.h> 2#include <qpopupmenu.h>
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4#include <qmessagebox.h> 4#include <qmessagebox.h>
5#include <qlistbox.h> 5#include <qlistbox.h>
6#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7#include <qpe/resource.h> 7#include <qpe/resource.h>
8 8
9#include <assert.h> 9#include <assert.h>
10 10
11#include "kvnc.h" 11#include "kvnc.h"
12#include "krfbcanvas.h" 12#include "krfbcanvas.h"
13#include "krfbconnection.h" 13#include "krfbconnection.h"
14#include "kvncconndlg.h" 14#include "kvncconndlg.h"
15 15
16static int u_id = 1; 16static int u_id = 1;
17static int get_unique_id() 17static int get_unique_id()
18{ 18{
19 return u_id++; 19 return u_id++;
20} 20}
21 21
22 22
23/* XPM */ 23/* XPM */
24static char * menu_xpm[] = { 24static char * menu_xpm[] = {
25"12 12 5 1", 25"12 12 5 1",
26 " c None", 26 " c None",
27 ".c #000000", 27 ".c #000000",
28 "+c #FFFDAD", 28 "+c #FFFDAD",
29 "@c #FFFF00", 29 "@c #FFFF00",
30 "#c #E5E100", 30 "#c #E5E100",
31" ", 31" ",
32" ", 32" ",
33" ......... ", 33" ......... ",
34" .+++++++. ", 34" .+++++++. ",
35" .+@@@@#. ", 35" .+@@@@#. ",
36" .+@@@#. ", 36" .+@@@#. ",
37" .+@@#. ", 37" .+@@#. ",
38" .+@#. ", 38" .+@#. ",
39" .+#. ", 39" .+#. ",
40" .+. ", 40" .+. ",
41" .. ", 41" .. ",
42" "}; 42" "};
43 43
44const int StatusTextId = 0; 44const int StatusTextId = 0;
45 45
46KVNC::KVNC( QWidget *parent, const char *name, WFlags f) : QMainWindow( 0, name ,WStyle_ContextHelp) 46KVNC::KVNC( QWidget *parent, const char *name, WFlags f) : QMainWindow( 0, name ,WStyle_ContextHelp)
47{ 47{
48 setCaption( tr("VNC Viewer") ); 48 setCaption( tr("VNC Viewer") );
49 fullscreen = false; 49 fullscreen = false;
50 50
51 stack = new QWidgetStack( this ); 51 stack = new QWidgetStack( this );
52 setCentralWidget( stack ); 52 setCentralWidget( stack );
53 53
54 bookmarkSelector=new KVNCBookmarkDlg(); 54 bookmarkSelector=new KVNCBookmarkDlg();
55 stack->addWidget(bookmarkSelector,get_unique_id()); 55 stack->addWidget(bookmarkSelector,get_unique_id());
56 stack->raiseWidget( bookmarkSelector ); 56 stack->raiseWidget( bookmarkSelector );
57 57
58 canvas = new KRFBCanvas( stack, "canvas" ); 58 canvas = new KRFBCanvas( stack, "canvas" );
59 stack->addWidget(canvas,get_unique_id()); 59 stack->addWidget(canvas,get_unique_id());
60 setCentralWidget( stack ); 60 setCentralWidget( stack );
61 61
62 62
63 connect( bookmarkSelector->bookmarkList, SIGNAL(clicked(QListBoxItem *)), 63 connect( bookmarkSelector->bookmarkList, SIGNAL(clicked(QListBoxItem*)),
64 this, SLOT(openConnection(QListBoxItem *)) ); 64 this, SLOT(openConnection(QListBoxItem*)) );
65 connect( canvas->connection(), SIGNAL(statusChanged(const QString &)), 65 connect( canvas->connection(), SIGNAL(statusChanged(const QString&)),
66 this, SLOT(statusMessage(const QString &)) ); 66 this, SLOT(statusMessage(const QString&)) );
67 connect( canvas->connection(), SIGNAL(error(const QString &)), 67 connect( canvas->connection(), SIGNAL(error(const QString&)),
68 this, SLOT(error(const QString &)) ); 68 this, SLOT(error(const QString&)) );
69 connect( canvas->connection(), SIGNAL(connected()), this, SLOT(connected()) ); 69 connect( canvas->connection(), SIGNAL(connected()), this, SLOT(connected()) );
70 connect( canvas->connection(), SIGNAL(loggedIn()), this, SLOT(loggedIn()) ); 70 connect( canvas->connection(), SIGNAL(loggedIn()), this, SLOT(loggedIn()) );
71 connect( canvas->connection(), SIGNAL(disconnected()), this, SLOT(disconnected()) ); 71 connect( canvas->connection(), SIGNAL(disconnected()), this, SLOT(disconnected()) );
72 72
73 setupActions(); 73 setupActions();
74 74
75 cornerButton = new QPushButton( this ); 75 cornerButton = new QPushButton( this );
76 cornerButton->setPixmap( QPixmap( (const char**)menu_xpm ) ); 76 cornerButton->setPixmap( QPixmap( (const char**)menu_xpm ) );
77 connect( cornerButton, SIGNAL(pressed()), this, SLOT(showMenu()) ); 77 connect( cornerButton, SIGNAL(pressed()), this, SLOT(showMenu()) );
78 canvas->setCornerWidget( cornerButton ); 78 canvas->setCornerWidget( cornerButton );
79 79
80 stack->raiseWidget( bookmarkSelector ); 80 stack->raiseWidget( bookmarkSelector );
81 81
82 82
83 bar= new QToolBar( this ); 83 bar= new QToolBar( this );
84 setToolBarsMovable( false ); 84 setToolBarsMovable( false );
85 setRightJustification(false); 85 setRightJustification(false);
86 86
87 87
88 QAction *n = new QAction( tr( "New Connection" ), Resource::loadPixmap( "new" ), 88 QAction *n = new QAction( tr( "New Connection" ), Resource::loadPixmap( "new" ),
89 QString::null, 0, this, 0 ); 89 QString::null, 0, this, 0 );
90 connect( n, SIGNAL( activated() ), 90 connect( n, SIGNAL( activated() ),
91 this, SLOT( newConnection() ) ); 91 this, SLOT( newConnection() ) );
92 n->addTo( bar ); 92 n->addTo( bar );
93 93
94 QAction *o = new QAction( tr( "Open Bookmark" ), Resource::loadPixmap( "fileopen" ), 94 QAction *o = new QAction( tr( "Open Bookmark" ), Resource::loadPixmap( "fileopen" ),
95 QString::null, 0, this, 0 ); 95 QString::null, 0, this, 0 );
96 connect( o, SIGNAL( activated() ), 96 connect( o, SIGNAL( activated() ),
97 this, SLOT( openConnection() ) ); 97 this, SLOT( openConnection() ) );
98 o->addTo( bar ); 98 o->addTo( bar );
99 99
100 QAction *d = new QAction( tr( "Delete Bookmark" ), Resource::loadPixmap( "trash" ), 100 QAction *d = new QAction( tr( "Delete Bookmark" ), Resource::loadPixmap( "trash" ),
101 QString::null, 0, this, 0 ); 101 QString::null, 0, this, 0 );
102 connect( d, SIGNAL( activated() ), 102 connect( d, SIGNAL( activated() ),
103 this, SLOT( deleteBookmark() ) ); 103 this, SLOT( deleteBookmark() ) );
104 d->addTo( bar ); 104 d->addTo( bar );
105} 105}
106 106
107KVNC::~KVNC() 107KVNC::~KVNC()
108{ 108{
109 109
110} 110}
111 111
112void KVNC::newConnection() 112void KVNC::newConnection()
113{ 113{
114 curServer=new KRFBServer; 114 curServer=new KRFBServer;
115 115
116 KVNCConnDlg dlg( curServer,this); 116 KVNCConnDlg dlg( curServer,this);
117 if ( QPEApplication::execDialog( &dlg )) { 117 if ( QPEApplication::execDialog( &dlg )) {
118 if (!curServer->name.isEmpty()) 118 if (!curServer->name.isEmpty())
119 bookmarkSelector->addBookmark(curServer); 119 bookmarkSelector->addBookmark(curServer);
120 canvas->openConnection(*curServer); 120 canvas->openConnection(*curServer);
121 } else 121 } else
122 curServer=0; 122 curServer=0;
123} 123}
124 124
125void KVNC::openConnection( QString name) 125void KVNC::openConnection( QString name)
126{ 126{
127 curServer=bookmarkSelector->getServer(name); 127 curServer=bookmarkSelector->getServer(name);
128 128
129 if (curServer) { 129 if (curServer) {
130 KVNCConnDlg dlg( curServer,this); 130 KVNCConnDlg dlg( curServer,this);
131 if ( QPEApplication::execDialog( &dlg ) ) { 131 if ( QPEApplication::execDialog( &dlg ) ) {
132 canvas->openConnection(*curServer); 132 canvas->openConnection(*curServer);
133 bookmarkSelector->writeBookmarks(); 133 bookmarkSelector->writeBookmarks();
134 } else 134 } else
135 curServer=0; 135 curServer=0;
136 } 136 }
137} 137}
138 138
139void KVNC::openConnection( void ) 139void KVNC::openConnection( void )
140{ 140{
141 openConnection( bookmarkSelector->selectedBookmark()); 141 openConnection( bookmarkSelector->selectedBookmark());
142} 142}
143 143
144void KVNC::openConnection( QListBoxItem * item) 144void KVNC::openConnection( QListBoxItem * item)
145{ 145{
146 if (item) 146 if (item)
147 openConnection(item->text()); 147 openConnection(item->text());
148} 148}
149 149
150void KVNC::setupActions() 150void KVNC::setupActions()
151{ 151{
152 cornerMenu = new QPopupMenu( this ); 152 cornerMenu = new QPopupMenu( this );
153 153
154 fullScreenAction = new QAction( tr("Full Screen"), QString::null, 0, 0 ); 154 fullScreenAction = new QAction( tr("Full Screen"), QString::null, 0, 0 );
155 connect( fullScreenAction, SIGNAL(activated()), 155 connect( fullScreenAction, SIGNAL(activated()),
156 this, SLOT( toggleFullScreen() ) ); 156 this, SLOT( toggleFullScreen() ) );
157 fullScreenAction->addTo( cornerMenu ); 157 fullScreenAction->addTo( cornerMenu );
158 fullScreenAction->setEnabled( false ); 158 fullScreenAction->setEnabled( false );
159 159
160 ctlAltDelAction = new QAction( tr("Send Contrl-Alt-Delete"), QString::null, 0, 0 ); 160 ctlAltDelAction = new QAction( tr("Send Contrl-Alt-Delete"), QString::null, 0, 0 );
161 connect( ctlAltDelAction, SIGNAL(activated()), 161 connect( ctlAltDelAction, SIGNAL(activated()),
162 canvas, SLOT( sendCtlAltDel() ) ); 162 canvas, SLOT( sendCtlAltDel() ) );
163 ctlAltDelAction->addTo( cornerMenu ); 163 ctlAltDelAction->addTo( cornerMenu );
164 ctlAltDelAction->setEnabled( false ); 164 ctlAltDelAction->setEnabled( false );
165 165
166 disconnectAction = new QAction( tr("Disconnect"), QString::null, 0, 0 ); 166 disconnectAction = new QAction( tr("Disconnect"), QString::null, 0, 0 );
167 connect( disconnectAction, SIGNAL(activated()), 167 connect( disconnectAction, SIGNAL(activated()),
168 this, SLOT( closeConnection() ) ); 168 this, SLOT( closeConnection() ) );
169 disconnectAction->addTo( cornerMenu ); 169 disconnectAction->addTo( cornerMenu );
170 disconnectAction->setEnabled( false ); 170 disconnectAction->setEnabled( false );
171 171
172 doubleClickAction = new QAction( tr("Next Click is Double Click"), QString::null, 0, 0 ); 172 doubleClickAction = new QAction( tr("Next Click is Double Click"), QString::null, 0, 0 );
173 connect( doubleClickAction, SIGNAL(activated()), 173 connect( doubleClickAction, SIGNAL(activated()),
174 canvas, SLOT( markDoubleClick() ) ); 174 canvas, SLOT( markDoubleClick() ) );
175 doubleClickAction->addTo( cornerMenu ); 175 doubleClickAction->addTo( cornerMenu );
176 doubleClickAction->setEnabled( false ); 176 doubleClickAction->setEnabled( false );
177 177
178 rightClickAction = new QAction( tr("Next Click is Right Click"), QString::null, 0, 0 ); 178 rightClickAction = new QAction( tr("Next Click is Right Click"), QString::null, 0, 0 );
179 connect( rightClickAction, SIGNAL(activated()), 179 connect( rightClickAction, SIGNAL(activated()),
180 canvas, SLOT( markRightClick() ) ); 180 canvas, SLOT( markRightClick() ) );
181 rightClickAction->addTo( cornerMenu ); 181 rightClickAction->addTo( cornerMenu );
182 rightClickAction->setEnabled( false ); 182 rightClickAction->setEnabled( false );
183} 183}
184 184
185void KVNC::toggleFullScreen() 185void KVNC::toggleFullScreen()
186{ 186{
187 if ( fullscreen ) { 187 if ( fullscreen ) {
188 canvas->releaseKeyboard(); 188 canvas->releaseKeyboard();
189 canvas->reparent( stack, 0, QPoint(0,0), false ); 189 canvas->reparent( stack, 0, QPoint(0,0), false );
190 canvas->setFrameStyle( QFrame::Panel | QFrame::Sunken ); 190 canvas->setFrameStyle( QFrame::Panel | QFrame::Sunken );
191 setCentralWidget( stack ); 191 setCentralWidget( stack );
192 stack->addWidget(canvas,get_unique_id()); 192 stack->addWidget(canvas,get_unique_id());
193 stack->raiseWidget(canvas); 193 stack->raiseWidget(canvas);
194 canvas->show(); 194 canvas->show();
195 stack->show(); 195 stack->show();
196 fullScreenAction->setText( tr("Full Screen") ); 196 fullScreenAction->setText( tr("Full Screen") );
197 } else { 197 } else {
198 canvas->setFrameStyle( QFrame::NoFrame ); 198 canvas->setFrameStyle( QFrame::NoFrame );
199 stack->removeWidget(canvas); 199 stack->removeWidget(canvas);
200 canvas->reparent( 0,WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop, 200 canvas->reparent( 0,WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop,
201 QPoint(0,0),false); 201 QPoint(0,0),false);
202 canvas->resize(qApp->desktop()->width(), qApp->desktop()->height()); 202 canvas->resize(qApp->desktop()->width(), qApp->desktop()->height());
203 canvas->raise(); 203 canvas->raise();
204 canvas->setFocus(); 204 canvas->setFocus();
205 canvas->grabKeyboard(); 205 canvas->grabKeyboard();
206 canvas->show(); 206 canvas->show();
207 207
208 fullScreenAction->setText( tr("Stop Full Screen") ); 208 fullScreenAction->setText( tr("Stop Full Screen") );
209 } 209 }
210 210
211 211
212 fullscreen = !fullscreen; 212 fullscreen = !fullscreen;
213} 213}
214 214
215void KVNC::closeConnection() 215void KVNC::closeConnection()
216{ 216{
217 if ( fullscreen ) 217 if ( fullscreen )
218 toggleFullScreen(); 218 toggleFullScreen();
219 canvas->closeConnection(); 219 canvas->closeConnection();
220} 220}
221 221
222void KVNC::showMenu() 222void KVNC::showMenu()
223{ 223{
224 QPoint pt = mapToGlobal(cornerButton->pos()); 224 QPoint pt = mapToGlobal(cornerButton->pos());
225 QSize s = cornerMenu->sizeHint(); 225 QSize s = cornerMenu->sizeHint();
226 pt.ry() -= s.height(); 226 pt.ry() -= s.height();
227 pt.rx() -= s.width(); 227 pt.rx() -= s.width();
228 cornerMenu->popup( pt ); 228 cornerMenu->popup( pt );
229} 229}
230 230
231void KVNC::connected() 231void KVNC::connected()
232{ 232{
233 static QString msg = tr( "Connected to remote host" ); 233 static QString msg = tr( "Connected to remote host" );
234 statusMessage( msg ); 234 statusMessage( msg );
235 ctlAltDelAction->setEnabled(true); 235 ctlAltDelAction->setEnabled(true);
236 disconnectAction->setEnabled( true ); 236 disconnectAction->setEnabled( true );
237 fullScreenAction->setEnabled( true ); 237 fullScreenAction->setEnabled( true );
238 doubleClickAction->setEnabled( false ); 238 doubleClickAction->setEnabled( false );
239 rightClickAction->setEnabled( true ); 239 rightClickAction->setEnabled( true );
240 stack->raiseWidget(canvas); 240 stack->raiseWidget(canvas);
241 bar->hide(); 241 bar->hide();
242} 242}
243 243
244void KVNC::loggedIn() 244void KVNC::loggedIn()
245{ 245{
246 static QString msg = tr( "Logged in to remote host" ); 246 static QString msg = tr( "Logged in to remote host" );
247 statusMessage( msg ); 247 statusMessage( msg );
248} 248}
249 249
250void KVNC::disconnected() 250void KVNC::disconnected()
251{ 251{
252 252
253 if ( fullscreen ) 253 if ( fullscreen )
254 toggleFullScreen(); 254 toggleFullScreen();
255 static QString msg = tr( "Connection closed" ); 255 static QString msg = tr( "Connection closed" );
256 statusMessage( msg ); 256 statusMessage( msg );
257 ctlAltDelAction->setEnabled(false); 257 ctlAltDelAction->setEnabled(false);
258 disconnectAction->setEnabled( false ); 258 disconnectAction->setEnabled( false );
259 fullScreenAction->setEnabled( false ); 259 fullScreenAction->setEnabled( false );
260 doubleClickAction->setEnabled( false ); 260 doubleClickAction->setEnabled( false );
261 rightClickAction->setEnabled( false ); 261 rightClickAction->setEnabled( false );
262 stack->raiseWidget(bookmarkSelector); 262 stack->raiseWidget(bookmarkSelector);
263 bar->show(); 263 bar->show();
264} 264}
265 265
266void KVNC::statusMessage( const QString &m ) 266void KVNC::statusMessage( const QString &m )
267{ 267{
268 Global::statusMessage( m ); 268 Global::statusMessage( m );
269} 269}
270 270
271void KVNC::error( const QString &msg ) 271void KVNC::error( const QString &msg )
272{ 272{
273 statusMessage( msg ); 273 statusMessage( msg );
274 QMessageBox::warning( this, tr("VNC Viewer"), msg ); 274 QMessageBox::warning( this, tr("VNC Viewer"), msg );
275} 275}
276void KVNC::deleteBookmark(void) 276void KVNC::deleteBookmark(void)
277{ 277{
278 bookmarkSelector->deleteBookmark(bookmarkSelector->selectedBookmark()); 278 bookmarkSelector->deleteBookmark(bookmarkSelector->selectedBookmark());
279} 279}
diff --git a/noncore/games/bounce/game.cpp b/noncore/games/bounce/game.cpp
index c07f453..1f1f8cd 100644
--- a/noncore/games/bounce/game.cpp
+++ b/noncore/games/bounce/game.cpp
@@ -1,605 +1,605 @@
1/* 1/*
2 * Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de> 2 * Copyright (C) 2000 Stefan Schimanski <1Stein@gmx.de>
3 * 3 *
4 * This program is free software; you can redistribute it and/or 4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public 5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either 6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version. 7 * version 2 of the License, or (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details. 12 * Library General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU Library General Public 14 * You should have received a copy of the GNU Library General Public
15 * License along with this program; if not, write to the Free 15 * License along with this program; if not, write to the Free
16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */ 17 */
18 18
19 19
20#include <stdlib.h> 20#include <stdlib.h>
21#include <qtimer.h> 21#include <qtimer.h>
22#include <qpe/qpeapplication.h> 22#include <qpe/qpeapplication.h>
23 23
24#include "game.h" 24#include "game.h"
25 25
26#define TILE_SIZE 9 26#define TILE_SIZE 9
27 27
28#define TILE_FIRST ((FIELD_WIDTH-2)*(FIELD_HEIGHT-2)) 28#define TILE_FIRST ((FIELD_WIDTH-2)*(FIELD_HEIGHT-2))
29#define TILE_FREE (TILE_FIRST + 0) 29#define TILE_FREE (TILE_FIRST + 0)
30#define TILE_BORDER (TILE_FIRST + 1) 30#define TILE_BORDER (TILE_FIRST + 1)
31#define TILE_WALLEND (TILE_FIRST + 2) 31#define TILE_WALLEND (TILE_FIRST + 2)
32#define TILE_WALLUP (TILE_FIRST + 3) 32#define TILE_WALLUP (TILE_FIRST + 3)
33#define TILE_WALLDOWN (TILE_FIRST + 4) 33#define TILE_WALLDOWN (TILE_FIRST + 4)
34#define TILE_WALLLEFT (TILE_FIRST + 5) 34#define TILE_WALLLEFT (TILE_FIRST + 5)
35#define TILE_WALLRIGHT (TILE_FIRST + 6) 35#define TILE_WALLRIGHT (TILE_FIRST + 6)
36 36
37#define GAME_DELAY 15 37#define GAME_DELAY 15
38#define BALL_ANIM_DELAY 60 38#define BALL_ANIM_DELAY 60
39#define WALL_DELAY 100 39#define WALL_DELAY 100
40 40
41#define MS2TICKS( ms ) ((ms)/GAME_DELAY) 41#define MS2TICKS( ms ) ((ms)/GAME_DELAY)
42 42
43Arrow::Arrow(QCanvasPixmapArray* array, QCanvas* canvas) 43Arrow::Arrow(QCanvasPixmapArray* array, QCanvas* canvas)
44 : QCanvasSprite( array, canvas ) 44 : QCanvasSprite( array, canvas )
45{ 45{
46 m_vertical = true; 46 m_vertical = true;
47 move(3,3); 47 move(3,3);
48} 48}
49 49
50void Arrow::update() 50void Arrow::update()
51{ 51{
52 if ( m_vertical ) 52 if ( m_vertical )
53 setFrame( 0 ); 53 setFrame( 0 );
54 else 54 else
55 setFrame( 1 ); 55 setFrame( 1 );
56} 56}
57 57
58void Arrow::changeDirection() 58void Arrow::changeDirection()
59{ 59{
60 m_vertical = ! m_vertical; 60 m_vertical = ! m_vertical;
61 update(); 61 update();
62} 62}
63 63
64 64
65Ball::Ball(QCanvasPixmapArray* array, QCanvas* canvas) 65Ball::Ball(QCanvasPixmapArray* array, QCanvas* canvas)
66 : QCanvasSprite( array, canvas ), m_animDelay( 0 ), m_soundDelay( MS2TICKS(BALL_ANIM_DELAY)/2 ) 66 : QCanvasSprite( array, canvas ), m_animDelay( 0 ), m_soundDelay( MS2TICKS(BALL_ANIM_DELAY)/2 )
67{ 67{
68} 68}
69 69
70void Ball::update() 70void Ball::update()
71{ 71{
72 m_animDelay--; 72 m_animDelay--;
73 if ( m_animDelay<=0 ) 73 if ( m_animDelay<=0 )
74 { 74 {
75 m_animDelay = MS2TICKS(BALL_ANIM_DELAY); 75 m_animDelay = MS2TICKS(BALL_ANIM_DELAY);
76 int frameNum = frame(); 76 int frameNum = frame();
77 frameNum++; 77 frameNum++;
78 if ( frameNum>=frameCount() ) 78 if ( frameNum>=frameCount() )
79 frameNum = 0; 79 frameNum = 0;
80 setFrame( frameNum ); 80 setFrame( frameNum );
81 } 81 }
82} 82}
83 83
84void Ball::advance(int stage) 84void Ball::advance(int stage)
85{ 85{
86 bool reflectX = false; 86 bool reflectX = false;
87 bool reflectY = false; 87 bool reflectY = false;
88 88
89 // check for collisions 89 // check for collisions
90 if ( collide(xVelocity(), 0) ) reflectX = true; 90 if ( collide(xVelocity(), 0) ) reflectX = true;
91 if ( collide(0, yVelocity()) ) reflectY = true; 91 if ( collide(0, yVelocity()) ) reflectY = true;
92 if ( !reflectX && !reflectY && collide(xVelocity(), yVelocity()) ) reflectX = reflectY = true; 92 if ( !reflectX && !reflectY && collide(xVelocity(), yVelocity()) ) reflectX = reflectY = true;
93 93
94 // emit collision 94 // emit collision
95 QRect r = boundingRect(); 95 QRect r = boundingRect();
96 r.moveBy( xVelocity(), yVelocity() ); 96 r.moveBy( xVelocity(), yVelocity() );
97 JezzField* field = (JezzField *)canvas(); 97 JezzField* field = (JezzField *)canvas();
98 98
99 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE ); 99 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
100 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE ); 100 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
101 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE ); 101 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
102 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE ); 102 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
103 103
104 if ( ul!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.top() / TILE_SIZE, ul ); else 104 if ( ul!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.top() / TILE_SIZE, ul ); else
105 if ( ur!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.top() / TILE_SIZE, ur ); else 105 if ( ur!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.top() / TILE_SIZE, ur ); else
106 if ( bl!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.bottom() / TILE_SIZE, bl ); else 106 if ( bl!=TILE_FREE ) field->emitBallCollisiton( this, r.left() / TILE_SIZE, r.bottom() / TILE_SIZE, bl ); else
107 if ( br!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.bottom() / TILE_SIZE, br ); 107 if ( br!=TILE_FREE ) field->emitBallCollisiton( this, r.right() / TILE_SIZE, r.bottom() / TILE_SIZE, br );
108 108
109 // apply reflection 109 // apply reflection
110 if ( reflectX ) setXVelocity( -xVelocity() ); 110 if ( reflectX ) setXVelocity( -xVelocity() );
111 if ( reflectY ) setYVelocity( -yVelocity() ); 111 if ( reflectY ) setYVelocity( -yVelocity() );
112 112
113 // update field 113 // update field
114 update(); 114 update();
115 QCanvasSprite::advance( stage ); 115 QCanvasSprite::advance( stage );
116} 116}
117 117
118bool Ball::collide( double dx, double dy ) 118bool Ball::collide( double dx, double dy )
119{ 119{
120 QRect r = boundingRect(); 120 QRect r = boundingRect();
121 r.moveBy( dx, dy ); 121 r.moveBy( dx, dy );
122 JezzField* field = (JezzField *)canvas(); 122 JezzField* field = (JezzField *)canvas();
123 123
124 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE ); 124 int ul = field->tile( r.left() / TILE_SIZE, r.top() / TILE_SIZE );
125 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE ); 125 int ur = field->tile( r.right() / TILE_SIZE, r.top() / TILE_SIZE );
126 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE ); 126 int bl = field->tile( r.left() / TILE_SIZE, r.bottom() / TILE_SIZE );
127 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE ); 127 int br = field->tile( r.right() / TILE_SIZE, r.bottom() / TILE_SIZE );
128 128
129 return ( ul!=TILE_FREE || ur!=TILE_FREE || bl!=TILE_FREE || br!=TILE_FREE ); 129 return ( ul!=TILE_FREE || ur!=TILE_FREE || bl!=TILE_FREE || br!=TILE_FREE );
130} 130}
131 131
132/*************************************************************************/ 132/*************************************************************************/
133 133
134Wall::Wall( JezzField *field, int x, int y, Direction dir, int tile, QObject *parent, const char *name ) 134Wall::Wall( JezzField *field, int x, int y, Direction dir, int tile, QObject *parent, const char *name )
135 : QObject( parent, name ), m_dir( dir ), m_field( field ), m_startX( x ), m_startY( y ), 135 : QObject( parent, name ), m_dir( dir ), m_field( field ), m_startX( x ), m_startY( y ),
136 m_tile( tile ), m_delay( MS2TICKS(WALL_DELAY)/2 ), m_active( true ) 136 m_tile( tile ), m_delay( MS2TICKS(WALL_DELAY)/2 ), m_active( true )
137{ 137{
138 // setup position and direction 138 // setup position and direction
139 m_dx = 0; 139 m_dx = 0;
140 m_dy = 0; 140 m_dy = 0;
141 switch ( m_dir ) 141 switch ( m_dir )
142 { 142 {
143 case Up: m_dy = -1; break; 143 case Up: m_dy = -1; break;
144 case Down: m_dy = 1; break; 144 case Down: m_dy = 1; break;
145 case Left: m_dx = -1; break; 145 case Left: m_dx = -1; break;
146 case Right: m_dx = 1; break; 146 case Right: m_dx = 1; break;
147 } 147 }
148 148
149 m_x = m_startX; 149 m_x = m_startX;
150 m_y = m_startY; 150 m_y = m_startY;
151 151
152 m_field->setTile( m_x, m_y, m_tile ); 152 m_field->setTile( m_x, m_y, m_tile );
153} 153}
154 154
155void Wall::finish() 155void Wall::finish()
156{ 156{
157 m_active = false; 157 m_active = false;
158} 158}
159 159
160bool Wall::isFree( int x, int y ) 160bool Wall::isFree( int x, int y )
161{ 161{
162 if ( m_field->tile(x, y)==TILE_FREE ) 162 if ( m_field->tile(x, y)==TILE_FREE )
163 { 163 {
164 // check whether there is a ball at the moment 164 // check whether there is a ball at the moment
165 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, 165 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE,
166 TILE_SIZE, TILE_SIZE) ); 166 TILE_SIZE, TILE_SIZE) );
167 if ( cols.count()==0 ) 167 if ( cols.count()==0 )
168 return true; 168 return true;
169 } 169 }
170 170
171 return false; 171 return false;
172} 172}
173 173
174void Wall::update() 174void Wall::update()
175{ 175{
176} 176}
177 177
178void Wall::advance() 178void Wall::advance()
179{ 179{
180 update(); 180 update();
181 181
182 // move wall 182 // move wall
183 if ( m_active ) 183 if ( m_active )
184 { 184 {
185 m_delay--; 185 m_delay--;
186 if ( m_delay<=0 ) 186 if ( m_delay<=0 )
187 { 187 {
188 m_delay = MS2TICKS(WALL_DELAY); 188 m_delay = MS2TICKS(WALL_DELAY);
189 189
190 // set previous tile 190 // set previous tile
191 m_field->setTile( m_x, m_y, m_tile ); 191 m_field->setTile( m_x, m_y, m_tile );
192 192
193 // check whether next place is still free 193 // check whether next place is still free
194 if ( isFree(m_x+m_dx, m_y+m_dy) ) 194 if ( isFree(m_x+m_dx, m_y+m_dy) )
195 { 195 {
196 // move ball 196 // move ball
197 m_x += m_dx; 197 m_x += m_dx;
198 m_y += m_dy; 198 m_y += m_dy;
199 199
200 // set tile 200 // set tile
201 m_field->setTile( m_x, m_y, TILE_WALLEND ); 201 m_field->setTile( m_x, m_y, TILE_WALLEND );
202 } else 202 } else
203 { 203 {
204 finish(); 204 finish();
205 emit finished( this, m_field->tile( m_x+m_dx, m_y+m_dy ) ); 205 emit finished( this, m_field->tile( m_x+m_dx, m_y+m_dy ) );
206 } 206 }
207 } 207 }
208 } 208 }
209} 209}
210 210
211void Wall::fill( bool black ) 211void Wall::fill( bool black )
212{ 212{
213 if ( m_dx ) 213 if ( m_dx )
214 { 214 {
215 for ( int x=m_startX ; x!=m_x; x+=m_dx ) 215 for ( int x=m_startX ; x!=m_x; x+=m_dx )
216 if ( m_field->tile(x, m_startY)==m_tile ) 216 if ( m_field->tile(x, m_startY)==m_tile )
217 m_field->setGameTile( x, m_startY, black ); 217 m_field->setGameTile( x, m_startY, black );
218 218
219 m_field->setGameTile( m_x, m_startY, black ); 219 m_field->setGameTile( m_x, m_startY, black );
220 } else 220 } else
221 { 221 {
222 for ( int y=m_startY ; y!=m_y; y+=m_dy ) 222 for ( int y=m_startY ; y!=m_y; y+=m_dy )
223 if ( m_field->tile(m_startX, y)==m_tile ) 223 if ( m_field->tile(m_startX, y)==m_tile )
224 m_field->setGameTile( m_startX, y, black ); 224 m_field->setGameTile( m_startX, y, black );
225 225
226 m_field->setGameTile( m_startX, m_y, black ); 226 m_field->setGameTile( m_startX, m_y, black );
227 } 227 }
228} 228}
229 229
230/*************************************************************************/ 230/*************************************************************************/
231 231
232JezzField::JezzField( QPixmap tiles, QObject* parent, const char* name ) 232JezzField::JezzField( QPixmap tiles, QObject* parent, const char* name )
233 : QCanvas( parent, name ), m_tiles( tiles ) 233 : QCanvas( parent, name ), m_tiles( tiles )
234{ 234{
235 setPixmaps( tiles ); 235 setPixmaps( tiles );
236} 236}
237 237
238void JezzField::setGameTile( int x, int y, bool black ) 238void JezzField::setGameTile( int x, int y, bool black )
239{ 239{
240 setTile( x, y, black ? TILE_BORDER : TILE_FREE ); 240 setTile( x, y, black ? TILE_BORDER : TILE_FREE );
241} 241}
242 242
243void JezzField::setPixmaps( QPixmap tiles ) 243void JezzField::setPixmaps( QPixmap tiles )
244{ 244{
245 // create new tiles 245 // create new tiles
246 QPixmap allTiles( TILE_SIZE*(FIELD_WIDTH-2), TILE_SIZE*(FIELD_HEIGHT-1) ); 246 QPixmap allTiles( TILE_SIZE*(FIELD_WIDTH-2), TILE_SIZE*(FIELD_HEIGHT-1) );
247 247
248 // handle default tiles 248 // handle default tiles
249 bitBlt( &allTiles, 0, TILE_SIZE*(FIELD_HEIGHT-2), 249 bitBlt( &allTiles, 0, TILE_SIZE*(FIELD_HEIGHT-2),
250 &tiles, 0, 0, tiles.width(), tiles.height() ); 250 &tiles, 0, 0, tiles.width(), tiles.height() );
251 251
252 // load tiles into canvas 252 // load tiles into canvas
253 setTiles( allTiles, FIELD_WIDTH, FIELD_HEIGHT, TILE_SIZE, TILE_SIZE ); 253 setTiles( allTiles, FIELD_WIDTH, FIELD_HEIGHT, TILE_SIZE, TILE_SIZE );
254} 254}
255 255
256/*************************************************************************/ 256/*************************************************************************/
257 257
258JezzView::JezzView(QCanvas* viewing, QWidget* parent, const char* name, WFlags f) 258JezzView::JezzView(QCanvas* viewing, QWidget* parent, const char* name, WFlags f)
259 : QCanvasView( viewing, parent, name, f ), m_vertical( false ) 259 : QCanvasView( viewing, parent, name, f ), m_vertical( false )
260{ 260{
261 setResizePolicy( AutoOne ); 261 setResizePolicy( AutoOne );
262 setHScrollBarMode( AlwaysOff ); 262 setHScrollBarMode( AlwaysOff );
263 setVScrollBarMode( AlwaysOff ); 263 setVScrollBarMode( AlwaysOff );
264 264
265 setCursor( sizeHorCursor ); 265 setCursor( sizeHorCursor );
266} 266}
267 267
268void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev ) 268void JezzView::viewportMouseReleaseEvent( QMouseEvent *ev )
269{ 269{
270 if ( ev->button() & LeftButton ) 270 if ( ev->button() & LeftButton )
271 { 271 {
272 emit buildWall( ev->x()/TILE_SIZE, ev->y()/TILE_SIZE, m_vertical ); 272 emit buildWall( ev->x()/TILE_SIZE, ev->y()/TILE_SIZE, m_vertical );
273 } 273 }
274} 274}
275 275
276void JezzView::changeCursor() 276void JezzView::changeCursor()
277{ 277{
278 m_vertical = !m_vertical; 278 m_vertical = !m_vertical;
279 if ( m_vertical ) 279 if ( m_vertical )
280 { 280 {
281 setCursor( sizeVerCursor ); 281 setCursor( sizeVerCursor );
282 } 282 }
283 else 283 else
284 { 284 {
285 setCursor( sizeHorCursor ); 285 setCursor( sizeHorCursor );
286 } 286 }
287} 287}
288 288
289/*************************************************************************/ 289/*************************************************************************/
290 290
291JezzGame::JezzGame( int ballNum, QWidget *parent, const char *name ) 291JezzGame::JezzGame( int ballNum, QWidget *parent, const char *name )
292 : QWidget( parent, name ), m_wall1( 0 ), m_wall2( 0 ), 292 : QWidget( parent, name ), m_wall1( 0 ), m_wall2( 0 ),
293 m_text( 0 ), m_running( false ), m_percent( 0 ), m_pictured( false ) 293 m_text( 0 ), m_running( false ), m_percent( 0 ), m_pictured( false )
294{ 294{
295 QString path = QPEApplication::qpeDir()+"pics/bounce/"; 295 QString path = QPEApplication::qpeDir()+"pics/bounce/";
296 296
297 // load gfx 297 // load gfx
298 m_ballPixmaps = new QCanvasPixmapArray( path + "ball%1.png", 25 ); 298 m_ballPixmaps = new QCanvasPixmapArray( path + "ball%1.png", 25 );
299 for ( unsigned n=0; n < m_ballPixmaps->count(); n++ ) 299 for ( unsigned n=0; n < m_ballPixmaps->count(); n++ )
300 m_ballPixmaps->image(n)->setOffset( 0, 0 ); 300 m_ballPixmaps->image(n)->setOffset( 0, 0 );
301 301
302 m_arrowPixmaps = new QCanvasPixmapArray( path + "arrow%1.png", 2 ); 302 m_arrowPixmaps = new QCanvasPixmapArray( path + "arrow%1.png", 2 );
303 for ( unsigned n=0; n < m_arrowPixmaps->count(); n++ ) 303 for ( unsigned n=0; n < m_arrowPixmaps->count(); n++ )
304 m_arrowPixmaps->image(n)->setOffset( 0, 0 ); 304 m_arrowPixmaps->image(n)->setOffset( 0, 0 );
305 305
306 QPixmap tiles( path + "tiles.png" ); 306 QPixmap tiles( path + "tiles.png" );
307 307
308 // create field 308 // create field
309 m_field = new JezzField( tiles, this, "m_field" ); 309 m_field = new JezzField( tiles, this, "m_field" );
310 m_field->resize( TILE_SIZE*FIELD_WIDTH, TILE_SIZE*FIELD_HEIGHT ); 310 m_field->resize( TILE_SIZE*FIELD_WIDTH, TILE_SIZE*FIELD_HEIGHT );
311 311
312 for ( int x=0; x<FIELD_WIDTH; x++ ) 312 for ( int x=0; x<FIELD_WIDTH; x++ )
313 m_field->setTile( x, 0, TILE_BORDER ); 313 m_field->setTile( x, 0, TILE_BORDER );
314 for ( int y=1; y<FIELD_HEIGHT-1; y++ ) 314 for ( int y=1; y<FIELD_HEIGHT-1; y++ )
315 { 315 {
316 m_field->setTile( 0, y, TILE_BORDER ); 316 m_field->setTile( 0, y, TILE_BORDER );
317 for ( int x=1; x<FIELD_WIDTH-1; x++ ) 317 for ( int x=1; x<FIELD_WIDTH-1; x++ )
318 m_field->setTile( x, y, TILE_FREE ); 318 m_field->setTile( x, y, TILE_FREE );
319 m_field->setTile( FIELD_WIDTH-1, y, TILE_BORDER ); 319 m_field->setTile( FIELD_WIDTH-1, y, TILE_BORDER );
320 } 320 }
321 for ( int x=0; x<FIELD_WIDTH; x++ ) 321 for ( int x=0; x<FIELD_WIDTH; x++ )
322 m_field->setTile( x, FIELD_HEIGHT-1, TILE_BORDER ); 322 m_field->setTile( x, FIELD_HEIGHT-1, TILE_BORDER );
323 323
324 connect( m_field, SIGNAL(ballCollision(Ball *, int, int, int)), this, SLOT(ballCollision(Ball *, int, int, int)) ); 324 connect( m_field, SIGNAL(ballCollision(Ball*,int,int,int)), this, SLOT(ballCollision(Ball*,int,int,int)) );
325 325
326 // create view 326 // create view
327 m_view = new JezzView( m_field, this, "m_view" ); 327 m_view = new JezzView( m_field, this, "m_view" );
328 m_view->move( 0, 0 ); 328 m_view->move( 0, 0 );
329 m_view->adjustSize(); 329 m_view->adjustSize();
330 connect( m_view, SIGNAL(buildWall(int, int, bool)), this, SLOT(buildWall(int, int, bool)) ); 330 connect( m_view, SIGNAL(buildWall(int,int,bool)), this, SLOT(buildWall(int,int,bool)) );
331 331
332 // create balls 332 // create balls
333 for ( int n=0; n<ballNum; n++ ) 333 for ( int n=0; n<ballNum; n++ )
334 { 334 {
335 Ball *ball = new Ball( m_ballPixmaps, m_field ); 335 Ball *ball = new Ball( m_ballPixmaps, m_field );
336 m_balls.append( ball ); 336 m_balls.append( ball );
337 ball->setVelocity( ((rand() & 1)*2-1)*2, ((rand() & 1)*2-1)*2 ); 337 ball->setVelocity( ((rand() & 1)*2-1)*2, ((rand() & 1)*2-1)*2 );
338 ball->setFrame( rand() % 25 ); 338 ball->setFrame( rand() % 25 );
339 ball->move( 4*TILE_SIZE + ( rand() - 50 ) % ( (FIELD_WIDTH-8)*TILE_SIZE ), 339 ball->move( 4*TILE_SIZE + ( rand() - 50 ) % ( (FIELD_WIDTH-8)*TILE_SIZE ),
340 4*TILE_SIZE + rand() % ( (FIELD_HEIGHT-8)*TILE_SIZE ) ); 340 4*TILE_SIZE + rand() % ( (FIELD_HEIGHT-8)*TILE_SIZE ) );
341 ball->show(); 341 ball->show();
342 } 342 }
343 343
344 // create arrow 344 // create arrow
345 arrow = new Arrow( m_arrowPixmaps, m_field ); 345 arrow = new Arrow( m_arrowPixmaps, m_field );
346 arrow->show(); 346 arrow->show();
347 347
348 // create text label 348 // create text label
349 m_text = new QCanvasText( m_field ); 349 m_text = new QCanvasText( m_field );
350 350
351 // create game clock 351 // create game clock
352 m_clock = new QTimer( this ); 352 m_clock = new QTimer( this );
353 connect( m_clock, SIGNAL(timeout()), this, SLOT(tick()) ); 353 connect( m_clock, SIGNAL(timeout()), this, SLOT(tick()) );
354 m_clock->start( GAME_DELAY ); 354 m_clock->start( GAME_DELAY );
355 355
356 // setup geometry 356 // setup geometry
357 setFixedSize( m_view->size() ); 357 setFixedSize( m_view->size() );
358} 358}
359 359
360JezzGame::~JezzGame() 360JezzGame::~JezzGame()
361{ 361{
362 m_balls.clear(); 362 m_balls.clear();
363 delete m_view; 363 delete m_view;
364 delete m_field; 364 delete m_field;
365 delete m_ballPixmaps; 365 delete m_ballPixmaps;
366} 366}
367 367
368void JezzGame::display( QString text, int size ) 368void JezzGame::display( QString text, int size )
369{ 369{
370 qDebug("This function \"display\" shouldn't be called!!!"); 370 qDebug("This function \"display\" shouldn't be called!!!");
371 if ( !text.isEmpty() ) 371 if ( !text.isEmpty() )
372 { 372 {
373 QFont font( "Helvetica", size, QFont::Bold ); 373 QFont font( "Helvetica", size, QFont::Bold );
374 font.setStyleHint( QFont::Helvetica ); 374 font.setStyleHint( QFont::Helvetica );
375 m_text->setFont( font ); 375 m_text->setFont( font );
376 m_text->setText( text ); 376 m_text->setText( text );
377 377
378 QRect size = m_text->boundingRect(); 378 QRect size = m_text->boundingRect();
379 m_text->move( ( FIELD_WIDTH*TILE_SIZE - size.width() ) / 2, 379 m_text->move( ( FIELD_WIDTH*TILE_SIZE - size.width() ) / 2,
380 ( FIELD_HEIGHT*TILE_SIZE - size.height() ) / 2 ); 380 ( FIELD_HEIGHT*TILE_SIZE - size.height() ) / 2 );
381 381
382 m_text->show(); 382 m_text->show();
383 } else 383 } else
384 { 384 {
385 m_text->hide(); 385 m_text->hide();
386 } 386 }
387} 387}
388 388
389void JezzGame::start() 389void JezzGame::start()
390{ 390{
391 m_running = true; 391 m_running = true;
392} 392}
393 393
394void JezzGame::stop() 394void JezzGame::stop()
395{ 395{
396 m_running = false; 396 m_running = false;
397} 397}
398 398
399 399
400void JezzGame::makeBlack() 400void JezzGame::makeBlack()
401{ 401{
402 // copy current field into buffer 402 // copy current field into buffer
403 for ( int y=0; y<FIELD_HEIGHT; y++ ) 403 for ( int y=0; y<FIELD_HEIGHT; y++ )
404 for ( int x=0; x<FIELD_WIDTH; x++ ) 404 for ( int x=0; x<FIELD_WIDTH; x++ )
405 m_buf[x][y] = m_field->tile( x, y ); 405 m_buf[x][y] = m_field->tile( x, y );
406 406
407 // fill areas that contains a ball 407 // fill areas that contains a ball
408 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() ) 408 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
409 fill( ball->x()/TILE_SIZE, ball->y()/TILE_SIZE ); 409 fill( ball->x()/TILE_SIZE, ball->y()/TILE_SIZE );
410 410
411 // areas still free can be blacked now 411 // areas still free can be blacked now
412 for ( int y=0; y<FIELD_HEIGHT; y++ ) 412 for ( int y=0; y<FIELD_HEIGHT; y++ )
413 for ( int x=0; x<FIELD_WIDTH; x++ ) 413 for ( int x=0; x<FIELD_WIDTH; x++ )
414 { 414 {
415 if ( m_buf[x][y]==TILE_FREE ) 415 if ( m_buf[x][y]==TILE_FREE )
416 m_field->setGameTile( x, y, true ); 416 m_field->setGameTile( x, y, true );
417 } 417 }
418 418
419 m_field->update(); 419 m_field->update();
420 m_view->repaint(); 420 m_view->repaint();
421 421
422 // count percent value of occupied area 422 // count percent value of occupied area
423 int p = percent(); 423 int p = percent();
424 if ( p!=m_percent ) 424 if ( p!=m_percent )
425 { 425 {
426 m_percent = p; 426 m_percent = p;
427 emit newPercent( m_percent ); 427 emit newPercent( m_percent );
428 } 428 }
429} 429}
430 430
431int JezzGame::percent() 431int JezzGame::percent()
432{ 432{
433 int notFree = 0; 433 int notFree = 0;
434 for ( int y=1; y<FIELD_HEIGHT-1; y++ ) 434 for ( int y=1; y<FIELD_HEIGHT-1; y++ )
435 for ( int x=1; x<FIELD_WIDTH-1; x++ ) 435 for ( int x=1; x<FIELD_WIDTH-1; x++ )
436 { 436 {
437 if ( m_field->tile(x,y)!=TILE_FREE ) 437 if ( m_field->tile(x,y)!=TILE_FREE )
438 notFree++; 438 notFree++;
439 } 439 }
440 440
441 return 100 * notFree / ( (FIELD_WIDTH-1) * (FIELD_HEIGHT-1) ); 441 return 100 * notFree / ( (FIELD_WIDTH-1) * (FIELD_HEIGHT-1) );
442} 442}
443 443
444void JezzGame::fill( int x, int y ) 444void JezzGame::fill( int x, int y )
445{ 445{
446 if ( m_buf[x][y]!=TILE_FREE) return; 446 if ( m_buf[x][y]!=TILE_FREE) return;
447 447
448 // go left 448 // go left
449 int _x=x; 449 int _x=x;
450 for ( ; m_buf[_x][y]==TILE_FREE; _x-- ) 450 for ( ; m_buf[_x][y]==TILE_FREE; _x-- )
451 m_buf[_x][y] = TILE_BORDER; 451 m_buf[_x][y] = TILE_BORDER;
452 int stopx = _x; 452 int stopx = _x;
453 453
454 // fill above 454 // fill above
455 for ( _x=x; _x>stopx; _x-- ) 455 for ( _x=x; _x>stopx; _x-- )
456 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 ); 456 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
457 457
458 // fill below 458 // fill below
459 for ( _x=x; _x>stopx; _x-- ) 459 for ( _x=x; _x>stopx; _x-- )
460 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 ); 460 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
461 461
462 // go right 462 // go right
463 for ( _x=x+1; m_buf[_x][y]==TILE_FREE; _x++ ) 463 for ( _x=x+1; m_buf[_x][y]==TILE_FREE; _x++ )
464 m_buf[_x][y] = TILE_BORDER; 464 m_buf[_x][y] = TILE_BORDER;
465 stopx = _x; 465 stopx = _x;
466 466
467 // fill above 467 // fill above
468 for ( _x=x+1; _x<stopx; _x++ ) 468 for ( _x=x+1; _x<stopx; _x++ )
469 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 ); 469 if ( m_buf[_x][y-1]==TILE_FREE ) fill( _x, y-1 );
470 470
471 // fill below; 471 // fill below;
472 for ( _x=x+1; _x<stopx; _x++ ) 472 for ( _x=x+1; _x<stopx; _x++ )
473 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 ); 473 if ( m_buf[_x][y+1]==TILE_FREE ) fill( _x, y+1 );
474} 474}
475 475
476void JezzGame::ballCollision( Ball*, int, int, int tile ) 476void JezzGame::ballCollision( Ball*, int, int, int tile )
477{ 477{
478 if ( tile!=TILE_BORDER && tile>TILE_FREE && tile!=TILE_WALLEND ) 478 if ( tile!=TILE_BORDER && tile>TILE_FREE && tile!=TILE_WALLEND )
479 { 479 {
480 // stop walls 480 // stop walls
481 if ( (tile==TILE_WALLUP || tile==TILE_WALLLEFT) && m_wall1 ) 481 if ( (tile==TILE_WALLUP || tile==TILE_WALLLEFT) && m_wall1 )
482 { 482 {
483 m_wall1->finish(); 483 m_wall1->finish();
484 m_wall1->fill( false ); 484 m_wall1->fill( false );
485 delete m_wall1; 485 delete m_wall1;
486 m_wall1 = 0; 486 m_wall1 = 0;
487 } 487 }
488 488
489 if ( (tile==TILE_WALLDOWN || tile==TILE_WALLRIGHT) && m_wall2 ) 489 if ( (tile==TILE_WALLDOWN || tile==TILE_WALLRIGHT) && m_wall2 )
490 { 490 {
491 m_wall2->finish(); 491 m_wall2->finish();
492 m_wall2->fill( false ); 492 m_wall2->fill( false );
493 delete m_wall2; 493 delete m_wall2;
494 m_wall2 = 0; 494 m_wall2 = 0;
495 } 495 }
496 496
497 // update view 497 // update view
498 m_field->update(); 498 m_field->update();
499 m_view->repaint(); 499 m_view->repaint();
500 500
501 // send death msg 501 // send death msg
502 emit died(); 502 emit died();
503 } 503 }
504} 504}
505 505
506void JezzGame::buildWall( int x, int y, bool vertical ) 506void JezzGame::buildWall( int x, int y, bool vertical )
507{ 507{
508 if ( !m_running ) return; 508 if ( !m_running ) return;
509 509
510 if ( m_field->tile(x, y)==TILE_FREE ) 510 if ( m_field->tile(x, y)==TILE_FREE )
511 { 511 {
512 // check whether there is a ball at the moment 512 // check whether there is a ball at the moment
513 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE) ); 513 QCanvasItemList cols = m_field->collisions( QRect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE) );
514 if ( cols.count()>0 ) 514 if ( cols.count()>0 )
515 { 515 {
516 //kdDebug() << "Direct collision" << endl; 516 //kdDebug() << "Direct collision" << endl;
517 emit ballCollision( (Ball*)cols.first(), x, y, TILE_WALLUP ); 517 emit ballCollision( (Ball*)cols.first(), x, y, TILE_WALLUP );
518 return; 518 return;
519 } 519 }
520 520
521 // start walls 521 // start walls
522 if ( !m_wall1 ) 522 if ( !m_wall1 )
523 { 523 {
524 m_wall1 = new Wall( m_field, x, y, 524 m_wall1 = new Wall( m_field, x, y,
525 vertical? Wall::Up : Wall::Left, 525 vertical? Wall::Up : Wall::Left,
526 vertical? TILE_WALLUP : TILE_WALLLEFT, 526 vertical? TILE_WALLUP : TILE_WALLLEFT,
527 this, "m_wall1" ); 527 this, "m_wall1" );
528 connect( m_wall1, SIGNAL(finished(Wall *, int)), 528 connect( m_wall1, SIGNAL(finished(Wall*,int)),
529 this, SLOT(wallFinished(Wall *, int)) ); } 529 this, SLOT(wallFinished(Wall*,int)) ); }
530 530
531 if ( !m_wall2 ) 531 if ( !m_wall2 )
532 { 532 {
533 m_wall2 = new Wall( m_field, x, y, 533 m_wall2 = new Wall( m_field, x, y,
534 vertical? Wall::Down: Wall::Right, 534 vertical? Wall::Down: Wall::Right,
535 vertical? TILE_WALLDOWN : TILE_WALLRIGHT, 535 vertical? TILE_WALLDOWN : TILE_WALLRIGHT,
536 this, "m_wall2" ); 536 this, "m_wall2" );
537 connect( m_wall2, SIGNAL(finished(Wall *, int)), 537 connect( m_wall2, SIGNAL(finished(Wall*,int)),
538 this, SLOT(wallFinished(Wall *, int)) ); 538 this, SLOT(wallFinished(Wall*,int)) );
539 } 539 }
540 } 540 }
541} 541}
542 542
543void JezzGame::wallFinished( Wall *wall, int tile ) 543void JezzGame::wallFinished( Wall *wall, int tile )
544{ 544{
545 if ( tile==TILE_WALLEND ) 545 if ( tile==TILE_WALLEND )
546 { 546 {
547 if ( m_wall1 ) 547 if ( m_wall1 )
548 { 548 {
549 m_wall1->fill( false ); 549 m_wall1->fill( false );
550 delete m_wall1; 550 delete m_wall1;
551 m_wall1 = 0; 551 m_wall1 = 0;
552 } 552 }
553 553
554 if ( m_wall2 ) 554 if ( m_wall2 )
555 { 555 {
556 m_wall2->fill( false ); 556 m_wall2->fill( false );
557 delete m_wall2; 557 delete m_wall2;
558 m_wall2 = 0; 558 m_wall2 = 0;
559 } 559 }
560 } else 560 } else
561 { 561 {
562 if ( m_wall1==wall && m_wall1 ) 562 if ( m_wall1==wall && m_wall1 )
563 { 563 {
564 m_wall1->fill( true ); 564 m_wall1->fill( true );
565 delete m_wall1; 565 delete m_wall1;
566 m_wall1 = 0; 566 m_wall1 = 0;
567 } 567 }
568 568
569 if ( m_wall2==wall && m_wall2 ) 569 if ( m_wall2==wall && m_wall2 )
570 { 570 {
571 m_wall2->fill( true ); 571 m_wall2->fill( true );
572 delete m_wall2; 572 delete m_wall2;
573 m_wall2 = 0; 573 m_wall2 = 0;
574 } 574 }
575 } 575 }
576 576
577 m_field->update(); 577 m_field->update();
578 m_view->repaint(); 578 m_view->repaint();
579 579
580 makeBlack(); 580 makeBlack();
581} 581}
582 582
583void JezzGame::tick() 583void JezzGame::tick()
584{ 584{
585 if ( m_running ) 585 if ( m_running )
586 { 586 {
587 if ( m_field ) m_field->advance(); 587 if ( m_field ) m_field->advance();
588 if ( m_wall1 ) m_wall1->advance(); 588 if ( m_wall1 ) m_wall1->advance();
589 if ( m_wall2 ) m_wall2->advance(); 589 if ( m_wall2 ) m_wall2->advance();
590 } else 590 } else
591 { 591 {
592 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() ) 592 for ( Ball *ball=m_balls.first(); ball!=0; ball=m_balls.next() )
593 ball->update(); 593 ball->update();
594 594
595 if ( m_field ) m_field->update(); 595 if ( m_field ) m_field->update();
596 if ( m_wall1 ) m_wall1->update(); 596 if ( m_wall1 ) m_wall1->update();
597 if ( m_wall2 ) m_wall2->update(); 597 if ( m_wall2 ) m_wall2->update();
598 } 598 }
599} 599}
600 600
601void JezzGame::changeCursor() 601void JezzGame::changeCursor()
602{ 602{
603 arrow->changeDirection(); 603 arrow->changeDirection();
604 m_view->changeCursor(); 604 m_view->changeCursor();
605} 605}
diff --git a/noncore/games/buzzword/buzzword.cpp b/noncore/games/buzzword/buzzword.cpp
index 13eb481..b7f2573 100644
--- a/noncore/games/buzzword/buzzword.cpp
+++ b/noncore/games/buzzword/buzzword.cpp
@@ -1,181 +1,181 @@
1/* 1/*
2 * Copyright (C) 2002 Martin Imobersteg <imm@gmx.ch> 2 * Copyright (C) 2002 Martin Imobersteg <imm@gmx.ch>
3 * 3 *
4 * This program is free software; you can redistribute it and/or 4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public 5 * modify it under the terms of the GNU General Public
6 * License as published by the Free Software Foundation; either 6 * License as published by the Free Software Foundation; either
7 * version 2 of the License,Life or (at your option) any later version. 7 * version 2 of the License,Life or (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details. 12 * Library General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU Library General Public 14 * You should have received a copy of the GNU Library General Public
15 * License along with this program; if not, write to the Free 15 * License along with this program; if not, write to the Free
16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 16 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */ 17 */
18 18
19#include <qlayout.h> 19#include <qlayout.h>
20#include <qmainwindow.h> 20#include <qmainwindow.h>
21#include <qlabel.h> 21#include <qlabel.h>
22#include <qgrid.h> 22#include <qgrid.h>
23#include <qcolor.h> 23#include <qcolor.h>
24#include <qbutton.h> 24#include <qbutton.h>
25#include <qfile.h> 25#include <qfile.h>
26#include <qtextstream.h> 26#include <qtextstream.h>
27#include <qstringlist.h> 27#include <qstringlist.h>
28#include <qmessagebox.h> 28#include <qmessagebox.h>
29#include <qdir.h> 29#include <qdir.h>
30 30
31#include <math.h> 31#include <math.h>
32#include <stdlib.h> 32#include <stdlib.h>
33 33
34#include <qpe/qpeapplication.h> 34#include <qpe/qpeapplication.h>
35 35
36#include "buzzword.h" 36#include "buzzword.h"
37 37
38BuzzLabel::BuzzLabel( QWidget *parent, const char *name ) 38BuzzLabel::BuzzLabel( QWidget *parent, const char *name )
39: QLabel( parent, name ) 39: QLabel( parent, name )
40{ 40{
41} 41}
42 42
43void BuzzLabel::mousePressEvent(QMouseEvent *e) 43void BuzzLabel::mousePressEvent(QMouseEvent *e)
44{ 44{
45 if(e->button() == LeftButton) 45 if(e->button() == LeftButton)
46 { 46 {
47 emit clicked(); 47 emit clicked();
48 } 48 }
49} 49}
50 50
51BuzzItem::BuzzItem( int row, int column, QString text, QWidget *parent, const char *name ) 51BuzzItem::BuzzItem( int row, int column, QString text, QWidget *parent, const char *name )
52: QVBox( parent, name ), _row(row), _column(column) 52: QVBox( parent, name ), _row(row), _column(column)
53{ 53{
54 setFrameStyle( QFrame::Panel | QFrame::Raised ); 54 setFrameStyle( QFrame::Panel | QFrame::Raised );
55 setLineWidth( 1 ); 55 setLineWidth( 1 );
56 label = new BuzzLabel(this, "label"); 56 label = new BuzzLabel(this, "label");
57 label->setText(text); 57 label->setText(text);
58 label->setAlignment( int( QLabel::AlignCenter ) ); 58 label->setAlignment( int( QLabel::AlignCenter ) );
59 59
60 connect( label, SIGNAL(clicked()), this, SLOT(flip()) ); 60 connect( label, SIGNAL(clicked()), this, SLOT(flip()) );
61} 61}
62 62
63void BuzzItem::flip() 63void BuzzItem::flip()
64{ 64{
65 setLineWidth( 1 ); 65 setLineWidth( 1 );
66 label->setBackgroundColor(label->colorGroup().highlight()); 66 label->setBackgroundColor(label->colorGroup().highlight());
67 emit clicked(_row, _column); 67 emit clicked(_row, _column);
68} 68}
69 69
70BuzzWord::BuzzWord(QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) 70BuzzWord::BuzzWord(QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl )
71{ 71{
72 setCaption(tr("buZzword")); 72 setCaption(tr("buZzword"));
73 73
74 menu = menuBar(); 74 menu = menuBar();
75 game = new QPopupMenu; 75 game = new QPopupMenu;
76 game->insertItem(tr("&New game"), this, SLOT(newGame()), Key_N ); 76 game->insertItem(tr("&New game"), this, SLOT(newGame()), Key_N );
77 menu->insertItem( tr("&Game"), game ); 77 menu->insertItem( tr("&Game"), game );
78 78
79 gridVal = 4; 79 gridVal = 4;
80 grid = NULL; 80 grid = NULL;
81 gameOver = false; 81 gameOver = false;
82 newGame(); 82 newGame();
83} 83}
84 84
85void BuzzWord::drawGrid() 85void BuzzWord::drawGrid()
86{ 86{
87 QStringList l; 87 QStringList l;
88 88
89 QString path = QPEApplication::qpeDir()+"share/buzzword/"; 89 QString path = QPEApplication::qpeDir()+"share/buzzword/";
90 QFile f( path + "buzzwords" ); 90 QFile f( path + "buzzwords" );
91 if ( !f.open( IO_ReadOnly ) ) 91 if ( !f.open( IO_ReadOnly ) )
92 return; 92 return;
93 93
94 QTextStream t( &f ); 94 QTextStream t( &f );
95 95
96 while (!t.atEnd()) 96 while (!t.atEnd())
97 { 97 {
98 l << t.readLine(); 98 l << t.readLine();
99 } 99 }
100 100
101 f.close(); 101 f.close();
102 102
103 grid = new QGrid(gridVal, this); 103 grid = new QGrid(gridVal, this);
104 //grid->setFixedSize( 480, 480 ); 104 //grid->setFixedSize( 480, 480 );
105 105
106 for( int c = 0 ; c < gridVal ; c++ ) 106 for( int c = 0 ; c < gridVal ; c++ )
107 { 107 {
108 for( int r = 0 ; r < gridVal ; r++ ) 108 for( int r = 0 ; r < gridVal ; r++ )
109 { 109 {
110 uint pos = rand() % l. count(); 110 uint pos = rand() % l. count();
111 111
112 QString word = QStringList::split(" ", l[pos]).join("\n"); 112 QString word = QStringList::split(" ", l[pos]).join("\n");
113 BuzzItem* bi = new BuzzItem( c, r, word, grid ); 113 BuzzItem* bi = new BuzzItem( c, r, word, grid );
114 connect( bi, SIGNAL(clicked(int, int)), this, SLOT(clicked(int,int)) ); 114 connect( bi, SIGNAL(clicked(int,int)), this, SLOT(clicked(int,int)) );
115 map[c][r] = 0; 115 map[c][r] = 0;
116 116
117 l.remove( l.at( pos )); 117 l.remove( l.at( pos ));
118 } 118 }
119 } 119 }
120} 120}
121 121
122void BuzzWord::clicked(int row, int column) 122void BuzzWord::clicked(int row, int column)
123{ 123{
124 if ( ! gameOver ) 124 if ( ! gameOver )
125 { 125 {
126 int rowTotal = 0; 126 int rowTotal = 0;
127 int columnTotal = 0; 127 int columnTotal = 0;
128 128
129 map[column][row] = 1; 129 map[column][row] = 1;
130 130
131 for( int c = 0 ; c < gridVal ; c++ ) 131 for( int c = 0 ; c < gridVal ; c++ )
132 { 132 {
133 for( int r = 0 ; r < gridVal ; r++ ) 133 for( int r = 0 ; r < gridVal ; r++ )
134 { 134 {
135 if ( map[c][r] == 1 ) 135 if ( map[c][r] == 1 )
136 rowTotal++; 136 rowTotal++;
137 137
138 if ( rowTotal == 4 ) 138 if ( rowTotal == 4 )
139 { 139 {
140 bingo(); 140 bingo();
141 } 141 }
142 } 142 }
143 rowTotal = 0; 143 rowTotal = 0;
144 } 144 }
145 145
146 for( int r = 0 ; r < gridVal ; r++ ) 146 for( int r = 0 ; r < gridVal ; r++ )
147 { 147 {
148 for( int c = 0 ; c < gridVal ; c++ ) 148 for( int c = 0 ; c < gridVal ; c++ )
149 { 149 {
150 if ( map[c][r] == 1 ) 150 if ( map[c][r] == 1 )
151 columnTotal++; 151 columnTotal++;
152 152
153 if ( columnTotal == 4 ) 153 if ( columnTotal == 4 )
154 { 154 {
155 bingo(); 155 bingo();
156 } 156 }
157 } 157 }
158 columnTotal = 0; 158 columnTotal = 0;
159 } 159 }
160 160
161 if ( map[0][0] && map[1][1] && map[2][2] && map[3][3] ) 161 if ( map[0][0] && map[1][1] && map[2][2] && map[3][3] )
162 bingo(); 162 bingo();
163 163
164 if ( map[0][3] && map[1][2] && map[2][1] && map[3][0] ) 164 if ( map[0][3] && map[1][2] && map[2][1] && map[3][0] )
165 bingo(); 165 bingo();
166 } 166 }
167} 167}
168 168
169void BuzzWord::bingo() 169void BuzzWord::bingo()
170{ 170{
171 gameOver = true; 171 gameOver = true;
172 QMessageBox::information( this, "BUZZWORD", tr("<h1><b>BINGO !</b></h1>")); 172 QMessageBox::information( this, "BUZZWORD", tr("<h1><b>BINGO !</b></h1>"));
173} 173}
174 174
175void BuzzWord::newGame() 175void BuzzWord::newGame()
176{ 176{
177 gameOver = false; 177 gameOver = false;
178 delete grid; 178 delete grid;
179 drawGrid(); 179 drawGrid();
180 setCentralWidget(grid); 180 setCentralWidget(grid);
181} 181}
diff --git a/noncore/games/kpacman/kpacman.cpp b/noncore/games/kpacman/kpacman.cpp
index be2e46d..9820e5a 100644
--- a/noncore/games/kpacman/kpacman.cpp
+++ b/noncore/games/kpacman/kpacman.cpp
@@ -1,363 +1,363 @@
1 1
2#include "portable.h" 2#include "portable.h"
3 3
4#if defined( KDE2_PORT ) 4#if defined( KDE2_PORT )
5#include <kpacman.h> 5#include <kpacman.h>
6#include <kpacman.moc> 6#include <kpacman.moc>
7#include <kcolordlg.h> 7#include <kcolordlg.h>
8#elif defined( QPE_PORT ) 8#elif defined( QPE_PORT )
9#include <qmenubar.h> 9#include <qmenubar.h>
10#include <qpe/config.h> 10#include <qpe/config.h>
11#include <qapplication.h> 11#include <qapplication.h>
12#include "kpacman.h" 12#include "kpacman.h"
13#endif 13#endif
14 14
15 15
16Kpacman::Kpacman(QWidget *parent, const char *name) 16Kpacman::Kpacman(QWidget *parent, const char *name)
17 : KTMainWindow(parent, name) 17 : KTMainWindow(parent, name)
18{ 18{
19 schemesPopup = new QList<QPopupMenu>; 19 schemesPopup = new QList<QPopupMenu>;
20 schemesPopup->setAutoDelete(TRUE); 20 schemesPopup->setAutoDelete(TRUE);
21 21
22 menu(); 22 menu();
23 23
24 m_view = new QWidget( this, "m_view" ); 24 m_view = new QWidget( this, "m_view" );
25 m_view->setBackgroundColor( black ); 25 m_view->setBackgroundColor( black );
26 m_layout = new QGridLayout( m_view ); 26 m_layout = new QGridLayout( m_view );
27 m_layout->setMargin( 7 ); 27 m_layout->setMargin( 7 );
28 28
29 view = new KpacmanWidget( this, QString(name)+"widget"); 29 view = new KpacmanWidget( this, QString(name)+"widget");
30 m_layout->addWidget( view, 0, 0 ); 30 m_layout->addWidget( view, 0, 0 );
31 31
32 setCaption( tr("KPacman") ); 32 setCaption( tr("KPacman") );
33 33
34 view->referee->setFocus(); 34 view->referee->setFocus();
35 35
36 connect(view->referee, SIGNAL(setScore(int, int)), 36 connect(view->referee, SIGNAL(setScore(int,int)),
37 view->score, SLOT(setScore(int, int))); 37 view->score, SLOT(setScore(int,int)));
38 connect(view->referee, SIGNAL(setPoints(int)), 38 connect(view->referee, SIGNAL(setPoints(int)),
39 view->score, SLOT(set(int))); 39 view->score, SLOT(set(int)));
40 connect(view->referee, SIGNAL(setLifes(int)), 40 connect(view->referee, SIGNAL(setLifes(int)),
41 view->status, SLOT(setLifes(int))); 41 view->status, SLOT(setLifes(int)));
42 connect(view->referee, SIGNAL(setLevel(int)), 42 connect(view->referee, SIGNAL(setLevel(int)),
43 view->status, SLOT(setLevel(int))); 43 view->status, SLOT(setLevel(int)));
44 connect(view->referee, SIGNAL(forcedHallOfFame(bool)), 44 connect(view->referee, SIGNAL(forcedHallOfFame(bool)),
45 this, SLOT(forcedHallOfFame(bool))); 45 this, SLOT(forcedHallOfFame(bool)));
46 connect(view->referee, SIGNAL(togglePaused()), this, SLOT(togglePaused())); 46 connect(view->referee, SIGNAL(togglePaused()), this, SLOT(togglePaused()));
47 connect(view->referee, SIGNAL(toggleNew()), this, SLOT(toggleNew())); 47 connect(view->referee, SIGNAL(toggleNew()), this, SLOT(toggleNew()));
48 48
49 connect(view->score, SIGNAL(toggleNew()), this, SLOT(toggleNew())); 49 connect(view->score, SIGNAL(toggleNew()), this, SLOT(toggleNew()));
50 connect(view->score, SIGNAL(forcedHallOfFame(bool)), 50 connect(view->score, SIGNAL(forcedHallOfFame(bool)),
51 this, SLOT(forcedHallOfFame(bool))); 51 this, SLOT(forcedHallOfFame(bool)));
52 52
53 APP_CONFIG_BEGIN( cfg ); 53 APP_CONFIG_BEGIN( cfg );
54 focusOutPause = !cfg->readBoolEntry("FocusOutPause", TRUE); 54 focusOutPause = !cfg->readBoolEntry("FocusOutPause", TRUE);
55 focusInContinue = !cfg->readBoolEntry("FocusInContinue", TRUE); 55 focusInContinue = !cfg->readBoolEntry("FocusInContinue", TRUE);
56 hideMouseCursor = !cfg->readBoolEntry("HideMouseCursor", TRUE); 56 hideMouseCursor = !cfg->readBoolEntry("HideMouseCursor", TRUE);
57 APP_CONFIG_END( cfg ); 57 APP_CONFIG_END( cfg );
58 58
59 toggleFocusOutPause(); 59 toggleFocusOutPause();
60 toggleFocusInContinue(); 60 toggleFocusInContinue();
61 toggleHideMouseCursor(); 61 toggleHideMouseCursor();
62 62
63 setCentralWidget( m_view ); 63 setCentralWidget( m_view );
64} 64}
65 65
66Kpacman::~Kpacman() 66Kpacman::~Kpacman()
67{ 67{
68 /* APP_CONFIG_BEGIN( cfg ); 68 /* APP_CONFIG_BEGIN( cfg );
69 cfg->writeEntry("FocusOutPause", focusOutPause); 69 cfg->writeEntry("FocusOutPause", focusOutPause);
70 cfg->writeEntry("FocusInContinue", focusInContinue); 70 cfg->writeEntry("FocusInContinue", focusInContinue);
71 cfg->writeEntry("HideMouseCursor", hideMouseCursor); 71 cfg->writeEntry("HideMouseCursor", hideMouseCursor);
72 APP_CONFIG_END( cfg ); 72 APP_CONFIG_END( cfg );
73 */ 73 */
74 delete _menuBar; 74 delete _menuBar;
75} 75}
76 76
77void Kpacman::menu() 77void Kpacman::menu()
78{ 78{
79 gamePopup = new QPopupMenu(); 79 gamePopup = new QPopupMenu();
80 CHECK_PTR( gamePopup ); 80 CHECK_PTR( gamePopup );
81 newID = gamePopup->insertItem(tr("&New"), this, SLOT(newKpacman()),Key_F2); 81 newID = gamePopup->insertItem(tr("&New"), this, SLOT(newKpacman()),Key_F2);
82 pauseID = gamePopup->insertItem(tr("&Pause"), 82 pauseID = gamePopup->insertItem(tr("&Pause"),
83 this, SLOT(pauseKpacman()), Key_F3); 83 this, SLOT(pauseKpacman()), Key_F3);
84 hofID = gamePopup->insertItem(tr("&Hall of fame"), 84 hofID = gamePopup->insertItem(tr("&Hall of fame"),
85 this, SLOT(toggleHallOfFame()), Key_F4); 85 this, SLOT(toggleHallOfFame()), Key_F4);
86 gamePopup->insertSeparator(); 86 gamePopup->insertSeparator();
87 gamePopup->insertItem(tr("&Quit"), this, SLOT(quitKpacman()), CTRL+Key_Q); 87 gamePopup->insertItem(tr("&Quit"), this, SLOT(quitKpacman()), CTRL+Key_Q);
88 gamePopup->setCheckable(TRUE); 88 gamePopup->setCheckable(TRUE);
89 89
90 optionsPopup = new QPopupMenu(); 90 optionsPopup = new QPopupMenu();
91 CHECK_PTR(optionsPopup); 91 CHECK_PTR(optionsPopup);
92 92
93 modesPopup = new QPopupMenu(); 93 modesPopup = new QPopupMenu();
94 CHECK_PTR(modesPopup); 94 CHECK_PTR(modesPopup);
95 95
96 hideMouseCursorID = optionsPopup->insertItem(tr("&Hide Mousecursor"), 96 hideMouseCursorID = optionsPopup->insertItem(tr("&Hide Mousecursor"),
97 this, SLOT(toggleHideMouseCursor()), 97 this, SLOT(toggleHideMouseCursor()),
98 CTRL+Key_H); 98 CTRL+Key_H);
99 optionsPopup->insertSeparator(); 99 optionsPopup->insertSeparator();
100 100
101 if (lookupSchemes() > 0) { 101 if (lookupSchemes() > 0) {
102 optionsPopup->insertItem(tr("&Select graphic scheme"), modesPopup); 102 optionsPopup->insertItem(tr("&Select graphic scheme"), modesPopup);
103 optionsPopup->insertSeparator(); 103 optionsPopup->insertSeparator();
104 } 104 }
105 105
106 focusOutPauseID = optionsPopup->insertItem(tr("&Pause in Background"), 106 focusOutPauseID = optionsPopup->insertItem(tr("&Pause in Background"),
107 this, SLOT(toggleFocusOutPause())); 107 this, SLOT(toggleFocusOutPause()));
108 focusInContinueID = optionsPopup->insertItem(tr("&Continue in Foreground"), 108 focusInContinueID = optionsPopup->insertItem(tr("&Continue in Foreground"),
109 this, SLOT(toggleFocusInContinue())); 109 this, SLOT(toggleFocusInContinue()));
110 optionsPopup->insertSeparator(); 110 optionsPopup->insertSeparator();
111 111
112 optionsPopup->insertItem(tr("Change &keys..."), this, SLOT(confKeys())); 112 optionsPopup->insertItem(tr("Change &keys..."), this, SLOT(confKeys()));
113 113
114#ifndef QPE_PORT 114#ifndef QPE_PORT
115 QString aboutText = tr("@PACKAGE@ - @VERSION@\n\n" 115 QString aboutText = tr("@PACKAGE@ - @VERSION@\n\n"
116 "Joerg Thoennissen (joe@dsite.de)\n\n" 116 "Joerg Thoennissen (joe@dsite.de)\n\n"
117 "A pacman game for the KDE Desktop\n\n" 117 "A pacman game for the KDE Desktop\n\n"
118 "The program based on the source of ksnake\n" 118 "The program based on the source of ksnake\n"
119 "by Michel Filippi (mfilippi@sade.rhein-main.de).\n" 119 "by Michel Filippi (mfilippi@sade.rhein-main.de).\n"
120 "The design was strongly influenced by the pacman\n" 120 "The design was strongly influenced by the pacman\n"
121 "(c) 1980 MIDWAY MFG.CO.\n\n" 121 "(c) 1980 MIDWAY MFG.CO.\n\n"
122 "I like to thank my girlfriend Elke Krueers for\n" 122 "I like to thank my girlfriend Elke Krueers for\n"
123 "the last 10 years of her friendship.\n"); 123 "the last 10 years of her friendship.\n");
124 aboutText.replace(QRegExp("@PACKAGE@"), PACKAGE); 124 aboutText.replace(QRegExp("@PACKAGE@"), PACKAGE);
125 aboutText.replace(QRegExp("@VERSION@"), VERSION); 125 aboutText.replace(QRegExp("@VERSION@"), VERSION);
126 QPopupMenu *helpPopup = helpMenu(aboutText, FALSE); 126 QPopupMenu *helpPopup = helpMenu(aboutText, FALSE);
127#endif 127#endif
128 128
129 //_menuBar = new KMenuBar(this); 129 //_menuBar = new KMenuBar(this);
130 //CHECK_PTR( _menuBar ); 130 //CHECK_PTR( _menuBar );
131 //_menuBar->insertItem(tr("&Game"), gamePopup); 131 //_menuBar->insertItem(tr("&Game"), gamePopup);
132 //_menuBar->insertItem(tr("&Options"), optionsPopup); 132 //_menuBar->insertItem(tr("&Options"), optionsPopup);
133 //_menuBar->insertSeparator(); 133 //_menuBar->insertSeparator();
134#ifndef QPE_PORT 134#ifndef QPE_PORT
135 _menuBar->insertItem(tr("&Help"), helpPopup); 135 _menuBar->insertItem(tr("&Help"), helpPopup);
136#endif 136#endif
137} 137}
138 138
139int Kpacman::lookupSchemes() 139int Kpacman::lookupSchemes()
140{ 140{
141 APP_CONFIG_BEGIN( cfg ); 141 APP_CONFIG_BEGIN( cfg );
142 int ModeCount = cfg->readNumEntry("ModeCount", 0); 142 int ModeCount = cfg->readNumEntry("ModeCount", 0);
143 int Mode = cfg->readNumEntry("Mode", 0); 143 int Mode = cfg->readNumEntry("Mode", 0);
144 int SchemeCount = cfg->readNumEntry("SchemeCount", 0); 144 int SchemeCount = cfg->readNumEntry("SchemeCount", 0);
145 int Scheme = cfg->readNumEntry("Scheme", 0); 145 int Scheme = cfg->readNumEntry("Scheme", 0);
146 146
147 /* 147 /*
148 if (SchemeCount == 0 || Scheme == -1) { 148 if (SchemeCount == 0 || Scheme == -1) {
149 QMessageBox::warning(this, tr("Configuration Error"), 149 QMessageBox::warning(this, tr("Configuration Error"),
150 tr("There are no schemes defined,\n" 150 tr("There are no schemes defined,\n"
151 "or no scheme is selected.")); 151 "or no scheme is selected."));
152 APP_CONFIG_END( cfg ); 152 APP_CONFIG_END( cfg );
153 return 0; 153 return 0;
154 } 154 }
155 */ 155 */
156 156
157 connect(modesPopup, SIGNAL(activated(int)), this, SLOT(schemeChecked(int))); 157 connect(modesPopup, SIGNAL(activated(int)), this, SLOT(schemeChecked(int)));
158 modeID.resize(ModeCount > 0 ? ModeCount : 0); 158 modeID.resize(ModeCount > 0 ? ModeCount : 0);
159 159
160 if (!schemesPopup->isEmpty()) 160 if (!schemesPopup->isEmpty())
161 schemesPopup->clear(); 161 schemesPopup->clear();
162 162
163 SAVE_CONFIG_GROUP( cfg, oldgroup ); 163 SAVE_CONFIG_GROUP( cfg, oldgroup );
164 164
165 QString ModeGroup; 165 QString ModeGroup;
166 QString ModeName; 166 QString ModeName;
167 167
168 for (int m = 0; m < ModeCount; m++) { 168 for (int m = 0; m < ModeCount; m++) {
169 ModeGroup.sprintf("Mode %d", m); 169 ModeGroup.sprintf("Mode %d", m);
170 cfg->setGroup(ModeGroup); 170 cfg->setGroup(ModeGroup);
171 171
172 ModeName = cfg->readEntry("Description", ModeGroup); 172 ModeName = cfg->readEntry("Description", ModeGroup);
173 173
174 QPopupMenu *p = new QPopupMenu; 174 QPopupMenu *p = new QPopupMenu;
175 p->setCheckable(TRUE); 175 p->setCheckable(TRUE);
176 connect(p, SIGNAL(activated(int)), this, SLOT(schemeChecked(int))); 176 connect(p, SIGNAL(activated(int)), this, SLOT(schemeChecked(int)));
177 schemesPopup->append(p); 177 schemesPopup->append(p);
178 178
179 modeID[m] = modesPopup->insertItem(ModeName, schemesPopup->at(m)); 179 modeID[m] = modesPopup->insertItem(ModeName, schemesPopup->at(m));
180 modesPopup->setItemEnabled(modeID[m], FALSE); 180 modesPopup->setItemEnabled(modeID[m], FALSE);
181 modesPopup->setItemChecked(modeID[m], m == Mode); 181 modesPopup->setItemChecked(modeID[m], m == Mode);
182 } 182 }
183 183
184 schemeID.resize(SchemeCount); 184 schemeID.resize(SchemeCount);
185 schemeMode.resize(SchemeCount); 185 schemeMode.resize(SchemeCount);
186 186
187 QString SchemeGroup; 187 QString SchemeGroup;
188 QString SchemeName; 188 QString SchemeName;
189 int SchemeMode; 189 int SchemeMode;
190 190
191 for (int i = 0; i < SchemeCount; i++) { 191 for (int i = 0; i < SchemeCount; i++) {
192 SchemeGroup.sprintf("Scheme %d", i); 192 SchemeGroup.sprintf("Scheme %d", i);
193 cfg->setGroup(SchemeGroup); 193 cfg->setGroup(SchemeGroup);
194 194
195 SchemeName = cfg->readEntry("Description", SchemeGroup); 195 SchemeName = cfg->readEntry("Description", SchemeGroup);
196 SchemeMode = cfg->readNumEntry("Mode", -1); 196 SchemeMode = cfg->readNumEntry("Mode", -1);
197 197
198 schemeMode[i] = SchemeMode; 198 schemeMode[i] = SchemeMode;
199 if (SchemeMode == -1) { 199 if (SchemeMode == -1) {
200 schemeID[i] = modesPopup->insertItem(SchemeName); 200 schemeID[i] = modesPopup->insertItem(SchemeName);
201 modesPopup->setItemChecked(schemeID[i], i == Scheme); 201 modesPopup->setItemChecked(schemeID[i], i == Scheme);
202 } else { 202 } else {
203 schemeID[i] = schemesPopup->at(SchemeMode)->insertItem(SchemeName); 203 schemeID[i] = schemesPopup->at(SchemeMode)->insertItem(SchemeName);
204 schemesPopup->at(SchemeMode)-> 204 schemesPopup->at(SchemeMode)->
205 setItemChecked(schemeID[i], i == Scheme); 205 setItemChecked(schemeID[i], i == Scheme);
206 modesPopup->setItemEnabled(modeID[SchemeMode], TRUE); 206 modesPopup->setItemEnabled(modeID[SchemeMode], TRUE);
207 } 207 }
208 } 208 }
209 209
210 RESTORE_CONFIG_GROUP( cfg, oldgroup ); 210 RESTORE_CONFIG_GROUP( cfg, oldgroup );
211 211
212 APP_CONFIG_END( cfg ); 212 APP_CONFIG_END( cfg );
213 return SchemeCount; 213 return SchemeCount;
214} 214}
215 215
216void Kpacman::quitKpacman() 216void Kpacman::quitKpacman()
217{ 217{
218 APP_QUIT(); 218 APP_QUIT();
219} 219}
220 220
221void Kpacman::newKpacman() 221void Kpacman::newKpacman()
222{ 222{
223 if (!gamePopup->isItemEnabled(hofID)) 223 if (!gamePopup->isItemEnabled(hofID))
224 gamePopup->setItemEnabled(hofID, TRUE); 224 gamePopup->setItemEnabled(hofID, TRUE);
225 225
226 if (gamePopup->isItemChecked(hofID)) 226 if (gamePopup->isItemChecked(hofID))
227 toggleHallOfFame(); 227 toggleHallOfFame();
228 228
229 if (gamePopup->isItemChecked(pauseID)) 229 if (gamePopup->isItemChecked(pauseID))
230 pauseKpacman(); 230 pauseKpacman();
231 231
232 view->referee->play(); 232 view->referee->play();
233} 233}
234 234
235void Kpacman::pauseKpacman() 235void Kpacman::pauseKpacman()
236{ 236{
237 view->referee->pause(); 237 view->referee->pause();
238 view->score->setPause(gamePopup->isItemChecked(pauseID)); 238 view->score->setPause(gamePopup->isItemChecked(pauseID));
239} 239}
240 240
241void Kpacman::toggleHallOfFame() 241void Kpacman::toggleHallOfFame()
242{ 242{
243 gamePopup->setItemChecked(hofID, !gamePopup->isItemChecked(hofID)); 243 gamePopup->setItemChecked(hofID, !gamePopup->isItemChecked(hofID));
244 view->referee->toggleHallOfFame(); 244 view->referee->toggleHallOfFame();
245 245
246 if (gamePopup->isItemChecked(hofID)) { 246 if (gamePopup->isItemChecked(hofID)) {
247 view->referee->lower(); 247 view->referee->lower();
248 view->status->lower(); 248 view->status->lower();
249 } else { 249 } else {
250 view->status->raise(); 250 view->status->raise();
251 view->referee->raise(); 251 view->referee->raise();
252 view->referee->setFocus(); 252 view->referee->setFocus();
253 } 253 }
254} 254}
255 255
256/* 256/*
257 * Disable or enable the "Hall of fame"-menuitem if the referee says so. 257 * Disable or enable the "Hall of fame"-menuitem if the referee says so.
258 * This is done, to disable turning off the "hall of fame"-display, in the automated 258 * This is done, to disable turning off the "hall of fame"-display, in the automated
259 * sequence of displaying the introduction, the demonstration (or playing) and the 259 * sequence of displaying the introduction, the demonstration (or playing) and the
260 * hall of fame. 260 * hall of fame.
261 * If on == TRUE then also lower the referee and the status widgets. 261 * If on == TRUE then also lower the referee and the status widgets.
262 */ 262 */
263void Kpacman::forcedHallOfFame(bool on) 263void Kpacman::forcedHallOfFame(bool on)
264{ 264{
265 if (!on && !gamePopup->isItemChecked(hofID)) 265 if (!on && !gamePopup->isItemChecked(hofID))
266 return; 266 return;
267 267
268 gamePopup->setItemEnabled(hofID, !on); 268 gamePopup->setItemEnabled(hofID, !on);
269 gamePopup->setItemChecked(hofID, on); 269 gamePopup->setItemChecked(hofID, on);
270 270
271 view->referee->toggleHallOfFame(); 271 view->referee->toggleHallOfFame();
272 if (on) { 272 if (on) {
273 view->referee->lower(); 273 view->referee->lower();
274 view->status->lower(); 274 view->status->lower();
275 } else { 275 } else {
276 view->status->raise(); 276 view->status->raise();
277 view->referee->raise(); 277 view->referee->raise();
278 view->referee->setFocus(); 278 view->referee->setFocus();
279 view->referee->intro(); 279 view->referee->intro();
280 } 280 }
281} 281}
282 282
283void Kpacman::togglePaused() 283void Kpacman::togglePaused()
284{ 284{
285 static bool checked = FALSE; 285 static bool checked = FALSE;
286 checked = !checked; 286 checked = !checked;
287 gamePopup->setItemChecked( pauseID, checked ); 287 gamePopup->setItemChecked( pauseID, checked );
288 view->score->setPause(gamePopup->isItemChecked(pauseID)); 288 view->score->setPause(gamePopup->isItemChecked(pauseID));
289} 289}
290 290
291/* 291/*
292 * This disables the "New Game" menuitem to prevent interruptions of the current 292 * This disables the "New Game" menuitem to prevent interruptions of the current
293 * play. 293 * play.
294 */ 294 */
295void Kpacman::toggleNew() 295void Kpacman::toggleNew()
296{ 296{
297 gamePopup->setItemEnabled(newID, !gamePopup->isItemEnabled(newID)); 297 gamePopup->setItemEnabled(newID, !gamePopup->isItemEnabled(newID));
298} 298}
299 299
300void Kpacman::toggleHideMouseCursor() 300void Kpacman::toggleHideMouseCursor()
301{ 301{
302 hideMouseCursor = !hideMouseCursor; 302 hideMouseCursor = !hideMouseCursor;
303 optionsPopup->setItemChecked(hideMouseCursorID, hideMouseCursor); 303 optionsPopup->setItemChecked(hideMouseCursorID, hideMouseCursor);
304 if (hideMouseCursor) 304 if (hideMouseCursor)
305 view->setCursor(blankCursor); 305 view->setCursor(blankCursor);
306 else 306 else
307 view->setCursor(arrowCursor); 307 view->setCursor(arrowCursor);
308} 308}
309 309
310void Kpacman::toggleFocusOutPause() 310void Kpacman::toggleFocusOutPause()
311{ 311{
312 focusOutPause = !focusOutPause; 312 focusOutPause = !focusOutPause;
313 optionsPopup->setItemChecked(focusOutPauseID, focusOutPause); 313 optionsPopup->setItemChecked(focusOutPauseID, focusOutPause);
314 view->referee->setFocusOutPause(focusOutPause); 314 view->referee->setFocusOutPause(focusOutPause);
315} 315}
316 316
317void Kpacman::toggleFocusInContinue() 317void Kpacman::toggleFocusInContinue()
318{ 318{
319 focusInContinue = !focusInContinue; 319 focusInContinue = !focusInContinue;
320 optionsPopup->setItemChecked(focusInContinueID, focusInContinue); 320 optionsPopup->setItemChecked(focusInContinueID, focusInContinue);
321 view->referee->setFocusInContinue(focusInContinue); 321 view->referee->setFocusInContinue(focusInContinue);
322} 322}
323 323
324void Kpacman::confKeys() 324void Kpacman::confKeys()
325{ 325{
326 Keys *keys = new Keys(); 326 Keys *keys = new Keys();
327 if (keys->exec() == QDialog::Accepted) { 327 if (keys->exec() == QDialog::Accepted) {
328 view->referee->initKeys(); 328 view->referee->initKeys();
329 view->score->initKeys(); 329 view->score->initKeys();
330 } 330 }
331 delete keys; 331 delete keys;
332} 332}
333 333
334void Kpacman::schemeChecked(int id) 334void Kpacman::schemeChecked(int id)
335{ 335{
336 int mode = 0, scheme = -1; 336 int mode = 0, scheme = -1;
337 337
338 for (uint s = 0; s < schemeID.size(); s++) { 338 for (uint s = 0; s < schemeID.size(); s++) {
339 if (schemeID[s] == id) { 339 if (schemeID[s] == id) {
340 scheme = s; 340 scheme = s;
341 mode = schemeMode[s]; 341 mode = schemeMode[s];
342 } 342 }
343 if (schemeMode[s] == -1) { 343 if (schemeMode[s] == -1) {
344 modesPopup->setItemChecked(schemeID[s], schemeID[s] == id); 344 modesPopup->setItemChecked(schemeID[s], schemeID[s] == id);
345 } else { 345 } else {
346 modesPopup->setItemChecked(modeID[schemeMode[s]], schemeMode[s] == mode); 346 modesPopup->setItemChecked(modeID[schemeMode[s]], schemeMode[s] == mode);
347 schemesPopup->at(schemeMode[s])->setItemChecked(schemeID[s], schemeID[s] == id); 347 schemesPopup->at(schemeMode[s])->setItemChecked(schemeID[s], schemeID[s] == id);
348 } 348 }
349 } 349 }
350 /* 350 /*
351 APP_CONFIG_BEGIN( cfg ); 351 APP_CONFIG_BEGIN( cfg );
352 cfg->writeEntry("Scheme", scheme); 352 cfg->writeEntry("Scheme", scheme);
353 cfg->writeEntry("Mode", mode); 353 cfg->writeEntry("Mode", mode);
354 APP_CONFIG_END( cfg ); 354 APP_CONFIG_END( cfg );
355 */ 355 */
356 356
357 view->setScheme(scheme, mode); 357 view->setScheme(scheme, mode);
358 view->updateGeometry(); 358 view->updateGeometry();
359 updateGeometry(); 359 updateGeometry();
360 update(); 360 update();
361 repaint(TRUE); 361 repaint(TRUE);
362 show(); 362 show();
363} 363}
diff --git a/noncore/games/oyatzee/oyatzee.cpp b/noncore/games/oyatzee/oyatzee.cpp
index 86318db..a55aa73 100644
--- a/noncore/games/oyatzee/oyatzee.cpp
+++ b/noncore/games/oyatzee/oyatzee.cpp
@@ -1,687 +1,687 @@
1#include "oyatzee.h" 1#include "oyatzee.h"
2 2
3#include <qmessagebox.h> 3#include <qmessagebox.h>
4#include <qpushbutton.h> 4#include <qpushbutton.h>
5#include <qpainter.h> 5#include <qpainter.h>
6#include <qlayout.h> 6#include <qlayout.h>
7 7
8#include <stdlib.h> 8#include <stdlib.h>
9 9
10OYatzee::OYatzee( QWidget *parent , const char *name, WFlags fl ) : QMainWindow( parent , name , fl ) 10OYatzee::OYatzee( QWidget *parent , const char *name, WFlags fl ) : QMainWindow( parent , name , fl )
11{ 11{
12 QWidget *thing = new QWidget( this ); 12 QWidget *thing = new QWidget( this );
13 setCentralWidget( thing ); 13 setCentralWidget( thing );
14 14
15 setCaption( tr( "OYatzee" ) ); 15 setCaption( tr( "OYatzee" ) );
16 16
17 setPlayerNumber( 4 ); 17 setPlayerNumber( 4 );
18 setRoundsNumber( 1 ); 18 setRoundsNumber( 1 );
19 19
20 lastPlayerFinished = false; 20 lastPlayerFinished = false;
21 currentPlayer = 1; 21 currentPlayer = 1;
22 22
23 ps.append( new Player( "Carsten" ) ); 23 ps.append( new Player( "Carsten" ) );
24 ps.append( new Player( "Julia" ) ); 24 ps.append( new Player( "Julia" ) );
25 ps.append( new Player( "Christine" ) ); 25 ps.append( new Player( "Christine" ) );
26 ps.append( new Player( "Stephan" ) ); 26 ps.append( new Player( "Stephan" ) );
27 27
28 28
29 QVBoxLayout *vbox = new QVBoxLayout( thing ); 29 QVBoxLayout *vbox = new QVBoxLayout( thing );
30 30
31 sb = new Scoreboard( ps, thing , "sb" ); 31 sb = new Scoreboard( ps, thing , "sb" );
32 connect( sb->pb , SIGNAL( item( int ) ), this , SLOT( slotEndRound( int ) ) ); 32 connect( sb->pb , SIGNAL( item(int) ), this , SLOT( slotEndRound(int) ) );
33 33
34 dw = new DiceWidget( thing , "dw" ); 34 dw = new DiceWidget( thing , "dw" );
35 dw->setMaximumHeight( this->height()/4 ); 35 dw->setMaximumHeight( this->height()/4 );
36 connect( dw->rollButton, SIGNAL( clicked() ), this , SLOT( slotRollDices() ) ); 36 connect( dw->rollButton, SIGNAL( clicked() ), this , SLOT( slotRollDices() ) );
37 37
38 vbox->addWidget( sb ); 38 vbox->addWidget( sb );
39 vbox->addWidget( dw ); 39 vbox->addWidget( dw );
40} 40}
41 41
42void OYatzee::slotEndRound( int item ) 42void OYatzee::slotEndRound( int item )
43{ 43{
44 qDebug( "Der User hat Nummer %d ausgewählt" , item ); 44 qDebug( "Der User hat Nummer %d ausgewählt" , item );
45 45
46 /* 46 /*
47 * if the user clicked on Total, Bonus or Score and thus not on a 47 * if the user clicked on Total, Bonus or Score and thus not on a
48 * selectable item return and do nothing 48 * selectable item return and do nothing
49 */ 49 */
50 if ( item == 7 || item == 8 || item == 16 ) return; 50 if ( item == 7 || item == 8 || item == 16 ) return;
51 51
52 /* 52 /*
53 * check if the user can really click on that item 53 * check if the user can really click on that item
54 */ 54 */
55 if ( posibilities.find( item ) == posibilities.end() ) return; 55 if ( posibilities.find( item ) == posibilities.end() ) return;
56 56
57 QValueListInt numbers; 57 QValueListInt numbers;
58 58
59 Dice *d = dw->diceList.first(); 59 Dice *d = dw->diceList.first();
60 for ( ; d != 0 ; d = dw->diceList.next() ) 60 for ( ; d != 0 ; d = dw->diceList.next() )
61 { 61 {
62 numbers.append( d->hasValue() ); 62 numbers.append( d->hasValue() );
63 } 63 }
64 64
65 int points = 0; 65 int points = 0;
66 66
67 switch ( item ) 67 switch ( item )
68 { 68 {
69 case Ones: 69 case Ones:
70 points = getPoints( 1 , numbers ); 70 points = getPoints( 1 , numbers );
71 break; 71 break;
72 case Twos: 72 case Twos:
73 points = getPoints( 2 , numbers ); 73 points = getPoints( 2 , numbers );
74 break; 74 break;
75 case Threes: 75 case Threes:
76 points = getPoints( 3 , numbers ); 76 points = getPoints( 3 , numbers );
77 break; 77 break;
78 case Fours: 78 case Fours:
79 points = getPoints( 4 , numbers ); 79 points = getPoints( 4 , numbers );
80 break; 80 break;
81 case Fives: 81 case Fives:
82 points = getPoints( 5 , numbers ); 82 points = getPoints( 5 , numbers );
83 break; 83 break;
84 case Sixes: 84 case Sixes:
85 points = getPoints( 6 , numbers ); 85 points = getPoints( 6 , numbers );
86 break; 86 break;
87 case ThreeOfAKind: 87 case ThreeOfAKind:
88 points = oakPoints; 88 points = oakPoints;
89 break; 89 break;
90 case FourOfAKind: 90 case FourOfAKind:
91 points = oakPoints; 91 points = oakPoints;
92 break; 92 break;
93 case FullHouse: 93 case FullHouse:
94 points = 25; 94 points = 25;
95 break; 95 break;
96 case SStraight: 96 case SStraight:
97 points = 30; 97 points = 30;
98 break; 98 break;
99 case LStraight: 99 case LStraight:
100 points = 40; 100 points = 40;
101 break; 101 break;
102 case Yatzee: 102 case Yatzee:
103 points = 50; 103 points = 50;
104 break; 104 break;
105 case Chance: 105 case Chance:
106 points = getPoints ( Chance , numbers ); 106 points = getPoints ( Chance , numbers );
107 } 107 }
108 108
109 sb->nextRB(currentPlayer-1)->updateMap( item , points ); 109 sb->nextRB(currentPlayer-1)->updateMap( item , points );
110 nextPlayer(); 110 nextPlayer();
111 111
112 qDebug( "Punkte: %d" , points ); 112 qDebug( "Punkte: %d" , points );
113} 113}
114 114
115void OYatzee::nextPlayer() 115void OYatzee::nextPlayer()
116{ 116{
117 currentPlayer++; 117 currentPlayer++;
118 118
119 if ( currentPlayer > numOfPlayers ) 119 if ( currentPlayer > numOfPlayers )
120 { 120 {
121 currentPlayer = 1; 121 currentPlayer = 1;
122 } 122 }
123 123
124 ps.at(currentPlayer-1)->turn = 0; 124 ps.at(currentPlayer-1)->turn = 0;
125} 125}
126 126
127int OYatzee::getPoints( const int num , QValueListInt l) 127int OYatzee::getPoints( const int num , QValueListInt l)
128{ 128{
129 QValueListInt::Iterator it = l.begin(); 129 QValueListInt::Iterator it = l.begin();
130 int c = 0; 130 int c = 0;
131 131
132 if ( num != Chance ) 132 if ( num != Chance )
133 { 133 {
134 for ( ; it != l.end() ; ++it ) 134 for ( ; it != l.end() ; ++it )
135 { 135 {
136 if ( *it == num ) 136 if ( *it == num )
137 c++; 137 c++;
138 } 138 }
139 139
140 return c * num; 140 return c * num;
141 } 141 }
142 else 142 else
143 { 143 {
144 for ( ; it != l.end() ; ++it ) 144 for ( ; it != l.end() ; ++it )
145 { 145 {
146 c += *it; 146 c += *it;
147 } 147 }
148 return c; 148 return c;
149 } 149 }
150 } 150 }
151 151
152OYatzee::~OYatzee() 152OYatzee::~OYatzee()
153{ 153{
154} 154}
155 155
156void OYatzee::detectPosibilities() 156void OYatzee::detectPosibilities()
157{ 157{
158 posibilities.clear(); 158 posibilities.clear();
159 qDebug( "running detectPosibilities()" ); 159 qDebug( "running detectPosibilities()" );
160 160
161 Dice *d = dw->diceList.first(); 161 Dice *d = dw->diceList.first();
162 162
163 QValueListInt numbers; 163 QValueListInt numbers;
164 164
165 for ( ; d != 0 ; d = dw->diceList.next() ) 165 for ( ; d != 0 ; d = dw->diceList.next() )
166 { 166 {
167 numbers.append( d->hasValue() ); 167 numbers.append( d->hasValue() );
168 } 168 }
169 169
170 //the 6 numbers 170 //the 6 numbers
171 QValueListInt::Iterator it; 171 QValueListInt::Iterator it;
172 172
173 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 173 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6
174 { 174 {
175 bool cont = false; 175 bool cont = false;
176 it = numbers.begin(); 176 it = numbers.begin();
177 for ( ; it != numbers.end() ; ++it ) 177 for ( ; it != numbers.end() ; ++it )
178 { 178 {
179 if ( cont ) 179 if ( cont )
180 continue; 180 continue;
181 181
182 if ( numbers.find( i ) != numbers.end() ) 182 if ( numbers.find( i ) != numbers.end() )
183 { 183 {
184 posibilities.append( i ); 184 posibilities.append( i );
185 cont = true; 185 cont = true;
186 } 186 }
187 } 187 }
188 } 188 }
189 189
190 //3er, 4er, Yatzee 190 //3er, 4er, Yatzee
191 it = numbers.begin(); 191 it = numbers.begin();
192 int count; 192 int count;
193 int temp; 193 int temp;
194 int countFH = 0; //for the full-house-check 194 int countFH = 0; //for the full-house-check
195 195
196 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 at least 3 times 196 for ( int i = 1 ; i < 7 ; ++i ) // check for 1-->6 at least 3 times
197 { 197 {
198 count = 0; 198 count = 0;
199 temp = 0; 199 temp = 0;
200 it = numbers.begin(); 200 it = numbers.begin();
201 for ( ; it != numbers.end() ; ++it ) 201 for ( ; it != numbers.end() ; ++it )
202 { 202 {
203 if ( *it == i ) 203 if ( *it == i )
204 { 204 {
205 count++; 205 count++;
206 temp++; 206 temp++;
207 } 207 }
208 if ( temp == 2 ) 208 if ( temp == 2 )
209 countFH = temp; 209 countFH = temp;
210 } 210 }
211 211
212 if ( count >= 3 ) 212 if ( count >= 3 )
213 { 213 {
214 posibilities.append( 9 ); 214 posibilities.append( 9 );
215 215
216 //now we check if it is a full house 216 //now we check if it is a full house
217 if ( count == 3 && countFH == 2 ) //aka Full House 217 if ( count == 3 && countFH == 2 ) //aka Full House
218 posibilities.append( 11 ); 218 posibilities.append( 11 );
219 if ( count >= 4 ) 219 if ( count >= 4 )
220 posibilities.append( 10 ); 220 posibilities.append( 10 );
221 if ( count == 5 ) //Yatzee 221 if ( count == 5 ) //Yatzee
222 posibilities.append( 14 ); 222 posibilities.append( 14 );
223 223
224 oakPoints = count * i; 224 oakPoints = count * i;
225 } 225 }
226 } 226 }
227 227
228 //S-Straight 228 //S-Straight
229 if ( numbers.find( 3 ) != numbers.end() && numbers.find( 4 ) != numbers.end() ) 229 if ( numbers.find( 3 ) != numbers.end() && numbers.find( 4 ) != numbers.end() )
230 { 230 {
231 bool isLong = false; 231 bool isLong = false;
232 bool isShort = true; 232 bool isShort = true;
233 //L-Straight 233 //L-Straight
234 if ( numbers.find( 2 ) != numbers.end() && numbers.find( 5 ) != numbers.end() ) 234 if ( numbers.find( 2 ) != numbers.end() && numbers.find( 5 ) != numbers.end() )
235 { 235 {
236 isShort = true; 236 isShort = true;
237 237
238 //12345 or 23456 238 //12345 or 23456
239 if ( numbers.find( 1 ) != numbers.end() || numbers.find( 6) != numbers.end() ) 239 if ( numbers.find( 1 ) != numbers.end() || numbers.find( 6) != numbers.end() )
240 isLong = true; 240 isLong = true;
241 } 241 }
242 //1234 242 //1234
243 if ( numbers.find( 1 ) != numbers.end() && numbers.find( 2 ) != numbers.end() ) 243 if ( numbers.find( 1 ) != numbers.end() && numbers.find( 2 ) != numbers.end() )
244 isShort = true; 244 isShort = true;
245 //3456 245 //3456
246 if ( numbers.find( 5 ) != numbers.end() && numbers.find( 6 ) != numbers.end() ) 246 if ( numbers.find( 5 ) != numbers.end() && numbers.find( 6 ) != numbers.end() )
247 isShort = true; 247 isShort = true;
248 248
249 if ( isShort ) 249 if ( isShort )
250 posibilities.append( 12 ); 250 posibilities.append( 12 );
251 if ( isLong ) 251 if ( isLong )
252 posibilities.append( 13 ); 252 posibilities.append( 13 );
253 } 253 }
254 254
255 posibilities.append( 13 ); //Chance, well, this is allways possible 255 posibilities.append( 13 ); //Chance, well, this is allways possible
256 256
257 displayPossibilites(); 257 displayPossibilites();
258} 258}
259 259
260void OYatzee::displayPossibilites() 260void OYatzee::displayPossibilites()
261{ 261{
262 //X for ( QValueListInt::Iterator it = posibilities.begin() ; it != posibilities.end(); ++it ) 262 //X for ( QValueListInt::Iterator it = posibilities.begin() ; it != posibilities.end(); ++it )
263 //X { 263 //X {
264 //X qDebug( QString::number( *it ) ); 264 //X qDebug( QString::number( *it ) );
265 //X switch ( *it ) 265 //X switch ( *it )
266 //X { 266 //X {
267 //X case Ones: 267 //X case Ones:
268 //X qDebug( "1er" ); 268 //X qDebug( "1er" );
269 //X break; 269 //X break;
270 //X case Twos: 270 //X case Twos:
271 //X qDebug( "2er" ); 271 //X qDebug( "2er" );
272 //X break; 272 //X break;
273 //X case Threes: 273 //X case Threes:
274 //X qDebug( "3er" ); 274 //X qDebug( "3er" );
275 //X break; 275 //X break;
276 //X case Fours: 276 //X case Fours:
277 //X qDebug( "4er" ); 277 //X qDebug( "4er" );
278 //X break; 278 //X break;
279 //X case Fives: 279 //X case Fives:
280 //X qDebug( "5er" ); 280 //X qDebug( "5er" );
281 //X break; 281 //X break;
282 //X case Sixes: 282 //X case Sixes:
283 //X qDebug( "6er" ); 283 //X qDebug( "6er" );
284 //X break; 284 //X break;
285 //X case ThreeOfAKind: 285 //X case ThreeOfAKind:
286 //X qDebug( "3oaK" ); 286 //X qDebug( "3oaK" );
287 //X break; 287 //X break;
288 //X case FourOfAKind: 288 //X case FourOfAKind:
289 //X qDebug( "4oaK" ); 289 //X qDebug( "4oaK" );
290 //X break; 290 //X break;
291 //X case FullHouse: 291 //X case FullHouse:
292 //X qDebug( "Full House" ); 292 //X qDebug( "Full House" );
293 //X break; 293 //X break;
294 //X case SStraight: 294 //X case SStraight:
295 //X qDebug( "Short S" ); 295 //X qDebug( "Short S" );
296 //X break; 296 //X break;
297 //X case LStraight: 297 //X case LStraight:
298 //X qDebug( "Long S" ); 298 //X qDebug( "Long S" );
299 //X break; 299 //X break;
300 //X case Yatzee: 300 //X case Yatzee:
301 //X qDebug( "Yatzee!" ); 301 //X qDebug( "Yatzee!" );
302 //X break; 302 //X break;
303 //X case Chance: 303 //X case Chance:
304 //X qDebug( "Chance" ); 304 //X qDebug( "Chance" );
305 //X break; 305 //X break;
306 //X } 306 //X }
307 //X } 307 //X }
308 308
309 sb->pb->setIntlist( posibilities ); 309 sb->pb->setIntlist( posibilities );
310 sb->pb->update(); 310 sb->pb->update();
311} 311}
312 312
313void OYatzee::startGame() 313void OYatzee::startGame()
314{ 314{
315 /* 315 /*
316 * TODO 316 * TODO
317 */ 317 */
318} 318}
319 319
320void OYatzee::stopGame(){} 320void OYatzee::stopGame(){}
321 321
322void OYatzee::setPlayerNumber( const int num ) 322void OYatzee::setPlayerNumber( const int num )
323{ 323{
324 numOfPlayers = num; 324 numOfPlayers = num;
325} 325}
326 326
327void OYatzee::setRoundsNumber( const int num ) 327void OYatzee::setRoundsNumber( const int num )
328{ 328{
329 numOfRounds = num; 329 numOfRounds = num;
330} 330}
331 331
332void OYatzee::slotStartGame() 332void OYatzee::slotStartGame()
333{ 333{
334} 334}
335 335
336void OYatzee::slotRollDices() 336void OYatzee::slotRollDices()
337{ 337{
338 qDebug( "Roll nummer: %d" , ps.at( currentPlayer-1 )->turn ); 338 qDebug( "Roll nummer: %d" , ps.at( currentPlayer-1 )->turn );
339 339
340 if ( ps.at( currentPlayer-1 )->turn == 3 ) 340 if ( ps.at( currentPlayer-1 )->turn == 3 )
341 { 341 {
342 QMessageBox::information( this, 342 QMessageBox::information( this,
343 "OYatzee", 343 "OYatzee",
344 tr( "Only three rolls per turn allowed." ) ); 344 tr( "Only three rolls per turn allowed." ) );
345 return; 345 return;
346 } 346 }
347 347
348 Dice *d = dw->diceList.first(); 348 Dice *d = dw->diceList.first();
349 349
350 for ( ; d != 0 ; d = dw->diceList.next() ) 350 for ( ; d != 0 ; d = dw->diceList.next() )
351 { 351 {
352 if ( !d->isSelected ) 352 if ( !d->isSelected )
353 d->roll(); 353 d->roll();
354 } 354 }
355 355
356 //qDebug( "Roll nummer (vorher): %d" , ps.at( currentPlayer-1 )->turn ); 356 //qDebug( "Roll nummer (vorher): %d" , ps.at( currentPlayer-1 )->turn );
357 ps.at(currentPlayer-1)->turn++; 357 ps.at(currentPlayer-1)->turn++;
358 //qDebug( "Roll nummer (nachher): %d" , ps.at( currentPlayer-1 )->turn ); 358 //qDebug( "Roll nummer (nachher): %d" , ps.at( currentPlayer-1 )->turn );
359 359
360 detectPosibilities(); 360 detectPosibilities();
361} 361}
362 362
363/* 363/*
364 * Scoreboard 364 * Scoreboard
365 */ 365 */
366Scoreboard::Scoreboard( playerList ps, QWidget *parent, const char *name ) : QWidget( parent , name ) 366Scoreboard::Scoreboard( playerList ps, QWidget *parent, const char *name ) : QWidget( parent , name )
367{ 367{
368 ps_ = ps; 368 ps_ = ps;
369 369
370 pb = new Possibilityboard( this , "pb" ); 370 pb = new Possibilityboard( this , "pb" );
371 371
372 createResultboards( 4 ); 372 createResultboards( 4 );
373 373
374 QHBoxLayout *hbox = new QHBoxLayout( this ); 374 QHBoxLayout *hbox = new QHBoxLayout( this );
375 375
376 hbox->addWidget( pb ); 376 hbox->addWidget( pb );
377 377
378 hbox->addSpacing( 25 ); 378 hbox->addSpacing( 25 );
379 379
380 Resultboard *r = rbList.first(); 380 Resultboard *r = rbList.first();
381 381
382 for ( ; r != 0 ; r = rbList.next() ) 382 for ( ; r != 0 ; r = rbList.next() )
383 { 383 {
384 hbox->addWidget( r ); 384 hbox->addWidget( r );
385 } 385 }
386} 386}
387 387
388Resultboard* Scoreboard::nextRB( int currentPlayer ) 388Resultboard* Scoreboard::nextRB( int currentPlayer )
389{ 389{
390 Resultboard *b; 390 Resultboard *b;
391 391
392 b = rbList.at( currentPlayer ); 392 b = rbList.at( currentPlayer );
393 393
394 qDebug( "Anzahl: %d" ,rbList.count() ); 394 qDebug( "Anzahl: %d" ,rbList.count() );
395 395
396 return b; 396 return b;
397 } 397 }
398 398
399void Scoreboard::createResultboards(const int num) 399void Scoreboard::createResultboards(const int num)
400{ 400{
401 Player *p = ps_.first(); 401 Player *p = ps_.first();
402 for ( int i = 0 ; i < num ; ++i , p = ps_.next() ) 402 for ( int i = 0 ; i < num ; ++i , p = ps_.next() )
403 { 403 {
404 QString n = p->playerName; 404 QString n = p->playerName;
405 rbList.append( new Resultboard( n , this ) ); 405 rbList.append( new Resultboard( n , this ) );
406 } 406 }
407} 407}
408 408
409void Scoreboard::paintEvent( QPaintEvent * ) 409void Scoreboard::paintEvent( QPaintEvent * )
410{ 410{
411 //X QPainter p; 411 //X QPainter p;
412 //X p.begin( this ); 412 //X p.begin( this );
413//X 413//X
414 //X p.drawRect( 0,0, this->width() , this->height() ); 414 //X p.drawRect( 0,0, this->width() , this->height() );
415} 415}
416 416
417/* 417/*
418 * Dice 418 * Dice
419 */ 419 */
420Dice::Dice( QWidget *parent , const char *name ) : QFrame( parent , name ) 420Dice::Dice( QWidget *parent , const char *name ) : QFrame( parent , name )
421{ 421{
422 QTime t = QTime::currentTime(); // set random seed 422 QTime t = QTime::currentTime(); // set random seed
423 srand(t.hour()*12+t.minute()*60+t.second()*60); 423 srand(t.hour()*12+t.minute()*60+t.second()*60);
424 424
425 connect( this , SIGNAL( selected() ), this , SLOT( slotSelected() ) ); 425 connect( this , SIGNAL( selected() ), this , SLOT( slotSelected() ) );
426} 426}
427 427
428void Dice::slotSelected() 428void Dice::slotSelected()
429{ 429{
430 if ( isSelected ) 430 if ( isSelected )
431 isSelected = false; 431 isSelected = false;
432 else isSelected = true; 432 else isSelected = true;
433 433
434 update(); 434 update();
435} 435}
436 436
437const int Dice::hasValue() const 437const int Dice::hasValue() const
438{ 438{
439 return Value; 439 return Value;
440} 440}
441 441
442void Dice::roll() 442void Dice::roll()
443{ 443{
444 Value = rand()%6; 444 Value = rand()%6;
445 Value += 1; 445 Value += 1;
446 446
447 update(); 447 update();
448} 448}
449 449
450void Dice::mousePressEvent( QMouseEvent* /*e*/ ) 450void Dice::mousePressEvent( QMouseEvent* /*e*/ )
451{ 451{
452 emit selected(); 452 emit selected();
453} 453}
454 454
455void Dice::paintEvent( QPaintEvent * ) 455void Dice::paintEvent( QPaintEvent * )
456{ 456{
457 QPainter p; 457 QPainter p;
458 p.begin( this ); 458 p.begin( this );
459 459
460 p.drawRect( 0,0, this->width() , this->height() ); 460 p.drawRect( 0,0, this->width() , this->height() );
461 461
462 if ( isSelected ) 462 if ( isSelected )
463 p.drawRect( 20,20, 10,10 ); 463 p.drawRect( 20,20, 10,10 );
464 464
465 paintNumber( &p ); 465 paintNumber( &p );
466} 466}
467 467
468void Dice::paintNumber( QPainter *p ) 468void Dice::paintNumber( QPainter *p )
469{ 469{
470 p->setBrush( Qt::black ); 470 p->setBrush( Qt::black );
471 471
472 int w = this->width(); 472 int w = this->width();
473 int h = this->height(); 473 int h = this->height();
474 int r = this->width(); 474 int r = this->width();
475 r /= 10; 475 r /= 10;
476 476
477 switch ( Value ) 477 switch ( Value )
478 { 478 {
479 case 1: 479 case 1:
480 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 480 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
481 break; 481 break;
482 case 2: 482 case 2:
483 p->drawEllipse( (int)( 0.3*w - r ) , (int)( 0.3*h - r ) , r , r ) ; 483 p->drawEllipse( (int)( 0.3*w - r ) , (int)( 0.3*h - r ) , r , r ) ;
484 p->drawEllipse( (int)( 0.7*w - r ) , (int)( 0.7*h - r ) , r , r ) ; 484 p->drawEllipse( (int)( 0.7*w - r ) , (int)( 0.7*h - r ) , r , r ) ;
485 break; 485 break;
486 case 3: 486 case 3:
487 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 487 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
488 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 488 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
489 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 489 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
490 break; 490 break;
491 case 4: 491 case 4:
492 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 492 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
493 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 493 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
494 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 494 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
495 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 495 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
496 break; 496 break;
497 case 5: 497 case 5:
498 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 498 p->drawEllipse( (int)( 0.5*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
499 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 499 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
500 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 500 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
501 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 501 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
502 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 502 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
503 break; 503 break;
504 case 6: 504 case 6:
505 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 505 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
506 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 506 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
507 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ; 507 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.2*h - r ) , r , r ) ;
508 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ; 508 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.8*h - r ) , r , r ) ;
509 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 509 p->drawEllipse( (int)( 0.2*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
510 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.5*h - r ) , r , r ) ; 510 p->drawEllipse( (int)( 0.8*w - r ) , (int)( 0.5*h - r ) , r , r ) ;
511 break; 511 break;
512 } 512 }
513} 513}
514 514
515/* 515/*
516 * DiceWidget 516 * DiceWidget
517 */ 517 */
518DiceWidget::DiceWidget( QWidget *parent , const char *name ) : QWidget( parent , name ) 518DiceWidget::DiceWidget( QWidget *parent , const char *name ) : QWidget( parent , name )
519{ 519{
520 rollButton = new QPushButton( tr( "Roll" ) , this ) ; 520 rollButton = new QPushButton( tr( "Roll" ) , this ) ;
521 521
522 for ( int i = 0 ; i < 5 ; i++ ) 522 for ( int i = 0 ; i < 5 ; i++ )
523 { 523 {
524 //appending the 5 dices of the game 524 //appending the 5 dices of the game
525 diceList.append( new Dice( this, "wuerfel" ) ); 525 diceList.append( new Dice( this, "wuerfel" ) );
526 } 526 }
527 527
528 QHBoxLayout *hbox = new QHBoxLayout( this ); 528 QHBoxLayout *hbox = new QHBoxLayout( this );
529 529
530 Dice *d = diceList.first(); 530 Dice *d = diceList.first();
531 531
532 for ( ; d != 0 ; d = diceList.next() ) 532 for ( ; d != 0 ; d = diceList.next() )
533 { 533 {
534 hbox->addWidget( d ); 534 hbox->addWidget( d );
535 } 535 }
536 536
537 hbox->addWidget( rollButton ); 537 hbox->addWidget( rollButton );
538} 538}
539 539
540/* 540/*
541 * Player 541 * Player
542 */ 542 */
543Player::Player( QString name ) 543Player::Player( QString name )
544{ 544{
545 playerName = name; 545 playerName = name;
546 setupResultList(); 546 setupResultList();
547 turn = 0; 547 turn = 0;
548} 548}
549 549
550void Player::setupResultList() 550void Player::setupResultList()
551{ 551{
552 for ( int i = 1 ; i < 14 ; ++i ) 552 for ( int i = 1 ; i < 14 ; ++i )
553 { 553 {
554 pResults.append( 0 ); 554 pResults.append( 0 );
555 } 555 }
556} 556}
557 557
558/* 558/*
559 * TODO: muss noch genutzt werden 559 * TODO: muss noch genutzt werden
560 */ 560 */
561void Player::updateTotalPoints( pointMap m ) 561void Player::updateTotalPoints( pointMap m )
562{ 562{
563 pointMap::Iterator it = m.begin(); 563 pointMap::Iterator it = m.begin();
564 for ( ; it != m.end() ; ++it ) 564 for ( ; it != m.end() ; ++it )
565 { 565 {
566 totalPoints += it.data(); 566 totalPoints += it.data();
567 } 567 }
568 568
569} 569}
570 570
571 571
572void Player::setResults( const int cat , const int points ) 572void Player::setResults( const int cat , const int points )
573{ 573{
574 QValueListInt::Iterator it = pResults.at( cat ); 574 QValueListInt::Iterator it = pResults.at( cat );
575 *it = points; 575 *it = points;
576} 576}
577 577
578/* 578/*
579 * Board 579 * Board
580 */ 580 */
581Board::Board( QWidget *parent , const char* name ) : QWidget ( parent , name ) 581Board::Board( QWidget *parent , const char* name ) : QWidget ( parent , name )
582{ 582{
583} 583}
584 584
585void Board::mousePressEvent( QMouseEvent *e ) 585void Board::mousePressEvent( QMouseEvent *e )
586{ 586{
587 emit clicked( e->pos() ); 587 emit clicked( e->pos() );
588} 588}
589 589
590/* 590/*
591 * Resultboard 591 * Resultboard
592 */ 592 */
593 593
594Resultboard::Resultboard( QString playerName , QWidget *parent , const char* name ) : Board ( parent , name ) 594Resultboard::Resultboard( QString playerName , QWidget *parent , const char* name ) : Board ( parent , name )
595{ 595{
596 pName = playerName; 596 pName = playerName;
597} 597}
598 598
599void Resultboard::paintEvent( QPaintEvent* ) 599void Resultboard::paintEvent( QPaintEvent* )
600{ 600{
601 QPainter p; 601 QPainter p;
602 p.begin( this ); 602 p.begin( this );
603 603
604 const int cell_width = this->width(); 604 const int cell_width = this->width();
605 const int cell_height = this->height()/17; 605 const int cell_height = this->height()/17;
606 606
607 pointMap::Iterator it = pMap.begin(); 607 pointMap::Iterator it = pMap.begin();
608 for ( ; it != pMap.end() ; ++it ) 608 for ( ; it != pMap.end() ; ++it )
609 { 609 {
610 int i = it.key(); 610 int i = it.key();
611 qDebug( "ok: %d , %d" , i , it.data() ); 611 qDebug( "ok: %d , %d" , i , it.data() );
612 p.drawText( 0, i*cell_height , cell_width , cell_height , Qt::AlignCenter , QString::number( it.data() ) ); 612 p.drawText( 0, i*cell_height , cell_width , cell_height , Qt::AlignCenter , QString::number( it.data() ) );
613 } 613 }
614 614
615 p.drawText( 0,0,cell_width,cell_height, Qt::AlignCenter , pName ); //Playername 615 p.drawText( 0,0,cell_width,cell_height, Qt::AlignCenter , pName ); //Playername
616} 616}
617 617
618 618
619void Resultboard::updateMap( int item , int points ) 619void Resultboard::updateMap( int item , int points )
620{ 620{
621 pMap.insert( item , points ); 621 pMap.insert( item , points );
622 622
623 update(); 623 update();
624} 624}
625 625
626/* 626/*
627 * Possibilityboard 627 * Possibilityboard
628 */ 628 */
629 629
630Possibilityboard::Possibilityboard( QWidget *parent , const char* name ) : Board ( parent , name ) 630Possibilityboard::Possibilityboard( QWidget *parent , const char* name ) : Board ( parent , name )
631{ 631{
632 begriffe.append( "1er" ); 632 begriffe.append( "1er" );
633 begriffe.append( "2er" ); 633 begriffe.append( "2er" );
634 begriffe.append( "3er" ); 634 begriffe.append( "3er" );
635 begriffe.append( "4er" ); 635 begriffe.append( "4er" );
636 begriffe.append( "5er" ); 636 begriffe.append( "5er" );
637 begriffe.append( "6er" ); 637 begriffe.append( "6er" );
638 begriffe.append( "Total" ); 638 begriffe.append( "Total" );
639 begriffe.append( "Bonus" ); 639 begriffe.append( "Bonus" );
640 begriffe.append( "3oaK" ); 640 begriffe.append( "3oaK" );
641 begriffe.append( "4oaK" ); 641 begriffe.append( "4oaK" );
642 begriffe.append( "Full House" ); 642 begriffe.append( "Full House" );
643 begriffe.append( "Short S" ); 643 begriffe.append( "Short S" );
644 begriffe.append( "Long S" ); 644 begriffe.append( "Long S" );
645 begriffe.append( "Yatzee!" ); 645 begriffe.append( "Yatzee!" );
646 begriffe.append( "Chance" ); 646 begriffe.append( "Chance" );
647 begriffe.append( "Score" ); 647 begriffe.append( "Score" );
648 648
649 connect( this , SIGNAL( clicked( QPoint ) ), this , SLOT( slotClicked( QPoint ) ) ); 649 connect( this , SIGNAL( clicked(QPoint) ), this , SLOT( slotClicked(QPoint) ) );
650} 650}
651 651
652void Possibilityboard::slotClicked( QPoint p) 652void Possibilityboard::slotClicked( QPoint p)
653{ 653{
654 emit item( p.y()/(this->height()/17) ); 654 emit item( p.y()/(this->height()/17) );
655} 655}
656 656
657void Possibilityboard::paintEvent( QPaintEvent* ) 657void Possibilityboard::paintEvent( QPaintEvent* )
658{ 658{
659 QPainter p; 659 QPainter p;
660 p.begin( this ); 660 p.begin( this );
661 661
662 const int cell_width = this->width(); 662 const int cell_width = this->width();
663 const int cell_height = this->height()/17; 663 const int cell_height = this->height()/17;
664 664
665 p.setBrush( Qt::blue ); 665 p.setBrush( Qt::blue );
666 666
667 QValueListInt::Iterator listIt = list.begin(); 667 QValueListInt::Iterator listIt = list.begin();
668 for ( ; listIt != list.end() ; ++listIt ) 668 for ( ; listIt != list.end() ; ++listIt )
669 { 669 {
670 p.drawRect( 0 , (*listIt) * cell_height , cell_width , cell_height ); 670 p.drawRect( 0 , (*listIt) * cell_height , cell_width , cell_height );
671 } 671 }
672 672
673 p.setBrush( Qt::black ); 673 p.setBrush( Qt::black );
674 p.setBrush( Qt::NoBrush ); 674 p.setBrush( Qt::NoBrush );
675 QStringList::Iterator begriffeIt = begriffe.begin(); 675 QStringList::Iterator begriffeIt = begriffe.begin();
676 for ( int i = 1 ; i < 18 ; ++i ) 676 for ( int i = 1 ; i < 18 ; ++i )
677 { 677 {
678 p.drawText( 0 , i*cell_height , cell_width , cell_height , Qt::AlignCenter , *begriffeIt ); 678 p.drawText( 0 , i*cell_height , cell_width , cell_height , Qt::AlignCenter , *begriffeIt );
679 ++begriffeIt; 679 ++begriffeIt;
680 } 680 }
681} 681}
682 682
683void Possibilityboard::setIntlist( QValueListInt &l ) 683void Possibilityboard::setIntlist( QValueListInt &l )
684{ 684{
685 list = l; 685 list = l;
686} 686}
687 687
diff --git a/noncore/multimedia/camera/gui/mainwindow.cpp b/noncore/multimedia/camera/gui/mainwindow.cpp
index 2f42049..e4e1b6c 100644
--- a/noncore/multimedia/camera/gui/mainwindow.cpp
+++ b/noncore/multimedia/camera/gui/mainwindow.cpp
@@ -1,728 +1,728 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2002 Michael 'Mickey' Lauer. All rights reserved. 2** Copyright (C) 2002 Michael 'Mickey' Lauer. All rights reserved.
3** 3**
4** This file is part of Opie Environment. 4** This file is part of Opie Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14**********************************************************************/ 14**********************************************************************/
15 15
16#include "mainwindow.h" 16#include "mainwindow.h"
17#include "previewwidget.h" 17#include "previewwidget.h"
18#include "zcameraio.h" 18#include "zcameraio.h"
19#include "imageio.h" 19#include "imageio.h"
20#include "avi.h" 20#include "avi.h"
21 21
22/* OPIE */ 22/* OPIE */
23#include <opie2/ofiledialog.h> 23#include <opie2/ofiledialog.h>
24#include <opie2/odevice.h> 24#include <opie2/odevice.h>
25#include <opie2/oapplication.h> 25#include <opie2/oapplication.h>
26#include <opie2/oconfig.h> 26#include <opie2/oconfig.h>
27#include <opie2/odebug.h> 27#include <opie2/odebug.h>
28#include <qpe/global.h> 28#include <qpe/global.h>
29#include <qpe/resource.h> 29#include <qpe/resource.h>
30#include <qpe/qcopenvelope_qws.h> 30#include <qpe/qcopenvelope_qws.h>
31using namespace Opie; 31using namespace Opie;
32 32
33/* QT */ 33/* QT */
34#include <qapplication.h> 34#include <qapplication.h>
35#include <qaction.h> 35#include <qaction.h>
36#include <qvbox.h> 36#include <qvbox.h>
37#include <qcombobox.h> 37#include <qcombobox.h>
38#include <qcursor.h> 38#include <qcursor.h>
39#include <qdatastream.h> 39#include <qdatastream.h>
40#include <qdir.h> 40#include <qdir.h>
41#include <qfile.h> 41#include <qfile.h>
42#include <qimage.h> 42#include <qimage.h>
43#include <qlabel.h> 43#include <qlabel.h>
44#include <qlineedit.h> 44#include <qlineedit.h>
45#include <qpopupmenu.h> 45#include <qpopupmenu.h>
46#include <qprogressbar.h> 46#include <qprogressbar.h>
47#include <qpushbutton.h> 47#include <qpushbutton.h>
48#include <qmessagebox.h> 48#include <qmessagebox.h>
49#include <qlayout.h> 49#include <qlayout.h>
50#include <qdirectpainter_qws.h> 50#include <qdirectpainter_qws.h>
51 51
52/* STD */ 52/* STD */
53#include <assert.h> 53#include <assert.h>
54#include <sys/types.h> 54#include <sys/types.h>
55#include <sys/stat.h> 55#include <sys/stat.h>
56#include <fcntl.h> 56#include <fcntl.h>
57#include <string.h> 57#include <string.h>
58#include <errno.h> 58#include <errno.h>
59#include <unistd.h> 59#include <unistd.h>
60 60
61#define CAPTUREFILE "/tmp/capture.dat" 61#define CAPTUREFILE "/tmp/capture.dat"
62#define OUTPUTFILE "/tmp/output.avi" 62#define OUTPUTFILE "/tmp/output.avi"
63 63
64#define OUTPUT_TO_CUSTOM 250 64#define OUTPUT_TO_CUSTOM 250
65#define OUTPUT_TO_DOCFOLDER 251 65#define OUTPUT_TO_DOCFOLDER 251
66 66
67CameraMainWindow::CameraMainWindow( QWidget * parent, const char * name, WFlags f ) 67CameraMainWindow::CameraMainWindow( QWidget * parent, const char * name, WFlags f )
68 :QMainWindow( parent, name, f ), 68 :QMainWindow( parent, name, f ),
69 _rotation( 270 ), // FIXME: get this from current settings (ODevice?) 69 _rotation( 270 ), // FIXME: get this from current settings (ODevice?)
70 _capturing( false ), 70 _capturing( false ),
71 _pics( 1 ), _videos( 1 ) 71 _pics( 1 ), _videos( 1 )
72{ 72{
73 #ifdef QT_NO_DEBUG 73 #ifdef QT_NO_DEBUG
74 if ( !ZCameraIO::instance()->isOpen() ) 74 if ( !ZCameraIO::instance()->isOpen() )
75 { 75 {
76 QVBox* v = new QVBox( this ); 76 QVBox* v = new QVBox( this );
77 v->setMargin( 10 ); 77 v->setMargin( 10 );
78 QLabel* l1 = new QLabel( v ); 78 QLabel* l1 = new QLabel( v );
79 l1->setPixmap( Resource::loadPixmap( "camera/error" ) ); 79 l1->setPixmap( Resource::loadPixmap( "camera/error" ) );
80 QLabel* l2 = new QLabel( v ); 80 QLabel* l2 = new QLabel( v );
81 l2->setText( "<b>Sorry. could not detect your camera :-(</b><p>" 81 l2->setText( "<b>Sorry. could not detect your camera :-(</b><p>"
82 "* Is the sharpzdc_cs module loaded ?<br>" 82 "* Is the sharpzdc_cs module loaded ?<br>"
83 "* Is /dev/sharpzdc read/writable ?<p>" ); 83 "* Is /dev/sharpzdc read/writable ?<p>" );
84 connect( new QPushButton( "Exit", v ), SIGNAL( clicked() ), this, SLOT( close() ) ); 84 connect( new QPushButton( "Exit", v ), SIGNAL( clicked() ), this, SLOT( close() ) );
85 setCentralWidget( v ); 85 setCentralWidget( v );
86 return; 86 return;
87 } 87 }
88 #endif 88 #endif
89 89
90 init(); 90 init();
91 91
92 _rotation = 270; //TODO: grab these from the actual settings 92 _rotation = 270; //TODO: grab these from the actual settings
93 93
94 preview = new PreviewWidget( this, "camera preview widget" ); 94 preview = new PreviewWidget( this, "camera preview widget" );
95 //setCentralWidget( preview ); <--- don't do this! 95 //setCentralWidget( preview ); <--- don't do this!
96 preview->resize( QSize( 240, 288 ) ); 96 preview->resize( QSize( 240, 288 ) );
97 preview->show(); 97 preview->show();
98 98
99 // construct a System Channel to receive setRotation messages 99 // construct a System Channel to receive setRotation messages
100 _sysChannel = new QCopChannel( "QPE/System", this ); 100 _sysChannel = new QCopChannel( "QPE/System", this );
101 connect( _sysChannel, SIGNAL( received( const QCString&, const QByteArray& ) ), 101 connect( _sysChannel, SIGNAL( received(const QCString&,const QByteArray&) ),
102 this, SLOT( systemMessage( const QCString&, const QByteArray& ) ) ); 102 this, SLOT( systemMessage(const QCString&,const QByteArray&) ) );
103 103
104 connect( preview, SIGNAL( contextMenuRequested() ), this, SLOT( showContextMenu() ) ); 104 connect( preview, SIGNAL( contextMenuRequested() ), this, SLOT( showContextMenu() ) );
105 105
106 connect( ZCameraIO::instance(), SIGNAL( shutterClicked() ), this, SLOT( shutterClicked() ) ); 106 connect( ZCameraIO::instance(), SIGNAL( shutterClicked() ), this, SLOT( shutterClicked() ) );
107 107
108 updateCaption(); 108 updateCaption();
109 109
110}; 110};
111 111
112 112
113CameraMainWindow::~CameraMainWindow() 113CameraMainWindow::~CameraMainWindow()
114{ 114{
115 // write back configuration 115 // write back configuration
116 OConfigGroupSaver cgs( oApp->config(), "General" ); 116 OConfigGroupSaver cgs( oApp->config(), "General" );
117 cgs.config()->writeEntry( "flip", flip ); 117 cgs.config()->writeEntry( "flip", flip );
118 cgs.config()->writeEntry( "quality", quality ); 118 cgs.config()->writeEntry( "quality", quality );
119 cgs.config()->writeEntry( "zoom", zoom ); 119 cgs.config()->writeEntry( "zoom", zoom );
120 cgs.config()->writeEntry( "captureX", captureX ); 120 cgs.config()->writeEntry( "captureX", captureX );
121 cgs.config()->writeEntry( "captureY", captureY ); 121 cgs.config()->writeEntry( "captureY", captureY );
122 cgs.config()->writeEntry( "captureFormat", captureFormat ); 122 cgs.config()->writeEntry( "captureFormat", captureFormat );
123 cgs.config()->writeEntry( "outputTo", outputTo ); 123 cgs.config()->writeEntry( "outputTo", outputTo );
124 cgs.config()->writeEntry( "prefix", prefix ); 124 cgs.config()->writeEntry( "prefix", prefix );
125 cgs.config()->writeEntry( "appendSettings", appendSettings ); 125 cgs.config()->writeEntry( "appendSettings", appendSettings );
126} 126}
127 127
128 128
129void CameraMainWindow::init() 129void CameraMainWindow::init()
130{ 130{
131 // get values from configuration 131 // get values from configuration
132 OConfigGroupSaver cgs( oApp->config(), "General" ); 132 OConfigGroupSaver cgs( oApp->config(), "General" );
133 flip = cgs.config()->readEntry( "flip", "A" ); 133 flip = cgs.config()->readEntry( "flip", "A" );
134 quality = cgs.config()->readNumEntry( "quality", 50 ); 134 quality = cgs.config()->readNumEntry( "quality", 50 );
135 zoom = cgs.config()->readNumEntry( "zoom", 1 ); 135 zoom = cgs.config()->readNumEntry( "zoom", 1 );
136 captureX = cgs.config()->readNumEntry( "captureX", 480 ); 136 captureX = cgs.config()->readNumEntry( "captureX", 480 );
137 captureY = cgs.config()->readNumEntry( "captureY", 640 ); 137 captureY = cgs.config()->readNumEntry( "captureY", 640 );
138 captureFormat = cgs.config()->readEntry( "captureFormat", "JPEG" ); 138 captureFormat = cgs.config()->readEntry( "captureFormat", "JPEG" );
139 outputTo = cgs.config()->readEntry( "outputTo", "Documents Folder" ); 139 outputTo = cgs.config()->readEntry( "outputTo", "Documents Folder" );
140 prefix = cgs.config()->readEntry( "prefix", "Untitled" ); 140 prefix = cgs.config()->readEntry( "prefix", "Untitled" );
141 appendSettings = cgs.config()->readBoolEntry( "appendSettings", true ); 141 appendSettings = cgs.config()->readBoolEntry( "appendSettings", true );
142 142
143 // create action groups 143 // create action groups
144 QAction* a; 144 QAction* a;
145 resog = new QActionGroup( 0, "reso", true ); 145 resog = new QActionGroup( 0, "reso", true );
146 resog->setToggleAction( true ); 146 resog->setToggleAction( true );
147 new QAction( " 64 x 48", 0, 0, resog, "64x48", true ); 147 new QAction( " 64 x 48", 0, 0, resog, "64x48", true );
148 new QAction( "128 x 96", 0, 0, resog, "128x96", true ); 148 new QAction( "128 x 96", 0, 0, resog, "128x96", true );
149 new QAction( "192 x 144", 0, 0, resog, "192x144", true ); 149 new QAction( "192 x 144", 0, 0, resog, "192x144", true );
150 new QAction( "256 x 192", 0, 0, resog, "256x192", true ); 150 new QAction( "256 x 192", 0, 0, resog, "256x192", true );
151 new QAction( "320 x 240", 0, 0, resog, "320x240", true ); 151 new QAction( "320 x 240", 0, 0, resog, "320x240", true );
152 new QAction( "384 x 288", 0, 0, resog, "384x288", true ); 152 new QAction( "384 x 288", 0, 0, resog, "384x288", true );
153 new QAction( "448 x 336", 0, 0, resog, "448x336", true ); 153 new QAction( "448 x 336", 0, 0, resog, "448x336", true );
154 new QAction( "512 x 384", 0, 0, resog, "512x384", true ); 154 new QAction( "512 x 384", 0, 0, resog, "512x384", true );
155 new QAction( "576 x 432", 0, 0, resog, "576x432", true ); 155 new QAction( "576 x 432", 0, 0, resog, "576x432", true );
156 new QAction( "640 x 480", 0, 0, resog, "640x480", true ); 156 new QAction( "640 x 480", 0, 0, resog, "640x480", true );
157 a = (QAction*) resog->child( QString().sprintf( "%dx%d", captureX>captureY ? captureX:captureY, captureX>captureY ? captureY:captureX ) ); 157 a = (QAction*) resog->child( QString().sprintf( "%dx%d", captureX>captureY ? captureX:captureY, captureX>captureY ? captureY:captureX ) );
158 if ( a ) a->setOn( true ); 158 if ( a ) a->setOn( true );
159 else owarn << "can't set resolution" << oendl; 159 else owarn << "can't set resolution" << oendl;
160 160
161 qualityg = new QActionGroup( 0, "quality", true ); 161 qualityg = new QActionGroup( 0, "quality", true );
162 qualityg->setToggleAction( true ); 162 qualityg->setToggleAction( true );
163 new QAction( " 0 (&minimal)", 0, 0, qualityg, "0", true ); 163 new QAction( " 0 (&minimal)", 0, 0, qualityg, "0", true );
164 new QAction( " 25 (&low)", 0, 0, qualityg, "25", true ); 164 new QAction( " 25 (&low)", 0, 0, qualityg, "25", true );
165 new QAction( " 50 (&good)", 0, 0, qualityg, "50", true ); 165 new QAction( " 50 (&good)", 0, 0, qualityg, "50", true );
166 new QAction( " 75 (&better)", 0, 0, qualityg, "75", true ); 166 new QAction( " 75 (&better)", 0, 0, qualityg, "75", true );
167 new QAction( "100 (bes&t)", 0, 0, qualityg, "100", true ); 167 new QAction( "100 (bes&t)", 0, 0, qualityg, "100", true );
168 a = (QAction*) qualityg->child( QString().sprintf( "%d", quality ) ); 168 a = (QAction*) qualityg->child( QString().sprintf( "%d", quality ) );
169 if ( a ) a->setOn( true ); 169 if ( a ) a->setOn( true );
170 else owarn << "can't set quality" << oendl; 170 else owarn << "can't set quality" << oendl;
171 171
172 zoomg = new QActionGroup( 0, "zoom", true ); 172 zoomg = new QActionGroup( 0, "zoom", true );
173 zoomg->setToggleAction( true ); 173 zoomg->setToggleAction( true );
174 new QAction( "x 1", 0, 0, zoomg, "1", true ); 174 new QAction( "x 1", 0, 0, zoomg, "1", true );
175 new QAction( "x 2", 0, 0, zoomg, "2", true ); 175 new QAction( "x 2", 0, 0, zoomg, "2", true );
176 a = (QAction*) zoomg->child( QString().sprintf( "%d", zoom ) ); 176 a = (QAction*) zoomg->child( QString().sprintf( "%d", zoom ) );
177 if ( a ) a->setOn( true ); 177 if ( a ) a->setOn( true );
178 else owarn << "can't set zoom" << oendl; 178 else owarn << "can't set zoom" << oendl;
179 179
180 flipg = new QActionGroup( 0, "flip", true ); 180 flipg = new QActionGroup( 0, "flip", true );
181 flipg->setToggleAction( true ); 181 flipg->setToggleAction( true );
182 new QAction( "Auto (recommended)", 0, 0, flipg, "A", true ); 182 new QAction( "Auto (recommended)", 0, 0, flipg, "A", true );
183 new QAction( "0 (always off)", 0, 0, flipg, "0", true ); 183 new QAction( "0 (always off)", 0, 0, flipg, "0", true );
184 new QAction( "X (always horizontal)", 0, 0, flipg, "X", true ); 184 new QAction( "X (always horizontal)", 0, 0, flipg, "X", true );
185 new QAction( "Y (always vertical)", 0, 0, flipg, "Y", true ); 185 new QAction( "Y (always vertical)", 0, 0, flipg, "Y", true );
186 new QAction( "* (always both)", 0, 0, flipg, "*", true ); 186 new QAction( "* (always both)", 0, 0, flipg, "*", true );
187 a = (QAction*) flipg->child( QString().sprintf( "%s", (const char*) flip ) ); 187 a = (QAction*) flipg->child( QString().sprintf( "%s", (const char*) flip ) );
188 if ( a ) a->setOn( true ); 188 if ( a ) a->setOn( true );
189 else owarn << "can't set flip" << oendl; 189 else owarn << "can't set flip" << oendl;
190 190
191 outputTog = new QActionGroup( 0, "output", true ); 191 outputTog = new QActionGroup( 0, "output", true );
192 outputTog->setToggleAction( true ); 192 outputTog->setToggleAction( true );
193 new QAction( "/tmp/", 0, 0, outputTog, "/tmp/", true ); 193 new QAction( "/tmp/", 0, 0, outputTog, "/tmp/", true );
194 new QAction( "/mnt/card/", 0, 0, outputTog, "/mnt/card/", true ); 194 new QAction( "/mnt/card/", 0, 0, outputTog, "/mnt/card/", true );
195 new QAction( "/mnt/cf/", 0, 0, outputTog, "/mnt/cf/", true ); 195 new QAction( "/mnt/cf/", 0, 0, outputTog, "/mnt/cf/", true );
196 docfolder = new QAction( "Documents Folder", 0, 0, outputTog, "Documents Folder", true ); 196 docfolder = new QAction( "Documents Folder", 0, 0, outputTog, "Documents Folder", true );
197 custom = new QAction( "&Custom...", 0, 0, outputTog, "custom", true ); //TODO: How to save custom!? 197 custom = new QAction( "&Custom...", 0, 0, outputTog, "custom", true ); //TODO: How to save custom!?
198 a = (QAction*) outputTog->child( QString().sprintf( "%s", (const char*) outputTo ) ); 198 a = (QAction*) outputTog->child( QString().sprintf( "%s", (const char*) outputTo ) );
199 if ( a ) a->setOn( true ); 199 if ( a ) a->setOn( true );
200 else owarn << "can't set outputTo" << oendl; 200 else owarn << "can't set outputTo" << oendl;
201 201
202 outputg = new QActionGroup( 0, "output", true ); 202 outputg = new QActionGroup( 0, "output", true );
203 outputg->setToggleAction( true ); 203 outputg->setToggleAction( true );
204 new QAction( "JPEG", 0, 0, outputg, "JPEG", true ); 204 new QAction( "JPEG", 0, 0, outputg, "JPEG", true );
205 new QAction( "PNG", 0, 0, outputg, "PNG", true ); 205 new QAction( "PNG", 0, 0, outputg, "PNG", true );
206 new QAction( "BMP", 0, 0, outputg, "BMP", true ); 206 new QAction( "BMP", 0, 0, outputg, "BMP", true );
207 new QAction( "AVI", 0, 0, outputg, "AVI", true ); 207 new QAction( "AVI", 0, 0, outputg, "AVI", true );
208 a = (QAction*) outputg->child( QString().sprintf( "%s", (const char*) captureFormat ) ); 208 a = (QAction*) outputg->child( QString().sprintf( "%s", (const char*) captureFormat ) );
209 if ( a ) a->setOn( true ); 209 if ( a ) a->setOn( true );
210 else owarn << "can't set output format" << oendl; 210 else owarn << "can't set output format" << oendl;
211 211
212 connect( resog, SIGNAL( selected(QAction*) ), this, SLOT( resoMenuItemClicked(QAction*) ) ); 212 connect( resog, SIGNAL( selected(QAction*) ), this, SLOT( resoMenuItemClicked(QAction*) ) );
213 connect( qualityg, SIGNAL( selected(QAction*) ), this, SLOT( qualityMenuItemClicked(QAction*) ) ); 213 connect( qualityg, SIGNAL( selected(QAction*) ), this, SLOT( qualityMenuItemClicked(QAction*) ) );
214 connect( zoomg, SIGNAL( selected(QAction*) ), this, SLOT( zoomMenuItemClicked(QAction*) ) ); 214 connect( zoomg, SIGNAL( selected(QAction*) ), this, SLOT( zoomMenuItemClicked(QAction*) ) );
215 connect( flipg, SIGNAL( selected(QAction*) ), this, SLOT( flipMenuItemClicked(QAction*) ) ); 215 connect( flipg, SIGNAL( selected(QAction*) ), this, SLOT( flipMenuItemClicked(QAction*) ) );
216 connect( outputTog, SIGNAL( selected(QAction*) ), this, SLOT( outputToMenuItemClicked(QAction*) ) ); 216 connect( outputTog, SIGNAL( selected(QAction*) ), this, SLOT( outputToMenuItemClicked(QAction*) ) );
217 connect( outputg, SIGNAL( selected(QAction*) ), this, SLOT( outputMenuItemClicked(QAction*) ) ); 217 connect( outputg, SIGNAL( selected(QAction*) ), this, SLOT( outputMenuItemClicked(QAction*) ) );
218} 218}
219 219
220 220
221void CameraMainWindow::systemMessage( const QCString& msg, const QByteArray& data ) 221void CameraMainWindow::systemMessage( const QCString& msg, const QByteArray& data )
222{ 222{
223 int _newrotation; 223 int _newrotation;
224 224
225 QDataStream stream( data, IO_ReadOnly ); 225 QDataStream stream( data, IO_ReadOnly );
226 odebug << "received system message: " << msg << oendl; 226 odebug << "received system message: " << msg << oendl;
227 if ( msg == "setCurrentRotation(int)" ) 227 if ( msg == "setCurrentRotation(int)" )
228 { 228 {
229 stream >> _newrotation; 229 stream >> _newrotation;
230 odebug << "received setCurrentRotation(" << _newrotation << ")" << oendl; 230 odebug << "received setCurrentRotation(" << _newrotation << ")" << oendl;
231 231
232 switch ( _newrotation ) 232 switch ( _newrotation )
233 { 233 {
234 case 270: preview->resize( QSize( 240, 288 ) ); break; 234 case 270: preview->resize( QSize( 240, 288 ) ); break;
235 case 180: preview->resize( QSize( 320, 208 ) ); break; 235 case 180: preview->resize( QSize( 320, 208 ) ); break;
236 default: QMessageBox::warning( this, "opie-camera", 236 default: QMessageBox::warning( this, "opie-camera",
237 "This rotation is not supported.\n" 237 "This rotation is not supported.\n"
238 "Supported are 180° and 270°" ); 238 "Supported are 180° and 270°" );
239 } 239 }
240 240
241 if ( _newrotation != _rotation ) 241 if ( _newrotation != _rotation )
242 { 242 {
243 int tmp = captureX; 243 int tmp = captureX;
244 captureX = captureY; 244 captureX = captureY;
245 captureY = tmp; 245 captureY = tmp;
246 _rotation = _newrotation; 246 _rotation = _newrotation;
247 } 247 }
248 248
249 updateCaption(); 249 updateCaption();
250 250
251 } 251 }
252} 252}
253 253
254 254
255void CameraMainWindow::changeZoom( int zoom ) 255void CameraMainWindow::changeZoom( int zoom )
256{ 256{
257 int z; 257 int z;
258 switch ( zoom ) 258 switch ( zoom )
259 { 259 {
260 case 0: z = 128; break; 260 case 0: z = 128; break;
261 case 1: z = 256; break; 261 case 1: z = 256; break;
262 case 2: z = 512; break; 262 case 2: z = 512; break;
263 default: assert( 0 ); break; 263 default: assert( 0 ); break;
264 } 264 }
265 265
266 ZCameraIO::instance()->setCaptureFrame( 240, 160, z ); 266 ZCameraIO::instance()->setCaptureFrame( 240, 160, z );
267} 267}
268 268
269 269
270void CameraMainWindow::showContextMenu() 270void CameraMainWindow::showContextMenu()
271{ 271{
272 QPopupMenu reso; 272 QPopupMenu reso;
273 reso.setCheckable( true ); 273 reso.setCheckable( true );
274 resog->addTo( &reso ); 274 resog->addTo( &reso );
275 275
276 QPopupMenu quality; 276 QPopupMenu quality;
277 quality.setCheckable( true ); 277 quality.setCheckable( true );
278 qualityg->addTo( &quality ); 278 qualityg->addTo( &quality );
279 279
280 QPopupMenu flip; 280 QPopupMenu flip;
281 flip.setCheckable( true ); 281 flip.setCheckable( true );
282 flipg->addTo( &flip ); 282 flipg->addTo( &flip );
283 283
284 QPopupMenu zoom; 284 QPopupMenu zoom;
285 zoom.setCheckable( true ); 285 zoom.setCheckable( true );
286 zoomg->addTo( &zoom ); 286 zoomg->addTo( &zoom );
287 287
288 QPopupMenu prefix; 288 QPopupMenu prefix;
289 prefix.insertItem( "&Choose...", this, SLOT( prefixItemChoosen() ) ); 289 prefix.insertItem( "&Choose...", this, SLOT( prefixItemChoosen() ) );
290 int id = prefix.insertItem( "&Append Settings", this, SLOT( appendSettingsChoosen() ) ); 290 int id = prefix.insertItem( "&Append Settings", this, SLOT( appendSettingsChoosen() ) );
291 prefix.setItemChecked( id, appendSettings ); 291 prefix.setItemChecked( id, appendSettings );
292 292
293 QPopupMenu outputTo; 293 QPopupMenu outputTo;
294 outputTo.setCheckable( true ); 294 outputTo.setCheckable( true );
295 outputTog->addTo( &outputTo ); 295 outputTog->addTo( &outputTo );
296 296
297 QPopupMenu output; 297 QPopupMenu output;
298 output.setCheckable( true ); 298 output.setCheckable( true );
299 outputg->addTo( &output ); 299 outputg->addTo( &output );
300 300
301 QPopupMenu m( this ); 301 QPopupMenu m( this );
302 m.insertItem( "&Resolution", &reso ); 302 m.insertItem( "&Resolution", &reso );
303 m.insertItem( "&Zoom", &zoom ); 303 m.insertItem( "&Zoom", &zoom );
304 m.insertItem( "&Flip", &flip ); 304 m.insertItem( "&Flip", &flip );
305 m.insertItem( "&Quality", &quality ); 305 m.insertItem( "&Quality", &quality );
306 m.insertSeparator(); 306 m.insertSeparator();
307 m.insertItem( "&Prefix", &prefix ); 307 m.insertItem( "&Prefix", &prefix );
308 m.insertItem( "Output &To", &outputTo ); 308 m.insertItem( "Output &To", &outputTo );
309 m.insertItem( "&Output As", &output ); 309 m.insertItem( "&Output As", &output );
310 310
311 #ifndef QT_NO_DEBUG 311 #ifndef QT_NO_DEBUG
312 m.insertItem( "&Debug!", this, SLOT( doSomething() ) ); 312 m.insertItem( "&Debug!", this, SLOT( doSomething() ) );
313 #endif 313 #endif
314 314
315 m.exec( QCursor::pos() ); 315 m.exec( QCursor::pos() );
316} 316}
317 317
318 318
319void CameraMainWindow::resoMenuItemClicked( QAction* a ) 319void CameraMainWindow::resoMenuItemClicked( QAction* a )
320{ 320{
321 switch ( _rotation ) 321 switch ( _rotation )
322 { 322 {
323 case 270: 323 case 270:
324 captureY = a->text().left(3).toInt(); 324 captureY = a->text().left(3).toInt();
325 captureX = a->text().right(3).toInt(); 325 captureX = a->text().right(3).toInt();
326 break; 326 break;
327 case 180: 327 case 180:
328 captureX = a->text().left(3).toInt(); 328 captureX = a->text().left(3).toInt();
329 captureY = a->text().right(3).toInt(); 329 captureY = a->text().right(3).toInt();
330 break; 330 break;
331 default: QMessageBox::warning( this, "opie-camera", 331 default: QMessageBox::warning( this, "opie-camera",
332 "This rotation is not supported.\n" 332 "This rotation is not supported.\n"
333 "Supported are 180° and 270°" ); 333 "Supported are 180° and 270°" );
334 } 334 }
335 odebug << "Capture Resolution now: " << captureX << ", " << captureY << oendl; 335 odebug << "Capture Resolution now: " << captureX << ", " << captureY << oendl;
336 updateCaption(); 336 updateCaption();
337} 337}
338 338
339 339
340void CameraMainWindow::qualityMenuItemClicked( QAction* a ) 340void CameraMainWindow::qualityMenuItemClicked( QAction* a )
341{ 341{
342 quality = a->text().left(3).toInt(); 342 quality = a->text().left(3).toInt();
343 odebug << "Quality now: " << quality << oendl; 343 odebug << "Quality now: " << quality << oendl;
344 updateCaption(); 344 updateCaption();
345} 345}
346 346
347 347
348void CameraMainWindow::zoomMenuItemClicked( QAction* a ) 348void CameraMainWindow::zoomMenuItemClicked( QAction* a )
349{ 349{
350 zoom = QString( a->text().at(2) ).toInt(); 350 zoom = QString( a->text().at(2) ).toInt();
351 odebug << "Zoom now: " << zoom << oendl; 351 odebug << "Zoom now: " << zoom << oendl;
352 ZCameraIO::instance()->setZoom( zoom ); 352 ZCameraIO::instance()->setZoom( zoom );
353 updateCaption(); 353 updateCaption();
354} 354}
355 355
356 356
357void CameraMainWindow::flipMenuItemClicked( QAction* a ) 357void CameraMainWindow::flipMenuItemClicked( QAction* a )
358{ 358{
359 flip = QString( a->text().at(0) ); 359 flip = QString( a->text().at(0) );
360 odebug << "Flip now: " << flip << oendl; 360 odebug << "Flip now: " << flip << oendl;
361 if ( flip == "A" ) 361 if ( flip == "A" )
362 ZCameraIO::instance()->setFlip( ZCameraIO::AUTOMATICFLIP ); 362 ZCameraIO::instance()->setFlip( ZCameraIO::AUTOMATICFLIP );
363 else if ( flip == "0" ) 363 else if ( flip == "0" )
364 ZCameraIO::instance()->setFlip( ZCameraIO::XNOFLIP | ZCameraIO::YNOFLIP ); 364 ZCameraIO::instance()->setFlip( ZCameraIO::XNOFLIP | ZCameraIO::YNOFLIP );
365 else if ( flip == "X" ) 365 else if ( flip == "X" )
366 ZCameraIO::instance()->setFlip( ZCameraIO::XFLIP ); 366 ZCameraIO::instance()->setFlip( ZCameraIO::XFLIP );
367 else if ( flip == "Y" ) 367 else if ( flip == "Y" )
368 ZCameraIO::instance()->setFlip( ZCameraIO::YFLIP ); 368 ZCameraIO::instance()->setFlip( ZCameraIO::YFLIP );
369 else if ( flip == "*" ) 369 else if ( flip == "*" )
370 ZCameraIO::instance()->setFlip( ZCameraIO::XFLIP | ZCameraIO::YFLIP ); 370 ZCameraIO::instance()->setFlip( ZCameraIO::XFLIP | ZCameraIO::YFLIP );
371 371
372 updateCaption(); 372 updateCaption();
373} 373}
374 374
375 375
376void CameraMainWindow::outputToMenuItemClicked( QAction* a ) 376void CameraMainWindow::outputToMenuItemClicked( QAction* a )
377{ 377{
378 if ( a->text() == "&Custom..." ) 378 if ( a->text() == "&Custom..." )
379 { 379 {
380 QMap<QString, QStringList> map; 380 QMap<QString, QStringList> map;
381 map.insert( tr("All"), QStringList() ); 381 map.insert( tr("All"), QStringList() );
382 QStringList text; 382 QStringList text;
383 text << "text/*"; 383 text << "text/*";
384 map.insert(tr("Text"), text ); 384 map.insert(tr("Text"), text );
385 text << "*"; 385 text << "*";
386 map.insert(tr("All"), text ); 386 map.insert(tr("All"), text );
387 387
388 QString str; 388 QString str;
389 str = OFileDialog::getSaveFileName( 2, "/", QString::null, map ); 389 str = OFileDialog::getSaveFileName( 2, "/", QString::null, map );
390 if ( str.isEmpty() || !QFileInfo(str).isDir() ) 390 if ( str.isEmpty() || !QFileInfo(str).isDir() )
391 { 391 {
392 docfolder->setOn( true ); 392 docfolder->setOn( true );
393 outputTo = "Documents Folder"; 393 outputTo = "Documents Folder";
394 } 394 }
395 else 395 else
396 { 396 {
397 outputTo = str; 397 outputTo = str;
398 } 398 }
399 } 399 }
400 else 400 else
401 { 401 {
402 outputTo = a->text(); 402 outputTo = a->text();
403 } 403 }
404 odebug << "Output to now: " << outputTo << oendl; 404 odebug << "Output to now: " << outputTo << oendl;
405} 405}
406 406
407 407
408void CameraMainWindow::outputMenuItemClicked( QAction* a ) 408void CameraMainWindow::outputMenuItemClicked( QAction* a )
409{ 409{
410 captureFormat = a->text(); 410 captureFormat = a->text();
411 odebug << "Output format now: " << captureFormat << oendl; 411 odebug << "Output format now: " << captureFormat << oendl;
412 updateCaption(); 412 updateCaption();
413} 413}
414 414
415 415
416void CameraMainWindow::prefixItemChoosen() 416void CameraMainWindow::prefixItemChoosen()
417{ 417{
418 QDialog* d = new QDialog( this, "dialog", true ); 418 QDialog* d = new QDialog( this, "dialog", true );
419 d->setCaption( "Enter Prefix..." ); 419 d->setCaption( "Enter Prefix..." );
420 QVBoxLayout* v = new QVBoxLayout( d ); 420 QVBoxLayout* v = new QVBoxLayout( d );
421 QLineEdit* le = new QLineEdit( prefix, d ); 421 QLineEdit* le = new QLineEdit( prefix, d );
422 v->addWidget( le ); 422 v->addWidget( le );
423 le->setFixedWidth( 150 ); //FIXME: 'tis a bit dirty 423 le->setFixedWidth( 150 ); //FIXME: 'tis a bit dirty
424 if ( d->exec() == QDialog::Accepted ) 424 if ( d->exec() == QDialog::Accepted )
425 prefix = le->text(); 425 prefix = le->text();
426 odebug << "Prefix now: " << prefix << oendl; 426 odebug << "Prefix now: " << prefix << oendl;
427} 427}
428 428
429 429
430void CameraMainWindow::appendSettingsChoosen() 430void CameraMainWindow::appendSettingsChoosen()
431{ 431{
432 appendSettings = !appendSettings; 432 appendSettings = !appendSettings;
433 odebug << "appendSettings now: " << appendSettings << oendl; 433 odebug << "appendSettings now: " << appendSettings << oendl;
434} 434}
435 435
436 436
437void CameraMainWindow::shutterClicked() 437void CameraMainWindow::shutterClicked()
438{ 438{
439 if ( captureFormat != "AVI" ) // capture one photo per shutterClick 439 if ( captureFormat != "AVI" ) // capture one photo per shutterClick
440 { 440 {
441 Global::statusMessage( "CAPTURING..." ); 441 Global::statusMessage( "CAPTURING..." );
442 qApp->processEvents(); 442 qApp->processEvents();
443 443
444 odebug << "Shutter has been pressed" << oendl; 444 odebug << "Shutter has been pressed" << oendl;
445 ODevice::inst()->playTouchSound(); 445 ODevice::inst()->playTouchSound();
446 446
447 performCapture( captureFormat ); 447 performCapture( captureFormat );
448 } 448 }
449 else // capture video! start with one shutter click and stop with the next 449 else // capture video! start with one shutter click and stop with the next
450 { 450 {
451 !_capturing ? startVideoCapture() : stopVideoCapture(); 451 !_capturing ? startVideoCapture() : stopVideoCapture();
452 } 452 }
453} 453}
454 454
455 455
456void CameraMainWindow::performCapture( const QString& format ) 456void CameraMainWindow::performCapture( const QString& format )
457{ 457{
458 QString name; 458 QString name;
459 459
460 if ( outputTo == "Documents Folder" ) 460 if ( outputTo == "Documents Folder" )
461 { 461 {
462 name.sprintf( "%s/Documents/image/%s/", (const char*) QDir::homeDirPath(), (const char*) captureFormat.lower() ); 462 name.sprintf( "%s/Documents/image/%s/", (const char*) QDir::homeDirPath(), (const char*) captureFormat.lower() );
463 if ( !QDir( name ).exists() ) 463 if ( !QDir( name ).exists() )
464 { 464 {
465 odebug << "creating directory " << name << oendl; 465 odebug << "creating directory " << name << oendl;
466 QString msg = "mkdir -p " + name; 466 QString msg = "mkdir -p " + name;
467 system( msg.latin1() ); 467 system( msg.latin1() );
468 } 468 }
469 } 469 }
470 else 470 else
471 name = outputTo; 471 name = outputTo;
472 472
473 name.append( prefix ); 473 name.append( prefix );
474 if ( appendSettings ) 474 if ( appendSettings )
475 { 475 {
476 name.append( QString().sprintf( "_%d_%d_q%d", captureX, captureY, quality ) ); 476 name.append( QString().sprintf( "_%d_%d_q%d", captureX, captureY, quality ) );
477 } 477 }
478 name.append( QString().sprintf( "-%d.%s", _pics++, (const char*) captureFormat.lower() ) ); 478 name.append( QString().sprintf( "-%d.%s", _pics++, (const char*) captureFormat.lower() ) );
479 479
480 QImage i; 480 QImage i;
481 ZCameraIO::instance()->captureFrame( captureX, captureY, zoom, &i ); 481 ZCameraIO::instance()->captureFrame( captureX, captureY, zoom, &i );
482 QImage im = i.convertDepth( 32 ); 482 QImage im = i.convertDepth( 32 );
483 bool result = im.save( name, format, quality ); 483 bool result = im.save( name, format, quality );
484 if ( !result ) 484 if ( !result )
485 { 485 {
486 oerr << "imageio-Problem while writing." << oendl; 486 oerr << "imageio-Problem while writing." << oendl;
487 Global::statusMessage( "Error!" ); 487 Global::statusMessage( "Error!" );
488 } 488 }
489 else 489 else
490 { 490 {
491 odebug << captureFormat << "-image has been successfully captured" << oendl; 491 odebug << captureFormat << "-image has been successfully captured" << oendl;
492 Global::statusMessage( "Ok." ); 492 Global::statusMessage( "Ok." );
493 } 493 }
494} 494}
495 495
496 496
497void CameraMainWindow::startVideoCapture() 497void CameraMainWindow::startVideoCapture()
498{ 498{
499 ODevice::inst()->playTouchSound(); 499 ODevice::inst()->playTouchSound();
500 ODevice::inst()->setLedState( Led_Mail, Led_BlinkSlow ); 500 ODevice::inst()->setLedState( Led_Mail, Led_BlinkSlow );
501 501
502 _capturefd = ::open( CAPTUREFILE, O_WRONLY | O_CREAT | O_TRUNC ); 502 _capturefd = ::open( CAPTUREFILE, O_WRONLY | O_CREAT | O_TRUNC );
503 if ( _capturefd == -1 ) 503 if ( _capturefd == -1 )
504 { 504 {
505 owarn << "can't open capture file: " << strerror(errno) << oendl; 505 owarn << "can't open capture file: " << strerror(errno) << oendl;
506 return; 506 return;
507 } 507 }
508 508
509 _capturebuf = new unsigned char[captureX*captureY*2]; 509 _capturebuf = new unsigned char[captureX*captureY*2];
510 _capturing = true; 510 _capturing = true;
511 _videopics = 0; 511 _videopics = 0;
512 _framerate = 0; 512 _framerate = 0;
513 updateCaption(); 513 updateCaption();
514 _time.start(); 514 _time.start();
515 preview->setRefreshingRate( 1000 ); 515 preview->setRefreshingRate( 1000 );
516 startTimer( 100 ); // too fast but that is ok 516 startTimer( 100 ); // too fast but that is ok
517} 517}
518 518
519 519
520void CameraMainWindow::timerEvent( QTimerEvent* ) 520void CameraMainWindow::timerEvent( QTimerEvent* )
521{ 521{
522 if ( !_capturing ) 522 if ( !_capturing )
523 { 523 {
524 odebug << "timer event in CameraMainWindow without capturing video ?" << oendl; 524 odebug << "timer event in CameraMainWindow without capturing video ?" << oendl;
525 return; 525 return;
526 } 526 }
527 527
528 odebug << "timer event during video - now capturing frame #" << _videopics+1 << oendl; 528 odebug << "timer event during video - now capturing frame #" << _videopics+1 << oendl;
529 529
530 ZCameraIO::instance()->captureFrame( captureX, captureY, zoom, _capturebuf ); 530 ZCameraIO::instance()->captureFrame( captureX, captureY, zoom, _capturebuf );
531 _videopics++; 531 _videopics++;
532 ::write( _capturefd, _capturebuf, captureX*captureY*2 ); 532 ::write( _capturefd, _capturebuf, captureX*captureY*2 );
533 setCaption( QString().sprintf( "Capturing %dx%d @ %.2f fps %d", 533 setCaption( QString().sprintf( "Capturing %dx%d @ %.2f fps %d",
534 captureX, captureY, 1000.0 / (_time.elapsed()/_videopics), _videopics ) ); 534 captureX, captureY, 1000.0 / (_time.elapsed()/_videopics), _videopics ) );
535} 535}
536 536
537 537
538void CameraMainWindow::stopVideoCapture() 538void CameraMainWindow::stopVideoCapture()
539{ 539{
540 killTimers(); 540 killTimers();
541 ODevice::inst()->playTouchSound(); 541 ODevice::inst()->playTouchSound();
542 ODevice::inst()->setLedState( Led_Mail, Led_Off ); 542 ODevice::inst()->setLedState( Led_Mail, Led_Off );
543 _capturing = false; 543 _capturing = false;
544 updateCaption(); 544 updateCaption();
545 ::close( _capturefd ); 545 ::close( _capturefd );
546 _framerate = 1000.0 / (_time.elapsed()/_videopics); 546 _framerate = 1000.0 / (_time.elapsed()/_videopics);
547 547
548 QString name; 548 QString name;
549 if ( outputTo == "Documents Folder" ) 549 if ( outputTo == "Documents Folder" )
550 { 550 {
551 name.sprintf( "%s/Documents/video/%s/", (const char*) QDir::homeDirPath(), (const char*) captureFormat.lower() ); 551 name.sprintf( "%s/Documents/video/%s/", (const char*) QDir::homeDirPath(), (const char*) captureFormat.lower() );
552 if ( !QDir( name ).exists() ) 552 if ( !QDir( name ).exists() )
553 { 553 {
554 odebug << "creating directory " << name << oendl; 554 odebug << "creating directory " << name << oendl;
555 QString msg = "mkdir -p " + name; 555 QString msg = "mkdir -p " + name;
556 system( msg.latin1() ); 556 system( msg.latin1() );
557 } 557 }
558 } 558 }
559 else 559 else
560 name = outputTo; 560 name = outputTo;
561 561
562 name.append( "/" ); // sure is sure and safe is safe ;-) 562 name.append( "/" ); // sure is sure and safe is safe ;-)
563 name.append( prefix ); 563 name.append( prefix );
564 if ( appendSettings ) 564 if ( appendSettings )
565 name.append( QString().sprintf( "_%d_%d_q%d_%dfps", captureX, captureY, quality, _framerate ) ); 565 name.append( QString().sprintf( "_%d_%d_q%d_%dfps", captureX, captureY, quality, _framerate ) );
566 name.append( QString().sprintf( "-%d.%s", _videos++, (const char*) captureFormat.lower() ) ); 566 name.append( QString().sprintf( "-%d.%s", _videos++, (const char*) captureFormat.lower() ) );
567 postProcessVideo( CAPTUREFILE, name ); 567 postProcessVideo( CAPTUREFILE, name );
568 568
569 #ifndef QT_NO_DEBUG 569 #ifndef QT_NO_DEBUG
570 preview->setRefreshingRate( 1500 ); 570 preview->setRefreshingRate( 1500 );
571 #else 571 #else
572 preview->setRefreshingRate( 200 ); 572 preview->setRefreshingRate( 200 );
573 #endif 573 #endif
574 574
575 //delete[] _capturebuf; //FIXME: close memory leak 575 //delete[] _capturebuf; //FIXME: close memory leak
576} 576}
577 577
578void CameraMainWindow::postProcessVideo( const QString& infile, const QString& outfile ) 578void CameraMainWindow::postProcessVideo( const QString& infile, const QString& outfile )
579{ 579{
580 odebug << "post processing " << infile << " --> " << outfile << oendl; 580 odebug << "post processing " << infile << " --> " << outfile << oendl;
581 581
582 preview->setRefreshingRate( 0 ); 582 preview->setRefreshingRate( 0 );
583 583
584 /* 584 /*
585 unsigned char buf[153600]; 585 unsigned char buf[153600];
586 586
587 int fd = ::open( "/var/compile/opie/noncore/multimedia/camera/capture-320x240.dat", O_RDONLY ); 587 int fd = ::open( "/var/compile/opie/noncore/multimedia/camera/capture-320x240.dat", O_RDONLY );
588 ::read( fd, &buf, 153600 ); 588 ::read( fd, &buf, 153600 );
589 QImage i; 589 QImage i;
590 bufferToImage( 240, 320, (unsigned char*) &buf, &i ); 590 bufferToImage( 240, 320, (unsigned char*) &buf, &i );
591 QPixmap p; 591 QPixmap p;
592 p.convertFromImage( i ); 592 p.convertFromImage( i );
593 preview->setPixmap( p ); 593 preview->setPixmap( p );
594 imageToFile( &i, "/tmp/tmpfile", "JPEG", 100 ); 594 imageToFile( &i, "/tmp/tmpfile", "JPEG", 100 );
595 return; 595 return;
596 */ 596 */
597 597
598 QDialog* fr = new QDialog( this, "splash", false, QWidget::WStyle_StaysOnTop ); //, false, QWidget::WStyle_NoBorder | QWidget::WStyle_Customize ); 598 QDialog* fr = new QDialog( this, "splash", false, QWidget::WStyle_StaysOnTop ); //, false, QWidget::WStyle_NoBorder | QWidget::WStyle_Customize );
599 fr->setCaption( "Please wait..." ); 599 fr->setCaption( "Please wait..." );
600 QVBoxLayout* box = new QVBoxLayout( fr, 2, 2 ); 600 QVBoxLayout* box = new QVBoxLayout( fr, 2, 2 );
601 QProgressBar* bar = new QProgressBar( fr ); 601 QProgressBar* bar = new QProgressBar( fr );
602 bar->setCenterIndicator( true ); 602 bar->setCenterIndicator( true );
603 bar->setTotalSteps( _videopics-1 ); 603 bar->setTotalSteps( _videopics-1 );
604 QLabel* label = new QLabel( "Post processing frame bla/bla", fr ); 604 QLabel* label = new QLabel( "Post processing frame bla/bla", fr );
605 box->addWidget( bar ); 605 box->addWidget( bar );
606 box->addWidget( label ); 606 box->addWidget( label );
607 fr->show(); 607 fr->show();
608 label->show(); 608 label->show();
609 bar->show(); 609 bar->show();
610 fr->repaint(); 610 fr->repaint();
611 qApp->processEvents(); 611 qApp->processEvents();
612 612
613 // open files 613 // open files
614 614
615 int infd = ::open( (const char*) infile, O_RDONLY ); 615 int infd = ::open( (const char*) infile, O_RDONLY );
616 if ( infd == -1 ) 616 if ( infd == -1 )
617 { 617 {
618 owarn << "couldn't open capture file: " << strerror(errno) << oendl; 618 owarn << "couldn't open capture file: " << strerror(errno) << oendl;
619 return; 619 return;
620 } 620 }
621 621
622 int outfd = ::open( (const char*) outfile, O_CREAT | O_WRONLY | O_TRUNC, 0644 ); 622 int outfd = ::open( (const char*) outfile, O_CREAT | O_WRONLY | O_TRUNC, 0644 );
623 if ( outfd == -1 ) 623 if ( outfd == -1 )
624 { 624 {
625 owarn << "couldn't open output file: " << strerror(errno) << oendl; 625 owarn << "couldn't open output file: " << strerror(errno) << oendl;
626 return; 626 return;
627 } 627 }
628 628
629 int framesize = captureX*captureY*2; 629 int framesize = captureX*captureY*2;
630 630
631 unsigned char* inbuffer = new unsigned char[ framesize ]; 631 unsigned char* inbuffer = new unsigned char[ framesize ];
632 QImage image; 632 QImage image;
633 633
634 avi_start( outfd, _videopics ); // write preambel 634 avi_start( outfd, _videopics ); // write preambel
635 635
636 // post process 636 // post process
637 637
638 for ( int i = 0; i < _videopics; ++i ) 638 for ( int i = 0; i < _videopics; ++i )
639 { 639 {
640 odebug << "processing frame " << i << oendl; 640 odebug << "processing frame " << i << oendl;
641 641
642 // <gui> 642 // <gui>
643 label->setText( QString().sprintf( "Post processing frame %d / %d", i+1, _videopics ) ); 643 label->setText( QString().sprintf( "Post processing frame %d / %d", i+1, _videopics ) );
644 bar->setProgress( i ); 644 bar->setProgress( i );
645 bar->repaint(); 645 bar->repaint();
646 qApp->processEvents(); 646 qApp->processEvents();
647 // </gui> 647 // </gui>
648 648
649 int read = ::read( infd, inbuffer, framesize ); 649 int read = ::read( infd, inbuffer, framesize );
650 odebug << "read " << read << " bytes" << oendl; 650 odebug << "read " << read << " bytes" << oendl;
651 bufferToImage( captureX, captureY, inbuffer, &image ); 651 bufferToImage( captureX, captureY, inbuffer, &image );
652 652
653 QPixmap p; 653 QPixmap p;
654 p.convertFromImage( image ); 654 p.convertFromImage( image );
655 preview->setPixmap( p ); 655 preview->setPixmap( p );
656 preview->repaint(); 656 preview->repaint();
657 qApp->processEvents(); 657 qApp->processEvents();
658 658
659 #ifdef CAMERA_EXTRA_DEBUG 659 #ifdef CAMERA_EXTRA_DEBUG
660 QString tmpfilename; 660 QString tmpfilename;
661 tmpfilename.sprintf( "/tmp/test/%04d.jpg", i ); 661 tmpfilename.sprintf( "/tmp/test/%04d.jpg", i );
662 #else 662 #else
663 QString tmpfilename( "/tmp/tempfile" ); 663 QString tmpfilename( "/tmp/tempfile" );
664 #endif 664 #endif
665 665
666 imageToFile( &image, tmpfilename, "JPEG", quality ); 666 imageToFile( &image, tmpfilename, "JPEG", quality );
667 667
668 QFile framefile( tmpfilename ); 668 QFile framefile( tmpfilename );
669 if ( !framefile.open( IO_ReadOnly ) ) 669 if ( !framefile.open( IO_ReadOnly ) )
670 { 670 {
671 oerr << "can't process file: %s" << strerror(errno) << oendl; 671 oerr << "can't process file: %s" << strerror(errno) << oendl;
672 return; // TODO: clean up temp ressources 672 return; // TODO: clean up temp ressources
673 } 673 }
674 674
675 int filesize = framefile.size(); 675 int filesize = framefile.size();
676 odebug << "filesize for frame " << i << " = " << filesize << oendl; 676 odebug << "filesize for frame " << i << " = " << filesize << oendl;
677 677
678 unsigned char* tempbuffer = new unsigned char[ filesize ]; 678 unsigned char* tempbuffer = new unsigned char[ filesize ];
679 framefile.readBlock( (char*) tempbuffer, filesize ); 679 framefile.readBlock( (char*) tempbuffer, filesize );
680 avi_add( outfd, tempbuffer, filesize ); 680 avi_add( outfd, tempbuffer, filesize );
681 delete tempbuffer; 681 delete tempbuffer;
682 framefile.close(); 682 framefile.close();
683 683
684 } 684 }
685 685
686 avi_end( outfd, captureX, captureY, _framerate ); 686 avi_end( outfd, captureX, captureY, _framerate );
687 ::close( outfd ); 687 ::close( outfd );
688 ::close( infd ); 688 ::close( infd );
689 689
690 label->setText( "deleting temp files..." ); 690 label->setText( "deleting temp files..." );
691 qApp->processEvents(); 691 qApp->processEvents();
692 odebug << "deleting temporary capturefile " << infile << oendl; 692 odebug << "deleting temporary capturefile " << infile << oendl;
693 QFile::remove( infile ); 693 QFile::remove( infile );
694 694
695 fr->hide(); 695 fr->hide();
696 delete fr; 696 delete fr;
697 697
698 updateCaption(); 698 updateCaption();
699 699
700} 700}
701 701
702 702
703void CameraMainWindow::updateCaption() 703void CameraMainWindow::updateCaption()
704{ 704{
705 if ( !_capturing ) 705 if ( !_capturing )
706 setCaption( QString().sprintf( "Opie-Camera: %dx%d %s q%d z%d (%s)", captureX, captureY, (const char*) captureFormat.lower(), quality, zoom, (const char*) flip ) ); 706 setCaption( QString().sprintf( "Opie-Camera: %dx%d %s q%d z%d (%s)", captureX, captureY, (const char*) captureFormat.lower(), quality, zoom, (const char*) flip ) );
707 else 707 else
708 setCaption( "Opie-Camera: => CAPTURING <=" ); 708 setCaption( "Opie-Camera: => CAPTURING <=" );
709 qApp->processEvents(); 709 qApp->processEvents();
710} 710}
711 711
712 712
713#ifndef QT_NO_DEBUG 713#ifndef QT_NO_DEBUG
714void CameraMainWindow::doSomething() 714void CameraMainWindow::doSomething()
715{ 715{
716 captureX = 240; 716 captureX = 240;
717 captureY = 320; 717 captureY = 320;
718 _videopics = 50; 718 _videopics = 50;
719 _framerate = 5; 719 _framerate = 5;
720 postProcessVideo( "/var/compile/opie/noncore/multimedia/camera/capture.dat", 720 postProcessVideo( "/var/compile/opie/noncore/multimedia/camera/capture.dat",
721 "/tmp/output.avi" ); 721 "/tmp/output.avi" );
722} 722}
723#else 723#else
724void CameraMainWindow::doSomething() 724void CameraMainWindow::doSomething()
725{ 725{
726} 726}
727#endif 727#endif
728 728
diff --git a/noncore/multimedia/opieplayer2/audiowidget.cpp b/noncore/multimedia/opieplayer2/audiowidget.cpp
index 870b4f3..f3eafab 100644
--- a/noncore/multimedia/opieplayer2/audiowidget.cpp
+++ b/noncore/multimedia/opieplayer2/audiowidget.cpp
@@ -1,326 +1,326 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org>
5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
7 =. 7 =.
8 .=l. 8 .=l.
9           .>+-= 9           .>+-=
10 _;:,     .>    :=|. This program is free software; you can 10 _;:,     .>    :=|. This program is free software; you can
11.> <`_,   >  .   <= redistribute it and/or modify it under 11.> <`_,   >  .   <= redistribute it and/or modify it under
12:`=1 )Y*s>-.--   : the terms of the GNU General Public 12:`=1 )Y*s>-.--   : the terms of the GNU General Public
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; Library General Public License for more 22..}^=.=       =       ; Library General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = Library General Public License along with 26  -_. . .   )=.  = Library General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34 34
35#include "audiowidget.h" 35#include "audiowidget.h"
36#include "mediaplayerstate.h" 36#include "mediaplayerstate.h"
37#include "playlistwidget.h" 37#include "playlistwidget.h"
38 38
39#include <qpe/qpeapplication.h> 39#include <qpe/qpeapplication.h>
40 40
41namespace 41namespace
42{ 42{
43 43
44const int xo = -2; // movable x offset 44const int xo = -2; // movable x offset
45const int yo = 22; // movable y offset 45const int yo = 22; // movable y offset
46 46
47const MediaWidget::SkinButtonInfo skinInfo[] = 47const MediaWidget::SkinButtonInfo skinInfo[] =
48{ 48{
49 { MediaWidget::Play, "play", MediaWidget::ToggleButton }, 49 { MediaWidget::Play, "play", MediaWidget::ToggleButton },
50 { MediaWidget::Stop, "stop", MediaWidget::NormalButton }, 50 { MediaWidget::Stop, "stop", MediaWidget::NormalButton },
51 { MediaWidget::Next, "next", MediaWidget::NormalButton }, 51 { MediaWidget::Next, "next", MediaWidget::NormalButton },
52 { MediaWidget::Previous, "prev", MediaWidget::NormalButton }, 52 { MediaWidget::Previous, "prev", MediaWidget::NormalButton },
53 { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton }, 53 { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton },
54 { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton }, 54 { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton },
55 { MediaWidget::Loop, "loop", MediaWidget::ToggleButton }, 55 { MediaWidget::Loop, "loop", MediaWidget::ToggleButton },
56 { MediaWidget::PlayList, "playlist", MediaWidget::NormalButton }, 56 { MediaWidget::PlayList, "playlist", MediaWidget::NormalButton },
57 { MediaWidget::Forward, "forward", MediaWidget::NormalButton }, 57 { MediaWidget::Forward, "forward", MediaWidget::NormalButton },
58 { MediaWidget::Back, "back", MediaWidget::NormalButton } 58 { MediaWidget::Back, "back", MediaWidget::NormalButton }
59}; 59};
60 60
61const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] ); 61const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] );
62 62
63void changeTextColor( QWidget * w) { 63void changeTextColor( QWidget * w) {
64 QPalette p = w->palette(); 64 QPalette p = w->palette();
65 p.setBrush( QColorGroup::Background, QColor( 167, 212, 167 ) ); 65 p.setBrush( QColorGroup::Background, QColor( 167, 212, 167 ) );
66 p.setBrush( QColorGroup::Base, QColor( 167, 212, 167 ) ); 66 p.setBrush( QColorGroup::Base, QColor( 167, 212, 167 ) );
67 w->setPalette( p ); 67 w->setPalette( p );
68} 68}
69 69
70} 70}
71 71
72AudioWidget::AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name) : 72AudioWidget::AudioWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name) :
73 73
74 MediaWidget( playList, mediaPlayerState, parent, name ), songInfo( this ), slider( Qt::Horizontal, this ), time( this ), 74 MediaWidget( playList, mediaPlayerState, parent, name ), songInfo( this ), slider( Qt::Horizontal, this ), time( this ),
75 audioSliderBeingMoved( false ) 75 audioSliderBeingMoved( false )
76{ 76{
77 setCaption( tr("OpiePlayer") ); 77 setCaption( tr("OpiePlayer") );
78 78
79 loadSkin(); 79 loadSkin();
80 80
81 connect( &mediaPlayerState, SIGNAL( loopingToggled(bool) ), this, SLOT( setLooping(bool) ) ); 81 connect( &mediaPlayerState, SIGNAL( loopingToggled(bool) ), this, SLOT( setLooping(bool) ) );
82 connect( &mediaPlayerState, SIGNAL( isSeekableToggled( bool ) ), this, SLOT( setSeekable( bool ) ) ); 82 connect( &mediaPlayerState, SIGNAL( isSeekableToggled(bool) ), this, SLOT( setSeekable(bool) ) );
83 83
84 connect( this, SIGNAL( forwardClicked() ), this, SLOT( skipFor() ) ); 84 connect( this, SIGNAL( forwardClicked() ), this, SLOT( skipFor() ) );
85 connect( this, SIGNAL( backClicked() ), this, SLOT( skipBack() ) ); 85 connect( this, SIGNAL( backClicked() ), this, SLOT( skipBack() ) );
86 connect( this, SIGNAL( forwardReleased() ), this, SLOT( stopSkip() ) ); 86 connect( this, SIGNAL( forwardReleased() ), this, SLOT( stopSkip() ) );
87 connect( this, SIGNAL( backReleased() ), this, SLOT( stopSkip() ) ); 87 connect( this, SIGNAL( backReleased() ), this, SLOT( stopSkip() ) );
88 88
89 // Intialise state 89 // Intialise state
90 setLength( mediaPlayerState.length() ); 90 setLength( mediaPlayerState.length() );
91 setPosition( mediaPlayerState.position() ); 91 setPosition( mediaPlayerState.position() );
92 setLooping( mediaPlayerState.isFullscreen() ); 92 setLooping( mediaPlayerState.isFullscreen() );
93 // setPaused( mediaPlayerState->paused() ); 93 // setPaused( mediaPlayerState->paused() );
94 setPlaying( mediaPlayerState.isPlaying() ); 94 setPlaying( mediaPlayerState.isPlaying() );
95} 95}
96 96
97AudioWidget::~AudioWidget() { 97AudioWidget::~AudioWidget() {
98 98
99// mediaPlayerState->setPlaying(false); 99// mediaPlayerState->setPlaying(false);
100} 100}
101 101
102MediaWidget::GUIInfo AudioWidget::guiInfo() 102MediaWidget::GUIInfo AudioWidget::guiInfo()
103{ 103{
104 return GUIInfo( QString::null /* infix */, ::skinInfo, ::buttonCount ); 104 return GUIInfo( QString::null /* infix */, ::skinInfo, ::buttonCount );
105} 105}
106 106
107void AudioWidget::resizeEvent( QResizeEvent *e ) { 107void AudioWidget::resizeEvent( QResizeEvent *e ) {
108 int h = height(); 108 int h = height();
109 int w = width(); 109 int w = width();
110 110
111 songInfo.setGeometry( QRect( 2, 2, w - 4, 20 ) ); 111 songInfo.setGeometry( QRect( 2, 2, w - 4, 20 ) );
112 slider.setFixedWidth( w - 110 ); 112 slider.setFixedWidth( w - 110 );
113 slider.setGeometry( QRect( 15, h - 22, w - 90, 20 ) ); 113 slider.setGeometry( QRect( 15, h - 22, w - 90, 20 ) );
114 slider.setBackgroundOrigin( QWidget::ParentOrigin ); 114 slider.setBackgroundOrigin( QWidget::ParentOrigin );
115 time.setGeometry( QRect( w - 85, h - 30, 70, 20 ) ); 115 time.setGeometry( QRect( w - 85, h - 30, 70, 20 ) );
116 116
117 upperLeftOfButtonMask.rx() = ( w - buttonUpImage.width() ) / 2; 117 upperLeftOfButtonMask.rx() = ( w - buttonUpImage.width() ) / 2;
118 upperLeftOfButtonMask.ry() = (( h - buttonUpImage.height() ) / 2) - 10; 118 upperLeftOfButtonMask.ry() = (( h - buttonUpImage.height() ) / 2) - 10;
119 119
120 MediaWidget::resizeEvent( e ); 120 MediaWidget::resizeEvent( e );
121} 121}
122 122
123void AudioWidget::sliderPressed() { 123void AudioWidget::sliderPressed() {
124 audioSliderBeingMoved = TRUE; 124 audioSliderBeingMoved = TRUE;
125} 125}
126 126
127 127
128void AudioWidget::sliderReleased() { 128void AudioWidget::sliderReleased() {
129 audioSliderBeingMoved = FALSE; 129 audioSliderBeingMoved = FALSE;
130 if ( slider.width() == 0 ) 130 if ( slider.width() == 0 )
131 return; 131 return;
132 long val = long((double)slider.value() * mediaPlayerState.length() / slider.width()); 132 long val = long((double)slider.value() * mediaPlayerState.length() / slider.width());
133 mediaPlayerState.setPosition( val ); 133 mediaPlayerState.setPosition( val );
134} 134}
135 135
136void AudioWidget::setPosition( long i ) { 136void AudioWidget::setPosition( long i ) {
137 // qDebug("<<<<<<<<<<<<<<<<<<<<<<<<set position %d",i); 137 // qDebug("<<<<<<<<<<<<<<<<<<<<<<<<set position %d",i);
138 updateSlider( i, mediaPlayerState.length() ); 138 updateSlider( i, mediaPlayerState.length() );
139} 139}
140 140
141 141
142void AudioWidget::setLength( long max ) { 142void AudioWidget::setLength( long max ) {
143 updateSlider( mediaPlayerState.position(), max ); 143 updateSlider( mediaPlayerState.position(), max );
144} 144}
145 145
146 146
147void AudioWidget::setDisplayType( MediaPlayerState::DisplayType mediaType ) { 147void AudioWidget::setDisplayType( MediaPlayerState::DisplayType mediaType ) {
148 if ( mediaType == MediaPlayerState::Audio ) { 148 if ( mediaType == MediaPlayerState::Audio ) {
149 // startTimer( 150 ); 149 // startTimer( 150 );
150 QPEApplication::showWidget( this ); 150 QPEApplication::showWidget( this );
151 return; 151 return;
152 } 152 }
153 153
154 killTimers(); 154 killTimers();
155 hide(); 155 hide();
156} 156}
157 157
158void AudioWidget::loadSkin() 158void AudioWidget::loadSkin()
159{ 159{
160 loadDefaultSkin( guiInfo() ); 160 loadDefaultSkin( guiInfo() );
161 161
162 songInfo.setFocusPolicy( QWidget::NoFocus ); 162 songInfo.setFocusPolicy( QWidget::NoFocus );
163// changeTextColor( &songInfo ); 163// changeTextColor( &songInfo );
164// songInfo.setBackgroundColor( QColor( 167, 212, 167 )); 164// songInfo.setBackgroundColor( QColor( 167, 212, 167 ));
165// songInfo.setFrameStyle( QFrame::NoFrame); 165// songInfo.setFrameStyle( QFrame::NoFrame);
166 songInfo.setFrameStyle( QFrame::WinPanel | QFrame::Sunken ); 166 songInfo.setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
167// songInfo.setForegroundColor(Qt::white); 167// songInfo.setForegroundColor(Qt::white);
168 168
169 slider.setFixedHeight( 20 ); 169 slider.setFixedHeight( 20 );
170 slider.setMinValue( 0 ); 170 slider.setMinValue( 0 );
171 slider.setMaxValue( 1 ); 171 slider.setMaxValue( 1 );
172 slider.setFocusPolicy( QWidget::NoFocus ); 172 slider.setFocusPolicy( QWidget::NoFocus );
173 slider.setBackgroundPixmap( backgroundPixmap ); 173 slider.setBackgroundPixmap( backgroundPixmap );
174 174
175// Config cofg("qpe"); 175// Config cofg("qpe");
176// cofg.setGroup("Appearance"); 176// cofg.setGroup("Appearance");
177// QColor backgroundcolor = QColor( cofg.readEntry( "Background", "#E5E1D5" ) ); 177// QColor backgroundcolor = QColor( cofg.readEntry( "Background", "#E5E1D5" ) );
178 178
179 time.setFocusPolicy( QWidget::NoFocus ); 179 time.setFocusPolicy( QWidget::NoFocus );
180 time.setAlignment( Qt::AlignCenter ); 180 time.setAlignment( Qt::AlignCenter );
181 181
182// time.setFrame(FALSE); 182// time.setFrame(FALSE);
183// changeTextColor( &time ); 183// changeTextColor( &time );
184 184
185 resizeEvent( 0 ); 185 resizeEvent( 0 );
186} 186}
187 187
188void AudioWidget::setSeekable( bool isSeekable ) { 188void AudioWidget::setSeekable( bool isSeekable ) {
189 189
190 if ( !isSeekable ) { 190 if ( !isSeekable ) {
191 qDebug("<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>"); 191 qDebug("<<<<<<<<<<<<<<file is STREAMING>>>>>>>>>>>>>>>>>>>");
192 if( !slider.isHidden()) { 192 if( !slider.isHidden()) {
193 slider.hide(); 193 slider.hide();
194 } 194 }
195 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 195 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
196 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 196 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
197 disconnect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 197 disconnect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
198 disconnect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 198 disconnect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
199 } else { 199 } else {
200 // this stops the slider from being moved, thus 200 // this stops the slider from being moved, thus
201 // does not stop stream when it reaches the end 201 // does not stop stream when it reaches the end
202 slider.show(); 202 slider.show();
203 qDebug( " CONNECT SET POSTION " ); 203 qDebug( " CONNECT SET POSTION " );
204 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 204 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
205 connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 205 connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
206 connect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 206 connect( &slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
207 connect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 207 connect( &slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
208 } 208 }
209} 209}
210 210
211 211
212static QString timeAsString( long length ) { 212static QString timeAsString( long length ) {
213 int minutes = length / 60; 213 int minutes = length / 60;
214 int seconds = length % 60; 214 int seconds = length % 60;
215 return QString("%1:%2%3").arg( minutes ).arg( seconds / 10 ).arg( seconds % 10 ); 215 return QString("%1:%2%3").arg( minutes ).arg( seconds / 10 ).arg( seconds % 10 );
216} 216}
217 217
218void AudioWidget::updateSlider( long i, long max ) { 218void AudioWidget::updateSlider( long i, long max ) {
219 219
220 time.setText( timeAsString( i ) + " / " + timeAsString( max ) ); 220 time.setText( timeAsString( i ) + " / " + timeAsString( max ) );
221// qDebug( timeAsString( i ) + " / " + timeAsString( max ) ) ; 221// qDebug( timeAsString( i ) + " / " + timeAsString( max ) ) ;
222 222
223 if ( max == 0 ) { 223 if ( max == 0 ) {
224 return; 224 return;
225 } 225 }
226 // Will flicker too much if we don't do this 226 // Will flicker too much if we don't do this
227 // Scale to something reasonable 227 // Scale to something reasonable
228 int width = slider.width(); 228 int width = slider.width();
229 int val = int((double)i * width / max); 229 int val = int((double)i * width / max);
230 if ( !audioSliderBeingMoved ) { 230 if ( !audioSliderBeingMoved ) {
231 if ( slider.value() != val ) { 231 if ( slider.value() != val ) {
232 slider.setValue( val ); 232 slider.setValue( val );
233 } 233 }
234 234
235 if ( slider.maxValue() != width ) { 235 if ( slider.maxValue() != width ) {
236 slider.setMaxValue( width ); 236 slider.setMaxValue( width );
237 } 237 }
238 } 238 }
239} 239}
240 240
241void AudioWidget::skipFor() { 241void AudioWidget::skipFor() {
242 skipDirection = +1; 242 skipDirection = +1;
243 startTimer( 50 ); 243 startTimer( 50 );
244 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 ); 244 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 );
245} 245}
246 246
247void AudioWidget::skipBack() { 247void AudioWidget::skipBack() {
248 skipDirection = -1; 248 skipDirection = -1;
249 startTimer( 50 ); 249 startTimer( 50 );
250 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 ); 250 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 );
251} 251}
252 252
253 253
254 254
255void AudioWidget::stopSkip() { 255void AudioWidget::stopSkip() {
256 killTimers(); 256 killTimers();
257} 257}
258 258
259 259
260void AudioWidget::timerEvent( QTimerEvent * ) { 260void AudioWidget::timerEvent( QTimerEvent * ) {
261 if ( skipDirection == +1 ) { 261 if ( skipDirection == +1 ) {
262 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 ); 262 mediaPlayerState.setPosition( mediaPlayerState.position() + 2 );
263 } else if ( skipDirection == -1 ) { 263 } else if ( skipDirection == -1 ) {
264 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 ); 264 mediaPlayerState.setPosition( mediaPlayerState.position() - 2 );
265 } 265 }
266} 266}
267 267
268void AudioWidget::keyReleaseEvent( QKeyEvent *e) { 268void AudioWidget::keyReleaseEvent( QKeyEvent *e) {
269 switch ( e->key() ) { 269 switch ( e->key() ) {
270 ////////////////////////////// Zaurus keys 270 ////////////////////////////// Zaurus keys
271 case Key_Home: 271 case Key_Home:
272 break; 272 break;
273 case Key_F9: //activity 273 case Key_F9: //activity
274 hide(); 274 hide();
275 // qDebug("Audio F9"); 275 // qDebug("Audio F9");
276 e->accept(); 276 e->accept();
277 break; 277 break;
278 case Key_F10: //contacts 278 case Key_F10: //contacts
279 break; 279 break;
280 case Key_F11: //menu 280 case Key_F11: //menu
281 mediaPlayerState.toggleBlank(); 281 mediaPlayerState.toggleBlank();
282 e->accept(); 282 e->accept();
283 break; 283 break;
284 case Key_F12: //home 284 case Key_F12: //home
285 break; 285 break;
286 case Key_F13: //mail 286 case Key_F13: //mail
287 mediaPlayerState.toggleBlank(); 287 mediaPlayerState.toggleBlank();
288 e->accept(); 288 e->accept();
289 break; 289 break;
290 case Key_Space: { 290 case Key_Space: {
291 e->accept(); 291 e->accept();
292 mediaPlayerState.togglePaused(); 292 mediaPlayerState.togglePaused();
293 } 293 }
294 break; 294 break;
295 case Key_Down: 295 case Key_Down:
296 // toggleButton(6); 296 // toggleButton(6);
297 emit lessClicked(); 297 emit lessClicked();
298 emit lessReleased(); 298 emit lessReleased();
299 // toggleButton(6); 299 // toggleButton(6);
300 e->accept(); 300 e->accept();
301 break; 301 break;
302 case Key_Up: 302 case Key_Up:
303 // toggleButton(5); 303 // toggleButton(5);
304 emit moreClicked(); 304 emit moreClicked();
305 emit moreReleased(); 305 emit moreReleased();
306 // toggleButton(5); 306 // toggleButton(5);
307 e->accept(); 307 e->accept();
308 break; 308 break;
309 case Key_Right: 309 case Key_Right:
310 // toggleButton(3); 310 // toggleButton(3);
311 mediaPlayerState.setNext(); 311 mediaPlayerState.setNext();
312 // toggleButton(3); 312 // toggleButton(3);
313 e->accept(); 313 e->accept();
314 break; 314 break;
315 case Key_Left: 315 case Key_Left:
316 // toggleButton(4); 316 // toggleButton(4);
317 mediaPlayerState.setPrev(); 317 mediaPlayerState.setPrev();
318 // toggleButton(4); 318 // toggleButton(4);
319 e->accept(); 319 e->accept();
320 break; 320 break;
321 case Key_Escape: { 321 case Key_Escape: {
322 } 322 }
323 break; 323 break;
324 324
325 }; 325 };
326} 326}
diff --git a/noncore/multimedia/opieplayer2/mediaplayer.cpp b/noncore/multimedia/opieplayer2/mediaplayer.cpp
index 9f51006..1e6bc4d 100644
--- a/noncore/multimedia/opieplayer2/mediaplayer.cpp
+++ b/noncore/multimedia/opieplayer2/mediaplayer.cpp
@@ -1,405 +1,405 @@
1#include <qpe/qpeapplication.h> 1#include <qpe/qpeapplication.h>
2#include <qpe/config.h> 2#include <qpe/config.h>
3#include <qpe/qcopenvelope_qws.h> 3#include <qpe/qcopenvelope_qws.h>
4#include <qfileinfo.h> 4#include <qfileinfo.h>
5 5
6#include "mediaplayer.h" 6#include "mediaplayer.h"
7#include "playlistwidget.h" 7#include "playlistwidget.h"
8#include "audiowidget.h" 8#include "audiowidget.h"
9#include "videowidget.h" 9#include "videowidget.h"
10#include "volumecontrol.h" 10#include "volumecontrol.h"
11#include "lib.h" 11#include "lib.h"
12 12
13#include "mediaplayerstate.h" 13#include "mediaplayerstate.h"
14 14
15 // for setBacklight() 15 // for setBacklight()
16#include <linux/fb.h> 16#include <linux/fb.h>
17#include <sys/file.h> 17#include <sys/file.h>
18#include <sys/ioctl.h> 18#include <sys/ioctl.h>
19 19
20 20
21#define FBIOBLANK 0x4611 21#define FBIOBLANK 0x4611
22 22
23MediaPlayer::MediaPlayer( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name ) 23MediaPlayer::MediaPlayer( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QObject *parent, const char *name )
24 : QObject( parent, name ), volumeDirection( 0 ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) { 24 : QObject( parent, name ), volumeDirection( 0 ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) {
25 25
26 m_audioUI = 0; 26 m_audioUI = 0;
27 m_videoUI = 0; 27 m_videoUI = 0;
28 m_xineControl = 0; 28 m_xineControl = 0;
29 xine = new XINE::Lib( XINE::Lib::InitializeInThread ); 29 xine = new XINE::Lib( XINE::Lib::InitializeInThread );
30 30
31 fd=-1;fl=-1; 31 fd=-1;fl=-1;
32 playList.setCaption( tr( "OpiePlayer: Initializating" ) ); 32 playList.setCaption( tr( "OpiePlayer: Initializating" ) );
33 33
34 qApp->processEvents(); 34 qApp->processEvents();
35 // QPEApplication::grabKeyboard(); // EVIL 35 // QPEApplication::grabKeyboard(); // EVIL
36 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 36 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
37 37
38 connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), this, SLOT( setPlaying( bool ) ) ); 38 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( setPlaying(bool) ) );
39 39
40// What is pauseCheck good for? (Simon) 40// What is pauseCheck good for? (Simon)
41// connect( &mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( pauseCheck( bool ) ) ); 41// connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pauseCheck(bool) ) );
42 42
43 connect( &mediaPlayerState, SIGNAL( next() ), this, SLOT( next() ) ); 43 connect( &mediaPlayerState, SIGNAL( next() ), this, SLOT( next() ) );
44 connect( &mediaPlayerState, SIGNAL( prev() ), this, SLOT( prev() ) ); 44 connect( &mediaPlayerState, SIGNAL( prev() ), this, SLOT( prev() ) );
45 connect( &mediaPlayerState, SIGNAL( blankToggled( bool ) ), this, SLOT ( blank( bool ) ) ); 45 connect( &mediaPlayerState, SIGNAL( blankToggled(bool) ), this, SLOT ( blank(bool) ) );
46 46
47 volControl = new VolumeControl; 47 volControl = new VolumeControl;
48 Config cfg( "OpiePlayer" ); 48 Config cfg( "OpiePlayer" );
49 cfg.setGroup("PlayList"); 49 cfg.setGroup("PlayList");
50 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default"); 50 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default");
51 playList.setCaption( tr( "OpiePlayer: " ) + QFileInfo(currentPlaylist).baseName() ); 51 playList.setCaption( tr( "OpiePlayer: " ) + QFileInfo(currentPlaylist).baseName() );
52 52
53 m_skinLoader = new SkinLoader; 53 m_skinLoader = new SkinLoader;
54 m_skinLoader->schedule( AudioWidget::guiInfo() ); 54 m_skinLoader->schedule( AudioWidget::guiInfo() );
55 m_skinLoader->schedule( VideoWidget::guiInfo() ); 55 m_skinLoader->schedule( VideoWidget::guiInfo() );
56 m_skinLoader->start(); 56 m_skinLoader->start();
57} 57}
58 58
59MediaPlayer::~MediaPlayer() { 59MediaPlayer::~MediaPlayer() {
60 // this shold never happen, but one never knows... 60 // this shold never happen, but one never knows...
61 if ( xine ) { 61 if ( xine ) {
62 xine->ensureInitialized(); 62 xine->ensureInitialized();
63 delete xine; 63 delete xine;
64 } 64 }
65 delete m_xineControl; 65 delete m_xineControl;
66 delete m_audioUI; 66 delete m_audioUI;
67 delete m_videoUI; 67 delete m_videoUI;
68 delete volControl; 68 delete volControl;
69} 69}
70 70
71void MediaPlayer::pauseCheck( bool b ) { 71void MediaPlayer::pauseCheck( bool b ) {
72 if ( b && !mediaPlayerState.isPlaying() ) { 72 if ( b && !mediaPlayerState.isPlaying() ) {
73 mediaPlayerState.setPaused( FALSE ); 73 mediaPlayerState.setPaused( FALSE );
74 } 74 }
75} 75}
76 76
77void MediaPlayer::play() { 77void MediaPlayer::play() {
78 mediaPlayerState.setPlaying( FALSE ); 78 mediaPlayerState.setPlaying( FALSE );
79 mediaPlayerState.setPlaying( TRUE ); 79 mediaPlayerState.setPlaying( TRUE );
80} 80}
81 81
82void MediaPlayer::setPlaying( bool play ) { 82void MediaPlayer::setPlaying( bool play ) {
83 if ( !play ) { 83 if ( !play ) {
84 return; 84 return;
85 } 85 }
86 86
87 if ( mediaPlayerState.isPaused() ) { 87 if ( mediaPlayerState.isPaused() ) {
88 mediaPlayerState.setPaused( FALSE ); 88 mediaPlayerState.setPaused( FALSE );
89 return; 89 return;
90 } 90 }
91 91
92 QString tickerText, time, fileName; 92 QString tickerText, time, fileName;
93 if ( playList.currentTab() != PlayListWidget::CurrentPlayList ) { 93 if ( playList.currentTab() != PlayListWidget::CurrentPlayList ) {
94 //if playing in file list.. play in a different way 94 //if playing in file list.. play in a different way
95 // random and looping settings enabled causes problems here, 95 // random and looping settings enabled causes problems here,
96 // since there is no selected file in the playlist, but a selected file in the file list, 96 // since there is no selected file in the playlist, but a selected file in the file list,
97 // so we remember and shutoff 97 // so we remember and shutoff
98 l = mediaPlayerState.isLooping(); 98 l = mediaPlayerState.isLooping();
99 if(l) { 99 if(l) {
100 mediaPlayerState.setLooping( false ); 100 mediaPlayerState.setLooping( false );
101 } 101 }
102 r = mediaPlayerState.isShuffled(); 102 r = mediaPlayerState.isShuffled();
103 mediaPlayerState.setShuffled( false ); 103 mediaPlayerState.setShuffled( false );
104 } 104 }
105 105
106 PlayListWidget::Entry playListEntry = playList.currentEntry(); 106 PlayListWidget::Entry playListEntry = playList.currentEntry();
107 fileName = playListEntry.name; 107 fileName = playListEntry.name;
108 xineControl()->play( playListEntry.file ); 108 xineControl()->play( playListEntry.file );
109 109
110 long seconds = mediaPlayerState.length(); 110 long seconds = mediaPlayerState.length();
111 time.sprintf("%li:%02i", seconds/60, (int)seconds%60 ); 111 time.sprintf("%li:%02i", seconds/60, (int)seconds%60 );
112 112
113 if( fileName.left(4) == "http" ) { 113 if( fileName.left(4) == "http" ) {
114 fileName = QFileInfo( fileName ).baseName(); 114 fileName = QFileInfo( fileName ).baseName();
115 if ( xineControl()->getMetaInfo().isEmpty() ) { 115 if ( xineControl()->getMetaInfo().isEmpty() ) {
116 tickerText = tr( " File: " ) + fileName; 116 tickerText = tr( " File: " ) + fileName;
117 } else { 117 } else {
118 tickerText = xineControl()->getMetaInfo(); 118 tickerText = xineControl()->getMetaInfo();
119 } 119 }
120 } else { 120 } else {
121 if ( xineControl()->getMetaInfo().isEmpty() ) { 121 if ( xineControl()->getMetaInfo().isEmpty() ) {
122 tickerText = tr( " File: " ) + fileName + tr( ", Length: " ) + time + " "; 122 tickerText = tr( " File: " ) + fileName + tr( ", Length: " ) + time + " ";
123 } else { 123 } else {
124 tickerText = xineControl()->getMetaInfo() + " Length: " + time + " "; 124 tickerText = xineControl()->getMetaInfo() + " Length: " + time + " ";
125 } 125 }
126 } 126 }
127 audioUI()->setTickerText( tickerText ); 127 audioUI()->setTickerText( tickerText );
128} 128}
129 129
130 130
131void MediaPlayer::prev() { 131void MediaPlayer::prev() {
132 if( playList.currentTab() == PlayListWidget::CurrentPlayList ) { //if using the playlist 132 if( playList.currentTab() == PlayListWidget::CurrentPlayList ) { //if using the playlist
133 if ( playList.prev() ) { 133 if ( playList.prev() ) {
134 play(); 134 play();
135 } else if ( mediaPlayerState.isLooping() ) { 135 } else if ( mediaPlayerState.isLooping() ) {
136 if ( playList.last() ) { 136 if ( playList.last() ) {
137 play(); 137 play();
138 } 138 }
139 } else { 139 } else {
140 mediaPlayerState.setList(); 140 mediaPlayerState.setList();
141 } 141 }
142 } 142 }
143} 143}
144 144
145 145
146void MediaPlayer::next() { 146void MediaPlayer::next() {
147 147
148 if(playList.currentTab() == PlayListWidget::CurrentPlayList) { //if using the playlist 148 if(playList.currentTab() == PlayListWidget::CurrentPlayList) { //if using the playlist
149 if ( playList.next() ) { 149 if ( playList.next() ) {
150 play(); 150 play();
151 } else if ( mediaPlayerState.isLooping() ) { 151 } else if ( mediaPlayerState.isLooping() ) {
152 if ( playList.first() ) { 152 if ( playList.first() ) {
153 play(); 153 play();
154 } 154 }
155 } else { 155 } else {
156 mediaPlayerState.setList(); 156 mediaPlayerState.setList();
157 } 157 }
158 } else { //if playing from file list, let's just stop 158 } else { //if playing from file list, let's just stop
159 qDebug("<<<<<<<<<<<<<<<<<stop for filelists"); 159 qDebug("<<<<<<<<<<<<<<<<<stop for filelists");
160 mediaPlayerState.setPlaying(false); 160 mediaPlayerState.setPlaying(false);
161 mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection ); 161 mediaPlayerState.setDisplayType( MediaPlayerState::MediaSelection );
162 if(l) mediaPlayerState.setLooping(l); 162 if(l) mediaPlayerState.setLooping(l);
163 if(r) mediaPlayerState.setShuffled(r); 163 if(r) mediaPlayerState.setShuffled(r);
164 } 164 }
165 qApp->processEvents(); 165 qApp->processEvents();
166} 166}
167 167
168 168
169void MediaPlayer::startDecreasingVolume() { 169void MediaPlayer::startDecreasingVolume() {
170 volumeDirection = -1; 170 volumeDirection = -1;
171 startTimer( 100 ); 171 startTimer( 100 );
172 volControl->decVol(2); 172 volControl->decVol(2);
173} 173}
174 174
175 175
176void MediaPlayer::startIncreasingVolume() { 176void MediaPlayer::startIncreasingVolume() {
177 volumeDirection = +1; 177 volumeDirection = +1;
178 startTimer( 100 ); 178 startTimer( 100 );
179 volControl->incVol(2); 179 volControl->incVol(2);
180} 180}
181 181
182 182
183bool drawnOnScreenDisplay = FALSE; 183bool drawnOnScreenDisplay = FALSE;
184unsigned int onScreenDisplayVolume = 0; 184unsigned int onScreenDisplayVolume = 0;
185const int yoff = 110; 185const int yoff = 110;
186 186
187void MediaPlayer::stopChangingVolume() { 187void MediaPlayer::stopChangingVolume() {
188 killTimers(); 188 killTimers();
189 // Get rid of the on-screen display stuff 189 // Get rid of the on-screen display stuff
190 drawnOnScreenDisplay = FALSE; 190 drawnOnScreenDisplay = FALSE;
191 onScreenDisplayVolume = 0; 191 onScreenDisplayVolume = 0;
192 int w=0; 192 int w=0;
193 int h=0; 193 int h=0;
194 if( !xineControl()->hasVideo() ) { 194 if( !xineControl()->hasVideo() ) {
195 w = audioUI()->width(); 195 w = audioUI()->width();
196 h = audioUI()->height(); 196 h = audioUI()->height();
197 audioUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE ); 197 audioUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE );
198 } else { 198 } else {
199 w = videoUI()->width(); 199 w = videoUI()->width();
200 h = videoUI()->height(); 200 h = videoUI()->height();
201 videoUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE ); 201 videoUI()->repaint( ( w - 200 ) / 2, h - yoff, 200 + 9, 70, FALSE );
202 } 202 }
203} 203}
204 204
205 205
206void MediaPlayer::timerEvent( QTimerEvent * ) { 206void MediaPlayer::timerEvent( QTimerEvent * ) {
207 if ( volumeDirection == +1 ) { 207 if ( volumeDirection == +1 ) {
208 volControl->incVol( 2 ); 208 volControl->incVol( 2 );
209 } else if ( volumeDirection == -1 ) { 209 } else if ( volumeDirection == -1 ) {
210 volControl->decVol( 2 ); 210 volControl->decVol( 2 );
211 } 211 }
212 212
213 213
214 // TODO FIXME 214 // TODO FIXME
215 // huh?? 215 // huh??
216 unsigned int v= 0; 216 unsigned int v= 0;
217 v = volControl->volume(); 217 v = volControl->volume();
218 v = v / 10; 218 v = v / 10;
219 219
220 if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) { 220 if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) {
221 return; 221 return;
222 } 222 }
223 223
224 int w=0; int h=0; 224 int w=0; int h=0;
225 if( !xineControl()->hasVideo() ) { 225 if( !xineControl()->hasVideo() ) {
226 w = audioUI()->width(); 226 w = audioUI()->width();
227 h = audioUI()->height(); 227 h = audioUI()->height();
228 228
229 if ( drawnOnScreenDisplay ) { 229 if ( drawnOnScreenDisplay ) {
230 if ( onScreenDisplayVolume > v ) { 230 if ( onScreenDisplayVolume > v ) {
231 audioUI()->repaint( ( w - 200 ) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE ); 231 audioUI()->repaint( ( w - 200 ) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE );
232 } 232 }
233 } 233 }
234 drawnOnScreenDisplay = TRUE; 234 drawnOnScreenDisplay = TRUE;
235 onScreenDisplayVolume = v; 235 onScreenDisplayVolume = v;
236 QPainter p( audioUI() ); 236 QPainter p( audioUI() );
237 p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); 237 p.setPen( QColor( 0x10, 0xD0, 0x10 ) );
238 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); 238 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) );
239 239
240 QFont f; 240 QFont f;
241 f.setPixelSize( 20 ); 241 f.setPixelSize( 20 );
242 f.setBold( TRUE ); 242 f.setBold( TRUE );
243 p.setFont( f ); 243 p.setFont( f );
244 p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") ); 244 p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") );
245 245
246 for ( unsigned int i = 0; i < 10; i++ ) { 246 for ( unsigned int i = 0; i < 10; i++ ) {
247 if ( v > i ) { 247 if ( v > i ) {
248 p.drawRect( ( w - 200 ) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); 248 p.drawRect( ( w - 200 ) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 );
249 } else { 249 } else {
250 p.drawRect( ( w - 200 ) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); 250 p.drawRect( ( w - 200 ) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 );
251 } 251 }
252 } 252 }
253 } else { 253 } else {
254 w = videoUI()->width(); 254 w = videoUI()->width();
255 h = videoUI()->height(); 255 h = videoUI()->height();
256 256
257 if ( drawnOnScreenDisplay ) { 257 if ( drawnOnScreenDisplay ) {
258 if ( onScreenDisplayVolume > v ) { 258 if ( onScreenDisplayVolume > v ) {
259 videoUI()->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE ); 259 videoUI()->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, ( onScreenDisplayVolume - v ) * 20 + 9, 30, FALSE );
260 } 260 }
261 } 261 }
262 drawnOnScreenDisplay = TRUE; 262 drawnOnScreenDisplay = TRUE;
263 onScreenDisplayVolume = v; 263 onScreenDisplayVolume = v;
264 QPainter p( videoUI() ); 264 QPainter p( videoUI() );
265 p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); 265 p.setPen( QColor( 0x10, 0xD0, 0x10 ) );
266 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); 266 p.setBrush( QColor( 0x10, 0xD0, 0x10 ) );
267 267
268 QFont f; 268 QFont f;
269 f.setPixelSize( 20 ); 269 f.setPixelSize( 20 );
270 f.setBold( TRUE ); 270 f.setBold( TRUE );
271 p.setFont( f ); 271 p.setFont( f );
272 p.drawText( (w - 200) / 2, h - yoff + 20, tr( "Volume" ) ); 272 p.drawText( (w - 200) / 2, h - yoff + 20, tr( "Volume" ) );
273 273
274 for ( unsigned int i = 0; i < 10; i++ ) { 274 for ( unsigned int i = 0; i < 10; i++ ) {
275 if ( v > i ) { 275 if ( v > i ) {
276 p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); 276 p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 );
277 } else { 277 } else {
278 p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); 278 p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 );
279 } 279 }
280 } 280 }
281 } 281 }
282} 282}
283 283
284 284
285void MediaPlayer::blank( bool b ) { 285void MediaPlayer::blank( bool b ) {
286 fd=open("/dev/fb0",O_RDWR); 286 fd=open("/dev/fb0",O_RDWR);
287#ifdef QT_QWS_SL5XXX 287#ifdef QT_QWS_SL5XXX
288 fl= open( "/dev/fl", O_RDWR ); 288 fl= open( "/dev/fl", O_RDWR );
289#endif 289#endif
290 if (fd != -1) { 290 if (fd != -1) {
291 if ( b ) { 291 if ( b ) {
292 qDebug("do blanking"); 292 qDebug("do blanking");
293#ifdef QT_QWS_SL5XXX 293#ifdef QT_QWS_SL5XXX
294 ioctl( fd, FBIOBLANK, 1 ); 294 ioctl( fd, FBIOBLANK, 1 );
295 if(fl !=-1) { 295 if(fl !=-1) {
296 ioctl( fl, 2 ); 296 ioctl( fl, 2 );
297 ::close(fl); 297 ::close(fl);
298 } 298 }
299#else 299#else
300 ioctl( fd, FBIOBLANK, 3 ); 300 ioctl( fd, FBIOBLANK, 3 );
301#endif 301#endif
302 isBlanked = TRUE; 302 isBlanked = TRUE;
303 } else { 303 } else {
304 qDebug("do unblanking"); 304 qDebug("do unblanking");
305 ioctl( fd, FBIOBLANK, 0); 305 ioctl( fd, FBIOBLANK, 0);
306#ifdef QT_QWS_SL5XXX 306#ifdef QT_QWS_SL5XXX
307 if(fl != -1) { 307 if(fl != -1) {
308 ioctl( fl, 1); 308 ioctl( fl, 1);
309 ::close(fl); 309 ::close(fl);
310 } 310 }
311#endif 311#endif
312 isBlanked = FALSE; 312 isBlanked = FALSE;
313 } 313 }
314 close( fd ); 314 close( fd );
315 } else { 315 } else {
316 qDebug("<< /dev/fb0 could not be opened >>"); 316 qDebug("<< /dev/fb0 could not be opened >>");
317 } 317 }
318} 318}
319 319
320void MediaPlayer::keyReleaseEvent( QKeyEvent *e) { 320void MediaPlayer::keyReleaseEvent( QKeyEvent *e) {
321 switch ( e->key() ) { 321 switch ( e->key() ) {
322////////////////////////////// Zaurus keys 322////////////////////////////// Zaurus keys
323 case Key_Home: 323 case Key_Home:
324 break; 324 break;
325 case Key_F9: //activity 325 case Key_F9: //activity
326 break; 326 break;
327 case Key_F10: //contacts 327 case Key_F10: //contacts
328 break; 328 break;
329 case Key_F11: //menu 329 case Key_F11: //menu
330 break; 330 break;
331 case Key_F12: //home 331 case Key_F12: //home
332 qDebug("Blank here"); 332 qDebug("Blank here");
333// mediaPlayerState->toggleBlank(); 333// mediaPlayerState->toggleBlank();
334 break; 334 break;
335 case Key_F13: //mail 335 case Key_F13: //mail
336 qDebug("Blank here"); 336 qDebug("Blank here");
337 // mediaPlayerState->toggleBlank(); 337 // mediaPlayerState->toggleBlank();
338 break; 338 break;
339 } 339 }
340} 340}
341 341
342void MediaPlayer::cleanUp() {// this happens on closing 342void MediaPlayer::cleanUp() {// this happens on closing
343 Config cfg( "OpiePlayer" ); 343 Config cfg( "OpiePlayer" );
344 mediaPlayerState.writeConfig( cfg ); 344 mediaPlayerState.writeConfig( cfg );
345 playList.writeDefaultPlaylist( ); 345 playList.writeDefaultPlaylist( );
346 346
347// QPEApplication::grabKeyboard(); 347// QPEApplication::grabKeyboard();
348// QPEApplication::ungrabKeyboard(); 348// QPEApplication::ungrabKeyboard();
349} 349}
350 350
351void MediaPlayer::recreateAudioAndVideoWidgets() const 351void MediaPlayer::recreateAudioAndVideoWidgets() const
352{ 352{
353 delete m_skinLoader; 353 delete m_skinLoader;
354 354
355 delete m_xineControl; 355 delete m_xineControl;
356 delete m_audioUI; 356 delete m_audioUI;
357 delete m_videoUI; 357 delete m_videoUI;
358 m_audioUI = new AudioWidget( playList, mediaPlayerState, 0, "audioUI" ); 358 m_audioUI = new AudioWidget( playList, mediaPlayerState, 0, "audioUI" );
359 m_videoUI = new VideoWidget( playList, mediaPlayerState, 0, "videoUI" ); 359 m_videoUI = new VideoWidget( playList, mediaPlayerState, 0, "videoUI" );
360 360
361 connect( m_audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); 361 connect( m_audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) );
362 connect( m_audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); 362 connect( m_audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) );
363 connect( m_audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); 363 connect( m_audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) );
364 connect( m_audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); 364 connect( m_audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) );
365 365
366 connect( m_videoUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); 366 connect( m_videoUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) );
367 connect( m_videoUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); 367 connect( m_videoUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) );
368 connect( m_videoUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); 368 connect( m_videoUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) );
369 connect( m_videoUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); 369 connect( m_videoUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) );
370 370
371 if ( !xine ) 371 if ( !xine )
372 xine = new XINE::Lib( XINE::Lib::InitializeImmediately ); 372 xine = new XINE::Lib( XINE::Lib::InitializeImmediately );
373 373
374 m_xineControl = new XineControl( xine, m_videoUI->vidWidget(), mediaPlayerState ); 374 m_xineControl = new XineControl( xine, m_videoUI->vidWidget(), mediaPlayerState );
375 375
376 xine = 0; 376 xine = 0;
377} 377}
378 378
379AudioWidget *MediaPlayer::audioUI() const 379AudioWidget *MediaPlayer::audioUI() const
380{ 380{
381 if ( !m_audioUI ) 381 if ( !m_audioUI )
382 recreateAudioAndVideoWidgets(); 382 recreateAudioAndVideoWidgets();
383 return m_audioUI; 383 return m_audioUI;
384} 384}
385 385
386VideoWidget *MediaPlayer::videoUI() const 386VideoWidget *MediaPlayer::videoUI() const
387{ 387{
388 if ( !m_videoUI ) 388 if ( !m_videoUI )
389 recreateAudioAndVideoWidgets(); 389 recreateAudioAndVideoWidgets();
390 return m_videoUI; 390 return m_videoUI;
391} 391}
392 392
393XineControl *MediaPlayer::xineControl() const 393XineControl *MediaPlayer::xineControl() const
394{ 394{
395 if ( !m_xineControl ) 395 if ( !m_xineControl )
396 recreateAudioAndVideoWidgets(); 396 recreateAudioAndVideoWidgets();
397 return m_xineControl; 397 return m_xineControl;
398} 398}
399 399
400void MediaPlayer::reloadSkins() 400void MediaPlayer::reloadSkins()
401{ 401{
402 audioUI()->loadSkin(); 402 audioUI()->loadSkin();
403 videoUI()->loadSkin(); 403 videoUI()->loadSkin();
404} 404}
405 405
diff --git a/noncore/multimedia/opieplayer2/mediawidget.cpp b/noncore/multimedia/opieplayer2/mediawidget.cpp
index f193001..08c62a2 100644
--- a/noncore/multimedia/opieplayer2/mediawidget.cpp
+++ b/noncore/multimedia/opieplayer2/mediawidget.cpp
@@ -1,263 +1,263 @@
1/* 1/*
2 Copyright (C) 2002 Simon Hausmann <simon@lst.de> 2 Copyright (C) 2002 Simon Hausmann <simon@lst.de>
3 (C) 2002 Max Reiss <harlekin@handhelds.org> 3 (C) 2002 Max Reiss <harlekin@handhelds.org>
4 (C) 2002 L. Potter <ljp@llornkcor.com> 4 (C) 2002 L. Potter <ljp@llornkcor.com>
5 (C) 2002 Holger Freyther <zecke@handhelds.org> 5 (C) 2002 Holger Freyther <zecke@handhelds.org>
6 6
7 This program is free software; you can redistribute it and/or 7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public 8 modify it under the terms of the GNU General Public
9 License as published by the Free Software Foundation; either 9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version. 10 version 2 of the License, or (at your option) any later version.
11 11
12 This program is distributed in the hope that it will be useful, 12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details. 15 General Public License for more details.
16 16
17 You should have received a copy of the GNU General Public License 17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING. If not, write to 18 along with this program; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. 20 Boston, MA 02111-1307, USA.
21*/ 21*/
22 22
23#include <assert.h> 23#include <assert.h>
24 24
25#include "mediawidget.h" 25#include "mediawidget.h"
26#include "playlistwidget.h" 26#include "playlistwidget.h"
27#include "skin.h" 27#include "skin.h"
28 28
29MediaWidget::MediaWidget( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QWidget *parent, const char *name ) 29MediaWidget::MediaWidget( PlayListWidget &_playList, MediaPlayerState &_mediaPlayerState, QWidget *parent, const char *name )
30 : QWidget( parent, name ), mediaPlayerState( _mediaPlayerState ), playList( _playList ) 30 : QWidget( parent, name ), mediaPlayerState( _mediaPlayerState ), playList( _playList )
31{ 31{
32 connect( &mediaPlayerState, SIGNAL( displayTypeChanged( MediaPlayerState::DisplayType ) ), 32 connect( &mediaPlayerState, SIGNAL( displayTypeChanged(MediaPlayerState::DisplayType) ),
33 this, SLOT( setDisplayType( MediaPlayerState::DisplayType ) ) ); 33 this, SLOT( setDisplayType(MediaPlayerState::DisplayType) ) );
34 connect( &mediaPlayerState, SIGNAL( lengthChanged( long ) ), 34 connect( &mediaPlayerState, SIGNAL( lengthChanged(long) ),
35 this, SLOT( setLength( long ) ) ); 35 this, SLOT( setLength(long) ) );
36 connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), 36 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ),
37 this, SLOT( setPlaying( bool ) ) ); 37 this, SLOT( setPlaying(bool) ) );
38 38
39 setBackgroundMode( NoBackground ); 39 setBackgroundMode( NoBackground );
40} 40}
41 41
42MediaWidget::~MediaWidget() 42MediaWidget::~MediaWidget()
43{ 43{
44} 44}
45 45
46void MediaWidget::setupButtons( const SkinButtonInfo *skinInfo, uint buttonCount, 46void MediaWidget::setupButtons( const SkinButtonInfo *skinInfo, uint buttonCount,
47 const Skin &skin ) 47 const Skin &skin )
48{ 48{
49 buttonMask = skin.buttonMask( skinInfo, buttonCount ); 49 buttonMask = skin.buttonMask( skinInfo, buttonCount );
50 50
51 buttons.clear(); 51 buttons.clear();
52 buttons.reserve( buttonCount ); 52 buttons.reserve( buttonCount );
53 53
54 for ( uint i = 0; i < buttonCount; ++i ) { 54 for ( uint i = 0; i < buttonCount; ++i ) {
55 Button button = setupButton( skinInfo[ i ], skin ); 55 Button button = setupButton( skinInfo[ i ], skin );
56 buttons.push_back( button ); 56 buttons.push_back( button );
57 } 57 }
58} 58}
59 59
60MediaWidget::Button MediaWidget::setupButton( const SkinButtonInfo &buttonInfo, const Skin &skin ) 60MediaWidget::Button MediaWidget::setupButton( const SkinButtonInfo &buttonInfo, const Skin &skin )
61{ 61{
62 Button button; 62 Button button;
63 button.command = buttonInfo.command; 63 button.command = buttonInfo.command;
64 button.type = buttonInfo.type; 64 button.type = buttonInfo.type;
65 button.mask = skin.buttonMaskImage( buttonInfo.fileName ); 65 button.mask = skin.buttonMaskImage( buttonInfo.fileName );
66 66
67 return button; 67 return button;
68} 68}
69 69
70void MediaWidget::loadDefaultSkin( const GUIInfo &guiInfo ) 70void MediaWidget::loadDefaultSkin( const GUIInfo &guiInfo )
71{ 71{
72 Skin skin( guiInfo.fileNameInfix ); 72 Skin skin( guiInfo.fileNameInfix );
73 skin.setCachable( false ); 73 skin.setCachable( false );
74 loadSkin( guiInfo.buttonInfo, guiInfo.buttonCount, skin ); 74 loadSkin( guiInfo.buttonInfo, guiInfo.buttonCount, skin );
75} 75}
76 76
77void MediaWidget::loadSkin( const SkinButtonInfo *skinInfo, uint buttonCount, const Skin &skin ) 77void MediaWidget::loadSkin( const SkinButtonInfo *skinInfo, uint buttonCount, const Skin &skin )
78{ 78{
79 backgroundPixmap = skin.backgroundPixmap(); 79 backgroundPixmap = skin.backgroundPixmap();
80 buttonUpImage = skin.buttonUpImage(); 80 buttonUpImage = skin.buttonUpImage();
81 buttonDownImage = skin.buttonDownImage(); 81 buttonDownImage = skin.buttonDownImage();
82 82
83 setupButtons( skinInfo, buttonCount, skin ); 83 setupButtons( skinInfo, buttonCount, skin );
84} 84}
85 85
86void MediaWidget::closeEvent( QCloseEvent * ) 86void MediaWidget::closeEvent( QCloseEvent * )
87{ 87{
88 mediaPlayerState.setList(); 88 mediaPlayerState.setList();
89} 89}
90 90
91void MediaWidget::paintEvent( QPaintEvent *pe ) 91void MediaWidget::paintEvent( QPaintEvent *pe )
92{ 92{
93 QPainter p( this ); 93 QPainter p( this );
94 94
95 if ( mediaPlayerState.isFullscreen() ) { 95 if ( mediaPlayerState.isFullscreen() ) {
96 // Clear the background 96 // Clear the background
97 p.setBrush( QBrush( Qt::black ) ); 97 p.setBrush( QBrush( Qt::black ) );
98 return; 98 return;
99 } 99 }
100 100
101 QPixmap buffer( size() ); 101 QPixmap buffer( size() );
102 QPainter bufferedPainter( &buffer ); 102 QPainter bufferedPainter( &buffer );
103 bufferedPainter.drawTiledPixmap( rect(), backgroundPixmap, QPoint( 0, 0 ) ); 103 bufferedPainter.drawTiledPixmap( rect(), backgroundPixmap, QPoint( 0, 0 ) );
104 paintAllButtons( bufferedPainter ); 104 paintAllButtons( bufferedPainter );
105 p.drawPixmap( 0, 0, buffer ); 105 p.drawPixmap( 0, 0, buffer );
106} 106}
107 107
108void MediaWidget::resizeEvent( QResizeEvent *e ) 108void MediaWidget::resizeEvent( QResizeEvent *e )
109{ 109{
110 QPixmap pixUp = combineImageWithBackground( buttonUpImage, backgroundPixmap, upperLeftOfButtonMask ); 110 QPixmap pixUp = combineImageWithBackground( buttonUpImage, backgroundPixmap, upperLeftOfButtonMask );
111 QPixmap pixDn = combineImageWithBackground( buttonDownImage, backgroundPixmap, upperLeftOfButtonMask ); 111 QPixmap pixDn = combineImageWithBackground( buttonDownImage, backgroundPixmap, upperLeftOfButtonMask );
112 112
113 for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) { 113 for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) {
114 Button &button = *it; 114 Button &button = *it;
115 115
116 if ( button.mask.isNull() ) 116 if ( button.mask.isNull() )
117 continue; 117 continue;
118 button.pixUp = addMaskToPixmap( pixUp, button.mask ); 118 button.pixUp = addMaskToPixmap( pixUp, button.mask );
119 button.pixDown = addMaskToPixmap( pixDn, button.mask ); 119 button.pixDown = addMaskToPixmap( pixDn, button.mask );
120 } 120 }
121 121
122 QWidget::resizeEvent( e ); 122 QWidget::resizeEvent( e );
123} 123}
124 124
125MediaWidget::Button *MediaWidget::buttonAt( const QPoint &position ) 125MediaWidget::Button *MediaWidget::buttonAt( const QPoint &position )
126{ 126{
127 if ( position.x() <= 0 || position.y() <= 0 || 127 if ( position.x() <= 0 || position.y() <= 0 ||
128 position.x() >= buttonMask.width() || 128 position.x() >= buttonMask.width() ||
129 position.y() >= buttonMask.height() ) 129 position.y() >= buttonMask.height() )
130 return 0; 130 return 0;
131 131
132 int pixelIdx = buttonMask.pixelIndex( position.x(), position.y() ); 132 int pixelIdx = buttonMask.pixelIndex( position.x(), position.y() );
133 for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) 133 for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it )
134 if ( it->command + 1 == pixelIdx ) 134 if ( it->command + 1 == pixelIdx )
135 return &( *it ); 135 return &( *it );
136 136
137 return 0; 137 return 0;
138} 138}
139 139
140void MediaWidget::mousePressEvent( QMouseEvent *event ) 140void MediaWidget::mousePressEvent( QMouseEvent *event )
141{ 141{
142 Button *button = buttonAt( event->pos() - upperLeftOfButtonMask ); 142 Button *button = buttonAt( event->pos() - upperLeftOfButtonMask );
143 143
144 if ( !button ) { 144 if ( !button ) {
145 QWidget::mousePressEvent( event ); 145 QWidget::mousePressEvent( event );
146 return; 146 return;
147 } 147 }
148 148
149 switch ( button->command ) { 149 switch ( button->command ) {
150 case VolumeUp: emit moreClicked(); return; 150 case VolumeUp: emit moreClicked(); return;
151 case VolumeDown: emit lessClicked(); return; 151 case VolumeDown: emit lessClicked(); return;
152 case Back: emit backClicked(); return; 152 case Back: emit backClicked(); return;
153 case Forward: emit forwardClicked(); return; 153 case Forward: emit forwardClicked(); return;
154 default: break; 154 default: break;
155 } 155 }
156} 156}
157 157
158void MediaWidget::mouseReleaseEvent( QMouseEvent *event ) 158void MediaWidget::mouseReleaseEvent( QMouseEvent *event )
159{ 159{
160 Button *button = buttonAt( event->pos() - upperLeftOfButtonMask ); 160 Button *button = buttonAt( event->pos() - upperLeftOfButtonMask );
161 161
162 if ( !button ) { 162 if ( !button ) {
163 QWidget::mouseReleaseEvent( event ); 163 QWidget::mouseReleaseEvent( event );
164 return; 164 return;
165 } 165 }
166 166
167 if ( button->type == ToggleButton ) 167 if ( button->type == ToggleButton )
168 toggleButton( *button ); 168 toggleButton( *button );
169 169
170 handleCommand( button->command, button->isDown ); 170 handleCommand( button->command, button->isDown );
171} 171}
172 172
173void MediaWidget::makeVisible() 173void MediaWidget::makeVisible()
174{ 174{
175} 175}
176 176
177void MediaWidget::handleCommand( Command command, bool buttonDown ) 177void MediaWidget::handleCommand( Command command, bool buttonDown )
178{ 178{
179 switch ( command ) { 179 switch ( command ) {
180 case Play: mediaPlayerState.togglePaused(); return; 180 case Play: mediaPlayerState.togglePaused(); return;
181 case Stop: mediaPlayerState.setPlaying(FALSE); return; 181 case Stop: mediaPlayerState.setPlaying(FALSE); return;
182 case Next: if( playList.currentTab() == PlayListWidget::CurrentPlayList ) mediaPlayerState.setNext(); return; 182 case Next: if( playList.currentTab() == PlayListWidget::CurrentPlayList ) mediaPlayerState.setNext(); return;
183 case Previous: if( playList.currentTab() == PlayListWidget::CurrentPlayList ) mediaPlayerState.setPrev(); return; 183 case Previous: if( playList.currentTab() == PlayListWidget::CurrentPlayList ) mediaPlayerState.setPrev(); return;
184 case Loop: mediaPlayerState.setLooping( buttonDown ); return; 184 case Loop: mediaPlayerState.setLooping( buttonDown ); return;
185 case VolumeUp: emit moreReleased(); return; 185 case VolumeUp: emit moreReleased(); return;
186 case VolumeDown: emit lessReleased(); return; 186 case VolumeDown: emit lessReleased(); return;
187 case PlayList: mediaPlayerState.setList(); return; 187 case PlayList: mediaPlayerState.setList(); return;
188 case Forward: emit forwardReleased(); return; 188 case Forward: emit forwardReleased(); return;
189 case Back: emit backReleased(); return; 189 case Back: emit backReleased(); return;
190 case FullScreen: mediaPlayerState.setFullscreen( true ); makeVisible(); return; 190 case FullScreen: mediaPlayerState.setFullscreen( true ); makeVisible(); return;
191 default: assert( false ); 191 default: assert( false );
192 } 192 }
193} 193}
194 194
195bool MediaWidget::isOverButton( const QPoint &position, int buttonId ) const 195bool MediaWidget::isOverButton( const QPoint &position, int buttonId ) const
196{ 196{
197 return ( position.x() > 0 && position.y() > 0 && 197 return ( position.x() > 0 && position.y() > 0 &&
198 position.x() < buttonMask.width() && 198 position.x() < buttonMask.width() &&
199 position.y() < buttonMask.height() && 199 position.y() < buttonMask.height() &&
200 buttonMask.pixelIndex( position.x(), position.y() ) == buttonId + 1 ); 200 buttonMask.pixelIndex( position.x(), position.y() ) == buttonId + 1 );
201} 201}
202 202
203void MediaWidget::paintAllButtons( QPainter &p ) 203void MediaWidget::paintAllButtons( QPainter &p )
204{ 204{
205 for ( ButtonVector::const_iterator it = buttons.begin(); 205 for ( ButtonVector::const_iterator it = buttons.begin();
206 it != buttons.end(); ++it ) 206 it != buttons.end(); ++it )
207 paintButton( p, *it ); 207 paintButton( p, *it );
208} 208}
209 209
210void MediaWidget::paintButton( const Button &button ) 210void MediaWidget::paintButton( const Button &button )
211{ 211{
212 QPainter p( this ); 212 QPainter p( this );
213 paintButton( p, button ); 213 paintButton( p, button );
214} 214}
215 215
216void MediaWidget::paintButton( QPainter &p, const Button &button ) 216void MediaWidget::paintButton( QPainter &p, const Button &button )
217{ 217{
218 if ( button.isDown ) 218 if ( button.isDown )
219 p.drawPixmap( upperLeftOfButtonMask, button.pixDown ); 219 p.drawPixmap( upperLeftOfButtonMask, button.pixDown );
220 else 220 else
221 p.drawPixmap( upperLeftOfButtonMask, button.pixUp ); 221 p.drawPixmap( upperLeftOfButtonMask, button.pixUp );
222} 222}
223 223
224void MediaWidget::setToggleButton( Command command, bool down ) 224void MediaWidget::setToggleButton( Command command, bool down )
225{ 225{
226 for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it ) 226 for ( ButtonVector::iterator it = buttons.begin(); it != buttons.end(); ++it )
227 if ( it->command == command ) { 227 if ( it->command == command ) {
228 setToggleButton( *it, down ); 228 setToggleButton( *it, down );
229 return; 229 return;
230 } 230 }
231} 231}
232 232
233void MediaWidget::setToggleButton( Button &button, bool down ) 233void MediaWidget::setToggleButton( Button &button, bool down )
234{ 234{
235 if ( down != button.isDown ) 235 if ( down != button.isDown )
236 toggleButton( button ); 236 toggleButton( button );
237} 237}
238 238
239void MediaWidget::toggleButton( Button &button ) 239void MediaWidget::toggleButton( Button &button )
240{ 240{
241 button.isDown = !button.isDown; 241 button.isDown = !button.isDown;
242 242
243 paintButton( button ); 243 paintButton( button );
244} 244}
245 245
246QPixmap MediaWidget::combineImageWithBackground( const QImage &image, const QPixmap &background, const QPoint &offset ) 246QPixmap MediaWidget::combineImageWithBackground( const QImage &image, const QPixmap &background, const QPoint &offset )
247{ 247{
248 QPixmap pix( image.size() ); 248 QPixmap pix( image.size() );
249 QPainter p( &pix ); 249 QPainter p( &pix );
250 p.drawTiledPixmap( pix.rect(), background, offset ); 250 p.drawTiledPixmap( pix.rect(), background, offset );
251 p.drawImage( 0, 0, image ); 251 p.drawImage( 0, 0, image );
252 return pix; 252 return pix;
253} 253}
254 254
255QPixmap MediaWidget::addMaskToPixmap( const QPixmap &pix, const QBitmap &mask ) 255QPixmap MediaWidget::addMaskToPixmap( const QPixmap &pix, const QBitmap &mask )
256{ 256{
257 QPixmap result( pix ); 257 QPixmap result( pix );
258 result.setMask( mask ); 258 result.setMask( mask );
259 return result; 259 return result;
260} 260}
261 261
262/* vim: et sw=4 ts=4 262/* vim: et sw=4 ts=4
263 */ 263 */
diff --git a/noncore/multimedia/opieplayer2/playlistwidget.cpp b/noncore/multimedia/opieplayer2/playlistwidget.cpp
index 9a9e1ec..0a84268 100644
--- a/noncore/multimedia/opieplayer2/playlistwidget.cpp
+++ b/noncore/multimedia/opieplayer2/playlistwidget.cpp
@@ -1,1043 +1,1043 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002,2003 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002,2003 Max Reiss <harlekin@handhelds.org>
5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
7 =. 7 =.
8 .=l. 8 .=l.
9           .>+-= 9           .>+-=
10 _;:,     .>    :=|. This program is free software; you can 10 _;:,     .>    :=|. This program is free software; you can
11.> <`_,   >  .   <= redistribute it and/or modify it under 11.> <`_,   >  .   <= redistribute it and/or modify it under
12:`=1 )Y*s>-.--   : the terms of the GNU General Public 12:`=1 )Y*s>-.--   : the terms of the GNU General Public
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; General Public License for more 22..}^=.=       =       ; General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = General Public License along with 26  -_. . .   )=.  = General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34#include <qtoolbar.h> 34#include <qtoolbar.h>
35 35
36#include <opie/ofiledialog.h> 36#include <opie/ofiledialog.h>
37 37
38#include <qmessagebox.h> 38#include <qmessagebox.h>
39 39
40#include "playlistselection.h" 40#include "playlistselection.h"
41#include "playlistwidget.h" 41#include "playlistwidget.h"
42#include "mediaplayer.h" 42#include "mediaplayer.h"
43#include "mediaplayerstate.h" 43#include "mediaplayerstate.h"
44#include "inputDialog.h" 44#include "inputDialog.h"
45#include "om3u.h" 45#include "om3u.h"
46#include "playlistfileview.h" 46#include "playlistfileview.h"
47 47
48//only needed for the random play 48//only needed for the random play
49#include <assert.h> 49#include <assert.h>
50 50
51PlayListWidget::PlayListWidget(QWidget* parent, const char* name, WFlags fl ) 51PlayListWidget::PlayListWidget(QWidget* parent, const char* name, WFlags fl )
52 : PlayListWidgetGui( parent, "playList" ) , currentFileListView( 0 ) 52 : PlayListWidgetGui( parent, "playList" ) , currentFileListView( 0 )
53{ 53{
54 mediaPlayerState = new MediaPlayerState(0, "mediaPlayerState" ); 54 mediaPlayerState = new MediaPlayerState(0, "mediaPlayerState" );
55 m_mp = new MediaPlayer(*this, *mediaPlayerState, 0, "mediaPlayer"); 55 m_mp = new MediaPlayer(*this, *mediaPlayerState, 0, "mediaPlayer");
56 56
57 57
58 58
59 d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ), 59 d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ),
60 "opieplayer2/add_to_playlist", 60 "opieplayer2/add_to_playlist",
61 this , SLOT(addSelected() ) ); 61 this , SLOT(addSelected() ) );
62 d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ), 62 d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ),
63 "opieplayer2/remove_from_playlist", 63 "opieplayer2/remove_from_playlist",
64 this , SLOT(removeSelected() ) ); 64 this , SLOT(removeSelected() ) );
65 d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer2/play", 65 d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer2/play",
66 this , SLOT( btnPlay( bool) ), TRUE ); 66 this , SLOT( btnPlay(bool) ), TRUE );
67 d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer2/shuffle", 67 d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer2/shuffle",
68 mediaPlayerState, SLOT( setShuffled( bool ) ), TRUE ); 68 mediaPlayerState, SLOT( setShuffled(bool) ), TRUE );
69 d->tbLoop = new ToolButton( bar, tr( "Loop" ), "opieplayer2/loop", 69 d->tbLoop = new ToolButton( bar, tr( "Loop" ), "opieplayer2/loop",
70 mediaPlayerState, SLOT( setLooping( bool ) ), TRUE ); 70 mediaPlayerState, SLOT( setLooping(bool) ), TRUE );
71 71
72 (void)new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) ); 72 (void)new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) );
73 (void)new MenuItem( pmPlayList, tr( "Add all audio files" ), 73 (void)new MenuItem( pmPlayList, tr( "Add all audio files" ),
74 this, SLOT( addAllMusicToList() ) ); 74 this, SLOT( addAllMusicToList() ) );
75 (void)new MenuItem( pmPlayList, tr( "Add all video files" ), 75 (void)new MenuItem( pmPlayList, tr( "Add all video files" ),
76 this, SLOT( addAllVideoToList() ) ); 76 this, SLOT( addAllVideoToList() ) );
77 (void)new MenuItem( pmPlayList, tr( "Add all files" ), 77 (void)new MenuItem( pmPlayList, tr( "Add all files" ),
78 this, SLOT( addAllToList() ) ); 78 this, SLOT( addAllToList() ) );
79 pmPlayList->insertSeparator(-1); 79 pmPlayList->insertSeparator(-1);
80 (void)new MenuItem( pmPlayList, tr( "Add File" ), 80 (void)new MenuItem( pmPlayList, tr( "Add File" ),
81 this,SLOT( openFile() ) ); 81 this,SLOT( openFile() ) );
82 (void)new MenuItem( pmPlayList, tr("Add URL"), 82 (void)new MenuItem( pmPlayList, tr("Add URL"),
83 this,SLOT( openURL() ) ); 83 this,SLOT( openURL() ) );
84 pmPlayList->insertSeparator(-1); 84 pmPlayList->insertSeparator(-1);
85 (void)new MenuItem( pmPlayList, tr( "Save Playlist" ), 85 (void)new MenuItem( pmPlayList, tr( "Save Playlist" ),
86 this, SLOT(writem3u() ) ); 86 this, SLOT(writem3u() ) );
87 pmPlayList->insertSeparator(-1); 87 pmPlayList->insertSeparator(-1);
88 (void)new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ), 88 (void)new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ),
89 audioView, SLOT( scanFiles() ) ); 89 audioView, SLOT( scanFiles() ) );
90 (void)new MenuItem( pmPlayList, tr( "Rescan for Video Files" ), 90 (void)new MenuItem( pmPlayList, tr( "Rescan for Video Files" ),
91 videoView, SLOT( scanFiles() ) ); 91 videoView, SLOT( scanFiles() ) );
92 92
93 pmView->insertItem( Resource::loadPixmap("fullscreen") , tr( "Full Screen"), 93 pmView->insertItem( Resource::loadPixmap("fullscreen") , tr( "Full Screen"),
94 mediaPlayerState, SLOT( toggleFullscreen() ) ); 94 mediaPlayerState, SLOT( toggleFullscreen() ) );
95 95
96 Config cfg( "OpiePlayer" ); 96 Config cfg( "OpiePlayer" );
97 bool b= cfg.readBoolEntry("FullScreen", 0); 97 bool b= cfg.readBoolEntry("FullScreen", 0);
98 mediaPlayerState->setFullscreen( b ); 98 mediaPlayerState->setFullscreen( b );
99 pmView->setItemChecked( -16, b ); 99 pmView->setItemChecked( -16, b );
100 100
101 (void)new ToolButton( vbox1, tr( "Move Up" ), "opieplayer2/up", 101 (void)new ToolButton( vbox1, tr( "Move Up" ), "opieplayer2/up",
102 d->selectedFiles, SLOT(moveSelectedUp() ) ); 102 d->selectedFiles, SLOT(moveSelectedUp() ) );
103 (void)new ToolButton( vbox1, tr( "Remove" ), "opieplayer2/cut", 103 (void)new ToolButton( vbox1, tr( "Remove" ), "opieplayer2/cut",
104 d->selectedFiles, SLOT(removeSelected() ) ); 104 d->selectedFiles, SLOT(removeSelected() ) );
105 (void)new ToolButton( vbox1, tr( "Move Down" ), "opieplayer2/down", 105 (void)new ToolButton( vbox1, tr( "Move Down" ), "opieplayer2/down",
106 d->selectedFiles, SLOT(moveSelectedDown() ) ); 106 d->selectedFiles, SLOT(moveSelectedDown() ) );
107 QVBox *stretch2 = new QVBox( vbox1 ); 107 QVBox *stretch2 = new QVBox( vbox1 );
108 108
109 connect( tbDeletePlaylist, ( SIGNAL( released() ) ), 109 connect( tbDeletePlaylist, ( SIGNAL( released() ) ),
110 SLOT( deletePlaylist() ) ); 110 SLOT( deletePlaylist() ) );
111 connect( pmView, SIGNAL( activated( int ) ), 111 connect( pmView, SIGNAL( activated(int) ),
112 this, SLOT( pmViewActivated( int ) ) ); 112 this, SLOT( pmViewActivated(int) ) );
113 connect( skinsMenu, SIGNAL( activated( int ) ) , 113 connect( skinsMenu, SIGNAL( activated(int) ) ,
114 this, SLOT( skinsMenuActivated( int ) ) ); 114 this, SLOT( skinsMenuActivated(int) ) );
115 connect( d->selectedFiles, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int) ), 115 connect( d->selectedFiles, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
116 this,SLOT( playlistViewPressed( int, QListViewItem *, const QPoint&, int ) ) ); 116 this,SLOT( playlistViewPressed(int,QListViewItem*,const QPoint&,int) ) );
117 connect( audioView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int ) ), 117 connect( audioView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
118 this,SLOT( viewPressed( int, QListViewItem *, const QPoint&, int ) ) ); 118 this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int) ) );
119 connect( audioView, SIGNAL( returnPressed( QListViewItem *) ), 119 connect( audioView, SIGNAL( returnPressed(QListViewItem*) ),
120 this,SLOT( playIt( QListViewItem *) ) ); 120 this,SLOT( playIt(QListViewItem*) ) );
121 connect( audioView, SIGNAL( doubleClicked( QListViewItem *) ), 121 connect( audioView, SIGNAL( doubleClicked(QListViewItem*) ),
122 this, SLOT( addToSelection( QListViewItem *) ) ); 122 this, SLOT( addToSelection(QListViewItem*) ) );
123 connect( videoView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int) ), 123 connect( videoView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
124 this,SLOT( viewPressed( int, QListViewItem *, const QPoint&, int) ) ); 124 this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int) ) );
125 connect( videoView, SIGNAL( returnPressed( QListViewItem *) ), 125 connect( videoView, SIGNAL( returnPressed(QListViewItem*) ),
126 this,SLOT( playIt( QListViewItem *) ) ); 126 this,SLOT( playIt(QListViewItem*) ) );
127 connect( videoView, SIGNAL( doubleClicked( QListViewItem *) ), 127 connect( videoView, SIGNAL( doubleClicked(QListViewItem*) ),
128 this, SLOT( addToSelection( QListViewItem *) ) ); 128 this, SLOT( addToSelection(QListViewItem*) ) );
129 connect( playLists, SIGNAL( fileSelected( const DocLnk &) ), 129 connect( playLists, SIGNAL( fileSelected(const DocLnk&) ),
130 this, SLOT( loadList( const DocLnk & ) ) ); 130 this, SLOT( loadList(const DocLnk&) ) );
131 connect( tabWidget, SIGNAL ( currentChanged(QWidget*) ), 131 connect( tabWidget, SIGNAL ( currentChanged(QWidget*) ),
132 this, SLOT( tabChanged( QWidget* ) ) ); 132 this, SLOT( tabChanged(QWidget*) ) );
133 connect( mediaPlayerState, SIGNAL( playingToggled( bool ) ), 133 connect( mediaPlayerState, SIGNAL( playingToggled(bool) ),
134 d->tbPlay, SLOT( setOn( bool ) ) ); 134 d->tbPlay, SLOT( setOn(bool) ) );
135 connect( mediaPlayerState, SIGNAL( loopingToggled( bool ) ), 135 connect( mediaPlayerState, SIGNAL( loopingToggled(bool) ),
136 d->tbLoop, SLOT( setOn( bool ) ) ); 136 d->tbLoop, SLOT( setOn(bool) ) );
137 connect( mediaPlayerState, SIGNAL( shuffledToggled( bool ) ), 137 connect( mediaPlayerState, SIGNAL( shuffledToggled(bool) ),
138 d->tbShuffle, SLOT( setOn( bool ) ) ); 138 d->tbShuffle, SLOT( setOn(bool) ) );
139 connect( d->selectedFiles, SIGNAL( doubleClicked( QListViewItem *) ), 139 connect( d->selectedFiles, SIGNAL( doubleClicked(QListViewItem*) ),
140 this, SLOT( playIt( QListViewItem *) ) ); 140 this, SLOT( playIt(QListViewItem*) ) );
141 connect ( gammaSlider, SIGNAL( valueChanged( int ) ), 141 connect ( gammaSlider, SIGNAL( valueChanged(int) ),
142 mediaPlayerState, SLOT( setVideoGamma( int ) ) ); 142 mediaPlayerState, SLOT( setVideoGamma(int) ) );
143 143
144 connect( this, SIGNAL(skinSelected() ), 144 connect( this, SIGNAL(skinSelected() ),
145 m_mp, SLOT( reloadSkins() ) ); 145 m_mp, SLOT( reloadSkins() ) );
146 146
147 // see which skins are installed 147 // see which skins are installed
148 populateSkinsMenu(); 148 populateSkinsMenu();
149 initializeStates(); 149 initializeStates();
150 150
151 channel = new QCopChannel( "QPE/Application/opieplayer2", this ); 151 channel = new QCopChannel( "QPE/Application/opieplayer2", this );
152 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 152 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
153 this, SLOT( qcopReceive(const QCString&, const QByteArray&)) ); 153 this, SLOT( qcopReceive(const QCString&,const QByteArray&)) );
154 154
155 155
156 cfg.setGroup("PlayList"); 156 cfg.setGroup("PlayList");
157 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default"); 157 QString currentPlaylist = cfg.readEntry( "CurrentPlaylist", "default");
158 loadList(DocLnk( currentPlaylist ) ); 158 loadList(DocLnk( currentPlaylist ) );
159 159
160 tabWidget->showPage( playListTab ); 160 tabWidget->showPage( playListTab );
161} 161}
162 162
163 163
164PlayListWidget::~PlayListWidget() { 164PlayListWidget::~PlayListWidget() {
165 delete d; 165 delete d;
166 delete m_mp; 166 delete m_mp;
167} 167}
168 168
169 169
170void PlayListWidget::initializeStates() { 170void PlayListWidget::initializeStates() {
171 d->tbPlay->setOn( mediaPlayerState->isPlaying() ); 171 d->tbPlay->setOn( mediaPlayerState->isPlaying() );
172 d->tbLoop->setOn( mediaPlayerState->isLooping() ); 172 d->tbLoop->setOn( mediaPlayerState->isLooping() );
173 d->tbShuffle->setOn( mediaPlayerState->isShuffled() ); 173 d->tbShuffle->setOn( mediaPlayerState->isShuffled() );
174 d->playListFrame->show(); 174 d->playListFrame->show();
175} 175}
176 176
177void PlayListWidget::writeDefaultPlaylist() { 177void PlayListWidget::writeDefaultPlaylist() {
178 178
179 Config config( "OpiePlayer" ); 179 Config config( "OpiePlayer" );
180 config.setGroup( "PlayList" ); 180 config.setGroup( "PlayList" );
181 QString filename=QPEApplication::documentDir() + "/default.m3u"; 181 QString filename=QPEApplication::documentDir() + "/default.m3u";
182 QString currentString = config.readEntry( "CurrentPlaylist", filename); 182 QString currentString = config.readEntry( "CurrentPlaylist", filename);
183 if( currentString == filename) { 183 if( currentString == filename) {
184 Om3u *m3uList; 184 Om3u *m3uList;
185 // qDebug("<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>"); 185 // qDebug("<<<<<<<<<<<<<default>>>>>>>>>>>>>>>>>>>");
186 if( d->selectedFiles->first() ) { 186 if( d->selectedFiles->first() ) {
187 m3uList = new Om3u(filename, IO_ReadWrite | IO_Truncate); 187 m3uList = new Om3u(filename, IO_ReadWrite | IO_Truncate);
188 do { 188 do {
189 // qDebug(d->selectedFiles->current()->file()); 189 // qDebug(d->selectedFiles->current()->file());
190 m3uList->add( d->selectedFiles->current()->file() ); 190 m3uList->add( d->selectedFiles->current()->file() );
191 } 191 }
192 while ( d->selectedFiles->next() ); 192 while ( d->selectedFiles->next() );
193 193
194 m3uList->write(); 194 m3uList->write();
195 m3uList->close(); 195 m3uList->close();
196 delete m3uList; 196 delete m3uList;
197 197
198 } 198 }
199 } 199 }
200} 200}
201 201
202void PlayListWidget::addToSelection( const DocLnk& lnk ) { 202void PlayListWidget::addToSelection( const DocLnk& lnk ) {
203 d->setDocumentUsed = FALSE; 203 d->setDocumentUsed = FALSE;
204 if( QFileInfo( lnk.file() ).exists() || 204 if( QFileInfo( lnk.file() ).exists() ||
205 lnk.file().left(4) == "http" ) { 205 lnk.file().left(4) == "http" ) {
206 d->selectedFiles->addToSelection( lnk ); 206 d->selectedFiles->addToSelection( lnk );
207 } 207 }
208// writeCurrentM3u(); 208// writeCurrentM3u();
209} 209}
210 210
211 211
212void PlayListWidget::clearList() { 212void PlayListWidget::clearList() {
213 while ( first() ) { 213 while ( first() ) {
214 d->selectedFiles->removeSelected(); 214 d->selectedFiles->removeSelected();
215 } 215 }
216 Config cfg( "OpiePlayer" ); 216 Config cfg( "OpiePlayer" );
217 cfg.setGroup("PlayList"); 217 cfg.setGroup("PlayList");
218 cfg.writeEntry("CurrentPlaylist","default"); 218 cfg.writeEntry("CurrentPlaylist","default");
219 setCaption("OpiePlayer"); 219 setCaption("OpiePlayer");
220} 220}
221 221
222void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint& , int) { 222void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint& , int) {
223 switch (mouse) { 223 switch (mouse) {
224 case LeftButton: 224 case LeftButton:
225 break; 225 break;
226 case RightButton: 226 case RightButton:
227 { 227 {
228 QPopupMenu m; 228 QPopupMenu m;
229 m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() )); 229 m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() ));
230 m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() )); 230 m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() ));
231 m.exec( QCursor::pos() ); 231 m.exec( QCursor::pos() );
232 } 232 }
233 break; 233 break;
234 } 234 }
235} 235}
236 236
237 237
238void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint& , int ) { 238void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint& , int ) {
239 switch (mouse) { 239 switch (mouse) {
240 case LeftButton: 240 case LeftButton:
241 break; 241 break;
242 case RightButton: 242 case RightButton:
243 { 243 {
244 QPopupMenu m; 244 QPopupMenu m;
245 m.insertItem( tr( "Play" ), this, SLOT( playSelected() )); 245 m.insertItem( tr( "Play" ), this, SLOT( playSelected() ));
246 m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() )); 246 m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() ));
247 m.exec( QCursor::pos() ); 247 m.exec( QCursor::pos() );
248 } 248 }
249 break; 249 break;
250 } 250 }
251} 251}
252 252
253 253
254void PlayListWidget::addAllToList() { 254void PlayListWidget::addAllToList() {
255 255
256 256
257 audioView->populateView(); 257 audioView->populateView();
258 258
259 QListViewItemIterator audioIt( audioView ); 259 QListViewItemIterator audioIt( audioView );
260 DocLnk lnk; 260 DocLnk lnk;
261 QString filename; 261 QString filename;
262 // iterate through all items of the listview 262 // iterate through all items of the listview
263 for ( ; audioIt.current(); ++audioIt ) { 263 for ( ; audioIt.current(); ++audioIt ) {
264 filename = audioIt.current()->text(3); 264 filename = audioIt.current()->text(3);
265 lnk.setName( QFileInfo(filename).baseName() ); //sets name 265 lnk.setName( QFileInfo(filename).baseName() ); //sets name
266 lnk.setFile( filename ); //sets file name 266 lnk.setFile( filename ); //sets file name
267 d->selectedFiles->addToSelection( lnk); 267 d->selectedFiles->addToSelection( lnk);
268 } 268 }
269 269
270 videoView->populateView(); 270 videoView->populateView();
271 271
272 QListViewItemIterator videoIt( videoView ); 272 QListViewItemIterator videoIt( videoView );
273 for ( ; videoIt.current(); ++videoIt ) { 273 for ( ; videoIt.current(); ++videoIt ) {
274 filename = videoIt.current()->text(3); 274 filename = videoIt.current()->text(3);
275 lnk.setName( QFileInfo(filename).baseName() ); //sets name 275 lnk.setName( QFileInfo(filename).baseName() ); //sets name
276 lnk.setFile( filename ); //sets file name 276 lnk.setFile( filename ); //sets file name
277 d->selectedFiles->addToSelection( lnk); 277 d->selectedFiles->addToSelection( lnk);
278 } 278 }
279 279
280 tabWidget->setCurrentPage(0); 280 tabWidget->setCurrentPage(0);
281 281
282 writeCurrentM3u(); 282 writeCurrentM3u();
283 d->selectedFiles->first(); 283 d->selectedFiles->first();
284} 284}
285 285
286 286
287void PlayListWidget::addAllMusicToList() { 287void PlayListWidget::addAllMusicToList() {
288 288
289 audioView->populateView(); 289 audioView->populateView();
290 290
291 QListViewItemIterator audioIt( audioView ); 291 QListViewItemIterator audioIt( audioView );
292 DocLnk lnk; 292 DocLnk lnk;
293 QString filename; 293 QString filename;
294 // iterate through all items of the listview 294 // iterate through all items of the listview
295 for ( ; audioIt.current(); ++audioIt ) { 295 for ( ; audioIt.current(); ++audioIt ) {
296 filename = audioIt.current()->text(3); 296 filename = audioIt.current()->text(3);
297 lnk.setName( QFileInfo(filename).baseName() ); //sets name 297 lnk.setName( QFileInfo(filename).baseName() ); //sets name
298 lnk.setFile( filename ); //sets file name 298 lnk.setFile( filename ); //sets file name
299 d->selectedFiles->addToSelection( lnk); 299 d->selectedFiles->addToSelection( lnk);
300 } 300 }
301 301
302 tabWidget->setCurrentPage(0); 302 tabWidget->setCurrentPage(0);
303 writeCurrentM3u(); 303 writeCurrentM3u();
304 d->selectedFiles->first(); 304 d->selectedFiles->first();
305} 305}
306 306
307 307
308void PlayListWidget::addAllVideoToList() { 308void PlayListWidget::addAllVideoToList() {
309 309
310 videoView->populateView(); 310 videoView->populateView();
311 311
312 QListViewItemIterator videoIt( videoView ); 312 QListViewItemIterator videoIt( videoView );
313 DocLnk lnk; 313 DocLnk lnk;
314 QString filename; 314 QString filename;
315 for ( ; videoIt.current(); ++videoIt ) { 315 for ( ; videoIt.current(); ++videoIt ) {
316 filename = videoIt.current()->text(3); 316 filename = videoIt.current()->text(3);
317 lnk.setName( QFileInfo(filename).baseName() ); //sets name 317 lnk.setName( QFileInfo(filename).baseName() ); //sets name
318 lnk.setFile( filename ); //sets file name 318 lnk.setFile( filename ); //sets file name
319 d->selectedFiles->addToSelection( lnk); 319 d->selectedFiles->addToSelection( lnk);
320 } 320 }
321 tabWidget->setCurrentPage(0); 321 tabWidget->setCurrentPage(0);
322 writeCurrentM3u(); 322 writeCurrentM3u();
323 d->selectedFiles->first(); 323 d->selectedFiles->first();
324} 324}
325 325
326 326
327void PlayListWidget::setDocument( const QString& fileref ) { 327void PlayListWidget::setDocument( const QString& fileref ) {
328 // qDebug( "<<<<<<<<set document>>>>>>>>>> "+fileref ); 328 // qDebug( "<<<<<<<<set document>>>>>>>>>> "+fileref );
329 fromSetDocument = TRUE; 329 fromSetDocument = TRUE;
330 QFileInfo fileInfo(fileref); 330 QFileInfo fileInfo(fileref);
331 331
332 if ( !fileInfo.exists() ) { 332 if ( !fileInfo.exists() ) {
333 QMessageBox::warning( this, tr( "Invalid File" ), 333 QMessageBox::warning( this, tr( "Invalid File" ),
334 tr( "There was a problem in getting the file." ) ); 334 tr( "There was a problem in getting the file." ) );
335 return; 335 return;
336 } 336 }
337 337
338 clearList(); 338 clearList();
339 QString extension = fileInfo.extension(false); 339 QString extension = fileInfo.extension(false);
340 340
341 if( extension.find( "m3u", 0, false) != -1 341 if( extension.find( "m3u", 0, false) != -1
342 || extension.find( "pls", 0, false) != -1 ) { 342 || extension.find( "pls", 0, false) != -1 ) {
343 readListFromFile( fileref ); 343 readListFromFile( fileref );
344 } else { 344 } else {
345 clearList(); 345 clearList();
346 DocLnk lnk; 346 DocLnk lnk;
347 lnk.setName( fileInfo.baseName() ); //sets name 347 lnk.setName( fileInfo.baseName() ); //sets name
348 lnk.setFile( fileref ); //sets file name 348 lnk.setFile( fileref ); //sets file name
349 addToSelection( lnk ); 349 addToSelection( lnk );
350 writeCurrentM3u(); 350 writeCurrentM3u();
351 351
352 d->setDocumentUsed = TRUE; 352 d->setDocumentUsed = TRUE;
353 mediaPlayerState->setPlaying( FALSE ); 353 mediaPlayerState->setPlaying( FALSE );
354 mediaPlayerState->setPlaying( TRUE ); 354 mediaPlayerState->setPlaying( TRUE );
355 } 355 }
356} 356}
357 357
358 358
359void PlayListWidget::useSelectedDocument() { 359void PlayListWidget::useSelectedDocument() {
360 d->setDocumentUsed = FALSE; 360 d->setDocumentUsed = FALSE;
361} 361}
362 362
363 363
364const DocLnk *PlayListWidget::current() const { // this is fugly 364const DocLnk *PlayListWidget::current() const { // this is fugly
365 assert( currentTab() == CurrentPlayList ); 365 assert( currentTab() == CurrentPlayList );
366 366
367 const DocLnk *lnk = d->selectedFiles->current(); 367 const DocLnk *lnk = d->selectedFiles->current();
368 if ( !lnk ) { 368 if ( !lnk ) {
369 d->selectedFiles->first(); 369 d->selectedFiles->first();
370 lnk = d->selectedFiles->current(); 370 lnk = d->selectedFiles->current();
371 } 371 }
372 assert( lnk ); 372 assert( lnk );
373 return lnk; 373 return lnk;
374} 374}
375 375
376 376
377bool PlayListWidget::prev() { 377bool PlayListWidget::prev() {
378 if ( mediaPlayerState->isShuffled() ) { 378 if ( mediaPlayerState->isShuffled() ) {
379 const DocLnk *cur = current(); 379 const DocLnk *cur = current();
380 int j = 1 + (int)(97.0 * rand() / (RAND_MAX + 1.0)); 380 int j = 1 + (int)(97.0 * rand() / (RAND_MAX + 1.0));
381 for ( int i = 0; i < j; i++ ) { 381 for ( int i = 0; i < j; i++ ) {
382 if ( !d->selectedFiles->next() ) 382 if ( !d->selectedFiles->next() )
383 d->selectedFiles->first(); 383 d->selectedFiles->first();
384 } 384 }
385 if ( cur == current() ) 385 if ( cur == current() )
386 if ( !d->selectedFiles->next() ) { 386 if ( !d->selectedFiles->next() ) {
387 d->selectedFiles->first(); 387 d->selectedFiles->first();
388 } 388 }
389 return TRUE; 389 return TRUE;
390 } else { 390 } else {
391 if ( !d->selectedFiles->prev() ) { 391 if ( !d->selectedFiles->prev() ) {
392 if ( mediaPlayerState->isLooping() ) { 392 if ( mediaPlayerState->isLooping() ) {
393 return d->selectedFiles->last(); 393 return d->selectedFiles->last();
394 } else { 394 } else {
395 return FALSE; 395 return FALSE;
396 } 396 }
397 } 397 }
398 return TRUE; 398 return TRUE;
399 } 399 }
400} 400}
401 401
402 402
403bool PlayListWidget::next() { 403bool PlayListWidget::next() {
404//qDebug("<<<<<<<<<<<<next()"); 404//qDebug("<<<<<<<<<<<<next()");
405 if ( mediaPlayerState->isShuffled() ) { 405 if ( mediaPlayerState->isShuffled() ) {
406 return prev(); 406 return prev();
407 } else { 407 } else {
408 if ( !d->selectedFiles->next() ) { 408 if ( !d->selectedFiles->next() ) {
409 if ( mediaPlayerState->isLooping() ) { 409 if ( mediaPlayerState->isLooping() ) {
410 return d->selectedFiles->first(); 410 return d->selectedFiles->first();
411 } else { 411 } else {
412 return FALSE; 412 return FALSE;
413 } 413 }
414 } 414 }
415 return TRUE; 415 return TRUE;
416 } 416 }
417} 417}
418 418
419 419
420bool PlayListWidget::first() { 420bool PlayListWidget::first() {
421 return d->selectedFiles->first(); 421 return d->selectedFiles->first();
422} 422}
423 423
424 424
425bool PlayListWidget::last() { 425bool PlayListWidget::last() {
426 return d->selectedFiles->last(); 426 return d->selectedFiles->last();
427} 427}
428 428
429 429
430 void PlayListWidget::saveList() { 430 void PlayListWidget::saveList() {
431 writem3u(); 431 writem3u();
432 } 432 }
433 433
434 434
435void PlayListWidget::loadList( const DocLnk & lnk) { 435void PlayListWidget::loadList( const DocLnk & lnk) {
436 QString name = lnk.name(); 436 QString name = lnk.name();
437 437
438 if( name.length()>0) { 438 if( name.length()>0) {
439 setCaption("OpiePlayer: "+name); 439 setCaption("OpiePlayer: "+name);
440 clearList(); 440 clearList();
441 readListFromFile(lnk.file()); 441 readListFromFile(lnk.file());
442 tabWidget->setCurrentPage(0); 442 tabWidget->setCurrentPage(0);
443 } 443 }
444} 444}
445 445
446void PlayListWidget::addSelected() { 446void PlayListWidget::addSelected() {
447 assert( inFileListMode() ); 447 assert( inFileListMode() );
448 448
449 QListViewItemIterator it( currentFileListView ); 449 QListViewItemIterator it( currentFileListView );
450 for ( ; it.current(); ++it ) 450 for ( ; it.current(); ++it )
451 if ( it.current()->isSelected() ) { 451 if ( it.current()->isSelected() ) {
452 QString filename = it.current()->text(3); 452 QString filename = it.current()->text(3);
453 453
454 DocLnk lnk; 454 DocLnk lnk;
455 lnk.setName( QFileInfo( filename ).baseName() ); //sets name 455 lnk.setName( QFileInfo( filename ).baseName() ); //sets name
456 lnk.setFile( filename ); //sets file name 456 lnk.setFile( filename ); //sets file name
457 457
458 d->selectedFiles->addToSelection( lnk ); 458 d->selectedFiles->addToSelection( lnk );
459 } 459 }
460 460
461 currentFileListView->clearSelection(); 461 currentFileListView->clearSelection();
462 462
463 writeCurrentM3u(); 463 writeCurrentM3u();
464} 464}
465 465
466 466
467void PlayListWidget::removeSelected() { 467void PlayListWidget::removeSelected() {
468 d->selectedFiles->removeSelected( ); 468 d->selectedFiles->removeSelected( );
469 writeCurrentM3u(); 469 writeCurrentM3u();
470} 470}
471 471
472 472
473void PlayListWidget::playIt( QListViewItem *it) { 473void PlayListWidget::playIt( QListViewItem *it) {
474 if(!it) return; 474 if(!it) return;
475 mediaPlayerState->setPlaying(FALSE); 475 mediaPlayerState->setPlaying(FALSE);
476 mediaPlayerState->setPlaying(TRUE); 476 mediaPlayerState->setPlaying(TRUE);
477 d->selectedFiles->unSelect(); 477 d->selectedFiles->unSelect();
478} 478}
479 479
480 480
481void PlayListWidget::addToSelection( QListViewItem *it) { 481void PlayListWidget::addToSelection( QListViewItem *it) {
482 d->setDocumentUsed = FALSE; 482 d->setDocumentUsed = FALSE;
483 483
484 if(it) { 484 if(it) {
485 if ( currentTab() == CurrentPlayList ) 485 if ( currentTab() == CurrentPlayList )
486 return; 486 return;
487 DocLnk lnk; 487 DocLnk lnk;
488 QString filename; 488 QString filename;
489 489
490 filename=it->text(3); 490 filename=it->text(3);
491 lnk.setName( QFileInfo(filename).baseName() ); //sets name 491 lnk.setName( QFileInfo(filename).baseName() ); //sets name
492 lnk.setFile( filename ); //sets file name 492 lnk.setFile( filename ); //sets file name
493 d->selectedFiles->addToSelection( lnk); 493 d->selectedFiles->addToSelection( lnk);
494 494
495 writeCurrentM3u(); 495 writeCurrentM3u();
496// tabWidget->setCurrentPage(0); 496// tabWidget->setCurrentPage(0);
497 497
498 } 498 }
499} 499}
500 500
501 501
502void PlayListWidget::tabChanged(QWidget *) { 502void PlayListWidget::tabChanged(QWidget *) {
503 503
504 d->tbPlay->setEnabled( true ); 504 d->tbPlay->setEnabled( true );
505 505
506 disconnect( audioView, SIGNAL( itemsSelected( bool ) ), 506 disconnect( audioView, SIGNAL( itemsSelected(bool) ),
507 d->tbPlay, SLOT( setEnabled( bool ) ) ); 507 d->tbPlay, SLOT( setEnabled(bool) ) );
508 disconnect( videoView, SIGNAL( itemsSelected( bool ) ), 508 disconnect( videoView, SIGNAL( itemsSelected(bool) ),
509 d->tbPlay, SLOT( setEnabled( bool ) ) ); 509 d->tbPlay, SLOT( setEnabled(bool) ) );
510 510
511 currentFileListView = 0; 511 currentFileListView = 0;
512 512
513 switch ( currentTab() ) { 513 switch ( currentTab() ) {
514 case CurrentPlayList: 514 case CurrentPlayList:
515 { 515 {
516 if( !tbDeletePlaylist->isHidden() ) { 516 if( !tbDeletePlaylist->isHidden() ) {
517 tbDeletePlaylist->hide(); 517 tbDeletePlaylist->hide();
518 } 518 }
519 d->tbRemoveFromList->setEnabled(TRUE); 519 d->tbRemoveFromList->setEnabled(TRUE);
520 d->tbAddToList->setEnabled(FALSE); 520 d->tbAddToList->setEnabled(FALSE);
521 521
522 d->tbPlay->setEnabled( !d->selectedFiles->isEmpty() ); 522 d->tbPlay->setEnabled( !d->selectedFiles->isEmpty() );
523 } 523 }
524 break; 524 break;
525 case AudioFiles: 525 case AudioFiles:
526 { 526 {
527 audioView->populateView(); 527 audioView->populateView();
528 528
529 if( !tbDeletePlaylist->isHidden() ) { 529 if( !tbDeletePlaylist->isHidden() ) {
530 tbDeletePlaylist->hide(); 530 tbDeletePlaylist->hide();
531 } 531 }
532 d->tbRemoveFromList->setEnabled(FALSE); 532 d->tbRemoveFromList->setEnabled(FALSE);
533 d->tbAddToList->setEnabled(TRUE); 533 d->tbAddToList->setEnabled(TRUE);
534 534
535 connect( audioView, SIGNAL( itemsSelected( bool ) ), 535 connect( audioView, SIGNAL( itemsSelected(bool) ),
536 d->tbPlay, SLOT( setEnabled( bool ) ) ); 536 d->tbPlay, SLOT( setEnabled(bool) ) );
537 537
538 d->tbPlay->setEnabled( audioView->hasSelection() ); 538 d->tbPlay->setEnabled( audioView->hasSelection() );
539 539
540 currentFileListView = audioView; 540 currentFileListView = audioView;
541 } 541 }
542 break; 542 break;
543 case VideoFiles: 543 case VideoFiles:
544 { 544 {
545 videoView->populateView(); 545 videoView->populateView();
546 if( !tbDeletePlaylist->isHidden() ) { 546 if( !tbDeletePlaylist->isHidden() ) {
547 tbDeletePlaylist->hide(); 547 tbDeletePlaylist->hide();
548 } 548 }
549 d->tbRemoveFromList->setEnabled(FALSE); 549 d->tbRemoveFromList->setEnabled(FALSE);
550 d->tbAddToList->setEnabled(TRUE); 550 d->tbAddToList->setEnabled(TRUE);
551 551
552 connect( videoView, SIGNAL( itemsSelected( bool ) ), 552 connect( videoView, SIGNAL( itemsSelected(bool) ),
553 d->tbPlay, SLOT( setEnabled( bool ) ) ); 553 d->tbPlay, SLOT( setEnabled(bool) ) );
554 554
555 d->tbPlay->setEnabled( videoView->hasSelection() ); 555 d->tbPlay->setEnabled( videoView->hasSelection() );
556 556
557 currentFileListView = videoView; 557 currentFileListView = videoView;
558 } 558 }
559 break; 559 break;
560 case PlayLists: 560 case PlayLists:
561 { 561 {
562 if( tbDeletePlaylist->isHidden() ) { 562 if( tbDeletePlaylist->isHidden() ) {
563 tbDeletePlaylist->show(); 563 tbDeletePlaylist->show();
564 } 564 }
565 playLists->reread(); 565 playLists->reread();
566 d->tbAddToList->setEnabled(FALSE); 566 d->tbAddToList->setEnabled(FALSE);
567 567
568 d->tbPlay->setEnabled( false ); 568 d->tbPlay->setEnabled( false );
569 } 569 }
570 break; 570 break;
571 }; 571 };
572} 572}
573 573
574 574
575void PlayListWidget::btnPlay(bool b) { 575void PlayListWidget::btnPlay(bool b) {
576// mediaPlayerState->setPlaying(false); 576// mediaPlayerState->setPlaying(false);
577 mediaPlayerState->setPlaying(b); 577 mediaPlayerState->setPlaying(b);
578 insanityBool=FALSE; 578 insanityBool=FALSE;
579} 579}
580 580
581void PlayListWidget::deletePlaylist() { 581void PlayListWidget::deletePlaylist() {
582 switch( QMessageBox::information( this, (tr("Remove Playlist?")), 582 switch( QMessageBox::information( this, (tr("Remove Playlist?")),
583 (tr("You really want to delete\nthis playlist?")), 583 (tr("You really want to delete\nthis playlist?")),
584 (tr("Yes")), (tr("No")), 0 )){ 584 (tr("Yes")), (tr("No")), 0 )){
585 case 0: // Yes clicked, 585 case 0: // Yes clicked,
586 QFile().remove(playLists->selectedDocument().file()); 586 QFile().remove(playLists->selectedDocument().file());
587 QFile().remove(playLists->selectedDocument().linkFile()); 587 QFile().remove(playLists->selectedDocument().linkFile());
588 playLists->reread(); 588 playLists->reread();
589 break; 589 break;
590 case 1: // Cancel 590 case 1: // Cancel
591 break; 591 break;
592 }; 592 };
593} 593}
594 594
595 595
596void PlayListWidget::playSelected() { 596void PlayListWidget::playSelected() {
597 btnPlay( TRUE); 597 btnPlay( TRUE);
598} 598}
599 599
600bool PlayListWidget::inFileListMode() const 600bool PlayListWidget::inFileListMode() const
601{ 601{
602 TabType tab = currentTab(); 602 TabType tab = currentTab();
603 return tab == AudioFiles || tab == VideoFiles; 603 return tab == AudioFiles || tab == VideoFiles;
604} 604}
605 605
606void PlayListWidget::openURL() { 606void PlayListWidget::openURL() {
607 // http://66.28.164.33:2080 607 // http://66.28.164.33:2080
608 // http://somafm.com/star0242.m3u 608 // http://somafm.com/star0242.m3u
609 QString filename, name; 609 QString filename, name;
610 InputDialog *fileDlg; 610 InputDialog *fileDlg;
611 fileDlg = new InputDialog(this,tr("Add URL"),TRUE, 0); 611 fileDlg = new InputDialog(this,tr("Add URL"),TRUE, 0);
612 fileDlg->exec(); 612 fileDlg->exec();
613 if( fileDlg->result() == 1 ) { 613 if( fileDlg->result() == 1 ) {
614 filename = fileDlg->text(); 614 filename = fileDlg->text();
615 qDebug( "Selected filename is " + filename ); 615 qDebug( "Selected filename is " + filename );
616 // Om3u *m3uList; 616 // Om3u *m3uList;
617 DocLnk lnk; 617 DocLnk lnk;
618 Config cfg( "OpiePlayer" ); 618 Config cfg( "OpiePlayer" );
619 cfg.setGroup("PlayList"); 619 cfg.setGroup("PlayList");
620 620
621 if(filename.left(4) == "http") { 621 if(filename.left(4) == "http") {
622 QString m3uFile, m3uFilePath; 622 QString m3uFile, m3uFilePath;
623 if(filename.find(":",8,TRUE) != -1) { //found a port 623 if(filename.find(":",8,TRUE) != -1) { //found a port
624 m3uFile = filename.left( filename.find( ":",8,TRUE)); 624 m3uFile = filename.left( filename.find( ":",8,TRUE));
625 m3uFile = m3uFile.right( 7); 625 m3uFile = m3uFile.right( 7);
626 } else if(filename.left(4) == "http"){ 626 } else if(filename.left(4) == "http"){
627 m3uFile=filename; 627 m3uFile=filename;
628 m3uFile = m3uFile.right( m3uFile.length() - 7); 628 m3uFile = m3uFile.right( m3uFile.length() - 7);
629 } else{ 629 } else{
630 m3uFile=filename; 630 m3uFile=filename;
631 } 631 }
632 632
633 lnk.setName( filename ); //sets name 633 lnk.setName( filename ); //sets name
634 lnk.setFile( filename ); //sets file name 634 lnk.setFile( filename ); //sets file name
635 635
636// lnk.setIcon("opieplayer2/musicfile"); 636// lnk.setIcon("opieplayer2/musicfile");
637 637
638 d->selectedFiles->addToSelection( lnk ); 638 d->selectedFiles->addToSelection( lnk );
639 writeCurrentM3u(); 639 writeCurrentM3u();
640 d->selectedFiles->setSelectedItem( lnk.name()); 640 d->selectedFiles->setSelectedItem( lnk.name());
641 } 641 }
642 else if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) { 642 else if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) {
643 readListFromFile( filename ); 643 readListFromFile( filename );
644 } else { 644 } else {
645 lnk.setName( QFileInfo(filename).baseName() ); //sets name 645 lnk.setName( QFileInfo(filename).baseName() ); //sets name
646 lnk.setFile( filename ); //sets file name 646 lnk.setFile( filename ); //sets file name
647 d->selectedFiles->addToSelection( lnk); 647 d->selectedFiles->addToSelection( lnk);
648 writeCurrentM3u(); 648 writeCurrentM3u();
649 d->selectedFiles->setSelectedItem( lnk.name()); 649 d->selectedFiles->setSelectedItem( lnk.name());
650 } 650 }
651 } 651 }
652 652
653 653
654 delete fileDlg; 654 delete fileDlg;
655} 655}
656 656
657 657
658void PlayListWidget::openFile() { 658void PlayListWidget::openFile() {
659 659
660 QString filename, name; 660 QString filename, name;
661 661
662 Config cfg( "OpiePlayer" ); 662 Config cfg( "OpiePlayer" );
663 cfg.setGroup("Dialog"); 663 cfg.setGroup("Dialog");
664 MimeTypes types; 664 MimeTypes types;
665 QStringList audio, video, all; 665 QStringList audio, video, all;
666 audio << "audio/*"; 666 audio << "audio/*";
667 audio << "playlist/plain"; 667 audio << "playlist/plain";
668 audio << "application/ogg"; 668 audio << "application/ogg";
669 audio << "audio/x-mpegurl"; 669 audio << "audio/x-mpegurl";
670 670
671 video << "video/*"; 671 video << "video/*";
672 video << "playlist/plain"; 672 video << "playlist/plain";
673 673
674 all += audio; 674 all += audio;
675 all += video; 675 all += video;
676 types.insert("All Media Files", all ); 676 types.insert("All Media Files", all );
677 types.insert("Audio", audio ); 677 types.insert("Audio", audio );
678 types.insert("Video", video ); 678 types.insert("Video", video );
679 679
680 QString str = OFileDialog::getOpenFileName( 1, 680 QString str = OFileDialog::getOpenFileName( 1,
681 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"", 681 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"",
682 types, 0 ); 682 types, 0 );
683 683
684 if(str.left(2) == "//") { 684 if(str.left(2) == "//") {
685 str=str.right(str.length()-1); 685 str=str.right(str.length()-1);
686 } 686 }
687 cfg.writeEntry( "LastDirectory" ,QFileInfo( str ).dirPath() ); 687 cfg.writeEntry( "LastDirectory" ,QFileInfo( str ).dirPath() );
688 688
689 if( !str.isEmpty() ) { 689 if( !str.isEmpty() ) {
690 690
691 qDebug( "Selected filename is " + str ); 691 qDebug( "Selected filename is " + str );
692 filename = str; 692 filename = str;
693 DocLnk lnk; 693 DocLnk lnk;
694 694
695 if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) { 695 if( filename.right( 3) == "m3u" || filename.right(3) == "pls" ) {
696 readListFromFile( filename ); 696 readListFromFile( filename );
697 } else { 697 } else {
698 lnk.setName( QFileInfo(filename).baseName() ); //sets name 698 lnk.setName( QFileInfo(filename).baseName() ); //sets name
699 lnk.setFile( filename ); //sets file name 699 lnk.setFile( filename ); //sets file name
700 d->selectedFiles->addToSelection( lnk ); 700 d->selectedFiles->addToSelection( lnk );
701 writeCurrentM3u(); 701 writeCurrentM3u();
702 d->selectedFiles->setSelectedItem( lnk.name() ); 702 d->selectedFiles->setSelectedItem( lnk.name() );
703 } 703 }
704 } 704 }
705} 705}
706 706
707 707
708void PlayListWidget::readListFromFile( const QString &filename ) { 708void PlayListWidget::readListFromFile( const QString &filename ) {
709 qDebug( "read list filename " + filename ); 709 qDebug( "read list filename " + filename );
710 QFileInfo fi(filename); 710 QFileInfo fi(filename);
711 Om3u *m3uList; 711 Om3u *m3uList;
712 QString s, name; 712 QString s, name;
713 m3uList = new Om3u( filename, IO_ReadOnly ); 713 m3uList = new Om3u( filename, IO_ReadOnly );
714 if(fi.extension(false).find("m3u",0,false) != -1 ) 714 if(fi.extension(false).find("m3u",0,false) != -1 )
715 m3uList->readM3u(); 715 m3uList->readM3u();
716 else if(fi.extension(false).find("pls",0,false) != -1 ) 716 else if(fi.extension(false).find("pls",0,false) != -1 )
717 m3uList->readPls(); 717 m3uList->readPls();
718 718
719 DocLnk lnk; 719 DocLnk lnk;
720 for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) { 720 for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) {
721 s = *it; 721 s = *it;
722 // qDebug(s); 722 // qDebug(s);
723 if(s.left(4)=="http") { 723 if(s.left(4)=="http") {
724 lnk.setName( s ); //sets file name 724 lnk.setName( s ); //sets file name
725 lnk.setIcon("opieplayer2/musicfile"); 725 lnk.setIcon("opieplayer2/musicfile");
726 lnk.setFile( s ); //sets file name 726 lnk.setFile( s ); //sets file name
727 727
728 } else { //is file 728 } else { //is file
729 lnk.setName( QFileInfo(s).baseName()); 729 lnk.setName( QFileInfo(s).baseName());
730 if(s.left(1) != "/") { 730 if(s.left(1) != "/") {
731 731
732 lnk.setFile( QFileInfo(filename).dirPath()+"/"+s); 732 lnk.setFile( QFileInfo(filename).dirPath()+"/"+s);
733 } else { 733 } else {
734 lnk.setFile( s); 734 lnk.setFile( s);
735 } 735 }
736 } 736 }
737 d->selectedFiles->addToSelection( lnk ); 737 d->selectedFiles->addToSelection( lnk );
738 } 738 }
739 Config config( "OpiePlayer" ); 739 Config config( "OpiePlayer" );
740 config.setGroup( "PlayList" ); 740 config.setGroup( "PlayList" );
741 741
742 config.writeEntry("CurrentPlaylist",filename); 742 config.writeEntry("CurrentPlaylist",filename);
743 config.write(); 743 config.write();
744 currentPlayList=filename; 744 currentPlayList=filename;
745 745
746 m3uList->close(); 746 m3uList->close();
747 delete m3uList; 747 delete m3uList;
748 748
749 d->selectedFiles->setSelectedItem( s); 749 d->selectedFiles->setSelectedItem( s);
750 setCaption(tr("OpiePlayer: ")+ QFileInfo(filename).baseName()); 750 setCaption(tr("OpiePlayer: ")+ QFileInfo(filename).baseName());
751 751
752} 752}
753 753
754// writes current playlist to current m3u file */ 754// writes current playlist to current m3u file */
755 void PlayListWidget::writeCurrentM3u() { 755 void PlayListWidget::writeCurrentM3u() {
756 qDebug("writing to current m3u"); 756 qDebug("writing to current m3u");
757 Config cfg( "OpiePlayer" ); 757 Config cfg( "OpiePlayer" );
758 cfg.setGroup("PlayList"); 758 cfg.setGroup("PlayList");
759 QString currentPlaylist = cfg.readEntry("CurrentPlaylist","default"); 759 QString currentPlaylist = cfg.readEntry("CurrentPlaylist","default");
760 760
761 Om3u *m3uList; 761 Om3u *m3uList;
762 m3uList = new Om3u( currentPlaylist, IO_ReadWrite | IO_Truncate ); 762 m3uList = new Om3u( currentPlaylist, IO_ReadWrite | IO_Truncate );
763 if( d->selectedFiles->first()) { 763 if( d->selectedFiles->first()) {
764 764
765 do { 765 do {
766 // qDebug( "add writeCurrentM3u " +d->selectedFiles->current()->file()); 766 // qDebug( "add writeCurrentM3u " +d->selectedFiles->current()->file());
767 m3uList->add( d->selectedFiles->current()->file() ); 767 m3uList->add( d->selectedFiles->current()->file() );
768 } 768 }
769 while ( d->selectedFiles->next() ); 769 while ( d->selectedFiles->next() );
770 // qDebug( "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" ); 770 // qDebug( "<<<<<<<<<<<<>>>>>>>>>>>>>>>>>" );
771 m3uList->write(); 771 m3uList->write();
772 m3uList->close(); 772 m3uList->close();
773 } 773 }
774 delete m3uList; 774 delete m3uList;
775 775
776 } 776 }
777 777
778 /* 778 /*
779 writes current playlist to m3u file */ 779 writes current playlist to m3u file */
780void PlayListWidget::writem3u() { 780void PlayListWidget::writem3u() {
781 //InputDilog *fileDlg; 781 //InputDilog *fileDlg;
782 //fileDlg = new InputDialog( this, tr( "Save m3u Playlist " ), TRUE, 0); 782 //fileDlg = new InputDialog( this, tr( "Save m3u Playlist " ), TRUE, 0);
783 //fileDlg->exec(); 783 //fileDlg->exec();
784 784
785 Config cfg( "OpiePlayer" ); 785 Config cfg( "OpiePlayer" );
786 cfg.setGroup("Dialog"); 786 cfg.setGroup("Dialog");
787 MimeTypes types; 787 MimeTypes types;
788 QStringList audio, video, all; 788 QStringList audio, video, all;
789 audio << "audio/*"; 789 audio << "audio/*";
790 audio << "playlist/plain"; 790 audio << "playlist/plain";
791 audio << "audio/x-mpegurl"; 791 audio << "audio/x-mpegurl";
792 792
793 video << "video/*"; 793 video << "video/*";
794 video << "playlist/plain"; 794 video << "playlist/plain";
795 795
796 all += audio; 796 all += audio;
797 all += video; 797 all += video;
798 types.insert("All Media Files", all ); 798 types.insert("All Media Files", all );
799 types.insert("Audio", audio ); 799 types.insert("Audio", audio );
800 types.insert("Video", video ); 800 types.insert("Video", video );
801 801
802 QString str = OFileDialog::getOpenFileName( 1, 802 QString str = OFileDialog::getOpenFileName( 1,
803 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"", 803 cfg.readEntry("LastDirectory",QPEApplication::documentDir()),"",
804 types, 0 ); 804 types, 0 );
805 if(str.left(2) == "//") str=str.right(str.length()-1); 805 if(str.left(2) == "//") str=str.right(str.length()-1);
806 cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath()); 806 cfg.writeEntry("LastDirectory" ,QFileInfo(str).dirPath());
807 807
808 808
809 QString name, filename, list; 809 QString name, filename, list;
810 Om3u *m3uList; 810 Om3u *m3uList;
811 811
812 if( !str.isEmpty() ) { 812 if( !str.isEmpty() ) {
813 name = str; 813 name = str;
814 // name = fileDlg->text(); 814 // name = fileDlg->text();
815// qDebug( filename ); 815// qDebug( filename );
816 if( name.find("/",0,true) != -1) {// assume they specify a file path 816 if( name.find("/",0,true) != -1) {// assume they specify a file path
817 filename = name; 817 filename = name;
818 name = name.right(name.length()- name.findRev("/",-1,true) - 1 ); 818 name = name.right(name.length()- name.findRev("/",-1,true) - 1 );
819 } 819 }
820 else //otherwise dump it somewhere noticable 820 else //otherwise dump it somewhere noticable
821 filename = QPEApplication::documentDir() + "/" + name; 821 filename = QPEApplication::documentDir() + "/" + name;
822 822
823 if( filename.right( 3 ) != "m3u" ) //needs filename extension 823 if( filename.right( 3 ) != "m3u" ) //needs filename extension
824 filename += ".m3u"; 824 filename += ".m3u";
825 825
826 if( d->selectedFiles->first()) { //ramble through playlist view 826 if( d->selectedFiles->first()) { //ramble through playlist view
827 m3uList = new Om3u( filename, IO_ReadWrite | IO_Truncate); 827 m3uList = new Om3u( filename, IO_ReadWrite | IO_Truncate);
828 828
829 do { 829 do {
830 m3uList->add( d->selectedFiles->current()->file()); 830 m3uList->add( d->selectedFiles->current()->file());
831 } 831 }
832 while ( d->selectedFiles->next() ); 832 while ( d->selectedFiles->next() );
833 // qDebug( list ); 833 // qDebug( list );
834 m3uList->write(); 834 m3uList->write();
835 m3uList->close(); 835 m3uList->close();
836 delete m3uList; 836 delete m3uList;
837 837
838 //delete fileDlg; 838 //delete fileDlg;
839 839
840 DocLnk lnk; 840 DocLnk lnk;
841 lnk.setFile( filename); 841 lnk.setFile( filename);
842 lnk.setIcon("opieplayer2/playlist2"); 842 lnk.setIcon("opieplayer2/playlist2");
843 lnk.setName( name); //sets file name 843 lnk.setName( name); //sets file name
844 844
845 // qDebug(filename); 845 // qDebug(filename);
846 Config config( "OpiePlayer" ); 846 Config config( "OpiePlayer" );
847 config.setGroup( "PlayList" ); 847 config.setGroup( "PlayList" );
848 848
849 config.writeEntry("CurrentPlaylist",filename); 849 config.writeEntry("CurrentPlaylist",filename);
850 currentPlayList=filename; 850 currentPlayList=filename;
851 851
852 if(!lnk.writeLink()) { 852 if(!lnk.writeLink()) {
853 qDebug("Writing doclink did not work"); 853 qDebug("Writing doclink did not work");
854 } 854 }
855 855
856 setCaption(tr("OpiePlayer: ") + name); 856 setCaption(tr("OpiePlayer: ") + name);
857 } 857 }
858 } 858 }
859} 859}
860 860
861void PlayListWidget::keyReleaseEvent( QKeyEvent *e ) { 861void PlayListWidget::keyReleaseEvent( QKeyEvent *e ) {
862 switch ( e->key() ) { 862 switch ( e->key() ) {
863 ////////////////////////////// Zaurus keys 863 ////////////////////////////// Zaurus keys
864 case Key_F9: //activity 864 case Key_F9: //activity
865 // if(audioUI->isHidden()) 865 // if(audioUI->isHidden())
866 // audioUI->showMaximized(); 866 // audioUI->showMaximized();
867 break; 867 break;
868 case Key_F10: //contacts 868 case Key_F10: //contacts
869 // if( videoUI->isHidden()) 869 // if( videoUI->isHidden())
870 // videoUI->showMaximized(); 870 // videoUI->showMaximized();
871 break; 871 break;
872 case Key_F11: //menu 872 case Key_F11: //menu
873 break; 873 break;
874 case Key_F12: //home 874 case Key_F12: //home
875 // doBlank(); 875 // doBlank();
876 break; 876 break;
877 case Key_F13: //mail 877 case Key_F13: //mail
878 // doUnblank(); 878 // doUnblank();
879 break; 879 break;
880 case Key_Q: //add to playlist 880 case Key_Q: //add to playlist
881 addSelected(); 881 addSelected();
882 break; 882 break;
883 case Key_R: //remove from playlist 883 case Key_R: //remove from playlist
884 removeSelected(); 884 removeSelected();
885 break; 885 break;
886 // case Key_P: //play 886 // case Key_P: //play
887 // qDebug("Play"); 887 // qDebug("Play");
888 // playSelected(); 888 // playSelected();
889 // break; 889 // break;
890 case Key_Space: 890 case Key_Space:
891 // playSelected(); puh 891 // playSelected(); puh
892 break; 892 break;
893 case Key_1: 893 case Key_1:
894 tabWidget->setCurrentPage( 0 ); 894 tabWidget->setCurrentPage( 0 );
895 break; 895 break;
896 case Key_2: 896 case Key_2:
897 tabWidget->setCurrentPage( 1 ); 897 tabWidget->setCurrentPage( 1 );
898 break; 898 break;
899 case Key_3: 899 case Key_3:
900 tabWidget->setCurrentPage( 2 ); 900 tabWidget->setCurrentPage( 2 );
901 break; 901 break;
902 case Key_4: 902 case Key_4:
903 tabWidget->setCurrentPage( 3 ); 903 tabWidget->setCurrentPage( 3 );
904 break; 904 break;
905 case Key_Down: 905 case Key_Down:
906 if ( !d->selectedFiles->next() ) 906 if ( !d->selectedFiles->next() )
907 d->selectedFiles->first(); 907 d->selectedFiles->first();
908 break; 908 break;
909 case Key_Up: 909 case Key_Up:
910 if ( !d->selectedFiles->prev() ) 910 if ( !d->selectedFiles->prev() )
911 // d->selectedFiles->last(); 911 // d->selectedFiles->last();
912 break; 912 break;
913 } 913 }
914} 914}
915 915
916void PlayListWidget::pmViewActivated(int index) { 916void PlayListWidget::pmViewActivated(int index) {
917// qDebug("%d", index); 917// qDebug("%d", index);
918 switch(index) { 918 switch(index) {
919 case -16: 919 case -16:
920 { 920 {
921 mediaPlayerState->toggleFullscreen(); 921 mediaPlayerState->toggleFullscreen();
922 bool b=mediaPlayerState->isFullscreen(); 922 bool b=mediaPlayerState->isFullscreen();
923 pmView->setItemChecked( index, b); 923 pmView->setItemChecked( index, b);
924 Config cfg( "OpiePlayer" ); 924 Config cfg( "OpiePlayer" );
925 cfg.writeEntry( "FullScreen", b ); 925 cfg.writeEntry( "FullScreen", b );
926 } 926 }
927 break; 927 break;
928 }; 928 };
929} 929}
930 930
931void PlayListWidget::populateSkinsMenu() { 931void PlayListWidget::populateSkinsMenu() {
932 int item = 0; 932 int item = 0;
933 defaultSkinIndex = 0; 933 defaultSkinIndex = 0;
934 QString skinName; 934 QString skinName;
935 Config cfg( "OpiePlayer" ); 935 Config cfg( "OpiePlayer" );
936 cfg.setGroup("Options" ); 936 cfg.setGroup("Options" );
937 QString skin = cfg.readEntry( "Skin", "default" ); 937 QString skin = cfg.readEntry( "Skin", "default" );
938 938
939 QDir skinsDir( QPEApplication::qpeDir() + "/pics/opieplayer2/skins" ); 939 QDir skinsDir( QPEApplication::qpeDir() + "/pics/opieplayer2/skins" );
940 skinsDir.setFilter( QDir::Dirs ); 940 skinsDir.setFilter( QDir::Dirs );
941 skinsDir.setSorting(QDir::Name ); 941 skinsDir.setSorting(QDir::Name );
942 const QFileInfoList *skinslist = skinsDir.entryInfoList(); 942 const QFileInfoList *skinslist = skinsDir.entryInfoList();
943 QFileInfoListIterator it( *skinslist ); 943 QFileInfoListIterator it( *skinslist );
944 QFileInfo *fi; 944 QFileInfo *fi;
945 while ( ( fi = it.current() ) ) { 945 while ( ( fi = it.current() ) ) {
946 skinName = fi->fileName(); 946 skinName = fi->fileName();
947// qDebug( fi->fileName() ); 947// qDebug( fi->fileName() );
948 if( skinName != "." && skinName != ".." && skinName !="CVS" ) { 948 if( skinName != "." && skinName != ".." && skinName !="CVS" ) {
949 item = skinsMenu->insertItem( fi->fileName() ) ; 949 item = skinsMenu->insertItem( fi->fileName() ) ;
950 } 950 }
951 if( skinName == "default" ) { 951 if( skinName == "default" ) {
952 defaultSkinIndex = item; 952 defaultSkinIndex = item;
953 } 953 }
954 if( skinName == skin ) { 954 if( skinName == skin ) {
955 skinsMenu->setItemChecked( item, TRUE ); 955 skinsMenu->setItemChecked( item, TRUE );
956 } 956 }
957 ++it; 957 ++it;
958 } 958 }
959} 959}
960 960
961void PlayListWidget::skinsMenuActivated( int item ) { 961void PlayListWidget::skinsMenuActivated( int item ) {
962 for(unsigned int i = defaultSkinIndex; i > defaultSkinIndex - skinsMenu->count(); i-- ) { 962 for(unsigned int i = defaultSkinIndex; i > defaultSkinIndex - skinsMenu->count(); i-- ) {
963 skinsMenu->setItemChecked( i, FALSE ); 963 skinsMenu->setItemChecked( i, FALSE );
964 } 964 }
965 skinsMenu->setItemChecked( item, TRUE ); 965 skinsMenu->setItemChecked( item, TRUE );
966 966
967 { 967 {
968 Config cfg( "OpiePlayer" ); 968 Config cfg( "OpiePlayer" );
969 cfg.setGroup("Options"); 969 cfg.setGroup("Options");
970 cfg.writeEntry("Skin", skinsMenu->text( item ) ); 970 cfg.writeEntry("Skin", skinsMenu->text( item ) );
971 } 971 }
972 972
973 emit skinSelected(); 973 emit skinSelected();
974} 974}
975 975
976PlayListWidget::TabType PlayListWidget::currentTab() const 976PlayListWidget::TabType PlayListWidget::currentTab() const
977{ 977{
978 static const TabType indexToTabType[ TabTypeCount ] = 978 static const TabType indexToTabType[ TabTypeCount ] =
979 { CurrentPlayList, AudioFiles, VideoFiles, PlayLists }; 979 { CurrentPlayList, AudioFiles, VideoFiles, PlayLists };
980 980
981 int index = tabWidget->currentPageIndex(); 981 int index = tabWidget->currentPageIndex();
982 assert( index < TabTypeCount && index >= 0 ); 982 assert( index < TabTypeCount && index >= 0 );
983 983
984 return indexToTabType[ index ]; 984 return indexToTabType[ index ];
985} 985}
986 986
987PlayListWidget::Entry PlayListWidget::currentEntry() const 987PlayListWidget::Entry PlayListWidget::currentEntry() const
988{ 988{
989 if ( currentTab() == CurrentPlayList ) { 989 if ( currentTab() == CurrentPlayList ) {
990 const DocLnk *lnk = current(); 990 const DocLnk *lnk = current();
991 return Entry( lnk->name(), lnk->file() ); 991 return Entry( lnk->name(), lnk->file() );
992 } 992 }
993 993
994 return Entry( currentFileListPathName() ); 994 return Entry( currentFileListPathName() );
995} 995}
996 996
997QString PlayListWidget::currentFileListPathName() const { 997QString PlayListWidget::currentFileListPathName() const {
998 return currentFileListView->currentItem()->text( 3 ); 998 return currentFileListView->currentItem()->text( 3 );
999} 999}
1000 1000
1001 1001
1002void PlayListWidget::qcopReceive(const QCString &msg, const QByteArray &data) { 1002void PlayListWidget::qcopReceive(const QCString &msg, const QByteArray &data) {
1003 qDebug("qcop message "+msg ); 1003 qDebug("qcop message "+msg );
1004 QDataStream stream ( data, IO_ReadOnly ); 1004 QDataStream stream ( data, IO_ReadOnly );
1005 if ( msg == "play()" ) { //plays current selection 1005 if ( msg == "play()" ) { //plays current selection
1006 btnPlay( true); 1006 btnPlay( true);
1007 } else if ( msg == "stop()" ) { 1007 } else if ( msg == "stop()" ) {
1008 mediaPlayerState->setPlaying( false); 1008 mediaPlayerState->setPlaying( false);
1009 } else if ( msg == "togglePause()" ) { 1009 } else if ( msg == "togglePause()" ) {
1010 mediaPlayerState->togglePaused(); 1010 mediaPlayerState->togglePaused();
1011 } else if ( msg == "next()" ) { //select next in list 1011 } else if ( msg == "next()" ) { //select next in list
1012 mediaPlayerState->setNext(); 1012 mediaPlayerState->setNext();
1013 } else if ( msg == "prev()" ) { //select previous in list 1013 } else if ( msg == "prev()" ) { //select previous in list
1014 mediaPlayerState->setPrev(); 1014 mediaPlayerState->setPrev();
1015 } else if ( msg == "toggleLooping()" ) { //loop or not loop 1015 } else if ( msg == "toggleLooping()" ) { //loop or not loop
1016 mediaPlayerState->toggleLooping(); 1016 mediaPlayerState->toggleLooping();
1017 } else if ( msg == "toggleShuffled()" ) { //shuffled or not shuffled 1017 } else if ( msg == "toggleShuffled()" ) { //shuffled or not shuffled
1018 mediaPlayerState->toggleShuffled(); 1018 mediaPlayerState->toggleShuffled();
1019 } else if ( msg == "volUp()" ) { //volume more 1019 } else if ( msg == "volUp()" ) { //volume more
1020// emit moreClicked(); 1020// emit moreClicked();
1021// emit moreReleased(); 1021// emit moreReleased();
1022 } else if ( msg == "volDown()" ) { //volume less 1022 } else if ( msg == "volDown()" ) { //volume less
1023// emit lessClicked(); 1023// emit lessClicked();
1024// emit lessReleased(); 1024// emit lessReleased();
1025 } else if ( msg == "play(QString)" ) { //play this now 1025 } else if ( msg == "play(QString)" ) { //play this now
1026 QString file; 1026 QString file;
1027 stream >> file; 1027 stream >> file;
1028 setDocument( (const QString &) file); 1028 setDocument( (const QString &) file);
1029 } else if ( msg == "add(QString)" ) { //add to playlist 1029 } else if ( msg == "add(QString)" ) { //add to playlist
1030 QString file; 1030 QString file;
1031 stream >> file; 1031 stream >> file;
1032 QFileInfo fileInfo(file); 1032 QFileInfo fileInfo(file);
1033 DocLnk lnk; 1033 DocLnk lnk;
1034 lnk.setName( fileInfo.baseName() ); //sets name 1034 lnk.setName( fileInfo.baseName() ); //sets name
1035 lnk.setFile( file ); //sets file name 1035 lnk.setFile( file ); //sets file name
1036 addToSelection( lnk ); 1036 addToSelection( lnk );
1037 } else if ( msg == "rem(QString)" ) { //remove from playlist 1037 } else if ( msg == "rem(QString)" ) { //remove from playlist
1038 QString file; 1038 QString file;
1039 stream >> file; 1039 stream >> file;
1040 1040
1041 } 1041 }
1042 1042
1043} 1043}
diff --git a/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp b/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp
index fec91ea..33fe188 100644
--- a/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp
+++ b/noncore/multimedia/opieplayer2/playlistwidgetgui.cpp
@@ -1,194 +1,194 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org>
5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
7 =. 7 =.
8 .=l. 8 .=l.
9           .>+-= 9           .>+-=
10 _;:,     .>    :=|. This program is free software; you can 10 _;:,     .>    :=|. This program is free software; you can
11.> <`_,   >  .   <= redistribute it and/or modify it under 11.> <`_,   >  .   <= redistribute it and/or modify it under
12:`=1 )Y*s>-.--   : the terms of the GNU General Public 12:`=1 )Y*s>-.--   : the terms of the GNU General Public
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; General Public License for more 22..}^=.=       =       ; General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = General Public License along with 26  -_. . .   )=.  = General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34 34
35#include <qtoolbar.h> 35#include <qtoolbar.h>
36#include <qpe/qpeapplication.h> 36#include <qpe/qpeapplication.h>
37 37
38#include <qlayout.h> 38#include <qlayout.h>
39#include <qmenubar.h> 39#include <qmenubar.h>
40 40
41#include "playlistselection.h" 41#include "playlistselection.h"
42#include "playlistwidget.h" 42#include "playlistwidget.h"
43#include "mediaplayerstate.h" 43#include "mediaplayerstate.h"
44#include "inputDialog.h" 44#include "inputDialog.h"
45#include "playlistfileview.h" 45#include "playlistfileview.h"
46 46
47#include "mediaplayerstate.h" 47#include "mediaplayerstate.h"
48 48
49PlayListWidgetGui::PlayListWidgetGui(QWidget* parent, const char* name ) 49PlayListWidgetGui::PlayListWidgetGui(QWidget* parent, const char* name )
50 : QMainWindow( parent, name ) { 50 : QMainWindow( parent, name ) {
51 51
52 d = new PlayListWidgetPrivate; 52 d = new PlayListWidgetPrivate;
53 d->setDocumentUsed = FALSE; 53 d->setDocumentUsed = FALSE;
54 54
55 setBackgroundMode( PaletteButton ); 55 setBackgroundMode( PaletteButton );
56 setToolBarsMovable( FALSE ); 56 setToolBarsMovable( FALSE );
57 57
58 // Create Toolbar 58 // Create Toolbar
59 QToolBar *toolbar = new QToolBar( this ); 59 QToolBar *toolbar = new QToolBar( this );
60 toolbar->setHorizontalStretchable( TRUE ); 60 toolbar->setHorizontalStretchable( TRUE );
61 61
62 // Create Menubar 62 // Create Menubar
63 QMenuBar *menu = new QMenuBar( toolbar ); 63 QMenuBar *menu = new QMenuBar( toolbar );
64 menu->setMargin( 0 ); 64 menu->setMargin( 0 );
65 65
66 bar = new QToolBar( this ); 66 bar = new QToolBar( this );
67 bar->setLabel( tr( "Play Operations" ) ); 67 bar->setLabel( tr( "Play Operations" ) );
68 68
69 tbDeletePlaylist = new QPushButton( Resource::loadIconSet( "trash" ), "", bar, "close" ); 69 tbDeletePlaylist = new QPushButton( Resource::loadIconSet( "trash" ), "", bar, "close" );
70 tbDeletePlaylist->setFlat( TRUE ); 70 tbDeletePlaylist->setFlat( TRUE );
71 tbDeletePlaylist->setFixedSize( 20, 20 ); 71 tbDeletePlaylist->setFixedSize( 20, 20 );
72 72
73 tbDeletePlaylist->hide(); 73 tbDeletePlaylist->hide();
74 74
75 pmPlayList = new QPopupMenu( this ); 75 pmPlayList = new QPopupMenu( this );
76 menu->insertItem( tr( "File" ), pmPlayList ); 76 menu->insertItem( tr( "File" ), pmPlayList );
77 77
78 pmView = new QPopupMenu( this ); 78 pmView = new QPopupMenu( this );
79 menu->insertItem( tr( "View" ), pmView ); 79 menu->insertItem( tr( "View" ), pmView );
80 pmView->isCheckable(); 80 pmView->isCheckable();
81 81
82 skinsMenu = new QPopupMenu( this ); 82 skinsMenu = new QPopupMenu( this );
83 pmView->insertItem( tr( "Skins" ), skinsMenu ); 83 pmView->insertItem( tr( "Skins" ), skinsMenu );
84 skinsMenu->isCheckable(); 84 skinsMenu->isCheckable();
85 85
86 gammaMenu = new QPopupMenu( this ); 86 gammaMenu = new QPopupMenu( this );
87 pmView->insertItem( tr( "Gamma (Video)" ), gammaMenu ); 87 pmView->insertItem( tr( "Gamma (Video)" ), gammaMenu );
88 88
89 gammaSlider = new QSlider( QSlider::Vertical, gammaMenu ); 89 gammaSlider = new QSlider( QSlider::Vertical, gammaMenu );
90 gammaSlider->setRange( -40, 40 ); 90 gammaSlider->setRange( -40, 40 );
91 gammaSlider->setTickmarks( QSlider::Left ); 91 gammaSlider->setTickmarks( QSlider::Left );
92 gammaSlider->setTickInterval( 20 ); 92 gammaSlider->setTickInterval( 20 );
93 gammaSlider->setFocusPolicy( QWidget::StrongFocus ); 93 gammaSlider->setFocusPolicy( QWidget::StrongFocus );
94 gammaSlider->setValue( 0 ); 94 gammaSlider->setValue( 0 );
95 gammaSlider->setMinimumHeight( 50 ); 95 gammaSlider->setMinimumHeight( 50 );
96 96
97 gammaLCD = new QLCDNumber( 3, gammaMenu ); 97 gammaLCD = new QLCDNumber( 3, gammaMenu );
98 gammaLCD-> setFrameShape ( QFrame::NoFrame ); 98 gammaLCD-> setFrameShape ( QFrame::NoFrame );
99 gammaLCD-> setSegmentStyle ( QLCDNumber::Flat ); 99 gammaLCD-> setSegmentStyle ( QLCDNumber::Flat );
100 100
101 gammaMenu->insertItem( gammaSlider ); 101 gammaMenu->insertItem( gammaSlider );
102 gammaMenu->insertItem( gammaLCD ); 102 gammaMenu->insertItem( gammaLCD );
103 103
104 connect( gammaSlider, SIGNAL( valueChanged( int ) ), gammaLCD, SLOT( display( int ) ) ); 104 connect( gammaSlider, SIGNAL( valueChanged(int) ), gammaLCD, SLOT( display(int) ) );
105 105
106 vbox5 = new QVBox( this ); 106 vbox5 = new QVBox( this );
107 QVBox *vbox4 = new QVBox( vbox5 ); 107 QVBox *vbox4 = new QVBox( vbox5 );
108 QHBox *hbox6 = new QHBox( vbox4 ); 108 QHBox *hbox6 = new QHBox( vbox4 );
109 109
110 tabWidget = new QTabWidget( hbox6, "tabWidget" ); 110 tabWidget = new QTabWidget( hbox6, "tabWidget" );
111 111
112 playListTab = new QWidget( tabWidget, "PlayListTab" ); 112 playListTab = new QWidget( tabWidget, "PlayListTab" );
113 tabWidget->insertTab( playListTab, "Playlist"); 113 tabWidget->insertTab( playListTab, "Playlist");
114 114
115 QGridLayout *Playout = new QGridLayout( playListTab ); 115 QGridLayout *Playout = new QGridLayout( playListTab );
116 Playout->setSpacing( 2); 116 Playout->setSpacing( 2);
117 Playout->setMargin( 2); 117 Playout->setMargin( 2);
118 118
119 // Add the playlist area 119 // Add the playlist area
120 QVBox *vbox3 = new QVBox( playListTab ); 120 QVBox *vbox3 = new QVBox( playListTab );
121 d->playListFrame = vbox3; 121 d->playListFrame = vbox3;
122 122
123 QHBox *hbox2 = new QHBox( vbox3 ); 123 QHBox *hbox2 = new QHBox( vbox3 );
124 d->selectedFiles = new PlayListSelection( hbox2 ); 124 d->selectedFiles = new PlayListSelection( hbox2 );
125 125
126 vbox1 = new QVBox( hbox2 ); 126 vbox1 = new QVBox( hbox2 );
127 QPEApplication::setStylusOperation( d->selectedFiles->viewport(), QPEApplication::RightOnHold ); 127 QPEApplication::setStylusOperation( d->selectedFiles->viewport(), QPEApplication::RightOnHold );
128 QVBox *stretch1 = new QVBox( vbox1 ); // add stretch 128 QVBox *stretch1 = new QVBox( vbox1 ); // add stretch
129 129
130 Playout->addMultiCellWidget( vbox3, 0, 0, 0, 1 ); 130 Playout->addMultiCellWidget( vbox3, 0, 0, 0, 1 );
131 131
132 QWidget *aTab; 132 QWidget *aTab;
133 aTab = new QWidget( tabWidget, "aTab" ); 133 aTab = new QWidget( tabWidget, "aTab" );
134 134
135 QGridLayout *Alayout = new QGridLayout( aTab ); 135 QGridLayout *Alayout = new QGridLayout( aTab );
136 Alayout->setSpacing( 2 ); 136 Alayout->setSpacing( 2 );
137 Alayout->setMargin( 2 ); 137 Alayout->setMargin( 2 );
138 // no m3u's here please 138 // no m3u's here please
139 audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;application/ogg", "opieplayer2/musicfile", aTab, "Audioview" ); 139 audioView = new PlayListFileView( "audio/mpeg;audio/x-wav;application/ogg", "opieplayer2/musicfile", aTab, "Audioview" );
140 Alayout->addMultiCellWidget( audioView, 0, 0, 0, 1 ); 140 Alayout->addMultiCellWidget( audioView, 0, 0, 0, 1 );
141 tabWidget->insertTab( aTab, tr( "Audio" ) ); 141 tabWidget->insertTab( aTab, tr( "Audio" ) );
142 142
143 QPEApplication::setStylusOperation( audioView->viewport(), QPEApplication::RightOnHold ); 143 QPEApplication::setStylusOperation( audioView->viewport(), QPEApplication::RightOnHold );
144 144
145 QWidget *vTab; 145 QWidget *vTab;
146 vTab = new QWidget( tabWidget, "vTab" ); 146 vTab = new QWidget( tabWidget, "vTab" );
147 147
148 QGridLayout *Vlayout = new QGridLayout( vTab ); 148 QGridLayout *Vlayout = new QGridLayout( vTab );
149 Vlayout->setSpacing( 2 ); 149 Vlayout->setSpacing( 2 );
150 Vlayout->setMargin( 2 ); 150 Vlayout->setMargin( 2 );
151 videoView = new PlayListFileView( "video/*", "opieplayer2/videofile", vTab, "Videoview" ); 151 videoView = new PlayListFileView( "video/*", "opieplayer2/videofile", vTab, "Videoview" );
152 Vlayout->addMultiCellWidget( videoView, 0, 0, 0, 1 ); 152 Vlayout->addMultiCellWidget( videoView, 0, 0, 0, 1 );
153 153
154 QPEApplication::setStylusOperation( videoView->viewport(), QPEApplication::RightOnHold ); 154 QPEApplication::setStylusOperation( videoView->viewport(), QPEApplication::RightOnHold );
155 155
156 tabWidget->insertTab( vTab, tr( "Video" ) ); 156 tabWidget->insertTab( vTab, tr( "Video" ) );
157 157
158 //playlists list 158 //playlists list
159 QWidget *LTab; 159 QWidget *LTab;
160 LTab = new QWidget( tabWidget, "LTab" ); 160 LTab = new QWidget( tabWidget, "LTab" );
161 QGridLayout *Llayout = new QGridLayout( LTab ); 161 QGridLayout *Llayout = new QGridLayout( LTab );
162 Llayout->setSpacing( 2 ); 162 Llayout->setSpacing( 2 );
163 Llayout->setMargin( 2 ); 163 Llayout->setMargin( 2 );
164 164
165 playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE ); 165 playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE );
166 Llayout->addMultiCellWidget( playLists, 0, 0, 0, 1 ); 166 Llayout->addMultiCellWidget( playLists, 0, 0, 0, 1 );
167 167
168 tabWidget->insertTab( LTab, tr( "Lists" ) ); 168 tabWidget->insertTab( LTab, tr( "Lists" ) );
169 169
170 setCentralWidget( vbox5 ); 170 setCentralWidget( vbox5 );
171} 171}
172 172
173 173
174 174
175PlayListWidgetGui::~PlayListWidgetGui() { 175PlayListWidgetGui::~PlayListWidgetGui() {
176} 176}
177 177
178void PlayListWidgetGui::setView( char view ) { 178void PlayListWidgetGui::setView( char view ) {
179 if ( view == 'l' ) 179 if ( view == 'l' )
180 showMaximized(); 180 showMaximized();
181 else 181 else
182 hide(); 182 hide();
183} 183}
184 184
185 185
186void PlayListWidgetGui::setActiveWindow() { 186void PlayListWidgetGui::setActiveWindow() {
187 // qDebug("SETTING active window"); 187 // qDebug("SETTING active window");
188 // When we get raised we need to ensure that it switches views 188 // When we get raised we need to ensure that it switches views
189 MediaPlayerState::DisplayType origDisplayType = mediaPlayerState->displayType(); 189 MediaPlayerState::DisplayType origDisplayType = mediaPlayerState->displayType();
190 mediaPlayerState->setDisplayType( MediaPlayerState::MediaSelection ); // invalidate 190 mediaPlayerState->setDisplayType( MediaPlayerState::MediaSelection ); // invalidate
191 mediaPlayerState->setDisplayType( origDisplayType ); // now switch back 191 mediaPlayerState->setDisplayType( origDisplayType ); // now switch back
192} 192}
193 193
194 194
diff --git a/noncore/multimedia/opieplayer2/threadutil.cpp b/noncore/multimedia/opieplayer2/threadutil.cpp
index ff38b1e..fb951b4 100644
--- a/noncore/multimedia/opieplayer2/threadutil.cpp
+++ b/noncore/multimedia/opieplayer2/threadutil.cpp
@@ -1,394 +1,394 @@
1/* This file is part of the KDE project 1/* This file is part of the KDE project
2 Copyright (C) 2002 Simon Hausmann <hausmann@kde.org> 2 Copyright (C) 2002 Simon Hausmann <hausmann@kde.org>
3 3
4 This library is free software; you can redistribute it and/or 4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public 5 modify it under the terms of the GNU Library General Public
6 License as published by the Free Software Foundation; either 6 License as published by the Free Software Foundation; either
7 version 2 of the License, or (at your option) any later version. 7 version 2 of the License, or (at your option) any later version.
8 8
9 This library is distributed in the hope that it will be useful, 9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of 10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details. 12 Library General Public License for more details.
13 13
14 You should have received a copy of the GNU Library General Public License 14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to 15 along with this library; see the file COPYING.LIB. If not, write to
16 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 16 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA. 17 Boston, MA 02111-1307, USA.
18*/ 18*/
19 19
20#include "threadutil.h" 20#include "threadutil.h"
21 21
22#include <qsocketnotifier.h> 22#include <qsocketnotifier.h>
23 23
24#include <pthread.h> 24#include <pthread.h>
25#include <assert.h> 25#include <assert.h>
26#include <unistd.h> 26#include <unistd.h>
27#include <errno.h> 27#include <errno.h>
28 28
29using namespace ThreadUtil; 29using namespace ThreadUtil;
30 30
31struct Mutex::Data 31struct Mutex::Data
32{ 32{
33 Data() 33 Data()
34 { 34 {
35 pthread_mutex_init( &mutex, 0 ); 35 pthread_mutex_init( &mutex, 0 );
36 } 36 }
37 ~Data() 37 ~Data()
38 { 38 {
39 pthread_mutex_destroy( &mutex ); 39 pthread_mutex_destroy( &mutex );
40 } 40 }
41 41
42 pthread_mutex_t mutex; 42 pthread_mutex_t mutex;
43}; 43};
44 44
45Mutex::Mutex() 45Mutex::Mutex()
46 : d( new Data ) 46 : d( new Data )
47{ 47{
48} 48}
49 49
50Mutex::~Mutex() 50Mutex::~Mutex()
51{ 51{
52 delete d; 52 delete d;
53} 53}
54 54
55void Mutex::lock() 55void Mutex::lock()
56{ 56{
57 pthread_mutex_lock( &d->mutex ); 57 pthread_mutex_lock( &d->mutex );
58} 58}
59 59
60void Mutex::unlock() 60void Mutex::unlock()
61{ 61{
62 pthread_mutex_unlock( &d->mutex ); 62 pthread_mutex_unlock( &d->mutex );
63} 63}
64 64
65bool Mutex::tryLock() 65bool Mutex::tryLock()
66{ 66{
67 return pthread_mutex_trylock( &d->mutex ) == 0; 67 return pthread_mutex_trylock( &d->mutex ) == 0;
68} 68}
69 69
70bool Mutex::isLocked() 70bool Mutex::isLocked()
71{ 71{
72 if ( !tryLock() ) 72 if ( !tryLock() )
73 return true; 73 return true;
74 74
75 unlock(); 75 unlock();
76 return false; 76 return false;
77} 77}
78 78
79struct WaitCondition::Data 79struct WaitCondition::Data
80{ 80{
81 Data() 81 Data()
82 { 82 {
83 int result = pthread_cond_init( &waitCondition, 0 ); 83 int result = pthread_cond_init( &waitCondition, 0 );
84 assert( result == 0 ); 84 assert( result == 0 );
85 } 85 }
86 ~Data() 86 ~Data()
87 { 87 {
88 pthread_cond_destroy( &waitCondition ); 88 pthread_cond_destroy( &waitCondition );
89 } 89 }
90 90
91 pthread_cond_t waitCondition; 91 pthread_cond_t waitCondition;
92}; 92};
93 93
94WaitCondition::WaitCondition() 94WaitCondition::WaitCondition()
95 : d( new Data ) 95 : d( new Data )
96{ 96{
97} 97}
98 98
99WaitCondition::~WaitCondition() 99WaitCondition::~WaitCondition()
100{ 100{
101 delete d; 101 delete d;
102} 102}
103 103
104bool WaitCondition::wait() 104bool WaitCondition::wait()
105{ 105{
106 Mutex m; 106 Mutex m;
107 m.lock(); 107 m.lock();
108 return wait( m ); 108 return wait( m );
109} 109}
110 110
111bool WaitCondition::wait( Mutex &mutex ) 111bool WaitCondition::wait( Mutex &mutex )
112{ 112{
113 return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex ); 113 return pthread_cond_wait( &d->waitCondition, &mutex.d->mutex );
114} 114}
115 115
116void WaitCondition::wakeOne() 116void WaitCondition::wakeOne()
117{ 117{
118 pthread_cond_signal( &d->waitCondition ); 118 pthread_cond_signal( &d->waitCondition );
119} 119}
120 120
121void WaitCondition::wakeAll() 121void WaitCondition::wakeAll()
122{ 122{
123 pthread_cond_broadcast( &d->waitCondition ); 123 pthread_cond_broadcast( &d->waitCondition );
124} 124}
125 125
126struct Thread::Data 126struct Thread::Data
127{ 127{
128 Data() : isRunning( false ) 128 Data() : isRunning( false )
129 {} 129 {}
130 130
131 pthread_t self; 131 pthread_t self;
132 Mutex guard; 132 Mutex guard;
133 bool isRunning; 133 bool isRunning;
134 134
135 WaitCondition finishCondition; 135 WaitCondition finishCondition;
136 136
137 Thread *thr; 137 Thread *thr;
138 138
139 void run() { thr->run(); } 139 void run() { thr->run(); }
140}; 140};
141 141
142extern "C" 142extern "C"
143{ 143{
144 144
145static void terminate_thread( void *arg ) 145static void terminate_thread( void *arg )
146{ 146{
147 Thread::Data *data = ( Thread::Data* )arg; 147 Thread::Data *data = ( Thread::Data* )arg;
148 148
149 assert( data ); 149 assert( data );
150 150
151 AutoLock locker( data->guard ); 151 AutoLock locker( data->guard );
152 data->isRunning = false; 152 data->isRunning = false;
153 data->finishCondition.wakeAll(); 153 data->finishCondition.wakeAll();
154} 154}
155 155
156static void *start_thread( void *arg ) 156static void *start_thread( void *arg )
157{ 157{
158 Thread::Data *data = ( Thread::Data* )arg; 158 Thread::Data *data = ( Thread::Data* )arg;
159 159
160 pthread_cleanup_push( terminate_thread, data ); 160 pthread_cleanup_push( terminate_thread, data );
161 161
162 data->isRunning = true; 162 data->isRunning = true;
163 data->run(); 163 data->run();
164 164
165 pthread_cleanup_pop( true ); 165 pthread_cleanup_pop( true );
166 166
167 Thread::exit(); 167 Thread::exit();
168 return 0; // never reached 168 return 0; // never reached
169} 169}
170 170
171} 171}
172 172
173Thread::Thread() 173Thread::Thread()
174 : d( new Data ) 174 : d( new Data )
175{ 175{
176 d->thr = this; 176 d->thr = this;
177} 177}
178 178
179Thread::~Thread() 179Thread::~Thread()
180{ 180{
181 assert( d->isRunning == false ); 181 assert( d->isRunning == false );
182 delete d; 182 delete d;
183} 183}
184 184
185void Thread::start() 185void Thread::start()
186{ 186{
187 AutoLock lock( d->guard ); 187 AutoLock lock( d->guard );
188 188
189 if ( d->isRunning ) { 189 if ( d->isRunning ) {
190 qDebug( "ThreadUtil::Thread::start() called for running thread." ); 190 qDebug( "ThreadUtil::Thread::start() called for running thread." );
191 return; 191 return;
192 } 192 }
193 193
194 pthread_attr_t attributes; 194 pthread_attr_t attributes;
195 pthread_attr_init( &attributes ); 195 pthread_attr_init( &attributes );
196 pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM ); 196 pthread_attr_setscope( &attributes, PTHREAD_SCOPE_SYSTEM );
197 int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d ); 197 int err = pthread_create( &d->self, &attributes, start_thread, ( void* )d );
198 if ( err != 0 ) { 198 if ( err != 0 ) {
199 qDebug( "ThreadUtil::Thread::start() : can't create thread: %s", strerror( err ) ); 199 qDebug( "ThreadUtil::Thread::start() : can't create thread: %s", strerror( err ) );
200 pthread_attr_destroy( &attributes ); 200 pthread_attr_destroy( &attributes );
201 return; 201 return;
202 } 202 }
203 pthread_attr_destroy( &attributes ); 203 pthread_attr_destroy( &attributes );
204} 204}
205 205
206void Thread::terminate() 206void Thread::terminate()
207{ 207{
208 AutoLock lock( d->guard ); 208 AutoLock lock( d->guard );
209 if ( !d->isRunning ) 209 if ( !d->isRunning )
210 return; 210 return;
211 211
212 pthread_cancel( d->self ); 212 pthread_cancel( d->self );
213} 213}
214 214
215bool Thread::wait() 215bool Thread::wait()
216{ 216{
217 AutoLock lock( d->guard ); 217 AutoLock lock( d->guard );
218 if ( !d->isRunning ) 218 if ( !d->isRunning )
219 return true; 219 return true;
220 220
221 return d->finishCondition.wait( d->guard ); 221 return d->finishCondition.wait( d->guard );
222} 222}
223 223
224bool Thread::isRunning() const 224bool Thread::isRunning() const
225{ 225{
226 AutoLock lock( d->guard ); 226 AutoLock lock( d->guard );
227 return d->isRunning; 227 return d->isRunning;
228} 228}
229 229
230void Thread::exit() 230void Thread::exit()
231{ 231{
232 pthread_exit( 0 ); 232 pthread_exit( 0 );
233} 233}
234 234
235OnewayNotifier::OnewayNotifier() 235OnewayNotifier::OnewayNotifier()
236{ 236{
237 int fds[ 2 ]; 237 int fds[ 2 ];
238 pipe( fds ); 238 pipe( fds );
239 m_readFd = fds[ 0 ]; 239 m_readFd = fds[ 0 ];
240 m_writeFd = fds[ 1 ]; 240 m_writeFd = fds[ 1 ];
241 241
242 m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read ); 242 m_notifier = new QSocketNotifier( m_readFd, QSocketNotifier::Read );
243 connect( m_notifier, SIGNAL( activated( int ) ), 243 connect( m_notifier, SIGNAL( activated(int) ),
244 this, SLOT( wakeUp() ) ); 244 this, SLOT( wakeUp() ) );
245} 245}
246 246
247OnewayNotifier::~OnewayNotifier() 247OnewayNotifier::~OnewayNotifier()
248{ 248{
249 delete m_notifier; 249 delete m_notifier;
250 250
251 ::close( m_readFd ); 251 ::close( m_readFd );
252 ::close( m_writeFd ); 252 ::close( m_writeFd );
253} 253}
254 254
255void OnewayNotifier::notify() 255void OnewayNotifier::notify()
256{ 256{
257 const char c = 42; 257 const char c = 42;
258 ::write( m_writeFd, &c, 1 ); 258 ::write( m_writeFd, &c, 1 );
259} 259}
260 260
261void OnewayNotifier::wakeUp() 261void OnewayNotifier::wakeUp()
262{ 262{
263 char c = 0; 263 char c = 0;
264 264
265 if ( ::read( m_readFd, &c, 1 ) != 1 ) 265 if ( ::read( m_readFd, &c, 1 ) != 1 )
266 return; 266 return;
267 267
268 emit awake(); 268 emit awake();
269} 269}
270 270
271ChannelMessage::ChannelMessage( int type ) 271ChannelMessage::ChannelMessage( int type )
272 : m_type( type ), m_isCall( false ), m_replied( false ), 272 : m_type( type ), m_isCall( false ), m_replied( false ),
273 m_inEventHandler( false ) 273 m_inEventHandler( false )
274{ 274{
275} 275}
276 276
277ChannelMessage::~ChannelMessage() 277ChannelMessage::~ChannelMessage()
278{ 278{
279 if ( m_guard.isLocked() ) 279 if ( m_guard.isLocked() )
280 m_guard.unlock(); 280 m_guard.unlock();
281} 281}
282 282
283void ChannelMessage::reply() 283void ChannelMessage::reply()
284{ 284{
285 if ( !m_isCall ) 285 if ( !m_isCall )
286 { 286 {
287 qDebug( "ChannelMessage::reply() - can't reply oneway message!" ); 287 qDebug( "ChannelMessage::reply() - can't reply oneway message!" );
288 return; 288 return;
289 } 289 }
290 290
291 if ( m_inEventHandler ) 291 if ( m_inEventHandler )
292 { 292 {
293 m_replied = true; 293 m_replied = true;
294 return; 294 return;
295 } 295 }
296 296
297 m_condition.wakeOne(); 297 m_condition.wakeOne();
298 m_guard.unlock(); 298 m_guard.unlock();
299} 299}
300 300
301struct Channel::Private 301struct Channel::Private
302{ 302{
303 Private() 303 Private()
304 { 304 {
305 ownerThread = pthread_self(); 305 ownerThread = pthread_self();
306 } 306 }
307 307
308 pthread_t ownerThread; 308 pthread_t ownerThread;
309}; 309};
310 310
311Channel::Channel( QObject *parent, const char *name ) 311Channel::Channel( QObject *parent, const char *name )
312 : QObject( parent, name ), d( new Private ) 312 : QObject( parent, name ), d( new Private )
313{ 313{
314 connect( &m_notifier, SIGNAL( awake() ), 314 connect( &m_notifier, SIGNAL( awake() ),
315 this, SLOT( deliver() ) ); 315 this, SLOT( deliver() ) );
316} 316}
317 317
318Channel::~Channel() 318Channel::~Channel()
319{ 319{
320 delete d; 320 delete d;
321} 321}
322 322
323void Channel::send( ChannelMessage *message, SendType type ) 323void Channel::send( ChannelMessage *message, SendType type )
324{ 324{
325 if ( type == WaitForReply ) 325 if ( type == WaitForReply )
326 { 326 {
327 message->m_guard.lock(); 327 message->m_guard.lock();
328 message->m_isCall = true; 328 message->m_isCall = true;
329 } 329 }
330 330
331 m_pendingMessagesGuard.lock(); 331 m_pendingMessagesGuard.lock();
332 m_pendingMessages << MsgEnvelope( type, message ); 332 m_pendingMessages << MsgEnvelope( type, message );
333 m_pendingMessagesGuard.unlock(); 333 m_pendingMessagesGuard.unlock();
334 334
335 if ( d->ownerThread == pthread_self() ) { 335 if ( d->ownerThread == pthread_self() ) {
336 assert( type != WaitForReply ); 336 assert( type != WaitForReply );
337 337
338 deliver(); 338 deliver();
339 } 339 }
340 else 340 else
341 m_notifier.notify(); 341 m_notifier.notify();
342 //QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) ); 342 //QThread::postEvent( this, new QCustomEvent( QEvent::User, envelope ) );
343 343
344 if ( type == WaitForReply ) 344 if ( type == WaitForReply )
345 { 345 {
346 message->m_condition.wait( message->m_guard ); 346 message->m_condition.wait( message->m_guard );
347 message->m_guard.unlock(); 347 message->m_guard.unlock();
348 } 348 }
349} 349}
350 350
351void Channel::deliver() 351void Channel::deliver()
352{ 352{
353 AutoLock lock( m_pendingMessagesGuard ); 353 AutoLock lock( m_pendingMessagesGuard );
354 354
355 while ( !m_pendingMessages.isEmpty() ) { 355 while ( !m_pendingMessages.isEmpty() ) {
356 MsgEnvelope envelope = m_pendingMessages.first(); 356 MsgEnvelope envelope = m_pendingMessages.first();
357 357
358 m_pendingMessages.remove( m_pendingMessages.begin() ); 358 m_pendingMessages.remove( m_pendingMessages.begin() );
359 359
360 m_pendingMessagesGuard.unlock(); 360 m_pendingMessagesGuard.unlock();
361 deliverOne( envelope ); 361 deliverOne( envelope );
362 m_pendingMessagesGuard.lock(); 362 m_pendingMessagesGuard.lock();
363 } 363 }
364} 364}
365 365
366void Channel::deliverOne( const MsgEnvelope &envelope ) 366void Channel::deliverOne( const MsgEnvelope &envelope )
367{ 367{
368 ChannelMessage *msg = envelope.msg; 368 ChannelMessage *msg = envelope.msg;
369 369
370 assert( msg ); 370 assert( msg );
371 371
372 if ( envelope.type == WaitForReply ) 372 if ( envelope.type == WaitForReply )
373 { 373 {
374 msg->m_guard.lock(); 374 msg->m_guard.lock();
375 msg->m_inEventHandler = true; 375 msg->m_inEventHandler = true;
376 } 376 }
377 377
378 receiveMessage( msg, envelope.type ); 378 receiveMessage( msg, envelope.type );
379 379
380 if ( envelope.type == WaitForReply ) 380 if ( envelope.type == WaitForReply )
381 { 381 {
382 msg->m_inEventHandler = false; 382 msg->m_inEventHandler = false;
383 if ( msg->m_replied ) 383 if ( msg->m_replied )
384 { 384 {
385 msg->m_condition.wakeOne(); 385 msg->m_condition.wakeOne();
386 // this is a bit tricky. we unlock only when we reply. 386 // this is a bit tricky. we unlock only when we reply.
387 // reply() does an unlock as well. 387 // reply() does an unlock as well.
388 msg->m_guard.unlock(); 388 msg->m_guard.unlock();
389 } 389 }
390 } 390 }
391} 391}
392 392
393/* vim: et sw=4 ts=4 393/* vim: et sw=4 ts=4
394 */ 394 */
diff --git a/noncore/multimedia/opieplayer2/videowidget.cpp b/noncore/multimedia/opieplayer2/videowidget.cpp
index c829e03..a4d09f5 100644
--- a/noncore/multimedia/opieplayer2/videowidget.cpp
+++ b/noncore/multimedia/opieplayer2/videowidget.cpp
@@ -1,303 +1,303 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org>
5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
7 =. 7 =.
8 .=l. 8 .=l.
9           .>+-= 9           .>+-=
10 _;:,     .>    :=|. This program is free software; you can 10 _;:,     .>    :=|. This program is free software; you can
11.> <`_,   >  .   <= redistribute it and/or modify it under 11.> <`_,   >  .   <= redistribute it and/or modify it under
12:`=1 )Y*s>-.--   : the terms of the GNU General Public 12:`=1 )Y*s>-.--   : the terms of the GNU General Public
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; Library General Public License for more 22..}^=.=       =       ; Library General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = Library General Public License along with 26  -_. . .   )=.  = Library General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34#include "videowidget.h" 34#include "videowidget.h"
35#include "mediaplayerstate.h" 35#include "mediaplayerstate.h"
36#include "playlistwidget.h" 36#include "playlistwidget.h"
37 37
38 38
39#ifdef Q_WS_QWS 39#ifdef Q_WS_QWS
40# define USE_DIRECT_PAINTER 40# define USE_DIRECT_PAINTER
41# include <qdirectpainter_qws.h> 41# include <qdirectpainter_qws.h>
42# include <qgfxraster_qws.h> 42# include <qgfxraster_qws.h>
43#endif 43#endif
44 44
45 45
46namespace 46namespace
47{ 47{
48 48
49const int xo = 2; // movable x offset 49const int xo = 2; // movable x offset
50const int yo = 0; // movable y offset 50const int yo = 0; // movable y offset
51 51
52const MediaWidget::SkinButtonInfo skinInfo[] = 52const MediaWidget::SkinButtonInfo skinInfo[] =
53{ 53{
54 { MediaWidget::Play, "play", MediaWidget::ToggleButton }, 54 { MediaWidget::Play, "play", MediaWidget::ToggleButton },
55 { MediaWidget::Stop, "stop", MediaWidget::NormalButton }, 55 { MediaWidget::Stop, "stop", MediaWidget::NormalButton },
56 { MediaWidget::Next, "fwd", MediaWidget::NormalButton }, 56 { MediaWidget::Next, "fwd", MediaWidget::NormalButton },
57 { MediaWidget::Previous, "back", MediaWidget::NormalButton }, 57 { MediaWidget::Previous, "back", MediaWidget::NormalButton },
58 { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton }, 58 { MediaWidget::VolumeUp, "up", MediaWidget::NormalButton },
59 { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton }, 59 { MediaWidget::VolumeDown, "down", MediaWidget::NormalButton },
60 { MediaWidget::FullScreen, "full", MediaWidget::ToggleButton } 60 { MediaWidget::FullScreen, "full", MediaWidget::ToggleButton }
61}; 61};
62 62
63const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] ); 63const uint buttonCount = sizeof( skinInfo ) / sizeof( skinInfo[ 0 ] );
64 64
65} 65}
66 66
67VideoWidget::VideoWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name ) 67VideoWidget::VideoWidget( PlayListWidget &playList, MediaPlayerState &mediaPlayerState, QWidget* parent, const char* name )
68 : MediaWidget( playList, mediaPlayerState, parent, name ), scaledWidth( 0 ), scaledHeight( 0 ), videoSliderBeingMoved( false ) 68 : MediaWidget( playList, mediaPlayerState, parent, name ), scaledWidth( 0 ), scaledHeight( 0 ), videoSliderBeingMoved( false )
69{ 69{
70 setCaption( tr("OpiePlayer - Video") ); 70 setCaption( tr("OpiePlayer - Video") );
71 71
72 videoFrame = new XineVideoWidget ( this, "Video frame" ); 72 videoFrame = new XineVideoWidget ( this, "Video frame" );
73 73
74 connect ( videoFrame, SIGNAL( videoResized ( const QSize & )), this, SIGNAL( videoResized ( const QSize & ))); 74 connect ( videoFrame, SIGNAL( videoResized(const QSize&)), this, SIGNAL( videoResized(const QSize&)));
75 connect ( videoFrame, SIGNAL( clicked () ), this, SLOT ( backToNormal() ) ); 75 connect ( videoFrame, SIGNAL( clicked() ), this, SLOT ( backToNormal() ) );
76 76
77 slider = 0; 77 slider = 0;
78 78
79 loadSkin(); 79 loadSkin();
80 80
81 setLength( mediaPlayerState.length() ); 81 setLength( mediaPlayerState.length() );
82 setPosition( mediaPlayerState.position() ); 82 setPosition( mediaPlayerState.position() );
83 setFullscreen( mediaPlayerState.isFullscreen() ); 83 setFullscreen( mediaPlayerState.isFullscreen() );
84 setPlaying( mediaPlayerState.isPlaying() ); 84 setPlaying( mediaPlayerState.isPlaying() );
85} 85}
86 86
87 87
88VideoWidget::~VideoWidget() 88VideoWidget::~VideoWidget()
89{ 89{
90} 90}
91 91
92MediaWidget::GUIInfo VideoWidget::guiInfo() 92MediaWidget::GUIInfo VideoWidget::guiInfo()
93{ 93{
94 return GUIInfo( "V" /* infix */, ::skinInfo, ::buttonCount ); 94 return GUIInfo( "V" /* infix */, ::skinInfo, ::buttonCount );
95} 95}
96 96
97void VideoWidget::resizeEvent( QResizeEvent *e ) { 97void VideoWidget::resizeEvent( QResizeEvent *e ) {
98 int h = height(); 98 int h = height();
99 int w = width(); 99 int w = width();
100 //int Vh = 160; 100 //int Vh = 160;
101 //int Vw = 220; 101 //int Vw = 220;
102 102
103 slider->setFixedWidth( w - 20 ); 103 slider->setFixedWidth( w - 20 );
104 slider->setGeometry( QRect( 15, h - 22, w - 90, 20 ) ); 104 slider->setGeometry( QRect( 15, h - 22, w - 90, 20 ) );
105 slider->setBackgroundOrigin( QWidget::ParentOrigin ); 105 slider->setBackgroundOrigin( QWidget::ParentOrigin );
106 slider->setFocusPolicy( QWidget::NoFocus ); 106 slider->setFocusPolicy( QWidget::NoFocus );
107 slider->setBackgroundPixmap( backgroundPixmap ); 107 slider->setBackgroundPixmap( backgroundPixmap );
108 108
109 upperLeftOfButtonMask.rx() = 0;// ( imgUp->width() ) / 2; 109 upperLeftOfButtonMask.rx() = 0;// ( imgUp->width() ) / 2;
110 if(w>h) 110 if(w>h)
111 upperLeftOfButtonMask.ry() = 0; 111 upperLeftOfButtonMask.ry() = 0;
112 else 112 else
113 upperLeftOfButtonMask.ry() = 185;//(( Vh - imgUp->height() ) / 2) - 10; 113 upperLeftOfButtonMask.ry() = 185;//(( Vh - imgUp->height() ) / 2) - 10;
114 114
115 MediaWidget::resizeEvent( e ); 115 MediaWidget::resizeEvent( e );
116} 116}
117 117
118void VideoWidget::sliderPressed() { 118void VideoWidget::sliderPressed() {
119 videoSliderBeingMoved = TRUE; 119 videoSliderBeingMoved = TRUE;
120} 120}
121 121
122void VideoWidget::sliderReleased() { 122void VideoWidget::sliderReleased() {
123 videoSliderBeingMoved = FALSE; 123 videoSliderBeingMoved = FALSE;
124 if ( slider->width() == 0 ) { 124 if ( slider->width() == 0 ) {
125 return; 125 return;
126 } 126 }
127 long val = long((double)slider->value() * mediaPlayerState.length() / slider->width()); 127 long val = long((double)slider->value() * mediaPlayerState.length() / slider->width());
128 mediaPlayerState.setPosition( val ); 128 mediaPlayerState.setPosition( val );
129} 129}
130 130
131void VideoWidget::setPosition( long i ) { 131void VideoWidget::setPosition( long i ) {
132 updateSlider( i, mediaPlayerState.length() ); 132 updateSlider( i, mediaPlayerState.length() );
133} 133}
134 134
135 135
136void VideoWidget::setLength( long max ) { 136void VideoWidget::setLength( long max ) {
137 updateSlider( mediaPlayerState.position(), max ); 137 updateSlider( mediaPlayerState.position(), max );
138} 138}
139 139
140void VideoWidget::setDisplayType( MediaPlayerState::DisplayType displayType ) 140void VideoWidget::setDisplayType( MediaPlayerState::DisplayType displayType )
141{ 141{
142 if ( displayType == MediaPlayerState::Video ) { 142 if ( displayType == MediaPlayerState::Video ) {
143 makeVisible(); 143 makeVisible();
144 return; 144 return;
145 } 145 }
146 146
147 // Effectively blank the view next time we show it so it looks nicer 147 // Effectively blank the view next time we show it so it looks nicer
148 scaledWidth = 0; 148 scaledWidth = 0;
149 scaledHeight = 0; 149 scaledHeight = 0;
150 hide(); 150 hide();
151} 151}
152 152
153void VideoWidget::loadSkin() 153void VideoWidget::loadSkin()
154{ 154{
155 loadDefaultSkin( guiInfo() ); 155 loadDefaultSkin( guiInfo() );
156 156
157 delete slider; 157 delete slider;
158 slider = new QSlider( Qt::Horizontal, this ); 158 slider = new QSlider( Qt::Horizontal, this );
159 slider->setMinValue( 0 ); 159 slider->setMinValue( 0 );
160 slider->setMaxValue( 1 ); 160 slider->setMaxValue( 1 );
161 slider->setBackgroundPixmap( backgroundPixmap ); 161 slider->setBackgroundPixmap( backgroundPixmap );
162 //slider->setFocusPolicy( QWidget::NoFocus ); 162 //slider->setFocusPolicy( QWidget::NoFocus );
163 163
164 resizeEvent( 0 ); 164 resizeEvent( 0 );
165} 165}
166 166
167void VideoWidget::updateSlider( long i, long max ) { 167void VideoWidget::updateSlider( long i, long max ) {
168 // Will flicker too much if we don't do this 168 // Will flicker too much if we don't do this
169 if ( max == 0 ) { 169 if ( max == 0 ) {
170 return; 170 return;
171 } 171 }
172 int width = slider->width(); 172 int width = slider->width();
173 int val = int((double)i * width / max); 173 int val = int((double)i * width / max);
174 if ( !mediaPlayerState.isFullscreen() && !videoSliderBeingMoved ) { 174 if ( !mediaPlayerState.isFullscreen() && !videoSliderBeingMoved ) {
175 if ( slider->value() != val ) { 175 if ( slider->value() != val ) {
176 slider->setValue( val ); 176 slider->setValue( val );
177 } 177 }
178 if ( slider->maxValue() != width ) { 178 if ( slider->maxValue() != width ) {
179 slider->setMaxValue( width ); 179 slider->setMaxValue( width );
180 } 180 }
181 } 181 }
182} 182}
183 183
184void VideoWidget::mouseReleaseEvent( QMouseEvent *event ) { 184void VideoWidget::mouseReleaseEvent( QMouseEvent *event ) {
185 if ( mediaPlayerState.isFullscreen() ) { 185 if ( mediaPlayerState.isFullscreen() ) {
186 mediaPlayerState.setFullscreen( FALSE ); 186 mediaPlayerState.setFullscreen( FALSE );
187 makeVisible(); 187 makeVisible();
188 } 188 }
189 MediaWidget::mouseReleaseEvent( event ); 189 MediaWidget::mouseReleaseEvent( event );
190} 190}
191 191
192void VideoWidget::backToNormal() { 192void VideoWidget::backToNormal() {
193 mediaPlayerState.setFullscreen( FALSE ); 193 mediaPlayerState.setFullscreen( FALSE );
194 makeVisible(); 194 makeVisible();
195 setToggleButton( FullScreen, false ); 195 setToggleButton( FullScreen, false );
196} 196}
197 197
198void VideoWidget::makeVisible() { 198void VideoWidget::makeVisible() {
199 if ( mediaPlayerState.isFullscreen() ) { 199 if ( mediaPlayerState.isFullscreen() ) {
200 showFullScreen(); 200 showFullScreen();
201 resize( qApp->desktop()->size() ); 201 resize( qApp->desktop()->size() );
202 videoFrame-> setGeometry ( 0, 0, width ( ), height ( )); 202 videoFrame-> setGeometry ( 0, 0, width ( ), height ( ));
203 203
204 slider->hide(); 204 slider->hide();
205 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 205 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
206 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 206 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
207 disconnect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 207 disconnect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
208 disconnect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 208 disconnect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
209 209
210 } else { 210 } else {
211 showNormal(); 211 showNormal();
212 showMaximized(); 212 showMaximized();
213 QWidget *d = QApplication::desktop(); 213 QWidget *d = QApplication::desktop();
214 int w = d->width(); 214 int w = d->width();
215 int h = d->height(); 215 int h = d->height();
216 216
217 if(w>h) { 217 if(w>h) {
218 int newW=(w/2)-(246/2); //this will only work with 320x240 218 int newW=(w/2)-(246/2); //this will only work with 320x240
219 videoFrame->setGeometry( QRect( newW, 4, 240, 170 ) ); 219 videoFrame->setGeometry( QRect( newW, 4, 240, 170 ) );
220 } else { 220 } else {
221 videoFrame->setGeometry( QRect( 0, 30, 240, 170 ) ); 221 videoFrame->setGeometry( QRect( 0, 30, 240, 170 ) );
222 } 222 }
223 223
224 if ( !mediaPlayerState.isSeekable() ) { 224 if ( !mediaPlayerState.isSeekable() ) {
225 if( !slider->isHidden()) { 225 if( !slider->isHidden()) {
226 slider->hide(); 226 slider->hide();
227 } 227 }
228 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 228 disconnect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
229 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 229 disconnect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
230 disconnect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 230 disconnect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
231 disconnect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 231 disconnect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
232 } else { 232 } else {
233 slider->show(); 233 slider->show();
234 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) ); 234 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ),this, SLOT( setPosition(long) ) );
235 connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) ); 235 connect( &mediaPlayerState, SIGNAL( positionUpdated(long) ),this, SLOT( setPosition(long) ) );
236 connect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) ); 236 connect( slider, SIGNAL( sliderPressed() ), this, SLOT( sliderPressed() ) );
237 connect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) ); 237 connect( slider, SIGNAL( sliderReleased() ), this, SLOT( sliderReleased() ) );
238 } 238 }
239 } 239 }
240} 240}
241 241
242void VideoWidget::keyReleaseEvent( QKeyEvent *e) { 242void VideoWidget::keyReleaseEvent( QKeyEvent *e) {
243 switch ( e->key() ) { 243 switch ( e->key() ) {
244////////////////////////////// Zaurus keys 244////////////////////////////// Zaurus keys
245 case Key_Home: 245 case Key_Home:
246 break; 246 break;
247 case Key_F9: //activity 247 case Key_F9: //activity
248 break; 248 break;
249 case Key_F10: //contacts 249 case Key_F10: //contacts
250// hide(); 250// hide();
251 break; 251 break;
252 case Key_F11: //menu 252 case Key_F11: //menu
253 break; 253 break;
254 case Key_F12: //home 254 case Key_F12: //home
255 break; 255 break;
256 case Key_F13: //mail 256 case Key_F13: //mail
257 break; 257 break;
258 case Key_Space: { 258 case Key_Space: {
259 if(mediaPlayerState.isPlaying()) { 259 if(mediaPlayerState.isPlaying()) {
260 mediaPlayerState.setPlaying(FALSE); 260 mediaPlayerState.setPlaying(FALSE);
261 } else { 261 } else {
262 mediaPlayerState.setPlaying(TRUE); 262 mediaPlayerState.setPlaying(TRUE);
263 } 263 }
264 } 264 }
265 break; 265 break;
266 case Key_Down: 266 case Key_Down:
267// toggleButton(6); 267// toggleButton(6);
268 emit lessClicked(); 268 emit lessClicked();
269 emit lessReleased(); 269 emit lessReleased();
270// toggleButton(6); 270// toggleButton(6);
271 break; 271 break;
272 case Key_Up: 272 case Key_Up:
273// toggleButton(5); 273// toggleButton(5);
274 emit moreClicked(); 274 emit moreClicked();
275 emit moreReleased(); 275 emit moreReleased();
276// toggleButton(5); 276// toggleButton(5);
277 break; 277 break;
278 case Key_Right: 278 case Key_Right:
279 mediaPlayerState.setNext(); 279 mediaPlayerState.setNext();
280 break; 280 break;
281 case Key_Left: 281 case Key_Left:
282 mediaPlayerState.setPrev(); 282 mediaPlayerState.setPrev();
283 break; 283 break;
284 case Key_Escape: 284 case Key_Escape:
285 break; 285 break;
286 286
287 }; 287 };
288} 288}
289 289
290XineVideoWidget* VideoWidget::vidWidget() { 290XineVideoWidget* VideoWidget::vidWidget() {
291 return videoFrame; 291 return videoFrame;
292} 292}
293 293
294 294
295void VideoWidget::setFullscreen ( bool b ) { 295void VideoWidget::setFullscreen ( bool b ) {
296 setToggleButton( FullScreen, b ); 296 setToggleButton( FullScreen, b );
297} 297}
298 298
299 299
300void VideoWidget::setPlaying( bool b) { 300void VideoWidget::setPlaying( bool b) {
301 setToggleButton( Play, b ); 301 setToggleButton( Play, b );
302} 302}
303 303
diff --git a/noncore/multimedia/opieplayer2/xinecontrol.cpp b/noncore/multimedia/opieplayer2/xinecontrol.cpp
index a392f4a..70f2ffd 100644
--- a/noncore/multimedia/opieplayer2/xinecontrol.cpp
+++ b/noncore/multimedia/opieplayer2/xinecontrol.cpp
@@ -1,272 +1,272 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org> 4              Copyright (c) 2002 Max Reiss <harlekin@handhelds.org>
5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com> 5 Copyright (c) 2002 L. Potter <ljp@llornkcor.com>
6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 6 Copyright (c) 2002 Holger Freyther <zecke@handhelds.org>
7 =. 7 =.
8 .=l. 8 .=l.
9           .>+-= 9           .>+-=
10 _;:,     .>    :=|. This program is free software; you can 10 _;:,     .>    :=|. This program is free software; you can
11.> <`_,   >  .   <= redistribute it and/or modify it under 11.> <`_,   >  .   <= redistribute it and/or modify it under
12:`=1 )Y*s>-.--   : the terms of the GNU General Public 12:`=1 )Y*s>-.--   : the terms of the GNU General Public
13.="- .-=="i,     .._ License as published by the Free Software 13.="- .-=="i,     .._ License as published by the Free Software
14 - .   .-<_>     .<> Foundation; either version 2 of the License, 14 - .   .-<_>     .<> Foundation; either version 2 of the License,
15     ._= =}       : or (at your option) any later version. 15     ._= =}       : or (at your option) any later version.
16    .%`+i>       _;_. 16    .%`+i>       _;_.
17    .i_,=:_.      -<s. This program is distributed in the hope that 17    .i_,=:_.      -<s. This program is distributed in the hope that
18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 18     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
19    : ..    .:,     . . . without even the implied warranty of 19    : ..    .:,     . . . without even the implied warranty of
20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 20    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 21  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
22..}^=.=       =       ; General Public License for more 22..}^=.=       =       ; General Public License for more
23++=   -.     .`     .: details. 23++=   -.     .`     .: details.
24 :     =  ...= . :.=- 24 :     =  ...= . :.=-
25 -.   .:....=;==+<; You should have received a copy of the GNU 25 -.   .:....=;==+<; You should have received a copy of the GNU
26  -_. . .   )=.  = General Public License along with 26  -_. . .   )=.  = General Public License along with
27    --        :-=` this library; see the file COPYING.LIB. 27    --        :-=` this library; see the file COPYING.LIB.
28 If not, write to the Free Software Foundation, 28 If not, write to the Free Software Foundation,
29 Inc., 59 Temple Place - Suite 330, 29 Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. 30 Boston, MA 02111-1307, USA.
31 31
32*/ 32*/
33 33
34 34
35#include <qtimer.h> 35#include <qtimer.h>
36#include <qmessagebox.h> 36#include <qmessagebox.h>
37#include <qpe/qcopenvelope_qws.h> 37#include <qpe/qcopenvelope_qws.h>
38#include <qpe/qpeapplication.h> 38#include <qpe/qpeapplication.h>
39 39
40#include "xinecontrol.h" 40#include "xinecontrol.h"
41#include "mediaplayerstate.h" 41#include "mediaplayerstate.h"
42#include "xinevideowidget.h" 42#include "xinevideowidget.h"
43 43
44XineControl::XineControl( XineVideoWidget *xineWidget, 44XineControl::XineControl( XineVideoWidget *xineWidget,
45 MediaPlayerState &_mediaPlayerState, 45 MediaPlayerState &_mediaPlayerState,
46 QObject *parent, const char *name ) 46 QObject *parent, const char *name )
47 : QObject( parent, name ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget ) 47 : QObject( parent, name ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget )
48{ 48{
49 libXine = new XINE::Lib( XINE::Lib::InitializeImmediately, xineWidget ); 49 libXine = new XINE::Lib( XINE::Lib::InitializeImmediately, xineWidget );
50 50
51 init(); 51 init();
52} 52}
53 53
54XineControl::XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget, 54XineControl::XineControl( XINE::Lib *xine, XineVideoWidget *xineWidget,
55 MediaPlayerState &_mediaPlayerState, 55 MediaPlayerState &_mediaPlayerState,
56 QObject *parent, const char *name ) 56 QObject *parent, const char *name )
57 : QObject( parent, name ), libXine( xine ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget ) 57 : QObject( parent, name ), libXine( xine ), mediaPlayerState( _mediaPlayerState ), xineVideoWidget( xineWidget )
58{ 58{
59 xine->ensureInitialized(); 59 xine->ensureInitialized();
60 60
61 xine->setWidget( xineWidget ); 61 xine->setWidget( xineWidget );
62 62
63 init(); 63 init();
64} 64}
65 65
66void XineControl::init() 66void XineControl::init()
67{ 67{
68 connect( &mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( pause( bool ) ) ); 68 connect( &mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pause(bool) ) );
69 connect( this, SIGNAL( positionChanged( long ) ), &mediaPlayerState, SLOT( updatePosition( long ) ) ); 69 connect( this, SIGNAL( positionChanged(long) ), &mediaPlayerState, SLOT( updatePosition(long) ) );
70 connect( &mediaPlayerState, SIGNAL( playingToggled( bool ) ), this, SLOT( stop( bool ) ) ); 70 connect( &mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( stop(bool) ) );
71 connect( &mediaPlayerState, SIGNAL( fullscreenToggled( bool ) ), this, SLOT( setFullscreen( bool ) ) ); 71 connect( &mediaPlayerState, SIGNAL( fullscreenToggled(bool) ), this, SLOT( setFullscreen(bool) ) );
72 connect( &mediaPlayerState, SIGNAL( positionChanged( long ) ), this, SLOT( seekTo( long ) ) ); 72 connect( &mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( seekTo(long) ) );
73 connect( &mediaPlayerState, SIGNAL( videoGammaChanged( int ) ), this, SLOT( setGamma( int ) ) ); 73 connect( &mediaPlayerState, SIGNAL( videoGammaChanged(int) ), this, SLOT( setGamma(int) ) );
74 connect( libXine, SIGNAL( stopped() ), this, SLOT( nextMedia() ) ); 74 connect( libXine, SIGNAL( stopped() ), this, SLOT( nextMedia() ) );
75 connect( xineVideoWidget, SIGNAL( videoResized( const QSize & ) ), this, SLOT( videoResized ( const QSize & ) ) ); 75 connect( xineVideoWidget, SIGNAL( videoResized(const QSize&) ), this, SLOT( videoResized(const QSize&) ) );
76 76
77 disabledSuspendScreenSaver = FALSE; 77 disabledSuspendScreenSaver = FALSE;
78} 78}
79 79
80XineControl::~XineControl() { 80XineControl::~XineControl() {
81#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 81#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
82 if ( disabledSuspendScreenSaver ) { 82 if ( disabledSuspendScreenSaver ) {
83 disabledSuspendScreenSaver = FALSE; 83 disabledSuspendScreenSaver = FALSE;
84 // Re-enable the suspend mode 84 // Re-enable the suspend mode
85 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 85 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
86 } 86 }
87#endif 87#endif
88 delete libXine; 88 delete libXine;
89} 89}
90 90
91void XineControl::play( const QString& fileName ) { 91void XineControl::play( const QString& fileName ) {
92 92
93 hasVideoChannel = FALSE; 93 hasVideoChannel = FALSE;
94 hasAudioChannel = FALSE; 94 hasAudioChannel = FALSE;
95 m_fileName = fileName; 95 m_fileName = fileName;
96 96
97 qDebug("<<FILENAME: " + fileName + ">>>>"); 97 qDebug("<<FILENAME: " + fileName + ">>>>");
98 98
99 if ( !libXine->play( fileName, 0, 0 ) ) { 99 if ( !libXine->play( fileName, 0, 0 ) ) {
100 QMessageBox::warning( 0l , tr( "Failure" ), getErrorCode() ); 100 QMessageBox::warning( 0l , tr( "Failure" ), getErrorCode() );
101 // toggle stop so the the play button is reset 101 // toggle stop so the the play button is reset
102 mediaPlayerState.setPlaying( false ); 102 mediaPlayerState.setPlaying( false );
103 return; 103 return;
104 } 104 }
105 mediaPlayerState.setPlaying( true ); 105 mediaPlayerState.setPlaying( true );
106 106
107 MediaPlayerState::DisplayType displayType; 107 MediaPlayerState::DisplayType displayType;
108 if ( !libXine->hasVideo() ) { 108 if ( !libXine->hasVideo() ) {
109 displayType = MediaPlayerState::Audio; 109 displayType = MediaPlayerState::Audio;
110 qDebug("HAS AUDIO"); 110 qDebug("HAS AUDIO");
111 libXine->setShowVideo( false ); 111 libXine->setShowVideo( false );
112 hasAudioChannel = TRUE; 112 hasAudioChannel = TRUE;
113 } else { 113 } else {
114 displayType = MediaPlayerState::Video; 114 displayType = MediaPlayerState::Video;
115 qDebug("HAS VIDEO"); 115 qDebug("HAS VIDEO");
116 libXine->setShowVideo( true ); 116 libXine->setShowVideo( true );
117 hasVideoChannel = TRUE; 117 hasVideoChannel = TRUE;
118 } 118 }
119 // determine if slider is shown 119 // determine if slider is shown
120 mediaPlayerState.setIsSeekable( libXine->isSeekable() ); 120 mediaPlayerState.setIsSeekable( libXine->isSeekable() );
121 121
122 // which gui (video / audio) 122 // which gui (video / audio)
123 mediaPlayerState.setDisplayType( displayType ); 123 mediaPlayerState.setDisplayType( displayType );
124 124
125#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 125#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
126 if ( !disabledSuspendScreenSaver ) { 126 if ( !disabledSuspendScreenSaver ) {
127 disabledSuspendScreenSaver = TRUE; 127 disabledSuspendScreenSaver = TRUE;
128 // Stop the screen from blanking and power saving state 128 // Stop the screen from blanking and power saving state
129 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) 129 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" )
130 << ( displayType == MediaPlayerState::Video ? QPEApplication::Disable : QPEApplication::DisableSuspend ); 130 << ( displayType == MediaPlayerState::Video ? QPEApplication::Disable : QPEApplication::DisableSuspend );
131 } 131 }
132#endif 132#endif
133 133
134 length(); 134 length();
135 position(); 135 position();
136} 136}
137 137
138void XineControl::nextMedia() { 138void XineControl::nextMedia() {
139 mediaPlayerState.setNext(); 139 mediaPlayerState.setNext();
140} 140}
141 141
142void XineControl::setGamma( int value ) { 142void XineControl::setGamma( int value ) {
143 libXine->setGamma( value ); 143 libXine->setGamma( value );
144} 144}
145 145
146void XineControl::stop( bool isSet ) { 146void XineControl::stop( bool isSet ) {
147 if ( !isSet ) { 147 if ( !isSet ) {
148 libXine->stop(); 148 libXine->stop();
149 149
150#if defined(Q_WS_QWS) && !defined(QT_NO_COP) 150#if defined(Q_WS_QWS) && !defined(QT_NO_COP)
151 if ( disabledSuspendScreenSaver ) { 151 if ( disabledSuspendScreenSaver ) {
152 disabledSuspendScreenSaver = FALSE; 152 disabledSuspendScreenSaver = FALSE;
153 // Re-enable the suspend mode 153 // Re-enable the suspend mode
154 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 154 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
155 } 155 }
156#endif 156#endif
157 } 157 }
158} 158}
159 159
160/** 160/**
161 * Pause playback 161 * Pause playback
162 * @isSet 162 * @isSet
163 */ 163 */
164void XineControl::pause( bool isSet) { 164void XineControl::pause( bool isSet) {
165 libXine->pause( isSet ); 165 libXine->pause( isSet );
166} 166}
167 167
168 168
169/** 169/**
170 * get current time in playback 170 * get current time in playback
171 */ 171 */
172long XineControl::currentTime() { 172long XineControl::currentTime() {
173 // todo: jede sekunde überprüfen 173 // todo: jede sekunde überprüfen
174 m_currentTime = libXine->currentTime(); 174 m_currentTime = libXine->currentTime();
175 return m_currentTime; 175 return m_currentTime;
176 QTimer::singleShot( 1000, this, SLOT( currentTime() ) ); 176 QTimer::singleShot( 1000, this, SLOT( currentTime() ) );
177} 177}
178 178
179/** 179/**
180 * Set the length of the media file 180 * Set the length of the media file
181 */ 181 */
182void XineControl::length() { 182void XineControl::length() {
183 m_length = libXine->length(); 183 m_length = libXine->length();
184 mediaPlayerState.setLength( m_length ); 184 mediaPlayerState.setLength( m_length );
185} 185}
186 186
187 187
188/** 188/**
189 * Reports the position the xine backend is at right now 189 * Reports the position the xine backend is at right now
190 * @return long the postion in seconds 190 * @return long the postion in seconds
191 */ 191 */
192long XineControl::position() { 192long XineControl::position() {
193 m_position = ( currentTime() ); 193 m_position = ( currentTime() );
194 mediaPlayerState.updatePosition( m_position ); 194 mediaPlayerState.updatePosition( m_position );
195 long emitPos = (long)m_position; 195 long emitPos = (long)m_position;
196 emit positionChanged( emitPos ); 196 emit positionChanged( emitPos );
197 if( mediaPlayerState.isPlaying() ) { 197 if( mediaPlayerState.isPlaying() ) {
198 // needs to be stopped the media is stopped 198 // needs to be stopped the media is stopped
199 QTimer::singleShot( 1000, this, SLOT( position() ) ); 199 QTimer::singleShot( 1000, this, SLOT( position() ) );
200 } 200 }
201 return m_position; 201 return m_position;
202} 202}
203 203
204/** 204/**
205 * Set videoplayback to fullscreen 205 * Set videoplayback to fullscreen
206 * @param isSet 206 * @param isSet
207 */ 207 */
208void XineControl::setFullscreen( bool isSet ) { 208void XineControl::setFullscreen( bool isSet ) {
209 libXine->showVideoFullScreen( isSet ); 209 libXine->showVideoFullScreen( isSet );
210} 210}
211 211
212 212
213QString XineControl::getMetaInfo() { 213QString XineControl::getMetaInfo() {
214 214
215 QString returnString; 215 QString returnString;
216 216
217 if ( !libXine->metaInfo( 0 ).isEmpty() ) { 217 if ( !libXine->metaInfo( 0 ).isEmpty() ) {
218 returnString += tr( " Title: " + libXine->metaInfo( 0 ) ); 218 returnString += tr( " Title: " + libXine->metaInfo( 0 ) );
219 } 219 }
220 220
221 if ( !libXine->metaInfo( 1 ).isEmpty() ) { 221 if ( !libXine->metaInfo( 1 ).isEmpty() ) {
222 returnString += tr( " Comment: " + libXine->metaInfo( 1 ) ); 222 returnString += tr( " Comment: " + libXine->metaInfo( 1 ) );
223 } 223 }
224 224
225 if ( !libXine->metaInfo( 2 ).isEmpty() ) { 225 if ( !libXine->metaInfo( 2 ).isEmpty() ) {
226 returnString += tr( " Artist: " + libXine->metaInfo( 2 ) ); 226 returnString += tr( " Artist: " + libXine->metaInfo( 2 ) );
227 } 227 }
228 228
229 if ( !libXine->metaInfo( 3 ).isEmpty() ) { 229 if ( !libXine->metaInfo( 3 ).isEmpty() ) {
230 returnString += tr( " Genre: " + libXine->metaInfo( 3 ) ); 230 returnString += tr( " Genre: " + libXine->metaInfo( 3 ) );
231 } 231 }
232 232
233 if ( !libXine->metaInfo( 4 ).isEmpty() ) { 233 if ( !libXine->metaInfo( 4 ).isEmpty() ) {
234 returnString += tr( " Album: " + libXine->metaInfo( 4 ) ); 234 returnString += tr( " Album: " + libXine->metaInfo( 4 ) );
235 } 235 }
236 236
237 if ( !libXine->metaInfo( 5 ).isEmpty() ) { 237 if ( !libXine->metaInfo( 5 ).isEmpty() ) {
238 returnString += tr( " Year: " + libXine->metaInfo( 5 ) ); 238 returnString += tr( " Year: " + libXine->metaInfo( 5 ) );
239 } 239 }
240 return returnString; 240 return returnString;
241} 241}
242 242
243QString XineControl::getErrorCode() { 243QString XineControl::getErrorCode() {
244 244
245 int errorCode = libXine->error(); 245 int errorCode = libXine->error();
246 246
247 qDebug( QString("ERRORCODE: %1 ").arg(errorCode) ); 247 qDebug( QString("ERRORCODE: %1 ").arg(errorCode) );
248 248
249 if ( errorCode == 1 ) { 249 if ( errorCode == 1 ) {
250 return tr( "No input plugin found for this media type" ); 250 return tr( "No input plugin found for this media type" );
251 } else if ( errorCode == 2 ) { 251 } else if ( errorCode == 2 ) {
252 return tr( "No demux plugin found for this media type" ); 252 return tr( "No demux plugin found for this media type" );
253 } else if ( errorCode == 3 ) { 253 } else if ( errorCode == 3 ) {
254 return tr( "Demuxing failed for this media type" ); 254 return tr( "Demuxing failed for this media type" );
255 } else if ( errorCode == 4 ) { 255 } else if ( errorCode == 4 ) {
256 return tr( "Malformed MRL" ); 256 return tr( "Malformed MRL" );
257 } else { 257 } else {
258 return tr( "Some other error" ); 258 return tr( "Some other error" );
259 } 259 }
260} 260}
261 261
262/** 262/**
263 * Seek to a position in the track 263 * Seek to a position in the track
264 * @param second the second to jump to 264 * @param second the second to jump to
265 */ 265 */
266void XineControl::seekTo( long second ) { 266void XineControl::seekTo( long second ) {
267 libXine->seekTo( (int)second ); 267 libXine->seekTo( (int)second );
268} 268}
269 269
270void XineControl::videoResized ( const QSize &s ) { 270void XineControl::videoResized ( const QSize &s ) {
271 libXine->resize( s ); 271 libXine->resize( s );
272} 272}
diff --git a/noncore/multimedia/opierec/qtrec.cpp b/noncore/multimedia/opierec/qtrec.cpp
index 0a6e5ae..f2035ef 100644
--- a/noncore/multimedia/opierec/qtrec.cpp
+++ b/noncore/multimedia/opierec/qtrec.cpp
@@ -1,2133 +1,2133 @@
1/**************************************************************************** 1/****************************************************************************
2 // qtrec.cpp 2 // qtrec.cpp
3 Created: Thu Jan 17 11:19:58 2002 3 Created: Thu Jan 17 11:19:58 2002
4 copyright 2002 by L.J. Potter <ljp@llornkcor.com> 4 copyright 2002 by L.J. Potter <ljp@llornkcor.com>
5****************************************************************************/ 5****************************************************************************/
6#define DEV_VERSION 6#define DEV_VERSION
7 7
8#include "pixmaps.h" 8#include "pixmaps.h"
9#include "qtrec.h" 9#include "qtrec.h"
10#include "waveform.h" 10#include "waveform.h"
11#include "device.h" 11#include "device.h"
12 12
13#include <pthread.h> 13#include <pthread.h>
14 14
15extern "C" { 15extern "C" {
16#include "adpcm.h" 16#include "adpcm.h"
17} 17}
18 18
19#include <sys/soundcard.h> 19#include <sys/soundcard.h>
20 20
21#include <qpe/config.h> 21#include <qpe/config.h>
22#include <qpe/qcopenvelope_qws.h> 22#include <qpe/qcopenvelope_qws.h>
23#include <qpe/qpeapplication.h> 23#include <qpe/qpeapplication.h>
24#include <qpe/resource.h> 24#include <qpe/resource.h>
25#include <qpe/storage.h> 25#include <qpe/storage.h>
26 26
27#include <qcheckbox.h> 27#include <qcheckbox.h>
28#include <qcombobox.h> 28#include <qcombobox.h>
29//#include <qdatetime.h> 29//#include <qdatetime.h>
30#include <qdir.h> 30#include <qdir.h>
31#include <qgroupbox.h> 31#include <qgroupbox.h>
32#include <qlabel.h> 32#include <qlabel.h>
33#include <qlayout.h> 33#include <qlayout.h>
34#include <qlistview.h> 34#include <qlistview.h>
35#include <qmessagebox.h> 35#include <qmessagebox.h>
36#include <qpopupmenu.h> 36#include <qpopupmenu.h>
37#include <qpushbutton.h> 37#include <qpushbutton.h>
38#include <qslider.h> 38#include <qslider.h>
39#include <qtabwidget.h> 39#include <qtabwidget.h>
40#include <qtimer.h> 40#include <qtimer.h>
41 41
42#include <errno.h> 42#include <errno.h>
43#include <fcntl.h> 43#include <fcntl.h>
44#include <math.h> 44#include <math.h>
45#include <mntent.h> 45#include <mntent.h>
46#include <stdio.h> 46#include <stdio.h>
47#include <stdlib.h> 47#include <stdlib.h>
48#include <sys/ioctl.h> 48#include <sys/ioctl.h>
49#include <sys/soundcard.h> 49#include <sys/soundcard.h>
50#include <sys/stat.h> 50#include <sys/stat.h>
51#include <sys/time.h> 51#include <sys/time.h>
52#include <sys/types.h> 52#include <sys/types.h>
53#include <sys/vfs.h> 53#include <sys/vfs.h>
54#include <unistd.h> 54#include <unistd.h>
55#include <sys/wait.h> 55#include <sys/wait.h>
56#include <sys/signal.h> 56#include <sys/signal.h>
57 57
58 58
59#ifdef PDAUDIO //ALSA 59#ifdef PDAUDIO //ALSA
60#include <alsa/asoundlib.h> 60#include <alsa/asoundlib.h>
61static int deviceSampleRates[8] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, -1 }; 61static int deviceSampleRates[8] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, -1 };
62static int deviceBitRates[] = { 8, 16, 24, 32, -1 }; 62static int deviceBitRates[] = { 8, 16, 24, 32, -1 };
63#else //OSS 63#else //OSS
64static int deviceSampleRates[6] = { 11025, 16000, 22050, 32000, 44100, -1 }; 64static int deviceSampleRates[6] = { 11025, 16000, 22050, 32000, 44100, -1 };
65static int deviceBitRates[] = { 8, 16, -1 }; 65static int deviceBitRates[] = { 8, 16, -1 };
66#endif 66#endif
67 67
68#if defined(QT_QWS_SL5XXX) 68#if defined(QT_QWS_SL5XXX)
69///#if defined(QT_QWS_EBX) 69///#if defined(QT_QWS_EBX)
70 70
71#define DSPSTROUT "/dev/dsp" 71#define DSPSTROUT "/dev/dsp"
72#define DSPSTRIN "/dev/dsp1" 72#define DSPSTRIN "/dev/dsp1"
73#define DSPSTRMIXEROUT "/dev/mixer" 73#define DSPSTRMIXEROUT "/dev/mixer"
74#define DSPSTRMIXERIN "/dev/mixer1" 74#define DSPSTRMIXERIN "/dev/mixer1"
75 75
76#else 76#else
77 77
78#define DSPSTROUT "/dev/dsp" 78#define DSPSTROUT "/dev/dsp"
79#define DSPSTRIN "/dev/dsp" 79#define DSPSTRIN "/dev/dsp"
80#define DSPSTRMIXERIN "/dev/mixer" 80#define DSPSTRMIXERIN "/dev/mixer"
81#define DSPSTRMIXEROUT "/dev/mixer" 81#define DSPSTRMIXEROUT "/dev/mixer"
82 82
83#endif 83#endif
84 84
85//#define ZAURUS 0 85//#define ZAURUS 0
86struct adpcm_state encoder_state; 86struct adpcm_state encoder_state;
87struct adpcm_state decoder_state; 87struct adpcm_state decoder_state;
88 88
89typedef struct { 89typedef struct {
90 int sampleRate; 90 int sampleRate;
91 /* int fragSize; */ 91 /* int fragSize; */
92 /* int blockSize; */ 92 /* int blockSize; */
93 int resolution; //bitrate 93 int resolution; //bitrate
94 int channels; //number of channels 94 int channels; //number of channels
95 int fd; //file descriptor 95 int fd; //file descriptor
96 int sd; //sound device descriptor 96 int sd; //sound device descriptor
97 int numberSamples; //total number of samples 97 int numberSamples; //total number of samples
98 int SecondsToRecord; // number of seconds that should be recorded 98 int SecondsToRecord; // number of seconds that should be recorded
99 float numberOfRecordedSeconds; //total number of samples recorded 99 float numberOfRecordedSeconds; //total number of samples recorded
100 int samplesToRecord; //number of samples to be recorded 100 int samplesToRecord; //number of samples to be recorded
101 int inVol; //input volume 101 int inVol; //input volume
102 int outVol; //output volume 102 int outVol; //output volume
103 int format; //wavfile format PCM.. ADPCM 103 int format; //wavfile format PCM.. ADPCM
104 const char *fileName; //name of fiel to be played/recorded 104 const char *fileName; //name of fiel to be played/recorded
105} fileParameters; 105} fileParameters;
106 106
107fileParameters filePara; 107fileParameters filePara;
108 108
109bool monitoring, recording, playing; 109bool monitoring, recording, playing;
110bool stopped; 110bool stopped;
111QLabel *timeLabel; 111QLabel *timeLabel;
112QSlider *timeSlider; 112QSlider *timeSlider;
113int sd; 113int sd;
114 114
115Waveform* waveform; 115Waveform* waveform;
116Device *soundDevice; 116Device *soundDevice;
117 117
118 118
119#ifdef THREADED 119#ifdef THREADED
120void quickRec() 120void quickRec()
121#else 121#else
122 void QtRec::quickRec() 122 void QtRec::quickRec()
123#endif 123#endif
124{ 124{
125 125
126 qDebug("%d", 126 qDebug("%d",
127 filePara.numberSamples/filePara.sampleRate * filePara.channels); 127 filePara.numberSamples/filePara.sampleRate * filePara.channels);
128 qDebug("samples %d, rate %d, channels %d", 128 qDebug("samples %d, rate %d, channels %d",
129 filePara.numberSamples, filePara.sampleRate, filePara.channels); 129 filePara.numberSamples, filePara.sampleRate, filePara.channels);
130 130
131 int total = 0; // Total number of bytes read in so far. 131 int total = 0; // Total number of bytes read in so far.
132 int bytesWritten, number; 132 int bytesWritten, number;
133 133
134 bytesWritten = 0; 134 bytesWritten = 0;
135 number = 0; 135 number = 0;
136 QString num; 136 QString num;
137 int level = 0; 137 int level = 0;
138 int threshold = 0; 138 int threshold = 0;
139// int bits = filePara.resolution; 139// int bits = filePara.resolution;
140// qDebug("bits %d", bits); 140// qDebug("bits %d", bits);
141 141
142 if( filePara.resolution == 16 ) { //AFMT_S16_LE) 142 if( filePara.resolution == 16 ) { //AFMT_S16_LE)
143// qDebug("AFMT_S16_LE size %d", filePara.SecondsToRecord); 143// qDebug("AFMT_S16_LE size %d", filePara.SecondsToRecord);
144// qDebug("samples to record %d", filePara.samplesToRecord); 144// qDebug("samples to record %d", filePara.samplesToRecord);
145// qDebug("%d", filePara.sd); 145// qDebug("%d", filePara.sd);
146 level = 7; 146 level = 7;
147 threshold = 0; 147 threshold = 0;
148 148
149 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) { 149 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) {
150// qDebug("start recording WAVE_FORMAT_DVI_ADPCM"); 150// qDebug("start recording WAVE_FORMAT_DVI_ADPCM");
151 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>> 151 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>>
152 char abuf[ BUFSIZE/2 ]; 152 char abuf[ BUFSIZE/2 ];
153 short sbuf[ BUFSIZE ]; 153 short sbuf[ BUFSIZE ];
154 short sbuf2[ BUFSIZE ]; 154 short sbuf2[ BUFSIZE ];
155 memset( abuf, 0, BUFSIZE/2); 155 memset( abuf, 0, BUFSIZE/2);
156 memset( sbuf, 0, BUFSIZE); 156 memset( sbuf, 0, BUFSIZE);
157 memset( sbuf2, 0, BUFSIZE); 157 memset( sbuf2, 0, BUFSIZE);
158 158
159 for(;;) { 159 for(;;) {
160 if ( stopped) { 160 if ( stopped) {
161 // qDebug("quickRec:: stopped"); 161 // qDebug("quickRec:: stopped");
162 break; 162 break;
163 } 163 }
164 164
165// number=::read( filePara.sd, sbuf, BUFSIZE); 165// number=::read( filePara.sd, sbuf, BUFSIZE);
166 number = soundDevice ->devRead( filePara.sd, sbuf, BUFSIZE); 166 number = soundDevice ->devRead( filePara.sd, sbuf, BUFSIZE);
167 167
168 if(number <= 0) { 168 if(number <= 0) {
169 perror("recording error "); 169 perror("recording error ");
170 qDebug( "%s %d", filePara.fileName, number); 170 qDebug( "%s %d", filePara.fileName, number);
171 stopped = true; 171 stopped = true;
172 return; 172 return;
173 } 173 }
174 //if(stereo == 2) { 174 //if(stereo == 2) {
175// adpcm_coder( sbuf2, abuf, number/2, &encoder_state); 175// adpcm_coder( sbuf2, abuf, number/2, &encoder_state);
176 adpcm_coder( sbuf, abuf, number/2, &encoder_state); 176 adpcm_coder( sbuf, abuf, number/2, &encoder_state);
177 177
178 bytesWritten = ::write( filePara.fd , (short *)abuf, number/4); 178 bytesWritten = ::write( filePara.fd , (short *)abuf, number/4);
179 179
180 waveform->newSamples( (const short *)abuf, bytesWritten ); 180 waveform->newSamples( (const short *)abuf, bytesWritten );
181 181
182 total += bytesWritten; 182 total += bytesWritten;
183 filePara.numberSamples = total; 183 filePara.numberSamples = total;
184 timeSlider->setValue( total); 184 timeSlider->setValue( total);
185 185
186 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate * (float)2 / filePara.channels; 186 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate * (float)2 / filePara.channels;
187 187
188 qApp->processEvents(); 188 qApp->processEvents();
189 if( total >= filePara.samplesToRecord) { 189 if( total >= filePara.samplesToRecord) {
190 stopped = true; 190 stopped = true;
191 break; 191 break;
192 } 192 }
193 } 193 }
194 } else { 194 } else {
195 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>> 195 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>>
196 qDebug("start recording WAVE_FORMAT_PCM"); 196 qDebug("start recording WAVE_FORMAT_PCM");
197 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ]; 197 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ];
198 memset( inbuffer, 0, BUFSIZE); 198 memset( inbuffer, 0, BUFSIZE);
199 memset( outbuffer, 0, BUFSIZE); 199 memset( outbuffer, 0, BUFSIZE);
200 200
201 for(;;) { 201 for(;;) {
202 if ( stopped) { 202 if ( stopped) {
203 qDebug("quickRec:: stopped"); 203 qDebug("quickRec:: stopped");
204 stopped = true; 204 stopped = true;
205 break; // stop if playing was set to false 205 break; // stop if playing was set to false
206 return; 206 return;
207 } 207 }
208 208
209 number = soundDevice->devRead( filePara.sd, (short *)inbuffer, BUFSIZE); 209 number = soundDevice->devRead( filePara.sd, (short *)inbuffer, BUFSIZE);
210 waveform->newSamples( inbuffer, number ); 210 waveform->newSamples( inbuffer, number );
211 211
212 if( number <= 0) { 212 if( number <= 0) {
213 perror( "recording error "); 213 perror( "recording error ");
214 qDebug( filePara.fileName); 214 qDebug( filePara.fileName);
215 stopped = true; 215 stopped = true;
216 return; 216 return;
217 } 217 }
218 218
219 bytesWritten = ::write( filePara.fd , inbuffer, number); 219 bytesWritten = ::write( filePara.fd , inbuffer, number);
220 220
221 if( bytesWritten < 0) { 221 if( bytesWritten < 0) {
222 perror("File writing error "); 222 perror("File writing error ");
223 stopped = true; 223 stopped = true;
224 return; 224 return;
225 } 225 }
226 226
227 total += bytesWritten; 227 total += bytesWritten;
228 228
229 filePara.numberSamples = total; 229 filePara.numberSamples = total;
230 230
231 if( filePara.SecondsToRecord != 0) 231 if( filePara.SecondsToRecord != 0)
232 timeSlider->setValue( total); 232 timeSlider->setValue( total);
233// printf("Writing number %d, bytes %d,total %d\r",number, bytesWritten , total); 233// printf("Writing number %d, bytes %d,total %d\r",number, bytesWritten , total);
234// fflush(stdout); 234// fflush(stdout);
235 235
236 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2/filePara.channels; 236 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2/filePara.channels;
237 qApp->processEvents(); 237 qApp->processEvents();
238 238
239 if( total >= filePara.samplesToRecord) { 239 if( total >= filePara.samplesToRecord) {
240 stopped = true; 240 stopped = true;
241 break; 241 break;
242 } 242 }
243 } 243 }
244 } //end main loop 244 } //end main loop
245 245
246 } else { 246 } else {
247// <<<<<<<<<<<<<<<<<<<<<<< format = AFMT_U8; 247// <<<<<<<<<<<<<<<<<<<<<<< format = AFMT_U8;
248 unsigned char unsigned_inbuffer[ BUFSIZE ], unsigned_outbuffer[ BUFSIZE ]; 248 unsigned char unsigned_inbuffer[ BUFSIZE ], unsigned_outbuffer[ BUFSIZE ];
249 memset( unsigned_inbuffer, 0, BUFSIZE); 249 memset( unsigned_inbuffer, 0, BUFSIZE);
250 memset( unsigned_outbuffer, 0, BUFSIZE); 250 memset( unsigned_outbuffer, 0, BUFSIZE);
251 251
252 for(;;) { 252 for(;;) {
253 if ( stopped) { 253 if ( stopped) {
254 qDebug("quickRec:: stopped"); 254 qDebug("quickRec:: stopped");
255 break; // stop if playing was set to false 255 break; // stop if playing was set to false
256 } 256 }
257 257
258 number = ::read( filePara.sd, unsigned_inbuffer, BUFSIZE); 258 number = ::read( filePara.sd, unsigned_inbuffer, BUFSIZE);
259 bytesWritten = ::write( filePara.fd , unsigned_inbuffer, number); 259 bytesWritten = ::write( filePara.fd , unsigned_inbuffer, number);
260 260
261 if(bytesWritten < 0) { 261 if(bytesWritten < 0) {
262 stopped = true; 262 stopped = true;
263 QMessageBox::message("Note","There was a problem\nwriting to the file"); 263 QMessageBox::message("Note","There was a problem\nwriting to the file");
264 perror("File writing error "); 264 perror("File writing error ");
265 return; 265 return;
266 } 266 }
267 267
268 total += bytesWritten; 268 total += bytesWritten;
269 filePara.numberSamples = total; 269 filePara.numberSamples = total;
270 // printf("\nWriting number %d, bytes %d,total %d \r",number, bytesWritten , total); 270 // printf("\nWriting number %d, bytes %d,total %d \r",number, bytesWritten , total);
271 // fflush(stdout); 271 // fflush(stdout);
272 if( filePara.SecondsToRecord !=0) 272 if( filePara.SecondsToRecord !=0)
273 timeSlider->setValue( total); 273 timeSlider->setValue( total);
274 274
275 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate; 275 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate;
276 276
277 qApp->processEvents(); 277 qApp->processEvents();
278 if( total >= filePara.samplesToRecord) { 278 if( total >= filePara.samplesToRecord) {
279 stopped = true; 279 stopped = true;
280 break; 280 break;
281 } 281 }
282 } //end main loop 282 } //end main loop
283 } 283 }
284} /// END quickRec() 284} /// END quickRec()
285 285
286 286
287#ifdef THREADED 287#ifdef THREADED
288void playIt() 288void playIt()
289#else 289#else
290 void QtRec::playIt() 290 void QtRec::playIt()
291#endif 291#endif
292{ 292{
293 int bytesWritten = 0; 293 int bytesWritten = 0;
294 int number = 0; 294 int number = 0;
295 int total = 0; // Total number of bytes read in so far. 295 int total = 0; // Total number of bytes read in so far.
296 if( filePara.resolution == 16 ) { //AFMT_S16_LE) { 296 if( filePara.resolution == 16 ) { //AFMT_S16_LE) {
297 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) { 297 if( filePara.format == WAVE_FORMAT_DVI_ADPCM) {
298 char abuf[ BUFSIZE / 2 ]; 298 char abuf[ BUFSIZE / 2 ];
299 short sbuf[ BUFSIZE ]; 299 short sbuf[ BUFSIZE ];
300 short sbuf2[ BUFSIZE * 2 ]; 300 short sbuf2[ BUFSIZE * 2 ];
301 memset( abuf, 0, BUFSIZE / 2); 301 memset( abuf, 0, BUFSIZE / 2);
302 memset( sbuf, 0, BUFSIZE); 302 memset( sbuf, 0, BUFSIZE);
303 memset( sbuf2, 0, BUFSIZE * 2); 303 memset( sbuf2, 0, BUFSIZE * 2);
304// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>> 304// <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_DVI_ADPCM >>>>>>>>>>>>>>>>>>>>>>
305 for(;;) { // play loop 305 for(;;) { // play loop
306 if ( stopped) { 306 if ( stopped) {
307 break; 307 break;
308 return; 308 return;
309 }// stop if playing was set to false 309 }// stop if playing was set to false
310 310
311 number = ::read( filePara.fd, abuf, BUFSIZE / 2); 311 number = ::read( filePara.fd, abuf, BUFSIZE / 2);
312 adpcm_decoder( abuf, sbuf, number * 2, &decoder_state); 312 adpcm_decoder( abuf, sbuf, number * 2, &decoder_state);
313 313
314// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel 314// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel
315// sbuf2[i+1]=sbuf2[i]=sbuf[i]; 315// sbuf2[i+1]=sbuf2[i]=sbuf[i];
316// } 316// }
317 bytesWritten = write ( filePara.sd, sbuf, number * 4); 317 bytesWritten = write ( filePara.sd, sbuf, number * 4);
318 waveform->newSamples( (const short *)sbuf, number ); 318 waveform->newSamples( (const short *)sbuf, number );
319 // if(filePara.channels==1) 319 // if(filePara.channels==1)
320 // total += bytesWritten/2; //mono 320 // total += bytesWritten/2; //mono
321 // else 321 // else
322 total += bytesWritten; 322 total += bytesWritten;
323 filePara.numberSamples = total/4; 323 filePara.numberSamples = total/4;
324 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / 2; 324 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / 2;
325 325
326 timeSlider->setValue( total/4); 326 timeSlider->setValue( total/4);
327// timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds); 327// timeString.sprintf("%.2f", filePara.numberOfRecordedSeconds);
328// if(filePara.numberOfRecordedSeconds>1) 328// if(filePara.numberOfRecordedSeconds>1)
329// timeLabel->setText( timeString+ tr(" seconds")); 329// timeLabel->setText( timeString+ tr(" seconds"));
330 // printf("playing number %d, bytes %d, total %d\n",number, bytesWritten, total/4); 330 // printf("playing number %d, bytes %d, total %d\n",number, bytesWritten, total/4);
331 // fflush(stdout); 331 // fflush(stdout);
332 332
333 qApp->processEvents(); 333 qApp->processEvents();
334 334
335 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) { 335 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
336// if( total >= filePara.numberSamples ){//|| secCount > filePara.numberOfRecordedSeconds ) { 336// if( total >= filePara.numberSamples ){//|| secCount > filePara.numberOfRecordedSeconds ) {
337 stopped = true; 337 stopped = true;
338 break; 338 break;
339 } 339 }
340 } 340 }
341 } else { 341 } else {
342 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>> 342 // <<<<<<<<<<<<<<<<<<<<<<<<<<< WAVE_FORMAT_PCM >>>>>>>>>>>>>>>>>>>>>>
343 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ]; 343 short inbuffer[ BUFSIZE ], outbuffer[ BUFSIZE ];
344 memset( inbuffer, 0, BUFSIZE); 344 memset( inbuffer, 0, BUFSIZE);
345 memset( outbuffer, 0, BUFSIZE); 345 memset( outbuffer, 0, BUFSIZE);
346 346
347 for(;;) { // play loop 347 for(;;) { // play loop
348 if ( stopped) { 348 if ( stopped) {
349 break; 349 break;
350 return; 350 return;
351 } 351 }
352// stop if playing was set to false 352// stop if playing was set to false
353 number = ::read( filePara.fd, inbuffer, BUFSIZE); 353 number = ::read( filePara.fd, inbuffer, BUFSIZE);
354// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel 354// for (int i=0;i< number * 2; 2 * i++) { //2*i is left channel
355// // for (int i=0;i< number ; i++) { //2*i is left channel 355// // for (int i=0;i< number ; i++) { //2*i is left channel
356// outbuffer[i+1]= outbuffer[i]=inbuffer[i]; 356// outbuffer[i+1]= outbuffer[i]=inbuffer[i];
357// } 357// }
358 bytesWritten = ::write( filePara.sd, inbuffer, number); 358 bytesWritten = ::write( filePara.sd, inbuffer, number);
359 waveform->newSamples( inbuffer, bytesWritten ); 359 waveform->newSamples( inbuffer, bytesWritten );
360 //-------------->>>> out to device 360 //-------------->>>> out to device
361 // total+=bytesWritten; 361 // total+=bytesWritten;
362 // if(filePara.channels==1) 362 // if(filePara.channels==1)
363 // total += bytesWritten/2; //mono 363 // total += bytesWritten/2; //mono
364 // else 364 // else
365 total += bytesWritten; 365 total += bytesWritten;
366 timeSlider->setValue( total); 366 timeSlider->setValue( total);
367 367
368 filePara.numberSamples = total; 368 filePara.numberSamples = total;
369 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2; 369 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate / (float)2;
370 370
371// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); 371// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds);
372// timeLabel->setText( timeString + tr(" seconds")); 372// timeLabel->setText( timeString + tr(" seconds"));
373 373
374 qApp->processEvents(); 374 qApp->processEvents();
375 375
376 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) { 376 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
377 qWarning("Jane! Stop this crazy thing!"); 377 qWarning("Jane! Stop this crazy thing!");
378 stopped = true; 378 stopped = true;
379// playing = false; 379// playing = false;
380 break; 380 break;
381 } 381 }
382 } 382 }
383 printf("\nplaying number %d, bytes %d, total %d\r",number, bytesWritten, total); 383 printf("\nplaying number %d, bytes %d, total %d\r",number, bytesWritten, total);
384 fflush(stdout); 384 fflush(stdout);
385 } //end loop 385 } //end loop
386 } else { 386 } else {
387/////////////////////////////// format = AFMT_U8; 387/////////////////////////////// format = AFMT_U8;
388 unsigned char unsigned_inbuffer[ BUFSIZE ]; //, unsigned_outbuffer[BUFSIZE]; 388 unsigned char unsigned_inbuffer[ BUFSIZE ]; //, unsigned_outbuffer[BUFSIZE];
389 memset( unsigned_inbuffer, 0, BUFSIZE); 389 memset( unsigned_inbuffer, 0, BUFSIZE);
390 for(;;) { 390 for(;;) {
391// main loop 391// main loop
392 if (stopped) { 392 if (stopped) {
393 break; // stop if playing was set to false 393 break; // stop if playing was set to false
394 return; 394 return;
395 } 395 }
396 number = ::read( filePara.fd, unsigned_inbuffer, BUFSIZE); 396 number = ::read( filePara.fd, unsigned_inbuffer, BUFSIZE);
397//data = (val >> 8) ^ 0x80; 397//data = (val >> 8) ^ 0x80;
398 // unsigned_outbuffer = (unsigned_inbuffer >> 8) ^ 0x80; 398 // unsigned_outbuffer = (unsigned_inbuffer >> 8) ^ 0x80;
399 bytesWritten = write ( filePara.sd, unsigned_inbuffer, number); 399 bytesWritten = write ( filePara.sd, unsigned_inbuffer, number);
400 waveform->newSamples( (const short *)unsigned_inbuffer, bytesWritten ); 400 waveform->newSamples( (const short *)unsigned_inbuffer, bytesWritten );
401 total += bytesWritten; 401 total += bytesWritten;
402 402
403 timeSlider->setValue( total); 403 timeSlider->setValue( total);
404 filePara.numberSamples = total; 404 filePara.numberSamples = total;
405 405
406 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate; 406 filePara.numberOfRecordedSeconds = (float)total / (float)filePara.sampleRate;
407// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds); 407// timeString.sprintf("%.2f",filePara.numberOfRecordedSeconds);
408// timeLabel->setText( timeString + tr(" seconds")); 408// timeLabel->setText( timeString + tr(" seconds"));
409 qApp->processEvents(); 409 qApp->processEvents();
410 410
411 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) { 411 if( /*total >= filePara.numberSamples || */ bytesWritten == 0) {
412// if( total >= filePara.numberSamples ) { 412// if( total >= filePara.numberSamples ) {
413 stopped = true; 413 stopped = true;
414 break; 414 break;
415 } 415 }
416 // printf("Writing number %d, bytes %d, total %d, numberSamples %d\r",number, bytesWritten , total, filePara.numberSamples); 416 // printf("Writing number %d, bytes %d, total %d, numberSamples %d\r",number, bytesWritten , total, filePara.numberSamples);
417 // fflush(stdout); 417 // fflush(stdout);
418 } 418 }
419 } 419 }
420} 420}
421 421
422 422
423QtRec::QtRec( QWidget* parent, const char* name, WFlags fl ) 423QtRec::QtRec( QWidget* parent, const char* name, WFlags fl )
424 : QWidget( parent, name, fl ) 424 : QWidget( parent, name, fl )
425{ 425{
426 if ( !name ) 426 if ( !name )
427 setName( "OpieRec" ); 427 setName( "OpieRec" );
428 init(); 428 init();
429 initConfig(); 429 initConfig();
430 initConnections(); 430 initConnections();
431 renameBox = 0; 431 renameBox = 0;
432 432
433// open sound device to get volumes 433// open sound device to get volumes
434 Config hwcfg("OpieRec"); 434 Config hwcfg("OpieRec");
435 hwcfg.setGroup("Hardware"); 435 hwcfg.setGroup("Hardware");
436 436
437 437
438 soundDevice = new Device( this, 438 soundDevice = new Device( this,
439 hwcfg.readEntry( "Audio",DSPSTROUT), 439 hwcfg.readEntry( "Audio",DSPSTROUT),
440 hwcfg.readEntry( "Mixer",DSPSTRMIXEROUT), false); 440 hwcfg.readEntry( "Mixer",DSPSTRMIXEROUT), false);
441 // soundDevice = new Device( this, hwcfg.readEntry( "Audio","hw:0"), hwcfg.readEntry( "Mixer","hw:0"), false); 441 // soundDevice = new Device( this, hwcfg.readEntry( "Audio","hw:0"), hwcfg.readEntry( "Mixer","hw:0"), false);
442 442
443// soundDevice->setDeviceFormat(AFMT_S16_LE); 443// soundDevice->setDeviceFormat(AFMT_S16_LE);
444// soundDevice->setDeviceChannels(1); 444// soundDevice->setDeviceChannels(1);
445// soundDevice->setDeviceRate( 22050); 445// soundDevice->setDeviceRate( 22050);
446 446
447 getInVol(); 447 getInVol();
448 getOutVol(); 448 getOutVol();
449 449
450 soundDevice->closeDevice( true); 450 soundDevice->closeDevice( true);
451 soundDevice->sd = -1; 451 soundDevice->sd = -1;
452 soundDevice = 0; 452 soundDevice = 0;
453 wavFile = 0; 453 wavFile = 0;
454 454
455 if( soundDevice) delete soundDevice; 455 if( soundDevice) delete soundDevice;
456 456
457 initIconView(); 457 initIconView();
458 458
459 if( autoMute) 459 if( autoMute)
460 doMute( true); 460 doMute( true);
461 ListView1->setFocus(); 461 ListView1->setFocus();
462 playing = false; 462 playing = false;
463} 463}
464 464
465QtRec::~QtRec() { 465QtRec::~QtRec() {
466 466
467} 467}
468 468
469void QtRec::cleanUp() { 469void QtRec::cleanUp() {
470 470
471 if( !stopped) { 471 if( !stopped) {
472 stopped = true; 472 stopped = true;
473 endRecording(); 473 endRecording();
474 } 474 }
475 475
476 ListView1->clear(); 476 ListView1->clear();
477 477
478 if( autoMute) 478 if( autoMute)
479 doMute(false); 479 doMute(false);
480 480
481 if( wavFile) delete wavFile; 481 if( wavFile) delete wavFile;
482// if(soundDevice) delete soundDevice; 482// if(soundDevice) delete soundDevice;
483} 483}
484 484
485void QtRec::init() { 485void QtRec::init() {
486 486
487 needsStereoOut = false; 487 needsStereoOut = false;
488 QPixmap image3( ( const char** ) image3_data ); 488 QPixmap image3( ( const char** ) image3_data );
489 QPixmap image4( ( const char** ) image4_data ); 489 QPixmap image4( ( const char** ) image4_data );
490 QPixmap image6( ( const char** ) image6_data ); 490 QPixmap image6( ( const char** ) image6_data );
491 491
492 stopped = true; 492 stopped = true;
493 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); 493 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
494 QGridLayout *layout = new QGridLayout( this ); 494 QGridLayout *layout = new QGridLayout( this );
495 layout->setSpacing( 2); 495 layout->setSpacing( 2);
496 layout->setMargin( 2); 496 layout->setMargin( 2);
497 497
498 TabWidget = new QTabWidget( this, "TabWidget" ); 498 TabWidget = new QTabWidget( this, "TabWidget" );
499 layout->addMultiCellWidget(TabWidget, 0, 7, 0, 7); 499 layout->addMultiCellWidget(TabWidget, 0, 7, 0, 7);
500// TabWidget->setTabShape(QTabWidget::Triangular); 500// TabWidget->setTabShape(QTabWidget::Triangular);
501 501
502 ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** 502 ///**********<<<<<<<<<<<<>>>>>>>>>>>>***************
503 tab = new QWidget( TabWidget, "tab" ); 503 tab = new QWidget( TabWidget, "tab" );
504 504
505 QGridLayout *layout1 = new QGridLayout( tab); 505 QGridLayout *layout1 = new QGridLayout( tab);
506 layout1->setSpacing( 2); 506 layout1->setSpacing( 2);
507 layout1->setMargin( 2); 507 layout1->setMargin( 2);
508 508
509 timeSlider = new QSlider( 0,100,10,0, QSlider::Horizontal, tab, (const char *) "timeSlider" ); 509 timeSlider = new QSlider( 0,100,10,0, QSlider::Horizontal, tab, (const char *) "timeSlider" );
510 layout1->addMultiCellWidget( timeSlider, 1, 1, 0, 3); 510 layout1->addMultiCellWidget( timeSlider, 1, 1, 0, 3);
511 511
512 timeLabel = new QLabel( tab, "TimeLabel" ); 512 timeLabel = new QLabel( tab, "TimeLabel" );
513 layout1->addMultiCellWidget( timeLabel, 0, 0, 0, 3); 513 layout1->addMultiCellWidget( timeLabel, 0, 0, 0, 3);
514 514
515 playLabel2 = new QLabel(tab, "PlayLabel2" ); 515 playLabel2 = new QLabel(tab, "PlayLabel2" );
516 playLabel2->setText(tr("Play") ); 516 playLabel2->setText(tr("Play") );
517 playLabel2->setFixedHeight( 18); 517 playLabel2->setFixedHeight( 18);
518 layout1->addMultiCellWidget( playLabel2, 0, 0, 4, 4); 518 layout1->addMultiCellWidget( playLabel2, 0, 0, 4, 4);
519 519
520 Stop_PushButton = new QPushButton( tab, "Stop_PushButton" ); 520 Stop_PushButton = new QPushButton( tab, "Stop_PushButton" );
521 layout1->addMultiCellWidget( Stop_PushButton, 1, 1, 4, 4); 521 layout1->addMultiCellWidget( Stop_PushButton, 1, 1, 4, 4);
522 Stop_PushButton->setFixedSize( 22, 22); 522 Stop_PushButton->setFixedSize( 22, 22);
523 Stop_PushButton->setPixmap( image4 ); 523 Stop_PushButton->setPixmap( image4 );
524 524
525 toBeginningButton = new QPushButton( tab, "Beginning_PushButton" ); 525 toBeginningButton = new QPushButton( tab, "Beginning_PushButton" );
526 layout1->addMultiCellWidget(toBeginningButton, 1, 1, 5, 5); 526 layout1->addMultiCellWidget(toBeginningButton, 1, 1, 5, 5);
527 toBeginningButton->setFixedSize( 22, 22); 527 toBeginningButton->setFixedSize( 22, 22);
528 toBeginningButton->setPixmap( Resource::loadPixmap("fastback") ); 528 toBeginningButton->setPixmap( Resource::loadPixmap("fastback") );
529 529
530 toEndButton = new QPushButton( tab, "End_PushButton" ); 530 toEndButton = new QPushButton( tab, "End_PushButton" );
531 layout1->addMultiCellWidget( toEndButton, 1, 1, 6, 6); 531 layout1->addMultiCellWidget( toEndButton, 1, 1, 6, 6);
532 toEndButton->setFixedSize( 22, 22); 532 toEndButton->setFixedSize( 22, 22);
533 toEndButton->setPixmap( Resource::loadPixmap( "fastforward" ) ); 533 toEndButton->setPixmap( Resource::loadPixmap( "fastforward" ) );
534 534
535 QLabel *recLabel2; 535 QLabel *recLabel2;
536 recLabel2 = new QLabel( tab, "recLabel2" ); 536 recLabel2 = new QLabel( tab, "recLabel2" );
537 recLabel2->setText(tr("Rec")); 537 recLabel2->setText(tr("Rec"));
538 recLabel2->setFixedHeight( 18); 538 recLabel2->setFixedHeight( 18);
539 layout1->addMultiCellWidget( recLabel2, 0, 0, 7, 7); 539 layout1->addMultiCellWidget( recLabel2, 0, 0, 7, 7);
540 540
541 Rec_PushButton = new QPushButton( tab, "Rec_PushButton" ); 541 Rec_PushButton = new QPushButton( tab, "Rec_PushButton" );
542 layout1->addMultiCellWidget( Rec_PushButton, 1, 1, 7, 7); 542 layout1->addMultiCellWidget( Rec_PushButton, 1, 1, 7, 7);
543 Rec_PushButton->setFixedSize( 22, 22); 543 Rec_PushButton->setFixedSize( 22, 22);
544 Rec_PushButton->setPixmap( image6 ); 544 Rec_PushButton->setPixmap( image6 );
545 545
546 t = new QTimer( this ); 546 t = new QTimer( this );
547 connect( t, SIGNAL( timeout() ), SLOT( timerBreak() ) ); 547 connect( t, SIGNAL( timeout() ), SLOT( timerBreak() ) );
548 548
549 rewindTimer = new QTimer( this ); 549 rewindTimer = new QTimer( this );
550 connect( rewindTimer, SIGNAL( timeout() ), 550 connect( rewindTimer, SIGNAL( timeout() ),
551 this, SLOT( rewindTimerTimeout() ) ); 551 this, SLOT( rewindTimerTimeout() ) );
552 552
553 forwardTimer = new QTimer( this ); 553 forwardTimer = new QTimer( this );
554 connect( forwardTimer, SIGNAL( timeout() ), 554 connect( forwardTimer, SIGNAL( timeout() ),
555 this, SLOT( forwardTimerTimeout() ) ); 555 this, SLOT( forwardTimerTimeout() ) );
556 556
557 deleteSoundButton = new QPushButton( tab, "deleteSoundButton" ); 557 deleteSoundButton = new QPushButton( tab, "deleteSoundButton" );
558 layout1->addMultiCellWidget( deleteSoundButton, 1, 1, 8, 8); 558 layout1->addMultiCellWidget( deleteSoundButton, 1, 1, 8, 8);
559 deleteSoundButton->setText( tr( "Delete" ) ); 559 deleteSoundButton->setText( tr( "Delete" ) );
560 560
561 ListView1 = new QListView( tab, "IconView1" ); 561 ListView1 = new QListView( tab, "IconView1" );
562 layout1->addMultiCellWidget( ListView1, 2, 2, 0, 8); 562 layout1->addMultiCellWidget( ListView1, 2, 2, 0, 8);
563 563
564 ListView1->addColumn( tr( "Name" ) ); 564 ListView1->addColumn( tr( "Name" ) );
565 ListView1->setColumnWidth( 0, 140); 565 ListView1->setColumnWidth( 0, 140);
566 ListView1->setSorting( 1, false); 566 ListView1->setSorting( 1, false);
567 ListView1->addColumn( tr( "Time" ) ); //in seconds 567 ListView1->addColumn( tr( "Time" ) ); //in seconds
568 ListView1->setColumnWidth( 1, 50); 568 ListView1->setColumnWidth( 1, 50);
569 ListView1->addColumn( tr("Location") ); 569 ListView1->addColumn( tr("Location") );
570 ListView1->setColumnWidth( 2, 50); 570 ListView1->setColumnWidth( 2, 50);
571 ListView1->addColumn( tr("Date") ); 571 ListView1->addColumn( tr("Date") );
572 ListView1->setColumnWidth( 3, 63); 572 ListView1->setColumnWidth( 3, 63);
573 573
574 ListView1->setColumnWidthMode( 0, QListView::Manual); 574 ListView1->setColumnWidthMode( 0, QListView::Manual);
575 ListView1->setColumnAlignment( 1, QListView::AlignCenter); 575 ListView1->setColumnAlignment( 1, QListView::AlignCenter);
576 ListView1->setColumnAlignment( 2, QListView::AlignRight); 576 ListView1->setColumnAlignment( 2, QListView::AlignRight);
577 ListView1->setColumnAlignment( 3, QListView::AlignLeft); 577 ListView1->setColumnAlignment( 3, QListView::AlignLeft);
578 ListView1->setAllColumnsShowFocus( true ); 578 ListView1->setAllColumnsShowFocus( true );
579 QPEApplication::setStylusOperation( ListView1->viewport(), QPEApplication::RightOnHold); 579 QPEApplication::setStylusOperation( ListView1->viewport(), QPEApplication::RightOnHold);
580 580
581 TabWidget->insertTab( tab, tr( "Files" ) ); 581 TabWidget->insertTab( tab, tr( "Files" ) );
582 582
583 ///**********<<<<<<<<<<<<>>>>>>>>>>>>*************** 583 ///**********<<<<<<<<<<<<>>>>>>>>>>>>***************
584 tab_3 = new QWidget( TabWidget, "tab_3" ); 584 tab_3 = new QWidget( TabWidget, "tab_3" );
585 QGridLayout *glayout3 = new QGridLayout( tab_3 ); 585 QGridLayout *glayout3 = new QGridLayout( tab_3 );
586 glayout3->setSpacing( 2); 586 glayout3->setSpacing( 2);
587 glayout3->setMargin( 2); 587 glayout3->setMargin( 2);
588 //////////////////////////////////// 588 ////////////////////////////////////
589 sampleGroup = new QGroupBox( tab_3, "samplegroup" ); 589 sampleGroup = new QGroupBox( tab_3, "samplegroup" );
590 sampleGroup->setTitle( tr( "Sample Rate" ) ); 590 sampleGroup->setTitle( tr( "Sample Rate" ) );
591 sampleGroup->setFixedSize( 95,50); 591 sampleGroup->setFixedSize( 95,50);
592 592
593 sampleRateComboBox = new QComboBox( false, sampleGroup, "SampleRateComboBox" ); 593 sampleRateComboBox = new QComboBox( false, sampleGroup, "SampleRateComboBox" );
594 sampleRateComboBox->setGeometry( QRect( 10, 20, 80, 25 ) ); 594 sampleRateComboBox->setGeometry( QRect( 10, 20, 80, 25 ) );
595//#ifndef QT_QWS_EBX 595//#ifndef QT_QWS_EBX
596 QString s; 596 QString s;
597 int z = 0; 597 int z = 0;
598 while( deviceSampleRates[z] != -1) { 598 while( deviceSampleRates[z] != -1) {
599 sampleRateComboBox->insertItem( s.setNum( deviceSampleRates[z], 10)); 599 sampleRateComboBox->insertItem( s.setNum( deviceSampleRates[z], 10));
600 z++; 600 z++;
601 } 601 }
602 602
603 603
604 glayout3->addMultiCellWidget( sampleGroup, 0, 0, 0, 0); 604 glayout3->addMultiCellWidget( sampleGroup, 0, 0, 0, 0);
605 605
606 sizeGroup= new QGroupBox( tab_3, "sizeGroup" ); 606 sizeGroup= new QGroupBox( tab_3, "sizeGroup" );
607 sizeGroup->setTitle( tr( "Limit Size" ) ); 607 sizeGroup->setTitle( tr( "Limit Size" ) );
608 sizeGroup->setFixedSize( 80, 50); 608 sizeGroup->setFixedSize( 80, 50);
609 609
610 sizeLimitCombo = new QComboBox( false, sizeGroup, "sizeLimitCombo" ); 610 sizeLimitCombo = new QComboBox( false, sizeGroup, "sizeLimitCombo" );
611 sizeLimitCombo ->setGeometry( QRect( 5, 20, 70, 25 ) ); 611 sizeLimitCombo ->setGeometry( QRect( 5, 20, 70, 25 ) );
612 sizeLimitCombo->insertItem(tr("Unlimited")); 612 sizeLimitCombo->insertItem(tr("Unlimited"));
613 613
614 for(int i=1;i<13; i++) { 614 for(int i=1;i<13; i++) {
615 sizeLimitCombo->insertItem( QString::number( i * 5)); 615 sizeLimitCombo->insertItem( QString::number( i * 5));
616 } 616 }
617 617
618 618
619 glayout3->addMultiCellWidget( sizeGroup, 0, 0, 1, 1); 619 glayout3->addMultiCellWidget( sizeGroup, 0, 0, 1, 1);
620 dirGroup = new QGroupBox( tab_3, "dirGroup" ); 620 dirGroup = new QGroupBox( tab_3, "dirGroup" );
621 dirGroup->setTitle( tr( "File Directory" ) ); 621 dirGroup->setTitle( tr( "File Directory" ) );
622 dirGroup->setFixedSize( 130, 50); 622 dirGroup->setFixedSize( 130, 50);
623 623
624 directoryComboBox = new QComboBox( false, dirGroup, "dirGroup" ); 624 directoryComboBox = new QComboBox( false, dirGroup, "dirGroup" );
625 directoryComboBox->setGeometry( QRect( 10, 15, 115, 25 ) ); 625 directoryComboBox->setGeometry( QRect( 10, 15, 115, 25 ) );
626 626
627 glayout3->addMultiCellWidget( dirGroup, 1, 1, 0, 0); 627 glayout3->addMultiCellWidget( dirGroup, 1, 1, 0, 0);
628 628
629 bitGroup = new QGroupBox( tab_3, "bitGroup" ); 629 bitGroup = new QGroupBox( tab_3, "bitGroup" );
630 bitGroup->setTitle( tr( "Bit Depth" ) ); 630 bitGroup->setTitle( tr( "Bit Depth" ) );
631 bitGroup->setFixedSize( 65, 50); 631 bitGroup->setFixedSize( 65, 50);
632 632
633 bitRateComboBox = new QComboBox( false, bitGroup, "BitRateComboBox" ); 633 bitRateComboBox = new QComboBox( false, bitGroup, "BitRateComboBox" );
634 634
635 z = 0; 635 z = 0;
636 while( deviceBitRates[z] != -1) { 636 while( deviceBitRates[z] != -1) {
637 bitRateComboBox->insertItem( s.setNum( deviceBitRates[z], 10) ); 637 bitRateComboBox->insertItem( s.setNum( deviceBitRates[z], 10) );
638 z++; 638 z++;
639 } 639 }
640 640
641 bitRateComboBox->setGeometry( QRect( 5, 20, 50, 25 ) ); 641 bitRateComboBox->setGeometry( QRect( 5, 20, 50, 25 ) );
642 642
643 glayout3->addMultiCellWidget( bitGroup, 1, 1, 1, 1); 643 glayout3->addMultiCellWidget( bitGroup, 1, 1, 1, 1);
644 644
645 compressionCheckBox = new QCheckBox ( tr("Wave Compression (smaller files)"), tab_3 ); 645 compressionCheckBox = new QCheckBox ( tr("Wave Compression (smaller files)"), tab_3 );
646 646
647 autoMuteCheckBox = new QCheckBox ( tr("Auto Mute"), tab_3 ); 647 autoMuteCheckBox = new QCheckBox ( tr("Auto Mute"), tab_3 );
648 stereoCheckBox = new QCheckBox ( tr("Stereo Channels"), tab_3 ); 648 stereoCheckBox = new QCheckBox ( tr("Stereo Channels"), tab_3 );
649 649
650 glayout3->addMultiCellWidget( compressionCheckBox, 2, 2, 0, 3); 650 glayout3->addMultiCellWidget( compressionCheckBox, 2, 2, 0, 3);
651 glayout3->addMultiCellWidget( autoMuteCheckBox, 3, 3, 0, 0); 651 glayout3->addMultiCellWidget( autoMuteCheckBox, 3, 3, 0, 0);
652 glayout3->addMultiCellWidget( stereoCheckBox, 3, 3, 1, 1); 652 glayout3->addMultiCellWidget( stereoCheckBox, 3, 3, 1, 1);
653 653
654 tab_5 = new QWidget( TabWidget, "tab_5" ); 654 tab_5 = new QWidget( TabWidget, "tab_5" );
655 655
656 QHBoxLayout *Layout19a; 656 QHBoxLayout *Layout19a;
657 Layout19a = new QHBoxLayout( tab_5); 657 Layout19a = new QHBoxLayout( tab_5);
658 Layout19a->setSpacing( 2 ); 658 Layout19a->setSpacing( 2 );
659 Layout19a->setMargin( 0 ); 659 Layout19a->setMargin( 0 );
660 660
661 Layout15 = new QVBoxLayout( this); 661 Layout15 = new QVBoxLayout( this);
662 Layout15->setSpacing( 2 ); 662 Layout15->setSpacing( 2 );
663 Layout15->setMargin( 0 ); 663 Layout15->setMargin( 0 );
664 664
665 Layout15b = new QVBoxLayout( this); 665 Layout15b = new QVBoxLayout( this);
666 Layout15b->setSpacing( 2 ); 666 Layout15b->setSpacing( 2 );
667 Layout15b->setMargin( 0 ); 667 Layout15b->setMargin( 0 );
668 668
669 TextLabel2 = new QLabel( tab_5, "InputLabel" ); 669 TextLabel2 = new QLabel( tab_5, "InputLabel" );
670 TextLabel2->setText( tr( "In")); 670 TextLabel2->setText( tr( "In"));
671 TextLabel2->setFixedWidth( 35); 671 TextLabel2->setFixedWidth( 35);
672 Layout15->addWidget( TextLabel2 ); 672 Layout15->addWidget( TextLabel2 );
673 673
674 TextLabel3 = new QLabel( tab_5, "OutputLabel" ); 674 TextLabel3 = new QLabel( tab_5, "OutputLabel" );
675 TextLabel3->setText( tr( "Out" ) ); 675 TextLabel3->setText( tr( "Out" ) );
676 Layout15b->addWidget( TextLabel3 ); 676 Layout15b->addWidget( TextLabel3 );
677 677
678 InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_5, (const char *) "InputSlider" ); 678 InputSlider = new QSlider( -100, 0, 10, 0, QSlider::Vertical, tab_5, (const char *) "InputSlider" );
679 InputSlider->setTickmarks( QSlider::Both); 679 InputSlider->setTickmarks( QSlider::Both);
680 Layout15->addWidget( InputSlider); 680 Layout15->addWidget( InputSlider);
681 681
682 OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_5,(const char *) "OutputSlider" ); 682 OutputSlider = new QSlider( -100,0,10,0, QSlider::Vertical,tab_5,(const char *) "OutputSlider" );
683 OutputSlider->setTickmarks( QSlider::Both); 683 OutputSlider->setTickmarks( QSlider::Both);
684 684
685 Layout15b->addWidget( OutputSlider ); 685 Layout15b->addWidget( OutputSlider );
686 686
687 outMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 ); 687 outMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 );
688 Layout15->addWidget( outMuteCheckBox ); 688 Layout15->addWidget( outMuteCheckBox );
689 689
690 inMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 ); 690 inMuteCheckBox = new QCheckBox ( tr("mute"), tab_5 );
691 inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus ); 691 inMuteCheckBox-> setFocusPolicy ( QWidget::NoFocus );
692 Layout15b->addWidget( inMuteCheckBox ); 692 Layout15b->addWidget( inMuteCheckBox );
693 693
694 694
695 Layout19a->addLayout( Layout15 ); 695 Layout19a->addLayout( Layout15 );
696 Layout19a->addLayout( Layout15b ); 696 Layout19a->addLayout( Layout15b );
697 697
698 fillDirectoryCombo(); 698 fillDirectoryCombo();
699 699
700 TabWidget->insertTab( tab_3, tr( "Options" ) ); 700 TabWidget->insertTab( tab_3, tr( "Options" ) );
701 701
702 TabWidget->insertTab( tab_5, tr( "Volume" ) ); 702 TabWidget->insertTab( tab_5, tr( "Volume" ) );
703 703
704 704
705 waveform = new Waveform( this, "waveform" ); 705 waveform = new Waveform( this, "waveform" );
706// waveform->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)3, waveform->sizePolicy().hasHeightForWidth() ) ); 706// waveform->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)3, waveform->sizePolicy().hasHeightForWidth() ) );
707 waveform->setMinimumSize( QSize( 0, 50 ) ); 707 waveform->setMinimumSize( QSize( 0, 50 ) );
708 708
709 layout->addMultiCellWidget( waveform, 8, 8, 0, 7 ); 709 layout->addMultiCellWidget( waveform, 8, 8, 0, 7 );
710 waveform->setBackgroundColor ( black ); 710 waveform->setBackgroundColor ( black );
711} 711}
712 712
713void QtRec::initIconView() { 713void QtRec::initIconView() {
714 714
715 ListView1->clear(); 715 ListView1->clear();
716 Config cfg("OpieRec"); 716 Config cfg("OpieRec");
717 cfg.setGroup("Sounds"); 717 cfg.setGroup("Sounds");
718 QString temp; 718 QString temp;
719 QPixmap image0( ( const char** ) image0_data ); 719 QPixmap image0( ( const char** ) image0_data );
720 720
721 int nFiles = cfg.readNumEntry("NumberofFiles",0); 721 int nFiles = cfg.readNumEntry("NumberofFiles",0);
722 // qDebug("init number of files %d", nFiles); 722 // qDebug("init number of files %d", nFiles);
723 723
724 for(int i=1;i<= nFiles;i++) { 724 for(int i=1;i<= nFiles;i++) {
725 725
726 QListViewItem * item; 726 QListViewItem * item;
727 QString fileS, mediaLocation, fileDate, filePath; 727 QString fileS, mediaLocation, fileDate, filePath;
728 728
729 temp.sprintf( "%d",i); 729 temp.sprintf( "%d",i);
730 temp = cfg.readEntry( temp,""); //reads currentFile 730 temp = cfg.readEntry( temp,""); //reads currentFile
731 filePath = cfg.readEntry( temp,""); //currentFileName 731 filePath = cfg.readEntry( temp,""); //currentFileName
732 732
733 QFileInfo info(filePath); 733 QFileInfo info(filePath);
734 fileDate = info.lastModified().toString(); 734 fileDate = info.lastModified().toString();
735 735
736 fileS = cfg.readEntry( filePath, "0" );// file length in seconds 736 fileS = cfg.readEntry( filePath, "0" );// file length in seconds
737 mediaLocation = getStorage( filePath); 737 mediaLocation = getStorage( filePath);
738 if( info.exists()) { 738 if( info.exists()) {
739 item = new QListViewItem( ListView1, temp, fileS, mediaLocation, fileDate); 739 item = new QListViewItem( ListView1, temp, fileS, mediaLocation, fileDate);
740 item->setPixmap( 0, image0); 740 item->setPixmap( 0, image0);
741 if( currentFileName == filePath) 741 if( currentFileName == filePath)
742 ListView1->setSelected( item, true); 742 ListView1->setSelected( item, true);
743 } 743 }
744 } 744 }
745} 745}
746 746
747void QtRec::initConnections() { 747void QtRec::initConnections() {
748 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 748 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
749 749
750 connect( toBeginningButton, SIGNAL( pressed()), 750 connect( toBeginningButton, SIGNAL( pressed()),
751 this, SLOT( rewindPressed() )); 751 this, SLOT( rewindPressed() ));
752 connect( toBeginningButton, SIGNAL( released()), 752 connect( toBeginningButton, SIGNAL( released()),
753 this, SLOT( rewindReleased() )); 753 this, SLOT( rewindReleased() ));
754 connect( toEndButton, SIGNAL( pressed()), 754 connect( toEndButton, SIGNAL( pressed()),
755 this, SLOT( FastforwardPressed() )); 755 this, SLOT( FastforwardPressed() ));
756 connect( toEndButton, SIGNAL( released()), 756 connect( toEndButton, SIGNAL( released()),
757 this, SLOT( FastforwardReleased() )); 757 this, SLOT( FastforwardReleased() ));
758 connect( deleteSoundButton, SIGNAL(released()), 758 connect( deleteSoundButton, SIGNAL(released()),
759 this, SLOT( deleteSound() )); 759 this, SLOT( deleteSound() ));
760 connect( Stop_PushButton, SIGNAL(released()), 760 connect( Stop_PushButton, SIGNAL(released()),
761 this, SLOT( doPlayBtn() )); 761 this, SLOT( doPlayBtn() ));
762 connect( Rec_PushButton, SIGNAL(released()), 762 connect( Rec_PushButton, SIGNAL(released()),
763 this, SLOT( newSound() ) ); 763 this, SLOT( newSound() ) );
764 connect( TabWidget, SIGNAL( currentChanged( QWidget*)), 764 connect( TabWidget, SIGNAL( currentChanged(QWidget*)),
765 this, SLOT(thisTab(QWidget*) )); 765 this, SLOT(thisTab(QWidget*) ));
766 connect( OutputSlider, SIGNAL(sliderReleased()), 766 connect( OutputSlider, SIGNAL(sliderReleased()),
767 this, SLOT( changedOutVolume()) ); 767 this, SLOT( changedOutVolume()) );
768 connect( InputSlider, SIGNAL(sliderReleased()), 768 connect( InputSlider, SIGNAL(sliderReleased()),
769 this, SLOT( changedInVolume()) ); 769 this, SLOT( changedInVolume()) );
770 770
771 connect( sampleRateComboBox, SIGNAL(activated( int)), 771 connect( sampleRateComboBox, SIGNAL(activated(int)),
772 this, SLOT( changesamplerateCombo(int)) ); 772 this, SLOT( changesamplerateCombo(int)) );
773 connect( bitRateComboBox, SIGNAL(activated( int)), 773 connect( bitRateComboBox, SIGNAL(activated(int)),
774 this, SLOT( changebitrateCombo(int)) ); 774 this, SLOT( changebitrateCombo(int)) );
775 775
776 connect( directoryComboBox, SIGNAL(activated( int)), 776 connect( directoryComboBox, SIGNAL(activated(int)),
777 this, SLOT( changeDirCombo(int)) ); 777 this, SLOT( changeDirCombo(int)) );
778 connect( sizeLimitCombo, SIGNAL(activated( int)), 778 connect( sizeLimitCombo, SIGNAL(activated(int)),
779 this, SLOT( changeSizeLimitCombo(int)) ); 779 this, SLOT( changeSizeLimitCombo(int)) );
780 780
781 connect( stereoCheckBox, SIGNAL(toggled( bool)), 781 connect( stereoCheckBox, SIGNAL(toggled(bool)),
782 this, SLOT( changeStereoCheck(bool)) ); 782 this, SLOT( changeStereoCheck(bool)) );
783 783
784 connect( outMuteCheckBox, SIGNAL(toggled( bool)), 784 connect( outMuteCheckBox, SIGNAL(toggled(bool)),
785 this, SLOT( doVolMuting(bool)) ); 785 this, SLOT( doVolMuting(bool)) );
786 connect( inMuteCheckBox , SIGNAL(toggled( bool)), 786 connect( inMuteCheckBox , SIGNAL(toggled(bool)),
787 this, SLOT( doMicMuting(bool)) ); 787 this, SLOT( doMicMuting(bool)) );
788 788
789 connect( ListView1,SIGNAL(doubleClicked( QListViewItem*)), 789 connect( ListView1,SIGNAL(doubleClicked(QListViewItem*)),
790 this,SLOT( itClick(QListViewItem*))); 790 this,SLOT( itClick(QListViewItem*)));
791 connect( ListView1, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), 791 connect( ListView1, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
792 this,SLOT( listPressed(int, QListViewItem *, const QPoint&, int)) ); 792 this,SLOT( listPressed(int,QListViewItem*,const QPoint&,int)) );
793 connect( timeSlider, SIGNAL( sliderMoved( int)), 793 connect( timeSlider, SIGNAL( sliderMoved(int)),
794 this, SLOT( changeTimeSlider(int) )); 794 this, SLOT( changeTimeSlider(int) ));
795 connect( timeSlider, SIGNAL( sliderPressed( )), 795 connect( timeSlider, SIGNAL( sliderPressed()),
796 this, SLOT( timeSliderPressed() )); 796 this, SLOT( timeSliderPressed() ));
797 connect( timeSlider, SIGNAL( sliderReleased( )), 797 connect( timeSlider, SIGNAL( sliderReleased()),
798 this, SLOT( timeSliderReleased() )); 798 this, SLOT( timeSliderReleased() ));
799 connect( compressionCheckBox, SIGNAL( toggled(bool)), 799 connect( compressionCheckBox, SIGNAL( toggled(bool)),
800 this, SLOT( compressionSelected(bool))); 800 this, SLOT( compressionSelected(bool)));
801 connect( autoMuteCheckBox, SIGNAL( toggled(bool)), 801 connect( autoMuteCheckBox, SIGNAL( toggled(bool)),
802 this, SLOT( slotAutoMute(bool))); 802 this, SLOT( slotAutoMute(bool)));
803} 803}
804 804
805void QtRec::initConfig() { 805void QtRec::initConfig() {
806 int index, fred, i; 806 int index, fred, i;
807 Config cfg("OpieRec"); 807 Config cfg("OpieRec");
808 cfg.setGroup("Settings"); 808 cfg.setGroup("Settings");
809 809
810 index = cfg.readNumEntry("samplerate",22050); 810 index = cfg.readNumEntry("samplerate",22050);
811 bool ok; 811 bool ok;
812 812
813 for(int ws=0;ws<sampleRateComboBox->count();ws++) { 813 for(int ws=0;ws<sampleRateComboBox->count();ws++) {
814 fred = sampleRateComboBox->text(ws).toInt(&ok, 10); 814 fred = sampleRateComboBox->text(ws).toInt(&ok, 10);
815 if( index == fred) { 815 if( index == fred) {
816 filePara.sampleRate = fred; 816 filePara.sampleRate = fred;
817 sampleRateComboBox->setCurrentItem(ws); 817 sampleRateComboBox->setCurrentItem(ws);
818 } 818 }
819 } 819 }
820 820
821 i = cfg.readNumEntry("bitrate",16); 821 i = cfg.readNumEntry("bitrate",16);
822 if(i == 16) 822 if(i == 16)
823 bitRateComboBox->setCurrentItem( 1); 823 bitRateComboBox->setCurrentItem( 1);
824 elseif(i == 24) 824 elseif(i == 24)
825 bitRateComboBox->setCurrentItem( 2); 825 bitRateComboBox->setCurrentItem( 2);
826 elseif(i == 32) 826 elseif(i == 32)
827 bitRateComboBox->setCurrentItem( 3); 827 bitRateComboBox->setCurrentItem( 3);
828 else 828 else
829 bitRateComboBox->setCurrentItem( 0); 829 bitRateComboBox->setCurrentItem( 0);
830 830
831 filePara.resolution = i; 831 filePara.resolution = i;
832 832
833 i = cfg.readNumEntry("sizeLimit", 5 ); 833 i = cfg.readNumEntry("sizeLimit", 5 );
834 QString temp; 834 QString temp;
835 sizeLimitCombo->setCurrentItem((i/5)); 835 sizeLimitCombo->setCurrentItem((i/5));
836 836
837 stereoCheckBox->setChecked( cfg.readBoolEntry("stereo", 1)); 837 stereoCheckBox->setChecked( cfg.readBoolEntry("stereo", 1));
838 if( stereoCheckBox->isChecked()) { 838 if( stereoCheckBox->isChecked()) {
839 filePara.channels = 2; 839 filePara.channels = 2;
840 } else { 840 } else {
841 filePara.channels = 1; 841 filePara.channels = 1;
842 } 842 }
843 843
844 compressionCheckBox->setChecked( cfg.readBoolEntry("wavCompression",1)); 844 compressionCheckBox->setChecked( cfg.readBoolEntry("wavCompression",1));
845 if( compressionCheckBox->isChecked()) { 845 if( compressionCheckBox->isChecked()) {
846 bitRateComboBox->setEnabled(false); 846 bitRateComboBox->setEnabled(false);
847 bitRateComboBox->setCurrentItem(0); 847 bitRateComboBox->setCurrentItem(0);
848 filePara.resolution=16; 848 filePara.resolution=16;
849 } 849 }
850 850
851 autoMuteCheckBox->setChecked( cfg.readBoolEntry("useAutoMute",0)); 851 autoMuteCheckBox->setChecked( cfg.readBoolEntry("useAutoMute",0));
852 if( autoMuteCheckBox->isChecked()) 852 if( autoMuteCheckBox->isChecked())
853 slotAutoMute(true); 853 slotAutoMute(true);
854 else 854 else
855 slotAutoMute(false); 855 slotAutoMute(false);
856 856
857 Config cofg( "qpe"); 857 Config cofg( "qpe");
858 cofg.setGroup( "Volume"); 858 cofg.setGroup( "Volume");
859 outMuteCheckBox->setChecked( cofg.readBoolEntry( "Mute",0)); 859 outMuteCheckBox->setChecked( cofg.readBoolEntry( "Mute",0));
860 inMuteCheckBox->setChecked( cofg.readBoolEntry( "MicMute",0)); 860 inMuteCheckBox->setChecked( cofg.readBoolEntry( "MicMute",0));
861} 861}
862 862
863void QtRec::stop() { 863void QtRec::stop() {
864 qWarning("STOP"); 864 qWarning("STOP");
865 setRecordButton(false); 865 setRecordButton(false);
866 866
867 if( !recording) 867 if( !recording)
868 endPlaying(); 868 endPlaying();
869 else 869 else
870 endRecording(); 870 endRecording();
871 timeSlider->setValue(0); 871 timeSlider->setValue(0);
872} 872}
873 873
874void QtRec::doPlayBtn() { 874void QtRec::doPlayBtn() {
875 875
876 if(!stopped) { 876 if(!stopped) {
877 playLabel2->setText(tr("Play")); 877 playLabel2->setText(tr("Play"));
878 stop(); 878 stop();
879 } else { 879 } else {
880 if(ListView1->currentItem() == 0) return; 880 if(ListView1->currentItem() == 0) return;
881 playLabel2->setText(tr("Stop")); 881 playLabel2->setText(tr("Stop"));
882 currentFile = ListView1->currentItem()->text(0); 882 currentFile = ListView1->currentItem()->text(0);
883 start(); 883 start();
884 } 884 }
885} 885}
886 886
887void QtRec::start() { //play 887void QtRec::start() { //play
888 if( stopped) { 888 if( stopped) {
889 QPixmap image3( ( const char** ) image3_data ); 889 QPixmap image3( ( const char** ) image3_data );
890 Stop_PushButton->setPixmap( image3 ); 890 Stop_PushButton->setPixmap( image3 );
891 Stop_PushButton->setDown( true); 891 Stop_PushButton->setDown( true);
892 stopped = false; 892 stopped = false;
893 paused = false; 893 paused = false;
894 secCount = 1; 894 secCount = 1;
895 895
896 if( openPlayFile()) 896 if( openPlayFile())
897 if( setupAudio( false)) //recording is false 897 if( setupAudio( false)) //recording is false
898 doPlay(); 898 doPlay();
899 } 899 }
900} 900}
901 901
902bool QtRec::rec() { //record 902bool QtRec::rec() { //record
903 QString timeString; 903 QString timeString;
904 timeString.sprintf("%.0f", 0.0); 904 timeString.sprintf("%.0f", 0.0);
905 timeLabel->setText( timeString+ " seconds"); 905 timeLabel->setText( timeString+ " seconds");
906 if(!stopped) { 906 if(!stopped) {
907 monitoring = true; 907 monitoring = true;
908 return false; 908 return false;
909 } else { 909 } else {
910 secCount = 1; 910 secCount = 1;
911 playLabel2->setText(tr("Stop")); 911 playLabel2->setText(tr("Stop"));
912 monitoring = false; 912 monitoring = false;
913 setRecordButton( true); 913 setRecordButton( true);
914 914
915 if( setupAudio( true)) 915 if( setupAudio( true))
916 if(setUpFile()) { 916 if(setUpFile()) {
917 int fileSize = 0; 917 int fileSize = 0;
918 Config cfg("OpieRec"); 918 Config cfg("OpieRec");
919 cfg.setGroup("Settings"); 919 cfg.setGroup("Settings");
920// qDebug( "<<<<<<<Device bits %d, device rate %d, device channels %d", 920// qDebug( "<<<<<<<Device bits %d, device rate %d, device channels %d",
921// soundDevice->getDeviceBits(), 921// soundDevice->getDeviceBits(),
922// soundDevice->getDeviceRate(), 922// soundDevice->getDeviceRate(),
923// soundDevice->getDeviceChannels()); 923// soundDevice->getDeviceChannels());
924 924
925 //filePara.sampleRate = cfg.readNumEntry("samplerate", 22050); 925 //filePara.sampleRate = cfg.readNumEntry("samplerate", 22050);
926// qDebug("sample rate is %d", filePara.sampleRate); 926// qDebug("sample rate is %d", filePara.sampleRate);
927 filePara.SecondsToRecord = getCurrentSizeLimit(); 927 filePara.SecondsToRecord = getCurrentSizeLimit();
928 928
929// qDebug("size limit %d sec", filePara.SecondsToRecord); 929// qDebug("size limit %d sec", filePara.SecondsToRecord);
930 int diskSize = checkDiskSpace( (const QString &) wavFile->trackName()); 930 int diskSize = checkDiskSpace( (const QString &) wavFile->trackName());
931 931
932 if( filePara.SecondsToRecord == 0) { 932 if( filePara.SecondsToRecord == 0) {
933 fileSize = diskSize; 933 fileSize = diskSize;
934 } else if( filePara.format == WAVE_FORMAT_PCM) { 934 } else if( filePara.format == WAVE_FORMAT_PCM) {
935// qDebug("WAVE_FORMAT_PCM"); 935// qDebug("WAVE_FORMAT_PCM");
936 fileSize = (filePara.SecondsToRecord ) * filePara.channels 936 fileSize = (filePara.SecondsToRecord ) * filePara.channels
937 * filePara.sampleRate * ( filePara.resolution / 8) + 1000; 937 * filePara.sampleRate * ( filePara.resolution / 8) + 1000;
938 } else { 938 } else {
939// qDebug("WAVE_FORMAT_DVI_ADPCM"); 939// qDebug("WAVE_FORMAT_DVI_ADPCM");
940 fileSize = ((filePara.SecondsToRecord) * filePara.channels 940 fileSize = ((filePara.SecondsToRecord) * filePara.channels
941 * filePara.sampleRate * ( filePara.resolution / 8) ) / 4 + 250; 941 * filePara.sampleRate * ( filePara.resolution / 8) ) / 4 + 250;
942 } 942 }
943 943
944 filePara.samplesToRecord = fileSize; 944 filePara.samplesToRecord = fileSize;
945 qDebug("filesize should be %d, bits %d, rate %d", 945 qDebug("filesize should be %d, bits %d, rate %d",
946 filePara.samplesToRecord, filePara.resolution, filePara.sampleRate); 946 filePara.samplesToRecord, filePara.resolution, filePara.sampleRate);
947 if( paused) { 947 if( paused) {
948 paused = false; 948 paused = false;
949 } 949 }
950 // else { 950 // else {
951 qDebug("Setting timeslider %d", filePara.samplesToRecord); 951 qDebug("Setting timeslider %d", filePara.samplesToRecord);
952 // if(fileSize != 0) 952 // if(fileSize != 0)
953 timeSlider->setRange(0, filePara.samplesToRecord); 953 timeSlider->setRange(0, filePara.samplesToRecord);
954 // } 954 // }
955 955
956 if( diskSize < fileSize/1024) { 956 if( diskSize < fileSize/1024) {
957 QMessageBox::warning(this, 957 QMessageBox::warning(this,
958 tr("Low Disk Space"), 958 tr("Low Disk Space"),
959 tr("You are running low of\nrecording space\n" 959 tr("You are running low of\nrecording space\n"
960 "or a card isn't being recognized")); 960 "or a card isn't being recognized"));
961 stopped = true; //we need to be stopped 961 stopped = true; //we need to be stopped
962 stop(); 962 stop();
963 } else { 963 } else {
964 QString msg; 964 QString msg;
965 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); 965 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution);
966#ifdef DEV_VERSION 966#ifdef DEV_VERSION
967 setCaption( msg); 967 setCaption( msg);
968#endif 968#endif
969 filePara.fileName=currentFile.latin1(); 969 filePara.fileName=currentFile.latin1();
970 qDebug("Start recording thread"); 970 qDebug("Start recording thread");
971 stopped = false; 971 stopped = false;
972 972
973#ifdef THREADED 973#ifdef THREADED
974 pthread_t thread1; 974 pthread_t thread1;
975 pthread_create( &thread1, NULL, (void * (*)(void *))quickRec, NULL/* &*/); 975 pthread_create( &thread1, NULL, (void * (*)(void *))quickRec, NULL/* &*/);
976#endif 976#endif
977 toBeginningButton->setEnabled( false); 977 toBeginningButton->setEnabled( false);
978 toEndButton->setEnabled( false); 978 toEndButton->setEnabled( false);
979 979
980 startTimer(1000); 980 startTimer(1000);
981#ifndef THREADED 981#ifndef THREADED
982 quickRec(); 982 quickRec();
983#endif 983#endif
984 } 984 }
985 } //end setUpFile 985 } //end setUpFile
986 } //end setupAudio 986 } //end setupAudio
987 return true; 987 return true;
988} 988}
989/* 989/*
990 This happens when a tab is selected*/ 990 This happens when a tab is selected*/
991void QtRec::thisTab(QWidget* widg) { 991void QtRec::thisTab(QWidget* widg) {
992 if(widg != NULL) { 992 if(widg != NULL) {
993 int index = TabWidget->currentPageIndex(); 993 int index = TabWidget->currentPageIndex();
994 994
995 if(index == 0) { //file page 995 if(index == 0) { //file page
996 } 996 }
997 997
998 if(index == 1) { //control page 998 if(index == 1) { //control page
999 fillDirectoryCombo(); 999 fillDirectoryCombo();
1000// soundDevice->getOutVol(); 1000// soundDevice->getOutVol();
1001// soundDevice->getInVol(); 1001// soundDevice->getInVol();
1002 } 1002 }
1003 1003
1004 if( index==2) { //help page 1004 if( index==2) { //help page
1005 } 1005 }
1006 1006
1007 qApp->processEvents(); 1007 qApp->processEvents();
1008 update(); 1008 update();
1009 } 1009 }
1010} 1010}
1011 1011
1012void QtRec::getOutVol( ) { 1012void QtRec::getOutVol( ) {
1013 filePara.outVol = soundDevice->getOutVolume(); 1013 filePara.outVol = soundDevice->getOutVolume();
1014// qDebug("out vol %d", filePara.outVol); 1014// qDebug("out vol %d", filePara.outVol);
1015 OutputSlider->setValue( -filePara.outVol); 1015 OutputSlider->setValue( -filePara.outVol);
1016} 1016}
1017 1017
1018void QtRec::getInVol() { 1018void QtRec::getInVol() {
1019 filePara.inVol = soundDevice->getInVolume(); 1019 filePara.inVol = soundDevice->getInVolume();
1020// qDebug("in vol %d", filePara.inVol); 1020// qDebug("in vol %d", filePara.inVol);
1021 InputSlider->setValue( -filePara.inVol); 1021 InputSlider->setValue( -filePara.inVol);
1022} 1022}
1023 1023
1024void QtRec::changedOutVolume() { 1024void QtRec::changedOutVolume() {
1025 soundDevice->changedOutVolume( -OutputSlider->value()); 1025 soundDevice->changedOutVolume( -OutputSlider->value());
1026} 1026}
1027 1027
1028void QtRec::changedInVolume( ) { 1028void QtRec::changedInVolume( ) {
1029 soundDevice->changedInVolume( -InputSlider->value()); 1029 soundDevice->changedInVolume( -InputSlider->value());
1030} 1030}
1031 1031
1032 1032
1033bool QtRec::setupAudio( bool b) { 1033bool QtRec::setupAudio( bool b) {
1034 bool ok; 1034 bool ok;
1035 int sampleformat, stereo, flags; 1035 int sampleformat, stereo, flags;
1036 QString dspString, mixerString; 1036 QString dspString, mixerString;
1037 1037
1038 filePara.resolution = bitRateComboBox->currentText().toInt( &ok,10); //16 1038 filePara.resolution = bitRateComboBox->currentText().toInt( &ok,10); //16
1039 1039
1040 if( !b) { 1040 if( !b) {
1041// we want to play 1041// we want to play
1042#ifdef PDAUDIO //ALSA 1042#ifdef PDAUDIO //ALSA
1043 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) { 1043 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) {
1044 sampleformat = SND_PCM_FORMAT_S16; 1044 sampleformat = SND_PCM_FORMAT_S16;
1045 filePara.resolution = 16; 1045 filePara.resolution = 16;
1046 } else if( filePara.resolution == 24 || compressionCheckBox->isChecked() ) { 1046 } else if( filePara.resolution == 24 || compressionCheckBox->isChecked() ) {
1047 sampleformat = SND_PCM_FORMAT_S24; 1047 sampleformat = SND_PCM_FORMAT_S24;
1048 filePara.resolution = 24; 1048 filePara.resolution = 24;
1049 } else if( filePara.resolution == 32 || compressionCheckBox->isChecked() ) { 1049 } else if( filePara.resolution == 32 || compressionCheckBox->isChecked() ) {
1050 sampleformat = SND_PCM_FORMAT_S32; 1050 sampleformat = SND_PCM_FORMAT_S32;
1051 filePara.resolution = 32; 1051 filePara.resolution = 32;
1052 } else { 1052 } else {
1053 sampleformat = SND_PCM_FORMAT_U8; 1053 sampleformat = SND_PCM_FORMAT_U8;
1054 filePara.resolution = 8; 1054 filePara.resolution = 8;
1055 } 1055 }
1056#else 1056#else
1057// we want to play 1057// we want to play
1058 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) { 1058 if( filePara.resolution == 16 || compressionCheckBox->isChecked() ) {
1059 sampleformat = AFMT_S16_LE; 1059 sampleformat = AFMT_S16_LE;
1060 filePara.resolution = 16; 1060 filePara.resolution = 16;
1061 } else { 1061 } else {
1062 sampleformat = AFMT_U8; 1062 sampleformat = AFMT_U8;
1063 filePara.resolution = 8; 1063 filePara.resolution = 8;
1064 } 1064 }
1065#endif 1065#endif
1066 1066
1067 stereo = filePara.channels; 1067 stereo = filePara.channels;
1068 flags = O_WRONLY; 1068 flags = O_WRONLY;
1069 Config hwcfg("OpieRec"); 1069 Config hwcfg("OpieRec");
1070 hwcfg.setGroup("Hardware"); 1070 hwcfg.setGroup("Hardware");
1071 dspString = hwcfg.readEntry( "Audio", DSPSTROUT); 1071 dspString = hwcfg.readEntry( "Audio", DSPSTROUT);
1072 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXEROUT); 1072 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXEROUT);
1073 recording = false; 1073 recording = false;
1074 } else { // we want to record 1074 } else { // we want to record
1075 1075
1076#ifdef PDAUDIO //ALSA 1076#ifdef PDAUDIO //ALSA
1077 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16") 1077 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16")
1078 sampleformat = SND_PCM_FORMAT_S16; 1078 sampleformat = SND_PCM_FORMAT_S16;
1079 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "24") 1079 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "24")
1080 sampleformat = SND_PCM_FORMAT_S24; 1080 sampleformat = SND_PCM_FORMAT_S24;
1081 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "32") 1081 else if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "32")
1082 sampleformat = SND_PCM_FORMAT_S32; 1082 sampleformat = SND_PCM_FORMAT_S32;
1083 else 1083 else
1084 sampleformat = SND_PCM_FORMAT_U8; 1084 sampleformat = SND_PCM_FORMAT_U8;
1085 1085
1086#else 1086#else
1087 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16") 1087 if( !bitRateComboBox->isEnabled() || bitRateComboBox->currentText() == "16")
1088 sampleformat = AFMT_S16_LE; 1088 sampleformat = AFMT_S16_LE;
1089 else 1089 else
1090 sampleformat = AFMT_U8; 1090 sampleformat = AFMT_U8;
1091 1091
1092 if( !compressionCheckBox->isChecked()) { 1092 if( !compressionCheckBox->isChecked()) {
1093 filePara.format = WAVE_FORMAT_PCM; 1093 filePara.format = WAVE_FORMAT_PCM;
1094// qDebug("WAVE_FORMAT_PCM"); 1094// qDebug("WAVE_FORMAT_PCM");
1095 } else { 1095 } else {
1096 filePara.format = WAVE_FORMAT_DVI_ADPCM; 1096 filePara.format = WAVE_FORMAT_DVI_ADPCM;
1097 sampleformat = AFMT_S16_LE; 1097 sampleformat = AFMT_S16_LE;
1098// qDebug("WAVE_FORMAT_DVI_ADPCM"); 1098// qDebug("WAVE_FORMAT_DVI_ADPCM");
1099 } 1099 }
1100#endif 1100#endif
1101 1101
1102 stereo = filePara.channels; 1102 stereo = filePara.channels;
1103// filePara.sampleRate = sampleRateComboBox->currentText().toInt( &ok,10);//44100; 1103// filePara.sampleRate = sampleRateComboBox->currentText().toInt( &ok,10);//44100;
1104 flags= O_RDWR; 1104 flags= O_RDWR;
1105// flags= O_RDONLY; 1105// flags= O_RDONLY;
1106 Config hwcfg("OpieRec"); 1106 Config hwcfg("OpieRec");
1107 hwcfg.setGroup("Hardware"); 1107 hwcfg.setGroup("Hardware");
1108 dspString = hwcfg.readEntry( "Audio", DSPSTRIN); 1108 dspString = hwcfg.readEntry( "Audio", DSPSTRIN);
1109 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXERIN); 1109 mixerString = hwcfg.readEntry( "Mixer", DSPSTRMIXERIN);
1110 recording = true; 1110 recording = true;
1111 } 1111 }
1112 1112
1113 // if(soundDevice) delete soundDevice; 1113 // if(soundDevice) delete soundDevice;
1114 qDebug("<<<<<<<<<<<<<<<<<<<open dsp %d %d %d", filePara.sampleRate, filePara.channels, sampleformat); 1114 qDebug("<<<<<<<<<<<<<<<<<<<open dsp %d %d %d", filePara.sampleRate, filePara.channels, sampleformat);
1115 qWarning("change waveform settings"); 1115 qWarning("change waveform settings");
1116 waveform->changeSettings( filePara.sampleRate, filePara.channels ); 1116 waveform->changeSettings( filePara.sampleRate, filePara.channels );
1117 1117
1118 soundDevice = new Device( this, dspString, mixerString, b); 1118 soundDevice = new Device( this, dspString, mixerString, b);
1119// soundDevice->openDsp(); 1119// soundDevice->openDsp();
1120 soundDevice->reset(); 1120 soundDevice->reset();
1121 1121
1122 qDebug("device has been made %d", soundDevice->sd); 1122 qDebug("device has been made %d", soundDevice->sd);
1123 1123
1124 ////////////////// <<<<<<<<<<<<>>>>>>>>>>>> 1124 ////////////////// <<<<<<<<<<<<>>>>>>>>>>>>
1125 soundDevice->setDeviceFormat( sampleformat); 1125 soundDevice->setDeviceFormat( sampleformat);
1126 soundDevice->setDeviceChannels( filePara.channels); 1126 soundDevice->setDeviceChannels( filePara.channels);
1127 soundDevice->setDeviceRate( filePara.sampleRate); 1127 soundDevice->setDeviceRate( filePara.sampleRate);
1128 soundDevice->getDeviceFragSize(); 1128 soundDevice->getDeviceFragSize();
1129#ifdef QT_QWS_EBX 1129#ifdef QT_QWS_EBX
1130 int frag = FRAGSIZE; 1130 int frag = FRAGSIZE;
1131 soundDevice->setFragSize( frag); 1131 soundDevice->setFragSize( frag);
1132 soundDevice->getDeviceFragSize(); 1132 soundDevice->getDeviceFragSize();
1133#endif 1133#endif
1134 ///////////////// 1134 /////////////////
1135 filePara.sd = soundDevice->sd; 1135 filePara.sd = soundDevice->sd;
1136 1136
1137 if ( filePara.sd == -1) { 1137 if ( filePara.sd == -1) {
1138 1138
1139 monitoring = false; 1139 monitoring = false;
1140 stopped = true; 1140 stopped = true;
1141 update(); 1141 update();
1142 setCaption( tr( "OpieRecord " )+ QString::number(VERSION) ); 1142 setCaption( tr( "OpieRecord " )+ QString::number(VERSION) );
1143 return false; 1143 return false;
1144 } 1144 }
1145 if(autoMute) 1145 if(autoMute)
1146 doMute(false); 1146 doMute(false);
1147 1147
1148 return true; 1148 return true;
1149} 1149}
1150 1150
1151 1151
1152bool QtRec::setUpFile() { //setup file for recording 1152bool QtRec::setUpFile() { //setup file for recording
1153// qDebug("Setting up wavfile"); 1153// qDebug("Setting up wavfile");
1154// if(wavFile) delete wavFile; 1154// if(wavFile) delete wavFile;
1155 wavFile = new WavFile( this, (const QString &)"", 1155 wavFile = new WavFile( this, (const QString &)"",
1156 true, 1156 true,
1157 filePara.sampleRate, 1157 filePara.sampleRate,
1158 filePara.channels, 1158 filePara.channels,
1159 filePara.resolution, 1159 filePara.resolution,
1160 filePara.format); 1160 filePara.format);
1161 1161
1162 filePara.fd = wavFile->wavHandle(); 1162 filePara.fd = wavFile->wavHandle();
1163 if(filePara.fd == -1) { 1163 if(filePara.fd == -1) {
1164 return false; 1164 return false;
1165 } else { 1165 } else {
1166// filePara.channels=1; 1166// filePara.channels=1;
1167 } 1167 }
1168 return true; 1168 return true;
1169} 1169}
1170 1170
1171/// <<<<<<<<<<<<<<<< PLAY >>>>>>>>>>>>>>>>>>> 1171/// <<<<<<<<<<<<<<<< PLAY >>>>>>>>>>>>>>>>>>>
1172bool QtRec::doPlay() { 1172bool QtRec::doPlay() {
1173 1173
1174 if( !paused) { 1174 if( !paused) {
1175 total = 0; 1175 total = 0;
1176 filePara.numberOfRecordedSeconds = 0; 1176 filePara.numberOfRecordedSeconds = 0;
1177 } else { 1177 } else {
1178 paused = false; 1178 paused = false;
1179 secCount = (int)filePara.numberOfRecordedSeconds; 1179 secCount = (int)filePara.numberOfRecordedSeconds;
1180 } 1180 }
1181 playing = true; 1181 playing = true;
1182 stopped = false; 1182 stopped = false;
1183 recording = false; 1183 recording = false;
1184 1184
1185 QString num; 1185 QString num;
1186 qDebug( "Play number of samples %d", filePara.numberSamples); 1186 qDebug( "Play number of samples %d", filePara.numberSamples);
1187 1187
1188// timeSlider->setRange( 0, filePara.numberSamples); 1188// timeSlider->setRange( 0, filePara.numberSamples);
1189 1189
1190 timeString.sprintf("%f", filePara.numberOfRecordedSeconds); 1190 timeString.sprintf("%f", filePara.numberOfRecordedSeconds);
1191 timeLabel->setText( timeString+ tr(" seconds")); 1191 timeLabel->setText( timeString+ tr(" seconds"));
1192 1192
1193 QString msg; 1193 QString msg;
1194 msg.sprintf("%d, %d, %d", 1194 msg.sprintf("%d, %d, %d",
1195 filePara.sampleRate, 1195 filePara.sampleRate,
1196 filePara.channels, 1196 filePara.channels,
1197 filePara.resolution); 1197 filePara.resolution);
1198#ifdef DEV_VERSION 1198#ifdef DEV_VERSION
1199 setCaption( msg); 1199 setCaption( msg);
1200#endif 1200#endif
1201 1201
1202 startTimer( 1000); 1202 startTimer( 1000);
1203#ifdef THREADED 1203#ifdef THREADED
1204 pthread_t thread2; 1204 pthread_t thread2;
1205 pthread_create( &thread2, NULL, (void * (*)(void *))playIt, NULL/* &*/); 1205 pthread_create( &thread2, NULL, (void * (*)(void *))playIt, NULL/* &*/);
1206#endif 1206#endif
1207 1207
1208 toBeginningButton->setEnabled( false); 1208 toBeginningButton->setEnabled( false);
1209 toEndButton->setEnabled( false); 1209 toEndButton->setEnabled( false);
1210#ifndef THREADED 1210#ifndef THREADED
1211 playIt(); 1211 playIt();
1212#endif 1212#endif
1213 return true; 1213 return true;
1214} 1214}
1215 1215
1216 1216
1217void QtRec::changebitrateCombo(int i) { 1217void QtRec::changebitrateCombo(int i) {
1218 Config cfg("OpieRec"); 1218 Config cfg("OpieRec");
1219 cfg.setGroup("Settings"); 1219 cfg.setGroup("Settings");
1220 int bits = 0; 1220 int bits = 0;
1221 if( i == 1) { bits = 16; } 1221 if( i == 1) { bits = 16; }
1222 else if( i == 2) { bits = 24; } 1222 else if( i == 2) { bits = 24; }
1223 else if( i == 3) { bits = 32; } 1223 else if( i == 3) { bits = 32; }
1224 else { bits=8; } 1224 else { bits=8; }
1225 cfg.writeEntry("bitrate", bits); 1225 cfg.writeEntry("bitrate", bits);
1226 filePara.resolution = bits; 1226 filePara.resolution = bits;
1227 cfg.write(); 1227 cfg.write();
1228} 1228}
1229 1229
1230void QtRec::changesamplerateCombo(int i) { 1230void QtRec::changesamplerateCombo(int i) {
1231 Config cfg("OpieRec"); 1231 Config cfg("OpieRec");
1232 cfg.setGroup("Settings"); 1232 cfg.setGroup("Settings");
1233 int rate=0; 1233 int rate=0;
1234 bool ok; 1234 bool ok;
1235 rate = sampleRateComboBox->text(i).toInt(&ok, 10); 1235 rate = sampleRateComboBox->text(i).toInt(&ok, 10);
1236 cfg.writeEntry( "samplerate",rate); 1236 cfg.writeEntry( "samplerate",rate);
1237 filePara.sampleRate=rate; 1237 filePara.sampleRate=rate;
1238 qDebug( "Change sample rate %d", rate); 1238 qDebug( "Change sample rate %d", rate);
1239 cfg.write(); 1239 cfg.write();
1240} 1240}
1241 1241
1242 1242
1243void QtRec::changeDirCombo(int index) { 1243void QtRec::changeDirCombo(int index) {
1244 Config cfg("OpieRec"); 1244 Config cfg("OpieRec");
1245 cfg.setGroup("Settings"); 1245 cfg.setGroup("Settings");
1246 QString sName = directoryComboBox->text(index); 1246 QString sName = directoryComboBox->text(index);
1247 1247
1248 StorageInfo storageInfo; 1248 StorageInfo storageInfo;
1249 const QList<FileSystem> &fs = storageInfo.fileSystems(); 1249 const QList<FileSystem> &fs = storageInfo.fileSystems();
1250 QListIterator<FileSystem> it ( fs ); 1250 QListIterator<FileSystem> it ( fs );
1251 QString storage; 1251 QString storage;
1252 for( ; it.current(); ++it ){ 1252 for( ; it.current(); ++it ){
1253 if( sName == (*it)->name()+" "+ (*it)->path() || 1253 if( sName == (*it)->name()+" "+ (*it)->path() ||
1254 (*it)->name() == sName ) { 1254 (*it)->name() == sName ) {
1255 const QString path = (*it)->path(); 1255 const QString path = (*it)->path();
1256 recDir = path; 1256 recDir = path;
1257 cfg.writeEntry("directory", recDir); 1257 cfg.writeEntry("directory", recDir);
1258 qDebug("new rec dir "+recDir); 1258 qDebug("new rec dir "+recDir);
1259 } 1259 }
1260 } 1260 }
1261 cfg.write(); 1261 cfg.write();
1262} 1262}
1263 1263
1264 1264
1265void QtRec::changeSizeLimitCombo(int) { 1265void QtRec::changeSizeLimitCombo(int) {
1266 Config cfg("OpieRec"); 1266 Config cfg("OpieRec");
1267 cfg.setGroup("Settings"); 1267 cfg.setGroup("Settings");
1268 cfg.writeEntry("sizeLimit", getCurrentSizeLimit() ); 1268 cfg.writeEntry("sizeLimit", getCurrentSizeLimit() );
1269 cfg.write(); 1269 cfg.write();
1270} 1270}
1271 1271
1272void QtRec::newSound() { 1272void QtRec::newSound() {
1273 if( !rec()) { 1273 if( !rec()) {
1274 endRecording(); 1274 endRecording();
1275 deleteSound(); 1275 deleteSound();
1276 } 1276 }
1277} 1277}
1278 1278
1279void QtRec::itClick(QListViewItem *item) { 1279void QtRec::itClick(QListViewItem *item) {
1280 currentFile = item->text(0); 1280 currentFile = item->text(0);
1281 setCaption("OpieRecord "+currentFile); 1281 setCaption("OpieRecord "+currentFile);
1282} 1282}
1283 1283
1284void QtRec::deleteSound() { 1284void QtRec::deleteSound() {
1285 Config cfg("OpieRec"); 1285 Config cfg("OpieRec");
1286 cfg.setGroup("Sounds"); 1286 cfg.setGroup("Sounds");
1287 if( ListView1->currentItem() == NULL) 1287 if( ListView1->currentItem() == NULL)
1288 return; 1288 return;
1289#ifndef DEV_VERSION 1289#ifndef DEV_VERSION
1290 switch ( QMessageBox::warning(this,tr("Delete"), 1290 switch ( QMessageBox::warning(this,tr("Delete"),
1291 tr("Do you really want to <font size=+2><B>DELETE</B></font>\nthe selected file?"), 1291 tr("Do you really want to <font size=+2><B>DELETE</B></font>\nthe selected file?"),
1292 tr("Yes"),tr("No"),0,1,1) ) { 1292 tr("Yes"),tr("No"),0,1,1) ) {
1293 case 0: 1293 case 0:
1294#endif 1294#endif
1295 { 1295 {
1296 QString file = ListView1->currentItem()->text(0); 1296 QString file = ListView1->currentItem()->text(0);
1297 QString fileName; 1297 QString fileName;
1298 fileName = cfg.readEntry( file, ""); 1298 fileName = cfg.readEntry( file, "");
1299 QFile f( fileName); 1299 QFile f( fileName);
1300 if( f.exists()) 1300 if( f.exists())
1301 if( !f.remove()) 1301 if( !f.remove())
1302 QMessageBox::message( tr("Error"), tr("Could not remove file.")); 1302 QMessageBox::message( tr("Error"), tr("Could not remove file."));
1303 1303
1304 int nFiles = cfg.readNumEntry( "NumberofFiles",0); 1304 int nFiles = cfg.readNumEntry( "NumberofFiles",0);
1305 bool found = false; 1305 bool found = false;
1306 for(int i=0;i<nFiles+1;i++) { 1306 for(int i=0;i<nFiles+1;i++) {
1307 1307
1308 if( cfg.readEntry( QString::number(i),"").find( file,0,true) != -1) { 1308 if( cfg.readEntry( QString::number(i),"").find( file,0,true) != -1) {
1309 found = true; 1309 found = true;
1310 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),"")); 1310 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),""));
1311 } 1311 }
1312 if(found) 1312 if(found)
1313 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),"")); 1313 cfg.writeEntry( QString::number(i), cfg.readEntry( QString::number(i+1),""));
1314 } 1314 }
1315 1315
1316 cfg.removeEntry( cfg.readEntry( file)); 1316 cfg.removeEntry( cfg.readEntry( file));
1317 cfg.removeEntry( file); 1317 cfg.removeEntry( file);
1318 cfg.writeEntry( "NumberofFiles", nFiles-1); 1318 cfg.writeEntry( "NumberofFiles", nFiles-1);
1319 cfg.write(); 1319 cfg.write();
1320 1320
1321 ListView1->takeItem( ListView1->currentItem() ); 1321 ListView1->takeItem( ListView1->currentItem() );
1322 delete ListView1->currentItem(); 1322 delete ListView1->currentItem();
1323 1323
1324 ListView1->clear(); 1324 ListView1->clear();
1325 ListView1->setSelected( ListView1->firstChild(), true); 1325 ListView1->setSelected( ListView1->firstChild(), true);
1326 initIconView(); 1326 initIconView();
1327 update(); 1327 update();
1328 } 1328 }
1329#ifndef DEV_VERSION 1329#ifndef DEV_VERSION
1330 }; 1330 };
1331#endif 1331#endif
1332 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); 1332 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
1333 1333
1334} 1334}
1335 1335
1336void QtRec::keyPressEvent( QKeyEvent *e) { 1336void QtRec::keyPressEvent( QKeyEvent *e) {
1337 1337
1338 switch ( e->key() ) { 1338 switch ( e->key() ) {
1339 // case Key_F1: 1339 // case Key_F1:
1340 // if(stopped && !recording) 1340 // if(stopped && !recording)
1341 // newSound(); 1341 // newSound();
1342 // else 1342 // else
1343 // stop(); 1343 // stop();
1344 // break; 1344 // break;
1345 // case Key_F2: { 1345 // case Key_F2: {
1346 // if( !e->isAutoRepeat()) 1346 // if( !e->isAutoRepeat())
1347 // rewindPressed(); 1347 // rewindPressed();
1348 // } 1348 // }
1349 // break; 1349 // break;
1350 // case Key_F3: { 1350 // case Key_F3: {
1351 // if( !e->isAutoRepeat()) 1351 // if( !e->isAutoRepeat())
1352 // FastforwardPressed(); 1352 // FastforwardPressed();
1353 // } 1353 // }
1354 // break; 1354 // break;
1355 1355
1356 ////////////////////////////// Zaurus keys 1356 ////////////////////////////// Zaurus keys
1357 case Key_F9: //activity 1357 case Key_F9: //activity
1358 break; 1358 break;
1359 case Key_F10: //contacts 1359 case Key_F10: //contacts
1360 break; 1360 break;
1361 case Key_F11: //menu 1361 case Key_F11: //menu
1362 break; 1362 break;
1363 case Key_F12: //home 1363 case Key_F12: //home
1364 break; 1364 break;
1365 case Key_F13: //mail 1365 case Key_F13: //mail
1366 break; 1366 break;
1367 case Key_Space: 1367 case Key_Space:
1368 break; 1368 break;
1369 case Key_Delete: 1369 case Key_Delete:
1370 break; 1370 break;
1371 case Key_Up: 1371 case Key_Up:
1372 // stop(); 1372 // stop();
1373 break; 1373 break;
1374 case Key_Down: 1374 case Key_Down:
1375 // newSound(); 1375 // newSound();
1376 break; 1376 break;
1377 case Key_Left: { 1377 case Key_Left: {
1378 qDebug("rewinding"); 1378 qDebug("rewinding");
1379 if( !e->isAutoRepeat()) 1379 if( !e->isAutoRepeat())
1380 rewindPressed(); 1380 rewindPressed();
1381 } 1381 }
1382 break; 1382 break;
1383 case Key_Right: { 1383 case Key_Right: {
1384 if( !e->isAutoRepeat()) 1384 if( !e->isAutoRepeat())
1385 FastforwardPressed(); 1385 FastforwardPressed();
1386 } 1386 }
1387 break; 1387 break;
1388 } 1388 }
1389} 1389}
1390 1390
1391void QtRec::keyReleaseEvent( QKeyEvent *e) { 1391void QtRec::keyReleaseEvent( QKeyEvent *e) {
1392 switch ( e->key() ) { 1392 switch ( e->key() ) {
1393 // case Key_F1: 1393 // case Key_F1:
1394 // if(stopped && !recording) 1394 // if(stopped && !recording)
1395 // newSound(); 1395 // newSound();
1396 // else 1396 // else
1397 // stop(); 1397 // stop();
1398 // break; 1398 // break;
1399 // case Key_F2: 1399 // case Key_F2:
1400 // rewindReleased(); 1400 // rewindReleased();
1401 // break; 1401 // break;
1402 // case Key_F3: 1402 // case Key_F3:
1403 // FastforwardReleased(); 1403 // FastforwardReleased();
1404 // break; 1404 // break;
1405 1405
1406 ////////////////////////////// Zaurus keys 1406 ////////////////////////////// Zaurus keys
1407 case Key_F9: //activity 1407 case Key_F9: //activity
1408 break; 1408 break;
1409 case Key_F10: //contacts 1409 case Key_F10: //contacts
1410 break; 1410 break;
1411 case Key_F11: //menu 1411 case Key_F11: //menu
1412 break; 1412 break;
1413 case Key_F12: //home 1413 case Key_F12: //home
1414 if(stopped) 1414 if(stopped)
1415 doPlayBtn(); 1415 doPlayBtn();
1416 else 1416 else
1417 stop(); 1417 stop();
1418 break; 1418 break;
1419 case Key_F13: //mail 1419 case Key_F13: //mail
1420 break; 1420 break;
1421 case Key_Space: 1421 case Key_Space:
1422 if(stopped && !recording) 1422 if(stopped && !recording)
1423 newSound(); 1423 newSound();
1424 else 1424 else
1425 stop(); 1425 stop();
1426 break; 1426 break;
1427 case Key_Delete: 1427 case Key_Delete:
1428 deleteSound(); 1428 deleteSound();
1429 break; 1429 break;
1430 case Key_Up: 1430 case Key_Up:
1431 // stop(); 1431 // stop();
1432 qDebug("Up"); 1432 qDebug("Up");
1433 break; 1433 break;
1434 case Key_Down: 1434 case Key_Down:
1435 // start(); 1435 // start();
1436 // qDebug("Down"); 1436 // qDebug("Down");
1437 // newSound(); 1437 // newSound();
1438 break; 1438 break;
1439 case Key_Left: 1439 case Key_Left:
1440 qDebug("Left"); 1440 qDebug("Left");
1441 rewindReleased(); 1441 rewindReleased();
1442 break; 1442 break;
1443 case Key_Right: 1443 case Key_Right:
1444 qDebug("Right"); 1444 qDebug("Right");
1445 FastforwardReleased(); 1445 FastforwardReleased();
1446 break; 1446 break;
1447 } 1447 }
1448} 1448}
1449 1449
1450void QtRec::endRecording() { 1450void QtRec::endRecording() {
1451 monitoring = false; 1451 monitoring = false;
1452 recording = false; 1452 recording = false;
1453 stopped = true; 1453 stopped = true;
1454 waveform->reset(); 1454 waveform->reset();
1455 setRecordButton( false); 1455 setRecordButton( false);
1456 1456
1457 toBeginningButton->setEnabled( true); 1457 toBeginningButton->setEnabled( true);
1458 toEndButton->setEnabled( true); 1458 toEndButton->setEnabled( true);
1459 1459
1460 killTimers(); 1460 killTimers();
1461 1461
1462 if(autoMute) 1462 if(autoMute)
1463 doMute( true); 1463 doMute( true);
1464 1464
1465 soundDevice->closeDevice( true); 1465 soundDevice->closeDevice( true);
1466 1466
1467 if( wavFile->track.isOpen()) { 1467 if( wavFile->track.isOpen()) {
1468 wavFile->adjustHeaders( filePara.fd, filePara.numberSamples); 1468 wavFile->adjustHeaders( filePara.fd, filePara.numberSamples);
1469 // soundDevice->sd=-1; 1469 // soundDevice->sd=-1;
1470 filePara.numberSamples = 0; 1470 filePara.numberSamples = 0;
1471 // filePara.sd=-1; 1471 // filePara.sd=-1;
1472 wavFile->closeFile(); 1472 wavFile->closeFile();
1473 filePara.fd=0; 1473 filePara.fd=0;
1474 1474
1475 if( wavFile->isTempFile()) { 1475 if( wavFile->isTempFile()) {
1476// move tmp file to regular file 1476// move tmp file to regular file
1477 QString cmd; 1477 QString cmd;
1478 cmd.sprintf("mv "+ wavFile->trackName() + " " + wavFile->currentFileName); 1478 cmd.sprintf("mv "+ wavFile->trackName() + " " + wavFile->currentFileName);
1479// qDebug("moving tmp file to "+currentFileName); 1479// qDebug("moving tmp file to "+currentFileName);
1480 system( cmd.latin1()); 1480 system( cmd.latin1());
1481 } 1481 }
1482 1482
1483 qDebug("Just moved " + wavFile->currentFileName); 1483 qDebug("Just moved " + wavFile->currentFileName);
1484 Config cfg("OpieRec"); 1484 Config cfg("OpieRec");
1485 cfg.setGroup("Sounds"); 1485 cfg.setGroup("Sounds");
1486 1486
1487 int nFiles = cfg.readNumEntry( "NumberofFiles",0); 1487 int nFiles = cfg.readNumEntry( "NumberofFiles",0);
1488 1488
1489 currentFile = QFileInfo( wavFile->currentFileName).fileName(); 1489 currentFile = QFileInfo( wavFile->currentFileName).fileName();
1490 currentFile = currentFile.left( currentFile.length() - 4); 1490 currentFile = currentFile.left( currentFile.length() - 4);
1491 1491
1492 cfg.writeEntry( "NumberofFiles", nFiles + 1); 1492 cfg.writeEntry( "NumberofFiles", nFiles + 1);
1493 cfg.writeEntry( QString::number( nFiles + 1), currentFile); 1493 cfg.writeEntry( QString::number( nFiles + 1), currentFile);
1494 cfg.writeEntry( currentFile, wavFile->currentFileName); 1494 cfg.writeEntry( currentFile, wavFile->currentFileName);
1495 1495
1496 QString time; 1496 QString time;
1497 time.sprintf("%.2f", filePara.numberOfRecordedSeconds); 1497 time.sprintf("%.2f", filePara.numberOfRecordedSeconds);
1498 cfg.writeEntry( wavFile->currentFileName, time ); 1498 cfg.writeEntry( wavFile->currentFileName, time );
1499// qDebug("writing config numberOfRecordedSeconds "+time); 1499// qDebug("writing config numberOfRecordedSeconds "+time);
1500 1500
1501 cfg.write(); 1501 cfg.write();
1502 qDebug("finished recording"); 1502 qDebug("finished recording");
1503 timeLabel->setText(""); 1503 timeLabel->setText("");
1504 } 1504 }
1505 1505
1506 if(soundDevice) delete soundDevice; 1506 if(soundDevice) delete soundDevice;
1507 1507
1508 timeSlider->setValue(0); 1508 timeSlider->setValue(0);
1509 initIconView(); 1509 initIconView();
1510 selectItemByName( currentFile); 1510 selectItemByName( currentFile);
1511} 1511}
1512 1512
1513void QtRec::endPlaying() { 1513void QtRec::endPlaying() {
1514 monitoring = false; 1514 monitoring = false;
1515 recording = false; 1515 recording = false;
1516 playing = false; 1516 playing = false;
1517 stopped = true; 1517 stopped = true;
1518 waveform->reset(); 1518 waveform->reset();
1519// errorStop(); 1519// errorStop();
1520// qDebug("end playing"); 1520// qDebug("end playing");
1521 setRecordButton( false); 1521 setRecordButton( false);
1522 1522
1523 toBeginningButton->setEnabled( true); 1523 toBeginningButton->setEnabled( true);
1524 toEndButton->setEnabled( true); 1524 toEndButton->setEnabled( true);
1525 1525
1526 if(autoMute) 1526 if(autoMute)
1527 doMute( true); 1527 doMute( true);
1528 1528
1529 soundDevice->closeDevice( false); 1529 soundDevice->closeDevice( false);
1530 soundDevice->sd = -1; 1530 soundDevice->sd = -1;
1531 // if(soundDevice) delete soundDevice; 1531 // if(soundDevice) delete soundDevice;
1532// qDebug("file and sound device closed"); 1532// qDebug("file and sound device closed");
1533 timeLabel->setText(""); 1533 timeLabel->setText("");
1534 total = 0; 1534 total = 0;
1535 filePara.numberSamples = 0; 1535 filePara.numberSamples = 0;
1536 filePara.sd = -1; 1536 filePara.sd = -1;
1537// wavFile->closeFile(); 1537// wavFile->closeFile();
1538 filePara.fd = 0; 1538 filePara.fd = 0;
1539// if(wavFile) delete wavFile; //this crashes 1539// if(wavFile) delete wavFile; //this crashes
1540 1540
1541// qDebug("track closed"); 1541// qDebug("track closed");
1542 killTimers(); 1542 killTimers();
1543 qWarning("reset slider"); 1543 qWarning("reset slider");
1544 timeSlider->setValue(0); 1544 timeSlider->setValue(0);
1545 1545
1546 if(soundDevice) delete soundDevice; 1546 if(soundDevice) delete soundDevice;
1547 1547
1548} 1548}
1549 1549
1550bool QtRec::openPlayFile() { 1550bool QtRec::openPlayFile() {
1551 1551
1552 qApp->processEvents(); 1552 qApp->processEvents();
1553 if( currentFile.isEmpty()) { 1553 if( currentFile.isEmpty()) {
1554 QMessageBox::message(tr("Opierec"),tr("Please select file to play")); 1554 QMessageBox::message(tr("Opierec"),tr("Please select file to play"));
1555 endPlaying(); 1555 endPlaying();
1556 return false; 1556 return false;
1557 } 1557 }
1558 QString currentFileName; 1558 QString currentFileName;
1559 Config cfg("OpieRec"); 1559 Config cfg("OpieRec");
1560 cfg.setGroup("Sounds"); 1560 cfg.setGroup("Sounds");
1561 int nFiles = cfg.readNumEntry( "NumberofFiles", 0); 1561 int nFiles = cfg.readNumEntry( "NumberofFiles", 0);
1562 for(int i=0;i<nFiles+1;i++) { //look for file 1562 for(int i=0;i<nFiles+1;i++) { //look for file
1563 if( cfg.readEntry( QString::number(i),"").find( currentFile,0,true) != -1) { 1563 if( cfg.readEntry( QString::number(i),"").find( currentFile,0,true) != -1) {
1564 currentFileName = cfg.readEntry( currentFile, "" ); 1564 currentFileName = cfg.readEntry( currentFile, "" );
1565 qDebug("opening for play: " + currentFileName); 1565 qDebug("opening for play: " + currentFileName);
1566 } 1566 }
1567 } 1567 }
1568 wavFile = new WavFile(this, 1568 wavFile = new WavFile(this,
1569 currentFileName, 1569 currentFileName,
1570 false); 1570 false);
1571 filePara.fd = wavFile->wavHandle(); 1571 filePara.fd = wavFile->wavHandle();
1572 if(filePara.fd == -1) { 1572 if(filePara.fd == -1) {
1573 // if(!track.open(IO_ReadOnly)) { 1573 // if(!track.open(IO_ReadOnly)) {
1574 QString errorMsg = (QString)strerror(errno); 1574 QString errorMsg = (QString)strerror(errno);
1575 monitoring = false; 1575 monitoring = false;
1576 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) ); 1576 setCaption( tr( "OpieRecord " ) + QString::number(VERSION) );
1577 QMessageBox::message(tr("Note"), tr("Could not open audio file.\n") 1577 QMessageBox::message(tr("Note"), tr("Could not open audio file.\n")
1578 + errorMsg + "\n" + currentFile); 1578 + errorMsg + "\n" + currentFile);
1579 return false; 1579 return false;
1580 } else { 1580 } else {
1581 1581
1582 filePara.numberSamples = wavFile->getNumberSamples(); 1582 filePara.numberSamples = wavFile->getNumberSamples();
1583 filePara.format = wavFile->getFormat(); 1583 filePara.format = wavFile->getFormat();
1584 filePara.sampleRate = wavFile->getSampleRate(); 1584 filePara.sampleRate = wavFile->getSampleRate();
1585 filePara.resolution = wavFile->getResolution(); 1585 filePara.resolution = wavFile->getResolution();
1586 filePara.channels = wavFile->getChannels(); 1586 filePara.channels = wavFile->getChannels();
1587 timeSlider->setPageStep(1); 1587 timeSlider->setPageStep(1);
1588 monitoring = true; 1588 monitoring = true;
1589 1589
1590 qDebug("file %d, samples %d %d", filePara.fd, filePara.numberSamples, filePara.sampleRate); 1590 qDebug("file %d, samples %d %d", filePara.fd, filePara.numberSamples, filePara.sampleRate);
1591 int sec = (int) (( filePara.numberSamples / filePara.sampleRate) / filePara.channels) / ( filePara.channels*( filePara.resolution/8)); 1591 int sec = (int) (( filePara.numberSamples / filePara.sampleRate) / filePara.channels) / ( filePara.channels*( filePara.resolution/8));
1592 1592
1593 qWarning("seconds %d", sec); 1593 qWarning("seconds %d", sec);
1594 1594
1595 timeSlider->setRange(0, filePara.numberSamples ); 1595 timeSlider->setRange(0, filePara.numberSamples );
1596 } 1596 }
1597 1597
1598 return true; 1598 return true;
1599} 1599}
1600 1600
1601void QtRec::listPressed( int mouse, QListViewItem *item, const QPoint &, int ) { 1601void QtRec::listPressed( int mouse, QListViewItem *item, const QPoint &, int ) {
1602 if(item == NULL ) 1602 if(item == NULL )
1603 return; 1603 return;
1604 switch (mouse) { 1604 switch (mouse) {
1605 case 1: { 1605 case 1: {
1606 if( renameBox != 0 ) //tricky 1606 if( renameBox != 0 ) //tricky
1607 cancelRename(); 1607 cancelRename();
1608 1608
1609 currentFile = item->text(0); 1609 currentFile = item->text(0);
1610 setCaption( "OpieRecord " + currentFile); 1610 setCaption( "OpieRecord " + currentFile);
1611 } 1611 }
1612 break; 1612 break;
1613 case 2: 1613 case 2:
1614 showListMenu(item); 1614 showListMenu(item);
1615 ListView1->clearSelection(); 1615 ListView1->clearSelection();
1616 break; 1616 break;
1617 }; 1617 };
1618} 1618}
1619 1619
1620void QtRec::showListMenu(QListViewItem * item) { 1620void QtRec::showListMenu(QListViewItem * item) {
1621 if(item == NULL) 1621 if(item == NULL)
1622 return; 1622 return;
1623 QPopupMenu *m = new QPopupMenu(this); 1623 QPopupMenu *m = new QPopupMenu(this);
1624 m->insertItem( tr("Play"), this, SLOT( doMenuPlay() )); 1624 m->insertItem( tr("Play"), this, SLOT( doMenuPlay() ));
1625 if(Ir::supported()) m->insertItem( tr( "Send with Ir" ), this, SLOT( doBeam() )); 1625 if(Ir::supported()) m->insertItem( tr( "Send with Ir" ), this, SLOT( doBeam() ));
1626 m->insertItem( tr( "Rename" ), this, SLOT( doRename() )); 1626 m->insertItem( tr( "Rename" ), this, SLOT( doRename() ));
1627 // #if defined (QTOPIA_INTERNAL_FSLP) 1627 // #if defined (QTOPIA_INTERNAL_FSLP)
1628 // m->insertItem( tr( "Properties" ), this, SLOT( doProperties() )); 1628 // m->insertItem( tr( "Properties" ), this, SLOT( doProperties() ));
1629 // #endif 1629 // #endif
1630 m->insertSeparator(); 1630 m->insertSeparator();
1631 m->insertItem( tr("Delete"), this, SLOT( deleteSound() ) ); 1631 m->insertItem( tr("Delete"), this, SLOT( deleteSound() ) );
1632 m->exec( QCursor::pos() ); 1632 m->exec( QCursor::pos() );
1633 qApp->processEvents(); 1633 qApp->processEvents();
1634} 1634}
1635 1635
1636void QtRec::fileBeamFinished( Ir *ir) { 1636void QtRec::fileBeamFinished( Ir *ir) {
1637 if(ir) 1637 if(ir)
1638 QMessageBox::message( tr("Ir Beam out"), tr("Ir sent.") ,tr("Ok") ); 1638 QMessageBox::message( tr("Ir Beam out"), tr("Ir sent.") ,tr("Ok") );
1639 1639
1640} 1640}
1641 1641
1642void QtRec::doBeam() { 1642void QtRec::doBeam() {
1643 qApp->processEvents(); 1643 qApp->processEvents();
1644 if( ListView1->currentItem() == NULL) 1644 if( ListView1->currentItem() == NULL)
1645 return; 1645 return;
1646 Ir ir; 1646 Ir ir;
1647 if( ir.supported()) { 1647 if( ir.supported()) {
1648 QString file = ListView1->currentItem()->text(0); 1648 QString file = ListView1->currentItem()->text(0);
1649 Config cfg("OpieRec"); 1649 Config cfg("OpieRec");
1650 cfg.setGroup("Sounds"); 1650 cfg.setGroup("Sounds");
1651 1651
1652 int nFiles = cfg.readNumEntry("NumberofFiles",0); 1652 int nFiles = cfg.readNumEntry("NumberofFiles",0);
1653 1653
1654 for(int i=0;i<nFiles+1;i++) { 1654 for(int i=0;i<nFiles+1;i++) {
1655 if( cfg.readEntry( QString::number( i),"").find( file, 0, true) != -1) { 1655 if( cfg.readEntry( QString::number( i),"").find( file, 0, true) != -1) {
1656 QString filePath = cfg.readEntry(file,""); 1656 QString filePath = cfg.readEntry(file,"");
1657 Ir *file = new Ir(this, "IR"); 1657 Ir *file = new Ir(this, "IR");
1658 connect( file, SIGNAL( done(Ir*)), 1658 connect( file, SIGNAL( done(Ir*)),
1659 this, SLOT( fileBeamFinished( Ir * ))); 1659 this, SLOT( fileBeamFinished(Ir*)));
1660 file->send( filePath, "OPieRec audio file\n" + filePath ); 1660 file->send( filePath, "OPieRec audio file\n" + filePath );
1661 } 1661 }
1662 } 1662 }
1663 } 1663 }
1664} 1664}
1665 1665
1666void QtRec::doMenuPlay() { 1666void QtRec::doMenuPlay() {
1667 qApp->processEvents(); 1667 qApp->processEvents();
1668 currentFile = ListView1->currentItem()->text(0); 1668 currentFile = ListView1->currentItem()->text(0);
1669} 1669}
1670 1670
1671void QtRec::doRename() { 1671void QtRec::doRename() {
1672 QRect r = ListView1->itemRect( ListView1->currentItem( )); 1672 QRect r = ListView1->itemRect( ListView1->currentItem( ));
1673 r = QRect( ListView1->viewportToContents( r.topLeft() ), r.size() ); 1673 r = QRect( ListView1->viewportToContents( r.topLeft() ), r.size() );
1674 r.setX( ListView1->contentsX() ); 1674 r.setX( ListView1->contentsX() );
1675 if ( r.width() > ListView1->visibleWidth() ) 1675 if ( r.width() > ListView1->visibleWidth() )
1676 r.setWidth( ListView1->visibleWidth() ); 1676 r.setWidth( ListView1->visibleWidth() );
1677 1677
1678 renameBox = new QLineEdit( ListView1->viewport(), "qt_renamebox" ); 1678 renameBox = new QLineEdit( ListView1->viewport(), "qt_renamebox" );
1679 renameBox->setFrame(true); 1679 renameBox->setFrame(true);
1680 1680
1681 renameBox->setText( ListView1->currentItem()->text(0) ); 1681 renameBox->setText( ListView1->currentItem()->text(0) );
1682 1682
1683 renameBox->selectAll(); 1683 renameBox->selectAll();
1684 renameBox->installEventFilter( this ); 1684 renameBox->installEventFilter( this );
1685 ListView1->addChild( renameBox, r.x(), r.y() ); 1685 ListView1->addChild( renameBox, r.x(), r.y() );
1686 renameBox->resize( r.size() ); 1686 renameBox->resize( r.size() );
1687 ListView1->viewport()->setFocusProxy( renameBox ); 1687 ListView1->viewport()->setFocusProxy( renameBox );
1688 renameBox->setFocus(); 1688 renameBox->setFocus();
1689 renameBox->show(); 1689 renameBox->show();
1690 1690
1691} 1691}
1692 1692
1693void QtRec::okRename() { 1693void QtRec::okRename() {
1694 qDebug(renameBox->text()); 1694 qDebug(renameBox->text());
1695 QString filename = renameBox->text(); 1695 QString filename = renameBox->text();
1696 cancelRename(); 1696 cancelRename();
1697 1697
1698 if( ListView1->currentItem() == NULL) 1698 if( ListView1->currentItem() == NULL)
1699 return; 1699 return;
1700 1700
1701 Config cfg("OpieRec"); 1701 Config cfg("OpieRec");
1702 cfg.setGroup("Sounds"); 1702 cfg.setGroup("Sounds");
1703 1703
1704 QString file = ListView1->currentItem()->text(0); 1704 QString file = ListView1->currentItem()->text(0);
1705 1705
1706 qDebug("filename is " + filename); 1706 qDebug("filename is " + filename);
1707 1707
1708 int nFiles = cfg.readNumEntry("NumberofFiles",0); 1708 int nFiles = cfg.readNumEntry("NumberofFiles",0);
1709 1709
1710 for(int i=0;i<nFiles+1;i++) { //look for file 1710 for(int i=0;i<nFiles+1;i++) { //look for file
1711 if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) { 1711 if( cfg.readEntry( QString::number(i),"").find(file,0,true) != -1) {
1712 1712
1713 QString filePath = cfg.readEntry(file,""); 1713 QString filePath = cfg.readEntry(file,"");
1714 1714
1715 cfg.writeEntry( QString::number(i), filename ); 1715 cfg.writeEntry( QString::number(i), filename );
1716 cfg.writeEntry( filename, filePath ); 1716 cfg.writeEntry( filename, filePath );
1717 cfg.removeEntry( file); 1717 cfg.removeEntry( file);
1718 cfg.write(); 1718 cfg.write();
1719 } 1719 }
1720 } 1720 }
1721 1721
1722 ListView1->takeItem( ListView1->currentItem() ); 1722 ListView1->takeItem( ListView1->currentItem() );
1723 delete ListView1->currentItem(); 1723 delete ListView1->currentItem();
1724 ListView1->clear(); 1724 ListView1->clear();
1725 initIconView(); 1725 initIconView();
1726 update(); 1726 update();
1727} 1727}
1728 1728
1729void QtRec::cancelRename() { 1729void QtRec::cancelRename() {
1730 bool resetFocus = ListView1->viewport()->focusProxy() == renameBox; 1730 bool resetFocus = ListView1->viewport()->focusProxy() == renameBox;
1731 delete renameBox; 1731 delete renameBox;
1732 renameBox = 0; 1732 renameBox = 0;
1733 if ( resetFocus ) { 1733 if ( resetFocus ) {
1734 ListView1->viewport()->setFocusProxy( ListView1 ); 1734 ListView1->viewport()->setFocusProxy( ListView1 );
1735 ListView1->setFocus(); 1735 ListView1->setFocus();
1736 } 1736 }
1737} 1737}
1738 1738
1739bool QtRec::eventFilter( QObject * o, QEvent * e ) { 1739bool QtRec::eventFilter( QObject * o, QEvent * e ) {
1740 if ( o->inherits( "QLineEdit" ) ) { 1740 if ( o->inherits( "QLineEdit" ) ) {
1741 if ( e->type() == QEvent::KeyPress ) { 1741 if ( e->type() == QEvent::KeyPress ) {
1742 QKeyEvent *ke = (QKeyEvent*)e; 1742 QKeyEvent *ke = (QKeyEvent*)e;
1743 if ( ke->key() == Key_Return || 1743 if ( ke->key() == Key_Return ||
1744 ke->key() == Key_Enter ) { 1744 ke->key() == Key_Enter ) {
1745 okRename(); 1745 okRename();
1746 return true; 1746 return true;
1747 } else if ( ke->key() == Key_Escape ) { 1747 } else if ( ke->key() == Key_Escape ) {
1748 cancelRename(); 1748 cancelRename();
1749 return true; 1749 return true;
1750 } 1750 }
1751 } else if ( e->type() == QEvent::FocusOut ) { 1751 } else if ( e->type() == QEvent::FocusOut ) {
1752 cancelRename(); 1752 cancelRename();
1753 return true; 1753 return true;
1754 } 1754 }
1755 } 1755 }
1756 return QWidget::eventFilter( o, e ); 1756 return QWidget::eventFilter( o, e );
1757} 1757}
1758 1758
1759 1759
1760int QtRec::getCurrentSizeLimit() { 1760int QtRec::getCurrentSizeLimit() {
1761 return sizeLimitCombo->currentItem() * 5; 1761 return sizeLimitCombo->currentItem() * 5;
1762} 1762}
1763 1763
1764void QtRec::timerBreak() { 1764void QtRec::timerBreak() {
1765 endPlaying(); 1765 endPlaying();
1766} 1766}
1767 1767
1768void QtRec::doVolMuting(bool b) { 1768void QtRec::doVolMuting(bool b) {
1769 Config cfg( "qpe" ); 1769 Config cfg( "qpe" );
1770 cfg. setGroup( "Volume" ); 1770 cfg. setGroup( "Volume" );
1771 cfg.writeEntry( "Mute",b); 1771 cfg.writeEntry( "Mute",b);
1772 cfg.write(); 1772 cfg.write();
1773 QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << b; 1773 QCopEnvelope( "QPE/System", "volumeChange(bool)" ) << b;
1774} 1774}
1775 1775
1776void QtRec::doMicMuting(bool b) { 1776void QtRec::doMicMuting(bool b) {
1777 // qDebug("mic mute"); 1777 // qDebug("mic mute");
1778 Config cfg( "qpe" ); 1778 Config cfg( "qpe" );
1779 cfg. setGroup( "Volume" ); 1779 cfg. setGroup( "Volume" );
1780 cfg.writeEntry( "MicMute",b); 1780 cfg.writeEntry( "MicMute",b);
1781 cfg.write(); 1781 cfg.write();
1782 QCopEnvelope( "QPE/System", "micChange(bool)" ) << b; 1782 QCopEnvelope( "QPE/System", "micChange(bool)" ) << b;
1783} 1783}
1784 1784
1785void QtRec::compressionSelected(bool b) { 1785void QtRec::compressionSelected(bool b) {
1786 Config cfg("OpieRec"); 1786 Config cfg("OpieRec");
1787 cfg.setGroup("Settings"); 1787 cfg.setGroup("Settings");
1788 cfg.writeEntry("wavCompression", b); 1788 cfg.writeEntry("wavCompression", b);
1789 cfg.writeEntry("bitrate", 16); 1789 cfg.writeEntry("bitrate", 16);
1790 filePara.resolution = 16; 1790 filePara.resolution = 16;
1791 cfg.write(); 1791 cfg.write();
1792 1792
1793 if(b) { 1793 if(b) {
1794 bitRateComboBox->setEnabled( false); 1794 bitRateComboBox->setEnabled( false);
1795 bitRateComboBox->setCurrentItem( 0); 1795 bitRateComboBox->setCurrentItem( 0);
1796 filePara.resolution = 16; 1796 filePara.resolution = 16;
1797 } else{ 1797 } else{
1798 bitRateComboBox->setEnabled( true); 1798 bitRateComboBox->setEnabled( true);
1799 } 1799 }
1800} 1800}
1801 1801
1802long QtRec::checkDiskSpace(const QString &path) { 1802long QtRec::checkDiskSpace(const QString &path) {
1803 1803
1804 struct statfs fs; 1804 struct statfs fs;
1805 1805
1806 if ( !statfs( path.latin1(), &fs ) ) { 1806 if ( !statfs( path.latin1(), &fs ) ) {
1807 1807
1808 int blkSize = fs.f_bsize; 1808 int blkSize = fs.f_bsize;
1809 int availBlks = fs.f_bavail; 1809 int availBlks = fs.f_bavail;
1810 1810
1811 long mult = blkSize / 1024; 1811 long mult = blkSize / 1024;
1812 long div = 1024 / blkSize; 1812 long div = 1024 / blkSize;
1813 1813
1814 if ( !mult ) mult = 1; 1814 if ( !mult ) mult = 1;
1815 if ( !div ) div = 1; 1815 if ( !div ) div = 1;
1816 1816
1817 return availBlks * mult / div; 1817 return availBlks * mult / div;
1818 } 1818 }
1819 return -1; 1819 return -1;
1820} 1820}
1821 1821
1822// short f_fstyp; /* File system type */ 1822// short f_fstyp; /* File system type */
1823// long f_bsize; /* Block size */ 1823// long f_bsize; /* Block size */
1824// long f_frsize; /* Fragment size */ 1824// long f_frsize; /* Fragment size */
1825// long f_blocks; /* Total number of blocks*/ 1825// long f_blocks; /* Total number of blocks*/
1826// long f_bfree; /* Count of free blocks */ 1826// long f_bfree; /* Count of free blocks */
1827// long f_files; /* Total number of file nodes */ 1827// long f_files; /* Total number of file nodes */
1828// long f_ffree; /* Count of free file nodes */ 1828// long f_ffree; /* Count of free file nodes */
1829// char f_fname[6]; /* Volumename */ 1829// char f_fname[6]; /* Volumename */
1830// char f_fpack[6]; /* Pack name */ 1830// char f_fpack[6]; /* Pack name */
1831 1831
1832void QtRec::receive( const QCString &msg, const QByteArray & ) { 1832void QtRec::receive( const QCString &msg, const QByteArray & ) {
1833 qDebug("Voicerecord received message "+msg); 1833 qDebug("Voicerecord received message "+msg);
1834 1834
1835} 1835}
1836 1836
1837 1837
1838///////////////////////////// timerEvent 1838///////////////////////////// timerEvent
1839void QtRec::timerEvent( QTimerEvent * ) { 1839void QtRec::timerEvent( QTimerEvent * ) {
1840 1840
1841// if(!recording) 1841// if(!recording)
1842// timeSlider->setValue( secCount); 1842// timeSlider->setValue( secCount);
1843// else 1843// else
1844// timeSlider->setValue( filePara.numberOfRecordedSeconds); 1844// timeSlider->setValue( filePara.numberOfRecordedSeconds);
1845 1845
1846 if( stopped && playing) { 1846 if( stopped && playing) {
1847 stop(); 1847 stop();
1848 } 1848 }
1849 1849
1850 if( stopped && recording ){ 1850 if( stopped && recording ){
1851 stop(); 1851 stop();
1852 } 1852 }
1853 1853
1854 if( recording && filePara.SecondsToRecord < secCount && filePara.SecondsToRecord != 0) { 1854 if( recording && filePara.SecondsToRecord < secCount && filePara.SecondsToRecord != 0) {
1855 stop(); 1855 stop();
1856 } 1856 }
1857 1857
1858 qDebug( "%d", secCount ); 1858 qDebug( "%d", secCount );
1859 QString timeString; 1859 QString timeString;
1860#ifdef DEV_VERSION 1860#ifdef DEV_VERSION
1861 QString msg; 1861 QString msg;
1862 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution); 1862 msg.sprintf("%d, %d, %d", filePara.sampleRate, filePara.channels, filePara.resolution);
1863 setCaption( msg +" :: "+QString::number(secCount)); 1863 setCaption( msg +" :: "+QString::number(secCount));
1864#endif 1864#endif
1865 1865
1866 timeString.sprintf("%d", secCount); 1866 timeString.sprintf("%d", secCount);
1867 timeLabel->setText( timeString + " seconds"); 1867 timeLabel->setText( timeString + " seconds");
1868 1868
1869 secCount++; 1869 secCount++;
1870} 1870}
1871 1871
1872void QtRec::changeTimeSlider(int index) { 1872void QtRec::changeTimeSlider(int index) {
1873 if( ListView1->currentItem() == 0 || !wavFile->track.isOpen()) return; 1873 if( ListView1->currentItem() == 0 || !wavFile->track.isOpen()) return;
1874 // qDebug("Slider moved to %d",index); 1874 // qDebug("Slider moved to %d",index);
1875 paused = true; 1875 paused = true;
1876 stopped = true; 1876 stopped = true;
1877 1877
1878 sliderPos=index; 1878 sliderPos=index;
1879 1879
1880 QString timeString; 1880 QString timeString;
1881 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2; 1881 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
1882 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); 1882 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
1883 secCount = (int)filePara.numberOfRecordedSeconds; 1883 secCount = (int)filePara.numberOfRecordedSeconds;
1884 timeLabel->setText( timeString + tr(" seconds")); 1884 timeLabel->setText( timeString + tr(" seconds"));
1885} 1885}
1886 1886
1887void QtRec::timeSliderPressed() { 1887void QtRec::timeSliderPressed() {
1888 if( ListView1->currentItem() == 0) return; 1888 if( ListView1->currentItem() == 0) return;
1889 // qDebug("slider pressed"); 1889 // qDebug("slider pressed");
1890 paused = true; 1890 paused = true;
1891 stopped = true; 1891 stopped = true;
1892} 1892}
1893 1893
1894void QtRec::timeSliderReleased() { 1894void QtRec::timeSliderReleased() {
1895 if( ListView1->currentItem() == 0) return; 1895 if( ListView1->currentItem() == 0) return;
1896 sliderPos = timeSlider->value(); 1896 sliderPos = timeSlider->value();
1897 1897
1898 // qDebug("slider released %d", sliderPos); 1898 // qDebug("slider released %d", sliderPos);
1899 stopped = false; 1899 stopped = false;
1900 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); 1900 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
1901 total = newPos*4; 1901 total = newPos*4;
1902 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2; 1902 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
1903 1903
1904 doPlay(); 1904 doPlay();
1905} 1905}
1906 1906
1907void QtRec::rewindPressed() { 1907void QtRec::rewindPressed() {
1908 if( ListView1->currentItem() == 0) return; 1908 if( ListView1->currentItem() == 0) return;
1909 if( !wavFile->track.isOpen()) { 1909 if( !wavFile->track.isOpen()) {
1910 if( !openPlayFile() ) 1910 if( !openPlayFile() )
1911 return; 1911 return;
1912 else 1912 else
1913 if( !setupAudio( false)) 1913 if( !setupAudio( false))
1914 return; 1914 return;
1915 } else { 1915 } else {
1916 killTimers(); 1916 killTimers();
1917 paused = true; 1917 paused = true;
1918 stopped = true; 1918 stopped = true;
1919 rewindTimer->start( 50, false); 1919 rewindTimer->start( 50, false);
1920 } 1920 }
1921} 1921}
1922 1922
1923void QtRec::rewindTimerTimeout() { 1923void QtRec::rewindTimerTimeout() {
1924 int sliderValue = timeSlider->value(); 1924 int sliderValue = timeSlider->value();
1925 sliderValue = sliderValue - ( filePara.numberSamples / 100); 1925 sliderValue = sliderValue - ( filePara.numberSamples / 100);
1926 // if(toBeginningButton->isDown()) 1926 // if(toBeginningButton->isDown())
1927 timeSlider->setValue( sliderValue ) ; 1927 timeSlider->setValue( sliderValue ) ;
1928 // qDebug("%d", sliderValue); 1928 // qDebug("%d", sliderValue);
1929 QString timeString; 1929 QString timeString;
1930 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2; 1930 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2;
1931 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); 1931 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
1932 timeLabel->setText( timeString+ tr(" seconds")); 1932 timeLabel->setText( timeString+ tr(" seconds"));
1933} 1933}
1934 1934
1935void QtRec::rewindReleased() { 1935void QtRec::rewindReleased() {
1936 rewindTimer->stop(); 1936 rewindTimer->stop();
1937 if( wavFile->track.isOpen()) { 1937 if( wavFile->track.isOpen()) {
1938 sliderPos=timeSlider->value(); 1938 sliderPos=timeSlider->value();
1939 stopped = false; 1939 stopped = false;
1940 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); 1940 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
1941 total = newPos * 4; 1941 total = newPos * 4;
1942 // qDebug("rewind released %d", total); 1942 // qDebug("rewind released %d", total);
1943 startTimer( 1000); 1943 startTimer( 1000);
1944 doPlay(); 1944 doPlay();
1945 } 1945 }
1946} 1946}
1947 1947
1948void QtRec::FastforwardPressed() { 1948void QtRec::FastforwardPressed() {
1949 if( ListView1->currentItem() == 0) return; 1949 if( ListView1->currentItem() == 0) return;
1950 if( !wavFile->track.isOpen()) 1950 if( !wavFile->track.isOpen())
1951 if( !openPlayFile() ) 1951 if( !openPlayFile() )
1952 return; 1952 return;
1953 else 1953 else
1954 if( !setupAudio( false)) 1954 if( !setupAudio( false))
1955 return; 1955 return;
1956 killTimers(); 1956 killTimers();
1957 1957
1958 paused = true; 1958 paused = true;
1959 stopped = true; 1959 stopped = true;
1960 forwardTimer->start(50, false); 1960 forwardTimer->start(50, false);
1961} 1961}
1962 1962
1963 1963
1964void QtRec::forwardTimerTimeout() { 1964void QtRec::forwardTimerTimeout() {
1965 int sliderValue = timeSlider->value(); 1965 int sliderValue = timeSlider->value();
1966 sliderValue = sliderValue + ( filePara.numberSamples / 100); 1966 sliderValue = sliderValue + ( filePara.numberSamples / 100);
1967 1967
1968 // if(toEndButton->isDown()) 1968 // if(toEndButton->isDown())
1969 timeSlider->setValue( sliderValue); 1969 timeSlider->setValue( sliderValue);
1970 1970
1971 QString timeString; 1971 QString timeString;
1972 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2; 1972 filePara.numberOfRecordedSeconds = (float)sliderValue / (float)filePara.sampleRate * (float)2;
1973 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds); 1973 timeString.sprintf( "%.2f", filePara.numberOfRecordedSeconds);
1974 timeLabel->setText( timeString+ tr(" seconds")); 1974 timeLabel->setText( timeString+ tr(" seconds"));
1975} 1975}
1976 1976
1977void QtRec::FastforwardReleased() { 1977void QtRec::FastforwardReleased() {
1978 forwardTimer->stop(); 1978 forwardTimer->stop();
1979 if( wavFile->track.isOpen()) { 1979 if( wavFile->track.isOpen()) {
1980 sliderPos=timeSlider->value(); 1980 sliderPos=timeSlider->value();
1981 stopped = false; 1981 stopped = false;
1982 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET); 1982 int newPos = lseek( filePara.fd, sliderPos, SEEK_SET);
1983 total = newPos * 4; 1983 total = newPos * 4;
1984 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2; 1984 filePara.numberOfRecordedSeconds = (float)sliderPos / (float)filePara.sampleRate * (float)2;
1985 startTimer( 1000); 1985 startTimer( 1000);
1986 doPlay(); 1986 doPlay();
1987 } 1987 }
1988} 1988}
1989 1989
1990 1990
1991QString QtRec::getStorage(const QString &fileName) { 1991QString QtRec::getStorage(const QString &fileName) {
1992 1992
1993 StorageInfo storageInfo; 1993 StorageInfo storageInfo;
1994 const QList<FileSystem> &fs = storageInfo.fileSystems(); 1994 const QList<FileSystem> &fs = storageInfo.fileSystems();
1995 QListIterator<FileSystem> it ( fs ); 1995 QListIterator<FileSystem> it ( fs );
1996 QString storage; 1996 QString storage;
1997 for( ; it.current(); ++it ){ 1997 for( ; it.current(); ++it ){
1998 const QString name = ( *it)->name(); 1998 const QString name = ( *it)->name();
1999 const QString path = ( *it)->path(); 1999 const QString path = ( *it)->path();
2000 const QString disk = ( *it)->disk(); 2000 const QString disk = ( *it)->disk();
2001 if( fileName.find( path,0,true) != -1) 2001 if( fileName.find( path,0,true) != -1)
2002 storage = name; 2002 storage = name;
2003 // const QString options = (*it)->options(); 2003 // const QString options = (*it)->options();
2004 // if( name.find( tr("Internal"),0,true) == -1) { 2004 // if( name.find( tr("Internal"),0,true) == -1) {
2005 // storageComboBox->insertItem( name +" -> "+disk); 2005 // storageComboBox->insertItem( name +" -> "+disk);
2006 // qDebug(name); 2006 // qDebug(name);
2007 } 2007 }
2008 return storage; 2008 return storage;
2009 // struct mntent *me; 2009 // struct mntent *me;
2010 // // if(fileName == "/etc/mtab") { 2010 // // if(fileName == "/etc/mtab") {
2011 // FILE *mntfp = setmntent( fileName.latin1(), "r" ); 2011 // FILE *mntfp = setmntent( fileName.latin1(), "r" );
2012 // if ( mntfp ) { 2012 // if ( mntfp ) {
2013 // while ( (me = getmntent( mntfp )) != 0 ) { 2013 // while ( (me = getmntent( mntfp )) != 0 ) {
2014 // QString filesystemType = me->mnt_type; 2014 // QString filesystemType = me->mnt_type;
2015 2015
2016 // } 2016 // }
2017 // } 2017 // }
2018 // endmntent( mntfp ); 2018 // endmntent( mntfp );
2019} 2019}
2020 2020
2021void QtRec::setRecordButton(bool b) { 2021void QtRec::setRecordButton(bool b) {
2022 2022
2023 if(b) { //about to record or play 2023 if(b) { //about to record or play
2024 2024
2025 Rec_PushButton->setDown( true); 2025 Rec_PushButton->setDown( true);
2026 QPixmap image3( ( const char** ) image3_data ); 2026 QPixmap image3( ( const char** ) image3_data );
2027 Stop_PushButton->setPixmap( image3 ); 2027 Stop_PushButton->setPixmap( image3 );
2028 if(Stop_PushButton->isDown()) 2028 if(Stop_PushButton->isDown())
2029 Stop_PushButton->setDown( true); 2029 Stop_PushButton->setDown( true);
2030 playLabel2->setText( tr("Stop") ); 2030 playLabel2->setText( tr("Stop") );
2031 2031
2032 } else { //about to stop 2032 } else { //about to stop
2033 2033
2034 QPixmap image4( ( const char** ) image4_data ); 2034 QPixmap image4( ( const char** ) image4_data );
2035 Stop_PushButton->setPixmap( image4); 2035 Stop_PushButton->setPixmap( image4);
2036 if(Stop_PushButton->isDown()) 2036 if(Stop_PushButton->isDown())
2037 Stop_PushButton->setDown( false); 2037 Stop_PushButton->setDown( false);
2038 playLabel2->setText( tr("Play") ); 2038 playLabel2->setText( tr("Play") );
2039 if(Rec_PushButton->isDown()) 2039 if(Rec_PushButton->isDown())
2040 Rec_PushButton->setDown( false); 2040 Rec_PushButton->setDown( false);
2041 } 2041 }
2042} 2042}
2043 2043
2044void QtRec::fillDirectoryCombo() { 2044void QtRec::fillDirectoryCombo() {
2045 if( directoryComboBox->count() > 0) 2045 if( directoryComboBox->count() > 0)
2046 directoryComboBox->clear(); 2046 directoryComboBox->clear();
2047 int index = 0; 2047 int index = 0;
2048 Config cfg("OpieRec"); 2048 Config cfg("OpieRec");
2049 cfg.setGroup("Settings"); 2049 cfg.setGroup("Settings");
2050 QString dir = cfg.readEntry("directory", "/"); 2050 QString dir = cfg.readEntry("directory", "/");
2051 StorageInfo storageInfo; 2051 StorageInfo storageInfo;
2052 const QList<FileSystem> &fs = storageInfo.fileSystems(); 2052 const QList<FileSystem> &fs = storageInfo.fileSystems();
2053 QListIterator<FileSystem> it ( fs ); 2053 QListIterator<FileSystem> it ( fs );
2054 QString storage; 2054 QString storage;
2055 for( ; it.current(); ++it ){ 2055 for( ; it.current(); ++it ){
2056 const QString name = ( *it)->name(); 2056 const QString name = ( *it)->name();
2057 const QString path = ( *it)->path(); 2057 const QString path = ( *it)->path();
2058 // directoryComboBox->insertItem(name+" "+path); 2058 // directoryComboBox->insertItem(name+" "+path);
2059 directoryComboBox->insertItem(name); 2059 directoryComboBox->insertItem(name);
2060 if( path == dir) 2060 if( path == dir)
2061 directoryComboBox->setCurrentItem( index); 2061 directoryComboBox->setCurrentItem( index);
2062 index++; 2062 index++;
2063 } 2063 }
2064} 2064}
2065 2065
2066void QtRec::errorStop() { 2066void QtRec::errorStop() {
2067 stopped = true; 2067 stopped = true;
2068 wavFile->closeFile(); 2068 wavFile->closeFile();
2069 killTimers(); 2069 killTimers();
2070} 2070}
2071 2071
2072void QtRec::doMute(bool b) { 2072void QtRec::doMute(bool b) {
2073 doVolMuting( b); 2073 doVolMuting( b);
2074 doMicMuting( b); 2074 doMicMuting( b);
2075} 2075}
2076 2076
2077void QtRec::slotAutoMute(bool b) { 2077void QtRec::slotAutoMute(bool b) {
2078 autoMute = b; 2078 autoMute = b;
2079 Config cfg("OpieRec"); 2079 Config cfg("OpieRec");
2080 cfg.setGroup("Settings"); 2080 cfg.setGroup("Settings");
2081 cfg.writeEntry("useAutoMute",b); 2081 cfg.writeEntry("useAutoMute",b);
2082 doMute( b); 2082 doMute( b);
2083 outMuteCheckBox->setChecked( b); 2083 outMuteCheckBox->setChecked( b);
2084 inMuteCheckBox->setChecked( b); 2084 inMuteCheckBox->setChecked( b);
2085} 2085}
2086 2086
2087void QtRec::selectItemByName(const QString & name) { 2087void QtRec::selectItemByName(const QString & name) {
2088 QListViewItemIterator it( ListView1 ); 2088 QListViewItemIterator it( ListView1 );
2089 for ( ; it.current(); ++it ) 2089 for ( ; it.current(); ++it )
2090 if( name == it.current()->text(0)) 2090 if( name == it.current()->text(0))
2091 ListView1->setCurrentItem(it.current()); 2091 ListView1->setCurrentItem(it.current());
2092} 2092}
2093 2093
2094 2094
2095// long findPeak(long input ) { 2095// long findPeak(long input ) {
2096 2096
2097// // halfLife = time in seconds for output to decay to half value after an impulse 2097// // halfLife = time in seconds for output to decay to half value after an impulse
2098// static float output = 0.0; 2098// static float output = 0.0;
2099// float halfLife = .0025; 2099// float halfLife = .0025;
2100// float vsf = .0025; 2100// float vsf = .0025;
2101// float scalar = pow( 0.5, 1.0/(halfLife * filePara.sampleRate )); 2101// float scalar = pow( 0.5, 1.0/(halfLife * filePara.sampleRate ));
2102// if( input < 0.0 ) 2102// if( input < 0.0 )
2103// input = -input; // Absolute value. 2103// input = -input; // Absolute value.
2104// if ( input >= output ) { 2104// if ( input >= output ) {
2105// // When we hit a peak, ride the peak to the top. 2105// // When we hit a peak, ride the peak to the top.
2106// output = input; 2106// output = input;
2107// } else { 2107// } else {
2108// // Exponential decay of output when signal is low. 2108// // Exponential decay of output when signal is low.
2109// output = output * scalar; 2109// output = output * scalar;
2110// // 2110// //
2111// // When current gets close to 0.0, set current to 0.0 to prevent FP underflow 2111// // When current gets close to 0.0, set current to 0.0 to prevent FP underflow
2112// // which can cause a severe performance degradation due to a flood 2112// // which can cause a severe performance degradation due to a flood
2113// // of interrupts. 2113// // of interrupts.
2114// // 2114// //
2115// if( output < vsf ) output = 0.0; 2115// if( output < vsf ) output = 0.0;
2116// } 2116// }
2117 2117
2118// return (long) output; 2118// return (long) output;
2119// } 2119// }
2120 2120
2121void QtRec::changeStereoCheck(bool b) { 2121void QtRec::changeStereoCheck(bool b) {
2122 Config cfg("OpieRec"); 2122 Config cfg("OpieRec");
2123 cfg.setGroup("Settings"); 2123 cfg.setGroup("Settings");
2124 int ch = 0; 2124 int ch = 0;
2125 if ( !b) { ch = 1;} 2125 if ( !b) { ch = 1;}
2126 else { ch = 2;} 2126 else { ch = 2;}
2127 cfg.writeEntry("stereo", b); 2127 cfg.writeEntry("stereo", b);
2128 filePara.channels = ch; 2128 filePara.channels = ch;
2129 2129
2130 cfg.write(); 2130 cfg.write();
2131} 2131}
2132 2132
2133 2133
diff --git a/noncore/multimedia/powerchord/powerchordbase.cpp b/noncore/multimedia/powerchord/powerchordbase.cpp
index 0b97984..7978426 100644
--- a/noncore/multimedia/powerchord/powerchordbase.cpp
+++ b/noncore/multimedia/powerchord/powerchordbase.cpp
@@ -1,592 +1,592 @@
1/**************************************************************************** 1/****************************************************************************
2** Form implementation generated from reading ui file 'powerchordbase.ui' 2** Form implementation generated from reading ui file 'powerchordbase.ui'
3** 3**
4** Created: Sun Jan 13 23:05:11 2002 4** Created: Sun Jan 13 23:05:11 2002
5** by: The User Interface Compiler (uic) 5** by: The User Interface Compiler (uic)
6** 6**
7** WARNING! All changes made in this file will be lost! 7** WARNING! All changes made in this file will be lost!
8****************************************************************************/ 8****************************************************************************/
9#include "powerchordbase.h" 9#include "powerchordbase.h"
10 10
11#include "fretboard.h" 11#include "fretboard.h"
12#include "vumeter.h" 12#include "vumeter.h"
13#include "gs.h" 13#include "gs.h"
14#include <qcombobox.h> 14#include <qcombobox.h>
15#include <qframe.h> 15#include <qframe.h>
16#include <qlabel.h> 16#include <qlabel.h>
17#include <qlistbox.h> 17#include <qlistbox.h>
18#include <qpushbutton.h> 18#include <qpushbutton.h>
19#include <qspinbox.h> 19#include <qspinbox.h>
20#include <qtabwidget.h> 20#include <qtabwidget.h>
21#include <qlayout.h> 21#include <qlayout.h>
22#include <qvariant.h> 22#include <qvariant.h>
23#include <qtooltip.h> 23#include <qtooltip.h>
24#include <qwhatsthis.h> 24#include <qwhatsthis.h>
25#include <qimage.h> 25#include <qimage.h>
26#include <qpixmap.h> 26#include <qpixmap.h>
27#include <qbitmap.h> 27#include <qbitmap.h>
28#include <qpe/resource.h> 28#include <qpe/resource.h>
29 29
30 30
31/* 31/*
32 * Constructs a PowerchordBase which is a child of 'parent', with the 32 * Constructs a PowerchordBase which is a child of 'parent', with the
33 * name 'name' and widget flags set to 'f' 33 * name 'name' and widget flags set to 'f'
34 */ 34 */
35PowerchordBase::PowerchordBase( QWidget* parent, const char* name, WFlags fl ) 35PowerchordBase::PowerchordBase( QWidget* parent, const char* name, WFlags fl )
36 : QWidget( parent, name, fl ) 36 : QWidget( parent, name, fl )
37{ 37{
38 simulation_timer = 0; 38 simulation_timer = 0;
39 audio_timer = 0; 39 audio_timer = 0;
40 40
41 // setPalette( QPalette( QColor( 232, 227, 215) ) ); 41 // setPalette( QPalette( QColor( 232, 227, 215) ) );
42 42
43 // QPixmap image0(QString("/opt/Qtopia/pics/powerchord/image0")); 43 // QPixmap image0(QString("/opt/Qtopia/pics/powerchord/image0"));
44 QPixmap image1 = Resource::loadPixmap( "powerchord/image1"); 44 QPixmap image1 = Resource::loadPixmap( "powerchord/image1");
45 QPixmap image2 = Resource::loadPixmap( "powerchord/image2"); 45 QPixmap image2 = Resource::loadPixmap( "powerchord/image2");
46 QPixmap image3 = Resource::loadPixmap( "powerchord/image3"); 46 QPixmap image3 = Resource::loadPixmap( "powerchord/image3");
47 QPixmap image4 = Resource::loadPixmap( "powerchord/image4"); 47 QPixmap image4 = Resource::loadPixmap( "powerchord/image4");
48 QPixmap image5 = Resource::loadPixmap( "powerchord/image5"); 48 QPixmap image5 = Resource::loadPixmap( "powerchord/image5");
49 image6 = Resource::loadPixmap( "powerchord/image6"); 49 image6 = Resource::loadPixmap( "powerchord/image6");
50 image_open = Resource::loadPixmap( "powerchord/image_open"); 50 image_open = Resource::loadPixmap( "powerchord/image_open");
51 51
52 // image0.setMask(image0.createHeuristicMask()); 52 // image0.setMask(image0.createHeuristicMask());
53 image1.setMask(image1.createHeuristicMask()); 53 image1.setMask(image1.createHeuristicMask());
54 // image2.setMask(image2.createHeuristicMask()); 54 // image2.setMask(image2.createHeuristicMask());
55 // image3.setMask(image3.createHeuristicMask()); 55 // image3.setMask(image3.createHeuristicMask());
56 // image4.setMask(image4.createHeuristicMask()); 56 // image4.setMask(image4.createHeuristicMask());
57 // image5.setMask(image5.createHeuristicMask()); 57 // image5.setMask(image5.createHeuristicMask());
58 // image6->setMask(image6->createHeuristicMask()); 58 // image6->setMask(image6->createHeuristicMask());
59 // image_open->setMask(image_open->createHeuristicMask()); 59 // image_open->setMask(image_open->createHeuristicMask());
60 60
61 if ( !name ) 61 if ( !name )
62 setName( "PowerchordBase" ); 62 setName( "PowerchordBase" );
63 resize( 240, 284 ); 63 resize( 240, 284 );
64 setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, sizePolicy().hasHeightForWidth() ) ); 64 setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, sizePolicy().hasHeightForWidth() ) );
65 setMinimumSize( QSize( 240, 284 ) ); 65 setMinimumSize( QSize( 240, 284 ) );
66 setMaximumSize( QSize( 240, 284 ) ); 66 setMaximumSize( QSize( 240, 284 ) );
67 setCaption( tr( "Powerchord" ) ); 67 setCaption( tr( "Powerchord" ) );
68 68
69 tabs = new QTabWidget( this, "tabs" ); 69 tabs = new QTabWidget( this, "tabs" );
70 tabs->setEnabled( TRUE ); 70 tabs->setEnabled( TRUE );
71 tabs->setGeometry( QRect( 0, 0, 240, 286 ) ); 71 tabs->setGeometry( QRect( 0, 0, 240, 286 ) );
72 tabs->setTabPosition( QTabWidget::Bottom ); 72 tabs->setTabPosition( QTabWidget::Bottom );
73 73
74 tab = new QWidget( tabs, "tab" ); 74 tab = new QWidget( tabs, "tab" );
75 75
76 chordkey = new QComboBox( FALSE, tab, "chordkey" ); 76 chordkey = new QComboBox( FALSE, tab, "chordkey" );
77 chordkey->insertItem( tr( "maj" ) ); 77 chordkey->insertItem( tr( "maj" ) );
78 chordkey->insertItem( tr( "min" ) ); 78 chordkey->insertItem( tr( "min" ) );
79 chordkey->insertItem( tr( "7th" ) ); 79 chordkey->insertItem( tr( "7th" ) );
80 chordkey->insertItem( tr( "m7" ) ); 80 chordkey->insertItem( tr( "m7" ) );
81 chordkey->insertItem( tr( "maj7" ) ); 81 chordkey->insertItem( tr( "maj7" ) );
82 chordkey->insertItem( tr( "6th" ) ); 82 chordkey->insertItem( tr( "6th" ) );
83 chordkey->insertItem( tr( "m6th" ) ); 83 chordkey->insertItem( tr( "m6th" ) );
84 chordkey->insertItem( tr( "aug" ) ); 84 chordkey->insertItem( tr( "aug" ) );
85 chordkey->insertItem( tr( "dim" ) ); 85 chordkey->insertItem( tr( "dim" ) );
86 chordkey->insertItem( tr( "sus4" ) ); 86 chordkey->insertItem( tr( "sus4" ) );
87 chordkey->insertItem( tr( "7sus4" ) ); 87 chordkey->insertItem( tr( "7sus4" ) );
88 chordkey->insertItem( tr( "9th" ) ); 88 chordkey->insertItem( tr( "9th" ) );
89 chordkey->insertItem( tr( "add9" ) ); 89 chordkey->insertItem( tr( "add9" ) );
90 chordkey->insertItem( tr( "m9th" ) ); 90 chordkey->insertItem( tr( "m9th" ) );
91 chordkey->insertItem( tr( "maj9" ) ); 91 chordkey->insertItem( tr( "maj9" ) );
92 chordkey->insertItem( tr( "sus2" ) ); 92 chordkey->insertItem( tr( "sus2" ) );
93 chordkey->insertItem( tr( "7sus2" ) ); 93 chordkey->insertItem( tr( "7sus2" ) );
94 chordkey->insertItem( tr( "11th" ) ); 94 chordkey->insertItem( tr( "11th" ) );
95 chordkey->insertItem( tr( "m11th" ) ); 95 chordkey->insertItem( tr( "m11th" ) );
96 chordkey->insertItem( tr( "13th" ) ); 96 chordkey->insertItem( tr( "13th" ) );
97 chordkey->insertItem( tr( "m13th" ) ); 97 chordkey->insertItem( tr( "m13th" ) );
98 chordkey->insertItem( tr( "maj13" ) ); 98 chordkey->insertItem( tr( "maj13" ) );
99 chordkey->insertItem( tr( "6/9" ) ); 99 chordkey->insertItem( tr( "6/9" ) );
100 chordkey->insertItem( tr( "flat5" ) ); 100 chordkey->insertItem( tr( "flat5" ) );
101 chordkey->insertItem( tr( "7#9" ) ); 101 chordkey->insertItem( tr( "7#9" ) );
102 chordkey->insertItem( tr( QString::fromUtf8( "ø7" ) ) ); 102 chordkey->insertItem( tr( QString::fromUtf8( "ø7" ) ) );
103 chordkey->insertItem( tr( "5" ) ); 103 chordkey->insertItem( tr( "5" ) );
104 chordkey->setGeometry( QRect( 40, 0, 51, 21 ) ); 104 chordkey->setGeometry( QRect( 40, 0, 51, 21 ) );
105 105
106 chordfret = new QComboBox( FALSE, tab, "chordfret" ); 106 chordfret = new QComboBox( FALSE, tab, "chordfret" );
107 chordfret->insertItem( tr( "open" ) ); 107 chordfret->insertItem( tr( "open" ) );
108 chordfret->insertItem( tr( "1st" ) ); 108 chordfret->insertItem( tr( "1st" ) );
109 chordfret->insertItem( tr( "2nd" ) ); 109 chordfret->insertItem( tr( "2nd" ) );
110 chordfret->insertItem( tr( "3rd" ) ); 110 chordfret->insertItem( tr( "3rd" ) );
111 chordfret->insertItem( tr( "4th" ) ); 111 chordfret->insertItem( tr( "4th" ) );
112 chordfret->insertItem( tr( "5th" ) ); 112 chordfret->insertItem( tr( "5th" ) );
113 chordfret->insertItem( tr( "6th" ) ); 113 chordfret->insertItem( tr( "6th" ) );
114 chordfret->insertItem( tr( "7th" ) ); 114 chordfret->insertItem( tr( "7th" ) );
115 chordfret->insertItem( tr( "8th" ) ); 115 chordfret->insertItem( tr( "8th" ) );
116 chordfret->insertItem( tr( "9th" ) ); 116 chordfret->insertItem( tr( "9th" ) );
117 chordfret->insertItem( tr( "10th" ) ); 117 chordfret->insertItem( tr( "10th" ) );
118 chordfret->insertItem( tr( "11th" ) ); 118 chordfret->insertItem( tr( "11th" ) );
119 chordfret->insertItem( tr( "12th" ) ); 119 chordfret->insertItem( tr( "12th" ) );
120 chordfret->insertItem( tr( "13th" ) ); 120 chordfret->insertItem( tr( "13th" ) );
121 chordfret->insertItem( tr( "14th" ) ); 121 chordfret->insertItem( tr( "14th" ) );
122 chordfret->insertItem( tr( "15th" ) ); 122 chordfret->insertItem( tr( "15th" ) );
123 chordfret->insertItem( tr( "16th" ) ); 123 chordfret->insertItem( tr( "16th" ) );
124 chordfret->setGeometry( QRect( 90, 0, 55, 21 ) ); //cxm less 5 width 124 chordfret->setGeometry( QRect( 90, 0, 55, 21 ) ); //cxm less 5 width
125 125
126 chordnote = new QComboBox( FALSE, tab, "chordnote" ); 126 chordnote = new QComboBox( FALSE, tab, "chordnote" );
127 chordnote->insertItem( tr( "C" ) ); 127 chordnote->insertItem( tr( "C" ) );
128 chordnote->insertItem( tr( "C#" ) ); 128 chordnote->insertItem( tr( "C#" ) );
129 chordnote->insertItem( tr( "D" ) ); 129 chordnote->insertItem( tr( "D" ) );
130 chordnote->insertItem( tr( "Eb" ) ); 130 chordnote->insertItem( tr( "Eb" ) );
131 chordnote->insertItem( tr( "E" ) ); 131 chordnote->insertItem( tr( "E" ) );
132 chordnote->insertItem( tr( "F" ) ); 132 chordnote->insertItem( tr( "F" ) );
133 chordnote->insertItem( tr( "F#" ) ); 133 chordnote->insertItem( tr( "F#" ) );
134 chordnote->insertItem( tr( "G" ) ); 134 chordnote->insertItem( tr( "G" ) );
135 chordnote->insertItem( tr( "G#" ) ); 135 chordnote->insertItem( tr( "G#" ) );
136 chordnote->insertItem( tr( "A" ) ); 136 chordnote->insertItem( tr( "A" ) );
137 chordnote->insertItem( tr( "Bb" ) ); 137 chordnote->insertItem( tr( "Bb" ) );
138 chordnote->insertItem( tr( "B" ) ); 138 chordnote->insertItem( tr( "B" ) );
139 chordnote->setGeometry( QRect( 0, 0, 40, 21 ) ); 139 chordnote->setGeometry( QRect( 0, 0, 40, 21 ) );
140 chordnote->setCurrentItem( 9 ); 140 chordnote->setCurrentItem( 9 );
141 141
142 QWidget* privateLayoutWidget = new QWidget( tab, "Layout1" ); 142 QWidget* privateLayoutWidget = new QWidget( tab, "Layout1" );
143 privateLayoutWidget->setGeometry( QRect( 5, 232, 160, 20 ) ); 143 privateLayoutWidget->setGeometry( QRect( 5, 232, 160, 20 ) );
144 Layout1 = new QHBoxLayout( privateLayoutWidget ); 144 Layout1 = new QHBoxLayout( privateLayoutWidget );
145 Layout1->setSpacing( 6 ); 145 Layout1->setSpacing( 6 );
146 Layout1->setMargin( 0 ); 146 Layout1->setMargin( 0 );
147 147
148 s1_1 = new QLabel( privateLayoutWidget, "s1_1" ); 148 s1_1 = new QLabel( privateLayoutWidget, "s1_1" );
149 s1_1->setText( tr( "E" ) ); 149 s1_1->setText( tr( "E" ) );
150 s1_1->setAlignment( int( QLabel::AlignCenter ) ); 150 s1_1->setAlignment( int( QLabel::AlignCenter ) );
151 Layout1->addWidget( s1_1 ); 151 Layout1->addWidget( s1_1 );
152 152
153 s1_2 = new QLabel( privateLayoutWidget, "s1_2" ); 153 s1_2 = new QLabel( privateLayoutWidget, "s1_2" );
154 s1_2->setText( tr( "A" ) ); 154 s1_2->setText( tr( "A" ) );
155 s1_2->setAlignment( int( QLabel::AlignCenter ) ); 155 s1_2->setAlignment( int( QLabel::AlignCenter ) );
156 Layout1->addWidget( s1_2 ); 156 Layout1->addWidget( s1_2 );
157 157
158 s1_3 = new QLabel( privateLayoutWidget, "s1_3" ); 158 s1_3 = new QLabel( privateLayoutWidget, "s1_3" );
159 s1_3->setText( tr( "E" ) ); 159 s1_3->setText( tr( "E" ) );
160 s1_3->setAlignment( int( QLabel::AlignCenter ) ); 160 s1_3->setAlignment( int( QLabel::AlignCenter ) );
161 Layout1->addWidget( s1_3 ); 161 Layout1->addWidget( s1_3 );
162 162
163 s1_4 = new QLabel( privateLayoutWidget, "s1_4" ); 163 s1_4 = new QLabel( privateLayoutWidget, "s1_4" );
164 s1_4->setText( tr( "A" ) ); 164 s1_4->setText( tr( "A" ) );
165 s1_4->setAlignment( int( QLabel::AlignCenter ) ); 165 s1_4->setAlignment( int( QLabel::AlignCenter ) );
166 Layout1->addWidget( s1_4 ); 166 Layout1->addWidget( s1_4 );
167 167
168 s1_5 = new QLabel( privateLayoutWidget, "s1_5" ); 168 s1_5 = new QLabel( privateLayoutWidget, "s1_5" );
169 s1_5->setText( tr( "C#" ) ); 169 s1_5->setText( tr( "C#" ) );
170 s1_5->setAlignment( int( QLabel::AlignCenter ) ); 170 s1_5->setAlignment( int( QLabel::AlignCenter ) );
171 Layout1->addWidget( s1_5 ); 171 Layout1->addWidget( s1_5 );
172 172
173 s1_6 = new QLabel( privateLayoutWidget, "s1_6" ); 173 s1_6 = new QLabel( privateLayoutWidget, "s1_6" );
174 s1_6->setText( tr( "E" ) ); 174 s1_6->setText( tr( "E" ) );
175 s1_6->setAlignment( int( QLabel::AlignCenter ) ); 175 s1_6->setAlignment( int( QLabel::AlignCenter ) );
176 Layout1->addWidget( s1_6 ); 176 Layout1->addWidget( s1_6 );
177 177
178 // sound_label = new QLabel( tab, "sound_label" ); 178 // sound_label = new QLabel( tab, "sound_label" );
179 // sound_label->setGeometry( QRect( 185, 160, 32, 17 ) ); 179 // sound_label->setGeometry( QRect( 185, 160, 32, 17 ) );
180 // sound_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, sound_label->sizePolicy().hasHeightForWidth() ) ); 180 // sound_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, sound_label->sizePolicy().hasHeightForWidth() ) );
181 // sound_label->setPixmap( image0 ); 181 // sound_label->setPixmap( image0 );
182 // sound_label->pixmap()->setMask(*image0.mask()); 182 // sound_label->pixmap()->setMask(*image0.mask());
183 // sound_label->setScaledContents( TRUE ); 183 // sound_label->setScaledContents( TRUE );
184 // sound_label->setBackgroundMode( QWidget::PaletteButton ); 184 // sound_label->setBackgroundMode( QWidget::PaletteButton );
185 // sound_label->setBackgroundColor(this->backgroundColor()); 185 // sound_label->setBackgroundColor(this->backgroundColor());
186 // sound_label->setPalette( QPalette( QColor( 232, 227, 215) ) ); 186 // sound_label->setPalette( QPalette( QColor( 232, 227, 215) ) );
187 187
188 188
189 Frame6 = new QFrame( tab, "Frame6" ); 189 Frame6 = new QFrame( tab, "Frame6" );
190 Frame6->setGeometry( QRect( 170, 145, 66, 10 ) ); 190 Frame6->setGeometry( QRect( 170, 145, 66, 10 ) );
191 Frame6->setFrameShape( QFrame::HLine ); 191 Frame6->setFrameShape( QFrame::HLine );
192 Frame6->setFrameShadow( QFrame::Raised ); 192 Frame6->setFrameShadow( QFrame::Raised );
193 193
194 chordshow_label = new QLabel( tab, "chordshow_label" ); 194 chordshow_label = new QLabel( tab, "chordshow_label" );
195 chordshow_label->setGeometry( QRect( 185, 60, 32, 17 ) ); 195 chordshow_label->setGeometry( QRect( 185, 60, 32, 17 ) );
196 // chordshow_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, chordshow_label->sizePolicy().hasHeightForWidth() ) ); 196 // chordshow_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, chordshow_label->sizePolicy().hasHeightForWidth() ) );
197 chordshow_label->setFrameShape( QLabel::NoFrame ); 197 chordshow_label->setFrameShape( QLabel::NoFrame );
198 chordshow_label->setPixmap( image1 ); 198 chordshow_label->setPixmap( image1 );
199 chordshow_label->setScaledContents( TRUE ); 199 chordshow_label->setScaledContents( TRUE );
200 // chordshow_label->setBackgroundMode( QWidget::PaletteButton ); 200 // chordshow_label->setBackgroundMode( QWidget::PaletteButton );
201 201
202 transport_rec = new QPushButton( tab, "transport_rec" ); 202 transport_rec = new QPushButton( tab, "transport_rec" );
203 transport_rec->setGeometry( QRect( 170, 80, 30, 30 ) ); 203 transport_rec->setGeometry( QRect( 170, 80, 30, 30 ) );
204 transport_rec->setText( tr( "" ) ); 204 transport_rec->setText( tr( "" ) );
205 transport_rec->setPixmap( image2 ); 205 transport_rec->setPixmap( image2 );
206 206
207 play_sound = new QPushButton( tab, "play_sound" ); 207 play_sound = new QPushButton( tab, "play_sound" );
208 play_sound->setGeometry( QRect( 170, 180, 60, 55 ) ); 208 play_sound->setGeometry( QRect( 170, 180, 60, 55 ) );
209 play_sound->setText( tr( "" ) ); 209 play_sound->setText( tr( "" ) );
210 play_sound->setPixmap( image3 ); 210 play_sound->setPixmap( image3 );
211 211
212 Frame6_2 = new QFrame( tab, "Frame6_2" ); 212 Frame6_2 = new QFrame( tab, "Frame6_2" );
213 Frame6_2->setGeometry( QRect( 170, 45, 66, 10 ) ); 213 Frame6_2->setGeometry( QRect( 170, 45, 66, 10 ) );
214 Frame6_2->setFrameShape( QFrame::HLine ); 214 Frame6_2->setFrameShape( QFrame::HLine );
215 Frame6_2->setFrameShadow( QFrame::Raised ); 215 Frame6_2->setFrameShadow( QFrame::Raised );
216 216
217 transport_play = new QPushButton( tab, "transport_play" ); 217 transport_play = new QPushButton( tab, "transport_play" );
218 transport_play->setEnabled( FALSE ); 218 transport_play->setEnabled( FALSE );
219 transport_play->setGeometry( QRect( 200, 80, 30, 30 ) ); 219 transport_play->setGeometry( QRect( 200, 80, 30, 30 ) );
220 transport_play->setText( tr( "" ) ); 220 transport_play->setText( tr( "" ) );
221 transport_play->setPixmap( image3 ); 221 transport_play->setPixmap( image3 );
222 222
223 transport_rew = new QPushButton( tab, "transport_rew" ); 223 transport_rew = new QPushButton( tab, "transport_rew" );
224 transport_rew->setEnabled( FALSE ); 224 transport_rew->setEnabled( FALSE );
225 transport_rew->setGeometry( QRect( 170, 110, 30, 30 ) ); 225 transport_rew->setGeometry( QRect( 170, 110, 30, 30 ) );
226 transport_rew->setText( tr( "" ) ); 226 transport_rew->setText( tr( "" ) );
227 transport_rew->setPixmap( image4 ); 227 transport_rew->setPixmap( image4 );
228 228
229 transport_fwd = new QPushButton( tab, "transport_fwd" ); 229 transport_fwd = new QPushButton( tab, "transport_fwd" );
230 transport_fwd->setEnabled( FALSE ); 230 transport_fwd->setEnabled( FALSE );
231 transport_fwd->setGeometry( QRect( 200, 110, 30, 30 ) ); 231 transport_fwd->setGeometry( QRect( 200, 110, 30, 30 ) );
232 transport_fwd->setText( tr( "" ) ); 232 transport_fwd->setText( tr( "" ) );
233 transport_fwd->setPixmap( image5 ); 233 transport_fwd->setPixmap( image5 );
234 234
235 chordname = new QLabel( tab, "chordname" ); 235 chordname = new QLabel( tab, "chordname" );
236 chordname->setGeometry( QRect( 146, 0, 90, 20 ) ); //cxm moved l 5 236 chordname->setGeometry( QRect( 146, 0, 90, 20 ) ); //cxm moved l 5
237 chordname->setText( tr( "A" ) ); 237 chordname->setText( tr( "A" ) );
238 chordname->setAlignment( int( QLabel::AlignCenter ) ); 238 chordname->setAlignment( int( QLabel::AlignCenter ) );
239 QToolTip::add( chordname, tr( "" ) ); 239 QToolTip::add( chordname, tr( "" ) );
240 240
241 synth = new gs(); 241 synth = new gs();
242 tuner = new gt(); 242 tuner = new gt();
243 frets = new FretBoard( tab, "frets" ); 243 frets = new FretBoard( tab, "frets" );
244 frets->setGeometry( QRect( 0, 20, 168, 210 ) ); 244 frets->setGeometry( QRect( 0, 20, 168, 210 ) );
245 tabs->insertTab( tab, tr( "Guitar" ) ); 245 tabs->insertTab( tab, tr( "Guitar" ) );
246 246
247 tab_2 = new QWidget( tabs, "tab_2" ); 247 tab_2 = new QWidget( tabs, "tab_2" );
248 248
249 optlab2 = new QLabel( tab_2, "optlab2" ); 249 optlab2 = new QLabel( tab_2, "optlab2" );
250 optlab2->setGeometry( QRect( 9, 58, 120, 41 ) ); 250 optlab2->setGeometry( QRect( 9, 58, 120, 41 ) );
251 optlab2->setText( tr( "Alternative tunings are possible" ) ); 251 optlab2->setText( tr( "Alternative tunings are possible" ) );
252 optlab2->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) ); 252 optlab2->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) );
253 253
254 span = new QComboBox( FALSE, tab_2, "span" ); 254 span = new QComboBox( FALSE, tab_2, "span" );
255 span->insertItem( tr( "2" ) ); 255 span->insertItem( tr( "2" ) );
256 span->insertItem( tr( "3" ) ); 256 span->insertItem( tr( "3" ) );
257 span->insertItem( tr( "4" ) ); 257 span->insertItem( tr( "4" ) );
258 span->insertItem( tr( "5" ) ); 258 span->insertItem( tr( "5" ) );
259 span->insertItem( tr( "6" ) ); 259 span->insertItem( tr( "6" ) );
260 span->setGeometry( QRect( 180, 20, 50, 21 ) ); 260 span->setGeometry( QRect( 180, 20, 50, 21 ) );
261 span->setCurrentItem( 1 ); 261 span->setCurrentItem( 1 );
262 262
263 TextLabel1 = new QLabel( tab_2, "TextLabel1" ); 263 TextLabel1 = new QLabel( tab_2, "TextLabel1" );
264 TextLabel1->setGeometry( QRect( 3, 109, 226, 140 ) ); 264 TextLabel1->setGeometry( QRect( 3, 109, 226, 140 ) );
265 TextLabel1->setText( tr( QString::fromUtf8( "©2002 Camilo Mesias\n" 265 TextLabel1->setText( tr( QString::fromUtf8( "©2002 Camilo Mesias\n"
266"camilo@mesias.co.uk\n" 266"camilo@mesias.co.uk\n"
267"Version 0.0.7 beta" ) ) ); 267"Version 0.0.7 beta" ) ) );
268 TextLabel1->setAlignment( int( QLabel::AlignBottom | QLabel::AlignLeft ) ); 268 TextLabel1->setAlignment( int( QLabel::AlignBottom | QLabel::AlignLeft ) );
269 269
270 tuning = new QComboBox( FALSE, tab_2, "tuning" ); 270 tuning = new QComboBox( FALSE, tab_2, "tuning" );
271 tuning->insertItem( tr( "EADGBE" ) ); 271 tuning->insertItem( tr( "EADGBE" ) );
272 tuning->insertItem( tr( "EBEG#BE" ) ); 272 tuning->insertItem( tr( "EBEG#BE" ) );
273 tuning->insertItem( tr( "EAEAC#E" ) ); 273 tuning->insertItem( tr( "EAEAC#E" ) );
274 tuning->insertItem( tr( "EADF#BE" ) ); 274 tuning->insertItem( tr( "EADF#BE" ) );
275 tuning->insertItem( tr( "EADGCF" ) ); 275 tuning->insertItem( tr( "EADGCF" ) );
276 tuning->insertItem( tr( "DADGAD" ) ); 276 tuning->insertItem( tr( "DADGAD" ) );
277 tuning->insertItem( tr( "DGCGCD" ) ); 277 tuning->insertItem( tr( "DGCGCD" ) );
278 tuning->insertItem( tr( "DADF#AD" ) ); 278 tuning->insertItem( tr( "DADF#AD" ) );
279 tuning->insertItem( tr( "DADGBE" ) ); 279 tuning->insertItem( tr( "DADGBE" ) );
280 tuning->insertItem( tr( "DGDGBD" ) ); 280 tuning->insertItem( tr( "DGDGBD" ) );
281 tuning->insertItem( tr( "DADACD" ) ); 281 tuning->insertItem( tr( "DADACD" ) );
282 tuning->insertItem( tr( "CGCGAE" ) ); 282 tuning->insertItem( tr( "CGCGAE" ) );
283 tuning->insertItem( tr( "FADGBE" ) ); 283 tuning->insertItem( tr( "FADGBE" ) );
284 tuning->insertItem( tr( "G minor" ) ); 284 tuning->insertItem( tr( "G minor" ) );
285 tuning->setGeometry( QRect( 140, 70, 91, 21 ) ); 285 tuning->setGeometry( QRect( 140, 70, 91, 21 ) );
286 286
287 optlab1 = new QLabel( tab_2, "optlab1" ); 287 optlab1 = new QLabel( tab_2, "optlab1" );
288 optlab1->setGeometry( QRect( 8, 8, 160, 40 ) ); 288 optlab1->setGeometry( QRect( 8, 8, 160, 40 ) );
289 optlab1->setText( tr( "Span: the greatest number of frets over which you want chords to be generated" ) ); 289 optlab1->setText( tr( "Span: the greatest number of frets over which you want chords to be generated" ) );
290 optlab1->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) ); 290 optlab1->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignLeft ) );
291 tabs->insertTab( tab_2, tr( "Options" ) ); 291 tabs->insertTab( tab_2, tr( "Options" ) );
292 292
293 Tuner = new QWidget( tabs, "Tuner" ); 293 Tuner = new QWidget( tabs, "Tuner" );
294 294
295 Frame4 = new QFrame( Tuner, "Frame4" ); 295 Frame4 = new QFrame( Tuner, "Frame4" );
296 Frame4->setGeometry( QRect( 0, 0, 230, 126 ) ); 296 Frame4->setGeometry( QRect( 0, 0, 230, 126 ) );
297 Frame4->setFrameShape( QFrame::Box ); 297 Frame4->setFrameShape( QFrame::Box );
298 Frame4->setFrameShadow( QFrame::Raised ); 298 Frame4->setFrameShadow( QFrame::Raised );
299 299
300 vu = new VUMeter( Frame4, "vu" ); 300 vu = new VUMeter( Frame4, "vu" );
301 vu->setGeometry( QRect( 5, 5, 220, 115 ) ); 301 vu->setGeometry( QRect( 5, 5, 220, 115 ) );
302 302
303 tuner_note = new QComboBox( FALSE, Tuner, "tuner_note" ); 303 tuner_note = new QComboBox( FALSE, Tuner, "tuner_note" );
304 tuner_note->insertItem( tr( "auto" ) ); 304 tuner_note->insertItem( tr( "auto" ) );
305 tuner_note->insertItem( tr( "E" ) ); 305 tuner_note->insertItem( tr( "E" ) );
306 tuner_note->insertItem( tr( "D" ) ); 306 tuner_note->insertItem( tr( "D" ) );
307 tuner_note->insertItem( tr( "G" ) ); 307 tuner_note->insertItem( tr( "G" ) );
308 tuner_note->insertItem( tr( "A" ) ); 308 tuner_note->insertItem( tr( "A" ) );
309 tuner_note->insertItem( tr( "B" ) ); 309 tuner_note->insertItem( tr( "B" ) );
310 tuner_note->insertItem( tr( "C" ) ); 310 tuner_note->insertItem( tr( "C" ) );
311 tuner_note->insertItem( tr( "F" ) ); 311 tuner_note->insertItem( tr( "F" ) );
312 tuner_note->setGeometry( QRect( 5, 160, 90, 20 ) ); 312 tuner_note->setGeometry( QRect( 5, 160, 90, 20 ) );
313 313
314 Frame8 = new QFrame( Tuner, "Frame8" ); 314 Frame8 = new QFrame( Tuner, "Frame8" );
315 Frame8->setGeometry( QRect( -2, 188, 231, 10 ) ); 315 Frame8->setGeometry( QRect( -2, 188, 231, 10 ) );
316 Frame8->setFrameShape( QFrame::HLine ); 316 Frame8->setFrameShape( QFrame::HLine );
317 Frame8->setFrameShadow( QFrame::Raised ); 317 Frame8->setFrameShadow( QFrame::Raised );
318 318
319 tuner_start = new QPushButton( Tuner, "tuner_start" ); 319 tuner_start = new QPushButton( Tuner, "tuner_start" );
320 tuner_start->setGeometry( QRect( 100, 155, 91, 30 ) ); 320 tuner_start->setGeometry( QRect( 100, 155, 91, 30 ) );
321 tuner_start->setText( tr( "Start" ) ); 321 tuner_start->setText( tr( "Start" ) );
322 322
323 tuner_lab1 = new QLabel( Tuner, "tuner_lab1" ); 323 tuner_lab1 = new QLabel( Tuner, "tuner_lab1" );
324 tuner_lab1->setGeometry( QRect( 10, 130, 100, 21 ) ); 324 tuner_lab1->setGeometry( QRect( 10, 130, 100, 21 ) );
325 tuner_lab1->setText( tr( "Tuner operation" ) ); 325 tuner_lab1->setText( tr( "Tuner operation" ) );
326 326
327 tuner_lab2 = new QLabel( Tuner, "tuner_lab2" ); 327 tuner_lab2 = new QLabel( Tuner, "tuner_lab2" );
328 tuner_lab2->setGeometry( QRect( 10, 200, 100, 16 ) ); 328 tuner_lab2->setGeometry( QRect( 10, 200, 100, 16 ) );
329 tuner_lab2->setText( tr( "Pitch calibration" ) ); 329 tuner_lab2->setText( tr( "Pitch calibration" ) );
330 330
331 tuner_calib_note = new QComboBox( FALSE, Tuner, "tuner_calib_note" ); 331 tuner_calib_note = new QComboBox( FALSE, Tuner, "tuner_calib_note" );
332 tuner_calib_note->insertItem( tr( "A" ) ); 332 tuner_calib_note->insertItem( tr( "A" ) );
333 tuner_calib_note->insertItem( tr( "C" ) ); 333 tuner_calib_note->insertItem( tr( "C" ) );
334 tuner_calib_note->setGeometry( QRect( 5, 225, 90, 21 ) ); 334 tuner_calib_note->setGeometry( QRect( 5, 225, 90, 21 ) );
335 335
336 tuner_calib_freq = new QSpinBox( Tuner, "tuner_calib_freq" ); 336 tuner_calib_freq = new QSpinBox( Tuner, "tuner_calib_freq" );
337 tuner_calib_freq->setGeometry( QRect( 105, 225, 71, 21 ) ); 337 tuner_calib_freq->setGeometry( QRect( 105, 225, 71, 21 ) );
338 tuner_calib_freq->setSuffix( tr( "Hz" ) ); 338 tuner_calib_freq->setSuffix( tr( "Hz" ) );
339 tuner_calib_freq->setWrapping( TRUE ); 339 tuner_calib_freq->setWrapping( TRUE );
340 tuner_calib_freq->setMaxValue( 500 ); 340 tuner_calib_freq->setMaxValue( 500 );
341 tuner_calib_freq->setMinValue( 300 ); 341 tuner_calib_freq->setMinValue( 300 );
342 tuner_calib_freq->setValue( 440 ); 342 tuner_calib_freq->setValue( 440 );
343 343
344 tuner_lab3 = new QLabel( Tuner, "tuner_lab3" ); 344 tuner_lab3 = new QLabel( Tuner, "tuner_lab3" );
345 tuner_lab3->setGeometry( QRect( 185, 225, 40, 21 ) ); 345 tuner_lab3->setGeometry( QRect( 185, 225, 40, 21 ) );
346 tuner_lab3->setText( tr( "Pitch" ) ); 346 tuner_lab3->setText( tr( "Pitch" ) );
347 347
348 tuner_pic1 = new QLabel( Tuner, "tuner_pic1" ); 348 tuner_pic1 = new QLabel( Tuner, "tuner_pic1" );
349 tuner_pic1->setGeometry( QRect( 195, 155, 31, 31 ) ); 349 tuner_pic1->setGeometry( QRect( 195, 155, 31, 31 ) );
350 tuner_pic1->setFrameShape( QLabel::NoFrame ); 350 tuner_pic1->setFrameShape( QLabel::NoFrame );
351 tuner_pic1->setPixmap( image6 ); 351 tuner_pic1->setPixmap( image6 );
352 tuner_pic1->setScaledContents( TRUE ); 352 tuner_pic1->setScaledContents( TRUE );
353 tabs->insertTab( Tuner, tr( "Tuner" ) ); 353 tabs->insertTab( Tuner, tr( "Tuner" ) );
354 354
355 tab_3 = new QWidget( tabs, "tab_3" ); 355 tab_3 = new QWidget( tabs, "tab_3" );
356 356
357 chordlistlab1 = new QLabel( tab_3, "chordlistlab1" ); 357 chordlistlab1 = new QLabel( tab_3, "chordlistlab1" );
358 chordlistlab1->setGeometry( QRect( 5, 5, 216, 16 ) ); 358 chordlistlab1->setGeometry( QRect( 5, 5, 216, 16 ) );
359 chordlistlab1->setText( tr( "Chord list" ) ); 359 chordlistlab1->setText( tr( "Chord list" ) );
360 360
361 chordlist = new QListBox( tab_3, "chordlist" ); 361 chordlist = new QListBox( tab_3, "chordlist" );
362 chordlist->setGeometry( QRect( 5, 25, 220, 200 ) ); 362 chordlist->setGeometry( QRect( 5, 25, 220, 200 ) );
363 363
364 list_remove_btn = new QPushButton( tab_3, "list_remove_btn" ); 364 list_remove_btn = new QPushButton( tab_3, "list_remove_btn" );
365 list_remove_btn->setGeometry( QRect( 150, 230, 71, 25 ) ); 365 list_remove_btn->setGeometry( QRect( 150, 230, 71, 25 ) );
366 list_remove_btn->setText( tr( "Remove" ) ); 366 list_remove_btn->setText( tr( "Remove" ) );
367 tabs->insertTab( tab_3, tr( "Chords" ) ); 367 tabs->insertTab( tab_3, tr( "Chords" ) );
368 368
369 // hope this does what it's supposed to!! 369 // hope this does what it's supposed to!!
370 // setPalette( QPalette( QColor( 232, 227, 215) ) ); 370 // setPalette( QPalette( QColor( 232, 227, 215) ) );
371 371
372 // signals and slots connections 372 // signals and slots connections
373 373
374 //cxm 374 //cxm
375 connect( tuning, SIGNAL( activated(int) ), frets, SLOT( Tune(int) ) ); 375 connect( tuning, SIGNAL( activated(int) ), frets, SLOT( Tune(int) ) );
376 connect( span, SIGNAL( activated(int) ), frets, SLOT( Span(int) ) ); 376 connect( span, SIGNAL( activated(int) ), frets, SLOT( Span(int) ) );
377 connect( transport_rec, SIGNAL( clicked() ), this, SLOT( transport_rec_cb() )); 377 connect( transport_rec, SIGNAL( clicked() ), this, SLOT( transport_rec_cb() ));
378 connect( play_sound, SIGNAL( clicked() ), this, SLOT( play_chord_cb() )); 378 connect( play_sound, SIGNAL( clicked() ), this, SLOT( play_chord_cb() ));
379 connect( tuner_start, SIGNAL( clicked() ), this, SLOT( tuner_start_cb() )); 379 connect( tuner_start, SIGNAL( clicked() ), this, SLOT( tuner_start_cb() ));
380 connect( tuner_note, SIGNAL( textChanged(const QString&) ), vu, SLOT( AnnotL(const QString&) )); 380 connect( tuner_note, SIGNAL( textChanged(const QString&) ), vu, SLOT( AnnotL(const QString&) ));
381 connect( this, SIGNAL( frequency_change(int) ), vu, SLOT( Value(int) )); 381 connect( this, SIGNAL( frequency_change(int) ), vu, SLOT( Value(int) ));
382 382
383 connect( chordnote, SIGNAL( activated(int) ), frets, SLOT( Base(int) ) ); 383 connect( chordnote, SIGNAL( activated(int) ), frets, SLOT( Base(int) ) );
384 connect( chordkey, SIGNAL( activated(int) ), frets, SLOT( Chord(int) ) ); 384 connect( chordkey, SIGNAL( activated(int) ), frets, SLOT( Chord(int) ) );
385 connect( chordfret, SIGNAL( activated(int) ), frets, SLOT( Fret(int) ) ); 385 connect( chordfret, SIGNAL( activated(int) ), frets, SLOT( Fret(int) ) );
386 connect( list_remove_btn, SIGNAL( clicked() ), this, SLOT( list_remove_cb() ) ); 386 connect( list_remove_btn, SIGNAL( clicked() ), this, SLOT( list_remove_cb() ) );
387 connect( frets, SIGNAL( s1nameChanged(const QString &) ), s1_1, SLOT( setText(const QString&) ) ); 387 connect( frets, SIGNAL( s1nameChanged(const QString&) ), s1_1, SLOT( setText(const QString&) ) );
388 connect( frets, SIGNAL( s2nameChanged(const QString &) ), s1_2, SLOT( setText(const QString&) ) ); 388 connect( frets, SIGNAL( s2nameChanged(const QString&) ), s1_2, SLOT( setText(const QString&) ) );
389 connect( frets, SIGNAL( s3nameChanged(const QString &) ), s1_3, SLOT( setText(const QString&) ) ); 389 connect( frets, SIGNAL( s3nameChanged(const QString&) ), s1_3, SLOT( setText(const QString&) ) );
390 connect( frets, SIGNAL( s4nameChanged(const QString &) ), s1_4, SLOT( setText(const QString&) ) ); 390 connect( frets, SIGNAL( s4nameChanged(const QString&) ), s1_4, SLOT( setText(const QString&) ) );
391 connect( frets, SIGNAL( s5nameChanged(const QString &) ), s1_5, SLOT( setText(const QString&) ) ); 391 connect( frets, SIGNAL( s5nameChanged(const QString&) ), s1_5, SLOT( setText(const QString&) ) );
392 connect( frets, SIGNAL( s6nameChanged(const QString &) ), s1_6, SLOT( setText(const QString&) ) ); 392 connect( frets, SIGNAL( s6nameChanged(const QString&) ), s1_6, SLOT( setText(const QString&) ) );
393 connect( frets, SIGNAL( nameChanged(const QString &) ), chordname, SLOT( setText(const QString&) ) ); 393 connect( frets, SIGNAL( nameChanged(const QString&) ), chordname, SLOT( setText(const QString&) ) );
394} 394}
395 395
396 396
397static int known=0; 397static int known=0;
398#include <qmessagebox.h> 398#include <qmessagebox.h>
399void PowerchordBase::transport_rec_cb(){ 399void PowerchordBase::transport_rec_cb(){
400 chordlist->insertItem(chordname->text(),-1); 400 chordlist->insertItem(chordname->text(),-1);
401 if (!known){ 401 if (!known){
402 QMessageBox::information(this, "Powerchord", "This chord has been saved\ninto the list of chords,\nfor later playback."); 402 QMessageBox::information(this, "Powerchord", "This chord has been saved\ninto the list of chords,\nfor later playback.");
403 known = 1; 403 known = 1;
404 } 404 }
405} 405}
406void PowerchordBase::list_remove_cb(){ 406void PowerchordBase::list_remove_cb(){
407 if (chordlist->count() > 0){ 407 if (chordlist->count() > 0){
408 chordlist->removeItem(0); 408 chordlist->removeItem(0);
409 } 409 }
410} 410}
411void PowerchordBase::play_chord_cb(){ 411void PowerchordBase::play_chord_cb(){
412 // QMessageBox::information(this, "Coming soon!", "This button plays\nthe chord by synthesizing\nthe sound of the notes."); 412 // QMessageBox::information(this, "Coming soon!", "This button plays\nthe chord by synthesizing\nthe sound of the notes.");
413 413
414 414
415 if (audio_timer){ 415 if (audio_timer){
416 audio_timer->stop(); 416 audio_timer->stop();
417 // set pixmap? 417 // set pixmap?
418 synth->Stop(); 418 synth->Stop();
419 delete(audio_timer); 419 delete(audio_timer);
420 audio_timer = 0; 420 audio_timer = 0;
421 }else{ 421 }else{
422 // get notes from chord engine 422 // get notes from chord engine
423 423
424 int note; 424 int note;
425 int base; 425 int base;
426 int octave; 426 int octave;
427 note = frets->ce.noteindex(0); 427 note = frets->ce.noteindex(0);
428 if (note >= 0){ 428 if (note >= 0){
429 //fprintf(stderr, "Note was %d\n", note); 429 //fprintf(stderr, "Note was %d\n", note);
430 base = note % 12; 430 base = note % 12;
431 octave = note / 12; 431 octave = note / 12;
432 synth->note_start(0, base, octave); 432 synth->note_start(0, base, octave);
433 }else{ 433 }else{
434 // subtle bug here - replay second note if 1st one muted 434 // subtle bug here - replay second note if 1st one muted
435 note = frets->ce.noteindex(1); 435 note = frets->ce.noteindex(1);
436 base = note % 12; 436 base = note % 12;
437 octave = note / 12; 437 octave = note / 12;
438 synth->note_start(1, base, octave); 438 synth->note_start(1, base, octave);
439 439
440 } 440 }
441 441
442 // init synth 442 // init synth
443 if (synth->Play()){ 443 if (synth->Play()){
444 // error 444 // error
445 QMessageBox::information(this, "Powerchord", "Unable to open device for sound playback - check that no other application is using it."); 445 QMessageBox::information(this, "Powerchord", "Unable to open device for sound playback - check that no other application is using it.");
446 return; 446 return;
447 } 447 }
448 synth->fill_buffer(); 448 synth->fill_buffer();
449 449
450 // start timer 450 // start timer
451 audio_timer = new QTimer(); 451 audio_timer = new QTimer();
452 connect(audio_timer, SIGNAL( timeout() ), this, SLOT( audio_cb() )); 452 connect(audio_timer, SIGNAL( timeout() ), this, SLOT( audio_cb() ));
453 // set pixmap on player? 453 // set pixmap on player?
454 audio_timer->start(19); // 19 msec (fudge factor!!) 454 audio_timer->start(19); // 19 msec (fudge factor!!)
455 } 455 }
456} 456}
457 457
458 458
459 459
460void PowerchordBase::audio_cb(){ 460void PowerchordBase::audio_cb(){
461 // play the next bit of audio until quiet 461 // play the next bit of audio until quiet
462 462
463 // strum timing 463 // strum timing
464#define INTERVAL 2 464#define INTERVAL 2
465 465
466 if ((synth->Frames() % INTERVAL) == 0){ 466 if ((synth->Frames() % INTERVAL) == 0){
467 int string = synth->Frames() / INTERVAL; 467 int string = synth->Frames() / INTERVAL;
468 if (string <= 5){ 468 if (string <= 5){
469 int note; 469 int note;
470 int base; 470 int base;
471 int octave; 471 int octave;
472 note = frets->ce.noteindex(string); 472 note = frets->ce.noteindex(string);
473 // check not muted... 473 // check not muted...
474 if (note > 0){ 474 if (note > 0){
475 base = note % 12; 475 base = note % 12;
476 octave = note / 12; 476 octave = note / 12;
477 synth->note_start(string, base, octave); 477 synth->note_start(string, base, octave);
478 } 478 }
479 } 479 }
480 } 480 }
481 481
482 if (synth->Playing()){ 482 if (synth->Playing()){
483 synth->write_buffer(); 483 synth->write_buffer();
484 synth->fill_buffer(); 484 synth->fill_buffer();
485 }else{ 485 }else{
486 audio_timer->stop(); 486 audio_timer->stop();
487 // set pixmap? 487 // set pixmap?
488 synth->Stop(); 488 synth->Stop();
489 delete(audio_timer); 489 delete(audio_timer);
490 audio_timer = 0; 490 audio_timer = 0;
491 } 491 }
492} 492}
493 493
494// the real tuner 494// the real tuner
495// void PowerchordBase::tuner_start_cb(){ 495// void PowerchordBase::tuner_start_cb(){
496 496
497// if (tuner->Listening()){ 497// if (tuner->Listening()){
498// simulation_timer->stop(); 498// simulation_timer->stop();
499// tuner->Stop(); 499// tuner->Stop();
500// tuner_pic1->setPixmap( *image6 ); 500// tuner_pic1->setPixmap( *image6 );
501 501
502// }else{ 502// }else{
503// tuner_pic1->setPixmap( *image_open ); 503// tuner_pic1->setPixmap( *image_open );
504 504
505// if (!simulation_timer){ 505// if (!simulation_timer){
506// simulation_timer = new QTimer(); 506// simulation_timer = new QTimer();
507 507
508 508
509// connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_cb() )); 509// connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_cb() ));
510// } 510// }
511 511
512// simulation_timer->start(50); 512// simulation_timer->start(50);
513// tuner->Listen(); 513// tuner->Listen();
514 514
515// } 515// }
516// } 516// }
517 517
518void PowerchordBase::tuner_cb(){ 518void PowerchordBase::tuner_cb(){
519 if (tuner->Listening()){ 519 if (tuner->Listening()){
520 tuner->read_buffer(); 520 tuner->read_buffer();
521 tuner->process_buffer(); 521 tuner->process_buffer();
522 522
523 // update gui 523 // update gui
524 // do something with the note: tuner->Note() 524 // do something with the note: tuner->Note()
525 emit frequency_change(tuner->Tuning()); 525 emit frequency_change(tuner->Tuning());
526 526
527 }else{ 527 }else{
528 simulation_timer->stop(); 528 simulation_timer->stop();
529 tuner->Stop(); 529 tuner->Stop();
530 tuner_pic1->setPixmap( image6 ); 530 tuner_pic1->setPixmap( image6 );
531 } 531 }
532} 532}
533 533
534 534
535void PowerchordBase::tuner_start_cb(){ 535void PowerchordBase::tuner_start_cb(){
536 if (0 == QMessageBox::information(this, "Powerchord", "Using the microphone,\nthe note's frequency\nis analysed. This\nis a simulation.", "OK", "Cancel", 0, 1)){ 536 if (0 == QMessageBox::information(this, "Powerchord", "Using the microphone,\nthe note's frequency\nis analysed. This\nis a simulation.", "OK", "Cancel", 0, 1)){
537 if (simulation_timer){ 537 if (simulation_timer){
538 simulation_timer->stop(); 538 simulation_timer->stop();
539 }else{ 539 }else{
540 simulation_timer = new QTimer(); 540 simulation_timer = new QTimer();
541 connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_simulation_cb() )); 541 connect(simulation_timer, SIGNAL( timeout() ), this, SLOT( tuner_simulation_cb() ));
542 542
543 } 543 }
544 simulation_x = -45; 544 simulation_x = -45;
545 simulation_v = 0; 545 simulation_v = 0;
546 simulation_iter = 0; 546 simulation_iter = 0;
547 547
548 tuner_pic1->setPixmap( image_open ); 548 tuner_pic1->setPixmap( image_open );
549 simulation_timer->start(100); 549 simulation_timer->start(100);
550 } 550 }
551} 551}
552 552
553#include <stdio.h> 553#include <stdio.h>
554 554
555void PowerchordBase::tuner_simulation_cb(){ 555void PowerchordBase::tuner_simulation_cb(){
556 if (simulation_x < -10 || simulation_x > 10){ 556 if (simulation_x < -10 || simulation_x > 10){
557 simulation_v = (simulation_v/2)-(simulation_x/5); 557 simulation_v = (simulation_v/2)-(simulation_x/5);
558 } 558 }
559 559
560 simulation_x += simulation_v; 560 simulation_x += simulation_v;
561 simulation_iter++; 561 simulation_iter++;
562 562
563 if (simulation_x > 50){ 563 if (simulation_x > 50){
564 simulation_x = 50; 564 simulation_x = 50;
565 } 565 }
566 566
567 if (simulation_x < -50){ 567 if (simulation_x < -50){
568 simulation_x = -50; 568 simulation_x = -50;
569 } 569 }
570 570
571 if (simulation_iter > 50){ 571 if (simulation_iter > 50){
572 simulation_timer->stop(); 572 simulation_timer->stop();
573 emit frequency_change(0); 573 emit frequency_change(0);
574 tuner_pic1->setPixmap( image6 ); 574 tuner_pic1->setPixmap( image6 );
575 }else{ 575 }else{
576 emit frequency_change(simulation_x); 576 emit frequency_change(simulation_x);
577 } 577 }
578} 578}
579 579
580/* 580/*
581 * Destroys the object and frees any allocated resources 581 * Destroys the object and frees any allocated resources
582 */ 582 */
583PowerchordBase::~PowerchordBase() 583PowerchordBase::~PowerchordBase()
584{ 584{
585 // no need to delete child widgets, Qt does it all for us 585 // no need to delete child widgets, Qt does it all for us
586} 586}
587 587
588void PowerchordBase::change_handler() 588void PowerchordBase::change_handler()
589{ 589{
590 qWarning( "PowerchordBase::change_handler(): Not implemented yet!" ); 590 qWarning( "PowerchordBase::change_handler(): Not implemented yet!" );
591} 591}
592 592
diff --git a/noncore/multimedia/showimg/ImageFileSelector.cpp b/noncore/multimedia/showimg/ImageFileSelector.cpp
index 7872c09..d2b65a9 100644
--- a/noncore/multimedia/showimg/ImageFileSelector.cpp
+++ b/noncore/multimedia/showimg/ImageFileSelector.cpp
@@ -1,271 +1,271 @@
1 1
2 2
3#include "qpe/global.h" 3#include "qpe/global.h"
4#include "qpe/applnk.h" 4#include "qpe/applnk.h"
5#include "qpe/lnkproperties.h" 5#include "qpe/lnkproperties.h"
6#include "qpe/applnk.h" 6#include "qpe/applnk.h"
7#include "qpe/qpeapplication.h" 7#include "qpe/qpeapplication.h"
8 8
9#include <stdlib.h> 9#include <stdlib.h>
10 10
11#include <qdir.h> 11#include <qdir.h>
12#include <qwidget.h> 12#include <qwidget.h>
13#include <qheader.h> 13#include <qheader.h>
14#include <qimage.h> 14#include <qimage.h>
15#include <qpixmap.h> 15#include <qpixmap.h>
16#include <qlabel.h> 16#include <qlabel.h>
17#include <qfileinfo.h> 17#include <qfileinfo.h>
18#include <qpainter.h> 18#include <qpainter.h>
19#include <qscrollview.h> 19#include <qscrollview.h>
20 20
21#include "ImageFileSelector.h" 21#include "ImageFileSelector.h"
22 22
23 23
24ThumbWidget::ThumbWidget(QPixmap p,QString text,const DocLnk& f,QWidget *parent,int w) 24ThumbWidget::ThumbWidget(QPixmap p,QString text,const DocLnk& f,QWidget *parent,int w)
25 : QWidget( parent ),fl(f) 25 : QWidget( parent ),fl(f)
26{ 26{
27 setBackgroundMode(NoBackground); 27 setBackgroundMode(NoBackground);
28 if ( w!=-1 ) 28 if ( w!=-1 )
29 setMinimumSize(w,p.height()+24); 29 setMinimumSize(w,p.height()+24);
30 else 30 else
31 setMinimumSize(p.width(),p.height()+24); 31 setMinimumSize(p.width(),p.height()+24);
32 description=new QLabel(text,this); 32 description=new QLabel(text,this);
33 description->setBackgroundColor(colorGroup().base()); 33 description->setBackgroundColor(colorGroup().base());
34 description->setAlignment(AlignCenter); 34 description->setAlignment(AlignCenter);
35 description->setGeometry(0,height()-24,width(),24); 35 description->setGeometry(0,height()-24,width(),24);
36 pixmap=p; 36 pixmap=p;
37} 37}
38 38
39void ThumbWidget::resizeEvent(QResizeEvent *) 39void ThumbWidget::resizeEvent(QResizeEvent *)
40{ 40{
41 description->setGeometry(0,height()-24,width(),24); 41 description->setGeometry(0,height()-24,width(),24);
42} 42}
43 43
44void ThumbWidget::paintEvent( QPaintEvent *e ) 44void ThumbWidget::paintEvent( QPaintEvent *e )
45{ 45{
46 QPainter painter(this); 46 QPainter painter(this);
47 47
48 painter.setClipRect(e->rect()); 48 painter.setClipRect(e->rect());
49 painter.fillRect(0,0,width(),height(),QColor(255,255,255)); 49 painter.fillRect(0,0,width(),height(),QColor(255,255,255));
50 painter.drawPixmap((width() - pixmap.width()) / 2,0, pixmap); 50 painter.drawPixmap((width() - pixmap.width()) / 2,0, pixmap);
51 51
52} 52}
53 53
54void ThumbWidget::mouseReleaseEvent(QMouseEvent* ) 54void ThumbWidget::mouseReleaseEvent(QMouseEvent* )
55{ 55{
56 emit clicked(fl); 56 emit clicked(fl);
57} 57}
58 58
59 59
60 60
61ImageFileSelectorItem::ImageFileSelectorItem( QListView *parent, const DocLnk &f) 61ImageFileSelectorItem::ImageFileSelectorItem( QListView *parent, const DocLnk &f)
62 : QListViewItem( parent ), fl( f ) 62 : QListViewItem( parent ), fl( f )
63{ 63{
64 setText( 0, f.name() ); 64 setText( 0, f.name() );
65 QFileInfo fi(f.file()); 65 QFileInfo fi(f.file());
66 setText( 1, (fi.extension()).upper() ); 66 setText( 1, (fi.extension()).upper() );
67 setPixmap( 0, f.pixmap() ); 67 setPixmap( 0, f.pixmap() );
68 68
69 69
70} 70}
71 71
72 72
73ImageFileSelectorItem::~ImageFileSelectorItem() 73ImageFileSelectorItem::~ImageFileSelectorItem()
74{ 74{
75 75
76} 76}
77 77
78 78
79ImageFileSelector::ImageFileSelector( CURRENT_VIEW scv,QWidget *parent,const char * ) 79ImageFileSelector::ImageFileSelector( CURRENT_VIEW scv,QWidget *parent,const char * )
80 : QWidgetStack(parent) 80 : QWidgetStack(parent)
81{ 81{
82 82
83 detailed=new QListView(this); 83 detailed=new QListView(this);
84 84
85 detailed->addColumn (tr("Title")); 85 detailed->addColumn (tr("Title"));
86 detailed->addColumn (tr("Type")); 86 detailed->addColumn (tr("Type"));
87 detailed->setAllColumnsShowFocus( true ); 87 detailed->setAllColumnsShowFocus( true );
88 88
89 tList.setAutoDelete(true); 89 tList.setAutoDelete(true);
90 90
91 thumb =new QScrollView(this); 91 thumb =new QScrollView(this);
92 thumb->setVScrollBarMode (QScrollView::Auto ); 92 thumb->setVScrollBarMode (QScrollView::Auto );
93 thumb->viewport()->setBackgroundColor(colorGroup().base()); 93 thumb->viewport()->setBackgroundColor(colorGroup().base());
94 94
95 background=new QWidget(0); 95 background=new QWidget(0);
96 background->setBackgroundColor(colorGroup().base()); 96 background->setBackgroundColor(colorGroup().base());
97 thumb->addChild(background); 97 thumb->addChild(background);
98 gl = new QGridLayout(background,1,2,4,4); 98 gl = new QGridLayout(background,1,2,4,4);
99 99
100 100
101 101
102 connect( detailed, SIGNAL( mouseButtonClicked( int, QListViewItem *, const QPoint &, int ) ), 102 connect( detailed, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),
103 this, SLOT( fileClicked( int, QListViewItem *, const QPoint &, int ) ) ); 103 this, SLOT( fileClicked(int,QListViewItem*,const QPoint&,int) ) );
104 connect( detailed, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint &, int ) ), 104 connect( detailed, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),
105 this, SLOT( filePressed( int, QListViewItem *, const QPoint &, int ) ) ); 105 this, SLOT( filePressed(int,QListViewItem*,const QPoint&,int) ) );
106 connect( detailed, SIGNAL( returnPressed( QListViewItem * ) ), 106 connect( detailed, SIGNAL( returnPressed(QListViewItem*) ),
107 this, SLOT( fileClicked( QListViewItem * ) ) ); 107 this, SLOT( fileClicked(QListViewItem*) ) );
108 108
109 cView=UNKNOWN; 109 cView=UNKNOWN;
110 setView(scv); 110 setView(scv);
111 reread(); 111 reread();
112 112
113} 113}
114ImageFileSelector::~ImageFileSelector() 114ImageFileSelector::~ImageFileSelector()
115{ 115{
116 116
117} 117}
118 118
119 119
120void ImageFileSelector::switchView() 120void ImageFileSelector::switchView()
121{ 121{
122 CURRENT_VIEW v=cView; 122 CURRENT_VIEW v=cView;
123 123
124 if ( v==DETAILED ) 124 if ( v==DETAILED )
125 v=THUMBNAIL; 125 v=THUMBNAIL;
126 else 126 else
127 v=DETAILED; 127 v=DETAILED;
128 setView(v); 128 setView(v);
129} 129}
130 130
131void ImageFileSelector::setView(CURRENT_VIEW v) 131void ImageFileSelector::setView(CURRENT_VIEW v)
132{ 132{
133 133
134 if ( v==cView ) 134 if ( v==cView )
135 return; 135 return;
136 cView=v; 136 cView=v;
137 137
138 if ( cView!=DETAILED ) 138 if ( cView!=DETAILED )
139 { 139 {
140 raiseWidget(thumb); 140 raiseWidget(thumb);
141 updateSizes(); 141 updateSizes();
142 } 142 }
143 else 143 else
144 { 144 {
145 raiseWidget(detailed); 145 raiseWidget(detailed);
146 updateSizes(); 146 updateSizes();
147 } 147 }
148 148
149 149
150} 150}
151 151
152void ImageFileSelector::resizeEvent(QResizeEvent *) 152void ImageFileSelector::resizeEvent(QResizeEvent *)
153{ 153{
154 updateSizes(); 154 updateSizes();
155} 155}
156 156
157void ImageFileSelector::updateSizes() 157void ImageFileSelector::updateSizes()
158{ 158{
159 int ww=(detailed->width()-detailed->frameWidth()*2); 159 int ww=(detailed->width()-detailed->frameWidth()*2);
160 double w=(double)ww*0.70; 160 double w=(double)ww*0.70;
161 detailed->setColumnWidth(0,(int)w); 161 detailed->setColumnWidth(0,(int)w);
162 detailed->setColumnWidth(1,ww-(int)w); 162 detailed->setColumnWidth(1,ww-(int)w);
163 background->setMinimumWidth(thumb->visibleWidth()); 163 background->setMinimumWidth(thumb->visibleWidth());
164 thumb->updateScrollBars(); 164 thumb->updateScrollBars();
165} 165}
166 166
167void ImageFileSelector::reread(bool) 167void ImageFileSelector::reread(bool)
168{ 168{
169// qDebug("reread"); 169// qDebug("reread");
170 ImageFileSelectorItem *item = (ImageFileSelectorItem *)detailed->selectedItem(); 170 ImageFileSelectorItem *item = (ImageFileSelectorItem *)detailed->selectedItem();
171 QString oldFile; 171 QString oldFile;
172 if ( item ) 172 if ( item )
173 oldFile = item->file().file(); 173 oldFile = item->file().file();
174 detailed->clear(); 174 detailed->clear();
175 tList.clear(); 175 tList.clear();
176 DocLnkSet files; 176 DocLnkSet files;
177 Global::findDocuments(&files, "image/*"); 177 Global::findDocuments(&files, "image/*");
178 count = files.children().count(); 178 count = files.children().count();
179 QListIterator<DocLnk> dit( files.children() ); 179 QListIterator<DocLnk> dit( files.children() );
180// int y=0; 180// int y=0;
181// int x=4; 181// int x=4;
182// int totalHeight=4; 182// int totalHeight=4;
183 ThumbWidget *l=0; 183 ThumbWidget *l=0;
184 int width=80; 184 int width=80;
185 gl->expand(dit.count()/2,2); 185 gl->expand(dit.count()/2,2);
186 int i,j; 186 int i,j;
187 i=j=0; 187 i=j=0;
188 detailed->setUpdatesEnabled(false); 188 detailed->setUpdatesEnabled(false);
189 thumb->setUpdatesEnabled(false); 189 thumb->setUpdatesEnabled(false);
190 190
191 for ( ; dit.current(); ++dit ) { 191 for ( ; dit.current(); ++dit ) {
192 item = new ImageFileSelectorItem( detailed, **dit ); 192 item = new ImageFileSelectorItem( detailed, **dit );
193 if ( item->file().file() == oldFile ) 193 if ( item->file().file() == oldFile )
194 detailed->setCurrentItem( item ); 194 detailed->setCurrentItem( item );
195 } 195 }
196 196
197 QListViewItemIterator it( detailed ); 197 QListViewItemIterator it( detailed );
198 ImageFileSelectorItem *ii; 198 ImageFileSelectorItem *ii;
199 // iterate through all items of the listview 199 // iterate through all items of the listview
200 for ( ; it.current(); ++it ) { 200 for ( ; it.current(); ++it ) {
201 ii=(ImageFileSelectorItem *)it.current(); 201 ii=(ImageFileSelectorItem *)it.current();
202 QImage img( ii->file().file() ); 202 QImage img( ii->file().file() );
203 if( !img.isNull()) { 203 if( !img.isNull()) {
204 img=img.smoothScale(64,64); 204 img=img.smoothScale(64,64);
205 QPixmap pix; 205 QPixmap pix;
206 pix.convertFromImage(img); 206 pix.convertFromImage(img);
207 l=new ThumbWidget(pix,ii->file().name(),ii->file(),background,width); 207 l=new ThumbWidget(pix,ii->file().name(),ii->file(),background,width);
208 l->setBackgroundColor(colorGroup().base()); 208 l->setBackgroundColor(colorGroup().base());
209 gl->addWidget(l,j,i); 209 gl->addWidget(l,j,i);
210 i++; 210 i++;
211 if ( i==2 ) { 211 if ( i==2 ) {
212 i=0; 212 i=0;
213 j++; 213 j++;
214 } 214 }
215 tList.append(l); 215 tList.append(l);
216 connect(l,SIGNAL(clicked(const DocLnk &)),this,SLOT(thumbClicked(const DocLnk &))); 216 connect(l,SIGNAL(clicked(const DocLnk&)),this,SLOT(thumbClicked(const DocLnk&)));
217 } 217 }
218 } 218 }
219 219
220 if ( !detailed->selectedItem() ) 220 if ( !detailed->selectedItem() )
221 detailed->setCurrentItem( detailed->firstChild() ); 221 detailed->setCurrentItem( detailed->firstChild() );
222 222
223 detailed->setUpdatesEnabled(true); 223 detailed->setUpdatesEnabled(true);
224 thumb->setUpdatesEnabled(true); 224 thumb->setUpdatesEnabled(true);
225 detailed->update(); 225 detailed->update();
226 thumb->update(); 226 thumb->update();
227} 227}
228 228
229int ImageFileSelector::fileCount() 229int ImageFileSelector::fileCount()
230{ 230{
231 return count; 231 return count;
232} 232}
233const DocLnk * ImageFileSelector::selected() 233const DocLnk * ImageFileSelector::selected()
234{ 234{
235 qDebug("image selected"); 235 qDebug("image selected");
236 ImageFileSelectorItem *item = (ImageFileSelectorItem *) detailed->selectedItem(); 236 ImageFileSelectorItem *item = (ImageFileSelectorItem *) detailed->selectedItem();
237 if ( item ) 237 if ( item )
238 return new DocLnk( item->file() ); 238 return new DocLnk( item->file() );
239 return 0; 239 return 0;
240} 240}
241 241
242 242
243 243
244void ImageFileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int ) 244void ImageFileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int )
245{ 245{
246 if ( !i ) 246 if ( !i )
247 return; 247 return;
248 if ( button == Qt::LeftButton ) 248 if ( button == Qt::LeftButton )
249 { 249 {
250 fileClicked( i ); 250 fileClicked( i );
251 } 251 }
252} 252}
253 // pressed to get 'right down' 253 // pressed to get 'right down'
254void ImageFileSelector::filePressed( int, QListViewItem *, const QPoint &, int ) 254void ImageFileSelector::filePressed( int, QListViewItem *, const QPoint &, int )
255{ 255{
256 256
257} 257}
258void ImageFileSelector::fileClicked( QListViewItem *i) 258void ImageFileSelector::fileClicked( QListViewItem *i)
259{ 259{
260 if ( !i ) 260 if ( !i )
261 return; 261 return;
262 emit fileSelected( ( (ImageFileSelectorItem*)i )->file() ); 262 emit fileSelected( ( (ImageFileSelectorItem*)i )->file() );
263 emit closeMe(); 263 emit closeMe();
264} 264}
265 265
266void ImageFileSelector::thumbClicked(const DocLnk &f) 266void ImageFileSelector::thumbClicked(const DocLnk &f)
267{ 267{
268 emit fileSelected( f ); 268 emit fileSelected( f );
269 emit closeMe(); 269 emit closeMe();
270} 270}
271 271
diff --git a/noncore/multimedia/showimg/showimg.cpp b/noncore/multimedia/showimg/showimg.cpp
index ba76e57..02a1d91 100644
--- a/noncore/multimedia/showimg/showimg.cpp
+++ b/noncore/multimedia/showimg/showimg.cpp
@@ -1,1251 +1,1251 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21// 21//
22// Full-screen and rotation options contributed by Robert Wittams <robert@wittams.com> 22// Full-screen and rotation options contributed by Robert Wittams <robert@wittams.com>
23// 23//
24 24
25#include "showimg.h" 25#include "showimg.h"
26#include "ImageFileSelector.h" 26#include "ImageFileSelector.h"
27#include "settingsdialog.h" 27#include "settingsdialog.h"
28 28
29 29
30#include <opie/ofiledialog.h> 30#include <opie/ofiledialog.h>
31 31
32#include <qpe/qpeapplication.h> 32#include <qpe/qpeapplication.h>
33#include <qpe/config.h> 33#include <qpe/config.h>
34#include <qpe/resource.h> 34#include <qpe/resource.h>
35#include <qpe/fileselector.h> 35#include <qpe/fileselector.h>
36#include <qpe/applnk.h> 36#include <qpe/applnk.h>
37#include <qfileinfo.h> 37#include <qfileinfo.h>
38#include <math.h> 38#include <math.h>
39#include <qmenubar.h> 39#include <qmenubar.h>
40#include <qwidgetstack.h> 40#include <qwidgetstack.h>
41#include <qpe/qpetoolbar.h> 41#include <qpe/qpetoolbar.h>
42#include <qaction.h> 42#include <qaction.h>
43#include <qfiledialog.h> 43#include <qfiledialog.h>
44#include <qmessagebox.h> 44#include <qmessagebox.h>
45#include <qpopupmenu.h> 45#include <qpopupmenu.h>
46#include <qscrollview.h> 46#include <qscrollview.h>
47#include <qlabel.h> 47#include <qlabel.h>
48#include <qpainter.h> 48#include <qpainter.h>
49#include <qkeycode.h> 49#include <qkeycode.h>
50#include <qapplication.h> 50#include <qapplication.h>
51#include <qclipboard.h> 51#include <qclipboard.h>
52#include <qtimer.h> 52#include <qtimer.h>
53#include <qspinbox.h> 53#include <qspinbox.h>
54 54
55 55
56 56
57ControlsDialog::ControlsDialog(const QString &caption,QImage image,int *brightness,QWidget *parent) 57ControlsDialog::ControlsDialog(const QString &caption,QImage image,int *brightness,QWidget *parent)
58 : QDialog(parent,0,true) 58 : QDialog(parent,0,true)
59{ 59{
60 setCaption(caption); 60 setCaption(caption);
61 61
62 if ( parent ) { 62 if ( parent ) {
63 setPalette(parent->palette()); 63 setPalette(parent->palette());
64 } 64 }
65 65
66 b=brightness; 66 b=brightness;
67 img=image; 67 img=image;
68 68
69 setMinimumSize(140,80); 69 setMinimumSize(140,80);
70 70
71 QGridLayout *gl= new QGridLayout(this,2,2,4,4); 71 QGridLayout *gl= new QGridLayout(this,2,2,4,4);
72 72
73 pixmap =new ImageWidget(this);; 73 pixmap =new ImageWidget(this);;
74 QPixmap pm; 74 QPixmap pm;
75 pm.convertFromImage(img); 75 pm.convertFromImage(img);
76 pixmap->setPixmap(pm); 76 pixmap->setPixmap(pm);
77 pixmap->setMinimumSize(pm.width(),pm.height()); 77 pixmap->setMinimumSize(pm.width(),pm.height());
78 gl->addMultiCellWidget(pixmap,0,0,0,2,AlignCenter); 78 gl->addMultiCellWidget(pixmap,0,0,0,2,AlignCenter);
79 QLabel *l=new QLabel(tr("Brightness")+":",this); 79 QLabel *l=new QLabel(tr("Brightness")+":",this);
80 gl->addWidget(l,1,0,AlignLeft); 80 gl->addWidget(l,1,0,AlignLeft);
81 spb=new QSpinBox(-100,100,2,this); 81 spb=new QSpinBox(-100,100,2,this);
82 gl->addWidget(spb,1,1,AlignRight); 82 gl->addWidget(spb,1,1,AlignRight);
83 83
84 spb->setValue(0); 84 spb->setValue(0);
85 85
86 connect(spb,SIGNAL(valueChanged(int)),this, SLOT(bValueChanged(int))); 86 connect(spb,SIGNAL(valueChanged(int)),this, SLOT(bValueChanged(int)));
87 87
88} 88}
89 89
90void ControlsDialog::bValueChanged(int value) 90void ControlsDialog::bValueChanged(int value)
91{ 91{
92 QImage nImage=img; 92 QImage nImage=img;
93 nImage.detach(); 93 nImage.detach();
94 ImageViewer::intensity(nImage, (float)value/100); 94 ImageViewer::intensity(nImage, (float)value/100);
95 QPixmap pm; 95 QPixmap pm;
96 pm.convertFromImage(nImage); 96 pm.convertFromImage(nImage);
97 pixmap->setPixmap(pm); 97 pixmap->setPixmap(pm);
98 pixmap->repaint(false); 98 pixmap->repaint(false);
99 99
100 100
101} 101}
102 102
103void ControlsDialog::accept() 103void ControlsDialog::accept()
104{ 104{
105 *b=spb->value(); 105 *b=spb->value();
106 done(1); 106 done(1);
107} 107}
108 108
109//=========================================================================== 109//===========================================================================
110 110
111InfoDialog::InfoDialog(const QString &caption, const QStringList text,QWidget *parent) 111InfoDialog::InfoDialog(const QString &caption, const QStringList text,QWidget *parent)
112 : QDialog(parent,0,true) 112 : QDialog(parent,0,true)
113{ 113{
114 setCaption(caption); 114 setCaption(caption);
115 115
116 if ( parent ) 116 if ( parent )
117 { 117 {
118 setPalette(parent->palette()); 118 setPalette(parent->palette());
119 } 119 }
120 120
121 121
122 122
123 QString labels[]={ tr("File Name"),tr("Format"),tr("File Size"),tr("Size"),tr("Colors"),tr("Alpha") }; 123 QString labels[]={ tr("File Name"),tr("Format"),tr("File Size"),tr("Size"),tr("Colors"),tr("Alpha") };
124 124
125 setMinimumSize(180,80); 125 setMinimumSize(180,80);
126 int num=ImageViewer::LAST+1; 126 int num=ImageViewer::LAST+1;
127 if ( text[ImageViewer::ALPHA].isEmpty() ) 127 if ( text[ImageViewer::ALPHA].isEmpty() )
128 num--; 128 num--;
129 QGridLayout *gl= new QGridLayout(this,num,2,4,2); 129 QGridLayout *gl= new QGridLayout(this,num,2,4,2);
130 QLabel *l; 130 QLabel *l;
131 int count=0; 131 int count=0;
132 for ( int i=0;i<num;i++ ) 132 for ( int i=0;i<num;i++ )
133 { 133 {
134 if ( i==1 ) 134 if ( i==1 )
135 { 135 {
136 QFrame *frm=new QFrame(this); 136 QFrame *frm=new QFrame(this);
137 frm->setFrameStyle(QFrame::HLine|QFrame::Sunken); 137 frm->setFrameStyle(QFrame::HLine|QFrame::Sunken);
138 gl->addMultiCellWidget(frm,i,i,0,1); 138 gl->addMultiCellWidget(frm,i,i,0,1);
139 } 139 }
140 else 140 else
141 { 141 {
142 l=new QLabel( tr( labels[count] )+":",this); 142 l=new QLabel( tr( labels[count] )+":",this);
143 gl->addWidget(l,i,0,AlignLeft); 143 gl->addWidget(l,i,0,AlignLeft);
144 l=new QLabel(text[count],this); 144 l=new QLabel(text[count],this);
145 gl->addWidget(l,i,1,AlignRight); 145 gl->addWidget(l,i,1,AlignRight);
146 count++; 146 count++;
147 } 147 }
148 148
149 } 149 }
150 150
151} 151}
152 152
153void InfoDialog::displayInfo(const QString &caption, const QStringList text, QWidget *parent) 153void InfoDialog::displayInfo(const QString &caption, const QStringList text, QWidget *parent)
154{ 154{
155 InfoDialog *dlg=new InfoDialog(caption,text,parent); 155 InfoDialog *dlg=new InfoDialog(caption,text,parent);
156 dlg->exec(); 156 dlg->exec();
157 delete dlg; 157 delete dlg;
158} 158}
159 159
160//=========================================================================== 160//===========================================================================
161 161
162 162
163ImagePane::ImagePane( QWidget *parent ) : QWidget( parent ) 163ImagePane::ImagePane( QWidget *parent ) : QWidget( parent )
164{ 164{
165 vb = new QVBoxLayout( this ); 165 vb = new QVBoxLayout( this );
166 166
167 image = new QScrollView(this,0,WResizeNoErase|WNorthWestGravity); 167 image = new QScrollView(this,0,WResizeNoErase|WNorthWestGravity);
168 pic=new ImageWidget(image); 168 pic=new ImageWidget(image);
169 image->addChild(pic); 169 image->addChild(pic);
170 170
171 connect(pic, SIGNAL( clicked() ), this, SLOT( imageClicked() )); 171 connect(pic, SIGNAL( clicked() ), this, SLOT( imageClicked() ));
172 172
173 vb->addWidget( image ); 173 vb->addWidget( image );
174 174
175} 175}
176 176
177void ImagePane::setPixmap( const QPixmap &pm ) 177void ImagePane::setPixmap( const QPixmap &pm )
178{ 178{
179 pic->setPixmap( pm ); 179 pic->setPixmap( pm );
180 pic->resize(pm.width(),pm.height()); 180 pic->resize(pm.width(),pm.height());
181 image->updateScrollBars (); 181 image->updateScrollBars ();
182 pic->repaint(false); 182 pic->repaint(false);
183} 183}
184 184
185void ImagePane::imageClicked() 185void ImagePane::imageClicked()
186{ 186{
187 emit clicked(); 187 emit clicked();
188} 188}
189//=========================================================================== 189//===========================================================================
190/* 190/*
191 Draws the portion of the scaled pixmap that needs to be updated 191 Draws the portion of the scaled pixmap that needs to be updated
192*/ 192*/
193 193
194void ImageWidget::paintEvent( QPaintEvent *e ) 194void ImageWidget::paintEvent( QPaintEvent *e )
195{ 195{
196 QPainter painter(this); 196 QPainter painter(this);
197 197
198 painter.setClipRect(e->rect()); 198 painter.setClipRect(e->rect());
199 painter.fillRect(0,0,width(),height(),QColor(0,0,0)); 199 painter.fillRect(0,0,width(),height(),QColor(0,0,0));
200 200
201 if ( pixmap.size() != QSize( 0, 0 ) ) 201 if ( pixmap.size() != QSize( 0, 0 ) )
202 { // is an image loaded? 202 { // is an image loaded?
203 painter.drawPixmap((width() - pixmap.width()) / 2, (height() - pixmap.height()) / 2, pixmap); 203 painter.drawPixmap((width() - pixmap.width()) / 2, (height() - pixmap.height()) / 2, pixmap);
204 } 204 }
205} 205}
206 206
207void ImageWidget::mouseReleaseEvent(QMouseEvent *) 207void ImageWidget::mouseReleaseEvent(QMouseEvent *)
208{ 208{
209 emit clicked(); 209 emit clicked();
210} 210}
211 211
212//=========================================================================== 212//===========================================================================
213 213
214ImageViewer::ImageViewer( QWidget *parent, const char *name, int wFlags ) 214ImageViewer::ImageViewer( QWidget *parent, const char *name, int wFlags )
215: QMainWindow( parent, name, WResizeNoErase ), filename( 0 ), bFromDocView( FALSE ) 215: QMainWindow( parent, name, WResizeNoErase ), filename( 0 ), bFromDocView( FALSE )
216{ 216{
217 setCaption( tr("Image Viewer") ); 217 setCaption( tr("Image Viewer") );
218 setIcon( Resource::loadPixmap( "ImageViewer" ) ); 218 setIcon( Resource::loadPixmap( "ImageViewer" ) );
219 219
220 220
221 Config cfg("Image Viewer"); 221 Config cfg("Image Viewer");
222 cfg.setGroup("Image Viewer"); 222 cfg.setGroup("Image Viewer");
223 223
224 showThumbView=cfg.readBoolEntry("ShowThumbnails",false); 224 showThumbView=cfg.readBoolEntry("ShowThumbnails",false);
225 isSized=cfg.readBoolEntry("SizeToScreen",true); 225 isSized=cfg.readBoolEntry("SizeToScreen",true);
226 226
227 isFullScreen = FALSE; 227 isFullScreen = FALSE;
228 228
229 setToolBarsMovable( FALSE ); 229 setToolBarsMovable( FALSE );
230 230
231 toolBar = new QToolBar( this ); 231 toolBar = new QToolBar( this );
232 toolBar->setHorizontalStretchable( TRUE ); 232 toolBar->setHorizontalStretchable( TRUE );
233 233
234 menuBar = new QMenuBar( toolBar ); 234 menuBar = new QMenuBar( toolBar );
235 235
236 current=menuBar; 236 current=menuBar;
237 237
238 238
239 239
240 fileMenuFile = new QPopupMenu(this); 240 fileMenuFile = new QPopupMenu(this);
241 //menuBarmenubarFile->insertItem( tr("File"), fileMenu ); 241 //menuBarmenubarFile->insertItem( tr("File"), fileMenu );
242 fileMenuFile->insertItem(tr("Open"), 242 fileMenuFile->insertItem(tr("Open"),
243 this, SLOT(openFile()), 0); 243 this, SLOT(openFile()), 0);
244 244
245 viewMenuFile = new QPopupMenu( this ); 245 viewMenuFile = new QPopupMenu( this );
246 //menubarFile->insertItem( tr("View"), viewMenu ); 246 //menubarFile->insertItem( tr("View"), viewMenu );
247 viewMenuFile->insertItem( tr("Thumbnail View"), 247 viewMenuFile->insertItem( tr("Thumbnail View"),
248 this, SLOT(switchThumbView()), 0, SHOW_THUMBNAILS ); 248 this, SLOT(switchThumbView()), 0, SHOW_THUMBNAILS );
249 249
250 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView ); 250 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView );
251 251
252 252
253 253
254 254
255 optionsMenuFile = new QPopupMenu( this); 255 optionsMenuFile = new QPopupMenu( this);
256 //menubarFile->insertItem( tr("Options"),optionsMenu ); 256 //menubarFile->insertItem( tr("Options"),optionsMenu );
257 slideAction = new QAction( tr( "Slide show" ), Resource::loadIconSet( "slideshow" ), 257 slideAction = new QAction( tr( "Slide show" ), Resource::loadIconSet( "slideshow" ),
258 QString::null, 0, this, 0 ); 258 QString::null, 0, this, 0 );
259 slideAction->setToggleAction( TRUE ); 259 slideAction->setToggleAction( TRUE );
260 connect( slideAction, SIGNAL( toggled(bool) ), this, SLOT( slideShow(bool) ) ); 260 connect( slideAction, SIGNAL( toggled(bool) ), this, SLOT( slideShow(bool) ) );
261 slideAction->addTo( optionsMenuFile); 261 slideAction->addTo( optionsMenuFile);
262// slideAction->addTo( toolBar ); 262// slideAction->addTo( toolBar );
263 263
264 264
265// optionsMenuFile->insertItem( tr("Slideshow") ); 265// optionsMenuFile->insertItem( tr("Slideshow") );
266 optionsMenuFile->insertSeparator(); 266 optionsMenuFile->insertSeparator();
267 optionsMenuFile->insertItem( tr("Preferences.."), this, SLOT(settings()), 0); 267 optionsMenuFile->insertItem( tr("Preferences.."), this, SLOT(settings()), 0);
268// optionsMenuFile->insertItem( tr("Help"), this, SLOT(help()), 0); 268// optionsMenuFile->insertItem( tr("Help"), this, SLOT(help()), 0);
269 269
270 QStrList fmt = QImage::outputFormats(); 270 QStrList fmt = QImage::outputFormats();
271 271
272 272
273 fileMenuView = new QPopupMenu( this ); 273 fileMenuView = new QPopupMenu( this );
274 //menubarView->insertItem( tr("File"),fileMenu ); 274 //menubarView->insertItem( tr("File"),fileMenu );
275 fileMenuView->insertItem( tr("Image Info ..."),this, SLOT(displayInfoDialog()),0 ); 275 fileMenuView->insertItem( tr("Image Info ..."),this, SLOT(displayInfoDialog()),0 );
276 fileMenuView->insertSeparator(); 276 fileMenuView->insertSeparator();
277 277
278 viewMenuView = new QPopupMenu(this ); 278 viewMenuView = new QPopupMenu(this );
279 viewMenuView->setCheckable ( true ); 279 viewMenuView->setCheckable ( true );
280 280
281 //menubarView->insertItem( tr("View"),viewMenu ); 281 //menubarView->insertItem( tr("View"),viewMenu );
282 viewMenuView->insertItem(tr("Horizontal flip"), this, SLOT(hFlip()), 0); 282 viewMenuView->insertItem(tr("Horizontal flip"), this, SLOT(hFlip()), 0);
283 viewMenuView->insertItem(tr("Vertical flip"), this, SLOT(vFlip()), 0); 283 viewMenuView->insertItem(tr("Vertical flip"), this, SLOT(vFlip()), 0);
284 284
285 stack = new QWidgetStack( this ); 285 stack = new QWidgetStack( this );
286 stack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); 286 stack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
287 setCentralWidget( stack ); 287 setCentralWidget( stack );
288 288
289 289
290 imagePanel = new ImagePane( stack ); 290 imagePanel = new ImagePane( stack );
291 connect(imagePanel, SIGNAL(clicked()), this, SLOT(normalView())); 291 connect(imagePanel, SIGNAL(clicked()), this, SLOT(normalView()));
292 292
293 293
294 ImageFileSelector::CURRENT_VIEW cv; 294 ImageFileSelector::CURRENT_VIEW cv;
295 if(showThumbView) 295 if(showThumbView)
296 cv=ImageFileSelector::THUMBNAIL; 296 cv=ImageFileSelector::THUMBNAIL;
297 else 297 else
298 cv=ImageFileSelector::DETAILED; 298 cv=ImageFileSelector::DETAILED;
299 299
300 qDebug("cv = %d",cv); 300 qDebug("cv = %d",cv);
301 301
302 fileSelector = new ImageFileSelector( cv,stack, "fs"); 302 fileSelector = new ImageFileSelector( cv,stack, "fs");
303 303
304 //switchThumbView(); 304 //switchThumbView();
305 305
306 306
307 //fileSelector = new ImageFileSelector("image/*", stack, "fs"); 307 //fileSelector = new ImageFileSelector("image/*", stack, "fs");
308 //fileSelector->setNewVisible(FALSE); 308 //fileSelector->setNewVisible(FALSE);
309 //fileSelector->setCloseVisible(FALSE); 309 //fileSelector->setCloseVisible(FALSE);
310 connect( fileSelector, SIGNAL( closeMe() ), this, SLOT( closeFileSelector() ) ); 310 connect( fileSelector, SIGNAL( closeMe() ), this, SLOT( closeFileSelector() ) );
311 connect( fileSelector, SIGNAL( fileSelected( const DocLnk &) ), 311 connect( fileSelector, SIGNAL( fileSelected(const DocLnk&) ),
312 this, SLOT( openFile( const DocLnk & ) ) ); 312 this, SLOT( openFile(const DocLnk&) ) );
313 313
314 imageList = fileSelector->fileList(); 314 imageList = fileSelector->fileList();
315 slideAction->setEnabled( imageList.count() != 0); 315 slideAction->setEnabled( imageList.count() != 0);
316 316
317 iconToolBar = new QToolBar(this); 317 iconToolBar = new QToolBar(this);
318 318
319 QAction *a; 319 QAction *a;
320 320
321 a = new QAction( tr( "Open ..." ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); 321 a = new QAction( tr( "Open ..." ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 );
322 connect( a, SIGNAL( activated() ), this, SLOT( open() ) ); 322 connect( a, SIGNAL( activated() ), this, SLOT( open() ) );
323 a->addTo( fileMenuView); 323 a->addTo( fileMenuView);
324 a->addTo( iconToolBar ); 324 a->addTo( iconToolBar );
325 325
326 326
327 a = new QAction( tr( "Rotate 90"), Resource::loadPixmap( "rotate90" ), QString::null, 0, this, 0); 327 a = new QAction( tr( "Rotate 90"), Resource::loadPixmap( "rotate90" ), QString::null, 0, this, 0);
328 connect( a, SIGNAL( activated() ), this, SLOT( rot90() ) ); 328 connect( a, SIGNAL( activated() ), this, SLOT( rot90() ) );
329 a->addTo( iconToolBar ); 329 a->addTo( iconToolBar );
330 a->addTo( viewMenuView ); 330 a->addTo( viewMenuView );
331 331
332 a = new QAction( tr( "Rotate 180" ), Resource::loadPixmap( "repeat" ), QString::null, 0, this, 0 ); 332 a = new QAction( tr( "Rotate 180" ), Resource::loadPixmap( "repeat" ), QString::null, 0, this, 0 );
333 connect( a, SIGNAL( activated() ), this, SLOT( rot180() ) ); 333 connect( a, SIGNAL( activated() ), this, SLOT( rot180() ) );
334 a->addTo( iconToolBar ); 334 a->addTo( iconToolBar );
335 a->addTo( viewMenuView ); 335 a->addTo( viewMenuView );
336 336
337 337
338 a = new QAction( tr( "Rotate 270"), Resource::loadPixmap( "rotate270" ), QString::null, 0, this, 0); 338 a = new QAction( tr( "Rotate 270"), Resource::loadPixmap( "rotate270" ), QString::null, 0, this, 0);
339 connect( a, SIGNAL( activated() ), this, SLOT( rot270() ) ); 339 connect( a, SIGNAL( activated() ), this, SLOT( rot270() ) );
340 //a->addTo( iconToolBar ); 340 //a->addTo( iconToolBar );
341 a->addTo( viewMenuView ); 341 a->addTo( viewMenuView );
342 342
343 343
344 344
345 viewMenuView->insertSeparator(); 345 viewMenuView->insertSeparator();
346 viewMenuView->insertItem(tr("Brightness ..."), this, SLOT(displayControlsDialog()), 0); 346 viewMenuView->insertItem(tr("Brightness ..."), this, SLOT(displayControlsDialog()), 0);
347 viewMenuView->insertItem(tr("Black And White"), this, SLOT(blackAndWhite()), 0,BLACKANDWHITE); 347 viewMenuView->insertItem(tr("Black And White"), this, SLOT(blackAndWhite()), 0,BLACKANDWHITE);
348 viewMenuView->insertSeparator(); 348 viewMenuView->insertSeparator();
349 349
350 350
351 sss = new QAction( tr( "Scale to Screen"), Resource::loadPixmap( "scale" ), QString::null, 0, this, 0,true); 351 sss = new QAction( tr( "Scale to Screen"), Resource::loadPixmap( "scale" ), QString::null, 0, this, 0,true);
352 connect( sss, SIGNAL( activated() ), this, SLOT( switchSizeToScreen() ) ); 352 connect( sss, SIGNAL( activated() ), this, SLOT( switchSizeToScreen() ) );
353 sss->addTo( iconToolBar ); 353 sss->addTo( iconToolBar );
354 sss->addTo( viewMenuView ); 354 sss->addTo( viewMenuView );
355 355
356 sss->setOn(isSized); 356 sss->setOn(isSized);
357 viewMenuView->insertSeparator(); 357 viewMenuView->insertSeparator();
358 358
359 359
360 a = new QAction( tr( "Fullscreen" ), Resource::loadPixmap( "fullscreen" ), 360 a = new QAction( tr( "Fullscreen" ), Resource::loadPixmap( "fullscreen" ),
361 QString::null, 0, this, 0 ); 361 QString::null, 0, this, 0 );
362 connect( a, SIGNAL( activated() ), this, SLOT( fullScreen() ) ); 362 connect( a, SIGNAL( activated() ), this, SLOT( fullScreen() ) );
363 a->addTo( iconToolBar ); 363 a->addTo( iconToolBar );
364 a->addTo( viewMenuView); 364 a->addTo( viewMenuView);
365 365
366 a = new QAction( tr( "Stop Slideshow" ), Resource::loadPixmap( "quit_icon" ), 366 a = new QAction( tr( "Stop Slideshow" ), Resource::loadPixmap( "quit_icon" ),
367 QString::null, 0, this, 0 ); 367 QString::null, 0, this, 0 );
368 connect( a, SIGNAL( activated() ), this, SLOT( stopSlideShow() ) ); 368 connect( a, SIGNAL( activated() ), this, SLOT( stopSlideShow() ) );
369 a->addTo( iconToolBar ); 369 a->addTo( iconToolBar );
370 a->addTo( viewMenuView); 370 a->addTo( viewMenuView);
371 371
372 372
373 Config config( "ImageViewer" ); 373 Config config( "ImageViewer" );
374 config.setGroup( "SlideShow" ); 374 config.setGroup( "SlideShow" );
375 slideDelay = config.readNumEntry( "Delay", 2); 375 slideDelay = config.readNumEntry( "Delay", 2);
376 slideRepeat = config.readBoolEntry( "Repeat", FALSE ); 376 slideRepeat = config.readBoolEntry( "Repeat", FALSE );
377 slideReverse = config.readBoolEntry("Reverse", FALSE); 377 slideReverse = config.readBoolEntry("Reverse", FALSE);
378 378
379 config.setGroup("Default"); 379 config.setGroup("Default");
380 rotateOnLoad = config.readBoolEntry("Rotate", FALSE); 380 rotateOnLoad = config.readBoolEntry("Rotate", FALSE);
381 fastLoad = config.readBoolEntry("FastLoad", TRUE); 381 fastLoad = config.readBoolEntry("FastLoad", TRUE);
382 slideTimer = new QTimer( this ); 382 slideTimer = new QTimer( this );
383 connect( slideTimer, SIGNAL(timeout()), this, SLOT(slideUpdate()) ); 383 connect( slideTimer, SIGNAL(timeout()), this, SLOT(slideUpdate()) );
384 384
385 switchToFileSelector(); 385 switchToFileSelector();
386 386
387 setMouseTracking( TRUE ); 387 setMouseTracking( TRUE );
388 388
389 389
390} 390}
391 391
392ImageViewer::~ImageViewer() 392ImageViewer::~ImageViewer()
393{ 393{
394 Config cfg("Image Viewer"); 394 Config cfg("Image Viewer");
395 cfg.setGroup("Image Viewer"); 395 cfg.setGroup("Image Viewer");
396 396
397 cfg.writeEntry("ShowThumbnails",(int)showThumbView); 397 cfg.writeEntry("ShowThumbnails",(int)showThumbView);
398 cfg.writeEntry("SizeToScreen",(int)isSized); 398 cfg.writeEntry("SizeToScreen",(int)isSized);
399 399
400 cfg.setGroup( "SlideShow" ); 400 cfg.setGroup( "SlideShow" );
401 cfg.writeEntry( "Delay", slideDelay); 401 cfg.writeEntry( "Delay", slideDelay);
402 cfg.writeEntry( "Repeat", slideRepeat ); 402 cfg.writeEntry( "Repeat", slideRepeat );
403 cfg.writeEntry("Reverse", slideReverse); 403 cfg.writeEntry("Reverse", slideReverse);
404 404
405 cfg.setGroup("Default"); 405 cfg.setGroup("Default");
406 cfg.writeEntry("Rotate", rotateOnLoad); 406 cfg.writeEntry("Rotate", rotateOnLoad);
407 cfg.writeEntry("FastLoad", fastLoad); 407 cfg.writeEntry("FastLoad", fastLoad);
408 408
409 delete imagePanel; // in case it is fullscreen 409 delete imagePanel; // in case it is fullscreen
410} 410}
411 411
412void ImageViewer::help() { 412void ImageViewer::help() {
413 413
414} 414}
415 415
416 416
417void ImageViewer::settings() 417void ImageViewer::settings()
418{ 418{
419 SettingsDialog dlg( this, 0, TRUE ); 419 SettingsDialog dlg( this, 0, TRUE );
420 dlg.setDelay( slideDelay ); 420 dlg.setDelay( slideDelay );
421 dlg.setRepeat( slideRepeat ); 421 dlg.setRepeat( slideRepeat );
422 dlg.setReverse( slideReverse ); 422 dlg.setReverse( slideReverse );
423 dlg.setRotate(rotateOnLoad); 423 dlg.setRotate(rotateOnLoad);
424 dlg.setFastLoad(fastLoad); 424 dlg.setFastLoad(fastLoad);
425 425
426 if ( QPEApplication::execDialog(&dlg) == QDialog::Accepted ) { 426 if ( QPEApplication::execDialog(&dlg) == QDialog::Accepted ) {
427 qDebug("<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>"); 427 qDebug("<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>");
428 slideDelay = dlg.delay(); 428 slideDelay = dlg.delay();
429 slideRepeat = dlg.repeat(); 429 slideRepeat = dlg.repeat();
430 slideReverse = dlg.reverse(); 430 slideReverse = dlg.reverse();
431 rotateOnLoad = dlg.rotate(); 431 rotateOnLoad = dlg.rotate();
432 fastLoad = dlg.fastLoad(); 432 fastLoad = dlg.fastLoad();
433 433
434 Config config( "ImageViewer" ); 434 Config config( "ImageViewer" );
435 config.setGroup( "SlideShow" ); 435 config.setGroup( "SlideShow" );
436 config.writeEntry( "Delay", slideDelay ); 436 config.writeEntry( "Delay", slideDelay );
437 config.writeEntry( "Repeat", slideRepeat ); 437 config.writeEntry( "Repeat", slideRepeat );
438 config.writeEntry("Reverse", slideReverse); 438 config.writeEntry("Reverse", slideReverse);
439 439
440 config.setGroup("Default"); 440 config.setGroup("Default");
441 config.writeEntry("Rotate", rotateOnLoad); 441 config.writeEntry("Rotate", rotateOnLoad);
442 config.writeEntry("FastLoad", fastLoad); 442 config.writeEntry("FastLoad", fastLoad);
443 } 443 }
444} 444}
445 445
446void ImageViewer::switchSizeToScreen() 446void ImageViewer::switchSizeToScreen()
447{ 447{
448 isSized=!isSized; 448 isSized=!isSized;
449 sss->setOn(isSized); 449 sss->setOn(isSized);
450 updateImage(); 450 updateImage();
451} 451}
452 452
453void ImageViewer::updateImage() 453void ImageViewer::updateImage()
454{ 454{
455 if ( isSized ) { 455 if ( isSized ) {
456 imagePanel->setPixmap(pmScaled); 456 imagePanel->setPixmap(pmScaled);
457 } else { 457 } else {
458 imagePanel->setPixmap(pm); 458 imagePanel->setPixmap(pm);
459 } 459 }
460} 460}
461 461
462void ImageViewer::switchThumbView() 462void ImageViewer::switchThumbView()
463{ 463{
464 464
465 showThumbView=!showThumbView; 465 showThumbView=!showThumbView;
466 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView ); 466 viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView );
467 fileSelector->switchView(); 467 fileSelector->switchView();
468 468
469} 469}
470 470
471void ImageViewer::switchToFileSelector() 471void ImageViewer::switchToFileSelector()
472{ 472{
473 stack->raiseWidget(fileSelector); 473 stack->raiseWidget(fileSelector);
474 menuBar->clear(); 474 menuBar->clear();
475 menuBar->insertItem( tr("File"), fileMenuFile ); 475 menuBar->insertItem( tr("File"), fileMenuFile );
476 menuBar->insertItem( tr("View"), viewMenuFile ); 476 menuBar->insertItem( tr("View"), viewMenuFile );
477 menuBar->insertItem( tr("Options"), optionsMenuFile ); 477 menuBar->insertItem( tr("Options"), optionsMenuFile );
478 iconToolBar->hide(); 478 iconToolBar->hide();
479 imagePanel->disable(); 479 imagePanel->disable();
480 slideShow(false); 480 slideShow(false);
481 481
482} 482}
483 483
484void ImageViewer::switchToImageView() 484void ImageViewer::switchToImageView()
485{ 485{
486 stack->raiseWidget(imagePanel); 486 stack->raiseWidget(imagePanel);
487 487
488 menuBar->clear(); 488 menuBar->clear();
489 menuBar->insertItem( tr("File"), fileMenuView ); 489 menuBar->insertItem( tr("File"), fileMenuView );
490 menuBar->insertItem( tr("View"), viewMenuView ); 490 menuBar->insertItem( tr("View"), viewMenuView );
491 viewMenuView->setItemEnabled(BLACKANDWHITE,true); 491 viewMenuView->setItemEnabled(BLACKANDWHITE,true);
492 iconToolBar->show(); 492 iconToolBar->show();
493 493
494 imagePanel->setPosition(0,0); 494 imagePanel->setPosition(0,0);
495 495
496} 496}
497 497
498 498
499void ImageViewer::setDocument(const QString& fileref) 499void ImageViewer::setDocument(const QString& fileref)
500{ 500{
501 delayLoad = fileref; 501 delayLoad = fileref;
502 switchToImageView(); 502 switchToImageView();
503 QTimer::singleShot( 0, this, SLOT(doDelayedLoad()) ); 503 QTimer::singleShot( 0, this, SLOT(doDelayedLoad()) );
504} 504}
505 505
506void ImageViewer::doDelayedLoad() 506void ImageViewer::doDelayedLoad()
507{ 507{
508 show(delayLoad); 508 show(delayLoad);
509} 509}
510 510
511void ImageViewer::show() 511void ImageViewer::show()
512{ 512{
513 normalView(); 513 normalView();
514 QMainWindow::show(); 514 QMainWindow::show();
515} 515}
516 516
517void ImageViewer::show(const QString& fileref) 517void ImageViewer::show(const QString& fileref)
518{ 518{
519// qDebug("Show "+fileref); 519// qDebug("Show "+fileref);
520 bFromDocView = TRUE; 520 bFromDocView = TRUE;
521 closeFileSelector(); 521 closeFileSelector();
522 DocLnk link(fileref); 522 DocLnk link(fileref);
523 if ( link.isValid() ) { 523 if ( link.isValid() ) {
524 openFile(link); 524 openFile(link);
525 } else { 525 } else {
526 filename = fileref; 526 filename = fileref;
527 updateCaption( fileref ); 527 updateCaption( fileref );
528 loadImage( fileref ); 528 loadImage( fileref );
529 } 529 }
530} 530}
531 531
532void ImageViewer::openFile() { 532void ImageViewer::openFile() {
533 MimeTypes types; 533 MimeTypes types;
534 QStringList image; 534 QStringList image;
535 image << "image/*"; 535 image << "image/*";
536 types.insert("Images", image); 536 types.insert("Images", image);
537 537
538 QString str = OFileDialog::getOpenFileName( 1,QPEApplication::documentDir(),"", types, 0 ); 538 QString str = OFileDialog::getOpenFileName( 1,QPEApplication::documentDir(),"", types, 0 );
539 DocLnk link(str); 539 DocLnk link(str);
540// if ( link.isValid() ) 540// if ( link.isValid() )
541 openFile(link); 541 openFile(link);
542 542
543} 543}
544 544
545void ImageViewer::openFile( const DocLnk &link ) 545void ImageViewer::openFile( const DocLnk &link )
546{ 546{
547 closeFileSelector(); 547 closeFileSelector();
548// DocLnk link(file); 548// DocLnk link(file);
549 qDebug("open "+link.name()); 549 qDebug("open "+link.name());
550 updateCaption( link.name() ); 550 updateCaption( link.name() );
551 loadImage( link.file() ); 551 loadImage( link.file() );
552 if (slideTimer->isActive()) { 552 if (slideTimer->isActive()) {
553 slideTimer->start(slideDelay * 1000, FALSE); 553 slideTimer->start(slideDelay * 1000, FALSE);
554 } 554 }
555 555
556} 556}
557 557
558void ImageViewer::open() 558void ImageViewer::open()
559{ 559{
560 switchToFileSelector(); 560 switchToFileSelector();
561} 561}
562 562
563void ImageViewer::closeFileSelector() 563void ImageViewer::closeFileSelector()
564{ 564{
565 switchToImageView(); 565 switchToImageView();
566} 566}
567 567
568void ImageViewer::updateCaption( QString name ) 568void ImageViewer::updateCaption( QString name )
569{ 569{
570 int sep = name.findRev( '/' ); 570 int sep = name.findRev( '/' );
571 if ( sep >= 0 ) 571 if ( sep >= 0 )
572 name = name.mid( sep+1 ); 572 name = name.mid( sep+1 );
573 setCaption( name + tr(" - Image Viewer") ); 573 setCaption( name + tr(" - Image Viewer") );
574} 574}
575 575
576/* 576/*
577 This function loads an image from a file. 577 This function loads an image from a file.
578*/ 578*/
579 579
580void ImageViewer::loadImage( const char *fileName ) 580void ImageViewer::loadImage( const char *fileName )
581{ 581{
582 filename = fileName; 582 filename = fileName;
583 if ( filename ) { 583 if ( filename ) {
584 QApplication::setOverrideCursor( waitCursor ); // this might take time 584 QApplication::setOverrideCursor( waitCursor ); // this might take time
585 //imagePanel->statusLabel()->setText( tr("Loading image...") ); 585 //imagePanel->statusLabel()->setText( tr("Loading image...") );
586 qApp->processEvents(); 586 qApp->processEvents();
587 bool ok = image.load(filename, 0); 587 bool ok = image.load(filename, 0);
588 if ( ok ) { 588 if ( ok ) {
589 ok = reconvertImage(); 589 ok = reconvertImage();
590 updateImageInfo(filename); 590 updateImageInfo(filename);
591 } 591 }
592 if ( !ok ) { 592 if ( !ok ) {
593 pm.resize(0,0); // couldn't load image 593 pm.resize(0,0); // couldn't load image
594 update(); 594 update();
595 } 595 }
596 QApplication::restoreOverrideCursor(); // restore original cursor 596 QApplication::restoreOverrideCursor(); // restore original cursor
597 } 597 }
598 598
599// fastLoad ? ", Fast" : "", 599// fastLoad ? ", Fast" : "",
600// fastLoad ? QMAX(imagewidth/maxsize, imageheight/maxsize) : 1); 600// fastLoad ? QMAX(imagewidth/maxsize, imageheight/maxsize) : 1);
601 601
602 602
603// matrix.reset(); 603// matrix.reset();
604 rotated90 = FALSE; 604 rotated90 = FALSE;
605 605
606 if (rotateOnLoad) { 606 if (rotateOnLoad) {
607 rotated90 = TRUE; 607 rotated90 = TRUE;
608 rot90(); 608 rot90();
609// matrix.rotate( -90.0 ); 609// matrix.rotate( -90.0 );
610 } 610 }
611 611
612 switchToImageView(); 612 switchToImageView();
613 updateImage(); 613 updateImage();
614 614
615} 615}
616 616
617bool ImageViewer::loadSelected() 617bool ImageViewer::loadSelected()
618{ 618{
619 bool ok = false; 619 bool ok = false;
620 if ( stack->visibleWidget() == fileSelector ) 620 if ( stack->visibleWidget() == fileSelector )
621 { 621 {
622 const DocLnk *link = fileSelector->selected(); 622 const DocLnk *link = fileSelector->selected();
623 if ( link ) 623 if ( link )
624 { 624 {
625 if ( link->file() != filename ) 625 if ( link->file() != filename )
626 { 626 {
627 updateCaption( link->name() ); 627 updateCaption( link->name() );
628 filename = link->file(); 628 filename = link->file();
629 qApp->processEvents(); 629 qApp->processEvents();
630 ok = image.load(filename, 0); 630 ok = image.load(filename, 0);
631 if ( ok ) 631 if ( ok )
632 { 632 {
633 updateImageInfo(filename); 633 updateImageInfo(filename);
634 ok = reconvertImage(); 634 ok = reconvertImage();
635 } 635 }
636 if ( !ok ) 636 if ( !ok )
637 pm.resize(0,0); 637 pm.resize(0,0);
638 } 638 }
639 } 639 }
640 } 640 }
641 if ( !image.isNull() ) 641 if ( !image.isNull() )
642 { 642 {
643 ok = true; 643 ok = true;
644 closeFileSelector(); 644 closeFileSelector();
645 } 645 }
646 646
647 return ok; 647 return ok;
648} 648}
649 649
650bool ImageViewer::reconvertImage() 650bool ImageViewer::reconvertImage()
651{ 651{
652 bool success = FALSE; 652 bool success = FALSE;
653 653
654 if ( image.isNull() ) return FALSE; 654 if ( image.isNull() ) return FALSE;
655 655
656 QApplication::setOverrideCursor( waitCursor ); // this might take time 656 QApplication::setOverrideCursor( waitCursor ); // this might take time
657 if ( pm.convertFromImage(image /*, conversion_flags */ ) ) 657 if ( pm.convertFromImage(image /*, conversion_flags */ ) )
658 { 658 {
659 pmScaled = QPixmap(); 659 pmScaled = QPixmap();
660 scale(); 660 scale();
661 success = TRUE; // load successful 661 success = TRUE; // load successful
662 } 662 }
663 else 663 else
664 { 664 {
665 pm.resize(0,0); // couldn't load image 665 pm.resize(0,0); // couldn't load image
666 } 666 }
667 QApplication::restoreOverrideCursor(); // restore original cursor 667 QApplication::restoreOverrideCursor(); // restore original cursor
668 668
669 return success; // TRUE if loaded OK 669 return success; // TRUE if loaded OK
670} 670}
671 671
672 672
673int ImageViewer::calcHeight() 673int ImageViewer::calcHeight()
674{ 674{
675 if ( !isFullScreen ) 675 if ( !isFullScreen )
676 return imagePanel->paneHeight(); 676 return imagePanel->paneHeight();
677 else 677 else
678 return qApp->desktop()->height(); 678 return qApp->desktop()->height();
679} 679}
680/* 680/*
681 This functions scales the pixmap in the member variable "pm" to fit the 681 This functions scales the pixmap in the member variable "pm" to fit the
682 widget size and puts the resulting pixmap in the member variable "pmScaled". 682 widget size and puts the resulting pixmap in the member variable "pmScaled".
683*/ 683*/
684void ImageViewer::scale() 684void ImageViewer::scale()
685{ 685{
686 int h = calcHeight(); 686 int h = calcHeight();
687 if ( image.isNull() ) return; 687 if ( image.isNull() ) return;
688 688
689 QApplication::setOverrideCursor( waitCursor ); // this might take time 689 QApplication::setOverrideCursor( waitCursor ); // this might take time
690 if ( imagePanel->paneWidth() == pm.width() && h == pm.height() ) 690 if ( imagePanel->paneWidth() == pm.width() && h == pm.height() )
691 { // no need to scale if widget 691 { // no need to scale if widget
692 pmScaled = pm; // size equals pixmap size 692 pmScaled = pm; // size equals pixmap size
693 } 693 }
694 else 694 else
695 { 695 {
696 double hs = (double)h / (double)image.height(); 696 double hs = (double)h / (double)image.height();
697 double ws = (double)imagePanel->paneWidth() / (double)image.width(); 697 double ws = (double)imagePanel->paneWidth() / (double)image.width();
698 double scaleFactor = (hs > ws) ? ws : hs; 698 double scaleFactor = (hs > ws) ? ws : hs;
699 int smoothW = (int)(scaleFactor * image.width()); 699 int smoothW = (int)(scaleFactor * image.width());
700 int smoothH = (int)(scaleFactor * image.height()); 700 int smoothH = (int)(scaleFactor * image.height());
701 701
702 pmScaled.convertFromImage( image.smoothScale( smoothW, smoothH ) /*, conversion_flags */ ); 702 pmScaled.convertFromImage( image.smoothScale( smoothW, smoothH ) /*, conversion_flags */ );
703 } 703 }
704 QApplication::restoreOverrideCursor(); // restore original cursor 704 QApplication::restoreOverrideCursor(); // restore original cursor
705} 705}
706 706
707/* 707/*
708 The resize event handler, if a valid pixmap was loaded it will call 708 The resize event handler, if a valid pixmap was loaded it will call
709 scale() to fit the pixmap to the new widget size. 709 scale() to fit the pixmap to the new widget size.
710*/ 710*/
711 711
712void ImageViewer::resizeEvent( QResizeEvent * ) 712void ImageViewer::resizeEvent( QResizeEvent * )
713{ 713{
714 714
715 if ( pm.size() == QSize( 0, 0 ) ) // we couldn't load the image 715 if ( pm.size() == QSize( 0, 0 ) ) // we couldn't load the image
716 return; 716 return;
717 717
718 int h = calcHeight(); 718 int h = calcHeight();
719 719
720 if ( imagePanel->paneWidth() != pmScaled.width() || h != pmScaled.height() ) 720 if ( imagePanel->paneWidth() != pmScaled.width() || h != pmScaled.height() )
721 { // if new size, 721 { // if new size,
722 scale(); // scale pmScaled to window 722 scale(); // scale pmScaled to window
723 } 723 }
724 if ( image.hasAlphaBuffer() ) 724 if ( image.hasAlphaBuffer() )
725 erase(); 725 erase();
726} 726}
727 727
728 728
729void ImageViewer::hFlip() 729void ImageViewer::hFlip()
730{ 730{
731// matrix.scale( -1.0, 1.0 ); 731// matrix.scale( -1.0, 1.0 );
732 732
733 setImage(image.mirror(TRUE,FALSE)); 733 setImage(image.mirror(TRUE,FALSE));
734} 734}
735 735
736void ImageViewer::vFlip() 736void ImageViewer::vFlip()
737{ 737{
738// matrix.scale( 1.0, -1.0 ); 738// matrix.scale( 1.0, -1.0 );
739 setImage(image.mirror(FALSE,TRUE)); 739 setImage(image.mirror(FALSE,TRUE));
740} 740}
741 741
742void ImageViewer::rot180() 742void ImageViewer::rot180()
743{ 743{
744// matrix.rotate( 180.0 ); 744// matrix.rotate( 180.0 );
745 setImage(image.mirror(TRUE,TRUE)); 745 setImage(image.mirror(TRUE,TRUE));
746} 746}
747 747
748void ImageViewer::rot90() 748void ImageViewer::rot90()
749{ 749{
750 QImage oldimage; 750 QImage oldimage;
751 oldimage = image.convertDepth(32); 751 oldimage = image.convertDepth(32);
752// matrix.rotate( -90.0 ); 752// matrix.rotate( -90.0 );
753 setImage(rotate(oldimage,Rotate90)); 753 setImage(rotate(oldimage,Rotate90));
754 754
755} 755}
756void ImageViewer::rot270() 756void ImageViewer::rot270()
757{ 757{
758 758
759 QImage oldimage; 759 QImage oldimage;
760 oldimage = image.convertDepth(32); 760 oldimage = image.convertDepth(32);
761// matrix.rotate(90.0); 761// matrix.rotate(90.0);
762 setImage(rotate(oldimage,Rotate270)); 762 setImage(rotate(oldimage,Rotate270));
763 763
764} 764}
765 765
766void ImageViewer::blackAndWhite() 766void ImageViewer::blackAndWhite()
767{ 767{
768 768
769 viewMenuView->setItemEnabled(BLACKANDWHITE,false); 769 viewMenuView->setItemEnabled(BLACKANDWHITE,false);
770 setImage(toGray(image,false)); 770 setImage(toGray(image,false));
771} 771}
772 772
773void ImageViewer::displayControlsDialog() 773void ImageViewer::displayControlsDialog()
774{ 774{
775 int w=80; 775 int w=80;
776 int h=w; 776 int h=w;
777 QImage small; 777 QImage small;
778 778
779 if ( image.width()<w ||image.height()<h ) 779 if ( image.width()<w ||image.height()<h )
780 small=image.smoothScale(w,h); 780 small=image.smoothScale(w,h);
781 else 781 else
782 small=image.copy(0,0,w,h); 782 small=image.copy(0,0,w,h);
783 783
784 int newB=0; 784 int newB=0;
785 ControlsDialog *dlg=new ControlsDialog("Image Viewer",small,&newB,this); 785 ControlsDialog *dlg=new ControlsDialog("Image Viewer",small,&newB,this);
786 dlg->exec(); 786 dlg->exec();
787 if ( newB ) { 787 if ( newB ) {
788 intensity(image,(float)newB/100); 788 intensity(image,(float)newB/100);
789 setImage(image); 789 setImage(image);
790 } 790 }
791 791
792} 792}
793 793
794 794
795void ImageViewer::displayInfoDialog() 795void ImageViewer::displayInfoDialog()
796{ 796{
797 797
798 QStringList ls; 798 QStringList ls;
799 799
800 for ( int i=0;i<LAST;i++ ) 800 for ( int i=0;i<LAST;i++ )
801 ls.append(imageInfo[i]); 801 ls.append(imageInfo[i]);
802 802
803 InfoDialog::displayInfo("Image Viewer",ls,this); 803 InfoDialog::displayInfo("Image Viewer",ls,this);
804} 804}
805void ImageViewer::normalView() 805void ImageViewer::normalView()
806{ 806{
807 if ( !imagePanel->parentWidget() ) 807 if ( !imagePanel->parentWidget() )
808 { 808 {
809 809
810 isFullScreen = FALSE; 810 isFullScreen = FALSE;
811 stack->addWidget( imagePanel, 1 ); 811 stack->addWidget( imagePanel, 1 );
812 switchToImageView(); 812 switchToImageView();
813 if ( isSized ) 813 if ( isSized )
814 scale(); 814 scale();
815 815
816 updateImage(); 816 updateImage();
817 817
818 } 818 }
819} 819}
820 820
821void ImageViewer::stopSlideShow() { 821void ImageViewer::stopSlideShow() {
822 if (slideTimer->isActive()) 822 if (slideTimer->isActive())
823 slideTimer->stop(); 823 slideTimer->stop();
824} 824}
825 825
826void ImageViewer::fullScreen() 826void ImageViewer::fullScreen()
827{ 827{
828 // Full-screen option 828 // Full-screen option
829 // contributed by Robert Wittams <robert@wittams.com> 829 // contributed by Robert Wittams <robert@wittams.com>
830 if ( imagePanel->parentWidget() && loadSelected() ) 830 if ( imagePanel->parentWidget() && loadSelected() )
831 { 831 {
832 isFullScreen = TRUE; 832 isFullScreen = TRUE;
833 imagePanel->reparent(0,QPoint(0,0)); 833 imagePanel->reparent(0,QPoint(0,0));
834 imagePanel->resize(qApp->desktop()->width(), qApp->desktop()->height()); 834 imagePanel->resize(qApp->desktop()->width(), qApp->desktop()->height());
835 835
836 if ( isSized ) 836 if ( isSized )
837 scale(); 837 scale();
838 updateImage(); 838 updateImage();
839 imagePanel->showFullScreen(); 839 imagePanel->showFullScreen();
840 } 840 }
841} 841}
842 842
843void ImageViewer::setImage(const QImage& newimage) 843void ImageViewer::setImage(const QImage& newimage)
844{ 844{
845 image = newimage; 845 image = newimage;
846 reconvertImage(); 846 reconvertImage();
847 updateImage(); 847 updateImage();
848} 848}
849 849
850void ImageViewer::updateImageInfo(QString &filePath) 850void ImageViewer::updateImageInfo(QString &filePath)
851{ 851{
852 852
853 for ( int i=0;i<LAST;i++ ) 853 for ( int i=0;i<LAST;i++ )
854 { 854 {
855 imageInfo[i]=""; 855 imageInfo[i]="";
856 } 856 }
857 857
858 imageInfo[FORMAT]=QImage::imageFormat (filePath ); 858 imageInfo[FORMAT]=QImage::imageFormat (filePath );
859 QFileInfo fi(filePath); 859 QFileInfo fi(filePath);
860 imageInfo[PATH]=fi.fileName(); 860 imageInfo[PATH]=fi.fileName();
861 imageInfo[FILE_SIZE]=QString::number(fi.size())+" (bytes)"; 861 imageInfo[FILE_SIZE]=QString::number(fi.size())+" (bytes)";
862 QString message("%1x%2"); 862 QString message("%1x%2");
863 imageInfo[SIZE]=QString("%1x%2"); 863 imageInfo[SIZE]=QString("%1x%2");
864 imageInfo[SIZE]=imageInfo[SIZE].arg(image.width()).arg(image.height()); 864 imageInfo[SIZE]=imageInfo[SIZE].arg(image.width()).arg(image.height());
865 if ( image.numColors() > 0 ) 865 if ( image.numColors() > 0 )
866 { 866 {
867 imageInfo[COLORS]=tr("%1 colors").arg(image.numColors()); 867 imageInfo[COLORS]=tr("%1 colors").arg(image.numColors());
868 } 868 }
869 else if ( image.depth() >= 16 ) 869 else if ( image.depth() >= 16 )
870 { 870 {
871 imageInfo[COLORS]=tr(" True color"); 871 imageInfo[COLORS]=tr(" True color");
872 } 872 }
873 if ( image.hasAlphaBuffer() ) 873 if ( image.hasAlphaBuffer() )
874 { 874 {
875 if ( image.depth() == 8 ) 875 if ( image.depth() == 8 )
876 { 876 {
877 int i; 877 int i;
878 bool alpha[256]; 878 bool alpha[256];
879 int nalpha=0; 879 int nalpha=0;
880 880
881 for ( i=0; i<256; i++ ) 881 for ( i=0; i<256; i++ )
882 alpha[i] = FALSE; 882 alpha[i] = FALSE;
883 883
884 for ( i=0; i<image.numColors(); i++ ) 884 for ( i=0; i<image.numColors(); i++ )
885 { 885 {
886 int alevel = image.color(i) >> 24; 886 int alevel = image.color(i) >> 24;
887 if ( !alpha[alevel] ) 887 if ( !alpha[alevel] )
888 { 888 {
889 alpha[alevel] = TRUE; 889 alpha[alevel] = TRUE;
890 nalpha++; 890 nalpha++;
891 } 891 }
892 } 892 }
893 imageInfo[ALPHA]=tr("%1 alpha levels").arg(nalpha); 893 imageInfo[ALPHA]=tr("%1 alpha levels").arg(nalpha);
894 } 894 }
895 else 895 else
896 { 896 {
897 imageInfo[ALPHA]=tr("8-bit alpha channel"); 897 imageInfo[ALPHA]=tr("8-bit alpha channel");
898 } 898 }
899 } 899 }
900 900
901} 901}
902 902
903void ImageViewer::closeEvent( QCloseEvent *e ) 903void ImageViewer::closeEvent( QCloseEvent *e )
904{ 904{
905 if ( stack->visibleWidget() == imagePanel && !bFromDocView ) 905 if ( stack->visibleWidget() == imagePanel && !bFromDocView )
906 { 906 {
907 e->ignore(); 907 e->ignore();
908 open(); 908 open();
909 } 909 }
910 else 910 else
911 { 911 {
912 bFromDocView = FALSE; 912 bFromDocView = FALSE;
913 e->accept(); 913 e->accept();
914 } 914 }
915} 915}
916 916
917// Intensity,toGray and rotate code courtesy of KDE project. 917// Intensity,toGray and rotate code courtesy of KDE project.
918 918
919 919
920QImage& ImageViewer::intensity(QImage &image, float percent) 920QImage& ImageViewer::intensity(QImage &image, float percent)
921{ 921{
922 922
923 int segColors = image.depth() > 8 ? 256 : image.numColors(); 923 int segColors = image.depth() > 8 ? 256 : image.numColors();
924 unsigned char *segTbl = new unsigned char[segColors]; 924 unsigned char *segTbl = new unsigned char[segColors];
925 int pixels = image.depth() > 8 ? image.width()*image.height() : 925 int pixels = image.depth() > 8 ? image.width()*image.height() :
926 image.numColors(); 926 image.numColors();
927 unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() : 927 unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() :
928 (unsigned int *)image.colorTable(); 928 (unsigned int *)image.colorTable();
929 929
930 bool brighten = (percent >= 0); 930 bool brighten = (percent >= 0);
931 if ( percent < 0 ) 931 if ( percent < 0 )
932 percent = -percent; 932 percent = -percent;
933 933
934 if ( brighten ) 934 if ( brighten )
935 { // keep overflow check out of loops 935 { // keep overflow check out of loops
936 for ( int i=0; i < segColors; ++i ) 936 for ( int i=0; i < segColors; ++i )
937 { 937 {
938 int tmp = (int)(i*percent); 938 int tmp = (int)(i*percent);
939 if ( tmp > 255 ) 939 if ( tmp > 255 )
940 tmp = 255; 940 tmp = 255;
941 segTbl[i] = tmp; 941 segTbl[i] = tmp;
942 } 942 }
943 } 943 }
944 else 944 else
945 { 945 {
946 for ( int i=0; i < segColors; ++i ) 946 for ( int i=0; i < segColors; ++i )
947 { 947 {
948 int tmp = (int)(i*percent); 948 int tmp = (int)(i*percent);
949 if ( tmp < 0 ) 949 if ( tmp < 0 )
950 tmp = 0; 950 tmp = 0;
951 segTbl[i] = tmp; 951 segTbl[i] = tmp;
952 } 952 }
953 } 953 }
954 954
955 if ( brighten ) 955 if ( brighten )
956 { // same here 956 { // same here
957 for ( int i=0; i < pixels; ++i ) 957 for ( int i=0; i < pixels; ++i )
958 { 958 {
959 int r = qRed(data[i]); 959 int r = qRed(data[i]);
960 int g = qGreen(data[i]); 960 int g = qGreen(data[i]);
961 int b = qBlue(data[i]); 961 int b = qBlue(data[i]);
962 int a = qAlpha(data[i]); 962 int a = qAlpha(data[i]);
963 r = r + segTbl[r] > 255 ? 255 : r + segTbl[r]; 963 r = r + segTbl[r] > 255 ? 255 : r + segTbl[r];
964 g = g + segTbl[g] > 255 ? 255 : g + segTbl[g]; 964 g = g + segTbl[g] > 255 ? 255 : g + segTbl[g];
965 b = b + segTbl[b] > 255 ? 255 : b + segTbl[b]; 965 b = b + segTbl[b] > 255 ? 255 : b + segTbl[b];
966 data[i] = qRgba(r, g, b,a); 966 data[i] = qRgba(r, g, b,a);
967 } 967 }
968 } 968 }
969 else 969 else
970 { 970 {
971 for ( int i=0; i < pixels; ++i ) 971 for ( int i=0; i < pixels; ++i )
972 { 972 {
973 int r = qRed(data[i]); 973 int r = qRed(data[i]);
974 int g = qGreen(data[i]); 974 int g = qGreen(data[i]);
975 int b = qBlue(data[i]); 975 int b = qBlue(data[i]);
976 int a = qAlpha(data[i]); 976 int a = qAlpha(data[i]);
977 r = r - segTbl[r] < 0 ? 0 : r - segTbl[r]; 977 r = r - segTbl[r] < 0 ? 0 : r - segTbl[r];
978 g = g - segTbl[g] < 0 ? 0 : g - segTbl[g]; 978 g = g - segTbl[g] < 0 ? 0 : g - segTbl[g];
979 b = b - segTbl[b] < 0 ? 0 : b - segTbl[b]; 979 b = b - segTbl[b] < 0 ? 0 : b - segTbl[b];
980 data[i] = qRgba(r, g, b, a); 980 data[i] = qRgba(r, g, b, a);
981 } 981 }
982 } 982 }
983 delete [] segTbl; 983 delete [] segTbl;
984 984
985 return image; 985 return image;
986} 986}
987 987
988QImage& ImageViewer::toGray(QImage &img, bool fast) 988QImage& ImageViewer::toGray(QImage &img, bool fast)
989{ 989{
990 if ( img.width() == 0 || img.height() == 0 ) 990 if ( img.width() == 0 || img.height() == 0 )
991 return img; 991 return img;
992 992
993 if ( fast ) 993 if ( fast )
994 { 994 {
995 if ( img.depth() == 32 ) 995 if ( img.depth() == 32 )
996 { 996 {
997 register uchar * r(img.bits()); 997 register uchar * r(img.bits());
998 register uchar * g(img.bits() + 1); 998 register uchar * g(img.bits() + 1);
999 register uchar * b(img.bits() + 2); 999 register uchar * b(img.bits() + 2);
1000 1000
1001 uchar * end(img.bits() + img.numBytes()); 1001 uchar * end(img.bits() + img.numBytes());
1002 1002
1003 while ( r != end ) 1003 while ( r != end )
1004 { 1004 {
1005 1005
1006 *r = *g = *b = (((*r + *g) >> 1) + *b) >> 1; // (r + b + g) / 3 1006 *r = *g = *b = (((*r + *g) >> 1) + *b) >> 1; // (r + b + g) / 3
1007 1007
1008 r += 4; 1008 r += 4;
1009 g += 4; 1009 g += 4;
1010 b += 4; 1010 b += 4;
1011 } 1011 }
1012 } 1012 }
1013 else 1013 else
1014 { 1014 {
1015 for ( int i = 0; i < img.numColors(); i++ ) 1015 for ( int i = 0; i < img.numColors(); i++ )
1016 { 1016 {
1017 register uint r = qRed(img.color(i)); 1017 register uint r = qRed(img.color(i));
1018 register uint g = qGreen(img.color(i)); 1018 register uint g = qGreen(img.color(i));
1019 register uint b = qBlue(img.color(i)); 1019 register uint b = qBlue(img.color(i));
1020 1020
1021 register uint gray = (((r + g) >> 1) + b) >> 1; 1021 register uint gray = (((r + g) >> 1) + b) >> 1;
1022 img.setColor(i, qRgba(gray, gray, gray, qAlpha(img.color(i)))); 1022 img.setColor(i, qRgba(gray, gray, gray, qAlpha(img.color(i))));
1023 } 1023 }
1024 } 1024 }
1025 } 1025 }
1026 else 1026 else
1027 { 1027 {
1028 int pixels = img.depth() > 8 ? img.width()*img.height() : 1028 int pixels = img.depth() > 8 ? img.width()*img.height() :
1029 img.numColors(); 1029 img.numColors();
1030 unsigned int *data = img.depth() > 8 ? (unsigned int *)img.bits() : 1030 unsigned int *data = img.depth() > 8 ? (unsigned int *)img.bits() :
1031 (unsigned int *)img.colorTable(); 1031 (unsigned int *)img.colorTable();
1032 int val, i; 1032 int val, i;
1033 for ( i=0; i < pixels; ++i ) 1033 for ( i=0; i < pixels; ++i )
1034 { 1034 {
1035 val = qGray(data[i]); 1035 val = qGray(data[i]);
1036 data[i] = qRgba(val, val, val, qAlpha(data[i])); 1036 data[i] = qRgba(val, val, val, qAlpha(data[i]));
1037 } 1037 }
1038 } 1038 }
1039 return img; 1039 return img;
1040} 1040}
1041 1041
1042 1042
1043QImage ImageViewer::rotate(QImage &img, RotateDirection r) 1043QImage ImageViewer::rotate(QImage &img, RotateDirection r)
1044{ 1044{
1045 QImage dest; 1045 QImage dest;
1046 int x, y; 1046 int x, y;
1047 if ( img.depth() > 8 ) 1047 if ( img.depth() > 8 )
1048 { 1048 {
1049 unsigned int *srcData, *destData; 1049 unsigned int *srcData, *destData;
1050 switch ( r ) 1050 switch ( r )
1051 { 1051 {
1052 case Rotate90: 1052 case Rotate90:
1053 dest.create(img.height(), img.width(), img.depth()); 1053 dest.create(img.height(), img.width(), img.depth());
1054 for ( y=0; y < img.height(); ++y ) 1054 for ( y=0; y < img.height(); ++y )
1055 { 1055 {
1056 srcData = (unsigned int *)img.scanLine(y); 1056 srcData = (unsigned int *)img.scanLine(y);
1057 for ( x=0; x < img.width(); ++x ) 1057 for ( x=0; x < img.width(); ++x )
1058 { 1058 {
1059 destData = (unsigned int *)dest.scanLine(x); 1059 destData = (unsigned int *)dest.scanLine(x);
1060 destData[img.height()-y-1] = srcData[x]; 1060 destData[img.height()-y-1] = srcData[x];
1061 } 1061 }
1062 } 1062 }
1063 break; 1063 break;
1064 case Rotate180: 1064 case Rotate180:
1065 dest.create(img.width(), img.height(), img.depth()); 1065 dest.create(img.width(), img.height(), img.depth());
1066 for ( y=0; y < img.height(); ++y ) 1066 for ( y=0; y < img.height(); ++y )
1067 { 1067 {
1068 srcData = (unsigned int *)img.scanLine(y); 1068 srcData = (unsigned int *)img.scanLine(y);
1069 destData = (unsigned int *)dest.scanLine(img.height()-y-1); 1069 destData = (unsigned int *)dest.scanLine(img.height()-y-1);
1070 for ( x=0; x < img.width(); ++x ) 1070 for ( x=0; x < img.width(); ++x )
1071 destData[img.width()-x-1] = srcData[x]; 1071 destData[img.width()-x-1] = srcData[x];
1072 } 1072 }
1073 break; 1073 break;
1074 case Rotate270: 1074 case Rotate270:
1075 dest.create(img.height(), img.width(), img.depth()); 1075 dest.create(img.height(), img.width(), img.depth());
1076 for ( y=0; y < img.height(); ++y ) 1076 for ( y=0; y < img.height(); ++y )
1077 { 1077 {
1078 srcData = (unsigned int *)img.scanLine(y); 1078 srcData = (unsigned int *)img.scanLine(y);
1079 for ( x=0; x < img.width(); ++x ) 1079 for ( x=0; x < img.width(); ++x )
1080 { 1080 {
1081 destData = (unsigned int *)dest.scanLine(img.width()-x-1); 1081 destData = (unsigned int *)dest.scanLine(img.width()-x-1);
1082 destData[y] = srcData[x]; 1082 destData[y] = srcData[x];
1083 } 1083 }
1084 } 1084 }
1085 break; 1085 break;
1086 default: 1086 default:
1087 dest = img; 1087 dest = img;
1088 break; 1088 break;
1089 } 1089 }
1090 } 1090 }
1091 else 1091 else
1092 { 1092 {
1093 unsigned char *srcData, *destData; 1093 unsigned char *srcData, *destData;
1094 unsigned int *srcTable, *destTable; 1094 unsigned int *srcTable, *destTable;
1095 switch ( r ) 1095 switch ( r )
1096 { 1096 {
1097 case Rotate90: 1097 case Rotate90:
1098 dest.create(img.height(), img.width(), img.depth()); 1098 dest.create(img.height(), img.width(), img.depth());
1099 dest.setNumColors(img.numColors()); 1099 dest.setNumColors(img.numColors());
1100 srcTable = (unsigned int *)img.colorTable(); 1100 srcTable = (unsigned int *)img.colorTable();
1101 destTable = (unsigned int *)dest.colorTable(); 1101 destTable = (unsigned int *)dest.colorTable();
1102 for ( x=0; x < img.numColors(); ++x ) 1102 for ( x=0; x < img.numColors(); ++x )
1103 destTable[x] = srcTable[x]; 1103 destTable[x] = srcTable[x];
1104 for ( y=0; y < img.height(); ++y ) 1104 for ( y=0; y < img.height(); ++y )
1105 { 1105 {
1106 srcData = (unsigned char *)img.scanLine(y); 1106 srcData = (unsigned char *)img.scanLine(y);
1107 for ( x=0; x < img.width(); ++x ) 1107 for ( x=0; x < img.width(); ++x )
1108 { 1108 {
1109 destData = (unsigned char *)dest.scanLine(x); 1109 destData = (unsigned char *)dest.scanLine(x);
1110 destData[img.height()-y-1] = srcData[x]; 1110 destData[img.height()-y-1] = srcData[x];
1111 } 1111 }
1112 } 1112 }
1113 break; 1113 break;
1114 case Rotate180: 1114 case Rotate180:
1115 dest.create(img.width(), img.height(), img.depth()); 1115 dest.create(img.width(), img.height(), img.depth());
1116 dest.setNumColors(img.numColors()); 1116 dest.setNumColors(img.numColors());
1117 srcTable = (unsigned int *)img.colorTable(); 1117 srcTable = (unsigned int *)img.colorTable();
1118 destTable = (unsigned int *)dest.colorTable(); 1118 destTable = (unsigned int *)dest.colorTable();
1119 for ( x=0; x < img.numColors(); ++x ) 1119 for ( x=0; x < img.numColors(); ++x )
1120 destTable[x] = srcTable[x]; 1120 destTable[x] = srcTable[x];
1121 for ( y=0; y < img.height(); ++y ) 1121 for ( y=0; y < img.height(); ++y )
1122 { 1122 {
1123 srcData = (unsigned char *)img.scanLine(y); 1123 srcData = (unsigned char *)img.scanLine(y);
1124 destData = (unsigned char *)dest.scanLine(img.height()-y-1); 1124 destData = (unsigned char *)dest.scanLine(img.height()-y-1);
1125 for ( x=0; x < img.width(); ++x ) 1125 for ( x=0; x < img.width(); ++x )
1126 destData[img.width()-x-1] = srcData[x]; 1126 destData[img.width()-x-1] = srcData[x];
1127 } 1127 }
1128 break; 1128 break;
1129 case Rotate270: 1129 case Rotate270:
1130 dest.create(img.height(), img.width(), img.depth()); 1130 dest.create(img.height(), img.width(), img.depth());
1131 dest.setNumColors(img.numColors()); 1131 dest.setNumColors(img.numColors());
1132 srcTable = (unsigned int *)img.colorTable(); 1132 srcTable = (unsigned int *)img.colorTable();
1133 destTable = (unsigned int *)dest.colorTable(); 1133 destTable = (unsigned int *)dest.colorTable();
1134 for ( x=0; x < img.numColors(); ++x ) 1134 for ( x=0; x < img.numColors(); ++x )
1135 destTable[x] = srcTable[x]; 1135 destTable[x] = srcTable[x];
1136 for ( y=0; y < img.height(); ++y ) 1136 for ( y=0; y < img.height(); ++y )
1137 { 1137 {
1138 srcData = (unsigned char *)img.scanLine(y); 1138 srcData = (unsigned char *)img.scanLine(y);
1139 for ( x=0; x < img.width(); ++x ) 1139 for ( x=0; x < img.width(); ++x )
1140 { 1140 {
1141 destData = (unsigned char *)dest.scanLine(img.width()-x-1); 1141 destData = (unsigned char *)dest.scanLine(img.width()-x-1);
1142 destData[y] = srcData[x]; 1142 destData[y] = srcData[x];
1143 } 1143 }
1144 } 1144 }
1145 break; 1145 break;
1146 default: 1146 default:
1147 dest = img; 1147 dest = img;
1148 break; 1148 break;
1149 } 1149 }
1150 1150
1151 } 1151 }
1152 return (dest); 1152 return (dest);
1153} 1153}
1154 1154
1155void ImageViewer::slideShow( bool on ) 1155void ImageViewer::slideShow( bool on )
1156{ 1156{
1157 if (on) { 1157 if (on) {
1158 if (!imageList.isEmpty()) { 1158 if (!imageList.isEmpty()) {
1159 slideTimer->start(slideDelay * 1000, FALSE); 1159 slideTimer->start(slideDelay * 1000, FALSE);
1160 filename = ""; // force restart 1160 filename = ""; // force restart
1161 slideReverse ? prevImage() : nextImage(); 1161 slideReverse ? prevImage() : nextImage();
1162 } 1162 }
1163 } else { 1163 } else {
1164 slideTimer->stop(); 1164 slideTimer->stop();
1165 slideAction->setOn( false); 1165 slideAction->setOn( false);
1166 } 1166 }
1167} 1167}
1168 1168
1169void ImageViewer::slideUpdate() 1169void ImageViewer::slideUpdate()
1170{ 1170{
1171 bool final_image = slideReverse ? prevImage() : nextImage(); 1171 bool final_image = slideReverse ? prevImage() : nextImage();
1172 1172
1173 if (final_image && !slideRepeat) { 1173 if (final_image && !slideRepeat) {
1174 slideTimer->stop(); 1174 slideTimer->stop();
1175 slideAction->setOn(FALSE); 1175 slideAction->setOn(FALSE);
1176 } 1176 }
1177} 1177}
1178 1178
1179// 1179//
1180// Display the image after the current one in the image list. 1180// Display the image after the current one in the image list.
1181// Return TRUE if the next call to nextImage() will wrap around to the 1181// Return TRUE if the next call to nextImage() will wrap around to the
1182// first image in the list (ie. we're now viewing the last image in the list). 1182// first image in the list (ie. we're now viewing the last image in the list).
1183// 1183//
1184bool ImageViewer::nextImage(void) 1184bool ImageViewer::nextImage(void)
1185{ 1185{
1186 int idx = 0; 1186 int idx = 0;
1187 1187
1188 if (imageList.count() > 0) { 1188 if (imageList.count() > 0) {
1189 idx = imageIndex(); 1189 idx = imageIndex();
1190 if (idx != -1) { 1190 if (idx != -1) {
1191 if (idx == int(imageList.count() - 1)) { 1191 if (idx == int(imageList.count() - 1)) {
1192 idx = 0; 1192 idx = 0;
1193 } else { 1193 } else {
1194 idx++; 1194 idx++;
1195 } 1195 }
1196 } else { 1196 } else {
1197 idx = 0; 1197 idx = 0;
1198 } 1198 }
1199 openFile(imageList[idx]); 1199 openFile(imageList[idx]);
1200 } 1200 }
1201 1201
1202 return idx == int(imageList.count() - 1) ? TRUE : FALSE; 1202 return idx == int(imageList.count() - 1) ? TRUE : FALSE;
1203} 1203}
1204 1204
1205// 1205//
1206// Display the image preceeding the current one in the image list. 1206// Display the image preceeding the current one in the image list.
1207// Return TRUE if the next call to prevImage() will wrap around to the last 1207// Return TRUE if the next call to prevImage() will wrap around to the last
1208// image in the list (ie. we're now viewing the first image in the list). 1208// image in the list (ie. we're now viewing the first image in the list).
1209// 1209//
1210bool ImageViewer::prevImage(void) 1210bool ImageViewer::prevImage(void)
1211{ 1211{
1212 int idx = -1; 1212 int idx = -1;
1213 1213
1214 if (imageList.count() > 0) { 1214 if (imageList.count() > 0) {
1215 idx = imageIndex(); 1215 idx = imageIndex();
1216 if (idx != -1) { 1216 if (idx != -1) {
1217 if (idx == 0) { 1217 if (idx == 0) {
1218 idx = imageList.count() - 1; 1218 idx = imageList.count() - 1;
1219 } else { 1219 } else {
1220 idx--; 1220 idx--;
1221 } 1221 }
1222 } else { 1222 } else {
1223 idx = imageList.count() - 1; 1223 idx = imageList.count() - 1;
1224 } 1224 }
1225 openFile(imageList[idx]); 1225 openFile(imageList[idx]);
1226 } 1226 }
1227 1227
1228 return idx == 0 ? TRUE : FALSE; 1228 return idx == 0 ? TRUE : FALSE;
1229} 1229}
1230 1230
1231// 1231//
1232// Return the index into the imageList of the currently viewed 1232// Return the index into the imageList of the currently viewed
1233// image (ie. ImageViewer::filename in ImageViewer::imageList). 1233// image (ie. ImageViewer::filename in ImageViewer::imageList).
1234// 1234//
1235int ImageViewer::imageIndex(void) 1235int ImageViewer::imageIndex(void)
1236{ 1236{
1237 QValueListConstIterator<DocLnk> i; 1237 QValueListConstIterator<DocLnk> i;
1238 int index; 1238 int index;
1239 1239
1240 if (imageList.count() == 0) { 1240 if (imageList.count() == 0) {
1241 return -1; 1241 return -1;
1242 } 1242 }
1243 1243
1244 for (index = 0, i = imageList.begin(); i != imageList.end(); ++i, index++) { 1244 for (index = 0, i = imageList.begin(); i != imageList.end(); ++i, index++) {
1245 if ((*i).file() == filename) { 1245 if ((*i).file() == filename) {
1246 return index; 1246 return index;
1247 } 1247 }
1248 } 1248 }
1249 1249
1250 return -1; 1250 return -1;
1251} 1251}
diff --git a/noncore/net/linphone/qlinphone.cpp b/noncore/net/linphone/qlinphone.cpp
index 3cc2ebc..ba4ee5f 100644
--- a/noncore/net/linphone/qlinphone.cpp
+++ b/noncore/net/linphone/qlinphone.cpp
@@ -1,210 +1,210 @@
1/*************************************************************************** 1/***************************************************************************
2 qlinphone.cpp - description 2 qlinphone.cpp - description
3 ------------------- 3 -------------------
4 begin : sam mai 24 2003 4 begin : sam mai 24 2003
5 copyright : (C) 2003 by Simon Morlat, 2004 Maximilian Reiss 5 copyright : (C) 2003 by Simon Morlat, 2004 Maximilian Reiss
6 email : simon.morlat@linphone.org, harlekin@handhelds.org 6 email : simon.morlat@linphone.org, harlekin@handhelds.org
7 ***************************************************************************/ 7 ***************************************************************************/
8 8
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free software; you can redistribute it and/or modify * 11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or * 13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. * 14 * (at your option) any later version. *
15 * * 15 * *
16 ***************************************************************************/ 16 ***************************************************************************/
17 17
18#include "qlinphone.h" 18#include "qlinphone.h"
19#include <qlineedit.h> 19#include <qlineedit.h>
20#include <qlabel.h> 20#include <qlabel.h>
21#include <qwidget.h> 21#include <qwidget.h>
22#include <qslider.h> 22#include <qslider.h>
23#include <qtabwidget.h> 23#include <qtabwidget.h>
24#include <qcheckbox.h> 24#include <qcheckbox.h>
25#include <qmessagebox.h> 25#include <qmessagebox.h>
26#include <qpe/config.h> 26#include <qpe/config.h>
27#include <qpe/qpeapplication.h> 27#include <qpe/qpeapplication.h>
28#include <linphonecore.h> 28#include <linphonecore.h>
29 29
30extern "C" { 30extern "C" {
31 static void stub(LinphoneCore*lc, char*msg) {} 31 static void stub(LinphoneCore*lc, char*msg) {}
32 32
33 static void qt_show(LinphoneCore *lc) { 33 static void qt_show(LinphoneCore *lc) {
34 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data; 34 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data;
35 w->pushGuiTask(new ShowTask(w)); 35 w->pushGuiTask(new ShowTask(w));
36 } 36 }
37 37
38 static void qt_inv_recv(LinphoneCore *lc, char *from) { 38 static void qt_inv_recv(LinphoneCore *lc, char *from) {
39 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data; 39 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data;
40 QString tmp(from); 40 QString tmp(from);
41 w->pushGuiTask(new InviteReceivedTask(w,tmp)); 41 w->pushGuiTask(new InviteReceivedTask(w,tmp));
42 } 42 }
43 43
44 static void qt_display_status(LinphoneCore *lc, char *status) { 44 static void qt_display_status(LinphoneCore *lc, char *status) {
45 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data; 45 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data;
46 QString tmp(status); 46 QString tmp(status);
47 w->pushGuiTask(new UpdateStatusBarTask(w,tmp)); 47 w->pushGuiTask(new UpdateStatusBarTask(w,tmp));
48 } 48 }
49 static void qt_display_message(LinphoneCore *lc, char *message) { 49 static void qt_display_message(LinphoneCore *lc, char *message) {
50 QString qmsg(message); 50 QString qmsg(message);
51 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data; 51 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data;
52 w->pushGuiTask(new DisplayMessageTask(w,qmsg,DisplayMessageTask::Info)); 52 w->pushGuiTask(new DisplayMessageTask(w,qmsg,DisplayMessageTask::Info));
53 } 53 }
54 static void qt_display_warning(LinphoneCore *lc, char *message) { 54 static void qt_display_warning(LinphoneCore *lc, char *message) {
55 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data; 55 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data;
56 QString qmsg(message); 56 QString qmsg(message);
57 w->pushGuiTask(new DisplayMessageTask(w,qmsg,DisplayMessageTask::Warn)); 57 w->pushGuiTask(new DisplayMessageTask(w,qmsg,DisplayMessageTask::Warn));
58 } 58 }
59 static void qt_display_url(LinphoneCore *lc, char *message, char *url) { 59 static void qt_display_url(LinphoneCore *lc, char *message, char *url) {
60 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data; 60 QLinphoneMainWidget *w=(QLinphoneMainWidget*)lc->data;
61 QString qmsg=QString(message)+QString(url); 61 QString qmsg=QString(message)+QString(url);
62 w->pushGuiTask(new DisplayMessageTask(w,qmsg,DisplayMessageTask::Info)); 62 w->pushGuiTask(new DisplayMessageTask(w,qmsg,DisplayMessageTask::Info));
63 } 63 }
64 static void qt_notify_recv(LinphoneCore *lc, const char *url, const char *status) { 64 static void qt_notify_recv(LinphoneCore *lc, const char *url, const char *status) {
65 } 65 }
66 66
67 LinphoneCoreVTable lcvtable={ 67 LinphoneCoreVTable lcvtable={
68 show: 68 show:
69 qt_show, 69 qt_show,
70 inv_recv: 70 inv_recv:
71 qt_inv_recv, 71 qt_inv_recv,
72 bye_recv : 72 bye_recv :
73 stub, 73 stub,
74 notify_recv : 74 notify_recv :
75 qt_notify_recv, 75 qt_notify_recv,
76 display_status : 76 display_status :
77 qt_display_status, 77 qt_display_status,
78 display_message : 78 display_message :
79 qt_display_message, 79 qt_display_message,
80 display_warning : 80 display_warning :
81 qt_display_warning, 81 qt_display_warning,
82 display_url : 82 display_url :
83 qt_display_url, 83 qt_display_url,
84 display_question : 84 display_question :
85 stub 85 stub
86 }; 86 };
87 87
88 88
89} //extern "C" 89} //extern "C"
90 90
91void UpdateStatusBarTask::execute() { 91void UpdateStatusBarTask::execute() {
92 static_cast<QLinphoneMainWidget*>(_w)->displayStatus(_msg); 92 static_cast<QLinphoneMainWidget*>(_w)->displayStatus(_msg);
93} 93}
94 94
95void InviteReceivedTask::execute() { 95void InviteReceivedTask::execute() {
96 static_cast<QLinphoneMainWidget*>(_w)->inviteReceived(_msg); 96 static_cast<QLinphoneMainWidget*>(_w)->inviteReceived(_msg);
97} 97}
98 98
99void DisplayMessageTask::execute() { 99void DisplayMessageTask::execute() {
100 switch(_msgtype) { 100 switch(_msgtype) {
101 case Info: 101 case Info:
102 QMessageBox::information(0,QObject::tr("Information"),_msg); 102 QMessageBox::information(0,QObject::tr("Information"),_msg);
103 break; 103 break;
104 case Warn: 104 case Warn:
105 QMessageBox::warning(0,QObject::tr("Warning"),_msg); 105 QMessageBox::warning(0,QObject::tr("Warning"),_msg);
106 break; 106 break;
107 } 107 }
108} 108}
109 109
110QLinphoneMainWidget::QLinphoneMainWidget(QWidget* parent , const char* name , WFlags fl ) : 110QLinphoneMainWidget::QLinphoneMainWidget(QWidget* parent , const char* name , WFlags fl ) :
111_QLinphoneMainWidget( parent, name, fl ) { 111_QLinphoneMainWidget( parent, name, fl ) {
112 112
113 readConfig(); 113 readConfig();
114 createLinphoneCore(); 114 createLinphoneCore();
115 connect( CheckBox1, SIGNAL( toggled( bool ) ), this, SLOT( slotHide( bool ) ) ); 115 connect( CheckBox1, SIGNAL( toggled(bool) ), this, SLOT( slotHide(bool) ) );
116 CheckBox1->setChecked( true ); 116 CheckBox1->setChecked( true );
117} 117}
118 118
119QLinphoneMainWidget::~QLinphoneMainWidget() { 119QLinphoneMainWidget::~QLinphoneMainWidget() {
120 linphone_core_destroy(_core); 120 linphone_core_destroy(_core);
121 writeConfig(); 121 writeConfig();
122} 122}
123 123
124void QLinphoneMainWidget::slotHide( bool show ) { 124void QLinphoneMainWidget::slotHide( bool show ) {
125 if ( show ) { 125 if ( show ) {
126 TabWidget2->show(); 126 TabWidget2->show();
127 } else { 127 } else {
128 TabWidget2->hide(); 128 TabWidget2->hide();
129 } 129 }
130} 130}
131 131
132void QLinphoneMainWidget::callOrAccept() { 132void QLinphoneMainWidget::callOrAccept() {
133 if (linphone_core_inc_invite_pending(_core)) { 133 if (linphone_core_inc_invite_pending(_core)) {
134 linphone_core_accept_dialog(_core,NULL); 134 linphone_core_accept_dialog(_core,NULL);
135 return; 135 return;
136 } 136 }
137 QString url=sip_url->text(); 137 QString url=sip_url->text();
138 linphone_core_invite(_core,(char*)url.ascii()); 138 linphone_core_invite(_core,(char*)url.ascii());
139} 139}
140void QLinphoneMainWidget::terminateCall() { 140void QLinphoneMainWidget::terminateCall() {
141 linphone_core_terminate_dialog(_core,NULL); 141 linphone_core_terminate_dialog(_core,NULL);
142} 142}
143 143
144void QLinphoneMainWidget::inviteReceived(QString &tmp) { 144void QLinphoneMainWidget::inviteReceived(QString &tmp) {
145 sip_url->setText(tmp); 145 sip_url->setText(tmp);
146} 146}
147 147
148void QLinphoneMainWidget::displayStatus(QString &msg) { 148void QLinphoneMainWidget::displayStatus(QString &msg) {
149 status_bar->setText(msg); 149 status_bar->setText(msg);
150} 150}
151 151
152void QLinphoneMainWidget::pushGuiTask(GuiTask* g) { 152void QLinphoneMainWidget::pushGuiTask(GuiTask* g) {
153 _mutex.lock(); 153 _mutex.lock();
154 _actionq.enqueue(g); 154 _actionq.enqueue(g);
155 _mutex.unlock(); 155 _mutex.unlock();
156 printf("New action added to task list.\n"); 156 printf("New action added to task list.\n");
157} 157}
158 158
159void QLinphoneMainWidget::processGuiTasks() { 159void QLinphoneMainWidget::processGuiTasks() {
160 GuiTask *g; 160 GuiTask *g;
161 _mutex.lock(); 161 _mutex.lock();
162 while(!_actionq.isEmpty()) { 162 while(!_actionq.isEmpty()) {
163 g=_actionq.dequeue(); 163 g=_actionq.dequeue();
164 printf("Executing action...\n"); 164 printf("Executing action...\n");
165 g->execute(); 165 g->execute();
166 delete g; 166 delete g;
167 } 167 }
168 _mutex.unlock(); 168 _mutex.unlock();
169} 169}
170 170
171void QLinphoneMainWidget::timerEvent(QTimerEvent *t) { 171void QLinphoneMainWidget::timerEvent(QTimerEvent *t) {
172 processGuiTasks(); 172 processGuiTasks();
173} 173}
174 174
175void QLinphoneMainWidget::readConfig() { 175void QLinphoneMainWidget::readConfig() {
176 Config cfg( "opie-phone" ); 176 Config cfg( "opie-phone" );
177 cfg.setGroup( "audio" ); 177 cfg.setGroup( "audio" );
178 SliderInput->setValue( cfg.readNumEntry( "rec_lev", 50 ) ); 178 SliderInput->setValue( cfg.readNumEntry( "rec_lev", 50 ) );
179 SliderOutput->setValue( cfg.readNumEntry( "play_lev", 50 ) ); 179 SliderOutput->setValue( cfg.readNumEntry( "play_lev", 50 ) );
180} 180}
181 181
182void QLinphoneMainWidget::writeConfig() { 182void QLinphoneMainWidget::writeConfig() {
183 Config cfg( "opie-phone" ); 183 Config cfg( "opie-phone" );
184 cfg.setGroup( "audio" ); 184 cfg.setGroup( "audio" );
185 cfg.writeEntry( "rec_lev", SliderInput->value() ); 185 cfg.writeEntry( "rec_lev", SliderInput->value() );
186 cfg.writeEntry( "playlev", SliderOutput->value() ); 186 cfg.writeEntry( "playlev", SliderOutput->value() );
187} 187}
188 188
189void QLinphoneMainWidget::helpAbout() { 189void QLinphoneMainWidget::helpAbout() {
190 QMessageBox::about(this,tr("About Linphone"),tr("QT version of linphone\nJuly 2003 - Made in old Europe.")); 190 QMessageBox::about(this,tr("About Linphone"),tr("QT version of linphone\nJuly 2003 - Made in old Europe."));
191} 191}
192 192
193void QLinphoneMainWidget::createLinphoneCore() { 193void QLinphoneMainWidget::createLinphoneCore() {
194 if ( _core ) { 194 if ( _core ) {
195 linphone_core_destroy(_core); 195 linphone_core_destroy(_core);
196 } 196 }
197 197
198 gchar *home=getenv("HOME"); 198 gchar *home=getenv("HOME");
199 gchar *suffix="/Settings/opie-phone.conf"; 199 gchar *suffix="/Settings/opie-phone.conf";
200 if (home==0) 200 if (home==0)
201 home=strdup("/root"); 201 home=strdup("/root");
202 gchar *config=new char[strlen(home)+strlen(suffix)+2]; 202 gchar *config=new char[strlen(home)+strlen(suffix)+2];
203 sprintf(config,"%s/%s",home,suffix); 203 sprintf(config,"%s/%s",home,suffix);
204 /* tracing for osip */ 204 /* tracing for osip */
205 TRACE_INITIALIZE((trace_level_t)5,stdout); 205 TRACE_INITIALIZE((trace_level_t)5,stdout);
206 _core=linphone_core_new(&lcvtable,config,(gpointer)this); 206 _core=linphone_core_new(&lcvtable,config,(gpointer)this);
207 delete [] config; 207 delete [] config;
208 startTimer(10); 208 startTimer(10);
209} 209}
210 210
diff --git a/noncore/net/mail/accountview.cpp b/noncore/net/mail/accountview.cpp
index c2185f2..64557ee 100644
--- a/noncore/net/mail/accountview.cpp
+++ b/noncore/net/mail/accountview.cpp
@@ -1,170 +1,170 @@
1 1
2#include "accountview.h" 2#include "accountview.h"
3#include "accountitem.h" 3#include "accountitem.h"
4#include "selectstore.h" 4#include "selectstore.h"
5 5
6/* OPIE */ 6/* OPIE */
7#include <libmailwrapper/settings.h> 7#include <libmailwrapper/settings.h>
8#include <libmailwrapper/mailwrapper.h> 8#include <libmailwrapper/mailwrapper.h>
9#include <libmailwrapper/mailtypes.h> 9#include <libmailwrapper/mailtypes.h>
10#include <libmailwrapper/abstractmail.h> 10#include <libmailwrapper/abstractmail.h>
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12 12
13/* QT */ 13/* QT */
14#include <qmessagebox.h> 14#include <qmessagebox.h>
15#include <qpopupmenu.h> 15#include <qpopupmenu.h>
16 16
17AccountView::AccountView( QWidget *parent, const char *name, WFlags flags ) 17AccountView::AccountView( QWidget *parent, const char *name, WFlags flags )
18 : QListView( parent, name, flags ) 18 : QListView( parent, name, flags )
19{ 19{
20 connect( this, SIGNAL( selectionChanged( QListViewItem * ) ), 20 connect( this, SIGNAL( selectionChanged(QListViewItem*) ),
21 SLOT( refresh( QListViewItem * ) ) ); 21 SLOT( refresh(QListViewItem*) ) );
22 connect( this, SIGNAL( mouseButtonPressed(int, QListViewItem *,const QPoint&,int ) ),this, 22 connect( this, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this,
23 SLOT( slotHold( int, QListViewItem *,const QPoint&,int ) ) ); 23 SLOT( slotHold(int,QListViewItem*,const QPoint&,int) ) );
24 setSorting(0); 24 setSorting(0);
25} 25}
26 26
27AccountView::~AccountView() 27AccountView::~AccountView()
28{ 28{
29 imapAccounts.clear(); 29 imapAccounts.clear();
30 mhAccounts.clear(); 30 mhAccounts.clear();
31} 31}
32 32
33void AccountView::slotContextMenu(int id) 33void AccountView::slotContextMenu(int id)
34{ 34{
35 AccountViewItem *view = static_cast<AccountViewItem *>(currentItem()); 35 AccountViewItem *view = static_cast<AccountViewItem *>(currentItem());
36 if (!view) return; 36 if (!view) return;
37 view->contextMenuSelected(id); 37 view->contextMenuSelected(id);
38} 38}
39 39
40void AccountView::slotHold(int button, QListViewItem * item,const QPoint&,int) 40void AccountView::slotHold(int button, QListViewItem * item,const QPoint&,int)
41{ 41{
42 if (button==1) {return;} 42 if (button==1) {return;}
43 if (!item) return; 43 if (!item) return;
44 AccountViewItem *view = static_cast<AccountViewItem *>(item); 44 AccountViewItem *view = static_cast<AccountViewItem *>(item);
45 QPopupMenu*m = view->getContextMenu(); 45 QPopupMenu*m = view->getContextMenu();
46 if (!m) return; 46 if (!m) return;
47 connect(m,SIGNAL(activated(int)),this,SLOT(slotContextMenu(int))); 47 connect(m,SIGNAL(activated(int)),this,SLOT(slotContextMenu(int)));
48 m->setFocus(); 48 m->setFocus();
49 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) ); 49 m->exec( QPoint( QCursor::pos().x(), QCursor::pos().y()) );
50 delete m; 50 delete m;
51} 51}
52 52
53void AccountView::populate( QList<Account> list ) 53void AccountView::populate( QList<Account> list )
54{ 54{
55 clear(); 55 clear();
56 56
57 imapAccounts.clear(); 57 imapAccounts.clear();
58 mhAccounts.clear(); 58 mhAccounts.clear();
59 59
60 mhAccounts.append(new MHviewItem(AbstractMail::defaultLocalfolder(),this)); 60 mhAccounts.append(new MHviewItem(AbstractMail::defaultLocalfolder(),this));
61 61
62 Account *it; 62 Account *it;
63 for ( it = list.first(); it; it = list.next() ) 63 for ( it = list.first(); it; it = list.next() )
64 { 64 {
65 if ( it->getType().compare( "IMAP" ) == 0 ) 65 if ( it->getType().compare( "IMAP" ) == 0 )
66 { 66 {
67 IMAPaccount *imap = static_cast<IMAPaccount *>(it); 67 IMAPaccount *imap = static_cast<IMAPaccount *>(it);
68 qDebug( "added IMAP " + imap->getAccountName() ); 68 qDebug( "added IMAP " + imap->getAccountName() );
69 imapAccounts.append(new IMAPviewItem( imap, this )); 69 imapAccounts.append(new IMAPviewItem( imap, this ));
70 } 70 }
71 else if ( it->getType().compare( "POP3" ) == 0 ) 71 else if ( it->getType().compare( "POP3" ) == 0 )
72 { 72 {
73 POP3account *pop3 = static_cast<POP3account *>(it); 73 POP3account *pop3 = static_cast<POP3account *>(it);
74 qDebug( "added POP3 " + pop3->getAccountName() ); 74 qDebug( "added POP3 " + pop3->getAccountName() );
75 /* must not be hold 'cause it isn't required */ 75 /* must not be hold 'cause it isn't required */
76 (void) new POP3viewItem( pop3, this ); 76 (void) new POP3viewItem( pop3, this );
77 } 77 }
78 else if ( it->getType().compare( "NNTP" ) == 0 ) 78 else if ( it->getType().compare( "NNTP" ) == 0 )
79 { 79 {
80 NNTPaccount *nntp = static_cast<NNTPaccount *>(it); 80 NNTPaccount *nntp = static_cast<NNTPaccount *>(it);
81 qDebug( "added NNTP " + nntp->getAccountName() ); 81 qDebug( "added NNTP " + nntp->getAccountName() );
82 /* must not be hold 'cause it isn't required */ 82 /* must not be hold 'cause it isn't required */
83 (void) new NNTPviewItem( nntp, this ); 83 (void) new NNTPviewItem( nntp, this );
84 } 84 }
85 } 85 }
86} 86}
87 87
88void AccountView::refresh(QListViewItem *item) 88void AccountView::refresh(QListViewItem *item)
89{ 89{
90 90
91 qDebug("AccountView refresh..."); 91 qDebug("AccountView refresh...");
92 if ( item ) 92 if ( item )
93 { 93 {
94 m_currentItem = item; 94 m_currentItem = item;
95 QList<RecMail> headerlist; 95 QList<RecMail> headerlist;
96 headerlist.setAutoDelete(true); 96 headerlist.setAutoDelete(true);
97 AccountViewItem *view = static_cast<AccountViewItem *>(item); 97 AccountViewItem *view = static_cast<AccountViewItem *>(item);
98 view->refresh(headerlist); 98 view->refresh(headerlist);
99 emit refreshMailview(&headerlist); 99 emit refreshMailview(&headerlist);
100 } 100 }
101} 101}
102 102
103void AccountView::refreshCurrent() 103void AccountView::refreshCurrent()
104{ 104{
105 m_currentItem = currentItem(); 105 m_currentItem = currentItem();
106 if ( !m_currentItem ) return; 106 if ( !m_currentItem ) return;
107 QList<RecMail> headerlist; 107 QList<RecMail> headerlist;
108 headerlist.setAutoDelete(true); 108 headerlist.setAutoDelete(true);
109 AccountViewItem *view = static_cast<AccountViewItem *>(m_currentItem); 109 AccountViewItem *view = static_cast<AccountViewItem *>(m_currentItem);
110 view->refresh(headerlist); 110 view->refresh(headerlist);
111 emit refreshMailview(&headerlist); 111 emit refreshMailview(&headerlist);
112} 112}
113 113
114void AccountView::refreshAll() 114void AccountView::refreshAll()
115{ 115{
116} 116}
117 117
118RecBody AccountView::fetchBody(const RecMail&aMail) 118RecBody AccountView::fetchBody(const RecMail&aMail)
119{ 119{
120 QListViewItem*item = selectedItem (); 120 QListViewItem*item = selectedItem ();
121 if (!item) return RecBody(); 121 if (!item) return RecBody();
122 AccountViewItem *view = static_cast<AccountViewItem *>(item); 122 AccountViewItem *view = static_cast<AccountViewItem *>(item);
123 return view->fetchBody(aMail); 123 return view->fetchBody(aMail);
124} 124}
125 125
126void AccountView::setupFolderselect(Selectstore*sels) 126void AccountView::setupFolderselect(Selectstore*sels)
127{ 127{
128 QPEApplication::showDialog( sels ); 128 QPEApplication::showDialog( sels );
129 QStringList sFolders; 129 QStringList sFolders;
130 unsigned int i = 0; 130 unsigned int i = 0;
131 for (i=0; i < mhAccounts.count();++i) 131 for (i=0; i < mhAccounts.count();++i)
132 { 132 {
133 mhAccounts[i]->refresh(false); 133 mhAccounts[i]->refresh(false);
134 sFolders = mhAccounts[i]->subFolders(); 134 sFolders = mhAccounts[i]->subFolders();
135 sels->addAccounts(mhAccounts[i]->getWrapper(),sFolders); 135 sels->addAccounts(mhAccounts[i]->getWrapper(),sFolders);
136 } 136 }
137 for (i=0; i < imapAccounts.count();++i) 137 for (i=0; i < imapAccounts.count();++i)
138 { 138 {
139 if (imapAccounts[i]->offline()) 139 if (imapAccounts[i]->offline())
140 continue; 140 continue;
141 imapAccounts[i]->refreshFolders(false); 141 imapAccounts[i]->refreshFolders(false);
142 sels->addAccounts(imapAccounts[i]->getWrapper(),imapAccounts[i]->subFolders()); 142 sels->addAccounts(imapAccounts[i]->getWrapper(),imapAccounts[i]->subFolders());
143 } 143 }
144} 144}
145 145
146void AccountView::downloadMails(Folder*fromFolder,AbstractMail*fromWrapper) 146void AccountView::downloadMails(Folder*fromFolder,AbstractMail*fromWrapper)
147{ 147{
148 AbstractMail*targetMail = 0; 148 AbstractMail*targetMail = 0;
149 QString targetFolder = ""; 149 QString targetFolder = "";
150 Selectstore sels; 150 Selectstore sels;
151 setupFolderselect(&sels); 151 setupFolderselect(&sels);
152 if (!sels.exec()) return; 152 if (!sels.exec()) return;
153 targetMail = sels.currentMail(); 153 targetMail = sels.currentMail();
154 targetFolder = sels.currentFolder(); 154 targetFolder = sels.currentFolder();
155 if ( (fromWrapper==targetMail && fromFolder->getName()==targetFolder) || 155 if ( (fromWrapper==targetMail && fromFolder->getName()==targetFolder) ||
156 targetFolder.isEmpty()) 156 targetFolder.isEmpty())
157 { 157 {
158 return; 158 return;
159 } 159 }
160 if (sels.newFolder() && !targetMail->createMbox(targetFolder)) 160 if (sels.newFolder() && !targetMail->createMbox(targetFolder))
161 { 161 {
162 QMessageBox::critical(0,tr("Error creating new Folder"), 162 QMessageBox::critical(0,tr("Error creating new Folder"),
163 tr("<center>Error while creating<br>new folder - breaking.</center>")); 163 tr("<center>Error while creating<br>new folder - breaking.</center>"));
164 return; 164 return;
165 } 165 }
166 qDebug("Targetfolder: %s",targetFolder.latin1()); 166 qDebug("Targetfolder: %s",targetFolder.latin1());
167 qDebug("Fromfolder: %s",fromFolder->getName().latin1()); 167 qDebug("Fromfolder: %s",fromFolder->getName().latin1());
168 fromWrapper->mvcpAllMails(fromFolder,targetFolder,targetMail,sels.moveMails()); 168 fromWrapper->mvcpAllMails(fromFolder,targetFolder,targetMail,sels.moveMails());
169 refreshCurrent(); 169 refreshCurrent();
170} 170}
diff --git a/noncore/net/mail/composemail.cpp b/noncore/net/mail/composemail.cpp
index 6708779..f51a8fe 100644
--- a/noncore/net/mail/composemail.cpp
+++ b/noncore/net/mail/composemail.cpp
@@ -1,240 +1,240 @@
1#include <qt.h> 1#include <qt.h>
2 2
3#include <opie2/ofiledialog.h> 3#include <opie2/ofiledialog.h>
4#include <qpe/resource.h> 4#include <qpe/resource.h>
5#include <qpe/config.h> 5#include <qpe/config.h>
6#include <qpe/global.h> 6#include <qpe/global.h>
7#include <qpe/contact.h> 7#include <qpe/contact.h>
8 8
9#include "composemail.h" 9#include "composemail.h"
10 10
11#include <libmailwrapper/smtpwrapper.h> 11#include <libmailwrapper/smtpwrapper.h>
12 12
13ComposeMail::ComposeMail( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags ) 13ComposeMail::ComposeMail( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags )
14 : ComposeMailUI( parent, name, modal, flags ) 14 : ComposeMailUI( parent, name, modal, flags )
15{ 15{
16 settings = s; 16 settings = s;
17 17
18 QString vfilename = Global::applicationFileName("addressbook", 18 QString vfilename = Global::applicationFileName("addressbook",
19 "businesscard.vcf"); 19 "businesscard.vcf");
20 Contact c; 20 Contact c;
21 if (QFile::exists(vfilename)) { 21 if (QFile::exists(vfilename)) {
22 c = Contact::readVCard( vfilename )[0]; 22 c = Contact::readVCard( vfilename )[0];
23 } 23 }
24 24
25 QStringList mails = c.emailList(); 25 QStringList mails = c.emailList();
26 QString defmail = c.defaultEmail(); 26 QString defmail = c.defaultEmail();
27 27
28 if (defmail.length()!=0) { 28 if (defmail.length()!=0) {
29 fromBox->insertItem(defmail); 29 fromBox->insertItem(defmail);
30 } 30 }
31 QStringList::ConstIterator sit = mails.begin(); 31 QStringList::ConstIterator sit = mails.begin();
32 for (;sit!=mails.end();++sit) { 32 for (;sit!=mails.end();++sit) {
33 if ( (*sit)==defmail) 33 if ( (*sit)==defmail)
34 continue; 34 continue;
35 fromBox->insertItem((*sit)); 35 fromBox->insertItem((*sit));
36 } 36 }
37 senderNameEdit->setText(c.firstName()+" "+c.lastName()); 37 senderNameEdit->setText(c.firstName()+" "+c.lastName());
38 Config cfg( "mail" ); 38 Config cfg( "mail" );
39 cfg.setGroup( "Compose" ); 39 cfg.setGroup( "Compose" );
40 checkBoxLater->setChecked( cfg.readBoolEntry( "sendLater", false ) ); 40 checkBoxLater->setChecked( cfg.readBoolEntry( "sendLater", false ) );
41 41
42 attList->addColumn( tr( "Name" ) ); 42 attList->addColumn( tr( "Name" ) );
43 attList->addColumn( tr( "Size" ) ); 43 attList->addColumn( tr( "Size" ) );
44 44
45 QList<Account> accounts = settings->getAccounts(); 45 QList<Account> accounts = settings->getAccounts();
46 46
47 Account *it; 47 Account *it;
48 for ( it = accounts.first(); it; it = accounts.next() ) { 48 for ( it = accounts.first(); it; it = accounts.next() ) {
49 if ( it->getType().compare( "SMTP" ) == 0 ) { 49 if ( it->getType().compare( "SMTP" ) == 0 ) {
50 SMTPaccount *smtp = static_cast<SMTPaccount *>(it); 50 SMTPaccount *smtp = static_cast<SMTPaccount *>(it);
51 smtpAccountBox->insertItem( smtp->getAccountName() ); 51 smtpAccountBox->insertItem( smtp->getAccountName() );
52 smtpAccounts.append( smtp ); 52 smtpAccounts.append( smtp );
53 } 53 }
54 } 54 }
55 55
56 if ( smtpAccounts.count() > 0 ) { 56 if ( smtpAccounts.count() > 0 ) {
57 fillValues( smtpAccountBox->currentItem() ); 57 fillValues( smtpAccountBox->currentItem() );
58 } else { 58 } else {
59 QMessageBox::information( this, tr( "Problem" ), 59 QMessageBox::information( this, tr( "Problem" ),
60 tr( "<p>Please create an SMTP account first.</p>" ), 60 tr( "<p>Please create an SMTP account first.</p>" ),
61 tr( "Ok" ) ); 61 tr( "Ok" ) );
62 return; 62 return;
63 } 63 }
64 64
65 connect( smtpAccountBox, SIGNAL( activated( int ) ), SLOT( fillValues( int ) ) ); 65 connect( smtpAccountBox, SIGNAL( activated(int) ), SLOT( fillValues(int) ) );
66 connect( toButton, SIGNAL( clicked() ), SLOT( pickAddressTo() ) ); 66 connect( toButton, SIGNAL( clicked() ), SLOT( pickAddressTo() ) );
67 connect( ccButton, SIGNAL( clicked() ), SLOT( pickAddressCC() ) ); 67 connect( ccButton, SIGNAL( clicked() ), SLOT( pickAddressCC() ) );
68 connect( bccButton, SIGNAL( clicked() ), SLOT( pickAddressBCC() ) ); 68 connect( bccButton, SIGNAL( clicked() ), SLOT( pickAddressBCC() ) );
69 connect( replyButton, SIGNAL( clicked() ), SLOT( pickAddressReply() ) ); 69 connect( replyButton, SIGNAL( clicked() ), SLOT( pickAddressReply() ) );
70 connect( addButton, SIGNAL( clicked() ), SLOT( addAttachment() ) ); 70 connect( addButton, SIGNAL( clicked() ), SLOT( addAttachment() ) );
71 connect( deleteButton, SIGNAL( clicked() ), SLOT( removeAttachment() ) ); 71 connect( deleteButton, SIGNAL( clicked() ), SLOT( removeAttachment() ) );
72} 72}
73 73
74void ComposeMail::pickAddress( QLineEdit *line ) 74void ComposeMail::pickAddress( QLineEdit *line )
75{ 75{
76 QString names = AddressPicker::getNames(); 76 QString names = AddressPicker::getNames();
77 if ( line->text().isEmpty() ) { 77 if ( line->text().isEmpty() ) {
78 line->setText( names ); 78 line->setText( names );
79 } else if ( !names.isEmpty() ) { 79 } else if ( !names.isEmpty() ) {
80 line->setText( line->text() + ", " + names ); 80 line->setText( line->text() + ", " + names );
81 } 81 }
82} 82}
83 83
84 84
85void ComposeMail::setTo( const QString & to ) 85void ComposeMail::setTo( const QString & to )
86{ 86{
87/* QString toline; 87/* QString toline;
88 QStringList toEntry = to; 88 QStringList toEntry = to;
89 for ( QStringList::Iterator it = toEntry.begin(); it != toEntry.end(); ++it ) { 89 for ( QStringList::Iterator it = toEntry.begin(); it != toEntry.end(); ++it ) {
90 toline += (*it); 90 toline += (*it);
91 } 91 }
92 toLine->setText( toline ); 92 toLine->setText( toline );
93*/ 93*/
94toLine->setText( to ); 94toLine->setText( to );
95} 95}
96 96
97void ComposeMail::setSubject( const QString & subject ) 97void ComposeMail::setSubject( const QString & subject )
98{ 98{
99 subjectLine->setText( subject ); 99 subjectLine->setText( subject );
100} 100}
101 101
102void ComposeMail::setInReplyTo( const QString & messageId ) 102void ComposeMail::setInReplyTo( const QString & messageId )
103{ 103{
104 104
105} 105}
106 106
107void ComposeMail::setMessage( const QString & text ) 107void ComposeMail::setMessage( const QString & text )
108{ 108{
109 message->setText( text ); 109 message->setText( text );
110} 110}
111 111
112 112
113void ComposeMail::pickAddressTo() 113void ComposeMail::pickAddressTo()
114{ 114{
115 pickAddress( toLine ); 115 pickAddress( toLine );
116} 116}
117 117
118void ComposeMail::pickAddressCC() 118void ComposeMail::pickAddressCC()
119{ 119{
120 pickAddress( ccLine ); 120 pickAddress( ccLine );
121} 121}
122 122
123void ComposeMail::pickAddressBCC() 123void ComposeMail::pickAddressBCC()
124{ 124{
125 pickAddress( bccLine ); 125 pickAddress( bccLine );
126} 126}
127 127
128void ComposeMail::pickAddressReply() 128void ComposeMail::pickAddressReply()
129{ 129{
130 pickAddress( replyLine ); 130 pickAddress( replyLine );
131} 131}
132 132
133void ComposeMail::fillValues( int current ) 133void ComposeMail::fillValues( int current )
134{ 134{
135#if 0 135#if 0
136 SMTPaccount *smtp = smtpAccounts.at( current ); 136 SMTPaccount *smtp = smtpAccounts.at( current );
137 ccLine->clear(); 137 ccLine->clear();
138 if ( smtp->getUseCC() ) { 138 if ( smtp->getUseCC() ) {
139 ccLine->setText( smtp->getCC() ); 139 ccLine->setText( smtp->getCC() );
140 } 140 }
141 bccLine->clear(); 141 bccLine->clear();
142 if ( smtp->getUseBCC() ) { 142 if ( smtp->getUseBCC() ) {
143 bccLine->setText( smtp->getBCC() ); 143 bccLine->setText( smtp->getBCC() );
144 } 144 }
145 replyLine->clear(); 145 replyLine->clear();
146 if ( smtp->getUseReply() ) { 146 if ( smtp->getUseReply() ) {
147 replyLine->setText( smtp->getReply() ); 147 replyLine->setText( smtp->getReply() );
148 } 148 }
149 sigMultiLine->setText( smtp->getSignature() ); 149 sigMultiLine->setText( smtp->getSignature() );
150#endif 150#endif
151} 151}
152 152
153void ComposeMail::slotAdjustColumns() 153void ComposeMail::slotAdjustColumns()
154{ 154{
155 int currPage = tabWidget->currentPageIndex(); 155 int currPage = tabWidget->currentPageIndex();
156 156
157 tabWidget->showPage( attachTab ); 157 tabWidget->showPage( attachTab );
158 attList->setColumnWidth( 0, attList->visibleWidth() - 80 ); 158 attList->setColumnWidth( 0, attList->visibleWidth() - 80 );
159 attList->setColumnWidth( 1, 80 ); 159 attList->setColumnWidth( 1, 80 );
160 160
161 tabWidget->setCurrentPage( currPage ); 161 tabWidget->setCurrentPage( currPage );
162} 162}
163 163
164void ComposeMail::addAttachment() 164void ComposeMail::addAttachment()
165{ 165{
166 DocLnk lnk = Opie::OFileDialog::getOpenFileName( 1, "/" ); 166 DocLnk lnk = Opie::OFileDialog::getOpenFileName( 1, "/" );
167 if ( !lnk.name().isEmpty() ) { 167 if ( !lnk.name().isEmpty() ) {
168 Attachment *att = new Attachment( lnk ); 168 Attachment *att = new Attachment( lnk );
169 (void) new AttachViewItem( attList, att ); 169 (void) new AttachViewItem( attList, att );
170 } 170 }
171} 171}
172 172
173void ComposeMail::removeAttachment() 173void ComposeMail::removeAttachment()
174{ 174{
175 if ( !attList->currentItem() ) { 175 if ( !attList->currentItem() ) {
176 QMessageBox::information( this, tr( "Error" ), 176 QMessageBox::information( this, tr( "Error" ),
177 tr( "<p>Please select a File.</p>" ), 177 tr( "<p>Please select a File.</p>" ),
178 tr( "Ok" ) ); 178 tr( "Ok" ) );
179 } else { 179 } else {
180 attList->takeItem( attList->currentItem() ); 180 attList->takeItem( attList->currentItem() );
181 } 181 }
182} 182}
183 183
184void ComposeMail::accept() 184void ComposeMail::accept()
185{ 185{
186 if ( checkBoxLater->isChecked() ) { 186 if ( checkBoxLater->isChecked() ) {
187 qDebug( "Send later" ); 187 qDebug( "Send later" );
188 } 188 }
189 189
190#if 0 190#if 0
191 qDebug( "Sending Mail with " + 191 qDebug( "Sending Mail with " +
192 smtpAccounts.at( smtpAccountBox->currentItem() )->getAccountName() ); 192 smtpAccounts.at( smtpAccountBox->currentItem() )->getAccountName() );
193#endif 193#endif
194 Mail *mail = new Mail(); 194 Mail *mail = new Mail();
195 195
196 SMTPaccount *smtp = smtpAccounts.at( smtpAccountBox->currentItem() ); 196 SMTPaccount *smtp = smtpAccounts.at( smtpAccountBox->currentItem() );
197 mail->setMail(fromBox->currentText()); 197 mail->setMail(fromBox->currentText());
198 198
199 if ( !toLine->text().isEmpty() ) { 199 if ( !toLine->text().isEmpty() ) {
200 mail->setTo( toLine->text() ); 200 mail->setTo( toLine->text() );
201 } else { 201 } else {
202 qDebug( "No Reciever spezified -> returning" ); 202 qDebug( "No Reciever spezified -> returning" );
203 return; 203 return;
204 } 204 }
205 mail->setName(senderNameEdit->text()); 205 mail->setName(senderNameEdit->text());
206 mail->setCC( ccLine->text() ); 206 mail->setCC( ccLine->text() );
207 mail->setBCC( bccLine->text() ); 207 mail->setBCC( bccLine->text() );
208 mail->setReply( replyLine->text() ); 208 mail->setReply( replyLine->text() );
209 mail->setSubject( subjectLine->text() ); 209 mail->setSubject( subjectLine->text() );
210 QString txt = message->text(); 210 QString txt = message->text();
211 if ( !sigMultiLine->text().isEmpty() ) { 211 if ( !sigMultiLine->text().isEmpty() ) {
212 txt.append( "\n--\n" ); 212 txt.append( "\n--\n" );
213 txt.append( sigMultiLine->text() ); 213 txt.append( sigMultiLine->text() );
214 } 214 }
215 qDebug(txt); 215 qDebug(txt);
216 mail->setMessage( txt ); 216 mail->setMessage( txt );
217 AttachViewItem *it = (AttachViewItem *) attList->firstChild(); 217 AttachViewItem *it = (AttachViewItem *) attList->firstChild();
218 while ( it != NULL ) { 218 while ( it != NULL ) {
219 mail->addAttachment( it->getAttachment() ); 219 mail->addAttachment( it->getAttachment() );
220 it = (AttachViewItem *) it->nextSibling(); 220 it = (AttachViewItem *) it->nextSibling();
221 } 221 }
222 222
223 SMTPwrapper wrapper( smtp ); 223 SMTPwrapper wrapper( smtp );
224 wrapper.sendMail( *mail,checkBoxLater->isChecked() ); 224 wrapper.sendMail( *mail,checkBoxLater->isChecked() );
225 225
226 QDialog::accept(); 226 QDialog::accept();
227} 227}
228 228
229AttachViewItem::AttachViewItem( QListView *parent, Attachment *att ) 229AttachViewItem::AttachViewItem( QListView *parent, Attachment *att )
230 : QListViewItem( parent ) 230 : QListViewItem( parent )
231{ 231{
232 attachment = att; 232 attachment = att;
233 qDebug( att->getMimeType() ); 233 qDebug( att->getMimeType() );
234 setPixmap( 0, attachment->getDocLnk().pixmap().isNull() ? 234 setPixmap( 0, attachment->getDocLnk().pixmap().isNull() ?
235 Resource::loadPixmap( "UnknownDocument-14" ) : 235 Resource::loadPixmap( "UnknownDocument-14" ) :
236 attachment->getDocLnk().pixmap() ); 236 attachment->getDocLnk().pixmap() );
237 setText( 0, att->getName().isEmpty() ? att->getFileName() : att->getName() ); 237 setText( 0, att->getName().isEmpty() ? att->getFileName() : att->getName() );
238 setText( 1, QString::number( att->getSize() ) ); 238 setText( 1, QString::number( att->getSize() ) );
239} 239}
240 240
diff --git a/noncore/net/mail/editaccounts.cpp b/noncore/net/mail/editaccounts.cpp
index 60bffa5..edeb1de 100644
--- a/noncore/net/mail/editaccounts.cpp
+++ b/noncore/net/mail/editaccounts.cpp
@@ -1,532 +1,532 @@
1 1
2#include "defines.h" 2#include "defines.h"
3#include "editaccounts.h" 3#include "editaccounts.h"
4 4
5/* OPIE */ 5/* OPIE */
6#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7 7
8/* QT */ 8/* QT */
9#include <qt.h> 9#include <qt.h>
10 10
11AccountListItem::AccountListItem( QListView *parent, Account *a) 11AccountListItem::AccountListItem( QListView *parent, Account *a)
12 : QListViewItem( parent ) 12 : QListViewItem( parent )
13{ 13{
14 account = a; 14 account = a;
15 setText( 0, account->getAccountName() ); 15 setText( 0, account->getAccountName() );
16 setText( 1, account->getType() ); 16 setText( 1, account->getType() );
17} 17}
18 18
19EditAccounts::EditAccounts( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags ) 19EditAccounts::EditAccounts( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags )
20 : EditAccountsUI( parent, name, modal, flags ) 20 : EditAccountsUI( parent, name, modal, flags )
21{ 21{
22 qDebug( "New Account Configuration Widget" ); 22 qDebug( "New Account Configuration Widget" );
23 settings = s; 23 settings = s;
24 24
25 mailList->addColumn( tr( "Account" ) ); 25 mailList->addColumn( tr( "Account" ) );
26 mailList->addColumn( tr( "Type" ) ); 26 mailList->addColumn( tr( "Type" ) );
27 27
28 newsList->addColumn( tr( "Account" ) ); 28 newsList->addColumn( tr( "Account" ) );
29 29
30 connect( newMail, SIGNAL( clicked() ), SLOT( slotNewMail() ) ); 30 connect( newMail, SIGNAL( clicked() ), SLOT( slotNewMail() ) );
31 connect( editMail, SIGNAL( clicked() ), SLOT( slotEditMail() ) ); 31 connect( editMail, SIGNAL( clicked() ), SLOT( slotEditMail() ) );
32 connect( deleteMail, SIGNAL( clicked() ), SLOT( slotDeleteMail() ) ); 32 connect( deleteMail, SIGNAL( clicked() ), SLOT( slotDeleteMail() ) );
33 connect( newNews, SIGNAL( clicked() ), SLOT( slotNewNews() ) ); 33 connect( newNews, SIGNAL( clicked() ), SLOT( slotNewNews() ) );
34 connect( editNews, SIGNAL( clicked() ), SLOT( slotEditNews() ) ); 34 connect( editNews, SIGNAL( clicked() ), SLOT( slotEditNews() ) );
35 connect( deleteNews, SIGNAL( clicked() ), SLOT( slotDeleteNews() ) ); 35 connect( deleteNews, SIGNAL( clicked() ), SLOT( slotDeleteNews() ) );
36 36
37 slotFillLists(); 37 slotFillLists();
38} 38}
39 39
40void EditAccounts::slotFillLists() 40void EditAccounts::slotFillLists()
41{ 41{
42 mailList->clear(); 42 mailList->clear();
43 newsList->clear(); 43 newsList->clear();
44 44
45 QList<Account> accounts = settings->getAccounts(); 45 QList<Account> accounts = settings->getAccounts();
46 Account *it; 46 Account *it;
47 for ( it = accounts.first(); it; it = accounts.next() ) 47 for ( it = accounts.first(); it; it = accounts.next() )
48 { 48 {
49 if ( it->getType().compare( "NNTP" ) == 0 ) 49 if ( it->getType().compare( "NNTP" ) == 0 )
50 { 50 {
51 (void) new AccountListItem( newsList, it ); 51 (void) new AccountListItem( newsList, it );
52 } 52 }
53 else 53 else
54 { 54 {
55 (void) new AccountListItem( mailList, it ); 55 (void) new AccountListItem( mailList, it );
56 } 56 }
57 } 57 }
58} 58}
59 59
60void EditAccounts::slotNewMail() 60void EditAccounts::slotNewMail()
61{ 61{
62 qDebug( "New Mail Account" ); 62 qDebug( "New Mail Account" );
63 QString *selection = new QString(); 63 QString *selection = new QString();
64 SelectMailType selType( selection, this, 0, true ); 64 SelectMailType selType( selection, this, 0, true );
65 selType.show(); 65 selType.show();
66 if ( QDialog::Accepted == selType.exec() ) 66 if ( QDialog::Accepted == selType.exec() )
67 { 67 {
68 slotNewAccount( *selection ); 68 slotNewAccount( *selection );
69 } 69 }
70} 70}
71 71
72void EditAccounts::slotNewAccount( const QString &type ) 72void EditAccounts::slotNewAccount( const QString &type )
73{ 73{
74 if ( type.compare( "IMAP" ) == 0 ) 74 if ( type.compare( "IMAP" ) == 0 )
75 { 75 {
76 qDebug( "-> config IMAP" ); 76 qDebug( "-> config IMAP" );
77 IMAPaccount *account = new IMAPaccount(); 77 IMAPaccount *account = new IMAPaccount();
78 IMAPconfig imap( account, this, 0, true ); 78 IMAPconfig imap( account, this, 0, true );
79 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) ) 79 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) )
80 { 80 {
81 settings->addAccount( account ); 81 settings->addAccount( account );
82 account->save(); 82 account->save();
83 slotFillLists(); 83 slotFillLists();
84 } 84 }
85 else 85 else
86 { 86 {
87 account->remove(); 87 account->remove();
88 } 88 }
89 } 89 }
90 else if ( type.compare( "POP3" ) == 0 ) 90 else if ( type.compare( "POP3" ) == 0 )
91 { 91 {
92 qDebug( "-> config POP3" ); 92 qDebug( "-> config POP3" );
93 POP3account *account = new POP3account(); 93 POP3account *account = new POP3account();
94 POP3config pop3( account, this, 0, true, WStyle_ContextHelp ); 94 POP3config pop3( account, this, 0, true, WStyle_ContextHelp );
95 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) ) 95 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) )
96 { 96 {
97 settings->addAccount( account ); 97 settings->addAccount( account );
98 account->save(); 98 account->save();
99 slotFillLists(); 99 slotFillLists();
100 } 100 }
101 else 101 else
102 { 102 {
103 account->remove(); 103 account->remove();
104 } 104 }
105 } 105 }
106 else if ( type.compare( "SMTP" ) == 0 ) 106 else if ( type.compare( "SMTP" ) == 0 )
107 { 107 {
108 qDebug( "-> config SMTP" ); 108 qDebug( "-> config SMTP" );
109 SMTPaccount *account = new SMTPaccount(); 109 SMTPaccount *account = new SMTPaccount();
110 SMTPconfig smtp( account, this, 0, true, WStyle_ContextHelp ); 110 SMTPconfig smtp( account, this, 0, true, WStyle_ContextHelp );
111 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) ) 111 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) )
112 { 112 {
113 settings->addAccount( account ); 113 settings->addAccount( account );
114 account->save(); 114 account->save();
115 slotFillLists(); 115 slotFillLists();
116 116
117 } 117 }
118 else 118 else
119 { 119 {
120 account->remove(); 120 account->remove();
121 } 121 }
122 } 122 }
123 else if ( type.compare( "NNTP" ) == 0 ) 123 else if ( type.compare( "NNTP" ) == 0 )
124 { 124 {
125 qDebug( "-> config NNTP" ); 125 qDebug( "-> config NNTP" );
126 NNTPaccount *account = new NNTPaccount(); 126 NNTPaccount *account = new NNTPaccount();
127 NNTPconfig nntp( account, this, 0, true, WStyle_ContextHelp ); 127 NNTPconfig nntp( account, this, 0, true, WStyle_ContextHelp );
128 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) ) 128 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) )
129 { 129 {
130 settings->addAccount( account ); 130 settings->addAccount( account );
131 account->save(); 131 account->save();
132 slotFillLists(); 132 slotFillLists();
133 } 133 }
134 else 134 else
135 { 135 {
136 account->remove(); 136 account->remove();
137 } 137 }
138 } 138 }
139} 139}
140 140
141void EditAccounts::slotEditAccount( Account *account ) 141void EditAccounts::slotEditAccount( Account *account )
142{ 142{
143 if ( account->getType().compare( "IMAP" ) == 0 ) 143 if ( account->getType().compare( "IMAP" ) == 0 )
144 { 144 {
145 IMAPaccount *imapAcc = static_cast<IMAPaccount *>(account); 145 IMAPaccount *imapAcc = static_cast<IMAPaccount *>(account);
146 IMAPconfig imap( imapAcc, this, 0, true, WStyle_ContextHelp ); 146 IMAPconfig imap( imapAcc, this, 0, true, WStyle_ContextHelp );
147 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) ) 147 if ( QDialog::Accepted == QPEApplication::execDialog( &imap ) )
148 { 148 {
149 slotFillLists(); 149 slotFillLists();
150 } 150 }
151 } 151 }
152 else if ( account->getType().compare( "POP3" ) == 0 ) 152 else if ( account->getType().compare( "POP3" ) == 0 )
153 { 153 {
154 POP3account *pop3Acc = static_cast<POP3account *>(account); 154 POP3account *pop3Acc = static_cast<POP3account *>(account);
155 POP3config pop3( pop3Acc, this, 0, true, WStyle_ContextHelp ); 155 POP3config pop3( pop3Acc, this, 0, true, WStyle_ContextHelp );
156 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) ) 156 if ( QDialog::Accepted == QPEApplication::execDialog( &pop3 ) )
157 { 157 {
158 slotFillLists(); 158 slotFillLists();
159 } 159 }
160 } 160 }
161 else if ( account->getType().compare( "SMTP" ) == 0 ) 161 else if ( account->getType().compare( "SMTP" ) == 0 )
162 { 162 {
163 SMTPaccount *smtpAcc = static_cast<SMTPaccount *>(account); 163 SMTPaccount *smtpAcc = static_cast<SMTPaccount *>(account);
164 SMTPconfig smtp( smtpAcc, this, 0, true, WStyle_ContextHelp ); 164 SMTPconfig smtp( smtpAcc, this, 0, true, WStyle_ContextHelp );
165 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) ) 165 if ( QDialog::Accepted == QPEApplication::execDialog( &smtp ) )
166 { 166 {
167 slotFillLists(); 167 slotFillLists();
168 } 168 }
169 } 169 }
170 else if ( account->getType().compare( "NNTP" ) == 0 ) 170 else if ( account->getType().compare( "NNTP" ) == 0 )
171 { 171 {
172 NNTPaccount *nntpAcc = static_cast<NNTPaccount *>(account); 172 NNTPaccount *nntpAcc = static_cast<NNTPaccount *>(account);
173 NNTPconfig nntp( nntpAcc, this, 0, true, WStyle_ContextHelp ); 173 NNTPconfig nntp( nntpAcc, this, 0, true, WStyle_ContextHelp );
174 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) ) 174 if ( QDialog::Accepted == QPEApplication::execDialog( &nntp ) )
175 { 175 {
176 slotFillLists(); 176 slotFillLists();
177 } 177 }
178 } 178 }
179} 179}
180 180
181void EditAccounts::slotDeleteAccount( Account *account ) 181void EditAccounts::slotDeleteAccount( Account *account )
182{ 182{
183 if ( QMessageBox::information( this, tr( "Question" ), 183 if ( QMessageBox::information( this, tr( "Question" ),
184 tr( "<p>Do you really want to delete the selected Account?</p>" ), 184 tr( "<p>Do you really want to delete the selected Account?</p>" ),
185 tr( "Yes" ), tr( "No" ) ) == 0 ) 185 tr( "Yes" ), tr( "No" ) ) == 0 )
186 { 186 {
187 settings->delAccount( account ); 187 settings->delAccount( account );
188 slotFillLists(); 188 slotFillLists();
189 } 189 }
190} 190}
191 191
192void EditAccounts::slotEditMail() 192void EditAccounts::slotEditMail()
193{ 193{
194 qDebug( "Edit Mail Account" ); 194 qDebug( "Edit Mail Account" );
195 if ( !mailList->currentItem() ) 195 if ( !mailList->currentItem() )
196 { 196 {
197 QMessageBox::information( this, tr( "Error" ), 197 QMessageBox::information( this, tr( "Error" ),
198 tr( "<p>Please select an account.</p>" ), 198 tr( "<p>Please select an account.</p>" ),
199 tr( "Ok" ) ); 199 tr( "Ok" ) );
200 return; 200 return;
201 } 201 }
202 202
203 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount(); 203 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount();
204 slotEditAccount( a ); 204 slotEditAccount( a );
205} 205}
206 206
207void EditAccounts::slotDeleteMail() 207void EditAccounts::slotDeleteMail()
208{ 208{
209 if ( !mailList->currentItem() ) 209 if ( !mailList->currentItem() )
210 { 210 {
211 QMessageBox::information( this, tr( "Error" ), 211 QMessageBox::information( this, tr( "Error" ),
212 tr( "<p>Please select an account.</p>" ), 212 tr( "<p>Please select an account.</p>" ),
213 tr( "Ok" ) ); 213 tr( "Ok" ) );
214 return; 214 return;
215 } 215 }
216 216
217 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount(); 217 Account *a = ((AccountListItem *) mailList->currentItem())->getAccount();
218 slotDeleteAccount( a ); 218 slotDeleteAccount( a );
219} 219}
220 220
221void EditAccounts::slotNewNews() 221void EditAccounts::slotNewNews()
222{ 222{
223 qDebug( "New News Account" ); 223 qDebug( "New News Account" );
224 slotNewAccount( "NNTP" ); 224 slotNewAccount( "NNTP" );
225} 225}
226 226
227void EditAccounts::slotEditNews() 227void EditAccounts::slotEditNews()
228{ 228{
229 qDebug( "Edit News Account" ); 229 qDebug( "Edit News Account" );
230 if ( !newsList->currentItem() ) 230 if ( !newsList->currentItem() )
231 { 231 {
232 QMessageBox::information( this, tr( "Error" ), 232 QMessageBox::information( this, tr( "Error" ),
233 tr( "<p>Please select an account.</p>" ), 233 tr( "<p>Please select an account.</p>" ),
234 tr( "Ok" ) ); 234 tr( "Ok" ) );
235 return; 235 return;
236 } 236 }
237 237
238 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount(); 238 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount();
239 slotEditAccount( a ); 239 slotEditAccount( a );
240} 240}
241 241
242void EditAccounts::slotDeleteNews() 242void EditAccounts::slotDeleteNews()
243{ 243{
244 qDebug( "Delete News Account" ); 244 qDebug( "Delete News Account" );
245 if ( !newsList->currentItem() ) 245 if ( !newsList->currentItem() )
246 { 246 {
247 QMessageBox::information( this, tr( "Error" ), 247 QMessageBox::information( this, tr( "Error" ),
248 tr( "<p>Please select an account.</p>" ), 248 tr( "<p>Please select an account.</p>" ),
249 tr( "Ok" ) ); 249 tr( "Ok" ) );
250 return; 250 return;
251 } 251 }
252 252
253 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount(); 253 Account *a = ((AccountListItem *) newsList->currentItem())->getAccount();
254 slotDeleteAccount( a ); 254 slotDeleteAccount( a );
255} 255}
256 256
257void EditAccounts::slotAdjustColumns() 257void EditAccounts::slotAdjustColumns()
258{ 258{
259 int currPage = configTab->currentPageIndex(); 259 int currPage = configTab->currentPageIndex();
260 260
261 configTab->showPage( mailTab ); 261 configTab->showPage( mailTab );
262 mailList->setColumnWidth( 0, mailList->visibleWidth() - 50 ); 262 mailList->setColumnWidth( 0, mailList->visibleWidth() - 50 );
263 mailList->setColumnWidth( 1, 50 ); 263 mailList->setColumnWidth( 1, 50 );
264 264
265 configTab->showPage( newsTab ); 265 configTab->showPage( newsTab );
266 newsList->setColumnWidth( 0, newsList->visibleWidth() ); 266 newsList->setColumnWidth( 0, newsList->visibleWidth() );
267 267
268 configTab->setCurrentPage( currPage ); 268 configTab->setCurrentPage( currPage );
269} 269}
270 270
271void EditAccounts::accept() 271void EditAccounts::accept()
272{ 272{
273 settings->saveAccounts(); 273 settings->saveAccounts();
274 274
275 QDialog::accept(); 275 QDialog::accept();
276} 276}
277 277
278/** 278/**
279 * SelectMailType 279 * SelectMailType
280 */ 280 */
281 281
282SelectMailType::SelectMailType( QString *selection, QWidget *parent, const char *name, bool modal, WFlags flags ) 282SelectMailType::SelectMailType( QString *selection, QWidget *parent, const char *name, bool modal, WFlags flags )
283 : SelectMailTypeUI( parent, name, modal, flags ) 283 : SelectMailTypeUI( parent, name, modal, flags )
284{ 284{
285 selected = selection; 285 selected = selection;
286 selected->replace( 0, selected->length(), typeBox->currentText() ); 286 selected->replace( 0, selected->length(), typeBox->currentText() );
287 connect( typeBox, SIGNAL( activated( const QString & ) ), SLOT( slotSelection( const QString & ) ) ); 287 connect( typeBox, SIGNAL( activated(const QString&) ), SLOT( slotSelection(const QString&) ) );
288} 288}
289 289
290void SelectMailType::slotSelection( const QString &sel ) 290void SelectMailType::slotSelection( const QString &sel )
291{ 291{
292 selected->replace( 0, selected->length(), sel ); 292 selected->replace( 0, selected->length(), sel );
293} 293}
294 294
295/** 295/**
296 * IMAPconfig 296 * IMAPconfig
297 */ 297 */
298 298
299IMAPconfig::IMAPconfig( IMAPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 299IMAPconfig::IMAPconfig( IMAPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
300 : IMAPconfigUI( parent, name, modal, flags ) 300 : IMAPconfigUI( parent, name, modal, flags )
301{ 301{
302 data = account; 302 data = account;
303 303
304 fillValues(); 304 fillValues();
305 305
306 connect( ComboBox1, SIGNAL( activated( int ) ), SLOT( slotConnectionToggle( int ) ) ); 306 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
307 ComboBox1->insertItem( "Only if available", 0 ); 307 ComboBox1->insertItem( "Only if available", 0 );
308 ComboBox1->insertItem( "Always, Negotiated", 1 ); 308 ComboBox1->insertItem( "Always, Negotiated", 1 );
309 ComboBox1->insertItem( "Connect on secure port", 2 ); 309 ComboBox1->insertItem( "Connect on secure port", 2 );
310 ComboBox1->insertItem( "Run command instead", 3 ); 310 ComboBox1->insertItem( "Run command instead", 3 );
311 CommandEdit->hide(); 311 CommandEdit->hide();
312 ComboBox1->setCurrentItem( data->ConnectionType() ); 312 ComboBox1->setCurrentItem( data->ConnectionType() );
313} 313}
314 314
315void IMAPconfig::slotConnectionToggle( int index ) 315void IMAPconfig::slotConnectionToggle( int index )
316{ 316{
317 if ( index == 2 ) 317 if ( index == 2 )
318 { 318 {
319 portLine->setText( IMAP_SSL_PORT ); 319 portLine->setText( IMAP_SSL_PORT );
320 } 320 }
321 else if ( index == 3 ) 321 else if ( index == 3 )
322 { 322 {
323 portLine->setText( IMAP_PORT ); 323 portLine->setText( IMAP_PORT );
324 CommandEdit->show(); 324 CommandEdit->show();
325 } 325 }
326 else 326 else
327 { 327 {
328 portLine->setText( IMAP_PORT ); 328 portLine->setText( IMAP_PORT );
329 } 329 }
330} 330}
331 331
332void IMAPconfig::fillValues() 332void IMAPconfig::fillValues()
333{ 333{
334 accountLine->setText( data->getAccountName() ); 334 accountLine->setText( data->getAccountName() );
335 serverLine->setText( data->getServer() ); 335 serverLine->setText( data->getServer() );
336 portLine->setText( data->getPort() ); 336 portLine->setText( data->getPort() );
337 ComboBox1->setCurrentItem( data->ConnectionType() ); 337 ComboBox1->setCurrentItem( data->ConnectionType() );
338 userLine->setText( data->getUser() ); 338 userLine->setText( data->getUser() );
339 passLine->setText( data->getPassword() ); 339 passLine->setText( data->getPassword() );
340 prefixLine->setText(data->getPrefix()); 340 prefixLine->setText(data->getPrefix());
341} 341}
342 342
343void IMAPconfig::accept() 343void IMAPconfig::accept()
344{ 344{
345 data->setAccountName( accountLine->text() ); 345 data->setAccountName( accountLine->text() );
346 data->setServer( serverLine->text() ); 346 data->setServer( serverLine->text() );
347 data->setPort( portLine->text() ); 347 data->setPort( portLine->text() );
348 data->setConnectionType( ComboBox1->currentItem() ); 348 data->setConnectionType( ComboBox1->currentItem() );
349 data->setUser( userLine->text() ); 349 data->setUser( userLine->text() );
350 data->setPassword( passLine->text() ); 350 data->setPassword( passLine->text() );
351 data->setPrefix(prefixLine->text()); 351 data->setPrefix(prefixLine->text());
352 352
353 QDialog::accept(); 353 QDialog::accept();
354} 354}
355 355
356/** 356/**
357 * POP3config 357 * POP3config
358 */ 358 */
359 359
360POP3config::POP3config( POP3account *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 360POP3config::POP3config( POP3account *account, QWidget *parent, const char *name, bool modal, WFlags flags )
361 : POP3configUI( parent, name, modal, flags ) 361 : POP3configUI( parent, name, modal, flags )
362{ 362{
363 data = account; 363 data = account;
364 fillValues(); 364 fillValues();
365 365
366 connect( ComboBox1, SIGNAL( activated( int ) ), SLOT( slotConnectionToggle( int ) ) ); 366 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
367 ComboBox1->insertItem( "Only if available", 0 ); 367 ComboBox1->insertItem( "Only if available", 0 );
368 ComboBox1->insertItem( "Always, Negotiated", 1 ); 368 ComboBox1->insertItem( "Always, Negotiated", 1 );
369 ComboBox1->insertItem( "Connect on secure port", 2 ); 369 ComboBox1->insertItem( "Connect on secure port", 2 );
370 ComboBox1->insertItem( "Run command instead", 3 ); 370 ComboBox1->insertItem( "Run command instead", 3 );
371 CommandEdit->hide(); 371 CommandEdit->hide();
372 ComboBox1->setCurrentItem( data->ConnectionType() ); 372 ComboBox1->setCurrentItem( data->ConnectionType() );
373} 373}
374 374
375void POP3config::slotConnectionToggle( int index ) 375void POP3config::slotConnectionToggle( int index )
376{ 376{
377 // 2 is ssl connection 377 // 2 is ssl connection
378 if ( index == 2 ) 378 if ( index == 2 )
379 { 379 {
380 portLine->setText( POP3_SSL_PORT ); 380 portLine->setText( POP3_SSL_PORT );
381 } 381 }
382 else if ( index == 3 ) 382 else if ( index == 3 )
383 { 383 {
384 portLine->setText( POP3_PORT ); 384 portLine->setText( POP3_PORT );
385 CommandEdit->show(); 385 CommandEdit->show();
386 } 386 }
387 else 387 else
388 { 388 {
389 portLine->setText( POP3_PORT ); 389 portLine->setText( POP3_PORT );
390 } 390 }
391} 391}
392 392
393void POP3config::fillValues() 393void POP3config::fillValues()
394{ 394{
395 accountLine->setText( data->getAccountName() ); 395 accountLine->setText( data->getAccountName() );
396 serverLine->setText( data->getServer() ); 396 serverLine->setText( data->getServer() );
397 portLine->setText( data->getPort() ); 397 portLine->setText( data->getPort() );
398 ComboBox1->setCurrentItem( data->ConnectionType() ); 398 ComboBox1->setCurrentItem( data->ConnectionType() );
399 userLine->setText( data->getUser() ); 399 userLine->setText( data->getUser() );
400 passLine->setText( data->getPassword() ); 400 passLine->setText( data->getPassword() );
401} 401}
402 402
403void POP3config::accept() 403void POP3config::accept()
404{ 404{
405 data->setAccountName( accountLine->text() ); 405 data->setAccountName( accountLine->text() );
406 data->setServer( serverLine->text() ); 406 data->setServer( serverLine->text() );
407 data->setPort( portLine->text() ); 407 data->setPort( portLine->text() );
408 data->setConnectionType( ComboBox1->currentItem() ); 408 data->setConnectionType( ComboBox1->currentItem() );
409 data->setUser( userLine->text() ); 409 data->setUser( userLine->text() );
410 data->setPassword( passLine->text() ); 410 data->setPassword( passLine->text() );
411 411
412 QDialog::accept(); 412 QDialog::accept();
413} 413}
414 414
415/** 415/**
416 * SMTPconfig 416 * SMTPconfig
417 */ 417 */
418 418
419SMTPconfig::SMTPconfig( SMTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 419SMTPconfig::SMTPconfig( SMTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
420 : SMTPconfigUI( parent, name, modal, flags ) 420 : SMTPconfigUI( parent, name, modal, flags )
421{ 421{
422 data = account; 422 data = account;
423 423
424 connect( loginBox, SIGNAL( toggled( bool ) ), userLine, SLOT( setEnabled( bool ) ) ); 424 connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) );
425 connect( loginBox, SIGNAL( toggled( bool ) ), passLine, SLOT( setEnabled( bool ) ) ); 425 connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) );
426 426
427 fillValues(); 427 fillValues();
428 428
429 connect( ComboBox1, SIGNAL( activated( int ) ), SLOT( slotConnectionToggle( int ) ) ); 429 connect( ComboBox1, SIGNAL( activated(int) ), SLOT( slotConnectionToggle(int) ) );
430 ComboBox1->insertItem( "Only if available", 0 ); 430 ComboBox1->insertItem( "Only if available", 0 );
431 ComboBox1->insertItem( "Always, Negotiated", 1 ); 431 ComboBox1->insertItem( "Always, Negotiated", 1 );
432 ComboBox1->insertItem( "Connect on secure port", 2 ); 432 ComboBox1->insertItem( "Connect on secure port", 2 );
433 ComboBox1->insertItem( "Run command instead", 3 ); 433 ComboBox1->insertItem( "Run command instead", 3 );
434 CommandEdit->hide(); 434 CommandEdit->hide();
435 ComboBox1->setCurrentItem( data->ConnectionType() ); 435 ComboBox1->setCurrentItem( data->ConnectionType() );
436} 436}
437 437
438void SMTPconfig::slotConnectionToggle( int index ) 438void SMTPconfig::slotConnectionToggle( int index )
439{ 439{
440 // 2 is ssl connection 440 // 2 is ssl connection
441 if ( index == 2 ) 441 if ( index == 2 )
442 { 442 {
443 portLine->setText( SMTP_SSL_PORT ); 443 portLine->setText( SMTP_SSL_PORT );
444 } 444 }
445 else if ( index == 3 ) 445 else if ( index == 3 )
446 { 446 {
447 portLine->setText( SMTP_PORT ); 447 portLine->setText( SMTP_PORT );
448 CommandEdit->show(); 448 CommandEdit->show();
449 } 449 }
450 else 450 else
451 { 451 {
452 portLine->setText( SMTP_PORT ); 452 portLine->setText( SMTP_PORT );
453 } 453 }
454} 454}
455 455
456void SMTPconfig::fillValues() 456void SMTPconfig::fillValues()
457{ 457{
458 accountLine->setText( data->getAccountName() ); 458 accountLine->setText( data->getAccountName() );
459 serverLine->setText( data->getServer() ); 459 serverLine->setText( data->getServer() );
460 portLine->setText( data->getPort() ); 460 portLine->setText( data->getPort() );
461 ComboBox1->setCurrentItem( data->ConnectionType() ); 461 ComboBox1->setCurrentItem( data->ConnectionType() );
462 loginBox->setChecked( data->getLogin() ); 462 loginBox->setChecked( data->getLogin() );
463 userLine->setText( data->getUser() ); 463 userLine->setText( data->getUser() );
464 passLine->setText( data->getPassword() ); 464 passLine->setText( data->getPassword() );
465} 465}
466 466
467void SMTPconfig::accept() 467void SMTPconfig::accept()
468{ 468{
469 data->setAccountName( accountLine->text() ); 469 data->setAccountName( accountLine->text() );
470 data->setServer( serverLine->text() ); 470 data->setServer( serverLine->text() );
471 data->setPort( portLine->text() ); 471 data->setPort( portLine->text() );
472 data->setConnectionType( ComboBox1->currentItem() ); 472 data->setConnectionType( ComboBox1->currentItem() );
473 data->setLogin( loginBox->isChecked() ); 473 data->setLogin( loginBox->isChecked() );
474 data->setUser( userLine->text() ); 474 data->setUser( userLine->text() );
475 data->setPassword( passLine->text() ); 475 data->setPassword( passLine->text() );
476 476
477 QDialog::accept(); 477 QDialog::accept();
478} 478}
479 479
480/** 480/**
481 * NNTPconfig 481 * NNTPconfig
482 */ 482 */
483 483
484NNTPconfig::NNTPconfig( NNTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags ) 484NNTPconfig::NNTPconfig( NNTPaccount *account, QWidget *parent, const char *name, bool modal, WFlags flags )
485 : NNTPconfigUI( parent, name, modal, flags ) 485 : NNTPconfigUI( parent, name, modal, flags )
486{ 486{
487 data = account; 487 data = account;
488 488
489 connect( loginBox, SIGNAL( toggled( bool ) ), userLine, SLOT( setEnabled( bool ) ) ); 489 connect( loginBox, SIGNAL( toggled(bool) ), userLine, SLOT( setEnabled(bool) ) );
490 connect( loginBox, SIGNAL( toggled( bool ) ), passLine, SLOT( setEnabled( bool ) ) ); 490 connect( loginBox, SIGNAL( toggled(bool) ), passLine, SLOT( setEnabled(bool) ) );
491 491
492 fillValues(); 492 fillValues();
493 493
494 connect( sslBox, SIGNAL( toggled( bool ) ), SLOT( slotSSL( bool ) ) ); 494 connect( sslBox, SIGNAL( toggled(bool) ), SLOT( slotSSL(bool) ) );
495} 495}
496 496
497void NNTPconfig::slotSSL( bool enabled ) 497void NNTPconfig::slotSSL( bool enabled )
498{ 498{
499 if ( enabled ) 499 if ( enabled )
500 { 500 {
501 portLine->setText( NNTP_SSL_PORT ); 501 portLine->setText( NNTP_SSL_PORT );
502 } 502 }
503 else 503 else
504 { 504 {
505 portLine->setText( NNTP_PORT ); 505 portLine->setText( NNTP_PORT );
506 } 506 }
507} 507}
508 508
509void NNTPconfig::fillValues() 509void NNTPconfig::fillValues()
510{ 510{
511 accountLine->setText( data->getAccountName() ); 511 accountLine->setText( data->getAccountName() );
512 serverLine->setText( data->getServer() ); 512 serverLine->setText( data->getServer() );
513 portLine->setText( data->getPort() ); 513 portLine->setText( data->getPort() );
514 sslBox->setChecked( data->getSSL() ); 514 sslBox->setChecked( data->getSSL() );
515 loginBox->setChecked( data->getLogin() ); 515 loginBox->setChecked( data->getLogin() );
516 userLine->setText( data->getUser() ); 516 userLine->setText( data->getUser() );
517 passLine->setText( data->getPassword() ); 517 passLine->setText( data->getPassword() );
518} 518}
519 519
520void NNTPconfig::accept() 520void NNTPconfig::accept()
521{ 521{
522 data->setAccountName( accountLine->text() ); 522 data->setAccountName( accountLine->text() );
523 data->setServer( serverLine->text() ); 523 data->setServer( serverLine->text() );
524 data->setPort( portLine->text() ); 524 data->setPort( portLine->text() );
525 data->setSSL( sslBox->isChecked() ); 525 data->setSSL( sslBox->isChecked() );
526 data->setLogin( loginBox->isChecked() ); 526 data->setLogin( loginBox->isChecked() );
527 data->setUser( userLine->text() ); 527 data->setUser( userLine->text() );
528 data->setPassword( passLine->text() ); 528 data->setPassword( passLine->text() );
529 529
530 QDialog::accept(); 530 QDialog::accept();
531} 531}
532 532
diff --git a/noncore/net/mail/libmailwrapper/mhwrapper.cpp b/noncore/net/mail/libmailwrapper/mhwrapper.cpp
index dfc00d8..df7f773 100644
--- a/noncore/net/mail/libmailwrapper/mhwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/mhwrapper.cpp
@@ -1,445 +1,445 @@
1#include "mhwrapper.h" 1#include "mhwrapper.h"
2#include "mailtypes.h" 2#include "mailtypes.h"
3#include "mailwrapper.h" 3#include "mailwrapper.h"
4#include <libetpan/libetpan.h> 4#include <libetpan/libetpan.h>
5#include <qdir.h> 5#include <qdir.h>
6#include <qmessagebox.h> 6#include <qmessagebox.h>
7#include <stdlib.h> 7#include <stdlib.h>
8#include <qpe/global.h> 8#include <qpe/global.h>
9#include <opie2/oprocess.h> 9#include <opie2/oprocess.h>
10 10
11const QString MHwrapper::wrapperType="MH"; 11const QString MHwrapper::wrapperType="MH";
12 12
13MHwrapper::MHwrapper(const QString & mbox_dir,const QString&mbox_name) 13MHwrapper::MHwrapper(const QString & mbox_dir,const QString&mbox_name)
14 : Genericwrapper(),MHPath(mbox_dir),MHName(mbox_name) 14 : Genericwrapper(),MHPath(mbox_dir),MHName(mbox_name)
15{ 15{
16 if (MHPath.length()>0) { 16 if (MHPath.length()>0) {
17 if (MHPath[MHPath.length()-1]=='/') { 17 if (MHPath[MHPath.length()-1]=='/') {
18 MHPath=MHPath.left(MHPath.length()-1); 18 MHPath=MHPath.left(MHPath.length()-1);
19 } 19 }
20 qDebug(MHPath); 20 qDebug(MHPath);
21 QDir dir(MHPath); 21 QDir dir(MHPath);
22 if (!dir.exists()) { 22 if (!dir.exists()) {
23 dir.mkdir(MHPath); 23 dir.mkdir(MHPath);
24 } 24 }
25 init_storage(); 25 init_storage();
26 } 26 }
27} 27}
28 28
29void MHwrapper::init_storage() 29void MHwrapper::init_storage()
30{ 30{
31 int r; 31 int r;
32 QString pre = MHPath; 32 QString pre = MHPath;
33 if (!m_storage) { 33 if (!m_storage) {
34 m_storage = mailstorage_new(NULL); 34 m_storage = mailstorage_new(NULL);
35 r = mh_mailstorage_init(m_storage,(char*)pre.latin1(),0,0,0); 35 r = mh_mailstorage_init(m_storage,(char*)pre.latin1(),0,0,0);
36 if (r != MAIL_NO_ERROR) { 36 if (r != MAIL_NO_ERROR) {
37 qDebug("error initializing storage"); 37 qDebug("error initializing storage");
38 mailstorage_free(m_storage); 38 mailstorage_free(m_storage);
39 m_storage = 0; 39 m_storage = 0;
40 return; 40 return;
41 } 41 }
42 } 42 }
43 r = mailstorage_connect(m_storage); 43 r = mailstorage_connect(m_storage);
44 if (r!=MAIL_NO_ERROR) { 44 if (r!=MAIL_NO_ERROR) {
45 qDebug("error connecting storage"); 45 qDebug("error connecting storage");
46 mailstorage_free(m_storage); 46 mailstorage_free(m_storage);
47 m_storage = 0; 47 m_storage = 0;
48 } 48 }
49} 49}
50 50
51void MHwrapper::clean_storage() 51void MHwrapper::clean_storage()
52{ 52{
53 if (m_storage) { 53 if (m_storage) {
54 mailstorage_disconnect(m_storage); 54 mailstorage_disconnect(m_storage);
55 mailstorage_free(m_storage); 55 mailstorage_free(m_storage);
56 m_storage = 0; 56 m_storage = 0;
57 } 57 }
58} 58}
59 59
60MHwrapper::~MHwrapper() 60MHwrapper::~MHwrapper()
61{ 61{
62 clean_storage(); 62 clean_storage();
63} 63}
64 64
65void MHwrapper::listMessages(const QString & mailbox, QList<RecMail> &target ) 65void MHwrapper::listMessages(const QString & mailbox, QList<RecMail> &target )
66{ 66{
67 init_storage(); 67 init_storage();
68 if (!m_storage) { 68 if (!m_storage) {
69 return; 69 return;
70 } 70 }
71 QString f = buildPath(mailbox); 71 QString f = buildPath(mailbox);
72 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1()); 72 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
73 if (r!=MAIL_NO_ERROR) { 73 if (r!=MAIL_NO_ERROR) {
74 qDebug("listMessages: error selecting folder!"); 74 qDebug("listMessages: error selecting folder!");
75 return; 75 return;
76 } 76 }
77 parseList(target,m_storage->sto_session,f); 77 parseList(target,m_storage->sto_session,f);
78 Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count())); 78 Global::statusMessage(tr("Mailbox has %1 mail(s)").arg(target.count()));
79} 79}
80 80
81QList<Folder>* MHwrapper::listFolders() 81QList<Folder>* MHwrapper::listFolders()
82{ 82{
83 QList<Folder> * folders = new QList<Folder>(); 83 QList<Folder> * folders = new QList<Folder>();
84 folders->setAutoDelete( false ); 84 folders->setAutoDelete( false );
85 /* this is needed! */ 85 /* this is needed! */
86 if (m_storage) mailstorage_disconnect(m_storage); 86 if (m_storage) mailstorage_disconnect(m_storage);
87 init_storage(); 87 init_storage();
88 if (!m_storage) { 88 if (!m_storage) {
89 return folders; 89 return folders;
90 } 90 }
91 mail_list*flist = 0; 91 mail_list*flist = 0;
92 clistcell*current=0; 92 clistcell*current=0;
93 int r = mailsession_list_folders(m_storage->sto_session,NULL,&flist); 93 int r = mailsession_list_folders(m_storage->sto_session,NULL,&flist);
94 if (r != MAIL_NO_ERROR || !flist) { 94 if (r != MAIL_NO_ERROR || !flist) {
95 qDebug("error getting folder list"); 95 qDebug("error getting folder list");
96 return folders; 96 return folders;
97 } 97 }
98 for (current=clist_begin(flist->mb_list);current!=0;current=clist_next(current)) { 98 for (current=clist_begin(flist->mb_list);current!=0;current=clist_next(current)) {
99 QString t = (char*)current->data; 99 QString t = (char*)current->data;
100 t.replace(0,MHPath.length(),""); 100 t.replace(0,MHPath.length(),"");
101 folders->append(new MHFolder(t,MHPath)); 101 folders->append(new MHFolder(t,MHPath));
102 } 102 }
103 mail_list_free(flist); 103 mail_list_free(flist);
104 return folders; 104 return folders;
105} 105}
106 106
107void MHwrapper::deleteMail(const RecMail&mail) 107void MHwrapper::deleteMail(const RecMail&mail)
108{ 108{
109 init_storage(); 109 init_storage();
110 if (!m_storage) { 110 if (!m_storage) {
111 return; 111 return;
112 } 112 }
113 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1()); 113 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1());
114 if (r!=MAIL_NO_ERROR) { 114 if (r!=MAIL_NO_ERROR) {
115 qDebug("error selecting folder!"); 115 qDebug("error selecting folder!");
116 return; 116 return;
117 } 117 }
118 r = mailsession_remove_message(m_storage->sto_session,mail.getNumber()); 118 r = mailsession_remove_message(m_storage->sto_session,mail.getNumber());
119 if (r != MAIL_NO_ERROR) { 119 if (r != MAIL_NO_ERROR) {
120 qDebug("error deleting mail"); 120 qDebug("error deleting mail");
121 } 121 }
122} 122}
123 123
124void MHwrapper::answeredMail(const RecMail&) 124void MHwrapper::answeredMail(const RecMail&)
125{ 125{
126} 126}
127 127
128RecBody MHwrapper::fetchBody( const RecMail &mail ) 128RecBody MHwrapper::fetchBody( const RecMail &mail )
129{ 129{
130 RecBody body; 130 RecBody body;
131 init_storage(); 131 init_storage();
132 if (!m_storage) { 132 if (!m_storage) {
133 return body; 133 return body;
134 } 134 }
135 mailmessage * msg; 135 mailmessage * msg;
136 char*data=0; 136 char*data=0;
137 size_t size; 137 size_t size;
138 138
139 /* mail should hold the complete path! */ 139 /* mail should hold the complete path! */
140 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1()); 140 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1());
141 if (r != MAIL_NO_ERROR) { 141 if (r != MAIL_NO_ERROR) {
142 return body; 142 return body;
143 } 143 }
144 r = mailsession_get_message(m_storage->sto_session, mail.getNumber(), &msg); 144 r = mailsession_get_message(m_storage->sto_session, mail.getNumber(), &msg);
145 if (r != MAIL_NO_ERROR) { 145 if (r != MAIL_NO_ERROR) {
146 qDebug("Error fetching mail %i",mail.getNumber()); 146 qDebug("Error fetching mail %i",mail.getNumber());
147 return body; 147 return body;
148 } 148 }
149 body = parseMail(msg); 149 body = parseMail(msg);
150 mailmessage_fetch_result_free(msg,data); 150 mailmessage_fetch_result_free(msg,data);
151 return body; 151 return body;
152} 152}
153 153
154void MHwrapper::mbox_progress( size_t current, size_t maximum ) 154void MHwrapper::mbox_progress( size_t current, size_t maximum )
155{ 155{
156 qDebug("MH %i von %i",current,maximum); 156 qDebug("MH %i von %i",current,maximum);
157} 157}
158 158
159QString MHwrapper::buildPath(const QString&p) 159QString MHwrapper::buildPath(const QString&p)
160{ 160{
161 QString f=""; 161 QString f="";
162 if (p.length()==0||p=="/") 162 if (p.length()==0||p=="/")
163 return MHPath; 163 return MHPath;
164 if (!p.startsWith(MHPath)) { 164 if (!p.startsWith(MHPath)) {
165 f+=MHPath; 165 f+=MHPath;
166 } 166 }
167 if (!p.startsWith("/")) { 167 if (!p.startsWith("/")) {
168 f+="/"; 168 f+="/";
169 } 169 }
170 f+=p; 170 f+=p;
171 return f; 171 return f;
172} 172}
173 173
174int MHwrapper::createMbox(const QString&folder,const Folder*pfolder,const QString&,bool ) 174int MHwrapper::createMbox(const QString&folder,const Folder*pfolder,const QString&,bool )
175{ 175{
176 init_storage(); 176 init_storage();
177 if (!m_storage) { 177 if (!m_storage) {
178 return 0; 178 return 0;
179 } 179 }
180 QString f; 180 QString f;
181 if (!pfolder) { 181 if (!pfolder) {
182 // toplevel folder 182 // toplevel folder
183 f = buildPath(folder); 183 f = buildPath(folder);
184 } else { 184 } else {
185 f = pfolder->getName(); 185 f = pfolder->getName();
186 f+="/"; 186 f+="/";
187 f+=folder; 187 f+=folder;
188 } 188 }
189 qDebug(f); 189 qDebug(f);
190 int r = mailsession_create_folder(m_storage->sto_session,(char*)f.latin1()); 190 int r = mailsession_create_folder(m_storage->sto_session,(char*)f.latin1());
191 if (r != MAIL_NO_ERROR) { 191 if (r != MAIL_NO_ERROR) {
192 qDebug("error creating folder %i",r); 192 qDebug("error creating folder %i",r);
193 return 0; 193 return 0;
194 } 194 }
195 qDebug("Folder created"); 195 qDebug("Folder created");
196 return 1; 196 return 1;
197} 197}
198 198
199void MHwrapper::storeMessage(const char*msg,size_t length, const QString&Folder) 199void MHwrapper::storeMessage(const char*msg,size_t length, const QString&Folder)
200{ 200{
201 init_storage(); 201 init_storage();
202 if (!m_storage) { 202 if (!m_storage) {
203 return; 203 return;
204 } 204 }
205 QString f = buildPath(Folder); 205 QString f = buildPath(Folder);
206 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1()); 206 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
207 if (r!=MAIL_NO_ERROR) { 207 if (r!=MAIL_NO_ERROR) {
208 qDebug("error selecting folder!"); 208 qDebug("error selecting folder!");
209 return; 209 return;
210 } 210 }
211 r = mailsession_append_message(m_storage->sto_session,(char*)msg,length); 211 r = mailsession_append_message(m_storage->sto_session,(char*)msg,length);
212 if (r!=MAIL_NO_ERROR) { 212 if (r!=MAIL_NO_ERROR) {
213 qDebug("error storing mail"); 213 qDebug("error storing mail");
214 } 214 }
215 return; 215 return;
216} 216}
217 217
218encodedString* MHwrapper::fetchRawBody(const RecMail&mail) 218encodedString* MHwrapper::fetchRawBody(const RecMail&mail)
219{ 219{
220 encodedString*result = 0; 220 encodedString*result = 0;
221 init_storage(); 221 init_storage();
222 if (!m_storage) { 222 if (!m_storage) {
223 return result; 223 return result;
224 } 224 }
225 mailmessage * msg = 0; 225 mailmessage * msg = 0;
226 char*data=0; 226 char*data=0;
227 size_t size; 227 size_t size;
228 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1()); 228 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1());
229 if (r!=MAIL_NO_ERROR) { 229 if (r!=MAIL_NO_ERROR) {
230 qDebug("error selecting folder!"); 230 qDebug("error selecting folder!");
231 return result; 231 return result;
232 } 232 }
233 r = mailsession_get_message(m_storage->sto_session, mail.getNumber(), &msg); 233 r = mailsession_get_message(m_storage->sto_session, mail.getNumber(), &msg);
234 if (r != MAIL_NO_ERROR) { 234 if (r != MAIL_NO_ERROR) {
235 Global::statusMessage(tr("Error fetching mail %i").arg(mail.getNumber())); 235 Global::statusMessage(tr("Error fetching mail %i").arg(mail.getNumber()));
236 return 0; 236 return 0;
237 } 237 }
238 r = mailmessage_fetch(msg,&data,&size); 238 r = mailmessage_fetch(msg,&data,&size);
239 if (r != MAIL_NO_ERROR) { 239 if (r != MAIL_NO_ERROR) {
240 Global::statusMessage(tr("Error fetching mail %i").arg(mail.getNumber())); 240 Global::statusMessage(tr("Error fetching mail %i").arg(mail.getNumber()));
241 if (msg) mailmessage_free(msg); 241 if (msg) mailmessage_free(msg);
242 return 0; 242 return 0;
243 } 243 }
244 result = new encodedString(data,size); 244 result = new encodedString(data,size);
245 if (msg) mailmessage_free(msg); 245 if (msg) mailmessage_free(msg);
246 return result; 246 return result;
247} 247}
248 248
249void MHwrapper::deleteMails(const QString & mailbox,QList<RecMail> &target) 249void MHwrapper::deleteMails(const QString & mailbox,QList<RecMail> &target)
250{ 250{
251 QString f = buildPath(mailbox); 251 QString f = buildPath(mailbox);
252 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1()); 252 int r = mailsession_select_folder(m_storage->sto_session,(char*)f.latin1());
253 if (r!=MAIL_NO_ERROR) { 253 if (r!=MAIL_NO_ERROR) {
254 qDebug("deleteMails: error selecting folder!"); 254 qDebug("deleteMails: error selecting folder!");
255 return; 255 return;
256 } 256 }
257 RecMail*c = 0; 257 RecMail*c = 0;
258 for (unsigned int i=0; i < target.count();++i) { 258 for (unsigned int i=0; i < target.count();++i) {
259 c = target.at(i); 259 c = target.at(i);
260 r = mailsession_remove_message(m_storage->sto_session,c->getNumber()); 260 r = mailsession_remove_message(m_storage->sto_session,c->getNumber());
261 if (r != MAIL_NO_ERROR) { 261 if (r != MAIL_NO_ERROR) {
262 qDebug("error deleting mail"); 262 qDebug("error deleting mail");
263 break; 263 break;
264 } 264 }
265 } 265 }
266} 266}
267 267
268int MHwrapper::deleteAllMail(const Folder*tfolder) 268int MHwrapper::deleteAllMail(const Folder*tfolder)
269{ 269{
270 init_storage(); 270 init_storage();
271 if (!m_storage) { 271 if (!m_storage) {
272 return 0; 272 return 0;
273 } 273 }
274 int res = 1; 274 int res = 1;
275 if (!tfolder) return 0; 275 if (!tfolder) return 0;
276 int r = mailsession_select_folder(m_storage->sto_session,(char*)tfolder->getName().latin1()); 276 int r = mailsession_select_folder(m_storage->sto_session,(char*)tfolder->getName().latin1());
277 if (r!=MAIL_NO_ERROR) { 277 if (r!=MAIL_NO_ERROR) {
278 qDebug("error selecting folder!"); 278 qDebug("error selecting folder!");
279 return 0; 279 return 0;
280 } 280 }
281 mailmessage_list*l=0; 281 mailmessage_list*l=0;
282 r = mailsession_get_messages_list(m_storage->sto_session,&l); 282 r = mailsession_get_messages_list(m_storage->sto_session,&l);
283 if (r != MAIL_NO_ERROR) { 283 if (r != MAIL_NO_ERROR) {
284 qDebug("Error message list"); 284 qDebug("Error message list");
285 res = 0; 285 res = 0;
286 } 286 }
287 unsigned j = 0; 287 unsigned j = 0;
288 for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) { 288 for(unsigned int i = 0 ; l!= 0 && res==1 && i < carray_count(l->msg_tab) ; ++i) {
289 mailmessage * msg; 289 mailmessage * msg;
290 msg = (mailmessage*)carray_get(l->msg_tab, i); 290 msg = (mailmessage*)carray_get(l->msg_tab, i);
291 j = msg->msg_index; 291 j = msg->msg_index;
292 r = mailsession_remove_message(m_storage->sto_session,j); 292 r = mailsession_remove_message(m_storage->sto_session,j);
293 if (r != MAIL_NO_ERROR) { 293 if (r != MAIL_NO_ERROR) {
294 Global::statusMessage(tr("Error deleting mail %1").arg(i+1)); 294 Global::statusMessage(tr("Error deleting mail %1").arg(i+1));
295 res = 0; 295 res = 0;
296 break; 296 break;
297 } 297 }
298 } 298 }
299 if (l) mailmessage_list_free(l); 299 if (l) mailmessage_list_free(l);
300 return res; 300 return res;
301} 301}
302 302
303int MHwrapper::deleteMbox(const Folder*tfolder) 303int MHwrapper::deleteMbox(const Folder*tfolder)
304{ 304{
305 init_storage(); 305 init_storage();
306 if (!m_storage) { 306 if (!m_storage) {
307 return 0; 307 return 0;
308 } 308 }
309 if (!tfolder) return 0; 309 if (!tfolder) return 0;
310 if (tfolder->getName()=="/" || tfolder->getName().isEmpty()) return 0; 310 if (tfolder->getName()=="/" || tfolder->getName().isEmpty()) return 0;
311 311
312 int r = mailsession_delete_folder(m_storage->sto_session,(char*)tfolder->getName().latin1()); 312 int r = mailsession_delete_folder(m_storage->sto_session,(char*)tfolder->getName().latin1());
313 313
314 if (r != MAIL_NO_ERROR) { 314 if (r != MAIL_NO_ERROR) {
315 qDebug("error deleting mail box"); 315 qDebug("error deleting mail box");
316 return 0; 316 return 0;
317 } 317 }
318 QString cmd = "rm -rf "+tfolder->getName(); 318 QString cmd = "rm -rf "+tfolder->getName();
319 QStringList command; 319 QStringList command;
320 command << "/bin/sh"; 320 command << "/bin/sh";
321 command << "-c"; 321 command << "-c";
322 command << cmd.latin1(); 322 command << cmd.latin1();
323 OProcess *process = new OProcess(); 323 OProcess *process = new OProcess();
324 324
325 connect(process, SIGNAL(processExited(OProcess *)), 325 connect(process, SIGNAL(processExited(OProcess*)),
326 this, SLOT( processEnded(OProcess *))); 326 this, SLOT( processEnded(OProcess*)));
327 connect(process, SIGNAL( receivedStderr(OProcess *, char *, int)), 327 connect(process, SIGNAL( receivedStderr(OProcess*,char*,int)),
328 this, SLOT( oprocessStderr(OProcess *, char *, int))); 328 this, SLOT( oprocessStderr(OProcess*,char*,int)));
329 329
330 *process << command; 330 *process << command;
331 removeMboxfailed = false; 331 removeMboxfailed = false;
332 if(!process->start(OProcess::Block, OProcess::All) ) { 332 if(!process->start(OProcess::Block, OProcess::All) ) {
333 qDebug("could not start process"); 333 qDebug("could not start process");
334 return 0; 334 return 0;
335 } 335 }
336 qDebug("mail box deleted"); 336 qDebug("mail box deleted");
337 return 1; 337 return 1;
338} 338}
339 339
340void MHwrapper::processEnded(OProcess *p) 340void MHwrapper::processEnded(OProcess *p)
341{ 341{
342 if (p) delete p; 342 if (p) delete p;
343} 343}
344 344
345void MHwrapper::oprocessStderr(OProcess*, char *buffer, int ) 345void MHwrapper::oprocessStderr(OProcess*, char *buffer, int )
346{ 346{
347 QString lineStr = buffer; 347 QString lineStr = buffer;
348 QMessageBox::warning( 0, tr("Error"), lineStr ,tr("Ok") ); 348 QMessageBox::warning( 0, tr("Error"), lineStr ,tr("Ok") );
349 removeMboxfailed = true; 349 removeMboxfailed = true;
350} 350}
351 351
352void MHwrapper::statusFolder(folderStat&target_stat,const QString & mailbox) 352void MHwrapper::statusFolder(folderStat&target_stat,const QString & mailbox)
353{ 353{
354 init_storage(); 354 init_storage();
355 if (!m_storage) { 355 if (!m_storage) {
356 return; 356 return;
357 } 357 }
358 target_stat.message_count = 0; 358 target_stat.message_count = 0;
359 target_stat.message_unseen = 0; 359 target_stat.message_unseen = 0;
360 target_stat.message_recent = 0; 360 target_stat.message_recent = 0;
361 QString f = buildPath(mailbox); 361 QString f = buildPath(mailbox);
362 int r = mailsession_status_folder(m_storage->sto_session,(char*)f.latin1(),&target_stat.message_count, 362 int r = mailsession_status_folder(m_storage->sto_session,(char*)f.latin1(),&target_stat.message_count,
363 &target_stat.message_recent,&target_stat.message_unseen); 363 &target_stat.message_recent,&target_stat.message_unseen);
364 if (r != MAIL_NO_ERROR) { 364 if (r != MAIL_NO_ERROR) {
365 Global::statusMessage(tr("Error retrieving status")); 365 Global::statusMessage(tr("Error retrieving status"));
366 } 366 }
367} 367}
368 368
369const QString&MHwrapper::getType()const 369const QString&MHwrapper::getType()const
370{ 370{
371 return wrapperType; 371 return wrapperType;
372} 372}
373 373
374const QString&MHwrapper::getName()const 374const QString&MHwrapper::getName()const
375{ 375{
376 return MHName; 376 return MHName;
377} 377}
378void MHwrapper::mvcpMail(const RecMail&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 378void MHwrapper::mvcpMail(const RecMail&mail,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
379{ 379{
380 init_storage(); 380 init_storage();
381 if (!m_storage) { 381 if (!m_storage) {
382 return; 382 return;
383 } 383 }
384 if (targetWrapper != this) { 384 if (targetWrapper != this) {
385 qDebug("Using generic"); 385 qDebug("Using generic");
386 Genericwrapper::mvcpMail(mail,targetFolder,targetWrapper,moveit); 386 Genericwrapper::mvcpMail(mail,targetFolder,targetWrapper,moveit);
387 return; 387 return;
388 } 388 }
389 qDebug("Using internal routines for move/copy"); 389 qDebug("Using internal routines for move/copy");
390 QString tf = buildPath(targetFolder); 390 QString tf = buildPath(targetFolder);
391 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1()); 391 int r = mailsession_select_folder(m_storage->sto_session,(char*)mail.getMbox().latin1());
392 if (r != MAIL_NO_ERROR) { 392 if (r != MAIL_NO_ERROR) {
393 qDebug("Error selecting source mailbox"); 393 qDebug("Error selecting source mailbox");
394 return; 394 return;
395 } 395 }
396 if (moveit) { 396 if (moveit) {
397 r = mailsession_move_message(m_storage->sto_session,mail.getNumber(),(char*)tf.latin1()); 397 r = mailsession_move_message(m_storage->sto_session,mail.getNumber(),(char*)tf.latin1());
398 } else { 398 } else {
399 r = mailsession_copy_message(m_storage->sto_session,mail.getNumber(),(char*)tf.latin1()); 399 r = mailsession_copy_message(m_storage->sto_session,mail.getNumber(),(char*)tf.latin1());
400 } 400 }
401 if (r != MAIL_NO_ERROR) { 401 if (r != MAIL_NO_ERROR) {
402 qDebug("Error copy/moving mail internal (%i)",r); 402 qDebug("Error copy/moving mail internal (%i)",r);
403 } 403 }
404} 404}
405 405
406void MHwrapper::mvcpAllMails(Folder*fromFolder,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit) 406void MHwrapper::mvcpAllMails(Folder*fromFolder,const QString&targetFolder,AbstractMail*targetWrapper,bool moveit)
407{ 407{
408 init_storage(); 408 init_storage();
409 if (!m_storage) { 409 if (!m_storage) {
410 return; 410 return;
411 } 411 }
412 if (targetWrapper != this) { 412 if (targetWrapper != this) {
413 qDebug("Using generic"); 413 qDebug("Using generic");
414 Genericwrapper::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit); 414 Genericwrapper::mvcpAllMails(fromFolder,targetFolder,targetWrapper,moveit);
415 return; 415 return;
416 } 416 }
417 if (!fromFolder) return; 417 if (!fromFolder) return;
418 int r = mailsession_select_folder(m_storage->sto_session,(char*)fromFolder->getName().latin1()); 418 int r = mailsession_select_folder(m_storage->sto_session,(char*)fromFolder->getName().latin1());
419 if (r!=MAIL_NO_ERROR) { 419 if (r!=MAIL_NO_ERROR) {
420 qDebug("error selecting source folder!"); 420 qDebug("error selecting source folder!");
421 return; 421 return;
422 } 422 }
423 QString tf = buildPath(targetFolder); 423 QString tf = buildPath(targetFolder);
424 mailmessage_list*l=0; 424 mailmessage_list*l=0;
425 r = mailsession_get_messages_list(m_storage->sto_session,&l); 425 r = mailsession_get_messages_list(m_storage->sto_session,&l);
426 if (r != MAIL_NO_ERROR) { 426 if (r != MAIL_NO_ERROR) {
427 qDebug("Error message list"); 427 qDebug("Error message list");
428 } 428 }
429 unsigned j = 0; 429 unsigned j = 0;
430 for(unsigned int i = 0 ; l!= 0 && i < carray_count(l->msg_tab) ; ++i) { 430 for(unsigned int i = 0 ; l!= 0 && i < carray_count(l->msg_tab) ; ++i) {
431 mailmessage * msg; 431 mailmessage * msg;
432 msg = (mailmessage*)carray_get(l->msg_tab, i); 432 msg = (mailmessage*)carray_get(l->msg_tab, i);
433 j = msg->msg_index; 433 j = msg->msg_index;
434 if (moveit) { 434 if (moveit) {
435 r = mailsession_move_message(m_storage->sto_session,j,(char*)tf.latin1()); 435 r = mailsession_move_message(m_storage->sto_session,j,(char*)tf.latin1());
436 } else { 436 } else {
437 r = mailsession_copy_message(m_storage->sto_session,j,(char*)tf.latin1()); 437 r = mailsession_copy_message(m_storage->sto_session,j,(char*)tf.latin1());
438 } 438 }
439 if (r != MAIL_NO_ERROR) { 439 if (r != MAIL_NO_ERROR) {
440 qDebug("Error copy/moving mail internal (%i)",r); 440 qDebug("Error copy/moving mail internal (%i)",r);
441 break; 441 break;
442 } 442 }
443 } 443 }
444 if (l) mailmessage_list_free(l); 444 if (l) mailmessage_list_free(l);
445} 445}
diff --git a/noncore/net/mail/libmailwrapper/smtpwrapper.cpp b/noncore/net/mail/libmailwrapper/smtpwrapper.cpp
index a3c68ae..d75d52a 100644
--- a/noncore/net/mail/libmailwrapper/smtpwrapper.cpp
+++ b/noncore/net/mail/libmailwrapper/smtpwrapper.cpp
@@ -1,875 +1,875 @@
1#include <stdlib.h> 1#include <stdlib.h>
2#include <sys/stat.h> 2#include <sys/stat.h>
3#include <sys/types.h> 3#include <sys/types.h>
4#include <unistd.h> 4#include <unistd.h>
5#include <fcntl.h> 5#include <fcntl.h>
6#include <string.h> 6#include <string.h>
7#include <qdir.h> 7#include <qdir.h>
8#include <qt.h> 8#include <qt.h>
9#include <qmessagebox.h> 9#include <qmessagebox.h>
10 10
11#include <qpe/config.h> 11#include <qpe/config.h>
12#include <qpe/qcopenvelope_qws.h> 12#include <qpe/qcopenvelope_qws.h>
13 13
14#include <libetpan/libetpan.h> 14#include <libetpan/libetpan.h>
15 15
16#include "smtpwrapper.h" 16#include "smtpwrapper.h"
17#include "mailwrapper.h" 17#include "mailwrapper.h"
18#include "abstractmail.h" 18#include "abstractmail.h"
19#include "logindialog.h" 19#include "logindialog.h"
20#include "mailtypes.h" 20#include "mailtypes.h"
21#include "sendmailprogress.h" 21#include "sendmailprogress.h"
22 22
23const char* SMTPwrapper::USER_AGENT="OpieMail v0.4"; 23const char* SMTPwrapper::USER_AGENT="OpieMail v0.4";
24 24
25progressMailSend*SMTPwrapper::sendProgress = 0; 25progressMailSend*SMTPwrapper::sendProgress = 0;
26 26
27SMTPwrapper::SMTPwrapper(SMTPaccount * aSmtp ) 27SMTPwrapper::SMTPwrapper(SMTPaccount * aSmtp )
28 : QObject() 28 : QObject()
29{ 29{
30 m_SmtpAccount = aSmtp; 30 m_SmtpAccount = aSmtp;
31 Config cfg( "mail" ); 31 Config cfg( "mail" );
32 cfg.setGroup( "Status" ); 32 cfg.setGroup( "Status" );
33 m_queuedMail = cfg.readNumEntry( "outgoing", 0 ); 33 m_queuedMail = cfg.readNumEntry( "outgoing", 0 );
34 emit queuedMails( m_queuedMail ); 34 emit queuedMails( m_queuedMail );
35 connect( this, SIGNAL( queuedMails( int ) ), this, SLOT( emitQCop( int ) ) ); 35 connect( this, SIGNAL( queuedMails(int) ), this, SLOT( emitQCop(int) ) );
36 m_smtp = 0; 36 m_smtp = 0;
37} 37}
38 38
39SMTPwrapper::~SMTPwrapper() 39SMTPwrapper::~SMTPwrapper()
40{ 40{
41 disc_server(); 41 disc_server();
42} 42}
43 43
44void SMTPwrapper::emitQCop( int queued ) { 44void SMTPwrapper::emitQCop( int queued ) {
45 QCopEnvelope env( "QPE/Pim", "outgoingMails(int)" ); 45 QCopEnvelope env( "QPE/Pim", "outgoingMails(int)" );
46 env << queued; 46 env << queued;
47} 47}
48 48
49QString SMTPwrapper::mailsmtpError( int errnum ) { 49QString SMTPwrapper::mailsmtpError( int errnum ) {
50 switch ( errnum ) { 50 switch ( errnum ) {
51 case MAILSMTP_NO_ERROR: 51 case MAILSMTP_NO_ERROR:
52 return tr( "No error" ); 52 return tr( "No error" );
53 case MAILSMTP_ERROR_UNEXPECTED_CODE: 53 case MAILSMTP_ERROR_UNEXPECTED_CODE:
54 return tr( "Unexpected error code" ); 54 return tr( "Unexpected error code" );
55 case MAILSMTP_ERROR_SERVICE_NOT_AVAILABLE: 55 case MAILSMTP_ERROR_SERVICE_NOT_AVAILABLE:
56 return tr( "Service not available" ); 56 return tr( "Service not available" );
57 case MAILSMTP_ERROR_STREAM: 57 case MAILSMTP_ERROR_STREAM:
58 return tr( "Stream error" ); 58 return tr( "Stream error" );
59 case MAILSMTP_ERROR_HOSTNAME: 59 case MAILSMTP_ERROR_HOSTNAME:
60 return tr( "gethostname() failed" ); 60 return tr( "gethostname() failed" );
61 case MAILSMTP_ERROR_NOT_IMPLEMENTED: 61 case MAILSMTP_ERROR_NOT_IMPLEMENTED:
62 return tr( "Not implemented" ); 62 return tr( "Not implemented" );
63 case MAILSMTP_ERROR_ACTION_NOT_TAKEN: 63 case MAILSMTP_ERROR_ACTION_NOT_TAKEN:
64 return tr( "Error, action not taken" ); 64 return tr( "Error, action not taken" );
65 case MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION: 65 case MAILSMTP_ERROR_EXCEED_STORAGE_ALLOCATION:
66 return tr( "Data exceeds storage allocation" ); 66 return tr( "Data exceeds storage allocation" );
67 case MAILSMTP_ERROR_IN_PROCESSING: 67 case MAILSMTP_ERROR_IN_PROCESSING:
68 return tr( "Error in processing" ); 68 return tr( "Error in processing" );
69 case MAILSMTP_ERROR_STARTTLS_NOT_SUPPORTED: 69 case MAILSMTP_ERROR_STARTTLS_NOT_SUPPORTED:
70 return tr( "Starttls not supported" ); 70 return tr( "Starttls not supported" );
71 // case MAILSMTP_ERROR_INSUFFISANT_SYSTEM_STORAGE: 71 // case MAILSMTP_ERROR_INSUFFISANT_SYSTEM_STORAGE:
72 // return tr( "Insufficient system storage" ); 72 // return tr( "Insufficient system storage" );
73 case MAILSMTP_ERROR_MAILBOX_UNAVAILABLE: 73 case MAILSMTP_ERROR_MAILBOX_UNAVAILABLE:
74 return tr( "Mailbox unavailable" ); 74 return tr( "Mailbox unavailable" );
75 case MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED: 75 case MAILSMTP_ERROR_MAILBOX_NAME_NOT_ALLOWED:
76 return tr( "Mailbox name not allowed" ); 76 return tr( "Mailbox name not allowed" );
77 case MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND: 77 case MAILSMTP_ERROR_BAD_SEQUENCE_OF_COMMAND:
78 return tr( "Bad command sequence" ); 78 return tr( "Bad command sequence" );
79 case MAILSMTP_ERROR_USER_NOT_LOCAL: 79 case MAILSMTP_ERROR_USER_NOT_LOCAL:
80 return tr( "User not local" ); 80 return tr( "User not local" );
81 case MAILSMTP_ERROR_TRANSACTION_FAILED: 81 case MAILSMTP_ERROR_TRANSACTION_FAILED:
82 return tr( "Transaction failed" ); 82 return tr( "Transaction failed" );
83 case MAILSMTP_ERROR_MEMORY: 83 case MAILSMTP_ERROR_MEMORY:
84 return tr( "Memory error" ); 84 return tr( "Memory error" );
85 case MAILSMTP_ERROR_CONNECTION_REFUSED: 85 case MAILSMTP_ERROR_CONNECTION_REFUSED:
86 return tr( "Connection refused" ); 86 return tr( "Connection refused" );
87 default: 87 default:
88 return tr( "Unknown error code" ); 88 return tr( "Unknown error code" );
89 } 89 }
90} 90}
91 91
92mailimf_mailbox *SMTPwrapper::newMailbox(const QString&name, const QString&mail ) { 92mailimf_mailbox *SMTPwrapper::newMailbox(const QString&name, const QString&mail ) {
93 return mailimf_mailbox_new( strdup( name.latin1() ), 93 return mailimf_mailbox_new( strdup( name.latin1() ),
94 strdup( mail.latin1() ) ); 94 strdup( mail.latin1() ) );
95} 95}
96 96
97mailimf_address_list *SMTPwrapper::parseAddresses(const QString&addr ) { 97mailimf_address_list *SMTPwrapper::parseAddresses(const QString&addr ) {
98 mailimf_address_list *addresses; 98 mailimf_address_list *addresses;
99 99
100 if ( addr.isEmpty() ) 100 if ( addr.isEmpty() )
101 return NULL; 101 return NULL;
102 102
103 addresses = mailimf_address_list_new_empty(); 103 addresses = mailimf_address_list_new_empty();
104 104
105 bool literal_open = false; 105 bool literal_open = false;
106 unsigned int startpos = 0; 106 unsigned int startpos = 0;
107 QStringList list; 107 QStringList list;
108 QString s; 108 QString s;
109 unsigned int i = 0; 109 unsigned int i = 0;
110 for (; i < addr.length();++i) { 110 for (; i < addr.length();++i) {
111 switch (addr[i]) { 111 switch (addr[i]) {
112 case '\"': 112 case '\"':
113 literal_open = !literal_open; 113 literal_open = !literal_open;
114 break; 114 break;
115 case ',': 115 case ',':
116 if (!literal_open) { 116 if (!literal_open) {
117 s = addr.mid(startpos,i-startpos); 117 s = addr.mid(startpos,i-startpos);
118 if (!s.isEmpty()) { 118 if (!s.isEmpty()) {
119 list.append(s); 119 list.append(s);
120 qDebug("Appended %s",s.latin1()); 120 qDebug("Appended %s",s.latin1());
121 } 121 }
122 // !!!! this is a MUST BE! 122 // !!!! this is a MUST BE!
123 startpos = ++i; 123 startpos = ++i;
124 } 124 }
125 break; 125 break;
126 default: 126 default:
127 break; 127 break;
128 } 128 }
129 } 129 }
130 s = addr.mid(startpos,i-startpos); 130 s = addr.mid(startpos,i-startpos);
131 if (!s.isEmpty()) { 131 if (!s.isEmpty()) {
132 list.append(s); 132 list.append(s);
133 qDebug("Appended %s",s.latin1()); 133 qDebug("Appended %s",s.latin1());
134 } 134 }
135 QStringList::Iterator it; 135 QStringList::Iterator it;
136 for ( it = list.begin(); it != list.end(); it++ ) { 136 for ( it = list.begin(); it != list.end(); it++ ) {
137 int err = mailimf_address_list_add_parse( addresses, (char*)(*it).latin1() ); 137 int err = mailimf_address_list_add_parse( addresses, (char*)(*it).latin1() );
138 if ( err != MAILIMF_NO_ERROR ) { 138 if ( err != MAILIMF_NO_ERROR ) {
139 qDebug( "Error parsing" ); 139 qDebug( "Error parsing" );
140 qDebug( *it ); 140 qDebug( *it );
141 } else { 141 } else {
142 qDebug( "Parse success! %s",(*it).latin1()); 142 qDebug( "Parse success! %s",(*it).latin1());
143 } 143 }
144 } 144 }
145 return addresses; 145 return addresses;
146} 146}
147 147
148mailimf_fields *SMTPwrapper::createImfFields(const Mail&mail ) { 148mailimf_fields *SMTPwrapper::createImfFields(const Mail&mail ) {
149 mailimf_fields *fields; 149 mailimf_fields *fields;
150 mailimf_field *xmailer; 150 mailimf_field *xmailer;
151 mailimf_mailbox *sender=0,*fromBox=0; 151 mailimf_mailbox *sender=0,*fromBox=0;
152 mailimf_mailbox_list *from=0; 152 mailimf_mailbox_list *from=0;
153 mailimf_address_list *to=0, *cc=0, *bcc=0, *reply=0; 153 mailimf_address_list *to=0, *cc=0, *bcc=0, *reply=0;
154 char *subject = strdup( mail.getSubject().latin1() ); 154 char *subject = strdup( mail.getSubject().latin1() );
155 int err; 155 int err;
156 156
157 sender = newMailbox( mail.getName(), mail.getMail() ); 157 sender = newMailbox( mail.getName(), mail.getMail() );
158 if ( sender == NULL ) 158 if ( sender == NULL )
159 goto err_free; 159 goto err_free;
160 160
161 fromBox = newMailbox( mail.getName(), mail.getMail() ); 161 fromBox = newMailbox( mail.getName(), mail.getMail() );
162 if ( fromBox == NULL ) 162 if ( fromBox == NULL )
163 goto err_free_sender; 163 goto err_free_sender;
164 164
165 from = mailimf_mailbox_list_new_empty(); 165 from = mailimf_mailbox_list_new_empty();
166 if ( from == NULL ) 166 if ( from == NULL )
167 goto err_free_fromBox; 167 goto err_free_fromBox;
168 168
169 err = mailimf_mailbox_list_add( from, fromBox ); 169 err = mailimf_mailbox_list_add( from, fromBox );
170 if ( err != MAILIMF_NO_ERROR ) 170 if ( err != MAILIMF_NO_ERROR )
171 goto err_free_from; 171 goto err_free_from;
172 172
173 to = parseAddresses( mail.getTo() ); 173 to = parseAddresses( mail.getTo() );
174 if ( to == NULL ) 174 if ( to == NULL )
175 goto err_free_from; 175 goto err_free_from;
176 176
177 cc = parseAddresses( mail.getCC() ); 177 cc = parseAddresses( mail.getCC() );
178 bcc = parseAddresses( mail.getBCC() ); 178 bcc = parseAddresses( mail.getBCC() );
179 reply = parseAddresses( mail.getReply() ); 179 reply = parseAddresses( mail.getReply() );
180 180
181 fields = mailimf_fields_new_with_data( from, sender, reply, to, cc, bcc, 181 fields = mailimf_fields_new_with_data( from, sender, reply, to, cc, bcc,
182 NULL, NULL, subject ); 182 NULL, NULL, subject );
183 if ( fields == NULL ) 183 if ( fields == NULL )
184 goto err_free_reply; 184 goto err_free_reply;
185 185
186 xmailer = mailimf_field_new_custom( strdup( "User-Agent" ), 186 xmailer = mailimf_field_new_custom( strdup( "User-Agent" ),
187 strdup( USER_AGENT ) ); 187 strdup( USER_AGENT ) );
188 if ( xmailer == NULL ) 188 if ( xmailer == NULL )
189 goto err_free_fields; 189 goto err_free_fields;
190 190
191 err = mailimf_fields_add( fields, xmailer ); 191 err = mailimf_fields_add( fields, xmailer );
192 if ( err != MAILIMF_NO_ERROR ) 192 if ( err != MAILIMF_NO_ERROR )
193 goto err_free_xmailer; 193 goto err_free_xmailer;
194 194
195 return fields; // Success :) 195 return fields; // Success :)
196 196
197err_free_xmailer: 197err_free_xmailer:
198 if (xmailer) 198 if (xmailer)
199 mailimf_field_free( xmailer ); 199 mailimf_field_free( xmailer );
200err_free_fields: 200err_free_fields:
201 if (fields) 201 if (fields)
202 mailimf_fields_free( fields ); 202 mailimf_fields_free( fields );
203err_free_reply: 203err_free_reply:
204 if (reply) 204 if (reply)
205 mailimf_address_list_free( reply ); 205 mailimf_address_list_free( reply );
206 if (bcc) 206 if (bcc)
207 mailimf_address_list_free( bcc ); 207 mailimf_address_list_free( bcc );
208 if (cc) 208 if (cc)
209 mailimf_address_list_free( cc ); 209 mailimf_address_list_free( cc );
210 if (to) 210 if (to)
211 mailimf_address_list_free( to ); 211 mailimf_address_list_free( to );
212err_free_from: 212err_free_from:
213 if (from) 213 if (from)
214 mailimf_mailbox_list_free( from ); 214 mailimf_mailbox_list_free( from );
215err_free_fromBox: 215err_free_fromBox:
216 mailimf_mailbox_free( fromBox ); 216 mailimf_mailbox_free( fromBox );
217err_free_sender: 217err_free_sender:
218 if (sender) 218 if (sender)
219 mailimf_mailbox_free( sender ); 219 mailimf_mailbox_free( sender );
220err_free: 220err_free:
221 if (subject) 221 if (subject)
222 free( subject ); 222 free( subject );
223 qDebug( "createImfFields - error" ); 223 qDebug( "createImfFields - error" );
224 224
225 return NULL; // Error :( 225 return NULL; // Error :(
226} 226}
227 227
228mailmime *SMTPwrapper::buildTxtPart(const QString&str ) { 228mailmime *SMTPwrapper::buildTxtPart(const QString&str ) {
229 mailmime *txtPart; 229 mailmime *txtPart;
230 mailmime_fields *fields; 230 mailmime_fields *fields;
231 mailmime_content *content; 231 mailmime_content *content;
232 mailmime_parameter *param; 232 mailmime_parameter *param;
233 int err; 233 int err;
234 234
235 param = mailmime_parameter_new( strdup( "charset" ), 235 param = mailmime_parameter_new( strdup( "charset" ),
236 strdup( "iso-8859-1" ) ); 236 strdup( "iso-8859-1" ) );
237 if ( param == NULL ) 237 if ( param == NULL )
238 goto err_free; 238 goto err_free;
239 239
240 content = mailmime_content_new_with_str( "text/plain" ); 240 content = mailmime_content_new_with_str( "text/plain" );
241 if ( content == NULL ) 241 if ( content == NULL )
242 goto err_free_param; 242 goto err_free_param;
243 243
244 err = clist_append( content->ct_parameters, param ); 244 err = clist_append( content->ct_parameters, param );
245 if ( err != MAILIMF_NO_ERROR ) 245 if ( err != MAILIMF_NO_ERROR )
246 goto err_free_content; 246 goto err_free_content;
247 247
248 fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT); 248 fields = mailmime_fields_new_encoding(MAILMIME_MECHANISM_8BIT);
249 if ( fields == NULL ) 249 if ( fields == NULL )
250 goto err_free_content; 250 goto err_free_content;
251 251
252 txtPart = mailmime_new_empty( content, fields ); 252 txtPart = mailmime_new_empty( content, fields );
253 if ( txtPart == NULL ) 253 if ( txtPart == NULL )
254 goto err_free_fields; 254 goto err_free_fields;
255 255
256 err = mailmime_set_body_text( txtPart, (char*)str.data(), str.length() ); 256 err = mailmime_set_body_text( txtPart, (char*)str.data(), str.length() );
257 if ( err != MAILIMF_NO_ERROR ) 257 if ( err != MAILIMF_NO_ERROR )
258 goto err_free_txtPart; 258 goto err_free_txtPart;
259 259
260 return txtPart; // Success :) 260 return txtPart; // Success :)
261 261
262err_free_txtPart: 262err_free_txtPart:
263 mailmime_free( txtPart ); 263 mailmime_free( txtPart );
264err_free_fields: 264err_free_fields:
265 mailmime_fields_free( fields ); 265 mailmime_fields_free( fields );
266err_free_content: 266err_free_content:
267 mailmime_content_free( content ); 267 mailmime_content_free( content );
268err_free_param: 268err_free_param:
269 mailmime_parameter_free( param ); 269 mailmime_parameter_free( param );
270err_free: 270err_free:
271 qDebug( "buildTxtPart - error" ); 271 qDebug( "buildTxtPart - error" );
272 272
273 return NULL; // Error :( 273 return NULL; // Error :(
274} 274}
275 275
276mailmime *SMTPwrapper::buildFilePart(const QString&filename,const QString&mimetype,const QString&TextContent ) { 276mailmime *SMTPwrapper::buildFilePart(const QString&filename,const QString&mimetype,const QString&TextContent ) {
277 mailmime * filePart = 0; 277 mailmime * filePart = 0;
278 mailmime_fields * fields = 0; 278 mailmime_fields * fields = 0;
279 mailmime_content * content = 0; 279 mailmime_content * content = 0;
280 mailmime_parameter * param = 0; 280 mailmime_parameter * param = 0;
281 char*name = 0; 281 char*name = 0;
282 char*file = 0; 282 char*file = 0;
283 int err; 283 int err;
284 284
285 int pos = filename.findRev( '/' ); 285 int pos = filename.findRev( '/' );
286 286
287 if (filename.length()>0) { 287 if (filename.length()>0) {
288 QString tmp = filename.right( filename.length() - ( pos + 1 ) ); 288 QString tmp = filename.right( filename.length() - ( pos + 1 ) );
289 name = strdup( tmp.latin1() ); // just filename 289 name = strdup( tmp.latin1() ); // just filename
290 file = strdup( filename.latin1() ); // full name with path 290 file = strdup( filename.latin1() ); // full name with path
291 } 291 }
292 292
293 int disptype = MAILMIME_DISPOSITION_TYPE_ATTACHMENT; 293 int disptype = MAILMIME_DISPOSITION_TYPE_ATTACHMENT;
294 int mechanism = MAILMIME_MECHANISM_BASE64; 294 int mechanism = MAILMIME_MECHANISM_BASE64;
295 295
296 if ( mimetype.startsWith( "text/" ) ) { 296 if ( mimetype.startsWith( "text/" ) ) {
297 param = mailmime_parameter_new( strdup( "charset" ), 297 param = mailmime_parameter_new( strdup( "charset" ),
298 strdup( "iso-8859-1" ) ); 298 strdup( "iso-8859-1" ) );
299 mechanism = MAILMIME_MECHANISM_QUOTED_PRINTABLE; 299 mechanism = MAILMIME_MECHANISM_QUOTED_PRINTABLE;
300 } 300 }
301 301
302 fields = mailmime_fields_new_filename( 302 fields = mailmime_fields_new_filename(
303 disptype, name, 303 disptype, name,
304 mechanism ); 304 mechanism );
305 content = mailmime_content_new_with_str( (char*)mimetype.latin1() ); 305 content = mailmime_content_new_with_str( (char*)mimetype.latin1() );
306 if (content!=0 && fields != 0) { 306 if (content!=0 && fields != 0) {
307 if (param) { 307 if (param) {
308 clist_append(content->ct_parameters,param); 308 clist_append(content->ct_parameters,param);
309 param = 0; 309 param = 0;
310 } 310 }
311 if (filename.length()>0) { 311 if (filename.length()>0) {
312 QFileInfo f(filename); 312 QFileInfo f(filename);
313 param = mailmime_parameter_new(strdup("name"),strdup(f.fileName().latin1())); 313 param = mailmime_parameter_new(strdup("name"),strdup(f.fileName().latin1()));
314 clist_append(content->ct_parameters,param); 314 clist_append(content->ct_parameters,param);
315 param = 0; 315 param = 0;
316 } 316 }
317 filePart = mailmime_new_empty( content, fields ); 317 filePart = mailmime_new_empty( content, fields );
318 } 318 }
319 if (filePart) { 319 if (filePart) {
320 if (filename.length()>0) { 320 if (filename.length()>0) {
321 err = mailmime_set_body_file( filePart, file ); 321 err = mailmime_set_body_file( filePart, file );
322 } else { 322 } else {
323 err = mailmime_set_body_text(filePart,strdup(TextContent.data()),TextContent.length()); 323 err = mailmime_set_body_text(filePart,strdup(TextContent.data()),TextContent.length());
324 } 324 }
325 if (err != MAILIMF_NO_ERROR) { 325 if (err != MAILIMF_NO_ERROR) {
326 qDebug("Error setting body with file %s",file); 326 qDebug("Error setting body with file %s",file);
327 mailmime_free( filePart ); 327 mailmime_free( filePart );
328 filePart = 0; 328 filePart = 0;
329 } 329 }
330 } 330 }
331 331
332 if (!filePart) { 332 if (!filePart) {
333 if ( param != NULL ) { 333 if ( param != NULL ) {
334 mailmime_parameter_free( param ); 334 mailmime_parameter_free( param );
335 } 335 }
336 if (content) { 336 if (content) {
337 mailmime_content_free( content ); 337 mailmime_content_free( content );
338 } 338 }
339 if (fields) { 339 if (fields) {
340 mailmime_fields_free( fields ); 340 mailmime_fields_free( fields );
341 } else { 341 } else {
342 if (name) { 342 if (name) {
343 free( name ); 343 free( name );
344 } 344 }
345 if (file) { 345 if (file) {
346 free( file ); 346 free( file );
347 } 347 }
348 } 348 }
349 } 349 }
350 return filePart; // Success :) 350 return filePart; // Success :)
351 351
352} 352}
353 353
354void SMTPwrapper::addFileParts( mailmime *message,const QList<Attachment>&files ) { 354void SMTPwrapper::addFileParts( mailmime *message,const QList<Attachment>&files ) {
355 const Attachment *it; 355 const Attachment *it;
356 unsigned int count = files.count(); 356 unsigned int count = files.count();
357 qDebug("List contains %i values",count); 357 qDebug("List contains %i values",count);
358 for ( unsigned int i = 0; i < count; ++i ) { 358 for ( unsigned int i = 0; i < count; ++i ) {
359 qDebug( "Adding file" ); 359 qDebug( "Adding file" );
360 mailmime *filePart; 360 mailmime *filePart;
361 int err; 361 int err;
362 it = ((QList<Attachment>)files).at(i); 362 it = ((QList<Attachment>)files).at(i);
363 363
364 filePart = buildFilePart( it->getFileName(), it->getMimeType(),"" ); 364 filePart = buildFilePart( it->getFileName(), it->getMimeType(),"" );
365 if ( filePart == NULL ) { 365 if ( filePart == NULL ) {
366 qDebug( "addFileParts: error adding file:" ); 366 qDebug( "addFileParts: error adding file:" );
367 qDebug( it->getFileName() ); 367 qDebug( it->getFileName() );
368 continue; 368 continue;
369 } 369 }
370 err = mailmime_smart_add_part( message, filePart ); 370 err = mailmime_smart_add_part( message, filePart );
371 if ( err != MAILIMF_NO_ERROR ) { 371 if ( err != MAILIMF_NO_ERROR ) {
372 mailmime_free( filePart ); 372 mailmime_free( filePart );
373 qDebug("error smart add"); 373 qDebug("error smart add");
374 } 374 }
375 } 375 }
376} 376}
377 377
378mailmime *SMTPwrapper::createMimeMail(const Mail &mail ) { 378mailmime *SMTPwrapper::createMimeMail(const Mail &mail ) {
379 mailmime *message, *txtPart; 379 mailmime *message, *txtPart;
380 mailimf_fields *fields; 380 mailimf_fields *fields;
381 int err; 381 int err;
382 382
383 fields = createImfFields( mail ); 383 fields = createImfFields( mail );
384 if ( fields == NULL ) 384 if ( fields == NULL )
385 goto err_free; 385 goto err_free;
386 386
387 message = mailmime_new_message_data( NULL ); 387 message = mailmime_new_message_data( NULL );
388 if ( message == NULL ) 388 if ( message == NULL )
389 goto err_free_fields; 389 goto err_free_fields;
390 390
391 mailmime_set_imf_fields( message, fields ); 391 mailmime_set_imf_fields( message, fields );
392 392
393 txtPart = buildTxtPart( mail.getMessage() ); 393 txtPart = buildTxtPart( mail.getMessage() );
394 394
395 if ( txtPart == NULL ) 395 if ( txtPart == NULL )
396 goto err_free_message; 396 goto err_free_message;
397 397
398 err = mailmime_smart_add_part( message, txtPart ); 398 err = mailmime_smart_add_part( message, txtPart );
399 if ( err != MAILIMF_NO_ERROR ) 399 if ( err != MAILIMF_NO_ERROR )
400 goto err_free_txtPart; 400 goto err_free_txtPart;
401 401
402 addFileParts( message, mail.getAttachments() ); 402 addFileParts( message, mail.getAttachments() );
403 403
404 return message; // Success :) 404 return message; // Success :)
405 405
406err_free_txtPart: 406err_free_txtPart:
407 mailmime_free( txtPart ); 407 mailmime_free( txtPart );
408err_free_message: 408err_free_message:
409 mailmime_free( message ); 409 mailmime_free( message );
410err_free_fields: 410err_free_fields:
411 mailimf_fields_free( fields ); 411 mailimf_fields_free( fields );
412err_free: 412err_free:
413 qDebug( "createMimeMail: error" ); 413 qDebug( "createMimeMail: error" );
414 414
415 return NULL; // Error :( 415 return NULL; // Error :(
416} 416}
417 417
418mailimf_field *SMTPwrapper::getField( mailimf_fields *fields, int type ) { 418mailimf_field *SMTPwrapper::getField( mailimf_fields *fields, int type ) {
419 mailimf_field *field; 419 mailimf_field *field;
420 clistiter *it; 420 clistiter *it;
421 421
422 it = clist_begin( fields->fld_list ); 422 it = clist_begin( fields->fld_list );
423 while ( it ) { 423 while ( it ) {
424 field = (mailimf_field *) it->data; 424 field = (mailimf_field *) it->data;
425 if ( field->fld_type == type ) { 425 if ( field->fld_type == type ) {
426 return field; 426 return field;
427 } 427 }
428 it = it->next; 428 it = it->next;
429 } 429 }
430 430
431 return NULL; 431 return NULL;
432} 432}
433 433
434void SMTPwrapper::addRcpts( clist *list, mailimf_address_list *addr_list ) { 434void SMTPwrapper::addRcpts( clist *list, mailimf_address_list *addr_list ) {
435 clistiter *it, *it2; 435 clistiter *it, *it2;
436 436
437 for ( it = clist_begin( addr_list->ad_list ); it; it = it->next ) { 437 for ( it = clist_begin( addr_list->ad_list ); it; it = it->next ) {
438 mailimf_address *addr; 438 mailimf_address *addr;
439 addr = (mailimf_address *) it->data; 439 addr = (mailimf_address *) it->data;
440 440
441 if ( addr->ad_type == MAILIMF_ADDRESS_MAILBOX ) { 441 if ( addr->ad_type == MAILIMF_ADDRESS_MAILBOX ) {
442 esmtp_address_list_add( list, addr->ad_data.ad_mailbox->mb_addr_spec, 0, NULL ); 442 esmtp_address_list_add( list, addr->ad_data.ad_mailbox->mb_addr_spec, 0, NULL );
443 } else if ( addr->ad_type == MAILIMF_ADDRESS_GROUP ) { 443 } else if ( addr->ad_type == MAILIMF_ADDRESS_GROUP ) {
444 clist *l = addr->ad_data.ad_group->grp_mb_list->mb_list; 444 clist *l = addr->ad_data.ad_group->grp_mb_list->mb_list;
445 for ( it2 = clist_begin( l ); it2; it2 = it2->next ) { 445 for ( it2 = clist_begin( l ); it2; it2 = it2->next ) {
446 mailimf_mailbox *mbox; 446 mailimf_mailbox *mbox;
447 mbox = (mailimf_mailbox *) it2->data; 447 mbox = (mailimf_mailbox *) it2->data;
448 esmtp_address_list_add( list, mbox->mb_addr_spec, 0, NULL ); 448 esmtp_address_list_add( list, mbox->mb_addr_spec, 0, NULL );
449 } 449 }
450 } 450 }
451 } 451 }
452} 452}
453 453
454clist *SMTPwrapper::createRcptList( mailimf_fields *fields ) { 454clist *SMTPwrapper::createRcptList( mailimf_fields *fields ) {
455 clist *rcptList; 455 clist *rcptList;
456 mailimf_field *field; 456 mailimf_field *field;
457 457
458 rcptList = esmtp_address_list_new(); 458 rcptList = esmtp_address_list_new();
459 459
460 field = getField( fields, MAILIMF_FIELD_TO ); 460 field = getField( fields, MAILIMF_FIELD_TO );
461 if ( field && (field->fld_type == MAILIMF_FIELD_TO) 461 if ( field && (field->fld_type == MAILIMF_FIELD_TO)
462 && field->fld_data.fld_to->to_addr_list ) { 462 && field->fld_data.fld_to->to_addr_list ) {
463 addRcpts( rcptList, field->fld_data.fld_to->to_addr_list ); 463 addRcpts( rcptList, field->fld_data.fld_to->to_addr_list );
464 } 464 }
465 465
466 field = getField( fields, MAILIMF_FIELD_CC ); 466 field = getField( fields, MAILIMF_FIELD_CC );
467 if ( field && (field->fld_type == MAILIMF_FIELD_CC) 467 if ( field && (field->fld_type == MAILIMF_FIELD_CC)
468 && field->fld_data.fld_cc->cc_addr_list ) { 468 && field->fld_data.fld_cc->cc_addr_list ) {
469 addRcpts( rcptList, field->fld_data.fld_cc->cc_addr_list ); 469 addRcpts( rcptList, field->fld_data.fld_cc->cc_addr_list );
470 } 470 }
471 471
472 field = getField( fields, MAILIMF_FIELD_BCC ); 472 field = getField( fields, MAILIMF_FIELD_BCC );
473 if ( field && (field->fld_type == MAILIMF_FIELD_BCC) 473 if ( field && (field->fld_type == MAILIMF_FIELD_BCC)
474 && field->fld_data.fld_bcc->bcc_addr_list ) { 474 && field->fld_data.fld_bcc->bcc_addr_list ) {
475 addRcpts( rcptList, field->fld_data.fld_bcc->bcc_addr_list ); 475 addRcpts( rcptList, field->fld_data.fld_bcc->bcc_addr_list );
476 } 476 }
477 477
478 return rcptList; 478 return rcptList;
479} 479}
480 480
481char *SMTPwrapper::getFrom( mailimf_field *ffrom) { 481char *SMTPwrapper::getFrom( mailimf_field *ffrom) {
482 char *from = NULL; 482 char *from = NULL;
483 if ( ffrom && (ffrom->fld_type == MAILIMF_FIELD_FROM) 483 if ( ffrom && (ffrom->fld_type == MAILIMF_FIELD_FROM)
484 && ffrom->fld_data.fld_from->frm_mb_list && ffrom->fld_data.fld_from->frm_mb_list->mb_list ) { 484 && ffrom->fld_data.fld_from->frm_mb_list && ffrom->fld_data.fld_from->frm_mb_list->mb_list ) {
485 clist *cl = ffrom->fld_data.fld_from->frm_mb_list->mb_list; 485 clist *cl = ffrom->fld_data.fld_from->frm_mb_list->mb_list;
486 clistiter *it; 486 clistiter *it;
487 for ( it = clist_begin( cl ); it; it = it->next ) { 487 for ( it = clist_begin( cl ); it; it = it->next ) {
488 mailimf_mailbox *mb = (mailimf_mailbox *) it->data; 488 mailimf_mailbox *mb = (mailimf_mailbox *) it->data;
489 from = strdup( mb->mb_addr_spec ); 489 from = strdup( mb->mb_addr_spec );
490 } 490 }
491 } 491 }
492 492
493 return from; 493 return from;
494} 494}
495 495
496char *SMTPwrapper::getFrom( mailmime *mail ) { 496char *SMTPwrapper::getFrom( mailmime *mail ) {
497 /* no need to delete - its just a pointer to structure content */ 497 /* no need to delete - its just a pointer to structure content */
498 mailimf_field *ffrom = 0; 498 mailimf_field *ffrom = 0;
499 ffrom = getField( mail->mm_data.mm_message.mm_fields, MAILIMF_FIELD_FROM ); 499 ffrom = getField( mail->mm_data.mm_message.mm_fields, MAILIMF_FIELD_FROM );
500 return getFrom(ffrom); 500 return getFrom(ffrom);
501} 501}
502 502
503void SMTPwrapper::progress( size_t current, size_t maximum ) { 503void SMTPwrapper::progress( size_t current, size_t maximum ) {
504 if (SMTPwrapper::sendProgress) { 504 if (SMTPwrapper::sendProgress) {
505 SMTPwrapper::sendProgress->setSingleMail(current, maximum ); 505 SMTPwrapper::sendProgress->setSingleMail(current, maximum );
506 qApp->processEvents(); 506 qApp->processEvents();
507 } 507 }
508} 508}
509 509
510void SMTPwrapper::storeMail(const char*mail, size_t length, const QString&box) { 510void SMTPwrapper::storeMail(const char*mail, size_t length, const QString&box) {
511 if (!mail) 511 if (!mail)
512 return; 512 return;
513 QString localfolders = AbstractMail::defaultLocalfolder(); 513 QString localfolders = AbstractMail::defaultLocalfolder();
514 AbstractMail*wrap = AbstractMail::getWrapper(localfolders); 514 AbstractMail*wrap = AbstractMail::getWrapper(localfolders);
515 wrap->createMbox(box); 515 wrap->createMbox(box);
516 wrap->storeMessage(mail,length,box); 516 wrap->storeMessage(mail,length,box);
517 delete wrap; 517 delete wrap;
518} 518}
519 519
520void SMTPwrapper::smtpSend( mailmime *mail,bool later) { 520void SMTPwrapper::smtpSend( mailmime *mail,bool later) {
521 clist *rcpts = 0; 521 clist *rcpts = 0;
522 char *from, *data; 522 char *from, *data;
523 size_t size; 523 size_t size;
524 524
525 from = data = 0; 525 from = data = 0;
526 526
527 mailmessage * msg = 0; 527 mailmessage * msg = 0;
528 msg = mime_message_init(mail); 528 msg = mime_message_init(mail);
529 mime_message_set_tmpdir(msg,getenv( "HOME" )); 529 mime_message_set_tmpdir(msg,getenv( "HOME" ));
530 int r = mailmessage_fetch(msg,&data,&size); 530 int r = mailmessage_fetch(msg,&data,&size);
531 mime_message_detach_mime(msg); 531 mime_message_detach_mime(msg);
532 mailmessage_free(msg); 532 mailmessage_free(msg);
533 if (r != MAIL_NO_ERROR || !data) { 533 if (r != MAIL_NO_ERROR || !data) {
534 if (data) 534 if (data)
535 free(data); 535 free(data);
536 qDebug("Error fetching mime..."); 536 qDebug("Error fetching mime...");
537 return; 537 return;
538 } 538 }
539 msg = 0; 539 msg = 0;
540 if (later) { 540 if (later) {
541 storeMail(data,size,"Outgoing"); 541 storeMail(data,size,"Outgoing");
542 if (data) 542 if (data)
543 free( data ); 543 free( data );
544 Config cfg( "mail" ); 544 Config cfg( "mail" );
545 cfg.setGroup( "Status" ); 545 cfg.setGroup( "Status" );
546 cfg.writeEntry( "outgoing", ++m_queuedMail ); 546 cfg.writeEntry( "outgoing", ++m_queuedMail );
547 emit queuedMails( m_queuedMail ); 547 emit queuedMails( m_queuedMail );
548 return; 548 return;
549 } 549 }
550 from = getFrom( mail ); 550 from = getFrom( mail );
551 rcpts = createRcptList( mail->mm_data.mm_message.mm_fields ); 551 rcpts = createRcptList( mail->mm_data.mm_message.mm_fields );
552 smtpSend(from,rcpts,data,size); 552 smtpSend(from,rcpts,data,size);
553 if (data) { 553 if (data) {
554 free(data); 554 free(data);
555 } 555 }
556 if (from) { 556 if (from) {
557 free(from); 557 free(from);
558 } 558 }
559 if (rcpts) 559 if (rcpts)
560 smtp_address_list_free( rcpts ); 560 smtp_address_list_free( rcpts );
561} 561}
562 562
563void SMTPwrapper::storeFailedMail(const char*data,unsigned int size, const char*failuremessage) 563void SMTPwrapper::storeFailedMail(const char*data,unsigned int size, const char*failuremessage)
564{ 564{
565 if (data) { 565 if (data) {
566 storeMail(data,size,"Sendfailed"); 566 storeMail(data,size,"Sendfailed");
567 } 567 }
568 if (failuremessage) { 568 if (failuremessage) {
569 QMessageBox::critical(0,tr("Error sending mail"), 569 QMessageBox::critical(0,tr("Error sending mail"),
570 tr("<center>%1</center>").arg(failuremessage)); 570 tr("<center>%1</center>").arg(failuremessage));
571 } 571 }
572} 572}
573 573
574int SMTPwrapper::start_smtp_tls() 574int SMTPwrapper::start_smtp_tls()
575{ 575{
576 if (!m_smtp) { 576 if (!m_smtp) {
577 return MAILSMTP_ERROR_IN_PROCESSING; 577 return MAILSMTP_ERROR_IN_PROCESSING;
578 } 578 }
579 int err = mailesmtp_starttls(m_smtp); 579 int err = mailesmtp_starttls(m_smtp);
580 if (err != MAILSMTP_NO_ERROR) return err; 580 if (err != MAILSMTP_NO_ERROR) return err;
581 mailstream_low * low; 581 mailstream_low * low;
582 mailstream_low * new_low; 582 mailstream_low * new_low;
583 low = mailstream_get_low(m_smtp->stream); 583 low = mailstream_get_low(m_smtp->stream);
584 if (!low) { 584 if (!low) {
585 return MAILSMTP_ERROR_IN_PROCESSING; 585 return MAILSMTP_ERROR_IN_PROCESSING;
586 } 586 }
587 int fd = mailstream_low_get_fd(low); 587 int fd = mailstream_low_get_fd(low);
588 if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) { 588 if (fd > -1 && (new_low = mailstream_low_ssl_open(fd))!=0) {
589 mailstream_low_free(low); 589 mailstream_low_free(low);
590 mailstream_set_low(m_smtp->stream, new_low); 590 mailstream_set_low(m_smtp->stream, new_low);
591 } else { 591 } else {
592 return MAILSMTP_ERROR_IN_PROCESSING; 592 return MAILSMTP_ERROR_IN_PROCESSING;
593 } 593 }
594 return err; 594 return err;
595} 595}
596 596
597void SMTPwrapper::connect_server() 597void SMTPwrapper::connect_server()
598{ 598{
599 const char *server, *user, *pass; 599 const char *server, *user, *pass;
600 bool ssl; 600 bool ssl;
601 uint16_t port; 601 uint16_t port;
602 ssl = false; 602 ssl = false;
603 bool try_tls = true; 603 bool try_tls = true;
604 bool force_tls=false; 604 bool force_tls=false;
605 server = user = pass = 0; 605 server = user = pass = 0;
606 QString failuretext = ""; 606 QString failuretext = "";
607 607
608 if (m_smtp || !m_SmtpAccount) { 608 if (m_smtp || !m_SmtpAccount) {
609 return; 609 return;
610 } 610 }
611 server = m_SmtpAccount->getServer().latin1(); 611 server = m_SmtpAccount->getServer().latin1();
612 if ( m_SmtpAccount->ConnectionType() == 2 ) { 612 if ( m_SmtpAccount->ConnectionType() == 2 ) {
613 ssl = true; 613 ssl = true;
614 try_tls = false; 614 try_tls = false;
615 } else if (m_SmtpAccount->ConnectionType() == 1) { 615 } else if (m_SmtpAccount->ConnectionType() == 1) {
616 force_tls = true; 616 force_tls = true;
617 } 617 }
618 int result = 1; 618 int result = 1;
619 port = m_SmtpAccount->getPort().toUInt(); 619 port = m_SmtpAccount->getPort().toUInt();
620 620
621 m_smtp = mailsmtp_new( 20, &progress ); 621 m_smtp = mailsmtp_new( 20, &progress );
622 if ( m_smtp == NULL ) { 622 if ( m_smtp == NULL ) {
623 /* no failure message cause this happens when problems with memory - than we 623 /* no failure message cause this happens when problems with memory - than we
624 we can not display any messagebox */ 624 we can not display any messagebox */
625 return; 625 return;
626 } 626 }
627 627
628 int err = MAILSMTP_NO_ERROR; 628 int err = MAILSMTP_NO_ERROR;
629 qDebug( "Servername %s at port %i", server, port ); 629 qDebug( "Servername %s at port %i", server, port );
630 if ( ssl ) { 630 if ( ssl ) {
631 qDebug( "SSL session" ); 631 qDebug( "SSL session" );
632 err = mailsmtp_ssl_connect( m_smtp, server, port ); 632 err = mailsmtp_ssl_connect( m_smtp, server, port );
633 } else { 633 } else {
634 qDebug( "No SSL session" ); 634 qDebug( "No SSL session" );
635 err = mailsmtp_socket_connect( m_smtp, server, port ); 635 err = mailsmtp_socket_connect( m_smtp, server, port );
636 } 636 }
637 if ( err != MAILSMTP_NO_ERROR ) { 637 if ( err != MAILSMTP_NO_ERROR ) {
638 qDebug("Error init connection"); 638 qDebug("Error init connection");
639 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err)); 639 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err));
640 result = 0; 640 result = 0;
641 } 641 }
642 642
643 /* switch to tls after init 'cause there it will send the ehlo */ 643 /* switch to tls after init 'cause there it will send the ehlo */
644 if (result) { 644 if (result) {
645 err = mailsmtp_init( m_smtp ); 645 err = mailsmtp_init( m_smtp );
646 if (err != MAILSMTP_NO_ERROR) { 646 if (err != MAILSMTP_NO_ERROR) {
647 result = 0; 647 result = 0;
648 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err)); 648 failuretext = tr("Error init SMTP connection: %1").arg(mailsmtpError(err));
649 } 649 }
650 } 650 }
651 651
652 if (try_tls) { 652 if (try_tls) {
653 err = start_smtp_tls(); 653 err = start_smtp_tls();
654 if (err != MAILSMTP_NO_ERROR) { 654 if (err != MAILSMTP_NO_ERROR) {
655 try_tls = false; 655 try_tls = false;
656 } else { 656 } else {
657 err = mailesmtp_ehlo(m_smtp); 657 err = mailesmtp_ehlo(m_smtp);
658 } 658 }
659 } 659 }
660 660
661 if (!try_tls && force_tls) { 661 if (!try_tls && force_tls) {
662 result = 0; 662 result = 0;
663 failuretext = tr("Error init SMTP tls: %1").arg(mailsmtpError(err)); 663 failuretext = tr("Error init SMTP tls: %1").arg(mailsmtpError(err));
664 } 664 }
665 665
666 if (result==1 && m_SmtpAccount->getLogin() ) { 666 if (result==1 && m_SmtpAccount->getLogin() ) {
667 qDebug("smtp with auth"); 667 qDebug("smtp with auth");
668 if ( m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty() ) { 668 if ( m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty() ) {
669 // get'em 669 // get'em
670 LoginDialog login( m_SmtpAccount->getUser(), 670 LoginDialog login( m_SmtpAccount->getUser(),
671 m_SmtpAccount->getPassword(), NULL, 0, true ); 671 m_SmtpAccount->getPassword(), NULL, 0, true );
672 login.show(); 672 login.show();
673 if ( QDialog::Accepted == login.exec() ) { 673 if ( QDialog::Accepted == login.exec() ) {
674 // ok 674 // ok
675 user = login.getUser().latin1(); 675 user = login.getUser().latin1();
676 pass = login.getPassword().latin1(); 676 pass = login.getPassword().latin1();
677 } else { 677 } else {
678 result = 0; 678 result = 0;
679 failuretext=tr("Login aborted - storing mail to localfolder"); 679 failuretext=tr("Login aborted - storing mail to localfolder");
680 } 680 }
681 } else { 681 } else {
682 user = m_SmtpAccount->getUser().latin1(); 682 user = m_SmtpAccount->getUser().latin1();
683 pass = m_SmtpAccount->getPassword().latin1(); 683 pass = m_SmtpAccount->getPassword().latin1();
684 } 684 }
685 qDebug( "session->auth: %i", m_smtp->auth); 685 qDebug( "session->auth: %i", m_smtp->auth);
686 if (result) { 686 if (result) {
687 err = mailsmtp_auth( m_smtp, (char*)user, (char*)pass ); 687 err = mailsmtp_auth( m_smtp, (char*)user, (char*)pass );
688 if ( err == MAILSMTP_NO_ERROR ) { 688 if ( err == MAILSMTP_NO_ERROR ) {
689 qDebug("auth ok"); 689 qDebug("auth ok");
690 } else { 690 } else {
691 failuretext = tr("Authentification failed"); 691 failuretext = tr("Authentification failed");
692 result = 0; 692 result = 0;
693 } 693 }
694 } 694 }
695 } 695 }
696} 696}
697 697
698void SMTPwrapper::disc_server() 698void SMTPwrapper::disc_server()
699{ 699{
700 if (m_smtp) { 700 if (m_smtp) {
701 mailsmtp_quit( m_smtp ); 701 mailsmtp_quit( m_smtp );
702 mailsmtp_free( m_smtp ); 702 mailsmtp_free( m_smtp );
703 m_smtp = 0; 703 m_smtp = 0;
704 } 704 }
705} 705}
706 706
707int SMTPwrapper::smtpSend(char*from,clist*rcpts,const char*data,size_t size ) 707int SMTPwrapper::smtpSend(char*from,clist*rcpts,const char*data,size_t size )
708{ 708{
709 int err,result; 709 int err,result;
710 QString failuretext = ""; 710 QString failuretext = "";
711 711
712 connect_server(); 712 connect_server();
713 713
714 result = 1; 714 result = 1;
715 if (m_smtp) { 715 if (m_smtp) {
716 err = mailsmtp_send( m_smtp, from, rcpts, data, size ); 716 err = mailsmtp_send( m_smtp, from, rcpts, data, size );
717 if ( err != MAILSMTP_NO_ERROR ) { 717 if ( err != MAILSMTP_NO_ERROR ) {
718 failuretext=tr("Error sending mail: %1").arg(mailsmtpError(err)); 718 failuretext=tr("Error sending mail: %1").arg(mailsmtpError(err));
719 result = 0; 719 result = 0;
720 } 720 }
721 } else { 721 } else {
722 result = 0; 722 result = 0;
723 } 723 }
724 724
725 if (!result) { 725 if (!result) {
726 storeFailedMail(data,size,failuretext); 726 storeFailedMail(data,size,failuretext);
727 } else { 727 } else {
728 qDebug( "Mail sent." ); 728 qDebug( "Mail sent." );
729 storeMail(data,size,"Sent"); 729 storeMail(data,size,"Sent");
730 } 730 }
731 return result; 731 return result;
732} 732}
733 733
734void SMTPwrapper::sendMail(const Mail&mail,bool later ) 734void SMTPwrapper::sendMail(const Mail&mail,bool later )
735{ 735{
736 mailmime * mimeMail; 736 mailmime * mimeMail;
737 737
738 mimeMail = createMimeMail(mail ); 738 mimeMail = createMimeMail(mail );
739 if ( mimeMail == NULL ) { 739 if ( mimeMail == NULL ) {
740 qDebug( "sendMail: error creating mime mail" ); 740 qDebug( "sendMail: error creating mime mail" );
741 } else { 741 } else {
742 sendProgress = new progressMailSend(); 742 sendProgress = new progressMailSend();
743 sendProgress->show(); 743 sendProgress->show();
744 sendProgress->setMaxMails(1); 744 sendProgress->setMaxMails(1);
745 smtpSend( mimeMail,later); 745 smtpSend( mimeMail,later);
746 qDebug("Clean up done"); 746 qDebug("Clean up done");
747 sendProgress->hide(); 747 sendProgress->hide();
748 delete sendProgress; 748 delete sendProgress;
749 sendProgress = 0; 749 sendProgress = 0;
750 mailmime_free( mimeMail ); 750 mailmime_free( mimeMail );
751 } 751 }
752} 752}
753 753
754int SMTPwrapper::sendQueuedMail(AbstractMail*wrap,RecMail*which) { 754int SMTPwrapper::sendQueuedMail(AbstractMail*wrap,RecMail*which) {
755 size_t curTok = 0; 755 size_t curTok = 0;
756 mailimf_fields *fields = 0; 756 mailimf_fields *fields = 0;
757 mailimf_field*ffrom = 0; 757 mailimf_field*ffrom = 0;
758 clist *rcpts = 0; 758 clist *rcpts = 0;
759 char*from = 0; 759 char*from = 0;
760 int res = 0; 760 int res = 0;
761 761
762 encodedString * data = wrap->fetchRawBody(*which); 762 encodedString * data = wrap->fetchRawBody(*which);
763 if (!data) 763 if (!data)
764 return 0; 764 return 0;
765 int err = mailimf_fields_parse( data->Content(), data->Length(), &curTok, &fields ); 765 int err = mailimf_fields_parse( data->Content(), data->Length(), &curTok, &fields );
766 if (err != MAILIMF_NO_ERROR) { 766 if (err != MAILIMF_NO_ERROR) {
767 delete data; 767 delete data;
768 delete wrap; 768 delete wrap;
769 return 0; 769 return 0;
770 } 770 }
771 771
772 rcpts = createRcptList( fields ); 772 rcpts = createRcptList( fields );
773 ffrom = getField(fields, MAILIMF_FIELD_FROM ); 773 ffrom = getField(fields, MAILIMF_FIELD_FROM );
774 from = getFrom(ffrom); 774 from = getFrom(ffrom);
775 775
776 if (rcpts && from) { 776 if (rcpts && from) {
777 res = smtpSend(from,rcpts,data->Content(),data->Length()); 777 res = smtpSend(from,rcpts,data->Content(),data->Length());
778 } 778 }
779 if (fields) { 779 if (fields) {
780 mailimf_fields_free(fields); 780 mailimf_fields_free(fields);
781 fields = 0; 781 fields = 0;
782 } 782 }
783 if (data) { 783 if (data) {
784 delete data; 784 delete data;
785 } 785 }
786 if (from) { 786 if (from) {
787 free(from); 787 free(from);
788 } 788 }
789 if (rcpts) { 789 if (rcpts) {
790 smtp_address_list_free( rcpts ); 790 smtp_address_list_free( rcpts );
791 } 791 }
792 return res; 792 return res;
793} 793}
794 794
795/* this is a special fun */ 795/* this is a special fun */
796bool SMTPwrapper::flushOutbox() { 796bool SMTPwrapper::flushOutbox() {
797 bool returnValue = true; 797 bool returnValue = true;
798 798
799 qDebug("Sending the queue"); 799 qDebug("Sending the queue");
800 if (!m_SmtpAccount) { 800 if (!m_SmtpAccount) {
801 qDebug("No smtp account given"); 801 qDebug("No smtp account given");
802 return false; 802 return false;
803 } 803 }
804 804
805 bool reset_user_value = false; 805 bool reset_user_value = false;
806 QString localfolders = AbstractMail::defaultLocalfolder(); 806 QString localfolders = AbstractMail::defaultLocalfolder();
807 AbstractMail*wrap = AbstractMail::getWrapper(localfolders); 807 AbstractMail*wrap = AbstractMail::getWrapper(localfolders);
808 if (!wrap) { 808 if (!wrap) {
809 qDebug("memory error"); 809 qDebug("memory error");
810 return false; 810 return false;
811 } 811 }
812 QString oldPw, oldUser; 812 QString oldPw, oldUser;
813 QList<RecMail> mailsToSend; 813 QList<RecMail> mailsToSend;
814 QList<RecMail> mailsToRemove; 814 QList<RecMail> mailsToRemove;
815 QString mbox("Outgoing"); 815 QString mbox("Outgoing");
816 wrap->listMessages(mbox,mailsToSend); 816 wrap->listMessages(mbox,mailsToSend);
817 if (mailsToSend.count()==0) { 817 if (mailsToSend.count()==0) {
818 delete wrap; 818 delete wrap;
819 qDebug("No mails to send"); 819 qDebug("No mails to send");
820 return false; 820 return false;
821 } 821 }
822 822
823 oldPw = m_SmtpAccount->getPassword(); 823 oldPw = m_SmtpAccount->getPassword();
824 oldUser = m_SmtpAccount->getUser(); 824 oldUser = m_SmtpAccount->getUser();
825 if (m_SmtpAccount->getLogin() && (m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty()) ) { 825 if (m_SmtpAccount->getLogin() && (m_SmtpAccount->getUser().isEmpty() || m_SmtpAccount->getPassword().isEmpty()) ) {
826 // get'em 826 // get'em
827 QString user,pass; 827 QString user,pass;
828 LoginDialog login( m_SmtpAccount->getUser(), m_SmtpAccount->getPassword(), NULL, 0, true ); 828 LoginDialog login( m_SmtpAccount->getUser(), m_SmtpAccount->getPassword(), NULL, 0, true );
829 login.show(); 829 login.show();
830 if ( QDialog::Accepted == login.exec() ) { 830 if ( QDialog::Accepted == login.exec() ) {
831 // ok 831 // ok
832 user = login.getUser().latin1(); 832 user = login.getUser().latin1();
833 pass = login.getPassword().latin1(); 833 pass = login.getPassword().latin1();
834 reset_user_value = true; 834 reset_user_value = true;
835 m_SmtpAccount->setUser(user); 835 m_SmtpAccount->setUser(user);
836 m_SmtpAccount->setPassword(pass); 836 m_SmtpAccount->setPassword(pass);
837 } else { 837 } else {
838 return true; 838 return true;
839 } 839 }
840 } 840 }
841 841
842 842
843 mailsToSend.setAutoDelete(false); 843 mailsToSend.setAutoDelete(false);
844 sendProgress = new progressMailSend(); 844 sendProgress = new progressMailSend();
845 sendProgress->show(); 845 sendProgress->show();
846 sendProgress->setMaxMails(mailsToSend.count()); 846 sendProgress->setMaxMails(mailsToSend.count());
847 847
848 while (mailsToSend.count()>0) { 848 while (mailsToSend.count()>0) {
849 if (sendQueuedMail(wrap,mailsToSend.at(0))==0) { 849 if (sendQueuedMail(wrap,mailsToSend.at(0))==0) {
850 QMessageBox::critical(0,tr("Error sending mail"), 850 QMessageBox::critical(0,tr("Error sending mail"),
851 tr("Error sending queued mail - breaking")); 851 tr("Error sending queued mail - breaking"));
852 returnValue = false; 852 returnValue = false;
853 break; 853 break;
854 } 854 }
855 mailsToRemove.append(mailsToSend.at(0)); 855 mailsToRemove.append(mailsToSend.at(0));
856 mailsToSend.removeFirst(); 856 mailsToSend.removeFirst();
857 sendProgress->setCurrentMails(mailsToRemove.count()); 857 sendProgress->setCurrentMails(mailsToRemove.count());
858 } 858 }
859 if (reset_user_value) { 859 if (reset_user_value) {
860 m_SmtpAccount->setUser(oldUser); 860 m_SmtpAccount->setUser(oldUser);
861 m_SmtpAccount->setPassword(oldPw); 861 m_SmtpAccount->setPassword(oldPw);
862 } 862 }
863 Config cfg( "mail" ); 863 Config cfg( "mail" );
864 cfg.setGroup( "Status" ); 864 cfg.setGroup( "Status" );
865 m_queuedMail = 0; 865 m_queuedMail = 0;
866 cfg.writeEntry( "outgoing", m_queuedMail ); 866 cfg.writeEntry( "outgoing", m_queuedMail );
867 emit queuedMails( m_queuedMail ); 867 emit queuedMails( m_queuedMail );
868 sendProgress->hide(); 868 sendProgress->hide();
869 delete sendProgress; 869 delete sendProgress;
870 sendProgress = 0; 870 sendProgress = 0;
871 wrap->deleteMails(mbox,mailsToRemove); 871 wrap->deleteMails(mbox,mailsToRemove);
872 mailsToSend.setAutoDelete(true); 872 mailsToSend.setAutoDelete(true);
873 delete wrap; 873 delete wrap;
874 return returnValue; 874 return returnValue;
875} 875}
diff --git a/noncore/net/mail/mainwindow.cpp b/noncore/net/mail/mainwindow.cpp
index 2a1f90d..3f34fe7 100644
--- a/noncore/net/mail/mainwindow.cpp
+++ b/noncore/net/mail/mainwindow.cpp
@@ -1,217 +1,217 @@
1#include <qlabel.h> 1#include <qlabel.h>
2#include <qvbox.h> 2#include <qvbox.h>
3#include <qheader.h> 3#include <qheader.h>
4#include <qtimer.h> 4#include <qtimer.h>
5#include <qlayout.h> 5#include <qlayout.h>
6#include <qmessagebox.h> 6#include <qmessagebox.h>
7 7
8#include <qpe/qpeapplication.h> 8#include <qpe/qpeapplication.h>
9#include <qpe/resource.h> 9#include <qpe/resource.h>
10 10
11#include "defines.h" 11#include "defines.h"
12#include "mainwindow.h" 12#include "mainwindow.h"
13 13
14 14
15MainWindow::MainWindow( QWidget *parent, const char *name, WFlags flags ) 15MainWindow::MainWindow( QWidget *parent, const char *name, WFlags flags )
16 : QMainWindow( parent, name, flags ) 16 : QMainWindow( parent, name, flags )
17{ 17{
18 18
19 setCaption( tr( "Mail" ) ); 19 setCaption( tr( "Mail" ) );
20 setToolBarsMovable( false ); 20 setToolBarsMovable( false );
21 21
22 toolBar = new QToolBar( this ); 22 toolBar = new QToolBar( this );
23 menuBar = new QMenuBar( toolBar ); 23 menuBar = new QMenuBar( toolBar );
24 mailMenu = new QPopupMenu( menuBar ); 24 mailMenu = new QPopupMenu( menuBar );
25 menuBar->insertItem( tr( "Mail" ), mailMenu ); 25 menuBar->insertItem( tr( "Mail" ), mailMenu );
26 settingsMenu = new QPopupMenu( menuBar ); 26 settingsMenu = new QPopupMenu( menuBar );
27 menuBar->insertItem( tr( "Settings" ), settingsMenu ); 27 menuBar->insertItem( tr( "Settings" ), settingsMenu );
28 28
29 addToolBar( toolBar ); 29 addToolBar( toolBar );
30 toolBar->setHorizontalStretchable( true ); 30 toolBar->setHorizontalStretchable( true );
31 31
32 QLabel *spacer = new QLabel( toolBar ); 32 QLabel *spacer = new QLabel( toolBar );
33 spacer->setBackgroundMode( QWidget::PaletteButton ); 33 spacer->setBackgroundMode( QWidget::PaletteButton );
34 toolBar->setStretchableWidget( spacer ); 34 toolBar->setStretchableWidget( spacer );
35 35
36 composeMail = new QAction( tr( "Compose new mail" ), ICON_COMPOSEMAIL, 36 composeMail = new QAction( tr( "Compose new mail" ), ICON_COMPOSEMAIL,
37 0, 0, this ); 37 0, 0, this );
38 composeMail->addTo( toolBar ); 38 composeMail->addTo( toolBar );
39 composeMail->addTo( mailMenu ); 39 composeMail->addTo( mailMenu );
40 40
41 sendQueued = new QAction( tr( "Send queued mails" ), ICON_SENDQUEUED, 41 sendQueued = new QAction( tr( "Send queued mails" ), ICON_SENDQUEUED,
42 0, 0, this ); 42 0, 0, this );
43 sendQueued->addTo( toolBar ); 43 sendQueued->addTo( toolBar );
44 sendQueued->addTo( mailMenu ); 44 sendQueued->addTo( mailMenu );
45 45
46 /* 46 /*
47 syncFolders = new QAction( tr( "Sync mailfolders" ), ICON_SYNC, 47 syncFolders = new QAction( tr( "Sync mailfolders" ), ICON_SYNC,
48 0, 0, this ); 48 0, 0, this );
49 syncFolders->addTo( toolBar ); 49 syncFolders->addTo( toolBar );
50 syncFolders->addTo( mailMenu ); 50 syncFolders->addTo( mailMenu );
51 */ 51 */
52 52
53 showFolders = new QAction( tr( "Show/Hide folders" ), ICON_SHOWFOLDERS, 53 showFolders = new QAction( tr( "Show/Hide folders" ), ICON_SHOWFOLDERS,
54 0, 0, this, 0, true ); 54 0, 0, this, 0, true );
55 showFolders->addTo( toolBar ); 55 showFolders->addTo( toolBar );
56 showFolders->addTo( mailMenu ); 56 showFolders->addTo( mailMenu );
57 showFolders->setOn( true ); 57 showFolders->setOn( true );
58 connect(showFolders, SIGNAL( toggled( bool ) ), 58 connect(showFolders, SIGNAL( toggled(bool) ),
59 SLOT( slotShowFolders( bool ) ) ); 59 SLOT( slotShowFolders(bool) ) );
60 60
61 /* 61 /*
62 searchMails = new QAction( tr( "Search mails" ), QIconSet( Resource::loadPixmap("find") ), 62 searchMails = new QAction( tr( "Search mails" ), QIconSet( Resource::loadPixmap("find") ),
63 0, 0, this ); 63 0, 0, this );
64 searchMails->addTo( toolBar ); 64 searchMails->addTo( toolBar );
65 searchMails->addTo( mailMenu ); 65 searchMails->addTo( mailMenu );
66 */ 66 */
67 67
68 deleteMails = new QAction(tr("Delete Mail"), QIconSet( Resource::loadPixmap("trash")), 0, 0, this); 68 deleteMails = new QAction(tr("Delete Mail"), QIconSet( Resource::loadPixmap("trash")), 0, 0, this);
69 deleteMails->addTo( toolBar ); 69 deleteMails->addTo( toolBar );
70 deleteMails->addTo( mailMenu ); 70 deleteMails->addTo( mailMenu );
71 connect( deleteMails, SIGNAL( activated() ), 71 connect( deleteMails, SIGNAL( activated() ),
72 SLOT( slotDeleteMail() ) ); 72 SLOT( slotDeleteMail() ) );
73 73
74 editSettings = new QAction( tr( "Edit settings" ), QIconSet( Resource::loadPixmap("SettingsIcon") ) , 74 editSettings = new QAction( tr( "Edit settings" ), QIconSet( Resource::loadPixmap("SettingsIcon") ) ,
75 0, 0, this ); 75 0, 0, this );
76 editSettings->addTo( settingsMenu ); 76 editSettings->addTo( settingsMenu );
77 connect( editSettings, SIGNAL( activated() ), 77 connect( editSettings, SIGNAL( activated() ),
78 SLOT( slotEditSettings() ) ); 78 SLOT( slotEditSettings() ) );
79 editAccounts = new QAction( tr( "Configure accounts" ), QIconSet( Resource::loadPixmap("mail/editaccounts") ) , 79 editAccounts = new QAction( tr( "Configure accounts" ), QIconSet( Resource::loadPixmap("mail/editaccounts") ) ,
80 0, 0, this ); 80 0, 0, this );
81 editAccounts->addTo( settingsMenu ); 81 editAccounts->addTo( settingsMenu );
82 82
83 //setCentralWidget( view ); 83 //setCentralWidget( view );
84 84
85 QVBox* wrapperBox = new QVBox( this ); 85 QVBox* wrapperBox = new QVBox( this );
86 setCentralWidget( wrapperBox ); 86 setCentralWidget( wrapperBox );
87 87
88 QWidget *view = new QWidget( wrapperBox ); 88 QWidget *view = new QWidget( wrapperBox );
89 89
90 layout = new QBoxLayout ( view, QBoxLayout::LeftToRight ); 90 layout = new QBoxLayout ( view, QBoxLayout::LeftToRight );
91 91
92 folderView = new AccountView( view ); 92 folderView = new AccountView( view );
93 folderView->header()->hide(); 93 folderView->header()->hide();
94 folderView->setRootIsDecorated( true ); 94 folderView->setRootIsDecorated( true );
95 folderView->addColumn( tr( "Mailbox" ) ); 95 folderView->addColumn( tr( "Mailbox" ) );
96 96
97 layout->addWidget( folderView ); 97 layout->addWidget( folderView );
98 98
99 mailView = new QListView( view ); 99 mailView = new QListView( view );
100 mailView->addColumn( tr( "" ) ); 100 mailView->addColumn( tr( "" ) );
101 mailView->addColumn( tr( "Subject" ),QListView::Manual ); 101 mailView->addColumn( tr( "Subject" ),QListView::Manual );
102 mailView->addColumn( tr( "Sender" ),QListView::Manual ); 102 mailView->addColumn( tr( "Sender" ),QListView::Manual );
103 mailView->addColumn( tr( "Size" ),QListView::Manual); 103 mailView->addColumn( tr( "Size" ),QListView::Manual);
104 mailView->addColumn( tr( "Date" )); 104 mailView->addColumn( tr( "Date" ));
105 mailView->setAllColumnsShowFocus(true); 105 mailView->setAllColumnsShowFocus(true);
106 mailView->setSorting(-1); 106 mailView->setSorting(-1);
107 107
108 statusWidget = new StatusWidget( wrapperBox ); 108 statusWidget = new StatusWidget( wrapperBox );
109 statusWidget->hide(); 109 statusWidget->hide();
110 110
111 layout->addWidget( mailView ); 111 layout->addWidget( mailView );
112 layout->setStretchFactor( folderView, 1 ); 112 layout->setStretchFactor( folderView, 1 );
113 layout->setStretchFactor( mailView, 2 ); 113 layout->setStretchFactor( mailView, 2 );
114 114
115 slotAdjustLayout(); 115 slotAdjustLayout();
116 116
117 QPEApplication::setStylusOperation( mailView->viewport(),QPEApplication::RightOnHold); 117 QPEApplication::setStylusOperation( mailView->viewport(),QPEApplication::RightOnHold);
118 QPEApplication::setStylusOperation( folderView->viewport(),QPEApplication::RightOnHold); 118 QPEApplication::setStylusOperation( folderView->viewport(),QPEApplication::RightOnHold);
119 119
120 connect( mailView, SIGNAL( mouseButtonClicked(int, QListViewItem *,const QPoint&,int ) ),this, 120 connect( mailView, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),this,
121 SLOT( mailLeftClicked( int, QListViewItem *,const QPoint&,int ) ) ); 121 SLOT( mailLeftClicked(int,QListViewItem*,const QPoint&,int) ) );
122 connect( mailView, SIGNAL( mouseButtonPressed(int, QListViewItem *,const QPoint&,int ) ),this, 122 connect( mailView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ),this,
123 SLOT( mailHold( int, QListViewItem *,const QPoint&,int ) ) ); 123 SLOT( mailHold(int,QListViewItem*,const QPoint&,int) ) );
124 connect(folderView, SIGNAL(refreshMailview(QList<RecMail>*)),this,SLOT(refreshMailView(QList<RecMail>*))); 124 connect(folderView, SIGNAL(refreshMailview(QList<RecMail>*)),this,SLOT(refreshMailView(QList<RecMail>*)));
125 connect( composeMail, SIGNAL( activated() ), SLOT( slotComposeMail() ) ); 125 connect( composeMail, SIGNAL( activated() ), SLOT( slotComposeMail() ) );
126 connect( sendQueued, SIGNAL( activated() ), SLOT( slotSendQueued() ) ); 126 connect( sendQueued, SIGNAL( activated() ), SLOT( slotSendQueued() ) );
127// connect( searchMails, SIGNAL( activated() ), SLOT( slotSearchMails() ) ); 127// connect( searchMails, SIGNAL( activated() ), SLOT( slotSearchMails() ) );
128 connect( editAccounts, SIGNAL( activated() ), SLOT( slotEditAccounts() ) ); 128 connect( editAccounts, SIGNAL( activated() ), SLOT( slotEditAccounts() ) );
129 // Added by Stefan Eilers to allow starting by addressbook.. 129 // Added by Stefan Eilers to allow starting by addressbook..
130 // copied from old mail2 130 // copied from old mail2
131#if !defined(QT_NO_COP) 131#if !defined(QT_NO_COP)
132 connect( qApp, SIGNAL( appMessage( const QCString&, const QByteArray& ) ), 132 connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ),
133 this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); 133 this, SLOT( appMessage(const QCString&,const QByteArray&) ) );
134#endif 134#endif
135 135
136 QTimer::singleShot( 1000, this, SLOT( slotAdjustColumns() ) ); 136 QTimer::singleShot( 1000, this, SLOT( slotAdjustColumns() ) );
137} 137}
138 138
139MainWindow::~MainWindow() 139MainWindow::~MainWindow()
140{ 140{
141} 141}
142 142
143void MainWindow::appMessage(const QCString &, const QByteArray &) 143void MainWindow::appMessage(const QCString &, const QByteArray &)
144{ 144{
145 qDebug("appMessage not reached"); 145 qDebug("appMessage not reached");
146} 146}
147 147
148void MainWindow::slotAdjustLayout() { 148void MainWindow::slotAdjustLayout() {
149 149
150 QWidget *d = QApplication::desktop(); 150 QWidget *d = QApplication::desktop();
151 151
152 if ( d->width() < d->height() ) { 152 if ( d->width() < d->height() ) {
153 layout->setDirection( QBoxLayout::TopToBottom ); 153 layout->setDirection( QBoxLayout::TopToBottom );
154 } else { 154 } else {
155 layout->setDirection( QBoxLayout::LeftToRight ); 155 layout->setDirection( QBoxLayout::LeftToRight );
156 } 156 }
157} 157}
158 158
159void MainWindow::slotAdjustColumns() 159void MainWindow::slotAdjustColumns()
160{ 160{
161 bool hidden = folderView->isHidden(); 161 bool hidden = folderView->isHidden();
162 if ( hidden ) folderView->show(); 162 if ( hidden ) folderView->show();
163 folderView->setColumnWidth( 0, folderView->visibleWidth() ); 163 folderView->setColumnWidth( 0, folderView->visibleWidth() );
164 if ( hidden ) folderView->hide(); 164 if ( hidden ) folderView->hide();
165 165
166 mailView->setColumnWidth( 0, 10 ); 166 mailView->setColumnWidth( 0, 10 );
167 mailView->setColumnWidth( 1, mailView->visibleWidth() - 130 ); 167 mailView->setColumnWidth( 1, mailView->visibleWidth() - 130 );
168 mailView->setColumnWidth( 2, 80 ); 168 mailView->setColumnWidth( 2, 80 );
169 mailView->setColumnWidth( 3, 50 ); 169 mailView->setColumnWidth( 3, 50 );
170 mailView->setColumnWidth( 4, 50 ); 170 mailView->setColumnWidth( 4, 50 );
171} 171}
172 172
173void MainWindow::slotEditSettings() 173void MainWindow::slotEditSettings()
174{ 174{
175} 175}
176 176
177void MainWindow::slotShowFolders( bool ) 177void MainWindow::slotShowFolders( bool )
178{ 178{
179 qDebug( "slotShowFolders not reached" ); 179 qDebug( "slotShowFolders not reached" );
180} 180}
181 181
182void MainWindow::refreshMailView(QList<RecMail>*) 182void MainWindow::refreshMailView(QList<RecMail>*)
183{ 183{
184 qDebug( "refreshMailView not reached" ); 184 qDebug( "refreshMailView not reached" );
185} 185}
186 186
187void MainWindow::mailLeftClicked(int, QListViewItem *,const QPoint&,int ) 187void MainWindow::mailLeftClicked(int, QListViewItem *,const QPoint&,int )
188{ 188{
189 qDebug( "mailLeftClicked not reached" ); 189 qDebug( "mailLeftClicked not reached" );
190} 190}
191 191
192void MainWindow::displayMail() 192void MainWindow::displayMail()
193{ 193{
194 qDebug("displayMail not reached"); 194 qDebug("displayMail not reached");
195} 195}
196 196
197void MainWindow::slotDeleteMail() 197void MainWindow::slotDeleteMail()
198{ 198{
199 qDebug("deleteMail not reached"); 199 qDebug("deleteMail not reached");
200} 200}
201 201
202void MainWindow::mailHold(int, QListViewItem *,const QPoint&,int ) 202void MainWindow::mailHold(int, QListViewItem *,const QPoint&,int )
203{ 203{
204 qDebug("mailHold not reached"); 204 qDebug("mailHold not reached");
205} 205}
206 206
207void MainWindow::slotSendQueued() 207void MainWindow::slotSendQueued()
208{ 208{
209} 209}
210 210
211void MainWindow::slotEditAccounts() 211void MainWindow::slotEditAccounts()
212{ 212{
213} 213}
214 214
215void MainWindow::slotComposeMail() 215void MainWindow::slotComposeMail()
216{ 216{
217} 217}
diff --git a/noncore/net/mail/viewmail.cpp b/noncore/net/mail/viewmail.cpp
index f015228..8636957 100644
--- a/noncore/net/mail/viewmail.cpp
+++ b/noncore/net/mail/viewmail.cpp
@@ -1,472 +1,472 @@
1#include "composemail.h" 1#include "composemail.h"
2#include "viewmail.h" 2#include "viewmail.h"
3#include "accountview.h" 3#include "accountview.h"
4 4
5/* OPIE */ 5/* OPIE */
6#include <libmailwrapper/settings.h> 6#include <libmailwrapper/settings.h>
7#include <libmailwrapper/abstractmail.h> 7#include <libmailwrapper/abstractmail.h>
8#include <libmailwrapper/mailtypes.h> 8#include <libmailwrapper/mailtypes.h>
9 9
10#include <opie2/ofiledialog.h> 10#include <opie2/ofiledialog.h>
11#include <qpe/config.h> 11#include <qpe/config.h>
12#include <qpe/qpeapplication.h> 12#include <qpe/qpeapplication.h>
13 13
14/* QT */ 14/* QT */
15#include <qtextbrowser.h> 15#include <qtextbrowser.h>
16#include <qmessagebox.h> 16#include <qmessagebox.h>
17#include <qtextstream.h> 17#include <qtextstream.h>
18#include <qaction.h> 18#include <qaction.h>
19#include <qpopupmenu.h> 19#include <qpopupmenu.h>
20#include <qfile.h> 20#include <qfile.h>
21#include <qapplication.h> 21#include <qapplication.h>
22#include <qvaluelist.h> 22#include <qvaluelist.h>
23 23
24AttachItem::AttachItem(QListView * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file, 24AttachItem::AttachItem(QListView * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file,
25 const QString&fsize,int num,const QValueList<int>&path) 25 const QString&fsize,int num,const QValueList<int>&path)
26 : QListViewItem(parent,after),_partNum(num) 26 : QListViewItem(parent,after),_partNum(num)
27{ 27{
28 _path=path; 28 _path=path;
29 setText(0, mime); 29 setText(0, mime);
30 setText(1, desc); 30 setText(1, desc);
31 setText(2, file); 31 setText(2, file);
32 setText(3, fsize); 32 setText(3, fsize);
33} 33}
34 34
35AttachItem::AttachItem(QListViewItem * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file, 35AttachItem::AttachItem(QListViewItem * parent,QListViewItem *after, const QString&mime,const QString&desc,const QString&file,
36 const QString&fsize,int num,const QValueList<int>&path) 36 const QString&fsize,int num,const QValueList<int>&path)
37 : QListViewItem(parent,after),_partNum(num) 37 : QListViewItem(parent,after),_partNum(num)
38{ 38{
39 _path=path; 39 _path=path;
40 setText(0, mime); 40 setText(0, mime);
41 setText(1, desc); 41 setText(1, desc);
42 setText(2, file); 42 setText(2, file);
43 setText(3, fsize); 43 setText(3, fsize);
44} 44}
45 45
46bool AttachItem::isParentof(const QValueList<int>&path) 46bool AttachItem::isParentof(const QValueList<int>&path)
47{ 47{
48 /* if not set, then no parent */ 48 /* if not set, then no parent */
49 if (path.count()==0||_path.count()==0) return false; 49 if (path.count()==0||_path.count()==0) return false;
50 /* the parent must have one digit less then a child */ 50 /* the parent must have one digit less then a child */
51 if (path.count()!=_path.count()+1) return false; 51 if (path.count()!=_path.count()+1) return false;
52 for (unsigned int i=0; i < _path.count();++i) 52 for (unsigned int i=0; i < _path.count();++i)
53 { 53 {
54 if (_path[i]!=path[i]) return false; 54 if (_path[i]!=path[i]) return false;
55 } 55 }
56 return true; 56 return true;
57} 57}
58 58
59AttachItem* ViewMail::searchParent(const QValueList<int>&path) 59AttachItem* ViewMail::searchParent(const QValueList<int>&path)
60{ 60{
61 QListViewItemIterator it( attachments ); 61 QListViewItemIterator it( attachments );
62 for ( ; it.current(); ++it ) 62 for ( ; it.current(); ++it )
63 { 63 {
64 AttachItem*ati = (AttachItem*)it.current(); 64 AttachItem*ati = (AttachItem*)it.current();
65 if (ati->isParentof(path)) return ati; 65 if (ati->isParentof(path)) return ati;
66 } 66 }
67 return 0; 67 return 0;
68} 68}
69 69
70AttachItem* ViewMail::lastChild(AttachItem*parent) 70AttachItem* ViewMail::lastChild(AttachItem*parent)
71{ 71{
72 if (!parent) return 0; 72 if (!parent) return 0;
73 AttachItem* item = (AttachItem*)parent->firstChild(); 73 AttachItem* item = (AttachItem*)parent->firstChild();
74 if (!item) return item; 74 if (!item) return item;
75 AttachItem*temp=0; 75 AttachItem*temp=0;
76 while( (temp=(AttachItem*)item->nextSibling())) 76 while( (temp=(AttachItem*)item->nextSibling()))
77 { 77 {
78 item = temp; 78 item = temp;
79 } 79 }
80 return item; 80 return item;
81} 81}
82 82
83void ViewMail::setBody( RecBody body ) 83void ViewMail::setBody( RecBody body )
84{ 84{
85 85
86 m_body = body; 86 m_body = body;
87 m_mail[2] = body.Bodytext(); 87 m_mail[2] = body.Bodytext();
88 attachbutton->setEnabled(body.Parts().count()>0); 88 attachbutton->setEnabled(body.Parts().count()>0);
89 attachments->setEnabled(body.Parts().count()>0); 89 attachments->setEnabled(body.Parts().count()>0);
90 if (body.Parts().count()==0) 90 if (body.Parts().count()==0)
91 { 91 {
92 return; 92 return;
93 } 93 }
94 AttachItem * curItem=0; 94 AttachItem * curItem=0;
95 AttachItem * parentItem = 0; 95 AttachItem * parentItem = 0;
96 QString type=body.Description().Type()+"/"+body.Description().Subtype(); 96 QString type=body.Description().Type()+"/"+body.Description().Subtype();
97 QString desc,fsize; 97 QString desc,fsize;
98 double s = body.Description().Size(); 98 double s = body.Description().Size();
99 int w; 99 int w;
100 w=0; 100 w=0;
101 101
102 while (s>1024) 102 while (s>1024)
103 { 103 {
104 s/=1024; 104 s/=1024;
105 ++w; 105 ++w;
106 if (w>=2) break; 106 if (w>=2) break;
107 } 107 }
108 108
109 QString q=""; 109 QString q="";
110 switch(w) 110 switch(w)
111 { 111 {
112 case 1: 112 case 1:
113 q="k"; 113 q="k";
114 break; 114 break;
115 case 2: 115 case 2:
116 q="M"; 116 q="M";
117 break; 117 break;
118 default: 118 default:
119 break; 119 break;
120 } 120 }
121 121
122 { 122 {
123 /* I did not found a method to make a CONTENT reset on a QTextStream 123 /* I did not found a method to make a CONTENT reset on a QTextStream
124 so I use this construct that the stream will re-constructed in each 124 so I use this construct that the stream will re-constructed in each
125 loop. To let it work, the textstream is packed into a own area of 125 loop. To let it work, the textstream is packed into a own area of
126 code is it will be destructed after finishing its small job. 126 code is it will be destructed after finishing its small job.
127 */ 127 */
128 QTextOStream o(&fsize); 128 QTextOStream o(&fsize);
129 if (w>0) o.precision(2); else o.precision(0); 129 if (w>0) o.precision(2); else o.precision(0);
130 o.setf(QTextStream::fixed); 130 o.setf(QTextStream::fixed);
131 o << s << " " << q << "Byte"; 131 o << s << " " << q << "Byte";
132 } 132 }
133 133
134 curItem=new AttachItem(attachments,curItem,type,"Mailbody","",fsize,-1,body.Description().Positionlist()); 134 curItem=new AttachItem(attachments,curItem,type,"Mailbody","",fsize,-1,body.Description().Positionlist());
135 QString filename = ""; 135 QString filename = "";
136 136
137 for (unsigned int i = 0; i < body.Parts().count();++i) 137 for (unsigned int i = 0; i < body.Parts().count();++i)
138 { 138 {
139 type = body.Parts()[i].Type()+"/"+body.Parts()[i].Subtype(); 139 type = body.Parts()[i].Type()+"/"+body.Parts()[i].Subtype();
140 part_plist_t::ConstIterator it = body.Parts()[i].Parameters().begin(); 140 part_plist_t::ConstIterator it = body.Parts()[i].Parameters().begin();
141 for (;it!=body.Parts()[i].Parameters().end();++it) 141 for (;it!=body.Parts()[i].Parameters().end();++it)
142 { 142 {
143 qDebug(it.key()); 143 qDebug(it.key());
144 if (it.key().lower()=="name") 144 if (it.key().lower()=="name")
145 { 145 {
146 filename=it.data(); 146 filename=it.data();
147 } 147 }
148 } 148 }
149 s = body.Parts()[i].Size(); 149 s = body.Parts()[i].Size();
150 w = 0; 150 w = 0;
151 while (s>1024) 151 while (s>1024)
152 { 152 {
153 s/=1024; 153 s/=1024;
154 ++w; 154 ++w;
155 if (w>=2) break; 155 if (w>=2) break;
156 } 156 }
157 switch(w) 157 switch(w)
158 { 158 {
159 case 1: 159 case 1:
160 q="k"; 160 q="k";
161 break; 161 break;
162 case 2: 162 case 2:
163 q="M"; 163 q="M";
164 break; 164 break;
165 default: 165 default:
166 q=""; 166 q="";
167 break; 167 break;
168 } 168 }
169 QTextOStream o(&fsize); 169 QTextOStream o(&fsize);
170 if (w>0) o.precision(2); else o.precision(0); 170 if (w>0) o.precision(2); else o.precision(0);
171 o.setf(QTextStream::fixed); 171 o.setf(QTextStream::fixed);
172 o << s << " " << q << "Byte"; 172 o << s << " " << q << "Byte";
173 desc = body.Parts()[i].Description(); 173 desc = body.Parts()[i].Description();
174 parentItem = searchParent(body.Parts()[i].Positionlist()); 174 parentItem = searchParent(body.Parts()[i].Positionlist());
175 if (parentItem) 175 if (parentItem)
176 { 176 {
177 AttachItem*temp = lastChild(parentItem); 177 AttachItem*temp = lastChild(parentItem);
178 if (temp) curItem = temp; 178 if (temp) curItem = temp;
179 curItem=new AttachItem(parentItem,curItem,type,desc,filename,fsize,i,body.Parts()[i].Positionlist()); 179 curItem=new AttachItem(parentItem,curItem,type,desc,filename,fsize,i,body.Parts()[i].Positionlist());
180 attachments->setRootIsDecorated(true); 180 attachments->setRootIsDecorated(true);
181 curItem = parentItem; 181 curItem = parentItem;
182 } 182 }
183 else 183 else
184 { 184 {
185 curItem=new AttachItem(attachments,curItem,type,desc,filename,fsize,i,body.Parts()[i].Positionlist()); 185 curItem=new AttachItem(attachments,curItem,type,desc,filename,fsize,i,body.Parts()[i].Positionlist());
186 } 186 }
187 } 187 }
188} 188}
189 189
190 190
191void ViewMail::slotShowHtml( bool state ) 191void ViewMail::slotShowHtml( bool state )
192{ 192{
193 m_showHtml = state; 193 m_showHtml = state;
194 setText(); 194 setText();
195} 195}
196 196
197void ViewMail::slotItemClicked( QListViewItem * item , const QPoint & point, int ) 197void ViewMail::slotItemClicked( QListViewItem * item , const QPoint & point, int )
198{ 198{
199 if (!item ) 199 if (!item )
200 return; 200 return;
201 201
202 if ( ( ( AttachItem* )item )->Partnumber() == -1 ) 202 if ( ( ( AttachItem* )item )->Partnumber() == -1 )
203 { 203 {
204 setText(); 204 setText();
205 return; 205 return;
206 } 206 }
207 QPopupMenu *menu = new QPopupMenu(); 207 QPopupMenu *menu = new QPopupMenu();
208 int ret=0; 208 int ret=0;
209 209
210 if ( item->text( 0 ).left( 5 ) == "text/" || item->text(0)=="message/rfc822" ) 210 if ( item->text( 0 ).left( 5 ) == "text/" || item->text(0)=="message/rfc822" )
211 { 211 {
212 menu->insertItem( tr( "Show Text" ), 1 ); 212 menu->insertItem( tr( "Show Text" ), 1 );
213 } 213 }
214 menu->insertItem( tr( "Save Attachment" ), 0 ); 214 menu->insertItem( tr( "Save Attachment" ), 0 );
215 menu->insertSeparator(1); 215 menu->insertSeparator(1);
216 216
217 ret = menu->exec( point, 0 ); 217 ret = menu->exec( point, 0 );
218 218
219 switch(ret) 219 switch(ret)
220 { 220 {
221 case 0: 221 case 0:
222 { 222 {
223 MimeTypes types; 223 MimeTypes types;
224 types.insert( "all", "*" ); 224 types.insert( "all", "*" );
225 QString str = Opie::OFileDialog::getSaveFileName( 1, 225 QString str = Opie::OFileDialog::getSaveFileName( 1,
226 "/", item->text( 2 ) , types, 0 ); 226 "/", item->text( 2 ) , types, 0 );
227 227
228 if( !str.isEmpty() ) 228 if( !str.isEmpty() )
229 { 229 {
230 encodedString*content = m_recMail.Wrapper()->fetchDecodedPart( m_recMail, m_body.Parts()[ ( ( AttachItem* )item )->Partnumber() ] ); 230 encodedString*content = m_recMail.Wrapper()->fetchDecodedPart( m_recMail, m_body.Parts()[ ( ( AttachItem* )item )->Partnumber() ] );
231 if (content) 231 if (content)
232 { 232 {
233 QFile output(str); 233 QFile output(str);
234 output.open(IO_WriteOnly); 234 output.open(IO_WriteOnly);
235 output.writeBlock(content->Content(),content->Length()); 235 output.writeBlock(content->Content(),content->Length());
236 output.close(); 236 output.close();
237 delete content; 237 delete content;
238 } 238 }
239 } 239 }
240 } 240 }
241 break ; 241 break ;
242 242
243 case 1: 243 case 1:
244 if ( ( ( AttachItem* )item )->Partnumber() == -1 ) 244 if ( ( ( AttachItem* )item )->Partnumber() == -1 )
245 { 245 {
246 setText(); 246 setText();
247 } 247 }
248 else 248 else
249 { 249 {
250 if ( m_recMail.Wrapper() != 0l ) 250 if ( m_recMail.Wrapper() != 0l )
251 { // make sure that there is a wrapper , even after delete or simular actions 251 { // make sure that there is a wrapper , even after delete or simular actions
252 browser->setText( m_recMail.Wrapper()->fetchTextPart( m_recMail, m_body.Parts()[ ( ( AttachItem* )item )->Partnumber() ] ) ); 252 browser->setText( m_recMail.Wrapper()->fetchTextPart( m_recMail, m_body.Parts()[ ( ( AttachItem* )item )->Partnumber() ] ) );
253 } 253 }
254 } 254 }
255 break; 255 break;
256 } 256 }
257 delete menu; 257 delete menu;
258} 258}
259 259
260 260
261void ViewMail::setMail( RecMail mail ) 261void ViewMail::setMail( RecMail mail )
262{ 262{
263 263
264 m_recMail = mail; 264 m_recMail = mail;
265 265
266 m_mail[0] = mail.getFrom(); 266 m_mail[0] = mail.getFrom();
267 m_mail[1] = mail.getSubject(); 267 m_mail[1] = mail.getSubject();
268 m_mail[3] = mail.getDate(); 268 m_mail[3] = mail.getDate();
269 m_mail[4] = mail.Msgid(); 269 m_mail[4] = mail.Msgid();
270 270
271 m_mail2[0] = mail.To(); 271 m_mail2[0] = mail.To();
272 m_mail2[1] = mail.CC(); 272 m_mail2[1] = mail.CC();
273 m_mail2[2] = mail.Bcc(); 273 m_mail2[2] = mail.Bcc();
274 274
275 setText(); 275 setText();
276} 276}
277 277
278 278
279 279
280ViewMail::ViewMail( QWidget *parent, const char *name, WFlags fl) 280ViewMail::ViewMail( QWidget *parent, const char *name, WFlags fl)
281 : ViewMailBase(parent, name, fl), _inLoop(false) 281 : ViewMailBase(parent, name, fl), _inLoop(false)
282{ 282{
283 m_gotBody = false; 283 m_gotBody = false;
284 deleted = false; 284 deleted = false;
285 285
286 connect( reply, SIGNAL(activated()), SLOT(slotReply())); 286 connect( reply, SIGNAL(activated()), SLOT(slotReply()));
287 connect( forward, SIGNAL(activated()), SLOT(slotForward())); 287 connect( forward, SIGNAL(activated()), SLOT(slotForward()));
288 connect( deleteMail, SIGNAL( activated() ), SLOT( slotDeleteMail( ) ) ); 288 connect( deleteMail, SIGNAL( activated() ), SLOT( slotDeleteMail() ) );
289 connect( showHtml, SIGNAL( toggled( bool ) ), SLOT( slotShowHtml( bool ) ) ); 289 connect( showHtml, SIGNAL( toggled(bool) ), SLOT( slotShowHtml(bool) ) );
290 290
291 attachments->setEnabled(m_gotBody); 291 attachments->setEnabled(m_gotBody);
292 connect( attachments, SIGNAL( clicked ( QListViewItem *, const QPoint & , int ) ), SLOT( slotItemClicked( QListViewItem *, const QPoint & , int ) ) ); 292 connect( attachments, SIGNAL( clicked(QListViewItem*,const QPoint&, int) ), SLOT( slotItemClicked(QListViewItem*,const QPoint&, int) ) );
293 293
294 readConfig(); 294 readConfig();
295 attachments->setSorting(-1); 295 attachments->setSorting(-1);
296} 296}
297 297
298void ViewMail::readConfig() 298void ViewMail::readConfig()
299{ 299{
300 Config cfg( "mail" ); 300 Config cfg( "mail" );
301 cfg.setGroup( "Settings" ); 301 cfg.setGroup( "Settings" );
302 m_showHtml = cfg.readBoolEntry( "showHtml", false ); 302 m_showHtml = cfg.readBoolEntry( "showHtml", false );
303 showHtml->setOn( m_showHtml ); 303 showHtml->setOn( m_showHtml );
304} 304}
305 305
306void ViewMail::setText() 306void ViewMail::setText()
307{ 307{
308 308
309 QString toString; 309 QString toString;
310 QString ccString; 310 QString ccString;
311 QString bccString; 311 QString bccString;
312 312
313 for ( QStringList::Iterator it = ( m_mail2[0] ).begin(); it != ( m_mail2[0] ).end(); ++it ) 313 for ( QStringList::Iterator it = ( m_mail2[0] ).begin(); it != ( m_mail2[0] ).end(); ++it )
314 { 314 {
315 toString += (*it); 315 toString += (*it);
316 } 316 }
317 for ( QStringList::Iterator it = ( m_mail2[1] ).begin(); it != ( m_mail2[1] ).end(); ++it ) 317 for ( QStringList::Iterator it = ( m_mail2[1] ).begin(); it != ( m_mail2[1] ).end(); ++it )
318 { 318 {
319 ccString += (*it); 319 ccString += (*it);
320 } 320 }
321 for ( QStringList::Iterator it = ( m_mail2[2] ).begin(); it != ( m_mail2[2] ).end(); ++it ) 321 for ( QStringList::Iterator it = ( m_mail2[2] ).begin(); it != ( m_mail2[2] ).end(); ++it )
322 { 322 {
323 bccString += (*it); 323 bccString += (*it);
324 } 324 }
325 325
326 setCaption( caption().arg( m_mail[0] ) ); 326 setCaption( caption().arg( m_mail[0] ) );
327 327
328 m_mailHtml = "<html><body>" 328 m_mailHtml = "<html><body>"
329 "<table width=\"100%\" border=\"0\"><tr bgcolor=\"#FFDD76\"><td>" 329 "<table width=\"100%\" border=\"0\"><tr bgcolor=\"#FFDD76\"><td>"
330 "<div align=left><b>" + deHtml( m_mail[1] ) + "</b></div>" 330 "<div align=left><b>" + deHtml( m_mail[1] ) + "</b></div>"
331 "</td></tr><tr bgcolor=\"#EEEEE6\"><td>" 331 "</td></tr><tr bgcolor=\"#EEEEE6\"><td>"
332 "<b>" + tr( "From" ) + ": </b><font color=#6C86C0>" + deHtml( m_mail[0] ) + "</font><br>" 332 "<b>" + tr( "From" ) + ": </b><font color=#6C86C0>" + deHtml( m_mail[0] ) + "</font><br>"
333 "<b>" + tr( "To" ) + ": </b><font color=#6C86C0>" + deHtml( toString ) + "</font><br><b>" + 333 "<b>" + tr( "To" ) + ": </b><font color=#6C86C0>" + deHtml( toString ) + "</font><br><b>" +
334 tr( "Cc" ) + ": </b>" + deHtml( ccString ) + "<br>" 334 tr( "Cc" ) + ": </b>" + deHtml( ccString ) + "<br>"
335 "<b>" + tr( "Date" ) + ": </b> " + m_mail[3] + 335 "<b>" + tr( "Date" ) + ": </b> " + m_mail[3] +
336 "</td></tr></table><font face=fixed>"; 336 "</td></tr></table><font face=fixed>";
337 337
338 if ( !m_showHtml ) 338 if ( !m_showHtml )
339 { 339 {
340 browser->setText( QString( m_mailHtml) + deHtml( m_mail[2] ) + "</font></html>" ); 340 browser->setText( QString( m_mailHtml) + deHtml( m_mail[2] ) + "</font></html>" );
341 } 341 }
342 else 342 else
343 { 343 {
344 browser->setText( QString( m_mailHtml) + m_mail[2] + "</font></html>" ); 344 browser->setText( QString( m_mailHtml) + m_mail[2] + "</font></html>" );
345 } 345 }
346 // remove later in favor of a real handling 346 // remove later in favor of a real handling
347 m_gotBody = true; 347 m_gotBody = true;
348} 348}
349 349
350 350
351ViewMail::~ViewMail() 351ViewMail::~ViewMail()
352{ 352{
353 m_recMail.Wrapper()->cleanMimeCache(); 353 m_recMail.Wrapper()->cleanMimeCache();
354 hide(); 354 hide();
355} 355}
356 356
357void ViewMail::hide() 357void ViewMail::hide()
358{ 358{
359 QWidget::hide(); 359 QWidget::hide();
360 360
361 if (_inLoop) 361 if (_inLoop)
362 { 362 {
363 _inLoop = false; 363 _inLoop = false;
364 qApp->exit_loop(); 364 qApp->exit_loop();
365 365
366 } 366 }
367 367
368} 368}
369 369
370void ViewMail::exec() 370void ViewMail::exec()
371{ 371{
372 show(); 372 show();
373 373
374 if (!_inLoop) 374 if (!_inLoop)
375 { 375 {
376 _inLoop = true; 376 _inLoop = true;
377 qApp->enter_loop(); 377 qApp->enter_loop();
378 } 378 }
379 379
380} 380}
381 381
382QString ViewMail::deHtml(const QString &string) 382QString ViewMail::deHtml(const QString &string)
383{ 383{
384 QString string_ = string; 384 QString string_ = string;
385 string_.replace(QRegExp("&"), "&amp;"); 385 string_.replace(QRegExp("&"), "&amp;");
386 string_.replace(QRegExp("<"), "&lt;"); 386 string_.replace(QRegExp("<"), "&lt;");
387 string_.replace(QRegExp(">"), "&gt;"); 387 string_.replace(QRegExp(">"), "&gt;");
388 string_.replace(QRegExp("\\n"), "<br>"); 388 string_.replace(QRegExp("\\n"), "<br>");
389 return string_; 389 return string_;
390} 390}
391 391
392void ViewMail::slotReply() 392void ViewMail::slotReply()
393{ 393{
394 if (!m_gotBody) 394 if (!m_gotBody)
395 { 395 {
396 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot reply yet."), tr("Ok")); 396 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot reply yet."), tr("Ok"));
397 return; 397 return;
398 } 398 }
399 399
400 QString rtext; 400 QString rtext;
401 rtext += QString("* %1 wrote on %2:\n") // no i18n on purpose 401 rtext += QString("* %1 wrote on %2:\n") // no i18n on purpose
402 .arg( m_mail[0] ) 402 .arg( m_mail[0] )
403 .arg( m_mail[3] ); 403 .arg( m_mail[3] );
404 404
405 QString text = m_mail[2]; 405 QString text = m_mail[2];
406 QStringList lines = QStringList::split(QRegExp("\\n"), text); 406 QStringList lines = QStringList::split(QRegExp("\\n"), text);
407 QStringList::Iterator it; 407 QStringList::Iterator it;
408 for (it = lines.begin(); it != lines.end(); it++) 408 for (it = lines.begin(); it != lines.end(); it++)
409 { 409 {
410 rtext += "> " + *it + "\n"; 410 rtext += "> " + *it + "\n";
411 } 411 }
412 rtext += "\n"; 412 rtext += "\n";
413 413
414 QString prefix; 414 QString prefix;
415 if ( m_mail[1].find(QRegExp("^Re: *$")) != -1) prefix = ""; 415 if ( m_mail[1].find(QRegExp("^Re: *$")) != -1) prefix = "";
416 else prefix = "Re: "; // no i18n on purpose 416 else prefix = "Re: "; // no i18n on purpose
417 417
418 Settings *settings = new Settings(); 418 Settings *settings = new Settings();
419 ComposeMail composer( settings ,this, 0, true); 419 ComposeMail composer( settings ,this, 0, true);
420 composer.setTo( m_mail[0] ); 420 composer.setTo( m_mail[0] );
421 composer.setSubject( "Re: " + m_mail[1] ); 421 composer.setSubject( "Re: " + m_mail[1] );
422 composer.setMessage( rtext ); 422 composer.setMessage( rtext );
423 if ( QDialog::Accepted == QPEApplication::execDialog( &composer ) ) 423 if ( QDialog::Accepted == QPEApplication::execDialog( &composer ) )
424 { 424 {
425 m_recMail.Wrapper()->answeredMail(m_recMail); 425 m_recMail.Wrapper()->answeredMail(m_recMail);
426 } 426 }
427} 427}
428 428
429void ViewMail::slotForward() 429void ViewMail::slotForward()
430{ 430{
431 if (!m_gotBody) 431 if (!m_gotBody)
432 { 432 {
433 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot forward yet."), tr("Ok")); 433 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot forward yet."), tr("Ok"));
434 return; 434 return;
435 } 435 }
436 436
437 QString ftext; 437 QString ftext;
438 ftext += QString("\n----- Forwarded message from %1 -----\n\n") 438 ftext += QString("\n----- Forwarded message from %1 -----\n\n")
439 .arg( m_mail[0] ); 439 .arg( m_mail[0] );
440 if (!m_mail[3].isNull()) 440 if (!m_mail[3].isNull())
441 ftext += QString("Date: %1\n") 441 ftext += QString("Date: %1\n")
442 .arg( m_mail[3] ); 442 .arg( m_mail[3] );
443 if (!m_mail[0].isNull()) 443 if (!m_mail[0].isNull())
444 ftext += QString("From: %1\n") 444 ftext += QString("From: %1\n")
445 .arg( m_mail[0] ); 445 .arg( m_mail[0] );
446 if (!m_mail[1].isNull()) 446 if (!m_mail[1].isNull())
447 ftext += QString("Subject: %1\n") 447 ftext += QString("Subject: %1\n")
448 .arg( m_mail[1] ); 448 .arg( m_mail[1] );
449 449
450 ftext += QString("\n%1\n") 450 ftext += QString("\n%1\n")
451 .arg( m_mail[2]); 451 .arg( m_mail[2]);
452 452
453 ftext += QString("----- End forwarded message -----\n"); 453 ftext += QString("----- End forwarded message -----\n");
454 454
455 Settings *settings = new Settings(); 455 Settings *settings = new Settings();
456 ComposeMail composer( settings ,this, 0, true); 456 ComposeMail composer( settings ,this, 0, true);
457 composer.setSubject( "Fwd: " + m_mail[1] ); 457 composer.setSubject( "Fwd: " + m_mail[1] );
458 composer.setMessage( ftext ); 458 composer.setMessage( ftext );
459 if ( QDialog::Accepted == QPEApplication::execDialog( &composer )) 459 if ( QDialog::Accepted == QPEApplication::execDialog( &composer ))
460 { 460 {
461 } 461 }
462} 462}
463 463
464void ViewMail::slotDeleteMail( ) 464void ViewMail::slotDeleteMail( )
465{ 465{
466 if ( QMessageBox::warning(this, tr("Delete Mail"), QString( tr("<p>Do you really want to delete this mail? <br><br>" ) + m_mail[0] + " - " + m_mail[1] ) , QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes ) 466 if ( QMessageBox::warning(this, tr("Delete Mail"), QString( tr("<p>Do you really want to delete this mail? <br><br>" ) + m_mail[0] + " - " + m_mail[1] ) , QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes )
467 { 467 {
468 m_recMail.Wrapper()->deleteMail( m_recMail ); 468 m_recMail.Wrapper()->deleteMail( m_recMail );
469 hide(); 469 hide();
470 deleted = true; 470 deleted = true;
471 } 471 }
472} 472}
diff --git a/noncore/net/opieftp/opieftp.cpp b/noncore/net/opieftp/opieftp.cpp
index 4064549..4c39569 100644
--- a/noncore/net/opieftp/opieftp.cpp
+++ b/noncore/net/opieftp/opieftp.cpp
@@ -1,1529 +1,1529 @@
1/*************************************************************************** 1/***************************************************************************
2 opieftp.cpp 2 opieftp.cpp
3 ------------------- 3 -------------------
4** Created: Sat Mar 9 23:33:09 2002 4** Created: Sat Mar 9 23:33:09 2002
5 copyright : (C) 2002 by ljp 5 copyright : (C) 2002 by ljp
6 email : ljp@llornkcor.com 6 email : ljp@llornkcor.com
7 * This program is free software; you can redistribute it and/or modify * 7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by * 8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or * 9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. * 10 * (at your option) any later version. *
11 ***************************************************************************/ 11 ***************************************************************************/
12//#define DEVELOPERS_VERSION 12//#define DEVELOPERS_VERSION
13 13
14#include "opieftp.h" 14#include "opieftp.h"
15 15
16extern "C" { 16extern "C" {
17#include "../ftplib/ftplib.h" 17#include "../ftplib/ftplib.h"
18} 18}
19 19
20#include "inputDialog.h" 20#include "inputDialog.h"
21 21
22#include <qmenubar.h> 22#include <qmenubar.h>
23#include <qpe/qpeapplication.h> 23#include <qpe/qpeapplication.h>
24#include <qpe/resource.h> 24#include <qpe/resource.h>
25#include <qpe/config.h> 25#include <qpe/config.h>
26#include <qpe/mimetype.h> 26#include <qpe/mimetype.h>
27 27
28#include <qtextstream.h> 28#include <qtextstream.h>
29#include <qpushbutton.h> 29#include <qpushbutton.h>
30#include <qtoolbutton.h> 30#include <qtoolbutton.h>
31#include <qcombobox.h> 31#include <qcombobox.h>
32#include <qlistview.h> 32#include <qlistview.h>
33#include <qlabel.h> 33#include <qlabel.h>
34#include <qprogressbar.h> 34#include <qprogressbar.h>
35#include <qspinbox.h> 35#include <qspinbox.h>
36#include <qtabwidget.h> 36#include <qtabwidget.h>
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qmessagebox.h> 38#include <qmessagebox.h>
39#include <qlineedit.h> 39#include <qlineedit.h>
40#include <qlistbox.h> 40#include <qlistbox.h>
41#include <qvbox.h> 41#include <qvbox.h>
42 42
43#include <unistd.h> 43#include <unistd.h>
44#include <stdlib.h> 44#include <stdlib.h>
45 45
46 46
47QProgressBar *ProgressBar; 47QProgressBar *ProgressBar;
48static netbuf *conn=NULL; 48static netbuf *conn=NULL;
49 49
50static int log_progress(netbuf *, int xfered, void *) 50static int log_progress(netbuf *, int xfered, void *)
51{ 51{
52// int fsz = *(int *)arg; 52// int fsz = *(int *)arg;
53// int pct = (xfered * 100) / fsz; 53// int pct = (xfered * 100) / fsz;
54// printf("%3d%%\r", pct); 54// printf("%3d%%\r", pct);
55// fflush(stdout); 55// fflush(stdout);
56 ProgressBar->setProgress(xfered); 56 ProgressBar->setProgress(xfered);
57 qApp->processEvents(); 57 qApp->processEvents();
58 return 1; 58 return 1;
59} 59}
60 60
61OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl) 61OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl)
62 : QMainWindow( parent, name, fl ) 62 : QMainWindow( parent, name, fl )
63{ 63{
64 qDebug("OpieFtp constructor"); 64 qDebug("OpieFtp constructor");
65 setCaption( tr( "OpieFtp" ) ); 65 setCaption( tr( "OpieFtp" ) );
66 fuckeduphack=FALSE; 66 fuckeduphack=FALSE;
67 67
68 QVBox* wrapperBox = new QVBox( this ); 68 QVBox* wrapperBox = new QVBox( this );
69 setCentralWidget( wrapperBox ); 69 setCentralWidget( wrapperBox );
70 70
71 QWidget *view = new QWidget( wrapperBox ); 71 QWidget *view = new QWidget( wrapperBox );
72 72
73 QGridLayout *layout = new QGridLayout( view ); 73 QGridLayout *layout = new QGridLayout( view );
74 layout->setSpacing( 2); 74 layout->setSpacing( 2);
75 layout->setMargin( 2); 75 layout->setMargin( 2);
76 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 76 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
77 77
78 QMenuBar *menuBar = new QMenuBar(this); 78 QMenuBar *menuBar = new QMenuBar(this);
79// QToolBar *menuBar = new QToolBar(this); 79// QToolBar *menuBar = new QToolBar(this);
80// menuBar->setHorizontalStretchable( TRUE ); 80// menuBar->setHorizontalStretchable( TRUE );
81 81
82 QWMatrix matrix; 82 QWMatrix matrix;
83 QPixmap pix(Resource::loadPixmap( "UnknownDocument" )); 83 QPixmap pix(Resource::loadPixmap( "UnknownDocument" ));
84 matrix.scale( .4, .4); 84 matrix.scale( .4, .4);
85 unknownXpm = pix.xForm(matrix); 85 unknownXpm = pix.xForm(matrix);
86 86
87 connectionMenu = new QPopupMenu( this ); 87 connectionMenu = new QPopupMenu( this );
88 localMenu = new QPopupMenu( this ); 88 localMenu = new QPopupMenu( this );
89 remoteMenu = new QPopupMenu( this ); 89 remoteMenu = new QPopupMenu( this );
90 tabMenu = new QPopupMenu( this ); 90 tabMenu = new QPopupMenu( this );
91 91
92//#if 0 92//#if 0
93 layout->addMultiCellWidget( menuBar, 0, 0, 0, 2 ); 93 layout->addMultiCellWidget( menuBar, 0, 0, 0, 2 );
94//#endif 94//#endif
95 95
96 menuBar->insertItem( tr( "Connection" ), connectionMenu); 96 menuBar->insertItem( tr( "Connection" ), connectionMenu);
97// menuBar->insertItem( tr( "Local" ), localMenu); 97// menuBar->insertItem( tr( "Local" ), localMenu);
98// menuBar->insertItem( tr( "Remote" ), remoteMenu); 98// menuBar->insertItem( tr( "Remote" ), remoteMenu);
99 menuBar->insertItem( tr( "View" ), tabMenu); 99 menuBar->insertItem( tr( "View" ), tabMenu);
100 100
101 tabMenu->insertItem( tr( "Local" ), localMenu); 101 tabMenu->insertItem( tr( "Local" ), localMenu);
102 tabMenu->insertItem( tr( "Remote" ), remoteMenu); 102 tabMenu->insertItem( tr( "Remote" ), remoteMenu);
103 103
104 connectionMenu->insertItem( tr( "New" ), this, SLOT( newConnection() )); 104 connectionMenu->insertItem( tr( "New" ), this, SLOT( newConnection() ));
105 connectionMenu->insertItem( tr( "Connect" ), this, SLOT( connector() )); 105 connectionMenu->insertItem( tr( "Connect" ), this, SLOT( connector() ));
106 connectionMenu->insertItem( tr( "Disconnect" ), this, SLOT( disConnector() )); 106 connectionMenu->insertItem( tr( "Disconnect" ), this, SLOT( disConnector() ));
107 107
108 localMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); 108 localMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
109 localMenu->insertSeparator(); 109 localMenu->insertSeparator();
110 localMenu->insertItem( tr( "Upload" ), this, SLOT( localUpload() )); 110 localMenu->insertItem( tr( "Upload" ), this, SLOT( localUpload() ));
111 localMenu->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() )); 111 localMenu->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() ));
112 localMenu->insertItem( tr( "Rename" ), this, SLOT( localRename() )); 112 localMenu->insertItem( tr( "Rename" ), this, SLOT( localRename() ));
113 localMenu->insertSeparator(); 113 localMenu->insertSeparator();
114 localMenu->insertItem( tr( "Delete" ), this, SLOT( localDelete() )); 114 localMenu->insertItem( tr( "Delete" ), this, SLOT( localDelete() ));
115 localMenu->setCheckable(TRUE); 115 localMenu->setCheckable(TRUE);
116 116
117 remoteMenu->insertItem( tr( "Download" ), this, SLOT( remoteDownload() )); 117 remoteMenu->insertItem( tr( "Download" ), this, SLOT( remoteDownload() ));
118 remoteMenu->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() )); 118 remoteMenu->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() ));
119 remoteMenu->insertItem( tr( "Rename" ), this, SLOT( remoteRename() )); 119 remoteMenu->insertItem( tr( "Rename" ), this, SLOT( remoteRename() ));
120 remoteMenu->insertSeparator(); 120 remoteMenu->insertSeparator();
121 remoteMenu->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); 121 remoteMenu->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() ));
122 122
123 tabMenu->insertSeparator(); 123 tabMenu->insertSeparator();
124 tabMenu->insertItem( tr( "Switch to Local" ), this, SLOT( switchToLocalTab() )); 124 tabMenu->insertItem( tr( "Switch to Local" ), this, SLOT( switchToLocalTab() ));
125 tabMenu->insertItem( tr( "Switch to Remote" ), this, SLOT( switchToRemoteTab() )); 125 tabMenu->insertItem( tr( "Switch to Remote" ), this, SLOT( switchToRemoteTab() ));
126 tabMenu->insertItem( tr( "Switch to Config" ), this, SLOT( switchToConfigTab() )); 126 tabMenu->insertItem( tr( "Switch to Config" ), this, SLOT( switchToConfigTab() ));
127 tabMenu->insertSeparator(); 127 tabMenu->insertSeparator();
128// tabMenu->insertItem( tr( "About" ), this, SLOT( doAbout() )); 128// tabMenu->insertItem( tr( "About" ), this, SLOT( doAbout() ));
129 tabMenu->setCheckable(TRUE); 129 tabMenu->setCheckable(TRUE);
130 130
131 131
132 cdUpButton = new QToolButton( view,"cdUpButton"); 132 cdUpButton = new QToolButton( view,"cdUpButton");
133 cdUpButton->setPixmap(Resource::loadPixmap("up")); 133 cdUpButton->setPixmap(Resource::loadPixmap("up"));
134 cdUpButton ->setFixedSize( QSize( 20, 20 ) ); 134 cdUpButton ->setFixedSize( QSize( 20, 20 ) );
135 connect( cdUpButton ,SIGNAL(released()),this,SLOT( upDir()) ); 135 connect( cdUpButton ,SIGNAL(released()),this,SLOT( upDir()) );
136 layout->addMultiCellWidget( cdUpButton, 0, 0, 3, 3 ); 136 layout->addMultiCellWidget( cdUpButton, 0, 0, 3, 3 );
137 cdUpButton->hide(); 137 cdUpButton->hide();
138 138
139// docButton = new QPushButton(Resource::loadIconSet("DocsIcon"),"",view,"docsButton"); 139// docButton = new QPushButton(Resource::loadIconSet("DocsIcon"),"",view,"docsButton");
140// docButton->setFixedSize( QSize( 20, 20 ) ); 140// docButton->setFixedSize( QSize( 20, 20 ) );
141// connect( docButton,SIGNAL(released()),this,SLOT( docButtonPushed()) ); 141// connect( docButton,SIGNAL(released()),this,SLOT( docButtonPushed()) );
142// docButton->setFlat(TRUE); 142// docButton->setFlat(TRUE);
143// layout->addMultiCellWidget( docButton, 0, 0, 6, 6 ); 143// layout->addMultiCellWidget( docButton, 0, 0, 6, 6 );
144 144
145 homeButton = new QToolButton(view,"homeButton"); 145 homeButton = new QToolButton(view,"homeButton");
146 homeButton->setPixmap( Resource::loadPixmap("home")); 146 homeButton->setPixmap( Resource::loadPixmap("home"));
147 homeButton->setFixedSize( QSize( 20, 20 ) ); 147 homeButton->setFixedSize( QSize( 20, 20 ) );
148 connect(homeButton,SIGNAL(released()),this,SLOT(homeButtonPushed()) ); 148 connect(homeButton,SIGNAL(released()),this,SLOT(homeButtonPushed()) );
149 layout->addMultiCellWidget( homeButton, 0, 0, 4, 4); 149 layout->addMultiCellWidget( homeButton, 0, 0, 4, 4);
150 homeButton->hide(); 150 homeButton->hide();
151 151
152 TabWidget = new QTabWidget( view, "TabWidget" ); 152 TabWidget = new QTabWidget( view, "TabWidget" );
153 layout->addMultiCellWidget( TabWidget, 1, 1, 0, 4 ); 153 layout->addMultiCellWidget( TabWidget, 1, 1, 0, 4 );
154 154
155// TabWidget->setTabShape(QTabWidget::Triangular); 155// TabWidget->setTabShape(QTabWidget::Triangular);
156 156
157 tab = new QWidget( TabWidget, "tab" ); 157 tab = new QWidget( TabWidget, "tab" );
158 tabLayout = new QGridLayout( tab ); 158 tabLayout = new QGridLayout( tab );
159 tabLayout->setSpacing( 2); 159 tabLayout->setSpacing( 2);
160 tabLayout->setMargin( 2); 160 tabLayout->setMargin( 2);
161 161
162 Local_View = new QListView( tab, "Local_View" ); 162 Local_View = new QListView( tab, "Local_View" );
163// Local_View->setResizePolicy( QListView::AutoOneFit ); 163// Local_View->setResizePolicy( QListView::AutoOneFit );
164 Local_View->addColumn( tr("File"),150); 164 Local_View->addColumn( tr("File"),150);
165 Local_View->addColumn( tr("Date"),-1); 165 Local_View->addColumn( tr("Date"),-1);
166 Local_View->setColumnAlignment(1,QListView::AlignRight); 166 Local_View->setColumnAlignment(1,QListView::AlignRight);
167 Local_View->addColumn( tr("Size"),-1); 167 Local_View->addColumn( tr("Size"),-1);
168 Local_View->setColumnAlignment(2,QListView::AlignRight); 168 Local_View->setColumnAlignment(2,QListView::AlignRight);
169 Local_View->setAllColumnsShowFocus(TRUE); 169 Local_View->setAllColumnsShowFocus(TRUE);
170 170
171 Local_View->setMultiSelection( TRUE); 171 Local_View->setMultiSelection( TRUE);
172 Local_View->setSelectionMode(QListView::Extended); 172 Local_View->setSelectionMode(QListView::Extended);
173 Local_View->setFocusPolicy(QWidget::ClickFocus); 173 Local_View->setFocusPolicy(QWidget::ClickFocus);
174 174
175 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold); 175 QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold);
176 176
177 tabLayout->addWidget( Local_View, 0, 0 ); 177 tabLayout->addWidget( Local_View, 0, 0 );
178 178
179 connect( Local_View, SIGNAL( clicked( QListViewItem*)), 179 connect( Local_View, SIGNAL( clicked(QListViewItem*)),
180 this,SLOT( localListClicked(QListViewItem *)) ); 180 this,SLOT( localListClicked(QListViewItem*)) );
181// connect( Local_View, SIGNAL( doubleClicked( QListViewItem*)), 181// connect( Local_View, SIGNAL( doubleClicked(QListViewItem*)),
182// this,SLOT( localListClicked(QListViewItem *)) ); 182// this,SLOT( localListClicked(QListViewItem*)) );
183 connect( Local_View, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), 183 connect( Local_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
184 this,SLOT( ListPressed(int, QListViewItem *, const QPoint&, int)) ); 184 this,SLOT( ListPressed(int,QListViewItem*,const QPoint&,int)) );
185 185
186 TabWidget->insertTab( tab, tr( "Local" ) ); 186 TabWidget->insertTab( tab, tr( "Local" ) );
187 187
188 tab_2 = new QWidget( TabWidget, "tab_2" ); 188 tab_2 = new QWidget( TabWidget, "tab_2" );
189 tabLayout_2 = new QGridLayout( tab_2 ); 189 tabLayout_2 = new QGridLayout( tab_2 );
190 tabLayout_2->setSpacing( 2); 190 tabLayout_2->setSpacing( 2);
191 tabLayout_2->setMargin( 2); 191 tabLayout_2->setMargin( 2);
192 192
193 Remote_View = new QListView( tab_2, "Remote_View" ); 193 Remote_View = new QListView( tab_2, "Remote_View" );
194 Remote_View->addColumn( tr("File"),150); 194 Remote_View->addColumn( tr("File"),150);
195 Remote_View->addColumn( tr("Date"),-1); 195 Remote_View->addColumn( tr("Date"),-1);
196// Remote_View->setColumnAlignment(1,QListView::AlignRight); 196// Remote_View->setColumnAlignment(1,QListView::AlignRight);
197 Remote_View->addColumn( tr("Size"),-1); 197 Remote_View->addColumn( tr("Size"),-1);
198 Remote_View->setColumnAlignment(2,QListView::AlignRight); 198 Remote_View->setColumnAlignment(2,QListView::AlignRight);
199 Remote_View->setColumnAlignment(3,QListView::AlignCenter); 199 Remote_View->setColumnAlignment(3,QListView::AlignCenter);
200 Remote_View->addColumn( tr("Dir"),-1); 200 Remote_View->addColumn( tr("Dir"),-1);
201 Remote_View->setColumnAlignment(4,QListView::AlignRight); 201 Remote_View->setColumnAlignment(4,QListView::AlignRight);
202 Remote_View->setAllColumnsShowFocus(TRUE); 202 Remote_View->setAllColumnsShowFocus(TRUE);
203 203
204 Remote_View->setMultiSelection( FALSE); 204 Remote_View->setMultiSelection( FALSE);
205 Remote_View->setSelectionMode(QListView::Extended); 205 Remote_View->setSelectionMode(QListView::Extended);
206 Remote_View->setFocusPolicy(QWidget::ClickFocus); 206 Remote_View->setFocusPolicy(QWidget::ClickFocus);
207 207
208 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold); 208 QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold);
209 209
210 connect( Remote_View, SIGNAL( clicked( QListViewItem*)), 210 connect( Remote_View, SIGNAL( clicked(QListViewItem*)),
211 this,SLOT( remoteListClicked(QListViewItem *)) ); 211 this,SLOT( remoteListClicked(QListViewItem*)) );
212 connect( Remote_View, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), 212 connect( Remote_View, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)),
213 this,SLOT( RemoteListPressed(int, QListViewItem *, const QPoint&, int)) ); 213 this,SLOT( RemoteListPressed(int,QListViewItem*,const QPoint&,int)) );
214 214
215 tabLayout_2->addWidget( Remote_View, 0, 0 ); 215 tabLayout_2->addWidget( Remote_View, 0, 0 );
216 216
217 TabWidget->insertTab( tab_2, tr( "Remote" ) ); 217 TabWidget->insertTab( tab_2, tr( "Remote" ) );
218 218
219 tab_3 = new QWidget( TabWidget, "tab_3" ); 219 tab_3 = new QWidget( TabWidget, "tab_3" );
220 tabLayout_3 = new QGridLayout( tab_3 ); 220 tabLayout_3 = new QGridLayout( tab_3 );
221 tabLayout_3->setSpacing( 2); 221 tabLayout_3->setSpacing( 2);
222 tabLayout_3->setMargin( 2); 222 tabLayout_3->setMargin( 2);
223 223
224 TextLabel1 = new QLabel( tab_3, "TextLabel1" ); 224 TextLabel1 = new QLabel( tab_3, "TextLabel1" );
225 TextLabel1->setText( tr( "Username" ) ); 225 TextLabel1->setText( tr( "Username" ) );
226 tabLayout_3->addMultiCellWidget( TextLabel1, 0, 0, 0, 1 ); 226 tabLayout_3->addMultiCellWidget( TextLabel1, 0, 0, 0, 1 );
227 227
228 UsernameComboBox = new QComboBox( FALSE, tab_3, "UsernameComboBox" ); 228 UsernameComboBox = new QComboBox( FALSE, tab_3, "UsernameComboBox" );
229 UsernameComboBox->setEditable(TRUE); 229 UsernameComboBox->setEditable(TRUE);
230 tabLayout_3->addMultiCellWidget( UsernameComboBox, 1, 1, 0, 1 ); 230 tabLayout_3->addMultiCellWidget( UsernameComboBox, 1, 1, 0, 1 );
231 231
232 connect( UsernameComboBox,SIGNAL(textChanged(const QString &)),this, 232 connect( UsernameComboBox,SIGNAL(textChanged(const QString&)),this,
233 SLOT( UsernameComboBoxEdited(const QString & ) )); 233 SLOT( UsernameComboBoxEdited(const QString&) ));
234 234
235 TextLabel2 = new QLabel( tab_3, "TextLabel2" ); 235 TextLabel2 = new QLabel( tab_3, "TextLabel2" );
236 TextLabel2->setText( tr( "Password" ) ); 236 TextLabel2->setText( tr( "Password" ) );
237 tabLayout_3->addMultiCellWidget( TextLabel2, 0, 0, 2, 3 ); 237 tabLayout_3->addMultiCellWidget( TextLabel2, 0, 0, 2, 3 );
238 238
239 PasswordEdit = new QLineEdit( "", tab_3, "PasswordComboBox" ); 239 PasswordEdit = new QLineEdit( "", tab_3, "PasswordComboBox" );
240 PasswordEdit->setEchoMode(QLineEdit::Password); 240 PasswordEdit->setEchoMode(QLineEdit::Password);
241 tabLayout_3->addMultiCellWidget( PasswordEdit, 1, 1, 2, 3 ); 241 tabLayout_3->addMultiCellWidget( PasswordEdit, 1, 1, 2, 3 );
242 242
243 connect( PasswordEdit,SIGNAL(textChanged(const QString &)),this, 243 connect( PasswordEdit,SIGNAL(textChanged(const QString&)),this,
244 SLOT( PasswordEditEdited(const QString & ) )); 244 SLOT( PasswordEditEdited(const QString&) ));
245 245
246//PasswordEdit->setFixedWidth(85); 246//PasswordEdit->setFixedWidth(85);
247 TextLabel3 = new QLabel( tab_3, "TextLabel3" ); 247 TextLabel3 = new QLabel( tab_3, "TextLabel3" );
248 TextLabel3->setText( tr( "Remote server" ) ); 248 TextLabel3->setText( tr( "Remote server" ) );
249 tabLayout_3->addMultiCellWidget( TextLabel3, 2, 2, 0, 1 ); 249 tabLayout_3->addMultiCellWidget( TextLabel3, 2, 2, 0, 1 );
250 250
251 ServerComboBox = new QComboBox( FALSE, tab_3, "ServerComboBox" ); 251 ServerComboBox = new QComboBox( FALSE, tab_3, "ServerComboBox" );
252 ServerComboBox->setEditable(TRUE); 252 ServerComboBox->setEditable(TRUE);
253 tabLayout_3->addMultiCellWidget( ServerComboBox, 3, 3, 0, 1 ); 253 tabLayout_3->addMultiCellWidget( ServerComboBox, 3, 3, 0, 1 );
254 254
255 connect(ServerComboBox,SIGNAL(activated(int)),this,SLOT(serverComboSelected(int ) )); 255 connect(ServerComboBox,SIGNAL(activated(int)),this,SLOT(serverComboSelected(int) ));
256 connect(ServerComboBox,SIGNAL(textChanged(const QString &)),this, 256 connect(ServerComboBox,SIGNAL(textChanged(const QString&)),this,
257 SLOT(serverComboEdited(const QString & ) )); 257 SLOT(serverComboEdited(const QString&) ));
258 258
259 QLabel *TextLabel5 = new QLabel( tab_3, "TextLabel5" ); 259 QLabel *TextLabel5 = new QLabel( tab_3, "TextLabel5" );
260 TextLabel5->setText( tr( "Remote path" ) ); 260 TextLabel5->setText( tr( "Remote path" ) );
261 tabLayout_3->addMultiCellWidget( TextLabel5, 2, 2, 2, 3 ); 261 tabLayout_3->addMultiCellWidget( TextLabel5, 2, 2, 2, 3 );
262 262
263 263
264 remotePath = new QLineEdit( "/", tab_3, "remotePath" ); 264 remotePath = new QLineEdit( "/", tab_3, "remotePath" );
265 tabLayout_3->addMultiCellWidget( remotePath, 3, 3, 2, 3 ); 265 tabLayout_3->addMultiCellWidget( remotePath, 3, 3, 2, 3 );
266 TextLabel4 = new QLabel( tab_3, "TextLabel4" ); 266 TextLabel4 = new QLabel( tab_3, "TextLabel4" );
267 TextLabel4->setText( tr( "Port" ) ); 267 TextLabel4->setText( tr( "Port" ) );
268 tabLayout_3->addMultiCellWidget( TextLabel4, 4, 4, 0, 1 ); 268 tabLayout_3->addMultiCellWidget( TextLabel4, 4, 4, 0, 1 );
269 269
270 PortSpinBox = new QSpinBox( tab_3, "PortSpinBox" ); 270 PortSpinBox = new QSpinBox( tab_3, "PortSpinBox" );
271 PortSpinBox->setButtonSymbols( QSpinBox::UpDownArrows ); 271 PortSpinBox->setButtonSymbols( QSpinBox::UpDownArrows );
272 PortSpinBox->setMaxValue(32786); 272 PortSpinBox->setMaxValue(32786);
273 tabLayout_3->addMultiCellWidget( PortSpinBox, 4, 4, 1, 1); 273 tabLayout_3->addMultiCellWidget( PortSpinBox, 4, 4, 1, 1);
274 274
275 serverListView = new QListBox( tab_3, "ServerListView" ); 275 serverListView = new QListBox( tab_3, "ServerListView" );
276 tabLayout_3->addMultiCellWidget( serverListView , 5, 5, 0, 5); 276 tabLayout_3->addMultiCellWidget( serverListView , 5, 5, 0, 5);
277 277
278 connect( serverListView, SIGNAL( highlighted( const QString &)), 278 connect( serverListView, SIGNAL( highlighted(const QString&)),
279 this,SLOT( serverListClicked( const QString &) ) ); 279 this,SLOT( serverListClicked(const QString&) ) );
280 280
281 connectServerBtn = new QPushButton( tr("Connect"), tab_3 , "ConnectButton" ); 281 connectServerBtn = new QPushButton( tr("Connect"), tab_3 , "ConnectButton" );
282 tabLayout_3->addMultiCellWidget( connectServerBtn, 6, 6, 0, 1); 282 tabLayout_3->addMultiCellWidget( connectServerBtn, 6, 6, 0, 1);
283 connectServerBtn->setToggleButton(TRUE); 283 connectServerBtn->setToggleButton(TRUE);
284 connect(connectServerBtn,SIGNAL( toggled( bool)),SLOT( connectorBtnToggled(bool) )); 284 connect(connectServerBtn,SIGNAL( toggled(bool)),SLOT( connectorBtnToggled(bool) ));
285 285
286 newServerButton= new QPushButton( tr("Add"), tab_3 , "NewServerButton" ); 286 newServerButton= new QPushButton( tr("Add"), tab_3 , "NewServerButton" );
287 tabLayout_3->addMultiCellWidget( newServerButton, 6, 6, 2, 2); 287 tabLayout_3->addMultiCellWidget( newServerButton, 6, 6, 2, 2);
288 connect( newServerButton,SIGNAL( clicked()),SLOT( NewServer() )); 288 connect( newServerButton,SIGNAL( clicked()),SLOT( NewServer() ));
289 289
290 QPushButton *deleteServerBtn; 290 QPushButton *deleteServerBtn;
291 deleteServerBtn = new QPushButton( tr("Delete"), tab_3 , "OpenButton" ); 291 deleteServerBtn = new QPushButton( tr("Delete"), tab_3 , "OpenButton" );
292 tabLayout_3->addMultiCellWidget( deleteServerBtn, 6, 6, 3, 3); 292 tabLayout_3->addMultiCellWidget( deleteServerBtn, 6, 6, 3, 3);
293 293
294 connect(deleteServerBtn,SIGNAL(clicked()),SLOT(deleteServer())); 294 connect(deleteServerBtn,SIGNAL(clicked()),SLOT(deleteServer()));
295 295
296 296
297 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); 297 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
298 tabLayout_3->addItem( spacer, 5, 0 ); 298 tabLayout_3->addItem( spacer, 5, 0 );
299 299
300 TabWidget->insertTab( tab_3, tr( "Config" ) ); 300 TabWidget->insertTab( tab_3, tr( "Config" ) );
301 301
302#if 0 302#if 0
303 connect(TabWidget,SIGNAL(currentChanged(QWidget *)), 303 connect(TabWidget,SIGNAL(currentChanged(QWidget*)),
304 this,SLOT(tabChanged(QWidget*))); 304 this,SLOT(tabChanged(QWidget*)));
305#endif 305#endif
306 306
307 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 307 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
308 currentDir.setPath( QDir::currentDirPath()); 308 currentDir.setPath( QDir::currentDirPath());
309// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 309// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
310 310
311 currentPathCombo = new QComboBox( FALSE, view, "currentPathCombo" ); 311 currentPathCombo = new QComboBox( FALSE, view, "currentPathCombo" );
312 layout->addMultiCellWidget( currentPathCombo, 3, 3, 0, 4); 312 layout->addMultiCellWidget( currentPathCombo, 3, 3, 0, 4);
313 currentPathCombo ->setFixedWidth(220); 313 currentPathCombo ->setFixedWidth(220);
314 currentPathCombo->setEditable(TRUE); 314 currentPathCombo->setEditable(TRUE);
315 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); 315 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
316 316
317#if 0 317#if 0
318 connect( currentPathCombo, SIGNAL( activated( const QString & ) ), 318 connect( currentPathCombo, SIGNAL( activated(const QString&) ),
319 this, SLOT( currentPathComboActivated( const QString & ) ) ); 319 this, SLOT( currentPathComboActivated(const QString&) ) );
320 320
321 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()), 321 connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()),
322 this,SLOT(currentPathComboChanged())); 322 this,SLOT(currentPathComboChanged()));
323#endif 323#endif
324 ProgressBar = new QProgressBar( view, "ProgressBar" ); 324 ProgressBar = new QProgressBar( view, "ProgressBar" );
325 layout->addMultiCellWidget( ProgressBar, 4, 4, 0, 4); 325 layout->addMultiCellWidget( ProgressBar, 4, 4, 0, 4);
326 ProgressBar->setMaximumHeight(10); 326 ProgressBar->setMaximumHeight(10);
327 filterStr="*"; 327 filterStr="*";
328 b=FALSE; 328 b=FALSE;
329#if 0 329#if 0
330 populateLocalView(); 330 populateLocalView();
331#endif 331#endif
332 readConfig(); 332 readConfig();
333 333
334// ServerComboBox->setCurrentItem(currentServerConfig); 334// ServerComboBox->setCurrentItem(currentServerConfig);
335 335
336 TabWidget->setCurrentPage(2); 336 TabWidget->setCurrentPage(2);
337 qDebug("Constructor done"); 337 qDebug("Constructor done");
338} 338}
339 339
340OpieFtp::~OpieFtp() 340OpieFtp::~OpieFtp()
341{ 341{
342} 342}
343 343
344void OpieFtp::cleanUp() 344void OpieFtp::cleanUp()
345{ 345{
346 if(conn) 346 if(conn)
347 FtpQuit(conn); 347 FtpQuit(conn);
348 QString sfile=QDir::homeDirPath(); 348 QString sfile=QDir::homeDirPath();
349 if(sfile.right(1) != "/") 349 if(sfile.right(1) != "/")
350 sfile+="/._temp"; 350 sfile+="/._temp";
351 else 351 else
352 sfile+="._temp"; 352 sfile+="._temp";
353 QFile file( sfile); 353 QFile file( sfile);
354 if(file.exists()) 354 if(file.exists())
355 file.remove(); 355 file.remove();
356 Config cfg("opieftp"); 356 Config cfg("opieftp");
357 cfg.setGroup("Server"); 357 cfg.setGroup("Server");
358 cfg.writeEntry("currentServer", currentServerConfig); 358 cfg.writeEntry("currentServer", currentServerConfig);
359 359
360 exit(0); 360 exit(0);
361} 361}
362 362
363void OpieFtp::tabChanged(QWidget *) 363void OpieFtp::tabChanged(QWidget *)
364{ 364{
365 if (TabWidget->currentPageIndex() == 0) { 365 if (TabWidget->currentPageIndex() == 0) {
366 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); 366 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath());
367 tabMenu->setItemChecked(tabMenu->idAt(0),TRUE); 367 tabMenu->setItemChecked(tabMenu->idAt(0),TRUE);
368 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE); 368 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE);
369 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE); 369 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE);
370 if(cdUpButton->isHidden()) 370 if(cdUpButton->isHidden())
371 cdUpButton->show(); 371 cdUpButton->show();
372 if(homeButton->isHidden()) 372 if(homeButton->isHidden())
373 homeButton->show(); 373 homeButton->show();
374 374
375 } 375 }
376 if (TabWidget->currentPageIndex() == 1) { 376 if (TabWidget->currentPageIndex() == 1) {
377 currentPathCombo->lineEdit()->setText( currentRemoteDir ); 377 currentPathCombo->lineEdit()->setText( currentRemoteDir );
378 tabMenu->setItemChecked(tabMenu->idAt(1),TRUE); 378 tabMenu->setItemChecked(tabMenu->idAt(1),TRUE);
379 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE); 379 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE);
380 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE); 380 tabMenu->setItemChecked(tabMenu->idAt(2),FALSE);
381 if(cdUpButton->isHidden()) 381 if(cdUpButton->isHidden())
382 cdUpButton->show(); 382 cdUpButton->show();
383 homeButton->hide(); 383 homeButton->hide();
384 384
385 } 385 }
386 if (TabWidget->currentPageIndex() == 2) { 386 if (TabWidget->currentPageIndex() == 2) {
387 tabMenu->setItemChecked(tabMenu->idAt(2),TRUE); 387 tabMenu->setItemChecked(tabMenu->idAt(2),TRUE);
388 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE); 388 tabMenu->setItemChecked(tabMenu->idAt(0),FALSE);
389 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE); 389 tabMenu->setItemChecked(tabMenu->idAt(1),FALSE);
390 cdUpButton->hide(); 390 cdUpButton->hide();
391 homeButton->hide(); 391 homeButton->hide();
392 } 392 }
393} 393}
394 394
395void OpieFtp::newConnection() 395void OpieFtp::newConnection()
396{ 396{
397 UsernameComboBox->lineEdit()->setText(""); 397 UsernameComboBox->lineEdit()->setText("");
398 PasswordEdit->setText( "" ); 398 PasswordEdit->setText( "" );
399 ServerComboBox->lineEdit()->setText( ""); 399 ServerComboBox->lineEdit()->setText( "");
400 remotePath->setText( currentRemoteDir = "/"); 400 remotePath->setText( currentRemoteDir = "/");
401 PortSpinBox->setValue( 21); 401 PortSpinBox->setValue( 21);
402 TabWidget->setCurrentPage(2); 402 TabWidget->setCurrentPage(2);
403} 403}
404 404
405void OpieFtp::serverComboEdited(const QString & ) 405void OpieFtp::serverComboEdited(const QString & )
406{ 406{
407// if( ServerComboBox->text(currentServerConfig) != edit /*edit.isEmpty() */) { 407// if( ServerComboBox->text(currentServerConfig) != edit /*edit.isEmpty() */) {
408// qDebug("ServerComboEdited"); 408// qDebug("ServerComboEdited");
409// // currentServerConfig = -1; 409// // currentServerConfig = -1;
410// } 410// }
411} 411}
412 412
413void OpieFtp::UsernameComboBoxEdited(const QString &) { 413void OpieFtp::UsernameComboBoxEdited(const QString &) {
414// currentServerConfig = -1; 414// currentServerConfig = -1;
415} 415}
416 416
417void OpieFtp::PasswordEditEdited(const QString & ) { 417void OpieFtp::PasswordEditEdited(const QString & ) {
418// currentServerConfig = -1; 418// currentServerConfig = -1;
419} 419}
420 420
421void OpieFtp::connectorBtnToggled(bool On) 421void OpieFtp::connectorBtnToggled(bool On)
422{ 422{
423 if(On) { 423 if(On) {
424 connector(); 424 connector();
425 } else { 425 } else {
426 disConnector(); 426 disConnector();
427 } 427 }
428 428
429} 429}
430 430
431void OpieFtp::connector() 431void OpieFtp::connector()
432{ 432{
433// QCopEnvelope ( "QPE/System", "busy()" ); 433// QCopEnvelope ( "QPE/System", "busy()" );
434// qApp->processEvents(); 434// qApp->processEvents();
435 currentRemoteDir=remotePath->text(); 435 currentRemoteDir=remotePath->text();
436 436
437 if( ServerComboBox->currentText().isEmpty()) { 437 if( ServerComboBox->currentText().isEmpty()) {
438 438
439 QMessageBox::warning(this,tr("Ftp"),tr("Please set the server info"),tr("Ok"),0,0); 439 QMessageBox::warning(this,tr("Ftp"),tr("Please set the server info"),tr("Ok"),0,0);
440 TabWidget->setCurrentPage(2); 440 TabWidget->setCurrentPage(2);
441 ServerComboBox->setFocus(); 441 ServerComboBox->setFocus();
442 connectServerBtn->setOn(FALSE); 442 connectServerBtn->setOn(FALSE);
443 connectServerBtn->setText( tr("Connect")); 443 connectServerBtn->setText( tr("Connect"));
444 return; 444 return;
445 } 445 }
446 446
447 FtpInit(); 447 FtpInit();
448 448
449 TabWidget->setCurrentPage(1); 449 TabWidget->setCurrentPage(1);
450 QString ftp_host = ServerComboBox->currentText(); 450 QString ftp_host = ServerComboBox->currentText();
451 QString ftp_user = UsernameComboBox->currentText(); 451 QString ftp_user = UsernameComboBox->currentText();
452 QString ftp_pass = PasswordEdit->text(); 452 QString ftp_pass = PasswordEdit->text();
453 QString port=PortSpinBox->cleanText(); 453 QString port=PortSpinBox->cleanText();
454 port.stripWhiteSpace(); 454 port.stripWhiteSpace();
455 455
456 Config cfg("opieftp"); 456 Config cfg("opieftp");
457 cfg.setGroup("Server"); 457 cfg.setGroup("Server");
458// int current=cfg.readNumEntry("currentServer", 1); 458// int current=cfg.readNumEntry("currentServer", 1);
459 459
460// if(ftp_host!= cfg.readEntry(QString::number( current))) 460// if(ftp_host!= cfg.readEntry(QString::number( current)))
461// currentServerConfig=-1; 461// currentServerConfig=-1;
462// cfg.setGroup(QString::number(current)); 462// cfg.setGroup(QString::number(current));
463// if( ftp_user != cfg.readEntry("Username")) 463// if( ftp_user != cfg.readEntry("Username"))
464// currentServerConfig=-1; 464// currentServerConfig=-1;
465// if(ftp_pass != cfg.readEntry(cfg.readEntry("Username"))) 465// if(ftp_pass != cfg.readEntry(cfg.readEntry("Username")))
466// currentServerConfig=-1; 466// currentServerConfig=-1;
467 467
468 468
469 if(ftp_host.find("ftp://",0, TRUE) != -1 ) 469 if(ftp_host.find("ftp://",0, TRUE) != -1 )
470 ftp_host=ftp_host.right(ftp_host.length()-6); 470 ftp_host=ftp_host.right(ftp_host.length()-6);
471 ftp_host+=":"+port; 471 ftp_host+=":"+port;
472 472
473 if (!FtpConnect( ftp_host.latin1(), &conn)) { 473 if (!FtpConnect( ftp_host.latin1(), &conn)) {
474 QMessageBox::message(tr("Note"),tr("Unable to connect to\n")+ftp_host); 474 QMessageBox::message(tr("Note"),tr("Unable to connect to\n")+ftp_host);
475 connectServerBtn->setOn(FALSE); 475 connectServerBtn->setOn(FALSE);
476 connectServerBtn->setText( tr("Connect")); 476 connectServerBtn->setText( tr("Connect"));
477 return ; 477 return ;
478 } 478 }
479 479
480 if (!FtpLogin( ftp_user.latin1(), ftp_pass.latin1(),conn )) { 480 if (!FtpLogin( ftp_user.latin1(), ftp_pass.latin1(),conn )) {
481 QString msg; 481 QString msg;
482 msg.sprintf(tr("Unable to log in\n")+"%s",FtpLastResponse(conn)); 482 msg.sprintf(tr("Unable to log in\n")+"%s",FtpLastResponse(conn));
483 msg.replace(QRegExp(":"),"\n"); 483 msg.replace(QRegExp(":"),"\n");
484 QMessageBox::message(tr("Note"),msg); 484 QMessageBox::message(tr("Note"),msg);
485 if(conn) 485 if(conn)
486 FtpQuit(conn); 486 FtpQuit(conn);
487 connectServerBtn->setOn(FALSE); 487 connectServerBtn->setOn(FALSE);
488 connectServerBtn->setText( tr("Connect")); 488 connectServerBtn->setText( tr("Connect"));
489 return ; 489 return ;
490 } 490 }
491 491
492 remoteDirList("/") ; 492 remoteDirList("/") ;
493 setCaption(ftp_host); 493 setCaption(ftp_host);
494 if( currentServerConfig == -1) 494 if( currentServerConfig == -1)
495 writeConfig(); 495 writeConfig();
496 connectServerBtn->setText( tr("Disconnect")); 496 connectServerBtn->setText( tr("Disconnect"));
497// QCopEnvelope ( "QPE/System", "notBusy()" ); 497// QCopEnvelope ( "QPE/System", "notBusy()" );
498} 498}
499 499
500void OpieFtp::disConnector() 500void OpieFtp::disConnector()
501{ 501{
502 if(conn) 502 if(conn)
503 FtpQuit(conn); 503 FtpQuit(conn);
504 setCaption("OpieFtp"); 504 setCaption("OpieFtp");
505 currentRemoteDir="/"; 505 currentRemoteDir="/";
506 Remote_View->clear(); 506 Remote_View->clear();
507 connectServerBtn->setText( tr("Connect")); 507 connectServerBtn->setText( tr("Connect"));
508 connectServerBtn->setOn(FALSE); 508 connectServerBtn->setOn(FALSE);
509 setCaption("OpieFtp"); 509 setCaption("OpieFtp");
510} 510}
511 511
512void OpieFtp::localUpload() 512void OpieFtp::localUpload()
513{ 513{
514 int fsz; 514 int fsz;
515// QCopEnvelope ( "QPE/System", "busy()" ); 515// QCopEnvelope ( "QPE/System", "busy()" );
516// qApp->processEvents(); 516// qApp->processEvents();
517 QList<QListViewItem> * getSelectedItems( QListView * Local_View ); 517 QList<QListViewItem> * getSelectedItems( QListView * Local_View );
518 QListViewItemIterator it( Local_View ); 518 QListViewItemIterator it( Local_View );
519 for ( ; it.current(); ++it ) { 519 for ( ; it.current(); ++it ) {
520 if ( it.current()->isSelected() ) { 520 if ( it.current()->isSelected() ) {
521 QString strItem = it.current()->text(0); 521 QString strItem = it.current()->text(0);
522 QString localFile = currentDir.canonicalPath()+"/"+strItem; 522 QString localFile = currentDir.canonicalPath()+"/"+strItem;
523 QString remoteFile= currentRemoteDir+strItem; 523 QString remoteFile= currentRemoteDir+strItem;
524 QFileInfo fi(localFile); 524 QFileInfo fi(localFile);
525 if( !fi.isDir()) { 525 if( !fi.isDir()) {
526 fsz=fi.size(); 526 fsz=fi.size();
527 ProgressBar->setTotalSteps(fsz); 527 ProgressBar->setTotalSteps(fsz);
528 528
529 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn); 529 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn);
530 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn); 530 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn);
531 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn); 531 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn);
532 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn); 532 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn);
533 qDebug("Put: %s, %s",localFile.latin1(),remoteFile.latin1()); 533 qDebug("Put: %s, %s",localFile.latin1(),remoteFile.latin1());
534 534
535 if( !FtpPut( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) { 535 if( !FtpPut( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) {
536 QString msg; 536 QString msg;
537 msg.sprintf(tr("Unable to upload\n")+"%s",FtpLastResponse(conn)); 537 msg.sprintf(tr("Unable to upload\n")+"%s",FtpLastResponse(conn));
538 msg.replace(QRegExp(":"),"\n"); 538 msg.replace(QRegExp(":"),"\n");
539 QMessageBox::message(tr("Note"),msg); 539 QMessageBox::message(tr("Note"),msg);
540 } 540 }
541 } else { 541 } else {
542 QMessageBox::message(tr("Note"),tr("Cannot upload directories")); 542 QMessageBox::message(tr("Note"),tr("Cannot upload directories"));
543 } 543 }
544 ProgressBar->reset(); 544 ProgressBar->reset();
545 nullifyCallBack(); 545 nullifyCallBack();
546 it.current()->setSelected(FALSE); 546 it.current()->setSelected(FALSE);
547 } //end currentSelected 547 } //end currentSelected
548 } 548 }
549 for ( ; it.current(); ++it ) { 549 for ( ; it.current(); ++it ) {
550 Local_View->clearSelection(); 550 Local_View->clearSelection();
551 } 551 }
552 Local_View->clearFocus(); 552 Local_View->clearFocus();
553 TabWidget->setCurrentPage(1); 553 TabWidget->setCurrentPage(1);
554 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 554 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
555// QCopEnvelope ( "QPE/System", "notBusy()" ); 555// QCopEnvelope ( "QPE/System", "notBusy()" );
556} 556}
557 557
558void OpieFtp::nullifyCallBack() 558void OpieFtp::nullifyCallBack()
559{ 559{
560 FtpOptions(FTPLIB_CALLBACK, 0, conn); 560 FtpOptions(FTPLIB_CALLBACK, 0, conn);
561 FtpOptions(FTPLIB_IDLETIME, 0, conn); 561 FtpOptions(FTPLIB_IDLETIME, 0, conn);
562 FtpOptions(FTPLIB_CALLBACKARG, 0, conn); 562 FtpOptions(FTPLIB_CALLBACKARG, 0, conn);
563 FtpOptions(FTPLIB_CALLBACKBYTES, 0, conn); 563 FtpOptions(FTPLIB_CALLBACKBYTES, 0, conn);
564} 564}
565 565
566void OpieFtp::remoteDownload() 566void OpieFtp::remoteDownload()
567{ 567{
568// qApp->processEvents(); 568// qApp->processEvents();
569 int fsz; 569 int fsz;
570// QCopEnvelope ( "QPE/System", "busy()" ); 570// QCopEnvelope ( "QPE/System", "busy()" );
571 571
572 QList<QListViewItem> * getSelectedItems( QListView * Remote_View ); 572 QList<QListViewItem> * getSelectedItems( QListView * Remote_View );
573 QListViewItemIterator it( Remote_View ); 573 QListViewItemIterator it( Remote_View );
574 for ( ; it.current(); ++it ) { 574 for ( ; it.current(); ++it ) {
575 if ( it.current()->isSelected() ) { 575 if ( it.current()->isSelected() ) {
576 QString strItem = it.current()->text(0); 576 QString strItem = it.current()->text(0);
577// strItem=strItem.right(strItem.length()-1); 577// strItem=strItem.right(strItem.length()-1);
578 QString localFile = currentDir.canonicalPath(); 578 QString localFile = currentDir.canonicalPath();
579 if(localFile.right(1).find("/",0,TRUE) == -1) 579 if(localFile.right(1).find("/",0,TRUE) == -1)
580 localFile += "/"; 580 localFile += "/";
581 localFile += strItem; 581 localFile += strItem;
582// QString localFile = currentDir.canonicalPath()+"/"+strItem; 582// QString localFile = currentDir.canonicalPath()+"/"+strItem;
583 QString remoteFile= currentRemoteDir+strItem; 583 QString remoteFile= currentRemoteDir+strItem;
584 if (!FtpSize( remoteFile.latin1(), &fsz, FTPLIB_ASCII, conn)) 584 if (!FtpSize( remoteFile.latin1(), &fsz, FTPLIB_ASCII, conn))
585 fsz = 0; 585 fsz = 0;
586 QString temp; 586 QString temp;
587 temp.sprintf( remoteFile+" "+" %dkb", fsz); 587 temp.sprintf( remoteFile+" "+" %dkb", fsz);
588 588
589 ProgressBar->setTotalSteps(fsz); 589 ProgressBar->setTotalSteps(fsz);
590 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn); 590 FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn);
591 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn); 591 FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn);
592 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn); 592 FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn);
593 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn); 593 FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn);
594 qDebug("Get: %s, %s",localFile.latin1(),remoteFile.latin1()); 594 qDebug("Get: %s, %s",localFile.latin1(),remoteFile.latin1());
595 595
596 if(!FtpGet( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) { 596 if(!FtpGet( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) {
597 QString msg; 597 QString msg;
598 msg.sprintf(tr("Unable to download \n")+"%s",FtpLastResponse(conn)); 598 msg.sprintf(tr("Unable to download \n")+"%s",FtpLastResponse(conn));
599 msg.replace(QRegExp(":"),"\n"); 599 msg.replace(QRegExp(":"),"\n");
600 QMessageBox::message(tr("Note"),msg); 600 QMessageBox::message(tr("Note"),msg);
601 } 601 }
602 ProgressBar->reset(); 602 ProgressBar->reset();
603 nullifyCallBack(); 603 nullifyCallBack();
604 it.current()->setSelected(FALSE); 604 it.current()->setSelected(FALSE);
605 } 605 }
606 } 606 }
607 for ( ; it.current(); ++it ) { 607 for ( ; it.current(); ++it ) {
608 Remote_View->clearSelection(); 608 Remote_View->clearSelection();
609 } 609 }
610 Remote_View->setFocus(); 610 Remote_View->setFocus();
611 TabWidget->setCurrentPage(0); 611 TabWidget->setCurrentPage(0);
612 populateLocalView(); 612 populateLocalView();
613// QCopEnvelope ( "QPE/System", "notBusy()" ); 613// QCopEnvelope ( "QPE/System", "notBusy()" );
614} 614}
615 615
616bool OpieFtp::remoteDirList(const QString &dir) 616bool OpieFtp::remoteDirList(const QString &dir)
617{ 617{
618 QString tmp = QDir::homeDirPath(); 618 QString tmp = QDir::homeDirPath();
619 if(tmp.right(1) != "/") 619 if(tmp.right(1) != "/")
620 tmp+="/._temp"; 620 tmp+="/._temp";
621 else 621 else
622 tmp+="._temp"; 622 tmp+="._temp";
623// qDebug("Listing remote dir "+tmp); 623// qDebug("Listing remote dir "+tmp);
624// QCopEnvelope ( "QPE/System", "busy()" ); 624// QCopEnvelope ( "QPE/System", "busy()" );
625 if (!FtpDir( tmp.latin1(), dir.latin1(), conn) ) { 625 if (!FtpDir( tmp.latin1(), dir.latin1(), conn) ) {
626 QString msg; 626 QString msg;
627 msg.sprintf(tr("Unable to list the directory\n")+dir+"\n%s",FtpLastResponse(conn) ); 627 msg.sprintf(tr("Unable to list the directory\n")+dir+"\n%s",FtpLastResponse(conn) );
628 msg.replace(QRegExp(":"),"\n"); 628 msg.replace(QRegExp(":"),"\n");
629 QMessageBox::message(tr("Note"),msg); 629 QMessageBox::message(tr("Note"),msg);
630 return false; 630 return false;
631 } 631 }
632 populateRemoteView() ; 632 populateRemoteView() ;
633// QCopEnvelope ( "QPE/System", "notBusy()" ); 633// QCopEnvelope ( "QPE/System", "notBusy()" );
634 return true; 634 return true;
635} 635}
636 636
637bool OpieFtp::remoteChDir(const QString &dir) 637bool OpieFtp::remoteChDir(const QString &dir)
638{ 638{
639// QCopEnvelope ( "QPE/System", "busy()" ); 639// QCopEnvelope ( "QPE/System", "busy()" );
640 if (!FtpChdir( dir.latin1(), conn )) { 640 if (!FtpChdir( dir.latin1(), conn )) {
641 QString msg; 641 QString msg;
642 msg.sprintf(tr("Unable to change directories\n")+dir+"\n%s",FtpLastResponse(conn)); 642 msg.sprintf(tr("Unable to change directories\n")+dir+"\n%s",FtpLastResponse(conn));
643 msg.replace(QRegExp(":"),"\n"); 643 msg.replace(QRegExp(":"),"\n");
644 QMessageBox::message(tr("Note"),msg); 644 QMessageBox::message(tr("Note"),msg);
645// qDebug(msg); 645// qDebug(msg);
646// QCopEnvelope ( "QPE/System", "notBusy()" ); 646// QCopEnvelope ( "QPE/System", "notBusy()" );
647 return FALSE; 647 return FALSE;
648 } 648 }
649// QCopEnvelope ( "QPE/System", "notBusy()" ); 649// QCopEnvelope ( "QPE/System", "notBusy()" );
650 return TRUE; 650 return TRUE;
651} 651}
652 652
653void OpieFtp::populateLocalView() 653void OpieFtp::populateLocalView()
654{ 654{
655 Local_View->clear(); 655 Local_View->clear();
656 currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 656 currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
657 currentDir.setMatchAllDirs(TRUE); 657 currentDir.setMatchAllDirs(TRUE);
658 currentDir.setNameFilter(filterStr); 658 currentDir.setNameFilter(filterStr);
659 QString fileL, fileS, fileDate; 659 QString fileL, fileS, fileDate;
660 bool isDir=FALSE; 660 bool isDir=FALSE;
661 const QFileInfoList *list = currentDir.entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/); 661 const QFileInfoList *list = currentDir.entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/);
662 QFileInfoListIterator it(*list); 662 QFileInfoListIterator it(*list);
663 QFileInfo *fi; 663 QFileInfo *fi;
664 while ( (fi=it.current()) ) { 664 while ( (fi=it.current()) ) {
665 if (fi->isSymLink() ){ 665 if (fi->isSymLink() ){
666 QString symLink=fi->readLink(); 666 QString symLink=fi->readLink();
667 qDebug("Symlink detected "+symLink); 667 qDebug("Symlink detected "+symLink);
668 QFileInfo sym( symLink); 668 QFileInfo sym( symLink);
669 fileS.sprintf( "%10i", sym.size() ); 669 fileS.sprintf( "%10i", sym.size() );
670 fileL.sprintf( "%s -> %s", fi->fileName().data(),sym.absFilePath().data() ); 670 fileL.sprintf( "%s -> %s", fi->fileName().data(),sym.absFilePath().data() );
671 fileDate = sym.lastModified().toString(); 671 fileDate = sym.lastModified().toString();
672 } else { 672 } else {
673 qDebug("Not a dir: "+currentDir.canonicalPath()+fileL); 673 qDebug("Not a dir: "+currentDir.canonicalPath()+fileL);
674 fileS.sprintf( "%10i", fi->size() ); 674 fileS.sprintf( "%10i", fi->size() );
675 fileL.sprintf( "%s",fi->fileName().data() ); 675 fileL.sprintf( "%s",fi->fileName().data() );
676 fileDate= fi->lastModified().toString(); 676 fileDate= fi->lastModified().toString();
677 if( QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+fileL)).exists() ) { 677 if( QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+fileL)).exists() ) {
678 fileL+="/"; 678 fileL+="/";
679 isDir=TRUE; 679 isDir=TRUE;
680 qDebug( fileL); 680 qDebug( fileL);
681 } 681 }
682 } 682 }
683 if(fileL !="./" && fi->exists()) { 683 if(fileL !="./" && fi->exists()) {
684 item = new QListViewItem( Local_View,fileL, fileDate, fileS ); 684 item = new QListViewItem( Local_View,fileL, fileDate, fileS );
685 QPixmap pm; 685 QPixmap pm;
686 686
687 if(isDir || fileL.find("/",0,TRUE) != -1) { 687 if(isDir || fileL.find("/",0,TRUE) != -1) {
688 if( !QDir( fi->filePath() ).isReadable()) 688 if( !QDir( fi->filePath() ).isReadable())
689 pm = Resource::loadPixmap( "lockedfolder" ); 689 pm = Resource::loadPixmap( "lockedfolder" );
690 else 690 else
691 pm= Resource::loadPixmap( "folder" ); 691 pm= Resource::loadPixmap( "folder" );
692 item->setPixmap( 0,pm ); 692 item->setPixmap( 0,pm );
693 } else { 693 } else {
694 if( !fi->isReadable() ) 694 if( !fi->isReadable() )
695 pm = Resource::loadPixmap( "locked" ); 695 pm = Resource::loadPixmap( "locked" );
696 else { 696 else {
697 MimeType mt(fi->filePath()); 697 MimeType mt(fi->filePath());
698 pm=mt.pixmap(); //sets the correct pixmap for mimetype 698 pm=mt.pixmap(); //sets the correct pixmap for mimetype
699 if(pm.isNull()) 699 if(pm.isNull())
700 pm = unknownXpm; 700 pm = unknownXpm;
701 } 701 }
702 } 702 }
703 if( fileL.find("->",0,TRUE) != -1) { 703 if( fileL.find("->",0,TRUE) != -1) {
704 // overlay link image 704 // overlay link image
705 pm= Resource::loadPixmap( "folder" ); 705 pm= Resource::loadPixmap( "folder" );
706 QPixmap lnk = Resource::loadPixmap( "opie/symlink" ); 706 QPixmap lnk = Resource::loadPixmap( "opie/symlink" );
707 QPainter painter( &pm ); 707 QPainter painter( &pm );
708 painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); 708 painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk );
709 pm.setMask( pm.createHeuristicMask( FALSE ) ); 709 pm.setMask( pm.createHeuristicMask( FALSE ) );
710 } 710 }
711 item->setPixmap( 0,pm); 711 item->setPixmap( 0,pm);
712 } 712 }
713 isDir=FALSE; 713 isDir=FALSE;
714 ++it; 714 ++it;
715 } 715 }
716 Local_View->setSorting( 3,FALSE); 716 Local_View->setSorting( 3,FALSE);
717 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath() ); 717 currentPathCombo->lineEdit()->setText( currentDir.canonicalPath() );
718 fillCombo( (const QString &)currentDir); 718 fillCombo( (const QString &)currentDir);
719} 719}
720 720
721bool OpieFtp::populateRemoteView( ) 721bool OpieFtp::populateRemoteView( )
722{ 722{
723// qDebug("populate remoteview"); 723// qDebug("populate remoteview");
724 QString sfile=QDir::homeDirPath(); 724 QString sfile=QDir::homeDirPath();
725 if(sfile.right(1) != "/") 725 if(sfile.right(1) != "/")
726 sfile+="/._temp"; 726 sfile+="/._temp";
727 else 727 else
728 sfile+="._temp"; 728 sfile+="._temp";
729 QFile file( sfile); 729 QFile file( sfile);
730 Remote_View->clear(); 730 Remote_View->clear();
731 QString s, File_Name; 731 QString s, File_Name;
732 QListViewItem *itemDir=NULL, *itemFile=NULL; 732 QListViewItem *itemDir=NULL, *itemFile=NULL;
733 QRegExp monthRe(" [JFMASOND][eapuecoe][brynlgptvc] [ 0-9][0-9] [ 0-9][0-9][:0-9][0-9][0-9] "); 733 QRegExp monthRe(" [JFMASOND][eapuecoe][brynlgptvc] [ 0-9][0-9] [ 0-9][0-9][:0-9][0-9][0-9] ");
734 QString fileL, fileS, fileDate; 734 QString fileL, fileS, fileDate;
735 if ( file.open(IO_ReadOnly)) { 735 if ( file.open(IO_ReadOnly)) {
736 QTextStream t( &file ); // use a text stream 736 QTextStream t( &file ); // use a text stream
737 while ( !t.eof()) { 737 while ( !t.eof()) {
738 s = t.readLine(); 738 s = t.readLine();
739 739
740 if(s.find("total",0,TRUE) == 0) 740 if(s.find("total",0,TRUE) == 0)
741 continue; 741 continue;
742 742
743 int len, month = monthRe.match(s, 0, &len); 743 int len, month = monthRe.match(s, 0, &len);
744 fileDate = s.mid(month + 1, len - 2); // minus spaces 744 fileDate = s.mid(month + 1, len - 2); // minus spaces
745 fileL = s.right(s.length() - month - len); 745 fileL = s.right(s.length() - month - len);
746 if(s.left(1) == "d") 746 if(s.left(1) == "d")
747 fileL = fileL+"/"; 747 fileL = fileL+"/";
748 fileS = s.mid(month - 8, 8); // FIXME 748 fileS = s.mid(month - 8, 8); // FIXME
749 fileS = fileS.stripWhiteSpace(); 749 fileS = fileS.stripWhiteSpace();
750 750
751 if(s.left(1) == "d" || fileL.find("/",0,TRUE) != -1) { 751 if(s.left(1) == "d" || fileL.find("/",0,TRUE) != -1) {
752 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"d"); 752 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"d");
753 item->setPixmap( 0, Resource::loadPixmap( "folder" )); 753 item->setPixmap( 0, Resource::loadPixmap( "folder" ));
754// if(itemDir) 754// if(itemDir)
755 item->moveItem(itemDir); 755 item->moveItem(itemDir);
756 itemDir=item; 756 itemDir=item;
757 } else { 757 } else {
758 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"f"); 758 QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"f");
759 item->setPixmap( 0, Resource::loadPixmap( "fileopen" )); 759 item->setPixmap( 0, Resource::loadPixmap( "fileopen" ));
760// if(itemFile) 760// if(itemFile)
761 item->moveItem(itemDir); 761 item->moveItem(itemDir);
762 item->moveItem(itemFile); 762 item->moveItem(itemFile);
763 itemFile=item; 763 itemFile=item;
764 } 764 }
765 } 765 }
766 QListViewItem * item1 = new QListViewItem( Remote_View, "../"); 766 QListViewItem * item1 = new QListViewItem( Remote_View, "../");
767 item1->setPixmap( 0, Resource::loadPixmap( "folder" )); 767 item1->setPixmap( 0, Resource::loadPixmap( "folder" ));
768 file.close(); 768 file.close();
769 if( file.exists()) 769 if( file.exists())
770 file. remove(); 770 file. remove();
771 } else 771 } else
772 qDebug("temp file not opened successfully "+sfile); 772 qDebug("temp file not opened successfully "+sfile);
773 Remote_View->setSorting( 4,TRUE); 773 Remote_View->setSorting( 4,TRUE);
774 return true; 774 return true;
775} 775}
776 776
777void OpieFtp::remoteListClicked(QListViewItem *selectedItem) 777void OpieFtp::remoteListClicked(QListViewItem *selectedItem)
778{ 778{
779 if( selectedItem) { 779 if( selectedItem) {
780 // if(selectedItem!= NULL) { 780 // if(selectedItem!= NULL) {
781// QCopEnvelope ( "QPE/System", "busy()" ); 781// QCopEnvelope ( "QPE/System", "busy()" );
782 QString oldRemoteCurrentDir = currentRemoteDir; 782 QString oldRemoteCurrentDir = currentRemoteDir;
783 QString strItem=selectedItem->text(0); 783 QString strItem=selectedItem->text(0);
784 strItem=strItem.simplifyWhiteSpace(); 784 strItem=strItem.simplifyWhiteSpace();
785 if(strItem == "../") { // the user wants to go ^ 785 if(strItem == "../") { // the user wants to go ^
786 if( FtpCDUp( conn) == 0) { 786 if( FtpCDUp( conn) == 0) {
787 QString msg; 787 QString msg;
788 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn)); 788 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn));
789 msg.replace(QRegExp(":"),"\n"); 789 msg.replace(QRegExp(":"),"\n");
790 QMessageBox::message(tr("Note"),msg); 790 QMessageBox::message(tr("Note"),msg);
791// qDebug(msg); 791// qDebug(msg);
792 } 792 }
793 char path[256]; 793 char path[256];
794 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string 794 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string
795 QString msg; 795 QString msg;
796 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn)); 796 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn));
797 msg.replace(QRegExp(":"),"\n"); 797 msg.replace(QRegExp(":"),"\n");
798 QMessageBox::message(tr("Note"),msg); 798 QMessageBox::message(tr("Note"),msg);
799// qDebug(msg); 799// qDebug(msg);
800 } 800 }
801 currentRemoteDir=path; 801 currentRemoteDir=path;
802 } else { 802 } else {
803 if(strItem.find("->",0,TRUE) != -1) { //symlink on some servers 803 if(strItem.find("->",0,TRUE) != -1) { //symlink on some servers
804 strItem=strItem.right( strItem.length() - strItem.find("->",0,TRUE) - 2 ); 804 strItem=strItem.right( strItem.length() - strItem.find("->",0,TRUE) - 2 );
805 strItem = strItem.stripWhiteSpace(); 805 strItem = strItem.stripWhiteSpace();
806 currentRemoteDir = strItem; 806 currentRemoteDir = strItem;
807 if( !remoteChDir( (const QString &)strItem)) { 807 if( !remoteChDir( (const QString &)strItem)) {
808 currentRemoteDir = oldRemoteCurrentDir; 808 currentRemoteDir = oldRemoteCurrentDir;
809 strItem=""; 809 strItem="";
810// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir); 810// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir);
811 } 811 }
812 } else if(strItem.find("/",0,TRUE) != -1) { // this is a directory 812 } else if(strItem.find("/",0,TRUE) != -1) { // this is a directory
813 if( !remoteChDir( (const QString &)currentRemoteDir + strItem)) { 813 if( !remoteChDir( (const QString &)currentRemoteDir + strItem)) {
814 currentRemoteDir = oldRemoteCurrentDir; 814 currentRemoteDir = oldRemoteCurrentDir;
815 strItem=""; 815 strItem="";
816// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir); 816// qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir);
817 817
818 } else { 818 } else {
819 currentRemoteDir = currentRemoteDir+strItem; 819 currentRemoteDir = currentRemoteDir+strItem;
820 } 820 }
821 } else { 821 } else {
822// QCopEnvelope ( "QPE/System", "notBusy()" ); 822// QCopEnvelope ( "QPE/System", "notBusy()" );
823 return; 823 return;
824 } 824 }
825 } 825 }
826 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 826 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
827 if(currentRemoteDir.right(1) !="/") 827 if(currentRemoteDir.right(1) !="/")
828 currentRemoteDir +="/"; 828 currentRemoteDir +="/";
829 currentPathCombo->lineEdit()->setText( currentRemoteDir); 829 currentPathCombo->lineEdit()->setText( currentRemoteDir);
830 fillRemoteCombo( (const QString &)currentRemoteDir); 830 fillRemoteCombo( (const QString &)currentRemoteDir);
831// QCopEnvelope ( "QPE/System", "notBusy()" ); 831// QCopEnvelope ( "QPE/System", "notBusy()" );
832 Remote_View->ensureItemVisible(Remote_View->firstChild()); 832 Remote_View->ensureItemVisible(Remote_View->firstChild());
833 833
834 } 834 }
835} 835}
836 836
837void OpieFtp::localListClicked(QListViewItem *selectedItem) 837void OpieFtp::localListClicked(QListViewItem *selectedItem)
838{ 838{
839 if(selectedItem!= NULL) { 839 if(selectedItem!= NULL) {
840 840
841 QString strItem=selectedItem->text(0); 841 QString strItem=selectedItem->text(0);
842 QString strSize=selectedItem->text(1); 842 QString strSize=selectedItem->text(1);
843 strSize=strSize.stripWhiteSpace(); 843 strSize=strSize.stripWhiteSpace();
844 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) { //if symlink 844 if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) { //if symlink
845 // is symlink 845 // is symlink
846 QString strItem2 = strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4); 846 QString strItem2 = strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4);
847 if(QDir(strItem2).exists() ) { 847 if(QDir(strItem2).exists() ) {
848 currentDir.cd(strItem2, TRUE); 848 currentDir.cd(strItem2, TRUE);
849 populateLocalView(); 849 populateLocalView();
850 } 850 }
851 } else { // not a symlink 851 } else { // not a symlink
852 if(strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) { 852 if(strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) {
853 853
854 if(QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem)).exists() ) { 854 if(QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem)).exists() ) {
855 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); 855 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem);
856 currentDir.cd(strItem,FALSE); 856 currentDir.cd(strItem,FALSE);
857 populateLocalView(); 857 populateLocalView();
858 } else { 858 } else {
859 currentDir.cdUp(); 859 currentDir.cdUp();
860 populateLocalView(); 860 populateLocalView();
861 } 861 }
862 if(QDir(strItem).exists()){ 862 if(QDir(strItem).exists()){
863 currentDir.cd(strItem, TRUE); 863 currentDir.cd(strItem, TRUE);
864 populateLocalView(); 864 populateLocalView();
865 } 865 }
866 } else { 866 } else {
867 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); 867 strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem);
868 if( QFile::exists(strItem ) ) { 868 if( QFile::exists(strItem ) ) {
869 // qDebug("upload "+strItem); 869 // qDebug("upload "+strItem);
870 return; 870 return;
871 } 871 }
872 } //end not symlink 872 } //end not symlink
873 chdir(strItem.latin1()); 873 chdir(strItem.latin1());
874 } 874 }
875 Local_View->ensureItemVisible(Local_View->firstChild()); 875 Local_View->ensureItemVisible(Local_View->firstChild());
876 } 876 }
877} 877}
878 878
879void OpieFtp::doLocalCd() 879void OpieFtp::doLocalCd()
880{ 880{
881 localListClicked( Local_View->currentItem()); 881 localListClicked( Local_View->currentItem());
882} 882}
883 883
884void OpieFtp:: doRemoteCd() 884void OpieFtp:: doRemoteCd()
885{ 885{
886 remoteListClicked( Remote_View->currentItem()); 886 remoteListClicked( Remote_View->currentItem());
887 887
888} 888}
889 889
890void OpieFtp::showHidden() 890void OpieFtp::showHidden()
891{ 891{
892 if (!b) { 892 if (!b) {
893 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); 893 currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All);
894 localMenu->setItemChecked(localMenu->idAt(0),TRUE); 894 localMenu->setItemChecked(localMenu->idAt(0),TRUE);
895// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 895// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
896 b=TRUE; 896 b=TRUE;
897 897
898 } else { 898 } else {
899 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); 899 currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All);
900 localMenu->setItemChecked(localMenu->idAt(0),FALSE); 900 localMenu->setItemChecked(localMenu->idAt(0),FALSE);
901// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); 901// currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst);
902 b=FALSE; 902 b=FALSE;
903 } 903 }
904 populateLocalView(); 904 populateLocalView();
905} 905}
906 906
907void OpieFtp::ListPressed( int mouse, QListViewItem *item, const QPoint &, int) 907void OpieFtp::ListPressed( int mouse, QListViewItem *item, const QPoint &, int)
908{ 908{
909// if(item) 909// if(item)
910 if (mouse == 2) { 910 if (mouse == 2) {
911 showLocalMenu(item); 911 showLocalMenu(item);
912 } 912 }
913} 913}
914 914
915void OpieFtp::RemoteListPressed( int mouse, QListViewItem *item, const QPoint &, int ) 915void OpieFtp::RemoteListPressed( int mouse, QListViewItem *item, const QPoint &, int )
916{ 916{
917 if(mouse == 2) { 917 if(mouse == 2) {
918 showRemoteMenu(item); 918 showRemoteMenu(item);
919 } 919 }
920} 920}
921 921
922void OpieFtp::showRemoteMenu(QListViewItem * item) 922void OpieFtp::showRemoteMenu(QListViewItem * item)
923{ 923{
924 QPopupMenu * m;// = new QPopupMenu( Local_View ); 924 QPopupMenu * m;// = new QPopupMenu( Local_View );
925 m = new QPopupMenu(this); 925 m = new QPopupMenu(this);
926 if(item != NULL ) { 926 if(item != NULL ) {
927 if( item->text(0).find("/",0,TRUE) != -1) 927 if( item->text(0).find("/",0,TRUE) != -1)
928 m->insertItem( tr( "Change Directory" ), this, SLOT( doRemoteCd() )); 928 m->insertItem( tr( "Change Directory" ), this, SLOT( doRemoteCd() ));
929 else 929 else
930 m->insertItem( tr( "Download" ), this, SLOT( remoteDownload() )); 930 m->insertItem( tr( "Download" ), this, SLOT( remoteDownload() ));
931 } 931 }
932 m->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() )); 932 m->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() ));
933 m->insertItem( tr("Rescan"), this, SLOT( populateLocalView() )); 933 m->insertItem( tr("Rescan"), this, SLOT( populateLocalView() ));
934 m->insertItem( tr( "Rename" ), this, SLOT( remoteRename() )); 934 m->insertItem( tr( "Rename" ), this, SLOT( remoteRename() ));
935 m->insertSeparator(); 935 m->insertSeparator();
936 m->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); 936 m->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() ));
937 m->exec( QCursor::pos() ); 937 m->exec( QCursor::pos() );
938 delete m; 938 delete m;
939} 939}
940 940
941void OpieFtp::showLocalMenu(QListViewItem * item) 941void OpieFtp::showLocalMenu(QListViewItem * item)
942{ 942{
943 943
944 QPopupMenu *m; 944 QPopupMenu *m;
945 m = new QPopupMenu( this); 945 m = new QPopupMenu( this);
946 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); 946 m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() ));
947 m->insertSeparator(); 947 m->insertSeparator();
948 if(item != NULL ) { 948 if(item != NULL ) {
949 if( item->text(0).find("/",0,TRUE) !=-1) 949 if( item->text(0).find("/",0,TRUE) !=-1)
950 m->insertItem( tr( "Change Directory" ), this, SLOT( doLocalCd() )); 950 m->insertItem( tr( "Change Directory" ), this, SLOT( doLocalCd() ));
951 else 951 else
952 m->insertItem( tr( "Upload" ), this, SLOT( localUpload() )); 952 m->insertItem( tr( "Upload" ), this, SLOT( localUpload() ));
953 } 953 }
954 m->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() )); 954 m->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() ));
955 m->insertItem( tr("Rescan"), this, SLOT( populateRemoteView() )); 955 m->insertItem( tr("Rescan"), this, SLOT( populateRemoteView() ));
956 m->insertItem( tr( "Rename" ), this, SLOT( localRename() )); 956 m->insertItem( tr( "Rename" ), this, SLOT( localRename() ));
957 m->insertSeparator(); 957 m->insertSeparator();
958 m->insertItem( tr( "Delete" ), this, SLOT( localDelete() )); 958 m->insertItem( tr( "Delete" ), this, SLOT( localDelete() ));
959 m->setCheckable(TRUE); 959 m->setCheckable(TRUE);
960 if (b) 960 if (b)
961 m->setItemChecked(m->idAt(0),TRUE); 961 m->setItemChecked(m->idAt(0),TRUE);
962 else 962 else
963 m->setItemChecked(m->idAt(0),FALSE); 963 m->setItemChecked(m->idAt(0),FALSE);
964 964
965 m->exec( QCursor::pos() ); 965 m->exec( QCursor::pos() );
966 delete m; 966 delete m;
967} 967}
968 968
969void OpieFtp::localMakDir() 969void OpieFtp::localMakDir()
970{ 970{
971 InputDialog *fileDlg; 971 InputDialog *fileDlg;
972 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); 972 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
973 fileDlg->exec(); 973 fileDlg->exec();
974 if( fileDlg->result() == 1 ) { 974 if( fileDlg->result() == 1 ) {
975 QString filename = fileDlg->LineEdit1->text(); 975 QString filename = fileDlg->LineEdit1->text();
976 currentDir.mkdir( currentDir.canonicalPath()+"/"+filename); 976 currentDir.mkdir( currentDir.canonicalPath()+"/"+filename);
977 } 977 }
978 populateLocalView(); 978 populateLocalView();
979} 979}
980 980
981void OpieFtp::localDelete() 981void OpieFtp::localDelete()
982{ 982{
983 QList<QListViewItem> * getSelectedItems( QListView * Local_View ); 983 QList<QListViewItem> * getSelectedItems( QListView * Local_View );
984 QListViewItemIterator it( Local_View ); 984 QListViewItemIterator it( Local_View );
985 for ( ; it.current(); ++it ) { 985 for ( ; it.current(); ++it ) {
986 if ( it.current()->isSelected() ) { 986 if ( it.current()->isSelected() ) {
987 QString f = it.current()->text(0); 987 QString f = it.current()->text(0);
988 it.current()->setSelected(FALSE); 988 it.current()->setSelected(FALSE);
989 989
990// QString f = Local_View->currentItem()->text(0); 990// QString f = Local_View->currentItem()->text(0);
991 if(QDir(f).exists() ) { 991 if(QDir(f).exists() ) {
992 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+ 992 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+
993 tr(" ?\nIt must be empty"),tr("Yes"),tr("No"),0,0,1) ) { 993 tr(" ?\nIt must be empty"),tr("Yes"),tr("No"),0,0,1) ) {
994 case 0: { 994 case 0: {
995 f=currentDir.canonicalPath()+"/"+f; 995 f=currentDir.canonicalPath()+"/"+f;
996 QString cmd="rmdir "+f; 996 QString cmd="rmdir "+f;
997 system( cmd.latin1()); 997 system( cmd.latin1());
998 } 998 }
999 break; 999 break;
1000 case 1: 1000 case 1:
1001 // exit 1001 // exit
1002 break; 1002 break;
1003 }; 1003 };
1004 1004
1005 } else { 1005 } else {
1006 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f 1006 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f
1007 +" ?",tr("Yes"),tr("No"),0,0,1) ) { 1007 +" ?",tr("Yes"),tr("No"),0,0,1) ) {
1008 case 0: { 1008 case 0: {
1009 f=currentDir.canonicalPath()+"/"+f; 1009 f=currentDir.canonicalPath()+"/"+f;
1010 QString cmd="rm "+f; 1010 QString cmd="rm "+f;
1011 system( cmd.latin1()); 1011 system( cmd.latin1());
1012 } 1012 }
1013 break; 1013 break;
1014 case 1: 1014 case 1:
1015 // exit 1015 // exit
1016 break; 1016 break;
1017 }; 1017 };
1018 } 1018 }
1019 } 1019 }
1020 } 1020 }
1021 populateLocalView(); 1021 populateLocalView();
1022 1022
1023} 1023}
1024 1024
1025void OpieFtp::remoteMakDir() 1025void OpieFtp::remoteMakDir()
1026{ 1026{
1027 InputDialog *fileDlg; 1027 InputDialog *fileDlg;
1028 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); 1028 fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0);
1029 fileDlg->exec(); 1029 fileDlg->exec();
1030 if( fileDlg->result() == 1 ) { 1030 if( fileDlg->result() == 1 ) {
1031 QString filename = fileDlg->LineEdit1->text();//+".playlist"; 1031 QString filename = fileDlg->LineEdit1->text();//+".playlist";
1032 QString tmp=currentRemoteDir+filename; 1032 QString tmp=currentRemoteDir+filename;
1033// QCopEnvelope ( "QPE/System", "busy()" ); 1033// QCopEnvelope ( "QPE/System", "busy()" );
1034 if(FtpMkdir( tmp.latin1(), conn) == 0) { 1034 if(FtpMkdir( tmp.latin1(), conn) == 0) {
1035 QString msg; 1035 QString msg;
1036 msg.sprintf(tr("Unable to make directory\n")+"%s",FtpLastResponse(conn)); 1036 msg.sprintf(tr("Unable to make directory\n")+"%s",FtpLastResponse(conn));
1037 msg.replace(QRegExp(":"),"\n"); 1037 msg.replace(QRegExp(":"),"\n");
1038 QMessageBox::message(tr("Note"),msg); 1038 QMessageBox::message(tr("Note"),msg);
1039 } 1039 }
1040// QCopEnvelope ( "QPE/System", "notBusy()" ); 1040// QCopEnvelope ( "QPE/System", "notBusy()" );
1041 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1041 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1042 } 1042 }
1043} 1043}
1044 1044
1045void OpieFtp::remoteDelete() 1045void OpieFtp::remoteDelete()
1046{ 1046{
1047 QList<QListViewItem> * getSelectedItems( QListView * Remote_View ); 1047 QList<QListViewItem> * getSelectedItems( QListView * Remote_View );
1048 QListViewItemIterator it( Remote_View ); 1048 QListViewItemIterator it( Remote_View );
1049 for ( ; it.current(); ++it ) { 1049 for ( ; it.current(); ++it ) {
1050 if ( it.current()->isSelected() ) { 1050 if ( it.current()->isSelected() ) {
1051 QString f = it.current()->text(0); 1051 QString f = it.current()->text(0);
1052// QString f = Remote_View->currentItem()->text(0); 1052// QString f = Remote_View->currentItem()->text(0);
1053// QCopEnvelope ( "QPE/System", "busy()" ); 1053// QCopEnvelope ( "QPE/System", "busy()" );
1054 if( f.right(1) =="/") { 1054 if( f.right(1) =="/") {
1055 QString path= currentRemoteDir+f; 1055 QString path= currentRemoteDir+f;
1056 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?" 1056 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?"
1057 ,tr("Yes"),tr("No"),0,0,1) ) { 1057 ,tr("Yes"),tr("No"),0,0,1) ) {
1058 case 0: { 1058 case 0: {
1059 f=currentDir.canonicalPath()+"/"+f; 1059 f=currentDir.canonicalPath()+"/"+f;
1060 if(FtpRmdir( path.latin1(), conn) ==0) { 1060 if(FtpRmdir( path.latin1(), conn) ==0) {
1061 QString msg; 1061 QString msg;
1062 msg.sprintf(tr("Unable to remove directory\n")+"%s",FtpLastResponse(conn)); 1062 msg.sprintf(tr("Unable to remove directory\n")+"%s",FtpLastResponse(conn));
1063 msg.replace(QRegExp(":"),"\n"); 1063 msg.replace(QRegExp(":"),"\n");
1064 QMessageBox::message(tr("Note"),msg); 1064 QMessageBox::message(tr("Note"),msg);
1065 } 1065 }
1066 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1066 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1067 } 1067 }
1068 break; 1068 break;
1069 }; 1069 };
1070 } else { 1070 } else {
1071 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?" 1071 switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?"
1072 ,tr("Yes"),tr("No"),0,0,1) ) { 1072 ,tr("Yes"),tr("No"),0,0,1) ) {
1073 case 0: { 1073 case 0: {
1074 QString path= currentRemoteDir+f; 1074 QString path= currentRemoteDir+f;
1075 if(FtpDelete( path.latin1(), conn)==0) { 1075 if(FtpDelete( path.latin1(), conn)==0) {
1076 QString msg; 1076 QString msg;
1077 msg.sprintf(tr("Unable to delete file\n")+"%s",FtpLastResponse(conn)); 1077 msg.sprintf(tr("Unable to delete file\n")+"%s",FtpLastResponse(conn));
1078 msg.replace(QRegExp(":"),"\n"); 1078 msg.replace(QRegExp(":"),"\n");
1079 QMessageBox::message(tr("Note"),msg); 1079 QMessageBox::message(tr("Note"),msg);
1080 } 1080 }
1081 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1081 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1082 } 1082 }
1083 break; 1083 break;
1084 }; 1084 };
1085 } 1085 }
1086 } 1086 }
1087 } 1087 }
1088// QCopEnvelope ( "QPE/System", "notBusy()" ); 1088// QCopEnvelope ( "QPE/System", "notBusy()" );
1089} 1089}
1090 1090
1091void OpieFtp::remoteRename() 1091void OpieFtp::remoteRename()
1092{ 1092{
1093 QString curFile = Remote_View->currentItem()->text(0); 1093 QString curFile = Remote_View->currentItem()->text(0);
1094 InputDialog *fileDlg; 1094 InputDialog *fileDlg;
1095 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0); 1095 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0);
1096 fileDlg->setTextEdit((const QString &)curFile); 1096 fileDlg->setTextEdit((const QString &)curFile);
1097 fileDlg->exec(); 1097 fileDlg->exec();
1098 if( fileDlg->result() == 1 ) { 1098 if( fileDlg->result() == 1 ) {
1099 QString oldName = currentRemoteDir +"/"+ curFile; 1099 QString oldName = currentRemoteDir +"/"+ curFile;
1100 QString newName = currentRemoteDir +"/"+ fileDlg->LineEdit1->text();//+".playlist"; 1100 QString newName = currentRemoteDir +"/"+ fileDlg->LineEdit1->text();//+".playlist";
1101// QCopEnvelope ( "QPE/System", "busy()" ); 1101// QCopEnvelope ( "QPE/System", "busy()" );
1102 if(FtpRename( oldName.latin1(), newName.latin1(),conn) == 0) { 1102 if(FtpRename( oldName.latin1(), newName.latin1(),conn) == 0) {
1103 QString msg; 1103 QString msg;
1104 msg.sprintf(tr("Unable to rename file\n")+"%s",FtpLastResponse(conn)); 1104 msg.sprintf(tr("Unable to rename file\n")+"%s",FtpLastResponse(conn));
1105 msg.replace(QRegExp(":"),"\n"); 1105 msg.replace(QRegExp(":"),"\n");
1106 QMessageBox::message(tr("Note"),msg); 1106 QMessageBox::message(tr("Note"),msg);
1107 } 1107 }
1108// QCopEnvelope ( "QPE/System", "notBusy()" ); 1108// QCopEnvelope ( "QPE/System", "notBusy()" );
1109 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1109 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1110 } 1110 }
1111} 1111}
1112 1112
1113void OpieFtp::localRename() 1113void OpieFtp::localRename()
1114{ 1114{
1115 QString curFile = Local_View->currentItem()->text(0); 1115 QString curFile = Local_View->currentItem()->text(0);
1116 InputDialog *fileDlg; 1116 InputDialog *fileDlg;
1117 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0); 1117 fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0);
1118 fileDlg->setTextEdit((const QString &)curFile); 1118 fileDlg->setTextEdit((const QString &)curFile);
1119 fileDlg->exec(); 1119 fileDlg->exec();
1120 if( fileDlg->result() == 1 ) { 1120 if( fileDlg->result() == 1 ) {
1121 QString oldname = currentDir.canonicalPath() + "/" + curFile; 1121 QString oldname = currentDir.canonicalPath() + "/" + curFile;
1122 QString newName = currentDir.canonicalPath() + "/" + fileDlg->LineEdit1->text();//+".playlist"; 1122 QString newName = currentDir.canonicalPath() + "/" + fileDlg->LineEdit1->text();//+".playlist";
1123 if( rename(oldname.latin1(), newName.latin1())== -1) 1123 if( rename(oldname.latin1(), newName.latin1())== -1)
1124 QMessageBox::message(tr("Note"),tr("Could not rename")); 1124 QMessageBox::message(tr("Note"),tr("Could not rename"));
1125 } 1125 }
1126 populateLocalView(); 1126 populateLocalView();
1127} 1127}
1128 1128
1129void OpieFtp::currentPathComboActivated(const QString & currentPath) { 1129void OpieFtp::currentPathComboActivated(const QString & currentPath) {
1130 if (TabWidget->currentPageIndex() == 0) { 1130 if (TabWidget->currentPageIndex() == 0) {
1131 chdir( currentPath.latin1() ); 1131 chdir( currentPath.latin1() );
1132 currentDir.cd( currentPath, TRUE); 1132 currentDir.cd( currentPath, TRUE);
1133 populateLocalView(); 1133 populateLocalView();
1134 update(); 1134 update();
1135 } else { 1135 } else {
1136// chdir( currentPath.latin1() ); 1136// chdir( currentPath.latin1() );
1137// currentDir.cd( currentPath, TRUE); 1137// currentDir.cd( currentPath, TRUE);
1138// populateList(); 1138// populateList();
1139// update(); 1139// update();
1140 1140
1141 } 1141 }
1142} 1142}
1143 1143
1144void OpieFtp::fillCombo(const QString &currentPath) { 1144void OpieFtp::fillCombo(const QString &currentPath) {
1145 1145
1146 currentPathCombo->lineEdit()->setText(currentPath); 1146 currentPathCombo->lineEdit()->setText(currentPath);
1147 if( localDirPathStringList.grep(currentPath,TRUE).isEmpty() ) { 1147 if( localDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
1148 currentPathCombo->clear(); 1148 currentPathCombo->clear();
1149 localDirPathStringList.prepend(currentPath ); 1149 localDirPathStringList.prepend(currentPath );
1150 currentPathCombo->insertStringList( localDirPathStringList,-1); 1150 currentPathCombo->insertStringList( localDirPathStringList,-1);
1151 } 1151 }
1152 currentPathCombo->lineEdit()->setText(currentPath); 1152 currentPathCombo->lineEdit()->setText(currentPath);
1153 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) { 1153 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
1154 currentPathCombo->clear(); 1154 currentPathCombo->clear();
1155 remoteDirPathStringList.prepend(currentPath ); 1155 remoteDirPathStringList.prepend(currentPath );
1156 currentPathCombo->insertStringList( remoteDirPathStringList,-1); 1156 currentPathCombo->insertStringList( remoteDirPathStringList,-1);
1157 } 1157 }
1158} 1158}
1159 1159
1160void OpieFtp::fillRemoteCombo(const QString &currentPath) { 1160void OpieFtp::fillRemoteCombo(const QString &currentPath) {
1161 1161
1162 currentPathCombo->lineEdit()->setText(currentPath); 1162 currentPathCombo->lineEdit()->setText(currentPath);
1163 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) { 1163 if( remoteDirPathStringList.grep(currentPath,TRUE).isEmpty() ) {
1164 currentPathCombo->clear(); 1164 currentPathCombo->clear();
1165 remoteDirPathStringList.prepend(currentPath ); 1165 remoteDirPathStringList.prepend(currentPath );
1166 currentPathCombo->insertStringList( remoteDirPathStringList,-1); 1166 currentPathCombo->insertStringList( remoteDirPathStringList,-1);
1167 } 1167 }
1168} 1168}
1169 1169
1170void OpieFtp::currentPathComboChanged() 1170void OpieFtp::currentPathComboChanged()
1171{ 1171{
1172 QString oldRemoteCurrentDir = currentRemoteDir; 1172 QString oldRemoteCurrentDir = currentRemoteDir;
1173// qDebug("oldRemoteCurrentDir "+oldRemoteCurrentDir); 1173// qDebug("oldRemoteCurrentDir "+oldRemoteCurrentDir);
1174 if (TabWidget->currentPageIndex() == 0) { 1174 if (TabWidget->currentPageIndex() == 0) {
1175 if(QDir( currentPathCombo->lineEdit()->text()).exists()) { 1175 if(QDir( currentPathCombo->lineEdit()->text()).exists()) {
1176 currentDir.setPath( currentPathCombo->lineEdit()->text() ); 1176 currentDir.setPath( currentPathCombo->lineEdit()->text() );
1177 populateLocalView(); 1177 populateLocalView();
1178 } else { 1178 } else {
1179 QMessageBox::message(tr("Note"),tr("That directory does not exist")); 1179 QMessageBox::message(tr("Note"),tr("That directory does not exist"));
1180 } 1180 }
1181 } 1181 }
1182 if (TabWidget->currentPageIndex() == 1) { 1182 if (TabWidget->currentPageIndex() == 1) {
1183 currentRemoteDir = currentPathCombo->lineEdit()->text(); 1183 currentRemoteDir = currentPathCombo->lineEdit()->text();
1184 if(currentRemoteDir.right(1) !="/") { 1184 if(currentRemoteDir.right(1) !="/") {
1185 currentRemoteDir = currentRemoteDir +"/"; 1185 currentRemoteDir = currentRemoteDir +"/";
1186 currentPathCombo->lineEdit()->setText( currentRemoteDir ); 1186 currentPathCombo->lineEdit()->setText( currentRemoteDir );
1187 } 1187 }
1188 if( !remoteChDir( (const QString &)currentRemoteDir) ) { 1188 if( !remoteChDir( (const QString &)currentRemoteDir) ) {
1189 currentRemoteDir = oldRemoteCurrentDir; 1189 currentRemoteDir = oldRemoteCurrentDir;
1190 currentPathCombo->lineEdit()->setText( currentRemoteDir ); 1190 currentPathCombo->lineEdit()->setText( currentRemoteDir );
1191 } 1191 }
1192 1192
1193 remoteDirList( (const QString &)currentRemoteDir); 1193 remoteDirList( (const QString &)currentRemoteDir);
1194 } 1194 }
1195} 1195}
1196 1196
1197void OpieFtp::switchToLocalTab() 1197void OpieFtp::switchToLocalTab()
1198{ 1198{
1199 TabWidget->setCurrentPage(0); 1199 TabWidget->setCurrentPage(0);
1200} 1200}
1201 1201
1202void OpieFtp::switchToRemoteTab() 1202void OpieFtp::switchToRemoteTab()
1203{ 1203{
1204 TabWidget->setCurrentPage(1); 1204 TabWidget->setCurrentPage(1);
1205} 1205}
1206 1206
1207void OpieFtp::switchToConfigTab() 1207void OpieFtp::switchToConfigTab()
1208{ 1208{
1209 TabWidget->setCurrentPage(2); 1209 TabWidget->setCurrentPage(2);
1210} 1210}
1211 1211
1212void OpieFtp::readConfig() 1212void OpieFtp::readConfig()
1213{ 1213{
1214 fillCombos(); 1214 fillCombos();
1215 Config cfg("opieftp"); 1215 Config cfg("opieftp");
1216 cfg.setGroup("Server"); 1216 cfg.setGroup("Server");
1217 currentServerConfig = cfg.readNumEntry("currentServer", -1); 1217 currentServerConfig = cfg.readNumEntry("currentServer", -1);
1218 1218
1219// qDebug("Reading %d", currentServerConfig); 1219// qDebug("Reading %d", currentServerConfig);
1220 serverComboSelected( currentServerConfig-1); 1220 serverComboSelected( currentServerConfig-1);
1221 1221
1222} 1222}
1223 1223
1224void OpieFtp::writeConfig() 1224void OpieFtp::writeConfig()
1225{ 1225{
1226 qDebug("write config"); 1226 qDebug("write config");
1227 Config cfg("opieftp"); 1227 Config cfg("opieftp");
1228 cfg.setGroup("Server"); 1228 cfg.setGroup("Server");
1229 1229
1230 QString username, remoteServerStr, remotePathStr, password, port, temp; 1230 QString username, remoteServerStr, remotePathStr, password, port, temp;
1231 1231
1232 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1232 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1233 1233
1234 if( currentServerConfig == -1) { 1234 if( currentServerConfig == -1) {
1235 1235
1236 for (int i = 1; i <= numberOfEntries; i++) { 1236 for (int i = 1; i <= numberOfEntries; i++) {
1237 temp.setNum(i); 1237 temp.setNum(i);
1238 cfg.setGroup("Server"); 1238 cfg.setGroup("Server");
1239 QString tempStr = cfg.readEntry( temp,""); 1239 QString tempStr = cfg.readEntry( temp,"");
1240 } 1240 }
1241 1241
1242 temp.setNum( numberOfEntries + 1); 1242 temp.setNum( numberOfEntries + 1);
1243 cfg.setGroup("Server"); 1243 cfg.setGroup("Server");
1244 1244
1245 remoteServerStr = cfg.readEntry( temp,""); 1245 remoteServerStr = cfg.readEntry( temp,"");
1246 1246
1247 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE); 1247 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
1248 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider); 1248 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider);
1249 1249
1250 temp.setNum(numberOfEntries+1); 1250 temp.setNum(numberOfEntries+1);
1251 cfg.setGroup("Server"); 1251 cfg.setGroup("Server");
1252 1252
1253 cfg.writeEntry( temp, ServerComboBox->currentText() +":"+PortSpinBox->cleanText() ); 1253 cfg.writeEntry( temp, ServerComboBox->currentText() +":"+PortSpinBox->cleanText() );
1254 cfg.writeEntry("currentServer", numberOfEntries+1); 1254 cfg.writeEntry("currentServer", numberOfEntries+1);
1255 1255
1256 currentServerConfig = numberOfEntries+1; 1256 currentServerConfig = numberOfEntries+1;
1257 qDebug("setting currentserverconfig to %d", currentServerConfig); 1257 qDebug("setting currentserverconfig to %d", currentServerConfig);
1258 1258
1259 cfg.setGroup(temp); 1259 cfg.setGroup(temp);
1260 if(!newServerName.isEmpty()) 1260 if(!newServerName.isEmpty())
1261 cfg.writeEntry("ServerName", newServerName); 1261 cfg.writeEntry("ServerName", newServerName);
1262 1262
1263 cfg.writeEntry("RemotePath", remotePath->text()); 1263 cfg.writeEntry("RemotePath", remotePath->text());
1264 1264
1265 cfg.writeEntry("Username", UsernameComboBox->currentText()); 1265 cfg.writeEntry("Username", UsernameComboBox->currentText());
1266 1266
1267 cfg.writeEntryCrypt( UsernameComboBox->currentText(), PasswordEdit->text()); 1267 cfg.writeEntryCrypt( UsernameComboBox->currentText(), PasswordEdit->text());
1268 cfg.setGroup("Server"); 1268 cfg.setGroup("Server");
1269 1269
1270 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries + 1 )); 1270 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries + 1 ));
1271 1271
1272 } 1272 }
1273} 1273}
1274 1274
1275void OpieFtp::clearCombos() { 1275void OpieFtp::clearCombos() {
1276 qDebug("clearing"); 1276 qDebug("clearing");
1277 ServerComboBox->clear(); 1277 ServerComboBox->clear();
1278 UsernameComboBox->clear(); 1278 UsernameComboBox->clear();
1279 PasswordEdit->clear(); 1279 PasswordEdit->clear();
1280 serverListView->clear(); 1280 serverListView->clear();
1281} 1281}
1282 1282
1283 1283
1284void OpieFtp::fillCombos() 1284void OpieFtp::fillCombos()
1285{ 1285{
1286 clearCombos(); 1286 clearCombos();
1287 1287
1288 Config cfg("opieftp"); 1288 Config cfg("opieftp");
1289 cfg.setGroup("Server"); 1289 cfg.setGroup("Server");
1290 QString username, remoteServerStr, remotePathStr, password, port, temp; 1290 QString username, remoteServerStr, remotePathStr, password, port, temp;
1291 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1291 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1292 1292
1293 for (int i = 1; i <= numberOfEntries; i++) { 1293 for (int i = 1; i <= numberOfEntries; i++) {
1294 temp.setNum(i); 1294 temp.setNum(i);
1295 qDebug(temp); 1295 qDebug(temp);
1296 cfg.setGroup("Server"); 1296 cfg.setGroup("Server");
1297 remoteServerStr = cfg.readEntry( temp,""); 1297 remoteServerStr = cfg.readEntry( temp,"");
1298 qDebug( remoteServerStr); 1298 qDebug( remoteServerStr);
1299 1299
1300 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE); 1300 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
1301 port = remoteServerStr.right( divider - 1); 1301 port = remoteServerStr.right( divider - 1);
1302 bool ok; 1302 bool ok;
1303 PortSpinBox->setValue( port.toInt(&ok,10)); 1303 PortSpinBox->setValue( port.toInt(&ok,10));
1304 1304
1305 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider); 1305 remoteServerStr = remoteServerStr.left(remoteServerStr.length()-divider);
1306 qDebug( "remote server string "+remoteServerStr); 1306 qDebug( "remote server string "+remoteServerStr);
1307 ServerComboBox->insertItem( remoteServerStr ); 1307 ServerComboBox->insertItem( remoteServerStr );
1308 1308
1309 cfg.setGroup(temp); 1309 cfg.setGroup(temp);
1310 1310
1311 username = cfg.readEntry(temp); 1311 username = cfg.readEntry(temp);
1312 UsernameComboBox->insertItem(username); 1312 UsernameComboBox->insertItem(username);
1313 password = cfg.readEntryCrypt(username,""); 1313 password = cfg.readEntryCrypt(username,"");
1314 PasswordEdit->setText(password); 1314 PasswordEdit->setText(password);
1315 1315
1316 serverListView->insertItem( cfg.readEntry("ServerName")); 1316 serverListView->insertItem( cfg.readEntry("ServerName"));
1317 } 1317 }
1318} 1318}
1319 1319
1320 1320
1321void OpieFtp::serverComboSelected(int index) 1321void OpieFtp::serverComboSelected(int index)
1322{ 1322{
1323 currentServerConfig = index+1; 1323 currentServerConfig = index+1;
1324 qDebug("server combo selected %d", index+1); 1324 qDebug("server combo selected %d", index+1);
1325 QString username, remoteServerStr, remotePathStr, password, port, temp; 1325 QString username, remoteServerStr, remotePathStr, password, port, temp;
1326// remoteServerStr = ServerComboBox->text(index); 1326// remoteServerStr = ServerComboBox->text(index);
1327 1327
1328 Config cfg("opieftp"); 1328 Config cfg("opieftp");
1329 cfg.setGroup("Server"); 1329 cfg.setGroup("Server");
1330// int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1330// int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1331 1331
1332 temp.setNum(index+1); 1332 temp.setNum(index+1);
1333 remoteServerStr = cfg.readEntry( temp,""); 1333 remoteServerStr = cfg.readEntry( temp,"");
1334 1334
1335 qDebug("Group" +temp); 1335 qDebug("Group" +temp);
1336 cfg.setGroup(temp); 1336 cfg.setGroup(temp);
1337// qDebug(temp); 1337// qDebug(temp);
1338 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE); 1338 int divider = remoteServerStr.length() - remoteServerStr.find(":",0,TRUE);
1339 port = remoteServerStr.right( divider - 1); 1339 port = remoteServerStr.right( divider - 1);
1340 bool ok; 1340 bool ok;
1341 int portInt = port.toInt(&ok,10); 1341 int portInt = port.toInt(&ok,10);
1342 if( portInt == 0) portInt = 21; 1342 if( portInt == 0) portInt = 21;
1343 1343
1344 ServerComboBox->lineEdit()->setText(remoteServerStr.left( remoteServerStr.find(":",0,TRUE))); 1344 ServerComboBox->lineEdit()->setText(remoteServerStr.left( remoteServerStr.find(":",0,TRUE)));
1345 1345
1346 PortSpinBox->setValue( portInt); 1346 PortSpinBox->setValue( portInt);
1347 1347
1348 remotePath->setText(cfg.readEntry("RemotePath", "/")); 1348 remotePath->setText(cfg.readEntry("RemotePath", "/"));
1349 1349
1350 username = cfg.readEntry("Username", "anonymous"); 1350 username = cfg.readEntry("Username", "anonymous");
1351 UsernameComboBox->lineEdit()->setText(username); 1351 UsernameComboBox->lineEdit()->setText(username);
1352 qDebug(username); 1352 qDebug(username);
1353// qDebug("Password is "+cfg.readEntryCrypt(username, "me@opieftp.org")); 1353// qDebug("Password is "+cfg.readEntryCrypt(username, "me@opieftp.org"));
1354 PasswordEdit->setText(cfg.readEntryCrypt(username, "me@opieftp.org")); 1354 PasswordEdit->setText(cfg.readEntryCrypt(username, "me@opieftp.org"));
1355// UsernameComboBox 1355// UsernameComboBox
1356// PasswordEdit 1356// PasswordEdit
1357 1357
1358 cfg.setGroup("Server"); 1358 cfg.setGroup("Server");
1359 temp.sprintf("%d",currentServerConfig); 1359 temp.sprintf("%d",currentServerConfig);
1360 cfg.writeEntry("currentServer", temp); 1360 cfg.writeEntry("currentServer", temp);
1361 1361
1362 fuckeduphack = TRUE; 1362 fuckeduphack = TRUE;
1363 serverListView->setCurrentItem( index); 1363 serverListView->setCurrentItem( index);
1364 fuckeduphack=FALSE; 1364 fuckeduphack=FALSE;
1365 qDebug("server list set selected %d",index); 1365 qDebug("server list set selected %d",index);
1366 update(); 1366 update();
1367} 1367}
1368 1368
1369void OpieFtp::deleteServer() 1369void OpieFtp::deleteServer()
1370{ 1370{
1371 QString username, remoteServerStr, remotePathStr, password, port, temp, servername; 1371 QString username, remoteServerStr, remotePathStr, password, port, temp, servername;
1372 remoteServerStr = ServerComboBox->currentText( ); 1372 remoteServerStr = ServerComboBox->currentText( );
1373 username = UsernameComboBox->currentText(); 1373 username = UsernameComboBox->currentText();
1374 servername=serverListView->currentText(); 1374 servername=serverListView->currentText();
1375 1375
1376 Config cfg("opieftp"); 1376 Config cfg("opieftp");
1377 cfg.setGroup("Server"); 1377 cfg.setGroup("Server");
1378 QString tempname; 1378 QString tempname;
1379 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1379 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1380 1380
1381 for (int i = 1; i <= numberOfEntries; i++) { 1381 for (int i = 1; i <= numberOfEntries; i++) {
1382 temp.setNum(i); 1382 temp.setNum(i);
1383// cfg.setGroup("Server"); 1383// cfg.setGroup("Server");
1384 cfg.setGroup(QString::number(i)); 1384 cfg.setGroup(QString::number(i));
1385 tempname=cfg.readEntry( "ServerName",""); 1385 tempname=cfg.readEntry( "ServerName","");
1386 1386
1387 if( tempname.find( servername,0,TRUE) != -1 ) { 1387 if( tempname.find( servername,0,TRUE) != -1 ) {
1388// servername.find( cfg.readEntry("ServerName")) != -1 && 1388// servername.find( cfg.readEntry("ServerName")) != -1 &&
1389// remoteServerStr.find( cfg.readEntry("RemotePath")) != -1 && 1389// remoteServerStr.find( cfg.readEntry("RemotePath")) != -1 &&
1390// username.find( cfg.readEntry("Username")) != -1) { 1390// username.find( cfg.readEntry("Username")) != -1) {
1391 1391
1392 serverListView->removeItem(i); 1392 serverListView->removeItem(i);
1393 1393
1394 qDebug("OK DELETE "+tempname); 1394 qDebug("OK DELETE "+tempname);
1395 cfg.removeEntry(QString::number(i)); 1395 cfg.removeEntry(QString::number(i));
1396 for ( ; i <= numberOfEntries; i++) { 1396 for ( ; i <= numberOfEntries; i++) {
1397 cfg.setGroup("Server"); 1397 cfg.setGroup("Server");
1398 cfg.writeEntry("Server", QString::number(numberOfEntries + 1 )); 1398 cfg.writeEntry("Server", QString::number(numberOfEntries + 1 ));
1399 1399
1400 cfg.setGroup(QString::number(i+1)); //get next server config 1400 cfg.setGroup(QString::number(i+1)); //get next server config
1401 servername=cfg.readEntry("ServerName"); 1401 servername=cfg.readEntry("ServerName");
1402 remoteServerStr=cfg.readEntry("RemotePath"); 1402 remoteServerStr=cfg.readEntry("RemotePath");
1403 username=cfg.readEntry("Username"); 1403 username=cfg.readEntry("Username");
1404 password=cfg.readEntryCrypt( username); 1404 password=cfg.readEntryCrypt( username);
1405 1405
1406 cfg.setGroup(QString::number(i)); 1406 cfg.setGroup(QString::number(i));
1407 1407
1408 cfg.writeEntry("RemotePath", remoteServerStr); 1408 cfg.writeEntry("RemotePath", remoteServerStr);
1409 cfg.writeEntry("ServerName", servername); 1409 cfg.writeEntry("ServerName", servername);
1410 cfg.writeEntry("Username", username); 1410 cfg.writeEntry("Username", username);
1411 cfg.writeEntryCrypt( username, password); 1411 cfg.writeEntryCrypt( username, password);
1412 1412
1413 } 1413 }
1414 cfg.setGroup("Server"); 1414 cfg.setGroup("Server");
1415 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries - 1 )); 1415 cfg.writeEntry("numberOfEntries", QString::number(numberOfEntries - 1 ));
1416 } 1416 }
1417 } 1417 }
1418 cfg.setGroup(QString::number(numberOfEntries)); 1418 cfg.setGroup(QString::number(numberOfEntries));
1419 cfg.removeEntry("Server"); 1419 cfg.removeEntry("Server");
1420 cfg.removeEntry("RemotePath"); 1420 cfg.removeEntry("RemotePath");
1421 cfg.removeEntry("ServerName"); 1421 cfg.removeEntry("ServerName");
1422 username=cfg.readEntry("Username"); 1422 username=cfg.readEntry("Username");
1423 cfg.removeEntry("Username"); 1423 cfg.removeEntry("Username");
1424 cfg.removeEntry(username); 1424 cfg.removeEntry(username);
1425 1425
1426 currentServerConfig=currentServerConfig-1; 1426 currentServerConfig=currentServerConfig-1;
1427 1427
1428 fillCombos(); 1428 fillCombos();
1429 update(); 1429 update();
1430} 1430}
1431 1431
1432void OpieFtp::upDir() 1432void OpieFtp::upDir()
1433{ 1433{
1434 if (TabWidget->currentPageIndex() == 0) { 1434 if (TabWidget->currentPageIndex() == 0) {
1435 QString current = currentDir.canonicalPath(); 1435 QString current = currentDir.canonicalPath();
1436 QDir dir(current); 1436 QDir dir(current);
1437 dir.cdUp(); 1437 dir.cdUp();
1438 current = dir.canonicalPath(); 1438 current = dir.canonicalPath();
1439 chdir( current.latin1() ); 1439 chdir( current.latin1() );
1440 currentDir.cd( current, TRUE); 1440 currentDir.cd( current, TRUE);
1441 populateLocalView(); 1441 populateLocalView();
1442 update(); 1442 update();
1443 } else { 1443 } else {
1444 if( FtpCDUp( conn) == 0) { 1444 if( FtpCDUp( conn) == 0) {
1445 QString msg; 1445 QString msg;
1446 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn)); 1446 msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn));
1447 msg.replace(QRegExp(":"),"\n"); 1447 msg.replace(QRegExp(":"),"\n");
1448 QMessageBox::message(tr("Note"),msg); 1448 QMessageBox::message(tr("Note"),msg);
1449// qDebug(msg); 1449// qDebug(msg);
1450 } 1450 }
1451 char path[256]; 1451 char path[256];
1452 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string 1452 if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string
1453 QString msg; 1453 QString msg;
1454 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn)); 1454 msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn));
1455 msg.replace(QRegExp(":"),"\n"); 1455 msg.replace(QRegExp(":"),"\n");
1456 QMessageBox::message(tr("Note"),msg); 1456 QMessageBox::message(tr("Note"),msg);
1457// qDebug(msg); 1457// qDebug(msg);
1458 } 1458 }
1459 currentRemoteDir=path; 1459 currentRemoteDir=path;
1460 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate 1460 remoteDirList( (const QString &)currentRemoteDir); //this also calls populate
1461 if(currentRemoteDir.right(1) !="/") 1461 if(currentRemoteDir.right(1) !="/")
1462 currentRemoteDir +="/"; 1462 currentRemoteDir +="/";
1463 currentPathCombo->lineEdit()->setText( currentRemoteDir); 1463 currentPathCombo->lineEdit()->setText( currentRemoteDir);
1464 fillRemoteCombo( (const QString &)currentRemoteDir); 1464 fillRemoteCombo( (const QString &)currentRemoteDir);
1465 1465
1466 } 1466 }
1467} 1467}
1468 1468
1469void OpieFtp::docButtonPushed() { 1469void OpieFtp::docButtonPushed() {
1470 QString current = QPEApplication::documentDir(); 1470 QString current = QPEApplication::documentDir();
1471 chdir( current.latin1() ); 1471 chdir( current.latin1() );
1472 currentDir.cd( current, TRUE); 1472 currentDir.cd( current, TRUE);
1473 populateLocalView(); 1473 populateLocalView();
1474 update(); 1474 update();
1475 1475
1476} 1476}
1477 1477
1478void OpieFtp::homeButtonPushed() { 1478void OpieFtp::homeButtonPushed() {
1479 QString current = QDir::homeDirPath(); 1479 QString current = QDir::homeDirPath();
1480 chdir( current.latin1() ); 1480 chdir( current.latin1() );
1481 currentDir.cd( current, TRUE); 1481 currentDir.cd( current, TRUE);
1482 populateLocalView(); 1482 populateLocalView();
1483 update(); 1483 update();
1484} 1484}
1485 1485
1486void OpieFtp::doAbout() { 1486void OpieFtp::doAbout() {
1487 QMessageBox::message("OpieFtp","Opie ftp client is copyright 2002 by\n" 1487 QMessageBox::message("OpieFtp","Opie ftp client is copyright 2002 by\n"
1488 "L.J.Potter<llornkcor@handhelds.org>\n" 1488 "L.J.Potter<llornkcor@handhelds.org>\n"
1489 "and uses ftplib copyright 1996-2000\n" 1489 "and uses ftplib copyright 1996-2000\n"
1490 "by Thomas Pfau, pfau@cnj.digex.net\n\n" 1490 "by Thomas Pfau, pfau@cnj.digex.net\n\n"
1491 "and is licensed by the GPL"); 1491 "and is licensed by the GPL");
1492} 1492}
1493 1493
1494void OpieFtp::NewServer() { 1494void OpieFtp::NewServer() {
1495 InputDialog *fileDlg; 1495 InputDialog *fileDlg;
1496 fileDlg = new InputDialog(this,tr("New Server name"),TRUE, 0); 1496 fileDlg = new InputDialog(this,tr("New Server name"),TRUE, 0);
1497 fileDlg->exec(); 1497 fileDlg->exec();
1498 Config cfg("opieftp"); 1498 Config cfg("opieftp");
1499 if( fileDlg->result() == 1 ) { 1499 if( fileDlg->result() == 1 ) {
1500 newServerName = fileDlg->LineEdit1->text(); 1500 newServerName = fileDlg->LineEdit1->text();
1501 for(int i=1;i<serverListView->count();i++) { 1501 for(int i=1;i<serverListView->count();i++) {
1502 cfg.setGroup( QString::number(i)); 1502 cfg.setGroup( QString::number(i));
1503 if(cfg.readEntry("ServerName").find(newServerName,0,TRUE) != -1) { 1503 if(cfg.readEntry("ServerName").find(newServerName,0,TRUE) != -1) {
1504 QMessageBox::message(tr("OpieFtp"),tr("Sorry name already taken")); 1504 QMessageBox::message(tr("OpieFtp"),tr("Sorry name already taken"));
1505 return; 1505 return;
1506 } 1506 }
1507 } 1507 }
1508 currentServerConfig =-1; 1508 currentServerConfig =-1;
1509 writeConfig(); 1509 writeConfig();
1510 serverListView->insertItem( newServerName ); 1510 serverListView->insertItem( newServerName );
1511 serverListView->setCurrentItem( serverListView->count()); 1511 serverListView->setCurrentItem( serverListView->count());
1512 } 1512 }
1513} 1513}
1514 1514
1515void OpieFtp::serverListClicked( const QString &item) { 1515void OpieFtp::serverListClicked( const QString &item) {
1516 if(item.isEmpty()) return; 1516 if(item.isEmpty()) return;
1517 Config cfg("opieftp"); 1517 Config cfg("opieftp");
1518 qDebug("highltined "+item); 1518 qDebug("highltined "+item);
1519 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0); 1519 int numberOfEntries = cfg.readNumEntry("numberOfEntries",0);
1520 for (int i = 1; i <= numberOfEntries; i++) { 1520 for (int i = 1; i <= numberOfEntries; i++) {
1521 cfg.setGroup(QString::number(i)); 1521 cfg.setGroup(QString::number(i));
1522 if(cfg.readEntry( "ServerName").find(item) != -1 && !fuckeduphack) 1522 if(cfg.readEntry( "ServerName").find(item) != -1 && !fuckeduphack)
1523 serverComboSelected(i-1); 1523 serverComboSelected(i-1);
1524 } 1524 }
1525} 1525}
1526 1526
1527void OpieFtp::timerOut() { 1527void OpieFtp::timerOut() {
1528 1528
1529} 1529}
diff --git a/noncore/net/opieirc/ircchanneltab.cpp b/noncore/net/opieirc/ircchanneltab.cpp
index b0771f6..667e977 100644
--- a/noncore/net/opieirc/ircchanneltab.cpp
+++ b/noncore/net/opieirc/ircchanneltab.cpp
@@ -1,165 +1,165 @@
1#include <qpe/resource.h> 1#include <qpe/resource.h>
2#include <qwhatsthis.h> 2#include <qwhatsthis.h>
3#include <qhbox.h> 3#include <qhbox.h>
4#include "ircchanneltab.h" 4#include "ircchanneltab.h"
5#include "ircservertab.h" 5#include "ircservertab.h"
6 6
7IRCChannelTab::IRCChannelTab(IRCChannel *channel, IRCServerTab *parentTab, MainWindow *mainWindow, QWidget *parent, const char *name, WFlags f) : IRCTab(parent, name, f) { 7IRCChannelTab::IRCChannelTab(IRCChannel *channel, IRCServerTab *parentTab, MainWindow *mainWindow, QWidget *parent, const char *name, WFlags f) : IRCTab(parent, name, f) {
8 m_mainWindow = mainWindow; 8 m_mainWindow = mainWindow;
9 m_parentTab = parentTab; 9 m_parentTab = parentTab;
10 m_channel = channel; 10 m_channel = channel;
11 m_description->setText(tr("Talking on channel") + " <b>" + channel->channelname() + "</b>"); 11 m_description->setText(tr("Talking on channel") + " <b>" + channel->channelname() + "</b>");
12 QHBox *hbox = new QHBox(this); 12 QHBox *hbox = new QHBox(this);
13 m_textview = new QTextView(hbox); 13 m_textview = new QTextView(hbox);
14 m_textview->setHScrollBarMode(QScrollView::AlwaysOff); 14 m_textview->setHScrollBarMode(QScrollView::AlwaysOff);
15 m_textview->setVScrollBarMode(QScrollView::AlwaysOn); 15 m_textview->setVScrollBarMode(QScrollView::AlwaysOn);
16 m_listVisible = TRUE; 16 m_listVisible = TRUE;
17 m_listButton = new QPushButton(">", m_textview); 17 m_listButton = new QPushButton(">", m_textview);
18 m_textview->setCornerWidget(m_listButton); 18 m_textview->setCornerWidget(m_listButton);
19 m_textview->setTextFormat(RichText); 19 m_textview->setTextFormat(RichText);
20 QWhatsThis::add(m_textview, tr("Channel discussion")); 20 QWhatsThis::add(m_textview, tr("Channel discussion"));
21 connect(m_listButton, SIGNAL(clicked()), this, SLOT(toggleList())); 21 connect(m_listButton, SIGNAL(clicked()), this, SLOT(toggleList()));
22 m_list = new IRCChannelList(m_channel, hbox); 22 m_list = new IRCChannelList(m_channel, hbox);
23 m_list->update(); 23 m_list->update();
24 m_list->setMaximumWidth(LISTWIDTH); 24 m_list->setMaximumWidth(LISTWIDTH);
25 m_field = new IRCHistoryLineEdit(this); 25 m_field = new IRCHistoryLineEdit(this);
26 QWhatsThis::add(m_field, tr("Type your message here to participate in the channel discussion")); 26 QWhatsThis::add(m_field, tr("Type your message here to participate in the channel discussion"));
27 m_popup = new QPopupMenu(m_list); 27 m_popup = new QPopupMenu(m_list);
28 m_lines = 0; 28 m_lines = 0;
29 /* Required so that embedded-style "right" clicks work */ 29 /* Required so that embedded-style "right" clicks work */
30 QPEApplication::setStylusOperation(m_list->viewport(), QPEApplication::RightOnHold); 30 QPEApplication::setStylusOperation(m_list->viewport(), QPEApplication::RightOnHold);
31 connect(m_list, SIGNAL(mouseButtonPressed(int, QListBoxItem *, const QPoint&)), this, SLOT(mouseButtonPressed(int, QListBoxItem *, const QPoint &))); 31 connect(m_list, SIGNAL(mouseButtonPressed(int,QListBoxItem*,const QPoint&)), this, SLOT(mouseButtonPressed(int,QListBoxItem*,const QPoint&)));
32 /* Construct the popup menu */ 32 /* Construct the popup menu */
33 QPopupMenu *ctcpMenu = new QPopupMenu(m_list); 33 QPopupMenu *ctcpMenu = new QPopupMenu(m_list);
34 m_popup->insertItem(Resource::loadPixmap("opieirc/ctcp"), tr("CTCP"), ctcpMenu); 34 m_popup->insertItem(Resource::loadPixmap("opieirc/ctcp"), tr("CTCP"), ctcpMenu);
35 m_popup->insertItem(Resource::loadPixmap("opieirc/query"), tr("Query"), this, SLOT(popupQuery())); 35 m_popup->insertItem(Resource::loadPixmap("opieirc/query"), tr("Query"), this, SLOT(popupQuery()));
36 ctcpMenu->insertItem(Resource::loadPixmap("opieirc/ping"), tr("Ping"), this, SLOT(popupPing())); 36 ctcpMenu->insertItem(Resource::loadPixmap("opieirc/ping"), tr("Ping"), this, SLOT(popupPing()));
37 ctcpMenu->insertItem(Resource::loadPixmap("opieirc/version"), tr("Version"), this, SLOT(popupVersion())); 37 ctcpMenu->insertItem(Resource::loadPixmap("opieirc/version"), tr("Version"), this, SLOT(popupVersion()));
38 ctcpMenu->insertItem(Resource::loadPixmap("opieirc/whois"), tr("Whois"), this, SLOT(popupWhois())); 38 ctcpMenu->insertItem(Resource::loadPixmap("opieirc/whois"), tr("Whois"), this, SLOT(popupWhois()));
39 connect(m_mainWindow, SIGNAL(updateScroll()), this, SLOT(scrolling())); 39 connect(m_mainWindow, SIGNAL(updateScroll()), this, SLOT(scrolling()));
40 m_layout->add(hbox); 40 m_layout->add(hbox);
41 hbox->show(); 41 hbox->show();
42 m_layout->add(m_field); 42 m_layout->add(m_field);
43 m_field->setFocus(); 43 m_field->setFocus();
44 connect(m_field, SIGNAL(returnPressed()), this, SLOT(processCommand())); 44 connect(m_field, SIGNAL(returnPressed()), this, SLOT(processCommand()));
45 settingsChanged(); 45 settingsChanged();
46} 46}
47 47
48void IRCChannelTab::scrolling(){ 48void IRCChannelTab::scrolling(){
49 m_textview->ensureVisible(0, m_textview->contentsHeight()); 49 m_textview->ensureVisible(0, m_textview->contentsHeight());
50} 50}
51 51
52void IRCChannelTab::appendText(QString text) { 52void IRCChannelTab::appendText(QString text) {
53 /* not using append because it creates layout problems */ 53 /* not using append because it creates layout problems */
54 QString txt = m_textview->text() + text + "\n"; 54 QString txt = m_textview->text() + text + "\n";
55 if (m_maxLines > 0 && m_lines >= m_maxLines) { 55 if (m_maxLines > 0 && m_lines >= m_maxLines) {
56 int firstBreak = txt.find('\n'); 56 int firstBreak = txt.find('\n');
57 if (firstBreak != -1) { 57 if (firstBreak != -1) {
58 txt = "<qt bgcolor=\"" + m_backgroundColor + "\"/>" + txt.right(txt.length() - (firstBreak + 1)); 58 txt = "<qt bgcolor=\"" + m_backgroundColor + "\"/>" + txt.right(txt.length() - (firstBreak + 1));
59 } 59 }
60 } else { 60 } else {
61 m_lines++; 61 m_lines++;
62 } 62 }
63 m_textview->ensureVisible(0, m_textview->contentsHeight()); 63 m_textview->ensureVisible(0, m_textview->contentsHeight());
64 m_textview->setText(txt); 64 m_textview->setText(txt);
65 m_textview->ensureVisible(0, m_textview->contentsHeight()); 65 m_textview->ensureVisible(0, m_textview->contentsHeight());
66 emit changed(this); 66 emit changed(this);
67} 67}
68 68
69IRCChannelTab::~IRCChannelTab() { 69IRCChannelTab::~IRCChannelTab() {
70 m_parentTab->removeChannelTab(this); 70 m_parentTab->removeChannelTab(this);
71} 71}
72 72
73void IRCChannelTab::processCommand() { 73void IRCChannelTab::processCommand() {
74 QString text = m_field->text(); 74 QString text = m_field->text();
75 if (text.length()>0) { 75 if (text.length()>0) {
76 if (session()->isSessionActive()) { 76 if (session()->isSessionActive()) {
77 if (text.startsWith("/") && !text.startsWith("//")) { 77 if (text.startsWith("/") && !text.startsWith("//")) {
78 /* Command mode */ 78 /* Command mode */
79 m_parentTab->executeCommand(this, text);; 79 m_parentTab->executeCommand(this, text);;
80 } else { 80 } else {
81 if (text.startsWith("//")) 81 if (text.startsWith("//"))
82 text = text.right(text.length()-1); 82 text = text.right(text.length()-1);
83 session()->sendMessage(m_channel, m_field->text()); 83 session()->sendMessage(m_channel, m_field->text());
84 appendText("<font color=\"" + m_textColor + "\">&lt;</font><font color=\"" + m_selfColor + "\">"+m_parentTab->server()->nick()+"</font><font color=\"" + m_textColor + "\">&gt; "+IRCOutput::toHTML(m_field->text())+"</font><br>"); 84 appendText("<font color=\"" + m_textColor + "\">&lt;</font><font color=\"" + m_selfColor + "\">"+m_parentTab->server()->nick()+"</font><font color=\"" + m_textColor + "\">&gt; "+IRCOutput::toHTML(m_field->text())+"</font><br>");
85 } 85 }
86 } else { 86 } else {
87 appendText("<font color=\"" + m_errorColor + "\">"+tr("Disconnected")+"</font><br>"); 87 appendText("<font color=\"" + m_errorColor + "\">"+tr("Disconnected")+"</font><br>");
88 } 88 }
89 } 89 }
90 m_field->clear(); 90 m_field->clear();
91} 91}
92 92
93void IRCChannelTab::settingsChanged() { 93void IRCChannelTab::settingsChanged() {
94 m_textview->setText("<qt bgcolor=\"" + m_backgroundColor + "\"/>"); 94 m_textview->setText("<qt bgcolor=\"" + m_backgroundColor + "\"/>");
95 m_lines = 0; 95 m_lines = 0;
96} 96}
97 97
98void IRCChannelTab::toggleList() { 98void IRCChannelTab::toggleList() {
99 if (m_listVisible) { 99 if (m_listVisible) {
100 m_list->setMaximumWidth(0); 100 m_list->setMaximumWidth(0);
101 m_listButton->setText("<"); 101 m_listButton->setText("<");
102 } else { 102 } else {
103 m_list->setMaximumWidth(LISTWIDTH); 103 m_list->setMaximumWidth(LISTWIDTH);
104 m_listButton->setText(">"); 104 m_listButton->setText(">");
105 } 105 }
106 m_listVisible = !m_listVisible; 106 m_listVisible = !m_listVisible;
107} 107}
108 108
109void IRCChannelTab::mouseButtonPressed(int mouse, QListBoxItem *, const QPoint &point) { 109void IRCChannelTab::mouseButtonPressed(int mouse, QListBoxItem *, const QPoint &point) {
110 switch (mouse) { 110 switch (mouse) {
111 case 1: 111 case 1:
112 break; 112 break;
113 case 2: 113 case 2:
114 m_popup->popup(point); 114 m_popup->popup(point);
115 break; 115 break;
116 }; 116 };
117} 117}
118 118
119void IRCChannelTab::popupQuery() { 119void IRCChannelTab::popupQuery() {
120 if (m_list->currentItem() != -1) { 120 if (m_list->currentItem() != -1) {
121 IRCPerson *person = session()->getPerson(m_list->item(m_list->currentItem())->text()); 121 IRCPerson *person = session()->getPerson(m_list->item(m_list->currentItem())->text());
122 if (person) { 122 if (person) {
123 IRCQueryTab *tab = m_parentTab->getTabForQuery(person); 123 IRCQueryTab *tab = m_parentTab->getTabForQuery(person);
124 if (!tab) { 124 if (!tab) {
125 tab = new IRCQueryTab(person, m_parentTab, m_mainWindow, (QWidget *)parent()); 125 tab = new IRCQueryTab(person, m_parentTab, m_mainWindow, (QWidget *)parent());
126 m_parentTab->addQueryTab(tab); 126 m_parentTab->addQueryTab(tab);
127 m_mainWindow->addTab(tab); 127 m_mainWindow->addTab(tab);
128 } 128 }
129 } 129 }
130 } 130 }
131} 131}
132 132
133void IRCChannelTab::popupPing() { 133void IRCChannelTab::popupPing() {
134 //HAHA, no wonder these don't work 134 //HAHA, no wonder these don't work
135} 135}
136 136
137void IRCChannelTab::popupVersion() { 137void IRCChannelTab::popupVersion() {
138} 138}
139 139
140void IRCChannelTab::popupWhois() { 140void IRCChannelTab::popupWhois() {
141} 141}
142 142
143QString IRCChannelTab::title() { 143QString IRCChannelTab::title() {
144 return m_channel->channelname(); 144 return m_channel->channelname();
145} 145}
146 146
147IRCSession *IRCChannelTab::session() { 147IRCSession *IRCChannelTab::session() {
148 return m_parentTab->session(); 148 return m_parentTab->session();
149} 149}
150 150
151void IRCChannelTab::remove() { 151void IRCChannelTab::remove() {
152 if (session()->isSessionActive()) { 152 if (session()->isSessionActive()) {
153 session()->part(m_channel); 153 session()->part(m_channel);
154 } else { 154 } else {
155 m_mainWindow->killTab(this); 155 m_mainWindow->killTab(this);
156 } 156 }
157} 157}
158 158
159IRCChannel *IRCChannelTab::channel() { 159IRCChannel *IRCChannelTab::channel() {
160 return m_channel; 160 return m_channel;
161} 161}
162 162
163IRCChannelList *IRCChannelTab::list() { 163IRCChannelList *IRCChannelTab::list() {
164 return m_list; 164 return m_list;
165} 165}
diff --git a/noncore/net/opieirc/ircsession.cpp b/noncore/net/opieirc/ircsession.cpp
index 6404d71..3b176d0 100644
--- a/noncore/net/opieirc/ircsession.cpp
+++ b/noncore/net/opieirc/ircsession.cpp
@@ -1,150 +1,150 @@
1#include "ircsession.h" 1#include "ircsession.h"
2#include "ircmessageparser.h" 2#include "ircmessageparser.h"
3#include "ircversion.h" 3#include "ircversion.h"
4 4
5IRCSession::IRCSession(IRCServer *server) { 5IRCSession::IRCSession(IRCServer *server) {
6 m_server = server; 6 m_server = server;
7 m_connection = new IRCConnection(m_server); 7 m_connection = new IRCConnection(m_server);
8 m_parser = new IRCMessageParser(this); 8 m_parser = new IRCMessageParser(this);
9 connect(m_connection, SIGNAL(messageArrived(IRCMessage *)), this, SLOT(handleMessage(IRCMessage *))); 9 connect(m_connection, SIGNAL(messageArrived(IRCMessage*)), this, SLOT(handleMessage(IRCMessage*)));
10 connect(m_parser, SIGNAL(outputReady(IRCOutput)), this, SIGNAL(outputReady(IRCOutput))); 10 connect(m_parser, SIGNAL(outputReady(IRCOutput)), this, SIGNAL(outputReady(IRCOutput)));
11 connect(m_connection, SIGNAL(outputReady(IRCOutput)), this, SIGNAL(outputReady(IRCOutput))); 11 connect(m_connection, SIGNAL(outputReady(IRCOutput)), this, SIGNAL(outputReady(IRCOutput)));
12} 12}
13 13
14IRCSession::~IRCSession() { 14IRCSession::~IRCSession() {
15 /* We want this to get deleted automatically */ 15 /* We want this to get deleted automatically */
16 m_channels.setAutoDelete(TRUE); 16 m_channels.setAutoDelete(TRUE);
17 m_people.setAutoDelete(TRUE); 17 m_people.setAutoDelete(TRUE);
18 18
19 delete m_parser; 19 delete m_parser;
20 delete m_connection; 20 delete m_connection;
21} 21}
22 22
23void IRCSession::beginSession() { 23void IRCSession::beginSession() {
24 m_connection->doConnect(); 24 m_connection->doConnect();
25} 25}
26 26
27void IRCSession::join(QString channelname) { 27void IRCSession::join(QString channelname) {
28 m_connection->sendLine("JOIN "+channelname); 28 m_connection->sendLine("JOIN "+channelname);
29} 29}
30 30
31void IRCSession::quit(){ 31void IRCSession::quit(){
32 m_connection->sendLine("QUIT :[OI] I'm too good to need a reason"); 32 m_connection->sendLine("QUIT :[OI] I'm too good to need a reason");
33} 33}
34 34
35void IRCSession::quit(QString message){ 35void IRCSession::quit(QString message){
36 m_connection->sendLine("QUIT :" + message); 36 m_connection->sendLine("QUIT :" + message);
37} 37}
38 38
39void IRCSession::topic(IRCChannel *channel, QString message){ 39void IRCSession::topic(IRCChannel *channel, QString message){
40 m_connection->sendLine("TOPIC :" + channel->channelname() + " " + message); 40 m_connection->sendLine("TOPIC :" + channel->channelname() + " " + message);
41} 41}
42 42
43void IRCSession::mode(IRCChannel *channel, QString message){ 43void IRCSession::mode(IRCChannel *channel, QString message){
44 m_connection->sendLine("MODE " + channel->channelname() + " " + message); 44 m_connection->sendLine("MODE " + channel->channelname() + " " + message);
45} 45}
46 46
47void IRCSession::mode(IRCPerson *person, QString message){ 47void IRCSession::mode(IRCPerson *person, QString message){
48 m_connection->sendLine("MODE " + person->nick() + " " + message); 48 m_connection->sendLine("MODE " + person->nick() + " " + message);
49} 49}
50 50
51void IRCSession::mode(QString message){ 51void IRCSession::mode(QString message){
52 m_connection->sendLine("MODE " + message); 52 m_connection->sendLine("MODE " + message);
53} 53}
54 54
55void IRCSession::raw(QString message){ 55void IRCSession::raw(QString message){
56 m_connection->sendLine(message); 56 m_connection->sendLine(message);
57} 57}
58 58
59void IRCSession::kick(IRCChannel *channel, IRCPerson *person) { 59void IRCSession::kick(IRCChannel *channel, IRCPerson *person) {
60 m_connection->sendLine("KICK "+ channel->channelname() + " " + person->nick() +" :0wn3d - no reason"); 60 m_connection->sendLine("KICK "+ channel->channelname() + " " + person->nick() +" :0wn3d - no reason");
61} 61}
62 62
63void IRCSession::op(IRCChannel *channel, IRCPerson *person) { 63void IRCSession::op(IRCChannel *channel, IRCPerson *person) {
64 m_connection->sendLine("MODE "+ channel->channelname() + " +ooo " + person->nick()); 64 m_connection->sendLine("MODE "+ channel->channelname() + " +ooo " + person->nick());
65} 65}
66 66
67void IRCSession::kick(IRCChannel *channel, IRCPerson *person, QString message) { 67void IRCSession::kick(IRCChannel *channel, IRCPerson *person, QString message) {
68 m_connection->sendLine("KICK "+ channel->channelname() + " " + person->nick() +" :" + message); 68 m_connection->sendLine("KICK "+ channel->channelname() + " " + person->nick() +" :" + message);
69} 69}
70 70
71void IRCSession::sendMessage(IRCPerson *person, QString message) { 71void IRCSession::sendMessage(IRCPerson *person, QString message) {
72 m_connection->sendLine("PRIVMSG " + person->nick() + " :" + message); 72 m_connection->sendLine("PRIVMSG " + person->nick() + " :" + message);
73} 73}
74 74
75void IRCSession::sendMessage(IRCChannel *channel, QString message) { 75void IRCSession::sendMessage(IRCChannel *channel, QString message) {
76 m_connection->sendLine("PRIVMSG " + channel->channelname() + " :" + message); 76 m_connection->sendLine("PRIVMSG " + channel->channelname() + " :" + message);
77} 77}
78 78
79void IRCSession::sendAction(IRCChannel *channel, QString message) { 79void IRCSession::sendAction(IRCChannel *channel, QString message) {
80 m_connection->sendLine("PRIVMSG " + channel->channelname() + " :\001ACTION " + message + "\001"); 80 m_connection->sendLine("PRIVMSG " + channel->channelname() + " :\001ACTION " + message + "\001");
81} 81}
82 82
83void IRCSession::sendAction(IRCPerson *person, QString message) { 83void IRCSession::sendAction(IRCPerson *person, QString message) {
84 m_connection->sendLine("PRIVMSG " + person->nick() + " :\001ACTION " + message + "\001"); 84 m_connection->sendLine("PRIVMSG " + person->nick() + " :\001ACTION " + message + "\001");
85} 85}
86 86
87bool IRCSession::isSessionActive() { 87bool IRCSession::isSessionActive() {
88 return m_connection->isConnected(); 88 return m_connection->isConnected();
89} 89}
90 90
91void IRCSession::endSession() { 91void IRCSession::endSession() {
92 if (m_connection->isLoggedIn()) 92 if (m_connection->isLoggedIn())
93 m_connection->sendLine("QUIT :" APP_VERSION); 93 m_connection->sendLine("QUIT :" APP_VERSION);
94 else 94 else
95 m_connection->close(); 95 m_connection->close();
96} 96}
97 97
98void IRCSession::part(IRCChannel *channel) { 98void IRCSession::part(IRCChannel *channel) {
99 m_connection->sendLine("PART " + channel->channelname() + " :" + APP_VERSION); 99 m_connection->sendLine("PART " + channel->channelname() + " :" + APP_VERSION);
100} 100}
101 101
102 102
103IRCChannel *IRCSession::getChannel(QString channelname) { 103IRCChannel *IRCSession::getChannel(QString channelname) {
104 QListIterator<IRCChannel> it(m_channels); 104 QListIterator<IRCChannel> it(m_channels);
105 for (; it.current(); ++it) { 105 for (; it.current(); ++it) {
106 if (it.current()->channelname() == channelname) { 106 if (it.current()->channelname() == channelname) {
107 return it.current(); 107 return it.current();
108 } 108 }
109 } 109 }
110 return 0; 110 return 0;
111} 111}
112 112
113IRCPerson *IRCSession::getPerson(QString nickname) { 113IRCPerson *IRCSession::getPerson(QString nickname) {
114 QListIterator<IRCPerson> it(m_people); 114 QListIterator<IRCPerson> it(m_people);
115 for (; it.current(); ++it) { 115 for (; it.current(); ++it) {
116 if (it.current()->nick() == nickname) { 116 if (it.current()->nick() == nickname) {
117 return it.current(); 117 return it.current();
118 } 118 }
119 } 119 }
120 return 0; 120 return 0;
121} 121}
122 122
123void IRCSession::getChannelsByPerson(IRCPerson *person, QList<IRCChannel> &channels) { 123void IRCSession::getChannelsByPerson(IRCPerson *person, QList<IRCChannel> &channels) {
124 QListIterator<IRCChannel> it(m_channels); 124 QListIterator<IRCChannel> it(m_channels);
125 for (; it.current(); ++it) { 125 for (; it.current(); ++it) {
126 if (it.current()->getPerson(person->nick()) != 0) { 126 if (it.current()->getPerson(person->nick()) != 0) {
127 channels.append(it.current()); 127 channels.append(it.current());
128 } 128 }
129 } 129 }
130} 130}
131 131
132void IRCSession::addPerson(IRCPerson *person) { 132void IRCSession::addPerson(IRCPerson *person) {
133 m_people.append(person); 133 m_people.append(person);
134} 134}
135 135
136void IRCSession::addChannel(IRCChannel *channel) { 136void IRCSession::addChannel(IRCChannel *channel) {
137 m_channels.append(channel); 137 m_channels.append(channel);
138} 138}
139 139
140void IRCSession::removeChannel(IRCChannel *channel) { 140void IRCSession::removeChannel(IRCChannel *channel) {
141 m_channels.remove(channel); 141 m_channels.remove(channel);
142} 142}
143 143
144void IRCSession::removePerson(IRCPerson *person) { 144void IRCSession::removePerson(IRCPerson *person) {
145 m_people.remove(person); 145 m_people.remove(person);
146} 146}
147 147
148void IRCSession::handleMessage(IRCMessage *message) { 148void IRCSession::handleMessage(IRCMessage *message) {
149 m_parser->parse(message); 149 m_parser->parse(message);
150} 150}
diff --git a/noncore/net/opieirc/mainwindow.cpp b/noncore/net/opieirc/mainwindow.cpp
index 7414154..0923a11 100644
--- a/noncore/net/opieirc/mainwindow.cpp
+++ b/noncore/net/opieirc/mainwindow.cpp
@@ -1,91 +1,91 @@
1#include <qmenubar.h> 1#include <qmenubar.h>
2#include <qpe/resource.h> 2#include <qpe/resource.h>
3#include <qwhatsthis.h> 3#include <qwhatsthis.h>
4 4
5#include "mainwindow.h" 5#include "mainwindow.h"
6#include "ircservertab.h" 6#include "ircservertab.h"
7#include "ircserverlist.h" 7#include "ircserverlist.h"
8#include "ircsettings.h" 8#include "ircsettings.h"
9 9
10MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) { 10MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) {
11 setCaption(tr("IRC Client")); 11 setCaption(tr("IRC Client"));
12 m_tabWidget = new IRCTabWidget(this); 12 m_tabWidget = new IRCTabWidget(this);
13 QWhatsThis::add(m_tabWidget, tr("Server connections, channels, queries and other things will be placed here")); 13 QWhatsThis::add(m_tabWidget, tr("Server connections, channels, queries and other things will be placed here"));
14 connect(m_tabWidget, SIGNAL(currentChanged(QWidget *)), this, SLOT(selected(QWidget *))); 14 connect(m_tabWidget, SIGNAL(currentChanged(QWidget*)), this, SLOT(selected(QWidget*)));
15 setCentralWidget(m_tabWidget); 15 setCentralWidget(m_tabWidget);
16 setToolBarsMovable(FALSE); 16 setToolBarsMovable(FALSE);
17 QMenuBar *menuBar = new QMenuBar(this); 17 QMenuBar *menuBar = new QMenuBar(this);
18 QPopupMenu *irc = new QPopupMenu(this); 18 QPopupMenu *irc = new QPopupMenu(this);
19 menuBar->insertItem(tr("IRC"), irc); 19 menuBar->insertItem(tr("IRC"), irc);
20 QAction *a = new QAction(tr("New connection"), Resource::loadPixmap("pass"), QString::null, 0, this, 0); 20 QAction *a = new QAction(tr("New connection"), Resource::loadPixmap("pass"), QString::null, 0, this, 0);
21 connect(a, SIGNAL(activated()), this, SLOT(newConnection())); 21 connect(a, SIGNAL(activated()), this, SLOT(newConnection()));
22 a->setWhatsThis(tr("Create a new connection to an IRC server")); 22 a->setWhatsThis(tr("Create a new connection to an IRC server"));
23 a->addTo(irc); 23 a->addTo(irc);
24 a = new QAction(tr("Settings"), Resource::loadPixmap("SettingsIcon"), QString::null, 0, this, 0); 24 a = new QAction(tr("Settings"), Resource::loadPixmap("SettingsIcon"), QString::null, 0, this, 0);
25 a->setWhatsThis(tr("Configure OpieIRC's behavior and appearance")); 25 a->setWhatsThis(tr("Configure OpieIRC's behavior and appearance"));
26 connect(a, SIGNAL(activated()), this, SLOT(settings())); 26 connect(a, SIGNAL(activated()), this, SLOT(settings()));
27 a->addTo(irc); 27 a->addTo(irc);
28 loadSettings(); 28 loadSettings();
29} 29}
30 30
31/*IRCTabWidget MainWindow::getTabWidget(){ 31/*IRCTabWidget MainWindow::getTabWidget(){
32 return m_tabWidget; 32 return m_tabWidget;
33} */ 33} */
34 34
35void MainWindow::loadSettings() { 35void MainWindow::loadSettings() {
36 Config config("OpieIRC"); 36 Config config("OpieIRC");
37 config.setGroup("OpieIRC"); 37 config.setGroup("OpieIRC");
38 IRCTab::m_backgroundColor = config.readEntry("BackgroundColor", "#FFFFFF"); 38 IRCTab::m_backgroundColor = config.readEntry("BackgroundColor", "#FFFFFF");
39 IRCTab::m_textColor = config.readEntry("TextColor", "#000000"); 39 IRCTab::m_textColor = config.readEntry("TextColor", "#000000");
40 IRCTab::m_errorColor = config.readEntry("ErrorColor", "#FF0000"); 40 IRCTab::m_errorColor = config.readEntry("ErrorColor", "#FF0000");
41 IRCTab::m_selfColor = config.readEntry("SelfColor", "#CC0000"); 41 IRCTab::m_selfColor = config.readEntry("SelfColor", "#CC0000");
42 IRCTab::m_otherColor = config.readEntry("OtherColor", "#0000BB"); 42 IRCTab::m_otherColor = config.readEntry("OtherColor", "#0000BB");
43 IRCTab::m_serverColor = config.readEntry("ServerColor", "#0000FF"); 43 IRCTab::m_serverColor = config.readEntry("ServerColor", "#0000FF");
44 IRCTab::m_notificationColor = config.readEntry("NotificationColor", "#AA3300"); 44 IRCTab::m_notificationColor = config.readEntry("NotificationColor", "#AA3300");
45 IRCTab::m_maxLines = config.readNumEntry("Lines", 100); 45 IRCTab::m_maxLines = config.readNumEntry("Lines", 100);
46} 46}
47 47
48void MainWindow::selected(QWidget *) { 48void MainWindow::selected(QWidget *) {
49 m_tabWidget->setTabColor(m_tabWidget->currentPageIndex(), black); 49 m_tabWidget->setTabColor(m_tabWidget->currentPageIndex(), black);
50 emit updateScroll(); 50 emit updateScroll();
51} 51}
52 52
53void MainWindow::addTab(IRCTab *tab) { 53void MainWindow::addTab(IRCTab *tab) {
54 connect(tab, SIGNAL(changed(IRCTab *)), this, SLOT(changeEvent(IRCTab *))); 54 connect(tab, SIGNAL(changed(IRCTab*)), this, SLOT(changeEvent(IRCTab*)));
55 m_tabWidget->addTab(tab, tab->title()); 55 m_tabWidget->addTab(tab, tab->title());
56 m_tabWidget->showPage(tab); 56 m_tabWidget->showPage(tab);
57 tab->setID(m_tabWidget->currentPageIndex()); 57 tab->setID(m_tabWidget->currentPageIndex());
58 m_tabs.append(tab); 58 m_tabs.append(tab);
59} 59}
60 60
61void MainWindow::changeEvent(IRCTab *tab) { 61void MainWindow::changeEvent(IRCTab *tab) {
62 if (tab->id() != m_tabWidget->currentPageIndex()) 62 if (tab->id() != m_tabWidget->currentPageIndex())
63 m_tabWidget->setTabColor(tab->id(), blue); 63 m_tabWidget->setTabColor(tab->id(), blue);
64} 64}
65 65
66void MainWindow::killTab(IRCTab *tab) { 66void MainWindow::killTab(IRCTab *tab) {
67 m_tabWidget->removePage(tab); 67 m_tabWidget->removePage(tab);
68 m_tabs.remove(tab); 68 m_tabs.remove(tab);
69 /* there might be nicer ways to do this .. */ 69 /* there might be nicer ways to do this .. */
70 delete tab; 70 delete tab;
71} 71}
72 72
73void MainWindow::newConnection() { 73void MainWindow::newConnection() {
74 IRCServerList list(this, "ServerList", TRUE); 74 IRCServerList list(this, "ServerList", TRUE);
75 if (list.exec() == QDialog::Accepted && list.hasServer()) { 75 if (list.exec() == QDialog::Accepted && list.hasServer()) {
76 IRCServerTab *serverTab = new IRCServerTab(list.server(), this, m_tabWidget); 76 IRCServerTab *serverTab = new IRCServerTab(list.server(), this, m_tabWidget);
77 addTab(serverTab); 77 addTab(serverTab);
78 serverTab->doConnect(); 78 serverTab->doConnect();
79 } 79 }
80} 80}
81 81
82void MainWindow::settings() { 82void MainWindow::settings() {
83 IRCSettings settings(this, "Settings", TRUE); 83 IRCSettings settings(this, "Settings", TRUE);
84 if (settings.exec() == QDialog::Accepted) { 84 if (settings.exec() == QDialog::Accepted) {
85 QListIterator<IRCTab> it(m_tabs); 85 QListIterator<IRCTab> it(m_tabs);
86 for (; it.current(); ++it) { 86 for (; it.current(); ++it) {
87 /* Inform all tabs about the new settings */ 87 /* Inform all tabs about the new settings */
88 it.current()->settingsChanged(); 88 it.current()->settingsChanged();
89 } 89 }
90 } 90 }
91} 91}
diff --git a/noncore/net/opietooth/lib/startdunconnection.cpp b/noncore/net/opietooth/lib/startdunconnection.cpp
index 6b6d247..c3850eb 100644
--- a/noncore/net/opietooth/lib/startdunconnection.cpp
+++ b/noncore/net/opietooth/lib/startdunconnection.cpp
@@ -1,67 +1,67 @@
1 1
2#include "startdunconnection.h" 2#include "startdunconnection.h"
3 3
4using namespace OpieTooth; 4using namespace OpieTooth;
5 5
6 6
7StartDunConnection::StartDunConnection() { 7StartDunConnection::StartDunConnection() {
8 m_dunConnect = 0l; 8 m_dunConnect = 0l;
9 setConnectionType(); 9 setConnectionType();
10} 10}
11 11
12StartDunConnection::~StartDunConnection() { 12StartDunConnection::~StartDunConnection() {
13 delete m_dunConnect; 13 delete m_dunConnect;
14} 14}
15 15
16StartDunConnection::StartDunConnection( QString mac ) { 16StartDunConnection::StartDunConnection( QString mac ) {
17 m_dunConnect = 0l; 17 m_dunConnect = 0l;
18 m_mac = mac; 18 m_mac = mac;
19 setConnectionType(); 19 setConnectionType();
20} 20}
21 21
22void StartDunConnection::setName( QString name ) { 22void StartDunConnection::setName( QString name ) {
23 m_name = name; 23 m_name = name;
24} 24}
25 25
26QString StartDunConnection::name() { 26QString StartDunConnection::name() {
27 return m_name; 27 return m_name;
28} 28}
29 29
30void StartDunConnection::setConnectionType() { 30void StartDunConnection::setConnectionType() {
31 m_connectionType = Pan; 31 m_connectionType = Pan;
32} 32}
33 33
34StartConnection::ConnectionType StartDunConnection::type() { 34StartConnection::ConnectionType StartDunConnection::type() {
35 return m_connectionType; 35 return m_connectionType;
36} 36}
37 37
38void StartDunConnection::start() { 38void StartDunConnection::start() {
39 m_dunConnect = new OProcess(); 39 m_dunConnect = new OProcess();
40 *m_dunConnect << "dund" << "--listen" << "--connect" << m_mac; 40 *m_dunConnect << "dund" << "--listen" << "--connect" << m_mac;
41 41
42 connect( m_dunConnect, SIGNAL( processExited( OProcess* ) ) , 42 connect( m_dunConnect, SIGNAL( processExited(OProcess*) ) ,
43 this, SLOT( slotExited( OProcess* ) ) ); 43 this, SLOT( slotExited(OProcess*) ) );
44 connect( m_dunConnect, SIGNAL( receivedStdout( OProcess*, char*, int ) ), 44 connect( m_dunConnect, SIGNAL( receivedStdout(OProcess*,char*,int) ),
45 this, SLOT( slotStdOut( OProcess*, char*, int ) ) ); 45 this, SLOT( slotStdOut(OProcess*,char*,int) ) );
46 if (!m_dunConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) { 46 if (!m_dunConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
47 qWarning( "could not start" ); 47 qWarning( "could not start" );
48 delete m_dunConnect; 48 delete m_dunConnect;
49 } 49 }
50} 50}
51 51
52 52
53void StartDunConnection::slotExited( OProcess* proc ) { 53void StartDunConnection::slotExited( OProcess* proc ) {
54 delete m_dunConnect; 54 delete m_dunConnect;
55} 55}
56 56
57void StartDunConnection::slotStdOut(OProcess* proc, char* chars, int len) 57void StartDunConnection::slotStdOut(OProcess* proc, char* chars, int len)
58{} 58{}
59 59
60 60
61void StartDunConnection::stop() { 61void StartDunConnection::stop() {
62 if ( m_dunConnect ) { 62 if ( m_dunConnect ) {
63 delete m_dunConnect; 63 delete m_dunConnect;
64 m_dunConnect = 0l; 64 m_dunConnect = 0l;
65 } 65 }
66} 66}
67 67
diff --git a/noncore/net/opietooth/lib/startpanconnection.cpp b/noncore/net/opietooth/lib/startpanconnection.cpp
index 6e0ab7e..a42b407 100644
--- a/noncore/net/opietooth/lib/startpanconnection.cpp
+++ b/noncore/net/opietooth/lib/startpanconnection.cpp
@@ -1,82 +1,82 @@
1 1
2#include "startpanconnection.h" 2#include "startpanconnection.h"
3 3
4using namespace OpieTooth; 4using namespace OpieTooth;
5 5
6 6
7StartPanConnection::StartPanConnection() { 7StartPanConnection::StartPanConnection() {
8 m_panConnect = 0l; 8 m_panConnect = 0l;
9 setConnectionType(); 9 setConnectionType();
10} 10}
11 11
12StartPanConnection::~StartPanConnection() { 12StartPanConnection::~StartPanConnection() {
13 delete m_panConnect; 13 delete m_panConnect;
14} 14}
15 15
16StartPanConnection::StartPanConnection( QString mac ) { 16StartPanConnection::StartPanConnection( QString mac ) {
17 m_panConnect = 0l; 17 m_panConnect = 0l;
18 m_mac = mac; 18 m_mac = mac;
19 setConnectionType(); 19 setConnectionType();
20} 20}
21 21
22void StartPanConnection::setName( QString name ) { 22void StartPanConnection::setName( QString name ) {
23 m_name = name; 23 m_name = name;
24} 24}
25 25
26QString StartPanConnection::name() { 26QString StartPanConnection::name() {
27 return m_name; 27 return m_name;
28} 28}
29 29
30void StartPanConnection::setConnectionType() { 30void StartPanConnection::setConnectionType() {
31 m_connectionType = Pan; 31 m_connectionType = Pan;
32} 32}
33 33
34StartConnection::ConnectionType StartPanConnection::type() { 34StartConnection::ConnectionType StartPanConnection::type() {
35 return m_connectionType; 35 return m_connectionType;
36} 36}
37 37
38void StartPanConnection::start() { 38void StartPanConnection::start() {
39 m_panConnect = new OProcess(); 39 m_panConnect = new OProcess();
40 qDebug( "IM START " + m_mac ); 40 qDebug( "IM START " + m_mac );
41 *m_panConnect << "pand" << "--connect" << m_mac; 41 *m_panConnect << "pand" << "--connect" << m_mac;
42 42
43 connect( m_panConnect, SIGNAL( processExited( OProcess* ) ) , 43 connect( m_panConnect, SIGNAL( processExited(OProcess*) ) ,
44 this, SLOT( slotExited( OProcess* ) ) ); 44 this, SLOT( slotExited(OProcess*) ) );
45 connect( m_panConnect, SIGNAL( receivedStdout( OProcess*, char*, int ) ), 45 connect( m_panConnect, SIGNAL( receivedStdout(OProcess*,char*,int) ),
46 this, SLOT( slotStdOut( OProcess*, char*, int ) ) ); 46 this, SLOT( slotStdOut(OProcess*,char*,int) ) );
47 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) { 47 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
48 qWarning( "could not start" ); 48 qWarning( "could not start" );
49 delete m_panConnect; 49 delete m_panConnect;
50 } 50 }
51} 51}
52 52
53 53
54void StartPanConnection::slotExited( OProcess* proc ) { 54void StartPanConnection::slotExited( OProcess* proc ) {
55 delete m_panConnect; 55 delete m_panConnect;
56 m_panConnect = 0l; 56 m_panConnect = 0l;
57} 57}
58 58
59void StartPanConnection::slotStdOut(OProcess* proc, char* chars, int len) 59void StartPanConnection::slotStdOut(OProcess* proc, char* chars, int len)
60{} 60{}
61 61
62 62
63void StartPanConnection::stop() { 63void StartPanConnection::stop() {
64 if ( m_panConnect ) { 64 if ( m_panConnect ) {
65 delete m_panConnect; 65 delete m_panConnect;
66 m_panConnect = 0l; 66 m_panConnect = 0l;
67 } 67 }
68 m_panConnect = new OProcess(); 68 m_panConnect = new OProcess();
69 qDebug("IM STOP " + m_mac); 69 qDebug("IM STOP " + m_mac);
70 70
71 *m_panConnect << "pand" << "--kill" << m_mac; 71 *m_panConnect << "pand" << "--kill" << m_mac;
72 72
73 connect( m_panConnect, SIGNAL( processExited( OProcess* ) ) , 73 connect( m_panConnect, SIGNAL( processExited(OProcess*) ) ,
74 this, SLOT( slotExited( OProcess* ) ) ); 74 this, SLOT( slotExited(OProcess*) ) );
75 connect( m_panConnect, SIGNAL( receivedStdout( OProcess*, char*, int ) ), 75 connect( m_panConnect, SIGNAL( receivedStdout(OProcess*,char*,int) ),
76 this, SLOT( slotStdOut( OProcess*, char*, int ) ) ); 76 this, SLOT( slotStdOut(OProcess*,char*,int) ) );
77 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) { 77 if (!m_panConnect->start( OProcess::NotifyOnExit, OProcess::AllOutput) ) {
78 qWarning( "could not stop" ); 78 qWarning( "could not stop" );
79 delete m_panConnect; 79 delete m_panConnect;
80 } 80 }
81} 81}
82 82
diff --git a/noncore/net/opietooth/manager/bluebase.cpp b/noncore/net/opietooth/manager/bluebase.cpp
index 0ea45d2..29030ab 100644
--- a/noncore/net/opietooth/manager/bluebase.cpp
+++ b/noncore/net/opietooth/manager/bluebase.cpp
@@ -1,688 +1,688 @@
1/* 1/*
2 * bluebase.cpp * 2 * bluebase.cpp *
3 * --------------------- 3 * ---------------------
4 * 4 *
5 * copyright : (c) 2002 by Maximilian Reiß 5 * copyright : (c) 2002 by Maximilian Reiß
6 * email : max.reiss@gmx.de 6 * email : max.reiss@gmx.de
7 * 7 *
8 */ 8 */
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free software; you can redistribute it and/or modify * 11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or * 13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. * 14 * (at your option) any later version. *
15 * * 15 * *
16 ***************************************************************************/ 16 ***************************************************************************/
17 17
18#include "bluebase.h" 18#include "bluebase.h"
19#include "scandialog.h" 19#include "scandialog.h"
20#include "hciconfwrapper.h" 20#include "hciconfwrapper.h"
21#include "devicehandler.h" 21#include "devicehandler.h"
22#include "btconnectionitem.h" 22#include "btconnectionitem.h"
23#include "rfcommassigndialogimpl.h" 23#include "rfcommassigndialogimpl.h"
24 24
25/* OPIE */ 25/* OPIE */
26#include <qpe/qpeapplication.h> 26#include <qpe/qpeapplication.h>
27#include <qpe/resource.h> 27#include <qpe/resource.h>
28#include <qpe/config.h> 28#include <qpe/config.h>
29 29
30/* QT */ 30/* QT */
31#include <qframe.h> 31#include <qframe.h>
32#include <qlabel.h> 32#include <qlabel.h>
33#include <qpushbutton.h> 33#include <qpushbutton.h>
34#include <qlayout.h> 34#include <qlayout.h>
35#include <qvariant.h> 35#include <qvariant.h>
36#include <qimage.h> 36#include <qimage.h>
37#include <qpixmap.h> 37#include <qpixmap.h>
38#include <qtabwidget.h> 38#include <qtabwidget.h>
39#include <qscrollview.h> 39#include <qscrollview.h>
40#include <qvbox.h> 40#include <qvbox.h>
41#include <qmessagebox.h> 41#include <qmessagebox.h>
42#include <qcheckbox.h> 42#include <qcheckbox.h>
43#include <qlineedit.h> 43#include <qlineedit.h>
44#include <qlistview.h> 44#include <qlistview.h>
45#include <qdir.h> 45#include <qdir.h>
46#include <qpopupmenu.h> 46#include <qpopupmenu.h>
47#include <qtimer.h> 47#include <qtimer.h>
48#include <qlist.h> 48#include <qlist.h>
49 49
50/* STD */ 50/* STD */
51#include <remotedevice.h> 51#include <remotedevice.h>
52#include <services.h> 52#include <services.h>
53#include <stdlib.h> 53#include <stdlib.h>
54 54
55using namespace OpieTooth; 55using namespace OpieTooth;
56 56
57BlueBase::BlueBase( QWidget* parent, const char* name, WFlags fl ) 57BlueBase::BlueBase( QWidget* parent, const char* name, WFlags fl )
58 : BluetoothBase( parent, name, fl ) 58 : BluetoothBase( parent, name, fl )
59{ 59{
60 60
61 m_localDevice = new Manager( "hci0" ); 61 m_localDevice = new Manager( "hci0" );
62 62
63 connect( PushButton2, SIGNAL( clicked() ), this, SLOT(startScan() ) ); 63 connect( PushButton2, SIGNAL( clicked() ), this, SLOT(startScan() ) );
64 connect( configApplyButton, SIGNAL(clicked() ), this, SLOT(applyConfigChanges() ) ); 64 connect( configApplyButton, SIGNAL(clicked() ), this, SLOT(applyConfigChanges() ) );
65 65
66 connect( rfcommBindButton, SIGNAL( clicked() ), this, SLOT( rfcommDialog() ) ); 66 connect( rfcommBindButton, SIGNAL( clicked() ), this, SLOT( rfcommDialog() ) );
67 // not good since lib is async 67 // not good since lib is async
68 // connect( ListView2, SIGNAL( expanded ( QListViewItem* ) ), 68 // connect( ListView2, SIGNAL( expanded(QListViewItem*) ),
69 // this, SLOT( addServicesToDevice( QListViewItem * ) ) ); 69 // this, SLOT( addServicesToDevice(QListViewItem*) ) );
70 connect( ListView2, SIGNAL( clicked( QListViewItem* )), 70 connect( ListView2, SIGNAL( clicked(QListViewItem*)),
71 this, SLOT( startServiceActionClicked( QListViewItem* ) ) ); 71 this, SLOT( startServiceActionClicked(QListViewItem*) ) );
72 connect( ListView2, SIGNAL( rightButtonClicked( QListViewItem *, const QPoint &, int ) ), 72 connect( ListView2, SIGNAL( rightButtonClicked(QListViewItem*,const QPoint&,int) ),
73 this, SLOT(startServiceActionHold( QListViewItem *, const QPoint &, int) ) ); 73 this, SLOT(startServiceActionHold(QListViewItem*,const QPoint&,int) ) );
74 connect( m_localDevice , SIGNAL( foundServices( const QString& , Services::ValueList ) ), 74 connect( m_localDevice , SIGNAL( foundServices(const QString&,Services::ValueList) ),
75 this, SLOT( addServicesToDevice( const QString& , Services::ValueList ) ) ); 75 this, SLOT( addServicesToDevice(const QString&,Services::ValueList) ) );
76 connect( m_localDevice, SIGNAL( available( const QString&, bool ) ), 76 connect( m_localDevice, SIGNAL( available(const QString&,bool) ),
77 this, SLOT( deviceActive( const QString& , bool ) ) ); 77 this, SLOT( deviceActive(const QString&,bool) ) );
78 connect( m_localDevice, SIGNAL( connections( ConnectionState::ValueList ) ), 78 connect( m_localDevice, SIGNAL( connections(ConnectionState::ValueList) ),
79 this, SLOT( addConnectedDevices( ConnectionState::ValueList ) ) ); 79 this, SLOT( addConnectedDevices(ConnectionState::ValueList) ) );
80 connect( m_localDevice, SIGNAL( signalStrength( const QString&, const QString& ) ), 80 connect( m_localDevice, SIGNAL( signalStrength(const QString&,const QString&) ),
81 this, SLOT( addSignalStrength( const QString&, const QString& ) ) ); 81 this, SLOT( addSignalStrength(const QString&,const QString&) ) );
82 82
83 83
84 // let hold be rightButtonClicked() 84 // let hold be rightButtonClicked()
85 QPEApplication::setStylusOperation( ListView2->viewport(), QPEApplication::RightOnHold); 85 QPEApplication::setStylusOperation( ListView2->viewport(), QPEApplication::RightOnHold);
86 QPEApplication::setStylusOperation( ListView4->viewport(), QPEApplication::RightOnHold); 86 QPEApplication::setStylusOperation( ListView4->viewport(), QPEApplication::RightOnHold);
87 87
88 //Load all icons needed 88 //Load all icons needed
89 m_offPix = Resource::loadPixmap( "opietooth/notconnected" ); 89 m_offPix = Resource::loadPixmap( "opietooth/notconnected" );
90 m_onPix = Resource::loadPixmap( "opietooth/connected" ); 90 m_onPix = Resource::loadPixmap( "opietooth/connected" );
91 m_findPix = Resource::loadPixmap( "opietooth/find" ); 91 m_findPix = Resource::loadPixmap( "opietooth/find" );
92 92
93 QPalette pal = this->palette(); 93 QPalette pal = this->palette();
94 QColor col = pal.color( QPalette::Active, QColorGroup::Background ); 94 QColor col = pal.color( QPalette::Active, QColorGroup::Background );
95 pal.setColor( QPalette::Active, QColorGroup::Button, col ); 95 pal.setColor( QPalette::Active, QColorGroup::Button, col );
96 pal.setColor( QPalette::Inactive, QColorGroup::Button, col ); 96 pal.setColor( QPalette::Inactive, QColorGroup::Button, col );
97 pal.setColor( QPalette::Normal, QColorGroup::Button, col ); 97 pal.setColor( QPalette::Normal, QColorGroup::Button, col );
98 pal.setColor( QPalette::Disabled, QColorGroup::Button, col ); 98 pal.setColor( QPalette::Disabled, QColorGroup::Button, col );
99 this->setPalette( pal ); 99 this->setPalette( pal );
100 100
101 setCaption( tr( "Bluetooth Manager" ) ); 101 setCaption( tr( "Bluetooth Manager" ) );
102 102
103 readConfig(); 103 readConfig();
104 initGui(); 104 initGui();
105 105
106 ListView2->setRootIsDecorated(true); 106 ListView2->setRootIsDecorated(true);
107 107
108 108
109 writeToHciConfig(); 109 writeToHciConfig();
110 // search conncetions 110 // search conncetions
111 addConnectedDevices(); 111 addConnectedDevices();
112 addSignalStrength(); 112 addSignalStrength();
113 m_iconLoader = new BTIconLoader(); 113 m_iconLoader = new BTIconLoader();
114 readSavedDevices(); 114 readSavedDevices();
115} 115}
116 116
117/** 117/**
118 * Reads all options from the config file 118 * Reads all options from the config file
119 */ 119 */
120void BlueBase::readConfig() 120void BlueBase::readConfig()
121{ 121{
122 122
123 Config cfg( "bluetoothmanager" ); 123 Config cfg( "bluetoothmanager" );
124 cfg.setGroup( "bluezsettings" ); 124 cfg.setGroup( "bluezsettings" );
125 125
126 m_deviceName = cfg.readEntry( "name" , "No name" ); // name the device should identify with 126 m_deviceName = cfg.readEntry( "name" , "No name" ); // name the device should identify with
127 m_defaultPasskey = cfg.readEntryCrypt( "passkey" , "" ); // <- hmm, look up how good the trolls did that, maybe too weak 127 m_defaultPasskey = cfg.readEntryCrypt( "passkey" , "" ); // <- hmm, look up how good the trolls did that, maybe too weak
128 m_useEncryption = cfg.readBoolEntry( "useEncryption" , TRUE ); 128 m_useEncryption = cfg.readBoolEntry( "useEncryption" , TRUE );
129 m_enableAuthentification = cfg.readBoolEntry( "enableAuthentification" , TRUE ); 129 m_enableAuthentification = cfg.readBoolEntry( "enableAuthentification" , TRUE );
130 m_enablePagescan = cfg.readBoolEntry( "enablePagescan" , TRUE ); 130 m_enablePagescan = cfg.readBoolEntry( "enablePagescan" , TRUE );
131 m_enableInquiryscan = cfg.readBoolEntry( "enableInquiryscan" , TRUE ); 131 m_enableInquiryscan = cfg.readBoolEntry( "enableInquiryscan" , TRUE );
132} 132}
133 133
134/** 134/**
135 * Writes all options to the config file 135 * Writes all options to the config file
136 */ 136 */
137void BlueBase::writeConfig() 137void BlueBase::writeConfig()
138{ 138{
139 139
140 Config cfg( "bluetoothmanager" ); 140 Config cfg( "bluetoothmanager" );
141 cfg.setGroup( "bluezsettings" ); 141 cfg.setGroup( "bluezsettings" );
142 142
143 cfg.writeEntry( "name" , m_deviceName ); 143 cfg.writeEntry( "name" , m_deviceName );
144 cfg.writeEntryCrypt( "passkey" , m_defaultPasskey ); 144 cfg.writeEntryCrypt( "passkey" , m_defaultPasskey );
145 cfg.writeEntry( "useEncryption" , m_useEncryption ); 145 cfg.writeEntry( "useEncryption" , m_useEncryption );
146 cfg.writeEntry( "enableAuthentification" , m_enableAuthentification ); 146 cfg.writeEntry( "enableAuthentification" , m_enableAuthentification );
147 cfg.writeEntry( "enablePagescan" , m_enablePagescan ); 147 cfg.writeEntry( "enablePagescan" , m_enablePagescan );
148 cfg.writeEntry( "enableInquiryscan" , m_enableInquiryscan ); 148 cfg.writeEntry( "enableInquiryscan" , m_enableInquiryscan );
149 149
150 writeToHciConfig(); 150 writeToHciConfig();
151} 151}
152 152
153/** 153/**
154 * Modify the hcid.conf file to our needs 154 * Modify the hcid.conf file to our needs
155 */ 155 */
156void BlueBase::writeToHciConfig() 156void BlueBase::writeToHciConfig()
157{ 157{
158 qWarning("writeToHciConfig"); 158 qWarning("writeToHciConfig");
159 HciConfWrapper hciconf ( "/etc/bluetooth/hcid.conf" ); 159 HciConfWrapper hciconf ( "/etc/bluetooth/hcid.conf" );
160 hciconf.load(); 160 hciconf.load();
161 hciconf.setPinHelper( "/opt/QtPalmtop/bin/bluepin" ); 161 hciconf.setPinHelper( "/opt/QtPalmtop/bin/bluepin" );
162 hciconf.setName( m_deviceName ); 162 hciconf.setName( m_deviceName );
163 hciconf.setEncrypt( m_useEncryption ); 163 hciconf.setEncrypt( m_useEncryption );
164 hciconf.setAuth( m_enableAuthentification ); 164 hciconf.setAuth( m_enableAuthentification );
165 hciconf.setPscan( m_enablePagescan ); 165 hciconf.setPscan( m_enablePagescan );
166 hciconf.setIscan( m_enableInquiryscan ); 166 hciconf.setIscan( m_enableInquiryscan );
167 hciconf.save(); 167 hciconf.save();
168} 168}
169 169
170 170
171/** 171/**
172 * Read the list of allready known devices 172 * Read the list of allready known devices
173 */ 173 */
174void BlueBase::readSavedDevices() 174void BlueBase::readSavedDevices()
175{ 175{
176 176
177 QValueList<RemoteDevice> loadedDevices; 177 QValueList<RemoteDevice> loadedDevices;
178 DeviceHandler handler; 178 DeviceHandler handler;
179 loadedDevices = handler.load(); 179 loadedDevices = handler.load();
180 180
181 addSearchedDevices( loadedDevices ); 181 addSearchedDevices( loadedDevices );
182} 182}
183 183
184 184
185/** 185/**
186 * Write the list of allready known devices 186 * Write the list of allready known devices
187 */ 187 */
188void BlueBase::writeSavedDevices() 188void BlueBase::writeSavedDevices()
189{ 189{
190 QListViewItemIterator it( ListView2 ); 190 QListViewItemIterator it( ListView2 );
191 BTListItem* item; 191 BTListItem* item;
192 BTDeviceItem* device; 192 BTDeviceItem* device;
193 RemoteDevice::ValueList list; 193 RemoteDevice::ValueList list;
194 for ( ; it.current(); ++it ) 194 for ( ; it.current(); ++it )
195 { 195 {
196 item = (BTListItem*)it.current(); 196 item = (BTListItem*)it.current();
197 if(item->typeId() != BTListItem::Device ) 197 if(item->typeId() != BTListItem::Device )
198 continue; 198 continue;
199 device = (BTDeviceItem*)item; 199 device = (BTDeviceItem*)item;
200 200
201 list.append( device->remoteDevice() ); 201 list.append( device->remoteDevice() );
202 } 202 }
203 /* 203 /*
204 * if not empty save the List through DeviceHandler 204 * if not empty save the List through DeviceHandler
205 */ 205 */
206 if ( list.isEmpty() ) 206 if ( list.isEmpty() )
207 return; 207 return;
208 DeviceHandler handler; 208 DeviceHandler handler;
209 handler.save( list ); 209 handler.save( list );
210} 210}
211 211
212 212
213/** 213/**
214 * Set up the gui 214 * Set up the gui
215 */ 215 */
216void BlueBase::initGui() 216void BlueBase::initGui()
217{ 217{
218 StatusLabel->setText( status() ); // maybe move it to getStatus() 218 StatusLabel->setText( status() ); // maybe move it to getStatus()
219 cryptCheckBox->setChecked( m_useEncryption ); 219 cryptCheckBox->setChecked( m_useEncryption );
220 authCheckBox->setChecked( m_enableAuthentification ); 220 authCheckBox->setChecked( m_enableAuthentification );
221 pagescanCheckBox->setChecked( m_enablePagescan ); 221 pagescanCheckBox->setChecked( m_enablePagescan );
222 inquiryscanCheckBox->setChecked( m_enableInquiryscan ); 222 inquiryscanCheckBox->setChecked( m_enableInquiryscan );
223 deviceNameLine->setText( m_deviceName ); 223 deviceNameLine->setText( m_deviceName );
224 passkeyLine->setText( m_defaultPasskey ); 224 passkeyLine->setText( m_defaultPasskey );
225 // set info tab 225 // set info tab
226 setInfo(); 226 setInfo();
227} 227}
228 228
229 229
230/** 230/**
231 * Get the status informations and returns it 231 * Get the status informations and returns it
232 * @return QString the status informations gathered 232 * @return QString the status informations gathered
233 */ 233 */
234QString BlueBase::status()const 234QString BlueBase::status()const
235{ 235{
236 QString infoString = tr( "<b>Device name : </b> Ipaq" ); 236 QString infoString = tr( "<b>Device name : </b> Ipaq" );
237 infoString += QString( "<br><b>" + tr( "MAC adress: " ) +"</b> No idea" ); 237 infoString += QString( "<br><b>" + tr( "MAC adress: " ) +"</b> No idea" );
238 infoString += QString( "<br><b>" + tr( "Class" ) + "</b> PDA" ); 238 infoString += QString( "<br><b>" + tr( "Class" ) + "</b> PDA" );
239 239
240 return (infoString); 240 return (infoString);
241} 241}
242 242
243 243
244/** 244/**
245 * Read the current values from the gui and invoke writeConfig() 245 * Read the current values from the gui and invoke writeConfig()
246 */ 246 */
247void BlueBase::applyConfigChanges() 247void BlueBase::applyConfigChanges()
248{ 248{
249 m_deviceName = deviceNameLine->text(); 249 m_deviceName = deviceNameLine->text();
250 m_defaultPasskey = passkeyLine->text(); 250 m_defaultPasskey = passkeyLine->text();
251 m_useEncryption = cryptCheckBox->isChecked(); 251 m_useEncryption = cryptCheckBox->isChecked();
252 m_enableAuthentification = authCheckBox->isChecked(); 252 m_enableAuthentification = authCheckBox->isChecked();
253 m_enablePagescan = pagescanCheckBox->isChecked(); 253 m_enablePagescan = pagescanCheckBox->isChecked();
254 m_enableInquiryscan = inquiryscanCheckBox->isChecked(); 254 m_enableInquiryscan = inquiryscanCheckBox->isChecked();
255 255
256 writeConfig(); 256 writeConfig();
257 257
258 QMessageBox::information( this, tr("Test") , tr("Changes were applied.") ); 258 QMessageBox::information( this, tr("Test") , tr("Changes were applied.") );
259} 259}
260 260
261/** 261/**
262 * Launch Rfcomm Bind dialog 262 * Launch Rfcomm Bind dialog
263 * 263 *
264 */ 264 */
265void BlueBase::rfcommDialog() 265void BlueBase::rfcommDialog()
266{ 266{
267 RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp ); 267 RfcommAssignDialog rfcommAssign ( this, "RfcommAssignDialog", true, WStyle_ContextHelp );
268 268
269 if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted ) 269 if ( QPEApplication::execDialog( &rfcommAssign ) == QDialog::Accepted )
270 { 270 {
271 rfcommAssign.saveConfig(); 271 rfcommAssign.saveConfig();
272 } 272 }
273} 273}
274 274
275/** 275/**
276 * Add fresh found devices from scan dialog to the listing 276 * Add fresh found devices from scan dialog to the listing
277 * 277 *
278 */ 278 */
279void BlueBase::addSearchedDevices( const QValueList<RemoteDevice> &newDevices ) 279void BlueBase::addSearchedDevices( const QValueList<RemoteDevice> &newDevices )
280{ 280{
281 BTDeviceItem * deviceItem; 281 BTDeviceItem * deviceItem;
282 QValueList<RemoteDevice>::ConstIterator it; 282 QValueList<RemoteDevice>::ConstIterator it;
283 283
284 for( it = newDevices.begin(); it != newDevices.end() ; ++it ) 284 for( it = newDevices.begin(); it != newDevices.end() ; ++it )
285 { 285 {
286 286
287 if (find( (*it) )) // is already inserted 287 if (find( (*it) )) // is already inserted
288 continue; 288 continue;
289 289
290 deviceItem = new BTDeviceItem( ListView2 , (*it) ); 290 deviceItem = new BTDeviceItem( ListView2 , (*it) );
291 deviceItem->setPixmap( 1, m_findPix ); 291 deviceItem->setPixmap( 1, m_findPix );
292 deviceItem->setExpandable ( true ); 292 deviceItem->setExpandable ( true );
293 293
294 // look if device is avail. atm, async 294 // look if device is avail. atm, async
295 deviceActive( (*it) ); 295 deviceActive( (*it) );
296 296
297 // ggf auch hier? 297 // ggf auch hier?
298 addServicesToDevice( deviceItem ); 298 addServicesToDevice( deviceItem );
299 } 299 }
300} 300}
301 301
302 302
303/** 303/**
304 * Action that is toggled on entrys on click 304 * Action that is toggled on entrys on click
305 */ 305 */
306void BlueBase::startServiceActionClicked( QListViewItem */*item*/ ) 306void BlueBase::startServiceActionClicked( QListViewItem */*item*/ )
307{} 307{}
308 308
309 309
310/** 310/**
311 * Action that are toggled on hold (mostly QPopups i guess) 311 * Action that are toggled on hold (mostly QPopups i guess)
312 */ 312 */
313void BlueBase::startServiceActionHold( QListViewItem * item, const QPoint & point, int /*column*/ ) 313void BlueBase::startServiceActionHold( QListViewItem * item, const QPoint & point, int /*column*/ )
314{ 314{
315 if (!item ) 315 if (!item )
316 return; 316 return;
317 317
318 QPopupMenu *menu = new QPopupMenu(); 318 QPopupMenu *menu = new QPopupMenu();
319 int ret=0; 319 int ret=0;
320 320
321 if ( ((BTListItem*)item)->type() == "device") 321 if ( ((BTListItem*)item)->type() == "device")
322 { 322 {
323 323
324 QPopupMenu *groups = new QPopupMenu(); 324 QPopupMenu *groups = new QPopupMenu();
325 325
326 menu->insertItem( ((BTDeviceItem*)item)->name(),0 ); 326 menu->insertItem( ((BTDeviceItem*)item)->name(),0 );
327 menu->insertSeparator(1); 327 menu->insertSeparator(1);
328 menu->insertItem( tr("rescan sevices"), 2); 328 menu->insertItem( tr("rescan sevices"), 2);
329 menu->insertItem( tr("to group"), groups , 3); 329 menu->insertItem( tr("to group"), groups , 3);
330 menu->insertItem( tr("delete"), 4); 330 menu->insertItem( tr("delete"), 4);
331 331
332 ret = menu->exec( point , 0); 332 ret = menu->exec( point , 0);
333 333
334 switch(ret) 334 switch(ret)
335 { 335 {
336 case -1: 336 case -1:
337 break; 337 break;
338 case 2: 338 case 2:
339 addServicesToDevice( (BTDeviceItem*)item ); 339 addServicesToDevice( (BTDeviceItem*)item );
340 break; 340 break;
341 341
342 case 4: 342 case 4:
343 // deletes childs too 343 // deletes childs too
344 delete item; 344 delete item;
345 break; 345 break;
346 } 346 }
347 delete groups; 347 delete groups;
348 348
349 } 349 }
350 350
351 /* 351 /*
352 * We got service sensitive PopupMenus in our factory 352 * We got service sensitive PopupMenus in our factory
353 * We will create one through the factory and will insert 353 * We will create one through the factory and will insert
354 * our Separator + ShowInfo into the menu or create a new 354 * our Separator + ShowInfo into the menu or create a new
355 * one if the factory returns 0 355 * one if the factory returns 0
356 * PopupMenu deletion is kind of weird. 356 * PopupMenu deletion is kind of weird.
357 * If escaped( -1 ) or any of our items were chosen we'll 357 * If escaped( -1 ) or any of our items were chosen we'll
358 * delete the PopupMenu otherwise it's the responsibility of 358 * delete the PopupMenu otherwise it's the responsibility of
359 * the PopupMenu to delete itself 359 * the PopupMenu to delete itself
360 * 360 *
361 */ 361 */
362 else if ( ((BTListItem*)item)->type() == "service") 362 else if ( ((BTListItem*)item)->type() == "service")
363 { 363 {
364 BTServiceItem* service = (BTServiceItem*)item; 364 BTServiceItem* service = (BTServiceItem*)item;
365 QMap<int, QString> list = service->services().classIdList(); 365 QMap<int, QString> list = service->services().classIdList();
366 QMap<int, QString>::Iterator it = list.begin(); 366 QMap<int, QString>::Iterator it = list.begin();
367 QPopupMenu *popup =0l; 367 QPopupMenu *popup =0l;
368 if ( it != list.end() ) 368 if ( it != list.end() )
369 { 369 {
370 qWarning("Searching id %d %s", it.key(), it.data().latin1() ); 370 qWarning("Searching id %d %s", it.key(), it.data().latin1() );
371 popup = m_popHelper.find( it.key(), 371 popup = m_popHelper.find( it.key(),
372 service->services(), 372 service->services(),
373 (BTDeviceItem*)service->parent() ); 373 (BTDeviceItem*)service->parent() );
374 } 374 }
375 else 375 else
376 { 376 {
377 qWarning("Empty"); 377 qWarning("Empty");
378 } 378 }
379 379
380 if ( popup == 0l ) 380 if ( popup == 0l )
381 { 381 {
382 qWarning("factory returned 0l"); 382 qWarning("factory returned 0l");
383 popup = new QPopupMenu(); 383 popup = new QPopupMenu();
384 } 384 }
385 int test1 = popup->insertItem( tr("Test1:"), 2); 385 int test1 = popup->insertItem( tr("Test1:"), 2);
386 386
387 ret = popup->exec( point ); 387 ret = popup->exec( point );
388 qWarning("returned from exec() "); 388 qWarning("returned from exec() ");
389 if ( ret == -1 ) 389 if ( ret == -1 )
390 { 390 {
391 ; 391 ;
392 } 392 }
393 else if ( ret == test1 ) 393 else if ( ret == test1 )
394 { 394 {
395 ; 395 ;
396 } 396 }
397 delete popup; 397 delete popup;
398 } 398 }
399 delete menu; 399 delete menu;
400} 400}
401 401
402 402
403/** 403/**
404 * Search and display avail. services for a device (on expand from device listing) 404 * Search and display avail. services for a device (on expand from device listing)
405 * @param item the service item returned 405 * @param item the service item returned
406 */ 406 */
407void BlueBase::addServicesToDevice( BTDeviceItem * item ) 407void BlueBase::addServicesToDevice( BTDeviceItem * item )
408{ 408{
409 qDebug("addServicesToDevice"); 409 qDebug("addServicesToDevice");
410 // row of mac adress text(3) 410 // row of mac adress text(3)
411 RemoteDevice device = item->remoteDevice(); 411 RemoteDevice device = item->remoteDevice();
412 m_deviceList.insert( item->mac() , item ); 412 m_deviceList.insert( item->mac() , item );
413 // and some time later I get a signal foundServices( const QString& device, Services::ValueList ); back 413 // and some time later I get a signal foundServices( const QString& device, Services::ValueList ); back
414 m_localDevice->searchServices( device ); 414 m_localDevice->searchServices( device );
415} 415}
416 416
417 417
418/** 418/**
419 * Overloaded. This one it the one that is 419 * Overloaded. This one it the one that is
420 ted to the foundServices signal 420 ted to the foundServices signal
421 * @param device the mac address of the remote device 421 * @param device the mac address of the remote device
422 * @param servicesList the list with the service the device has. 422 * @param servicesList the list with the service the device has.
423 */ 423 */
424void BlueBase::addServicesToDevice( const QString& device, Services::ValueList servicesList ) 424void BlueBase::addServicesToDevice( const QString& device, Services::ValueList servicesList )
425{ 425{
426 qDebug("fill services list"); 426 qDebug("fill services list");
427 427
428 QMap<QString,BTDeviceItem*>::Iterator it; 428 QMap<QString,BTDeviceItem*>::Iterator it;
429 BTDeviceItem* deviceItem = 0; 429 BTDeviceItem* deviceItem = 0;
430 430
431 // get the right devices which requested the search 431 // get the right devices which requested the search
432 it = m_deviceList.find( device ); 432 it = m_deviceList.find( device );
433 if( it == m_deviceList.end() ) 433 if( it == m_deviceList.end() )
434 return; 434 return;
435 deviceItem = it.data(); 435 deviceItem = it.data();
436 436
437 // remove previous entries 437 // remove previous entries
438 QList<QListViewItem> tempList; 438 QList<QListViewItem> tempList;
439 tempList.setAutoDelete( true ); 439 tempList.setAutoDelete( true );
440 QListViewItem * child = deviceItem->firstChild(); 440 QListViewItem * child = deviceItem->firstChild();
441 while( child ) 441 while( child )
442 { 442 {
443 tempList.append( child ); 443 tempList.append( child );
444 child = child->nextSibling(); 444 child = child->nextSibling();
445 } 445 }
446 tempList.clear(); 446 tempList.clear();
447 447
448 QValueList<OpieTooth::Services>::Iterator it2; 448 QValueList<OpieTooth::Services>::Iterator it2;
449 BTServiceItem* serviceItem; 449 BTServiceItem* serviceItem;
450 450
451 451
452 if (!servicesList.isEmpty() ) 452 if (!servicesList.isEmpty() )
453 { 453 {
454 // add services 454 // add services
455 QMap<int, QString> list; 455 QMap<int, QString> list;
456 QMap<int, QString>::Iterator classIt; 456 QMap<int, QString>::Iterator classIt;
457 for( it2 = servicesList.begin(); it2 != servicesList.end(); ++it2 ) 457 for( it2 = servicesList.begin(); it2 != servicesList.end(); ++it2 )
458 { 458 {
459 serviceItem = new BTServiceItem( deviceItem, (*it2) ); 459 serviceItem = new BTServiceItem( deviceItem, (*it2) );
460 list = (*it2).classIdList(); 460 list = (*it2).classIdList();
461 classIt = list.begin(); 461 classIt = list.begin();
462 int classId=0; 462 int classId=0;
463 if ( classIt != list.end() ) 463 if ( classIt != list.end() )
464 { 464 {
465 classId = classIt.key(); 465 classId = classIt.key();
466 } 466 }
467 467
468 serviceItem->setPixmap( 0, m_iconLoader->serviceIcon( classId ) ); 468 serviceItem->setPixmap( 0, m_iconLoader->serviceIcon( classId ) );
469 } 469 }
470 } 470 }
471 else 471 else
472 { 472 {
473 Services s1; 473 Services s1;
474 s1.setServiceName( tr("no services found") ); 474 s1.setServiceName( tr("no services found") );
475 serviceItem = new BTServiceItem( deviceItem, s1 ); 475 serviceItem = new BTServiceItem( deviceItem, s1 );
476 } 476 }
477 // now remove them from the list 477 // now remove them from the list
478 m_deviceList.remove( it ); 478 m_deviceList.remove( it );
479} 479}
480 480
481 481
482 482
483 483
484 484
485void BlueBase::addSignalStrength() 485void BlueBase::addSignalStrength()
486{ 486{
487 487
488 QListViewItemIterator it( ListView4 ); 488 QListViewItemIterator it( ListView4 );
489 for ( ; it.current(); ++it ) 489 for ( ; it.current(); ++it )
490 { 490 {
491 m_localDevice->signalStrength( ((BTConnectionItem*)it.current() )->connection().mac() ); 491 m_localDevice->signalStrength( ((BTConnectionItem*)it.current() )->connection().mac() );
492 } 492 }
493 493
494 QTimer::singleShot( 5000, this, SLOT( addSignalStrength() ) ); 494 QTimer::singleShot( 5000, this, SLOT( addSignalStrength() ) );
495} 495}
496 496
497void BlueBase::addSignalStrength( const QString& mac, const QString& strength ) 497void BlueBase::addSignalStrength( const QString& mac, const QString& strength )
498{ 498{
499 499
500 QListViewItemIterator it( ListView4 ); 500 QListViewItemIterator it( ListView4 );
501 for ( ; it.current(); ++it ) 501 for ( ; it.current(); ++it )
502 { 502 {
503 if( ((BTConnectionItem*)it.current())->connection().mac() == mac ) 503 if( ((BTConnectionItem*)it.current())->connection().mac() == mac )
504 { 504 {
505 ((BTConnectionItem*)it.current() )->setSignalStrength( strength ); 505 ((BTConnectionItem*)it.current() )->setSignalStrength( strength );
506 } 506 }
507 } 507 }
508} 508}
509 509
510/** 510/**
511 * Add the existing connections (pairs) to the connections tab. 511 * Add the existing connections (pairs) to the connections tab.
512 * This one triggers the search 512 * This one triggers the search
513 */ 513 */
514void BlueBase::addConnectedDevices() 514void BlueBase::addConnectedDevices()
515{ 515{
516 m_localDevice->searchConnections(); 516 m_localDevice->searchConnections();
517} 517}
518 518
519/** 519/**
520 * This adds the found connections to the connection tab. 520 * This adds the found connections to the connection tab.
521 * @param connectionList the ValueList with all current connections 521 * @param connectionList the ValueList with all current connections
522 */ 522 */
523void BlueBase::addConnectedDevices( ConnectionState::ValueList connectionList ) 523void BlueBase::addConnectedDevices( ConnectionState::ValueList connectionList )
524{ 524{
525 525
526 QValueList<OpieTooth::ConnectionState>::Iterator it; 526 QValueList<OpieTooth::ConnectionState>::Iterator it;
527 BTConnectionItem * connectionItem; 527 BTConnectionItem * connectionItem;
528 528
529 if ( !connectionList.isEmpty() ) 529 if ( !connectionList.isEmpty() )
530 { 530 {
531 531
532 for (it = connectionList.begin(); it != connectionList.end(); ++it) 532 for (it = connectionList.begin(); it != connectionList.end(); ++it)
533 { 533 {
534 534
535 QListViewItemIterator it2( ListView4 ); 535 QListViewItemIterator it2( ListView4 );
536 bool found = false; 536 bool found = false;
537 for ( ; it2.current(); ++it2 ) 537 for ( ; it2.current(); ++it2 )
538 { 538 {
539 if( ( (BTConnectionItem*)it2.current())->connection().mac() == (*it).mac() ) 539 if( ( (BTConnectionItem*)it2.current())->connection().mac() == (*it).mac() )
540 { 540 {
541 found = true; 541 found = true;
542 } 542 }
543 } 543 }
544 544
545 if ( found == false ) 545 if ( found == false )
546 { 546 {
547 connectionItem = new BTConnectionItem( ListView4, (*it) ); 547 connectionItem = new BTConnectionItem( ListView4, (*it) );
548 548
549 if( m_deviceList.find((*it).mac()).data() ) 549 if( m_deviceList.find((*it).mac()).data() )
550 { 550 {
551 connectionItem->setName( m_deviceList.find( (*it).mac()).data()->name() ); 551 connectionItem->setName( m_deviceList.find( (*it).mac()).data()->name() );
552 } 552 }
553 } 553 }
554 554
555 } 555 }
556 556
557 QListViewItemIterator it2( ListView4 ); 557 QListViewItemIterator it2( ListView4 );
558 for ( ; it2.current(); ++it2 ) 558 for ( ; it2.current(); ++it2 )
559 { 559 {
560 bool found = false; 560 bool found = false;
561 for (it = connectionList.begin(); it != connectionList.end(); ++it) 561 for (it = connectionList.begin(); it != connectionList.end(); ++it)
562 { 562 {
563 if( ( ((BTConnectionItem*)it2.current())->connection().mac() ) == (*it).mac() ) 563 if( ( ((BTConnectionItem*)it2.current())->connection().mac() ) == (*it).mac() )
564 { 564 {
565 found = true; 565 found = true;
566 } 566 }
567 } 567 }
568 568
569 if ( !found ) 569 if ( !found )
570 { 570 {
571 delete it2.current(); 571 delete it2.current();
572 } 572 }
573 573
574 } 574 }
575 575
576 576
577 } 577 }
578 else 578 else
579 { 579 {
580 ListView4->clear(); 580 ListView4->clear();
581 ConnectionState con; 581 ConnectionState con;
582 con.setMac( tr("No connections found") ); 582 con.setMac( tr("No connections found") );
583 connectionItem = new BTConnectionItem( ListView4 , con ); 583 connectionItem = new BTConnectionItem( ListView4 , con );
584 } 584 }
585 585
586 // recall connection search after some time 586 // recall connection search after some time
587 QTimer::singleShot( 15000, this, SLOT( addConnectedDevices() ) ); 587 QTimer::singleShot( 15000, this, SLOT( addConnectedDevices() ) );
588} 588}
589 589
590 590
591/** 591/**
592 * Find out if a device can currently be reached 592 * Find out if a device can currently be reached
593 * @param device 593 * @param device
594 */ 594 */
595void BlueBase::deviceActive( const RemoteDevice &device ) 595void BlueBase::deviceActive( const RemoteDevice &device )
596{ 596{
597 // search by mac, async, gets a signal back 597 // search by mac, async, gets a signal back
598 // We should have a BTDeviceItem there or where does it get added to the map -zecke 598 // We should have a BTDeviceItem there or where does it get added to the map -zecke
599 m_localDevice->isAvailable( device.mac() ); 599 m_localDevice->isAvailable( device.mac() );
600} 600}
601 601
602 602
603/** 603/**
604 * The signal catcher. Set the avail. status on device. 604 * The signal catcher. Set the avail. status on device.
605 * @param device - the mac address 605 * @param device - the mac address
606 * @param connected - if it is avail. or not 606 * @param connected - if it is avail. or not
607 */ 607 */
608void BlueBase::deviceActive( const QString& device, bool connected ) 608void BlueBase::deviceActive( const QString& device, bool connected )
609{ 609{
610 qDebug("deviceActive slot"); 610 qDebug("deviceActive slot");
611 611
612 QMap<QString,BTDeviceItem*>::Iterator it; 612 QMap<QString,BTDeviceItem*>::Iterator it;
613 613
614 it = m_deviceList.find( device ); 614 it = m_deviceList.find( device );
615 if( it == m_deviceList.end() ) 615 if( it == m_deviceList.end() )
616 return; 616 return;
617 617
618 BTDeviceItem* deviceItem = it.data(); 618 BTDeviceItem* deviceItem = it.data();
619 619
620 620
621 if ( connected ) 621 if ( connected )
622 { 622 {
623 deviceItem->setPixmap( 1, m_onPix ); 623 deviceItem->setPixmap( 1, m_onPix );
624 } 624 }
625 else 625 else
626 { 626 {
627 deviceItem->setPixmap( 1, m_offPix ); 627 deviceItem->setPixmap( 1, m_offPix );
628 } 628 }
629 m_deviceList.remove( it ); 629 m_deviceList.remove( it );
630} 630}
631 631
632 632
633/** 633/**
634 * Open the "scan for devices" dialog 634 * Open the "scan for devices" dialog
635 */ 635 */
636void BlueBase::startScan() 636void BlueBase::startScan()
637{ 637{
638 ScanDialog *scan = new ScanDialog( this, "ScanDialog", 638 ScanDialog *scan = new ScanDialog( this, "ScanDialog",
639 true, WDestructiveClose ); 639 true, WDestructiveClose );
640 QObject::connect( scan, SIGNAL( selectedDevices( const QValueList<RemoteDevice>& ) ), 640 QObject::connect( scan, SIGNAL( selectedDevices(const QValueList<RemoteDevice>&) ),
641 this, SLOT( addSearchedDevices( const QValueList<RemoteDevice>& ) ) ); 641 this, SLOT( addSearchedDevices(const QValueList<RemoteDevice>&) ) );
642 642
643 QPEApplication::showDialog( scan ); 643 QPEApplication::showDialog( scan );
644} 644}
645 645
646 646
647/** 647/**
648 * Set the informations about the local device in information Tab 648 * Set the informations about the local device in information Tab
649 */ 649 */
650void BlueBase::setInfo() 650void BlueBase::setInfo()
651{ 651{
652 StatusLabel->setText( status() ); 652 StatusLabel->setText( status() );
653} 653}
654 654
655 655
656/** 656/**
657 * Decontructor 657 * Decontructor
658 */ 658 */
659BlueBase::~BlueBase() 659BlueBase::~BlueBase()
660{ 660{
661 writeSavedDevices(); 661 writeSavedDevices();
662 delete m_iconLoader; 662 delete m_iconLoader;
663} 663}
664 664
665 665
666/** 666/**
667 * find searches the ListView for a BTDeviceItem containig 667 * find searches the ListView for a BTDeviceItem containig
668 * the same Device if found return true else false 668 * the same Device if found return true else false
669 * @param dev RemoteDevice to find 669 * @param dev RemoteDevice to find
670 * @return returns true if found 670 * @return returns true if found
671 */ 671 */
672bool BlueBase::find( const RemoteDevice& rem ) 672bool BlueBase::find( const RemoteDevice& rem )
673{ 673{
674 QListViewItemIterator it( ListView2 ); 674 QListViewItemIterator it( ListView2 );
675 BTListItem* item; 675 BTListItem* item;
676 BTDeviceItem* device; 676 BTDeviceItem* device;
677 for (; it.current(); ++it ) 677 for (; it.current(); ++it )
678 { 678 {
679 item = (BTListItem*) it.current(); 679 item = (BTListItem*) it.current();
680 if ( item->typeId() != BTListItem::Device ) 680 if ( item->typeId() != BTListItem::Device )
681 continue; 681 continue;
682 682
683 device = (BTDeviceItem*)item; 683 device = (BTDeviceItem*)item;
684 if ( rem.equals( device->remoteDevice() ) ) 684 if ( rem.equals( device->remoteDevice() ) )
685 return true; 685 return true;
686 } 686 }
687 return false; // not found 687 return false; // not found
688} 688}
diff --git a/noncore/net/opietooth/manager/obexdialog.cpp b/noncore/net/opietooth/manager/obexdialog.cpp
index 15973d4..46a0e3d 100644
--- a/noncore/net/opietooth/manager/obexdialog.cpp
+++ b/noncore/net/opietooth/manager/obexdialog.cpp
@@ -1,86 +1,86 @@
1 1
2#include "obexdialog.h" 2#include "obexdialog.h"
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4#include <qmultilineedit.h> 4#include <qmultilineedit.h>
5#include <qlineedit.h> 5#include <qlineedit.h>
6#include <qlayout.h> 6#include <qlayout.h>
7#include <qlabel.h> 7#include <qlabel.h>
8#include <qfileinfo.h> 8#include <qfileinfo.h>
9 9
10#include <qpe/resource.h> 10#include <qpe/resource.h>
11 11
12#include <opie/oprocess.h> 12#include <opie/oprocess.h>
13#include <opie/ofiledialog.h> 13#include <opie/ofiledialog.h>
14 14
15using namespace OpieTooth; 15using namespace OpieTooth;
16 16
17ObexDialog::ObexDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device ) 17ObexDialog::ObexDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device )
18 : QDialog( parent, name, modal, fl ) { 18 : QDialog( parent, name, modal, fl ) {
19 19
20 if ( !name ) 20 if ( !name )
21 setName( "ObexDialog" ); 21 setName( "ObexDialog" );
22 setCaption( tr( "beam files " ) ) ; 22 setCaption( tr( "beam files " ) ) ;
23 23
24 m_device = device; 24 m_device = device;
25 25
26 layout = new QVBoxLayout( this ); 26 layout = new QVBoxLayout( this );
27 27
28 QLabel* info = new QLabel( this ); 28 QLabel* info = new QLabel( this );
29 info->setText( tr("Which file should be beamed?") ); 29 info->setText( tr("Which file should be beamed?") );
30 30
31 cmdLine = new QLineEdit( this ); 31 cmdLine = new QLineEdit( this );
32 32
33 QPushButton *browserButton; 33 QPushButton *browserButton;
34 browserButton = new QPushButton( Resource::loadIconSet("fileopen"),"",this,"BrowseButton"); 34 browserButton = new QPushButton( Resource::loadIconSet("fileopen"),"",this,"BrowseButton");
35 connect( browserButton, SIGNAL(released() ), this , SLOT(browse() ) ); 35 connect( browserButton, SIGNAL(released() ), this , SLOT(browse() ) );
36 36
37 chNameLine = new QLineEdit( this ); 37 chNameLine = new QLineEdit( this );
38 38
39 sendButton = new QPushButton( this ); 39 sendButton = new QPushButton( this );
40 sendButton->setText( tr( "Send" ) ); 40 sendButton->setText( tr( "Send" ) );
41 41
42 layout->addWidget(info); 42 layout->addWidget(info);
43 layout->addWidget(cmdLine); 43 layout->addWidget(cmdLine);
44 layout->addWidget(browserButton); 44 layout->addWidget(browserButton);
45 layout->addWidget(chNameLine); 45 layout->addWidget(chNameLine);
46 layout->addWidget(sendButton); 46 layout->addWidget(sendButton);
47 47
48 connect( sendButton, SIGNAL( clicked() ), this, SLOT( sendData() ) ); 48 connect( sendButton, SIGNAL( clicked() ), this, SLOT( sendData() ) );
49 49
50} 50}
51 51
52ObexDialog::~ObexDialog() { 52ObexDialog::~ObexDialog() {
53} 53}
54 54
55void ObexDialog::browse() { 55void ObexDialog::browse() {
56 56
57 MimeTypes types; 57 MimeTypes types;
58 QStringList all; 58 QStringList all;
59 all << "*/*"; 59 all << "*/*";
60 types.insert("All Files", all ); 60 types.insert("All Files", all );
61 61
62 QString str = OFileDialog::getOpenFileName( 1,"/","", types, 0 ); 62 QString str = OFileDialog::getOpenFileName( 1,"/","", types, 0 );
63 cmdLine->setText( str ); 63 cmdLine->setText( str );
64 64
65} 65}
66 66
67void ObexDialog::sendData() { 67void ObexDialog::sendData() {
68 QString fileURL = cmdLine->text(); 68 QString fileURL = cmdLine->text();
69 QString file = QFileInfo( fileURL ).fileName(); 69 QString file = QFileInfo( fileURL ).fileName();
70 QString modifiedName = chNameLine->text(); 70 QString modifiedName = chNameLine->text();
71 71
72 // vom popupmenu beziehen 72 // vom popupmenu beziehen
73 OProcess* obexSend = new OProcess(); 73 OProcess* obexSend = new OProcess();
74 if ( !modifiedName.isEmpty() ) { 74 if ( !modifiedName.isEmpty() ) {
75 *obexSend << "ussp-push" << m_device << fileURL << modifiedName; 75 *obexSend << "ussp-push" << m_device << fileURL << modifiedName;
76 } else { 76 } else {
77 *obexSend << "ussp-push" << m_device << fileURL << file; 77 *obexSend << "ussp-push" << m_device << fileURL << file;
78 } 78 }
79 if (!obexSend->start(OProcess::DontCare, OProcess::AllOutput) ) { 79 if (!obexSend->start(OProcess::DontCare, OProcess::AllOutput) ) {
80 qWarning("could not start"); 80 qWarning("could not start");
81 delete obexSend; 81 delete obexSend;
82 } 82 }
83 83
84 84
85 85
86} 86}
diff --git a/noncore/net/opietooth/manager/pppdialog.cpp b/noncore/net/opietooth/manager/pppdialog.cpp
index 1f347ce..4e58552 100644
--- a/noncore/net/opietooth/manager/pppdialog.cpp
+++ b/noncore/net/opietooth/manager/pppdialog.cpp
@@ -1,68 +1,68 @@
1 1
2#include "pppdialog.h" 2#include "pppdialog.h"
3#include <qpushbutton.h> 3#include <qpushbutton.h>
4#include <qmultilineedit.h> 4#include <qmultilineedit.h>
5#include <qlineedit.h> 5#include <qlineedit.h>
6#include <qlayout.h> 6#include <qlayout.h>
7#include <qlabel.h> 7#include <qlabel.h>
8#include <opie/oprocess.h> 8#include <opie/oprocess.h>
9 9
10using namespace OpieTooth; 10using namespace OpieTooth;
11 11
12PPPDialog::PPPDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device ) 12PPPDialog::PPPDialog( QWidget* parent, const char* name, bool modal, WFlags fl, const QString& device )
13 : QDialog( parent, name, modal, fl ) { 13 : QDialog( parent, name, modal, fl ) {
14 14
15 if ( !name ) 15 if ( !name )
16 setName( "PPPDialog" ); 16 setName( "PPPDialog" );
17 setCaption( tr( "ppp connection " ) ) ; 17 setCaption( tr( "ppp connection " ) ) ;
18 18
19 m_device = device; 19 m_device = device;
20 20
21 layout = new QVBoxLayout( this ); 21 layout = new QVBoxLayout( this );
22 22
23 QLabel* info = new QLabel( this ); 23 QLabel* info = new QLabel( this );
24 info->setText( tr("Enter an ppp script name:") ); 24 info->setText( tr("Enter an ppp script name:") );
25 25
26 cmdLine = new QLineEdit( this ); 26 cmdLine = new QLineEdit( this );
27 27
28 outPut = new QMultiLineEdit( this ); 28 outPut = new QMultiLineEdit( this );
29 QFont outPut_font( outPut->font() ); 29 QFont outPut_font( outPut->font() );
30 outPut_font.setPointSize( 8 ); 30 outPut_font.setPointSize( 8 );
31 outPut->setFont( outPut_font ); 31 outPut->setFont( outPut_font );
32 outPut->setWordWrap( QMultiLineEdit::WidgetWidth ); 32 outPut->setWordWrap( QMultiLineEdit::WidgetWidth );
33 33
34 connectButton = new QPushButton( this ); 34 connectButton = new QPushButton( this );
35 connectButton->setText( tr( "Connect" ) ); 35 connectButton->setText( tr( "Connect" ) );
36 36
37 layout->addWidget(info); 37 layout->addWidget(info);
38 layout->addWidget(cmdLine); 38 layout->addWidget(cmdLine);
39 layout->addWidget(outPut); 39 layout->addWidget(outPut);
40 layout->addWidget(connectButton); 40 layout->addWidget(connectButton);
41 41
42 connect( connectButton, SIGNAL( clicked() ), this, SLOT( connectToDevice() ) ); 42 connect( connectButton, SIGNAL( clicked() ), this, SLOT( connectToDevice() ) );
43 43
44} 44}
45 45
46PPPDialog::~PPPDialog() { 46PPPDialog::~PPPDialog() {
47} 47}
48 48
49void PPPDialog::connectToDevice() { 49void PPPDialog::connectToDevice() {
50 outPut->clear(); 50 outPut->clear();
51 // vom popupmenu beziehen 51 // vom popupmenu beziehen
52 QString connectScript = "/etc/ppp/peers/" + cmdLine->text(); 52 QString connectScript = "/etc/ppp/peers/" + cmdLine->text();
53 OProcess* pppDial = new OProcess(); 53 OProcess* pppDial = new OProcess();
54 *pppDial << "pppd" << m_device << "call" << connectScript; 54 *pppDial << "pppd" << m_device << "call" << connectScript;
55 connect( pppDial, SIGNAL(receivedStdout(OProcess*, char*, int ) ), 55 connect( pppDial, SIGNAL(receivedStdout(OProcess*,char*,int) ),
56 this, SLOT(fillOutPut(OProcess*, char*, int ) ) ); 56 this, SLOT(fillOutPut(OProcess*,char*,int) ) );
57 if (!pppDial->start(OProcess::DontCare, OProcess::AllOutput) ) { 57 if (!pppDial->start(OProcess::DontCare, OProcess::AllOutput) ) {
58 qWarning("could not start"); 58 qWarning("could not start");
59 delete pppDial; 59 delete pppDial;
60 } 60 }
61} 61}
62 62
63void PPPDialog::fillOutPut( OProcess* pppDial, char* cha, int len ) { 63void PPPDialog::fillOutPut( OProcess* pppDial, char* cha, int len ) {
64 QCString str(cha, len ); 64 QCString str(cha, len );
65 outPut->insertLine( str ); 65 outPut->insertLine( str );
66 delete pppDial; 66 delete pppDial;
67} 67}
68 68
diff --git a/noncore/net/opietooth/manager/scandialog.cpp b/noncore/net/opietooth/manager/scandialog.cpp
index de4f742..c8ea3e3 100644
--- a/noncore/net/opietooth/manager/scandialog.cpp
+++ b/noncore/net/opietooth/manager/scandialog.cpp
@@ -1,161 +1,161 @@
1/* main.cpp 1/* main.cpp
2 * 2 *
3 * --------------------- 3 * ---------------------
4 * 4 *
5 * copyright : (c) 2002 by Maximilian Reiß 5 * copyright : (c) 2002 by Maximilian Reiß
6 * email : max.reiss@gmx.de 6 * email : max.reiss@gmx.de
7 * 7 *
8 */ 8 */
9/*************************************************************************** 9/***************************************************************************
10 * * 10 * *
11 * This program is free software; you can redistribute it and/or modify * 11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by * 12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or * 13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. * 14 * (at your option) any later version. *
15 * * 15 * *
16 ***************************************************************************/ 16 ***************************************************************************/
17 17
18 18
19#include "scandialog.h" 19#include "scandialog.h"
20 20
21#include <qheader.h> 21#include <qheader.h>
22#include <qlistview.h> 22#include <qlistview.h>
23#include <qpushbutton.h> 23#include <qpushbutton.h>
24#include <qlayout.h> 24#include <qlayout.h>
25#include <qvariant.h> 25#include <qvariant.h>
26#include <qtooltip.h> 26#include <qtooltip.h>
27#include <qwhatsthis.h> 27#include <qwhatsthis.h>
28#include <qprogressbar.h> 28#include <qprogressbar.h>
29#include <qlist.h> 29#include <qlist.h>
30 30
31#include <manager.h> 31#include <manager.h>
32#include <device.h> 32#include <device.h>
33 33
34 34
35namespace OpieTooth { 35namespace OpieTooth {
36 36
37#include <remotedevice.h> 37#include <remotedevice.h>
38 38
39/** 39/**
40 */ 40 */
41 ScanDialog::ScanDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) 41 ScanDialog::ScanDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
42 : QDialog( parent, name, modal, fl ) { 42 : QDialog( parent, name, modal, fl ) {
43 43
44 setCaption( tr( "Scan for devices" ) ); 44 setCaption( tr( "Scan for devices" ) );
45 45
46 Layout11 = new QVBoxLayout( this ); 46 Layout11 = new QVBoxLayout( this );
47 Layout11->setSpacing( 6 ); 47 Layout11->setSpacing( 6 );
48 Layout11->setMargin( 0 ); 48 Layout11->setMargin( 0 );
49 49
50 progress = new QProgressBar( this, "progbar"); 50 progress = new QProgressBar( this, "progbar");
51 progress->setTotalSteps(20); 51 progress->setTotalSteps(20);
52 52
53 StartStopButton = new QPushButton( this, "StartButton" ); 53 StartStopButton = new QPushButton( this, "StartButton" );
54 StartStopButton->setText( tr( "Start scan" ) ); 54 StartStopButton->setText( tr( "Start scan" ) );
55 55
56 ListView1 = new QListView( this, "ListView1" ); 56 ListView1 = new QListView( this, "ListView1" );
57 57
58 //ListView1->addColumn( tr( "Add" ) ); 58 //ListView1->addColumn( tr( "Add" ) );
59 ListView1->addColumn( tr( "Add Device" ) ); 59 ListView1->addColumn( tr( "Add Device" ) );
60 //ListView1->addColumn( tr( "Type" ) ); 60 //ListView1->addColumn( tr( "Type" ) );
61 61
62 Layout11->addWidget( ListView1 ); 62 Layout11->addWidget( ListView1 );
63 Layout11->addWidget( progress ); 63 Layout11->addWidget( progress );
64 Layout11->addWidget( StartStopButton ); 64 Layout11->addWidget( StartStopButton );
65 65
66 localDevice = new Manager( "hci0" ); 66 localDevice = new Manager( "hci0" );
67 67
68 connect( StartStopButton, SIGNAL( clicked() ), this, SLOT( startSearch() ) ); 68 connect( StartStopButton, SIGNAL( clicked() ), this, SLOT( startSearch() ) );
69 connect( localDevice, SIGNAL( foundDevices( const QString& , RemoteDevice::ValueList ) ), 69 connect( localDevice, SIGNAL( foundDevices(const QString&,RemoteDevice::ValueList) ),
70 this, SLOT( fillList( const QString& , RemoteDevice::ValueList ) ) ) ; 70 this, SLOT( fillList(const QString&,RemoteDevice::ValueList) ) ) ;
71 71
72 progressStat = 0; 72 progressStat = 0;
73 m_search = false; 73 m_search = false;
74 } 74 }
75 75
76// hack, make cleaner later 76// hack, make cleaner later
77 void ScanDialog::progressTimer() { 77 void ScanDialog::progressTimer() {
78 78
79 progressStat++; 79 progressStat++;
80 if ( progressStat++ < 20 && m_search ) { 80 if ( progressStat++ < 20 && m_search ) {
81 QTimer::singleShot( 2000, this, SLOT( progressTimer() ) ); 81 QTimer::singleShot( 2000, this, SLOT( progressTimer() ) );
82 progress->setProgress( progressStat++ ); 82 progress->setProgress( progressStat++ );
83 } 83 }
84 } 84 }
85 85
86 void ScanDialog::accept() { 86 void ScanDialog::accept() {
87 emitToManager(); 87 emitToManager();
88 QDialog::accept(); 88 QDialog::accept();
89 } 89 }
90 90
91 91
92 void ScanDialog::startSearch() { 92 void ScanDialog::startSearch() {
93 if ( m_search ) { 93 if ( m_search ) {
94 stopSearch(); 94 stopSearch();
95 return; 95 return;
96 } 96 }
97 m_search = true; 97 m_search = true;
98 progress->setProgress(0); 98 progress->setProgress(0);
99 progressStat = 0; 99 progressStat = 0;
100 100
101 // empty list before a new scan 101 // empty list before a new scan
102 ListView1->clear(); 102 ListView1->clear();
103 103
104 progressTimer(); 104 progressTimer();
105 // when finished, it emmite foundDevices() 105 // when finished, it emmite foundDevices()
106 // checken ob initialisiert , qcop ans applet. 106 // checken ob initialisiert , qcop ans applet.
107 StartStopButton->setText( tr( "Stop scan" ) ); 107 StartStopButton->setText( tr( "Stop scan" ) );
108 108
109 localDevice->searchDevices(); 109 localDevice->searchDevices();
110 110
111 } 111 }
112 112
113 void ScanDialog::stopSearch() { 113 void ScanDialog::stopSearch() {
114 m_search = true; 114 m_search = true;
115 } 115 }
116 116
117 void ScanDialog::fillList(const QString&, RemoteDevice::ValueList deviceList) { 117 void ScanDialog::fillList(const QString&, RemoteDevice::ValueList deviceList) {
118 progress->setProgress(0); 118 progress->setProgress(0);
119 progressStat = 0; 119 progressStat = 0;
120 QCheckListItem * deviceItem; 120 QCheckListItem * deviceItem;
121 121
122 RemoteDevice::ValueList::Iterator it; 122 RemoteDevice::ValueList::Iterator it;
123 for( it = deviceList.begin(); it != deviceList.end(); ++it ) { 123 for( it = deviceList.begin(); it != deviceList.end(); ++it ) {
124 124
125 deviceItem = new QCheckListItem( ListView1, (*it).name(), QCheckListItem::CheckBox ); 125 deviceItem = new QCheckListItem( ListView1, (*it).name(), QCheckListItem::CheckBox );
126 deviceItem->setText( 1, (*it).mac() ); 126 deviceItem->setText( 1, (*it).mac() );
127 } 127 }
128 m_search = false; 128 m_search = false;
129 StartStopButton->setText( tr( "Start scan" ) ); 129 StartStopButton->setText( tr( "Start scan" ) );
130 } 130 }
131 131
132/** 132/**
133 * Iterates trough the items, and collects the checked items. 133 * Iterates trough the items, and collects the checked items.
134 * Then it emits it, so the manager can connect to the signal to fill the listing. 134 * Then it emits it, so the manager can connect to the signal to fill the listing.
135 */ 135 */
136 void ScanDialog::emitToManager() { 136 void ScanDialog::emitToManager() {
137 137
138 if (!ListView1) { 138 if (!ListView1) {
139 return; 139 return;
140 } 140 }
141 141
142 QValueList<RemoteDevice> deviceList; 142 QValueList<RemoteDevice> deviceList;
143 143
144 QListViewItemIterator it( ListView1 ); 144 QListViewItemIterator it( ListView1 );
145 for ( ; it.current(); ++it ) { 145 for ( ; it.current(); ++it ) {
146 if ( ( (QCheckListItem*)it.current() )->isOn() ) { 146 if ( ( (QCheckListItem*)it.current() )->isOn() ) {
147 RemoteDevice device( it.current()->text(1), it.current()->text(0) ); 147 RemoteDevice device( it.current()->text(1), it.current()->text(0) );
148 deviceList.append( device ); 148 deviceList.append( device );
149 } 149 }
150 } 150 }
151 emit selectedDevices( deviceList ); 151 emit selectedDevices( deviceList );
152 } 152 }
153 153
154/** 154/**
155 * Cleanup 155 * Cleanup
156 */ 156 */
157 ScanDialog::~ScanDialog() { 157 ScanDialog::~ScanDialog() {
158 qWarning("delete scan dialog"); 158 qWarning("delete scan dialog");
159 delete localDevice; 159 delete localDevice;
160 } 160 }
161} 161}
diff --git a/noncore/settings/appearance2/appearance.cpp b/noncore/settings/appearance2/appearance.cpp
index b39203b..8ae87fe 100644
--- a/noncore/settings/appearance2/appearance.cpp
+++ b/noncore/settings/appearance2/appearance.cpp
@@ -1,889 +1,889 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 Copyright (c) 2002 Trolltech AS <info@trolltech.com> 3 Copyright (c) 2002 Trolltech AS <info@trolltech.com>
4 =. Copyright (c) 2002 Dan Williams <williamsdr@acm.org> 4 =. Copyright (c) 2002 Dan Williams <williamsdr@acm.org>
5             .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> 5             .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org>
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include "appearance.h" 30#include "appearance.h"
31#include "editScheme.h" 31#include "editScheme.h"
32#include "stylelistitem.h" 32#include "stylelistitem.h"
33#include "decolistitem.h" 33#include "decolistitem.h"
34#include "colorlistitem.h" 34#include "colorlistitem.h"
35#include "exceptlistitem.h" 35#include "exceptlistitem.h"
36#include "sample.h" 36#include "sample.h"
37 37
38/* OPIE */ 38/* OPIE */
39#include <opie2/odevice.h> 39#include <opie2/odevice.h>
40#include <opie2/ofiledialog.h> 40#include <opie2/ofiledialog.h>
41#include <opie2/otabwidget.h> 41#include <opie2/otabwidget.h>
42 42
43#include <qpe/config.h> 43#include <qpe/config.h>
44#include <qpe/global.h> 44#include <qpe/global.h>
45#include <qpe/qpeapplication.h> 45#include <qpe/qpeapplication.h>
46#include <qpe/qpemessagebox.h> 46#include <qpe/qpemessagebox.h>
47#include <qpe/qcopenvelope_qws.h> 47#include <qpe/qcopenvelope_qws.h>
48#include <qpe/qpestyle.h> 48#include <qpe/qpestyle.h>
49#include <qpe/lightstyle.h> 49#include <qpe/lightstyle.h>
50#include <qpe/styleinterface.h> 50#include <qpe/styleinterface.h>
51 51
52/* QT */ 52/* QT */
53#include <qbuttongroup.h> 53#include <qbuttongroup.h>
54#include <qcheckbox.h> 54#include <qcheckbox.h>
55#include <qcombobox.h> 55#include <qcombobox.h>
56#include <qdialog.h> 56#include <qdialog.h>
57#include <qdir.h> 57#include <qdir.h>
58#include <qlabel.h> 58#include <qlabel.h>
59#include <qlayout.h> 59#include <qlayout.h>
60#include <qlineedit.h> 60#include <qlineedit.h>
61#include <qlistbox.h> 61#include <qlistbox.h>
62#include <qmessagebox.h> 62#include <qmessagebox.h>
63#include <qpushbutton.h> 63#include <qpushbutton.h>
64#include <qradiobutton.h> 64#include <qradiobutton.h>
65#if QT_VERSION >= 300 65#if QT_VERSION >= 300
66#include <qstylefactory.h> 66#include <qstylefactory.h>
67#endif 67#endif
68#include <qtoolbutton.h> 68#include <qtoolbutton.h>
69#include <qwindowsstyle.h> 69#include <qwindowsstyle.h>
70#include <qlistview.h> 70#include <qlistview.h>
71#include <qheader.h> 71#include <qheader.h>
72#include <qvbox.h> 72#include <qvbox.h>
73#include <qwhatsthis.h> 73#include <qwhatsthis.h>
74 74
75using namespace Opie; 75using namespace Opie;
76 76
77 77
78class DefaultWindowDecoration : public WindowDecorationInterface 78class DefaultWindowDecoration : public WindowDecorationInterface
79{ 79{
80public: 80public:
81 DefaultWindowDecoration() : ref(0) {} 81 DefaultWindowDecoration() : ref(0) {}
82 QString name() const 82 QString name() const
83 { 83 {
84 return "Default"; 84 return "Default";
85 } 85 }
86 QPixmap icon() const 86 QPixmap icon() const
87 { 87 {
88 return QPixmap(); 88 return QPixmap();
89 } 89 }
90 QRESULT queryInterface( const QUuid &uuid, QUnknownInterface **iface ) 90 QRESULT queryInterface( const QUuid &uuid, QUnknownInterface **iface )
91 { 91 {
92 *iface = 0; 92 *iface = 0;
93 if ( uuid == IID_QUnknown ) 93 if ( uuid == IID_QUnknown )
94 *iface = this; 94 *iface = this;
95 else if ( uuid == IID_WindowDecoration ) 95 else if ( uuid == IID_WindowDecoration )
96 *iface = this; 96 *iface = this;
97 97
98 if ( *iface ) 98 if ( *iface )
99 (*iface)->addRef(); 99 (*iface)->addRef();
100 return QS_OK; 100 return QS_OK;
101 } 101 }
102 Q_REFCOUNT 102 Q_REFCOUNT
103 103
104private: 104private:
105 ulong ref; 105 ulong ref;
106}; 106};
107 107
108 108
109 109
110 110
111 111
112 112
113 113
114QWidget *Appearance::createStyleTab ( QWidget *parent, Config &cfg ) 114QWidget *Appearance::createStyleTab ( QWidget *parent, Config &cfg )
115{ 115{
116 QWidget* tab = new QWidget( parent, "StyleTab" ); 116 QWidget* tab = new QWidget( parent, "StyleTab" );
117 QVBoxLayout* vertLayout = new QVBoxLayout( tab, 3, 3 ); 117 QVBoxLayout* vertLayout = new QVBoxLayout( tab, 3, 3 );
118 118
119 m_style_list = new QListBox( tab, "m_style_list" ); 119 m_style_list = new QListBox( tab, "m_style_list" );
120 vertLayout->addWidget( m_style_list ); 120 vertLayout->addWidget( m_style_list );
121 QWhatsThis::add( m_style_list, tr( "Styles control the way items such as buttons and scroll bars appear in all applications.\n\nClick here to select an available style." ) ); 121 QWhatsThis::add( m_style_list, tr( "Styles control the way items such as buttons and scroll bars appear in all applications.\n\nClick here to select an available style." ) );
122 122
123 m_style_settings = new QPushButton ( tr( "Settings..." ), tab ); 123 m_style_settings = new QPushButton ( tr( "Settings..." ), tab );
124 connect ( m_style_settings, SIGNAL( clicked ( )), this, SLOT( styleSettingsClicked ( ))); 124 connect ( m_style_settings, SIGNAL( clicked()), this, SLOT( styleSettingsClicked()));
125 vertLayout-> addWidget ( m_style_settings ); 125 vertLayout-> addWidget ( m_style_settings );
126 QWhatsThis::add( m_style_settings, tr( "Click here to configure the currently selected style.\n\nNote: This option is not available for all styles." ) ); 126 QWhatsThis::add( m_style_settings, tr( "Click here to configure the currently selected style.\n\nNote: This option is not available for all styles." ) );
127 127
128 QString s = cfg. readEntry ( "Style", "Light" ); 128 QString s = cfg. readEntry ( "Style", "Light" );
129 129
130 130
131#if QT_VERSION >= 300 131#if QT_VERSION >= 300
132 m_style_list->insertStringList(QStyleFactory::styles()); 132 m_style_list->insertStringList(QStyleFactory::styles());
133#else 133#else
134 m_style_list-> insertItem ( new StyleListItem ( "Windows", new QWindowsStyle ( ))); 134 m_style_list-> insertItem ( new StyleListItem ( "Windows", new QWindowsStyle ( )));
135 m_style_list-> insertItem ( new StyleListItem ( "Light", new LightStyle ( ))); 135 m_style_list-> insertItem ( new StyleListItem ( "Light", new LightStyle ( )));
136 m_style_list-> insertItem ( new StyleListItem ( "QPE", new QPEStyle ( ))); 136 m_style_list-> insertItem ( new StyleListItem ( "QPE", new QPEStyle ( )));
137#endif 137#endif
138 138
139 { 139 {
140 QString path = QPEApplication::qpeDir ( ); 140 QString path = QPEApplication::qpeDir ( );
141 path.append( "/plugins/styles/" ); 141 path.append( "/plugins/styles/" );
142 QStringList sl = QDir ( path, "lib*.so" ). entryList ( ); 142 QStringList sl = QDir ( path, "lib*.so" ). entryList ( );
143 143
144 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) 144 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it )
145 { 145 {
146 QString libstr = path; 146 QString libstr = path;
147 libstr.append( "/" ); 147 libstr.append( "/" );
148 libstr.append( *it ); 148 libstr.append( *it );
149 QLibrary *lib = new QLibrary ( libstr ); 149 QLibrary *lib = new QLibrary ( libstr );
150 StyleInterface *iface; 150 StyleInterface *iface;
151 151
152 if (( lib-> queryInterface ( IID_Style, (QUnknownInterface **) &iface ) == QS_OK ) && iface ) 152 if (( lib-> queryInterface ( IID_Style, (QUnknownInterface **) &iface ) == QS_OK ) && iface )
153 { 153 {
154 StyleListItem *slit = new StyleListItem ( lib, iface ); 154 StyleListItem *slit = new StyleListItem ( lib, iface );
155 m_style_list-> insertItem ( slit ); 155 m_style_list-> insertItem ( slit );
156 156
157 if ( slit-> key ( ) == s ) 157 if ( slit-> key ( ) == s )
158 m_style_list-> setCurrentItem ( slit ); 158 m_style_list-> setCurrentItem ( slit );
159 } 159 }
160 else 160 else
161 delete lib; 161 delete lib;
162 } 162 }
163 } 163 }
164 164
165 m_original_style = m_style_list-> currentItem ( ); 165 m_original_style = m_style_list-> currentItem ( );
166 styleClicked ( m_original_style ); 166 styleClicked ( m_original_style );
167 167
168 connect( m_style_list, SIGNAL( highlighted( int ) ), this, SLOT( styleClicked( int ) ) ); 168 connect( m_style_list, SIGNAL( highlighted(int) ), this, SLOT( styleClicked(int) ) );
169 169
170 return tab; 170 return tab;
171} 171}
172 172
173QWidget *Appearance::createDecoTab ( QWidget *parent, Config &cfg ) 173QWidget *Appearance::createDecoTab ( QWidget *parent, Config &cfg )
174{ 174{
175 QWidget* tab = new QWidget( parent, "DecoTab" ); 175 QWidget* tab = new QWidget( parent, "DecoTab" );
176 QVBoxLayout* vertLayout = new QVBoxLayout( tab, 3, 3 ); 176 QVBoxLayout* vertLayout = new QVBoxLayout( tab, 3, 3 );
177 177
178 m_deco_list = new QListBox( tab, "m_deco_list" ); 178 m_deco_list = new QListBox( tab, "m_deco_list" );
179 vertLayout->addWidget( m_deco_list ); 179 vertLayout->addWidget( m_deco_list );
180 QWhatsThis::add( m_deco_list, tr( "Window decorations control the way the application title bar and its buttons appear.\n\nClick here to select an available decoration." ) ); 180 QWhatsThis::add( m_deco_list, tr( "Window decorations control the way the application title bar and its buttons appear.\n\nClick here to select an available decoration." ) );
181 181
182 QString s = cfg. readEntry ( "Decoration", "libflat.so" ); 182 QString s = cfg. readEntry ( "Decoration", "libflat.so" );
183 183
184 m_deco_list-> insertItem ( new DecoListItem ( "QPE" )); 184 m_deco_list-> insertItem ( new DecoListItem ( "QPE" ));
185 185
186 { 186 {
187 QString path = QPEApplication::qpeDir(); 187 QString path = QPEApplication::qpeDir();
188 path.append( "/plugins/decorations/" ); 188 path.append( "/plugins/decorations/" );
189 QStringList sl = QDir ( path, "lib*.so" ). entryList ( ); 189 QStringList sl = QDir ( path, "lib*.so" ). entryList ( );
190 190
191 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) 191 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it )
192 { 192 {
193 QString libstr = path; 193 QString libstr = path;
194 libstr.append( "/" ); 194 libstr.append( "/" );
195 libstr.append( *it ); 195 libstr.append( *it );
196 QLibrary *lib = new QLibrary ( libstr ); 196 QLibrary *lib = new QLibrary ( libstr );
197 WindowDecorationInterface *iface; 197 WindowDecorationInterface *iface;
198 198
199 if ( lib-> queryInterface ( IID_WindowDecoration, (QUnknownInterface **) &iface ) == QS_OK ) 199 if ( lib-> queryInterface ( IID_WindowDecoration, (QUnknownInterface **) &iface ) == QS_OK )
200 { 200 {
201 DecoListItem *dlit = new DecoListItem ( lib, iface ); 201 DecoListItem *dlit = new DecoListItem ( lib, iface );
202 m_deco_list-> insertItem ( dlit ); 202 m_deco_list-> insertItem ( dlit );
203 203
204 if ( dlit-> key ( ) == s ) 204 if ( dlit-> key ( ) == s )
205 m_deco_list-> setCurrentItem ( dlit ); 205 m_deco_list-> setCurrentItem ( dlit );
206 } 206 }
207 else 207 else
208 delete lib; 208 delete lib;
209 } 209 }
210 } 210 }
211 211
212 m_original_deco = m_deco_list-> currentItem ( ); 212 m_original_deco = m_deco_list-> currentItem ( );
213 if ( m_deco_list-> currentItem ( ) < 0 ) 213 if ( m_deco_list-> currentItem ( ) < 0 )
214 m_deco_list-> setCurrentItem ( 0 ); 214 m_deco_list-> setCurrentItem ( 0 );
215 decoClicked ( m_original_deco ); 215 decoClicked ( m_original_deco );
216 216
217 connect( m_deco_list, SIGNAL( highlighted( int ) ), this, SLOT( decoClicked( int ) ) ); 217 connect( m_deco_list, SIGNAL( highlighted(int) ), this, SLOT( decoClicked(int) ) );
218 218
219 return tab; 219 return tab;
220} 220}
221 221
222QWidget *Appearance::createFontTab ( QWidget *parent, Config &cfg ) 222QWidget *Appearance::createFontTab ( QWidget *parent, Config &cfg )
223{ 223{
224 QString familyStr = cfg. readEntry ( "FontFamily", "Helvetica" ); 224 QString familyStr = cfg. readEntry ( "FontFamily", "Helvetica" );
225 QString styleStr = cfg. readEntry ( "FontStyle", "Regular" ); 225 QString styleStr = cfg. readEntry ( "FontStyle", "Regular" );
226 int size = cfg. readNumEntry ( "FontSize", 10 ); 226 int size = cfg. readNumEntry ( "FontSize", 10 );
227 227
228 m_fontselect = new OFontSelector ( false, parent, "FontTab" ); 228 m_fontselect = new OFontSelector ( false, parent, "FontTab" );
229 m_fontselect-> setSelectedFont ( familyStr, styleStr, size ); 229 m_fontselect-> setSelectedFont ( familyStr, styleStr, size );
230 QWhatsThis::add( m_fontselect, tr( "Select the desired name, style and size of the default font applications will use." ) ); 230 QWhatsThis::add( m_fontselect, tr( "Select the desired name, style and size of the default font applications will use." ) );
231 231
232 connect( m_fontselect, SIGNAL( fontSelected ( const QFont & )), 232 connect( m_fontselect, SIGNAL( fontSelected(const QFont&)),
233 this, SLOT( fontClicked ( const QFont & ))); 233 this, SLOT( fontClicked(const QFont&)));
234 234
235 return m_fontselect; 235 return m_fontselect;
236} 236}
237 237
238QWidget *Appearance::createColorTab ( QWidget *parent, Config &cfg ) 238QWidget *Appearance::createColorTab ( QWidget *parent, Config &cfg )
239{ 239{
240 QWidget *tab = new QWidget( parent, "ColorTab" ); 240 QWidget *tab = new QWidget( parent, "ColorTab" );
241 QGridLayout *gridLayout = new QGridLayout( tab, 0, 0, 3, 3 ); 241 QGridLayout *gridLayout = new QGridLayout( tab, 0, 0, 3, 3 );
242 gridLayout->setRowStretch ( 3, 10 ); 242 gridLayout->setRowStretch ( 3, 10 );
243 243
244 m_color_list = new QListBox ( tab ); 244 m_color_list = new QListBox ( tab );
245 gridLayout->addMultiCellWidget ( m_color_list, 0, 3, 0, 0 ); 245 gridLayout->addMultiCellWidget ( m_color_list, 0, 3, 0, 0 );
246 connect( m_color_list, SIGNAL( highlighted( int ) ), this, SLOT( colorClicked( int ) ) ); 246 connect( m_color_list, SIGNAL( highlighted(int) ), this, SLOT( colorClicked(int) ) );
247 QWhatsThis::add( m_color_list, tr( "Color schemes are a collection of colors which are used for various parts of the display.\n\nClick here to select an available scheme." ) ); 247 QWhatsThis::add( m_color_list, tr( "Color schemes are a collection of colors which are used for various parts of the display.\n\nClick here to select an available scheme." ) );
248 248
249 m_color_list-> insertItem ( new ColorListItem ( tr( "Current scheme" ), cfg )); 249 m_color_list-> insertItem ( new ColorListItem ( tr( "Current scheme" ), cfg ));
250 250
251 QString path = QPEApplication::qpeDir ( ); 251 QString path = QPEApplication::qpeDir ( );
252 path.append( "/etc/colors/" ); 252 path.append( "/etc/colors/" );
253 QStringList sl = QDir ( path ). entryList ( "*.scheme" ); 253 QStringList sl = QDir ( path ). entryList ( "*.scheme" );
254 254
255 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) 255 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it )
256 { 256 {
257 QString name = (*it). left ((*it). find ( ".scheme" )); 257 QString name = (*it). left ((*it). find ( ".scheme" ));
258 QString pathstr = path; 258 QString pathstr = path;
259 pathstr.append( *it ); 259 pathstr.append( *it );
260 Config config ( pathstr, Config::File ); 260 Config config ( pathstr, Config::File );
261 config. setGroup ( "Colors" ); 261 config. setGroup ( "Colors" );
262 262
263 m_color_list-> insertItem ( new ColorListItem ( name, config )); 263 m_color_list-> insertItem ( new ColorListItem ( name, config ));
264 } 264 }
265 265
266 m_color_list-> setCurrentItem ( 0 ); 266 m_color_list-> setCurrentItem ( 0 );
267 267
268 QPushButton* tempButton = new QPushButton( tab, "editSchemeButton" ); 268 QPushButton* tempButton = new QPushButton( tab, "editSchemeButton" );
269 tempButton->setText( tr( "Edit..." ) ); 269 tempButton->setText( tr( "Edit..." ) );
270 connect( tempButton, SIGNAL( clicked() ), this, SLOT( editSchemeClicked() ) ); 270 connect( tempButton, SIGNAL( clicked() ), this, SLOT( editSchemeClicked() ) );
271 gridLayout->addWidget( tempButton, 0, 1 ); 271 gridLayout->addWidget( tempButton, 0, 1 );
272 QWhatsThis::add( tempButton, tr( "Click here to change the colors in the current color scheme." ) ); 272 QWhatsThis::add( tempButton, tr( "Click here to change the colors in the current color scheme." ) );
273 273
274 tempButton = new QPushButton( tab, "deleteSchemeButton" ); 274 tempButton = new QPushButton( tab, "deleteSchemeButton" );
275 tempButton->setText( tr( "Delete" ) ); 275 tempButton->setText( tr( "Delete" ) );
276 connect( tempButton, SIGNAL( clicked() ), this, SLOT( deleteSchemeClicked() ) ); 276 connect( tempButton, SIGNAL( clicked() ), this, SLOT( deleteSchemeClicked() ) );
277 gridLayout->addWidget( tempButton, 1, 1 ); 277 gridLayout->addWidget( tempButton, 1, 1 );
278 QWhatsThis::add( tempButton, tr( "Click here to delete the color scheme selected in the list to the left." ) ); 278 QWhatsThis::add( tempButton, tr( "Click here to delete the color scheme selected in the list to the left." ) );
279 279
280 tempButton = new QPushButton( tab, "saveSchemeButton" ); 280 tempButton = new QPushButton( tab, "saveSchemeButton" );
281 tempButton->setText( tr( "Save" ) ); 281 tempButton->setText( tr( "Save" ) );
282 connect( tempButton, SIGNAL( clicked() ), this, SLOT( saveSchemeClicked() ) ); 282 connect( tempButton, SIGNAL( clicked() ), this, SLOT( saveSchemeClicked() ) );
283 gridLayout->addWidget( tempButton, 2, 1 ); 283 gridLayout->addWidget( tempButton, 2, 1 );
284 QWhatsThis::add( tempButton, tr( "Click here to name and save the current color scheme." ) ); 284 QWhatsThis::add( tempButton, tr( "Click here to name and save the current color scheme." ) );
285 285
286 return tab; 286 return tab;
287} 287}
288 288
289QWidget *Appearance::createAdvancedTab ( QWidget *parent, Config &cfg ) 289QWidget *Appearance::createAdvancedTab ( QWidget *parent, Config &cfg )
290{ 290{
291 QWidget *tab = new QWidget ( parent ); 291 QWidget *tab = new QWidget ( parent );
292 QVBoxLayout *vertLayout = new QVBoxLayout( tab, 3, 3 ); 292 QVBoxLayout *vertLayout = new QVBoxLayout( tab, 3, 3 );
293 293
294 QGridLayout *lay = new QGridLayout ( vertLayout, 0, 0, 3, 0 ); 294 QGridLayout *lay = new QGridLayout ( vertLayout, 0, 0, 3, 0 );
295 295
296 m_force = new QCheckBox ( tr( "Force styling for all applications." ), tab ); 296 m_force = new QCheckBox ( tr( "Force styling for all applications." ), tab );
297 m_force-> setChecked ( cfg. readBoolEntry ( "ForceStyle" )); 297 m_force-> setChecked ( cfg. readBoolEntry ( "ForceStyle" ));
298 lay-> addMultiCellWidget ( m_force, 0, 0, 0, 1 ); 298 lay-> addMultiCellWidget ( m_force, 0, 0, 0, 1 );
299 QWhatsThis::add( m_force, tr( "Click here to allow all applications to use global appearance settings." ) ); 299 QWhatsThis::add( m_force, tr( "Click here to allow all applications to use global appearance settings." ) );
300 300
301 QLabel *l = new QLabel ( tab ); 301 QLabel *l = new QLabel ( tab );
302 l-> setText ( QString ( "<p>%1</p>" ). arg ( tr( "Disable styling for these applications ( <b>*</b> can be used as a wildcard):" ))); 302 l-> setText ( QString ( "<p>%1</p>" ). arg ( tr( "Disable styling for these applications ( <b>*</b> can be used as a wildcard):" )));
303 lay-> addMultiCellWidget ( l, 1, 1, 0, 1 ); 303 lay-> addMultiCellWidget ( l, 1, 1, 0, 1 );
304 QWhatsThis::add( l, tr( "If some applications do not display correctly with the global appearance settings, certain features can be turned off for that application.\n\nThis area allows you to select an application and which settings you wish to disable." ) ); 304 QWhatsThis::add( l, tr( "If some applications do not display correctly with the global appearance settings, certain features can be turned off for that application.\n\nThis area allows you to select an application and which settings you wish to disable." ) );
305 305
306 m_except = new QListView ( tab ); 306 m_except = new QListView ( tab );
307 m_except-> addColumn ( Resource::loadIconSet ( "appearance" ), "", 24 ); 307 m_except-> addColumn ( Resource::loadIconSet ( "appearance" ), "", 24 );
308 m_except-> addColumn ( Resource::loadIconSet ( "font" ), "", 24 ); 308 m_except-> addColumn ( Resource::loadIconSet ( "font" ), "", 24 );
309 m_except-> addColumn ( Resource::loadIconSet ( "appearance/deco" ), "", 24 ); 309 m_except-> addColumn ( Resource::loadIconSet ( "appearance/deco" ), "", 24 );
310 m_except-> addColumn ( tr( "Binary file(s)" )); 310 m_except-> addColumn ( tr( "Binary file(s)" ));
311 m_except-> setColumnAlignment ( 0, AlignCenter ); 311 m_except-> setColumnAlignment ( 0, AlignCenter );
312 m_except-> setColumnAlignment ( 1, AlignCenter ); 312 m_except-> setColumnAlignment ( 1, AlignCenter );
313 m_except-> setColumnAlignment ( 2, AlignCenter ); 313 m_except-> setColumnAlignment ( 2, AlignCenter );
314 m_except-> setAllColumnsShowFocus ( true ); 314 m_except-> setAllColumnsShowFocus ( true );
315 m_except-> setMinimumHeight ( 30 ); 315 m_except-> setMinimumHeight ( 30 );
316 m_except-> header ( )-> setClickEnabled ( false ); 316 m_except-> header ( )-> setClickEnabled ( false );
317 m_except-> header ( )-> setResizeEnabled ( false ); 317 m_except-> header ( )-> setResizeEnabled ( false );
318 m_except-> header ( )-> setMovingEnabled ( false ); 318 m_except-> header ( )-> setMovingEnabled ( false );
319 m_except-> setSorting ( -1 ); 319 m_except-> setSorting ( -1 );
320 lay-> addMultiCellWidget ( m_except, 2, 6, 0, 0 ); 320 lay-> addMultiCellWidget ( m_except, 2, 6, 0, 0 );
321 QWhatsThis::add( m_except, tr( "If some applications do not display correctly with the global appearance settings, certain features can be turned off for that application.\n\nThis area allows you to select an application and which settings you wish to disable." ) ); 321 QWhatsThis::add( m_except, tr( "If some applications do not display correctly with the global appearance settings, certain features can be turned off for that application.\n\nThis area allows you to select an application and which settings you wish to disable." ) );
322 322
323 connect ( m_except, SIGNAL( clicked ( QListViewItem *, const QPoint &, int )), this, SLOT( clickedExcept ( QListViewItem *, const QPoint &, int ))); 323 connect ( m_except, SIGNAL( clicked(QListViewItem*,const QPoint&,int)), this, SLOT( clickedExcept(QListViewItem*,const QPoint&,int)));
324 324
325 QToolButton *tb = new QToolButton ( tab ); 325 QToolButton *tb = new QToolButton ( tab );
326 tb-> setIconSet ( Resource::loadIconSet ( "appearance/add" )); 326 tb-> setIconSet ( Resource::loadIconSet ( "appearance/add" ));
327 tb-> setFocusPolicy ( QWidget::StrongFocus ); 327 tb-> setFocusPolicy ( QWidget::StrongFocus );
328 lay-> addWidget ( tb, 2, 1 ); 328 lay-> addWidget ( tb, 2, 1 );
329 connect ( tb, SIGNAL( clicked ( )), this, SLOT( addExcept ( ))); 329 connect ( tb, SIGNAL( clicked()), this, SLOT( addExcept()));
330 QWhatsThis::add( tb, tr( "Click here to add an application to the list above." ) ); 330 QWhatsThis::add( tb, tr( "Click here to add an application to the list above." ) );
331 331
332 tb = new QToolButton ( tab ); 332 tb = new QToolButton ( tab );
333 tb-> setIconSet ( Resource::loadIconSet ( "editdelete" )); 333 tb-> setIconSet ( Resource::loadIconSet ( "editdelete" ));
334 tb-> setFocusPolicy ( QWidget::StrongFocus ); 334 tb-> setFocusPolicy ( QWidget::StrongFocus );
335 lay-> addWidget ( tb, 3, 1 ); 335 lay-> addWidget ( tb, 3, 1 );
336 connect ( tb, SIGNAL( clicked ( )), this, SLOT( delExcept ( ))); 336 connect ( tb, SIGNAL( clicked()), this, SLOT( delExcept()));
337 QWhatsThis::add( tb, tr( "Click here to delete the currently selected application." ) ); 337 QWhatsThis::add( tb, tr( "Click here to delete the currently selected application." ) );
338 338
339 tb = new QToolButton ( tab ); 339 tb = new QToolButton ( tab );
340 tb-> setIconSet ( Resource::loadIconSet ( "up" )); 340 tb-> setIconSet ( Resource::loadIconSet ( "up" ));
341 tb-> setFocusPolicy ( QWidget::StrongFocus ); 341 tb-> setFocusPolicy ( QWidget::StrongFocus );
342 lay-> addWidget ( tb, 4, 1 ); 342 lay-> addWidget ( tb, 4, 1 );
343 connect ( tb, SIGNAL( clicked ( )), this, SLOT( upExcept ( ))); 343 connect ( tb, SIGNAL( clicked()), this, SLOT( upExcept()));
344 QWhatsThis::add( tb, tr( "Click here to move the currently selected application up in the list." ) ); 344 QWhatsThis::add( tb, tr( "Click here to move the currently selected application up in the list." ) );
345 345
346 tb = new QToolButton ( tab ); 346 tb = new QToolButton ( tab );
347 tb-> setIconSet ( Resource::loadIconSet ( "down" )); 347 tb-> setIconSet ( Resource::loadIconSet ( "down" ));
348 tb-> setFocusPolicy ( QWidget::StrongFocus ); 348 tb-> setFocusPolicy ( QWidget::StrongFocus );
349 lay-> addWidget ( tb, 5, 1 ); 349 lay-> addWidget ( tb, 5, 1 );
350 connect ( tb, SIGNAL( clicked ( )), this, SLOT( downExcept ( ))); 350 connect ( tb, SIGNAL( clicked()), this, SLOT( downExcept()));
351 QWhatsThis::add( tb, tr( "Click here to move the currently selected application down in the list." ) ); 351 QWhatsThis::add( tb, tr( "Click here to move the currently selected application down in the list." ) );
352 352
353 lay-> setRowStretch ( 6, 10 ); 353 lay-> setRowStretch ( 6, 10 );
354 lay-> setColStretch ( 0, 10 ); 354 lay-> setColStretch ( 0, 10 );
355 355
356 QStringList sl = cfg. readListEntry ( "NoStyle", ';' ); 356 QStringList sl = cfg. readListEntry ( "NoStyle", ';' );
357 QListViewItem *lvit = 0; 357 QListViewItem *lvit = 0;
358 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) 358 for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it )
359 { 359 {
360 int fl = ( *it ). left ( 1 ). toInt ( 0, 32 ); 360 int fl = ( *it ). left ( 1 ). toInt ( 0, 32 );
361 361
362 lvit = new ExceptListItem ( m_except, lvit, ( *it ). mid ( 1 ), fl & 0x01, fl & 0x02, fl & 0x04 ); 362 lvit = new ExceptListItem ( m_except, lvit, ( *it ). mid ( 1 ), fl & 0x01, fl & 0x02, fl & 0x04 );
363 } 363 }
364 364
365 365
366 vertLayout-> addSpacing ( 3 ); 366 vertLayout-> addSpacing ( 3 );
367 QFrame *f = new QFrame ( tab ); 367 QFrame *f = new QFrame ( tab );
368 f-> setFrameStyle ( QFrame::HLine | QFrame::Sunken ); 368 f-> setFrameStyle ( QFrame::HLine | QFrame::Sunken );
369 vertLayout-> addWidget ( f ); 369 vertLayout-> addWidget ( f );
370 vertLayout-> addSpacing ( 3 ); 370 vertLayout-> addSpacing ( 3 );
371 371
372 372
373 QGridLayout* gridLayout = new QGridLayout ( vertLayout, 0, 0, 3, 0 ); 373 QGridLayout* gridLayout = new QGridLayout ( vertLayout, 0, 0, 3, 0 );
374 374
375 int style = cfg. readNumEntry ( "TabStyle", 2 ) - 1; 375 int style = cfg. readNumEntry ( "TabStyle", 2 ) - 1;
376 bool tabtop = ( cfg. readEntry ( "TabPosition", "Top" ) == "Top" ); 376 bool tabtop = ( cfg. readEntry ( "TabPosition", "Top" ) == "Top" );
377 377
378 QLabel* label = new QLabel( tr( "Tab style:" ), tab ); 378 QLabel* label = new QLabel( tr( "Tab style:" ), tab );
379 gridLayout-> addWidget ( label, 0, 0 ); 379 gridLayout-> addWidget ( label, 0, 0 );
380 QWhatsThis::add( label, tr( "Click here to select a desired style for tabbed dialogs (such as this application). The styles available are:\n\n1. Tabs - normal tabs with text labels only\n2. Tabs w/icons - tabs with icons for each tab, text label only appears on current tab\n3. Drop down list - a vertical listing of tabs\n4. Drop down list w/icons - a vertical listing of tabs with icons" ) ); 380 QWhatsThis::add( label, tr( "Click here to select a desired style for tabbed dialogs (such as this application). The styles available are:\n\n1. Tabs - normal tabs with text labels only\n2. Tabs w/icons - tabs with icons for each tab, text label only appears on current tab\n3. Drop down list - a vertical listing of tabs\n4. Drop down list w/icons - a vertical listing of tabs with icons" ) );
381 381
382 QButtonGroup* btngrp = new QButtonGroup( tab, "buttongroup" ); 382 QButtonGroup* btngrp = new QButtonGroup( tab, "buttongroup" );
383 btngrp-> hide ( ); 383 btngrp-> hide ( );
384 btngrp-> setExclusive ( true ); 384 btngrp-> setExclusive ( true );
385 385
386 m_tabstyle_list = new QComboBox ( false, tab, "tabstyle" ); 386 m_tabstyle_list = new QComboBox ( false, tab, "tabstyle" );
387 m_tabstyle_list-> insertItem ( tr( "Tabs" )); 387 m_tabstyle_list-> insertItem ( tr( "Tabs" ));
388 m_tabstyle_list-> insertItem ( tr( "Tabs w/icons" )); 388 m_tabstyle_list-> insertItem ( tr( "Tabs w/icons" ));
389 m_tabstyle_list-> insertItem ( tr( "Drop down list" )); 389 m_tabstyle_list-> insertItem ( tr( "Drop down list" ));
390 m_tabstyle_list-> insertItem ( tr( "Drop down list w/icons" )); 390 m_tabstyle_list-> insertItem ( tr( "Drop down list w/icons" ));
391 m_tabstyle_list-> setCurrentItem ( style ); 391 m_tabstyle_list-> setCurrentItem ( style );
392 gridLayout-> addMultiCellWidget ( m_tabstyle_list, 0, 0, 1, 2 ); 392 gridLayout-> addMultiCellWidget ( m_tabstyle_list, 0, 0, 1, 2 );
393 QWhatsThis::add( m_tabstyle_list, tr( "Click here to select a desired style for tabbed dialogs (such as this application). The styles available are:\n\n1. Tabs - normal tabs with text labels only\n2. Tabs w/icons - tabs with icons for each tab, text label only appears on current tab\n3. Drop down list - a vertical listing of tabs\n4. Drop down list w/icons - a vertical listing of tabs with icons" ) ); 393 QWhatsThis::add( m_tabstyle_list, tr( "Click here to select a desired style for tabbed dialogs (such as this application). The styles available are:\n\n1. Tabs - normal tabs with text labels only\n2. Tabs w/icons - tabs with icons for each tab, text label only appears on current tab\n3. Drop down list - a vertical listing of tabs\n4. Drop down list w/icons - a vertical listing of tabs with icons" ) );
394 394
395 m_tabstyle_top = new QRadioButton( tr( "Top" ), tab, "tabpostop" ); 395 m_tabstyle_top = new QRadioButton( tr( "Top" ), tab, "tabpostop" );
396 btngrp-> insert ( m_tabstyle_top ); 396 btngrp-> insert ( m_tabstyle_top );
397 gridLayout-> addWidget( m_tabstyle_top, 1, 1 ); 397 gridLayout-> addWidget( m_tabstyle_top, 1, 1 );
398 QWhatsThis::add( m_tabstyle_top, tr( "Click here so that tabs appear at the top of the window." ) ); 398 QWhatsThis::add( m_tabstyle_top, tr( "Click here so that tabs appear at the top of the window." ) );
399 399
400 m_tabstyle_bottom = new QRadioButton( tr( "Bottom" ), tab, "tabposbottom" ); 400 m_tabstyle_bottom = new QRadioButton( tr( "Bottom" ), tab, "tabposbottom" );
401 btngrp-> insert ( m_tabstyle_bottom ); 401 btngrp-> insert ( m_tabstyle_bottom );
402 gridLayout-> addWidget( m_tabstyle_bottom, 1, 2 ); 402 gridLayout-> addWidget( m_tabstyle_bottom, 1, 2 );
403 QWhatsThis::add( m_tabstyle_bottom, tr( "Click here so that tabs appear at the bottom of the window." ) ); 403 QWhatsThis::add( m_tabstyle_bottom, tr( "Click here so that tabs appear at the bottom of the window." ) );
404 404
405 m_tabstyle_top-> setChecked ( tabtop ); 405 m_tabstyle_top-> setChecked ( tabtop );
406 m_tabstyle_bottom-> setChecked ( !tabtop ); 406 m_tabstyle_bottom-> setChecked ( !tabtop );
407 407
408 m_original_tabstyle = style; 408 m_original_tabstyle = style;
409 m_original_tabpos = tabtop; 409 m_original_tabpos = tabtop;
410 410
411 vertLayout-> addSpacing ( 3 ); 411 vertLayout-> addSpacing ( 3 );
412 QHBoxLayout *rotLay = new QHBoxLayout ( vertLayout, 3 ); 412 QHBoxLayout *rotLay = new QHBoxLayout ( vertLayout, 3 );
413 413
414 QLabel* rotlabel = new QLabel( tr( "Rotation direction:" ), tab ); 414 QLabel* rotlabel = new QLabel( tr( "Rotation direction:" ), tab );
415 m_rotdir_cw = new QRadioButton( tab, "rotdir_cw" ); 415 m_rotdir_cw = new QRadioButton( tab, "rotdir_cw" );
416 QPixmap cw1 = Resource::loadIconSet("redo"). pixmap( ); 416 QPixmap cw1 = Resource::loadIconSet("redo"). pixmap( );
417 m_rotdir_ccw = new QRadioButton( tab, "rotdir_ccw" ); 417 m_rotdir_ccw = new QRadioButton( tab, "rotdir_ccw" );
418 QImage ccwImage = cw1. convertToImage( ). mirror( 1, 0 ); 418 QImage ccwImage = cw1. convertToImage( ). mirror( 1, 0 );
419 QPixmap ccw1; 419 QPixmap ccw1;
420 m_rotdir_flip = new QRadioButton( tab, "rotdir_flip" ); 420 m_rotdir_flip = new QRadioButton( tab, "rotdir_flip" );
421 QPixmap flip1 = Resource::loadIconSet("pass"). pixmap( ); 421 QPixmap flip1 = Resource::loadIconSet("pass"). pixmap( );
422 QButtonGroup* rotbtngrp = new QButtonGroup( tab, "rotbuttongroup" ); 422 QButtonGroup* rotbtngrp = new QButtonGroup( tab, "rotbuttongroup" );
423 423
424 rotbtngrp-> hide ( ); 424 rotbtngrp-> hide ( );
425 rotbtngrp-> setExclusive ( true ); 425 rotbtngrp-> setExclusive ( true );
426 rotbtngrp-> insert ( m_rotdir_cw ); 426 rotbtngrp-> insert ( m_rotdir_cw );
427 rotbtngrp-> insert ( m_rotdir_ccw ); 427 rotbtngrp-> insert ( m_rotdir_ccw );
428 rotbtngrp-> insert ( m_rotdir_flip ); 428 rotbtngrp-> insert ( m_rotdir_flip );
429 429
430 ccw1. convertFromImage( ccwImage ); 430 ccw1. convertFromImage( ccwImage );
431 m_rotdir_cw-> setPixmap( cw1 ); 431 m_rotdir_cw-> setPixmap( cw1 );
432 m_rotdir_ccw-> setPixmap( ccw1 ); 432 m_rotdir_ccw-> setPixmap( ccw1 );
433 m_rotdir_flip-> setPixmap( flip1 ); 433 m_rotdir_flip-> setPixmap( flip1 );
434 434
435 rotLay-> addWidget ( rotlabel, 0 ); 435 rotLay-> addWidget ( rotlabel, 0 );
436 rotLay-> addWidget ( m_rotdir_cw, 0 ); 436 rotLay-> addWidget ( m_rotdir_cw, 0 );
437 rotLay-> addWidget ( m_rotdir_ccw, 0 ); 437 rotLay-> addWidget ( m_rotdir_ccw, 0 );
438 rotLay-> addWidget ( m_rotdir_flip, 0 ); 438 rotLay-> addWidget ( m_rotdir_flip, 0 );
439 439
440 int rotDirection = cfg.readNumEntry( "rotatedir" ); 440 int rotDirection = cfg.readNumEntry( "rotatedir" );
441 ODirection rot = CW; 441 ODirection rot = CW;
442 442
443 if (rotDirection == -1) 443 if (rotDirection == -1)
444 { 444 {
445 rot = ODevice::inst ( )-> direction ( ); 445 rot = ODevice::inst ( )-> direction ( );
446 } 446 }
447 else 447 else
448 { 448 {
449 rot = (ODirection)rotDirection; 449 rot = (ODirection)rotDirection;
450 } 450 }
451 451
452 m_rotdir_cw-> setChecked ( rot == CW ); 452 m_rotdir_cw-> setChecked ( rot == CW );
453 m_rotdir_ccw-> setChecked ( rot == CCW ); 453 m_rotdir_ccw-> setChecked ( rot == CCW );
454 m_rotdir_flip-> setChecked ( rot == Flip ); 454 m_rotdir_flip-> setChecked ( rot == Flip );
455 455
456 return tab; 456 return tab;
457} 457}
458 458
459 459
460Appearance::Appearance( QWidget* parent, const char* name, WFlags ) 460Appearance::Appearance( QWidget* parent, const char* name, WFlags )
461 : QDialog ( parent, name, true, WStyle_ContextHelp ) 461 : QDialog ( parent, name, true, WStyle_ContextHelp )
462{ 462{
463 setCaption( tr( "Appearance Settings" ) ); 463 setCaption( tr( "Appearance Settings" ) );
464 464
465 Config config( "qpe" ); 465 Config config( "qpe" );
466 config.setGroup( "Appearance" ); 466 config.setGroup( "Appearance" );
467 467
468 QVBoxLayout *top = new QVBoxLayout ( this, 3, 3 ); 468 QVBoxLayout *top = new QVBoxLayout ( this, 3, 3 );
469 469
470 m_sample = new SampleWindow ( this ); 470 m_sample = new SampleWindow ( this );
471 471
472 m_sample-> setDecoration ( new DefaultWindowDecoration ( ) ); 472 m_sample-> setDecoration ( new DefaultWindowDecoration ( ) );
473 QWhatsThis::add( m_sample, tr( "This is a preview window. Look here to see your new appearance as options are changed." ) ); 473 QWhatsThis::add( m_sample, tr( "This is a preview window. Look here to see your new appearance as options are changed." ) );
474 474
475 OTabWidget* tw = new OTabWidget ( this, "tabwidget", OTabWidget::Global, OTabWidget::Bottom ); 475 OTabWidget* tw = new OTabWidget ( this, "tabwidget", OTabWidget::Global, OTabWidget::Bottom );
476 QWidget *styletab; 476 QWidget *styletab;
477 477
478 m_color_list = 0; 478 m_color_list = 0;
479 479
480 tw-> addTab ( styletab = createStyleTab ( tw, config ), "appearance", tr( "Style" )); 480 tw-> addTab ( styletab = createStyleTab ( tw, config ), "appearance", tr( "Style" ));
481 tw-> addTab ( createFontTab ( tw, config ), "font", tr( "Font" )); 481 tw-> addTab ( createFontTab ( tw, config ), "font", tr( "Font" ));
482 tw-> addTab ( createColorTab ( tw, config ), "appearance/color", tr( "Colors" ) ); 482 tw-> addTab ( createColorTab ( tw, config ), "appearance/color", tr( "Colors" ) );
483 tw-> addTab ( createDecoTab ( tw, config ), "appearance/deco", tr( "Windows" ) ); 483 tw-> addTab ( createDecoTab ( tw, config ), "appearance/deco", tr( "Windows" ) );
484 tw-> addTab ( m_advtab = createAdvancedTab ( tw, config ), "SettingsIcon", tr( "Advanced" ) ); 484 tw-> addTab ( m_advtab = createAdvancedTab ( tw, config ), "SettingsIcon", tr( "Advanced" ) );
485 485
486 top-> addWidget ( tw, 10 ); 486 top-> addWidget ( tw, 10 );
487 top-> addWidget ( m_sample, 1 ); 487 top-> addWidget ( m_sample, 1 );
488 488
489 tw-> setCurrentTab ( styletab ); 489 tw-> setCurrentTab ( styletab );
490 connect ( tw, SIGNAL( currentChanged ( QWidget * )), this, SLOT( tabChanged ( QWidget * ))); 490 connect ( tw, SIGNAL( currentChanged(QWidget*)), this, SLOT( tabChanged(QWidget*)));
491 491
492 m_style_changed = m_font_changed = m_color_changed = m_deco_changed = false; 492 m_style_changed = m_font_changed = m_color_changed = m_deco_changed = false;
493} 493}
494 494
495Appearance::~Appearance() 495Appearance::~Appearance()
496{} 496{}
497 497
498void Appearance::tabChanged ( QWidget *w ) 498void Appearance::tabChanged ( QWidget *w )
499{ 499{
500 if ( w == m_advtab ) 500 if ( w == m_advtab )
501 { 501 {
502 m_sample-> hide ( ); 502 m_sample-> hide ( );
503 updateGeometry ( ); // shouldn't be necessary ... 503 updateGeometry ( ); // shouldn't be necessary ...
504 } 504 }
505 else 505 else
506 m_sample-> show ( ); 506 m_sample-> show ( );
507} 507}
508 508
509void Appearance::accept ( ) 509void Appearance::accept ( )
510{ 510{
511 bool newtabpos = m_tabstyle_top-> isChecked ( ); 511 bool newtabpos = m_tabstyle_top-> isChecked ( );
512 int newtabstyle = m_tabstyle_list-> currentItem ( ); 512 int newtabstyle = m_tabstyle_list-> currentItem ( );
513 513
514 Config config ( "qpe" ); 514 Config config ( "qpe" );
515 config. setGroup ( "Appearance" ); 515 config. setGroup ( "Appearance" );
516 516
517 if ( m_style_changed ) 517 if ( m_style_changed )
518 { 518 {
519 StyleListItem *item = (StyleListItem *) m_style_list-> item ( m_style_list-> currentItem ( )); 519 StyleListItem *item = (StyleListItem *) m_style_list-> item ( m_style_list-> currentItem ( ));
520 if ( item ) 520 if ( item )
521 config.writeEntry( "Style", item-> key ( )); 521 config.writeEntry( "Style", item-> key ( ));
522 } 522 }
523 523
524 if ( m_deco_changed ) 524 if ( m_deco_changed )
525 { 525 {
526 DecoListItem *item = (DecoListItem *) m_deco_list-> item ( m_deco_list-> currentItem ( )); 526 DecoListItem *item = (DecoListItem *) m_deco_list-> item ( m_deco_list-> currentItem ( ));
527 if ( item ) 527 if ( item )
528 config.writeEntry( "Decoration", item-> key ( )); 528 config.writeEntry( "Decoration", item-> key ( ));
529 } 529 }
530 530
531 if (( newtabstyle != m_original_tabstyle ) || ( newtabpos != m_original_tabpos )) 531 if (( newtabstyle != m_original_tabstyle ) || ( newtabpos != m_original_tabpos ))
532 { 532 {
533 config. writeEntry ( "TabStyle", newtabstyle + 1 ); 533 config. writeEntry ( "TabStyle", newtabstyle + 1 );
534 config. writeEntry ( "TabPosition", newtabpos ? "Top" : "Bottom" ); 534 config. writeEntry ( "TabPosition", newtabpos ? "Top" : "Bottom" );
535 } 535 }
536 536
537 if ( m_font_changed ) 537 if ( m_font_changed )
538 { 538 {
539 config. writeEntry ( "FontFamily", m_fontselect-> fontFamily ( )); 539 config. writeEntry ( "FontFamily", m_fontselect-> fontFamily ( ));
540 config. writeEntry ( "FontStyle", m_fontselect-> fontStyle ( )); 540 config. writeEntry ( "FontStyle", m_fontselect-> fontStyle ( ));
541 config. writeEntry ( "FontSize", m_fontselect-> fontSize ( )); 541 config. writeEntry ( "FontSize", m_fontselect-> fontSize ( ));
542 } 542 }
543 543
544 544
545 if ( m_color_changed ) 545 if ( m_color_changed )
546 { 546 {
547 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); 547 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( ));
548 548
549 if ( item ) 549 if ( item )
550 item-> save ( config ); 550 item-> save ( config );
551 } 551 }
552 552
553 ODirection rot; 553 ODirection rot;
554 if (m_rotdir_ccw-> isChecked ( )) 554 if (m_rotdir_ccw-> isChecked ( ))
555 { 555 {
556 rot = CCW; 556 rot = CCW;
557 } 557 }
558 else if (m_rotdir_cw-> isChecked ( )) 558 else if (m_rotdir_cw-> isChecked ( ))
559 { 559 {
560 rot = CW; 560 rot = CW;
561 } 561 }
562 else 562 else
563 { 563 {
564 rot = Flip; 564 rot = Flip;
565 } 565 }
566 config. writeEntry ( "rotatedir", (int)rot ); 566 config. writeEntry ( "rotatedir", (int)rot );
567 567
568 m_except-> setFocus ( ); // if the focus was on the embedded line-edit, we have to move it away first, so the contents are updated 568 m_except-> setFocus ( ); // if the focus was on the embedded line-edit, we have to move it away first, so the contents are updated
569 569
570 QStringList sl; 570 QStringList sl;
571 QString exceptstr; 571 QString exceptstr;
572 for ( ExceptListItem *it = (ExceptListItem *) m_except-> firstChild ( ); it; it = (ExceptListItem *) it-> nextSibling ( )) 572 for ( ExceptListItem *it = (ExceptListItem *) m_except-> firstChild ( ); it; it = (ExceptListItem *) it-> nextSibling ( ))
573 { 573 {
574 int fl = 0; 574 int fl = 0;
575 fl |= ( it-> noStyle ( ) ? 0x01 : 0 ); 575 fl |= ( it-> noStyle ( ) ? 0x01 : 0 );
576 fl |= ( it-> noFont ( ) ? 0x02 : 0 ); 576 fl |= ( it-> noFont ( ) ? 0x02 : 0 );
577 fl |= ( it-> noDeco ( ) ? 0x04 : 0 ); 577 fl |= ( it-> noDeco ( ) ? 0x04 : 0 );
578 exceptstr = QString::number ( fl, 32 ); 578 exceptstr = QString::number ( fl, 32 );
579 exceptstr.append( it-> pattern ( )); 579 exceptstr.append( it-> pattern ( ));
580 sl << exceptstr; 580 sl << exceptstr;
581 } 581 }
582 config. writeEntry ( "NoStyle", sl, ';' ); 582 config. writeEntry ( "NoStyle", sl, ';' );
583 config. writeEntry ( "ForceStyle", m_force-> isChecked ( )); 583 config. writeEntry ( "ForceStyle", m_force-> isChecked ( ));
584 584
585 config. write ( ); // need to flush the config info first 585 config. write ( ); // need to flush the config info first
586 Global::applyStyle ( ); 586 Global::applyStyle ( );
587 587
588 QDialog::accept ( ); 588 QDialog::accept ( );
589} 589}
590 590
591void Appearance::done ( int r ) 591void Appearance::done ( int r )
592{ 592{
593 QDialog::done ( r ); 593 QDialog::done ( r );
594 close ( ); 594 close ( );
595} 595}
596 596
597 597
598void Appearance::styleClicked ( int index ) 598void Appearance::styleClicked ( int index )
599{ 599{
600 StyleListItem *sli = (StyleListItem *) m_style_list-> item ( index ); 600 StyleListItem *sli = (StyleListItem *) m_style_list-> item ( index );
601 m_style_settings-> setEnabled ( sli ? sli-> hasSettings ( ) : false ); 601 m_style_settings-> setEnabled ( sli ? sli-> hasSettings ( ) : false );
602 602
603 if ( m_sample && sli && sli-> style ( )) 603 if ( m_sample && sli && sli-> style ( ))
604 { 604 {
605 int ci = m_color_list ? m_color_list-> currentItem ( ) : -1; 605 int ci = m_color_list ? m_color_list-> currentItem ( ) : -1;
606 606
607 m_sample-> setStyle2 ( sli-> style ( ), ci < 0 ? palette ( ) : ((ColorListItem *) m_color_list-> item ( ci ))-> palette ( )); 607 m_sample-> setStyle2 ( sli-> style ( ), ci < 0 ? palette ( ) : ((ColorListItem *) m_color_list-> item ( ci ))-> palette ( ));
608 } 608 }
609 609
610 m_style_changed |= ( index != m_original_style ); 610 m_style_changed |= ( index != m_original_style );
611} 611}
612 612
613void Appearance::styleSettingsClicked ( ) 613void Appearance::styleSettingsClicked ( )
614{ 614{
615 StyleListItem *item = (StyleListItem *) m_style_list-> item ( m_style_list-> currentItem ( )); 615 StyleListItem *item = (StyleListItem *) m_style_list-> item ( m_style_list-> currentItem ( ));
616 616
617 if ( item && item-> hasSettings ( )) 617 if ( item && item-> hasSettings ( ))
618 { 618 {
619 QDialog *d = new QDialog ( this, "SETTINGS-DLG", true ); 619 QDialog *d = new QDialog ( this, "SETTINGS-DLG", true );
620 QVBoxLayout *vbox = new QVBoxLayout ( d, 3, 0 ); 620 QVBoxLayout *vbox = new QVBoxLayout ( d, 3, 0 );
621 621
622 QWidget *w = item-> settings ( d ); 622 QWidget *w = item-> settings ( d );
623 623
624 if ( w ) 624 if ( w )
625 { 625 {
626 vbox-> addWidget ( w ); 626 vbox-> addWidget ( w );
627 627
628 d-> setCaption ( w-> caption ( )); 628 d-> setCaption ( w-> caption ( ));
629 629
630 bool accepted = ( QPEApplication::execDialog ( d ) == QDialog::Accepted ); 630 bool accepted = ( QPEApplication::execDialog ( d ) == QDialog::Accepted );
631 631
632 if ( item-> setSettings ( accepted )) 632 if ( item-> setSettings ( accepted ))
633 m_style_changed = true; 633 m_style_changed = true;
634 } 634 }
635 delete d; 635 delete d;
636 } 636 }
637} 637}
638 638
639void Appearance::decoClicked ( int index ) 639void Appearance::decoClicked ( int index )
640{ 640{
641 DecoListItem *dli = (DecoListItem *) m_deco_list-> item ( index ); 641 DecoListItem *dli = (DecoListItem *) m_deco_list-> item ( index );
642 642
643 if ( m_sample ) 643 if ( m_sample )
644 { 644 {
645 if ( dli && dli-> interface ( )) 645 if ( dli && dli-> interface ( ))
646 m_sample-> setDecoration ( dli-> interface ( )); 646 m_sample-> setDecoration ( dli-> interface ( ));
647 else 647 else
648 m_sample-> setDecoration ( new DefaultWindowDecoration ( )); 648 m_sample-> setDecoration ( new DefaultWindowDecoration ( ));
649 m_sample-> repaint ( ); 649 m_sample-> repaint ( );
650 } 650 }
651 m_deco_changed |= ( index != m_original_deco ); 651 m_deco_changed |= ( index != m_original_deco );
652} 652}
653 653
654void Appearance::fontClicked ( const QFont &f ) 654void Appearance::fontClicked ( const QFont &f )
655{ 655{
656 m_font_changed |= ( f != m_sample-> font ( )); 656 m_font_changed |= ( f != m_sample-> font ( ));
657 m_sample-> setFont ( f ); 657 m_sample-> setFont ( f );
658} 658}
659 659
660void Appearance::colorClicked ( int index ) 660void Appearance::colorClicked ( int index )
661{ 661{
662 ColorListItem *item = (ColorListItem *) m_color_list-> item ( index ); 662 ColorListItem *item = (ColorListItem *) m_color_list-> item ( index );
663 663
664 if ( item ) 664 if ( item )
665 m_sample-> setPalette ( item-> palette ( )); 665 m_sample-> setPalette ( item-> palette ( ));
666 666
667 m_color_changed |= ( item-> palette ( ) != qApp-> palette ( )); 667 m_color_changed |= ( item-> palette ( ) != qApp-> palette ( ));
668} 668}
669 669
670 670
671void Appearance::editSchemeClicked ( ) 671void Appearance::editSchemeClicked ( )
672{ 672{
673 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); 673 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( ));
674 674
675 int cnt = 0; 675 int cnt = 0;
676 QString labels [QColorGroup::NColorRoles]; 676 QString labels [QColorGroup::NColorRoles];
677 QColor colors [QColorGroup::NColorRoles]; 677 QColor colors [QColorGroup::NColorRoles];
678 678
679 for ( QColorGroup::ColorRole role = (QColorGroup::ColorRole) 0; role != QColorGroup::NColorRoles; ((int) role )++ ) 679 for ( QColorGroup::ColorRole role = (QColorGroup::ColorRole) 0; role != QColorGroup::NColorRoles; ((int) role )++ )
680 { 680 {
681 QColor col = item-> color ( role ); 681 QColor col = item-> color ( role );
682 682
683 if ( col. isValid ( )) 683 if ( col. isValid ( ))
684 { 684 {
685 labels [cnt] = item-> label ( role ); 685 labels [cnt] = item-> label ( role );
686 colors [cnt] = col; 686 colors [cnt] = col;
687 687
688 cnt++; 688 cnt++;
689 } 689 }
690 } 690 }
691 691
692 EditScheme* editdlg = new EditScheme( cnt, labels, colors, this, "editScheme", true ); 692 EditScheme* editdlg = new EditScheme( cnt, labels, colors, this, "editScheme", true );
693 if ( QPEApplication::execDialog( editdlg ) == QDialog::Accepted ) 693 if ( QPEApplication::execDialog( editdlg ) == QDialog::Accepted )
694 { 694 {
695 ColorListItem *citem = (ColorListItem *) m_color_list-> item ( 0 ); 695 ColorListItem *citem = (ColorListItem *) m_color_list-> item ( 0 );
696 cnt = 0; 696 cnt = 0;
697 697
698 for ( QColorGroup::ColorRole role = (QColorGroup::ColorRole) 0; role != QColorGroup::NColorRoles; ((int) role )++ ) 698 for ( QColorGroup::ColorRole role = (QColorGroup::ColorRole) 0; role != QColorGroup::NColorRoles; ((int) role )++ )
699 { 699 {
700 if ( item-> color ( role ). isValid ( )) 700 if ( item-> color ( role ). isValid ( ))
701 { 701 {
702 citem-> setColor ( role, colors [cnt] ); 702 citem-> setColor ( role, colors [cnt] );
703 cnt++; 703 cnt++;
704 } 704 }
705 } 705 }
706 706
707 m_color_list-> setCurrentItem ( 0 ); 707 m_color_list-> setCurrentItem ( 0 );
708 colorClicked ( 0 ); 708 colorClicked ( 0 );
709 709
710 m_color_changed = true; 710 m_color_changed = true;
711 } 711 }
712 delete editdlg; 712 delete editdlg;
713} 713}
714 714
715 715
716void Appearance::saveSchemeClicked() 716void Appearance::saveSchemeClicked()
717{ 717{
718 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); 718 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( ));
719 719
720 if ( !item ) 720 if ( !item )
721 return; 721 return;
722 722
723 QDialog *d = new QDialog ( this, 0, true ); 723 QDialog *d = new QDialog ( this, 0, true );
724 d-> setCaption ( tr( "Save Scheme" )); 724 d-> setCaption ( tr( "Save Scheme" ));
725 QLineEdit *ed = new QLineEdit ( d ); 725 QLineEdit *ed = new QLineEdit ( d );
726 ( new QVBoxLayout ( d, 3, 3 ))-> addWidget ( ed ); 726 ( new QVBoxLayout ( d, 3, 3 ))-> addWidget ( ed );
727 ed-> setFocus ( ); 727 ed-> setFocus ( );
728 728
729 if ( d-> exec ( ) == QDialog::Accepted ) 729 if ( d-> exec ( ) == QDialog::Accepted )
730 { 730 {
731 QString schemename = ed-> text ( ); 731 QString schemename = ed-> text ( );
732 QString filestr = QPEApplication::qpeDir(); 732 QString filestr = QPEApplication::qpeDir();
733 filestr.append( "/etc/colors/" ); 733 filestr.append( "/etc/colors/" );
734 filestr.append( schemename ); 734 filestr.append( schemename );
735 filestr.append( ".scheme" ); 735 filestr.append( ".scheme" );
736 QFile file ( filestr ); 736 QFile file ( filestr );
737 if ( !file. exists ( )) 737 if ( !file. exists ( ))
738 { 738 {
739 QPalette p = item-> palette ( ); 739 QPalette p = item-> palette ( );
740 740
741 Config config ( file.name(), Config::File ); 741 Config config ( file.name(), Config::File );
742 config. setGroup( "Colors" ); 742 config. setGroup( "Colors" );
743 743
744 item-> save ( config ); 744 item-> save ( config );
745 745
746 config. write ( ); // need to flush the config info first 746 config. write ( ); // need to flush the config info first
747 747
748 m_color_list-> insertItem ( new ColorListItem ( schemename, config )); 748 m_color_list-> insertItem ( new ColorListItem ( schemename, config ));
749 } 749 }
750 else 750 else
751 { 751 {
752 QMessageBox::information ( this, tr( "Save scheme" ), tr( "Scheme does already exist." )); 752 QMessageBox::information ( this, tr( "Save scheme" ), tr( "Scheme does already exist." ));
753 } 753 }
754 } 754 }
755 delete d; 755 delete d;
756} 756}
757 757
758void Appearance::deleteSchemeClicked() 758void Appearance::deleteSchemeClicked()
759{ 759{
760 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); 760 ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( ));
761 761
762 if ( !item ) 762 if ( !item )
763 return; 763 return;
764 764
765 if ( m_color_list-> currentItem ( ) > 0 ) 765 if ( m_color_list-> currentItem ( ) > 0 )
766 { 766 {
767 if ( QPEMessageBox::confirmDelete ( this, tr( "Delete scheme" ), item-> text ( ) ) ) 767 if ( QPEMessageBox::confirmDelete ( this, tr( "Delete scheme" ), item-> text ( ) ) )
768 { 768 {
769 QString filestr = QPEApplication::qpeDir ( ); 769 QString filestr = QPEApplication::qpeDir ( );
770 filestr.append( "/etc/colors/" ); 770 filestr.append( "/etc/colors/" );
771 filestr.append( item-> text ( ) ); 771 filestr.append( item-> text ( ) );
772 filestr.append( ".scheme" ); 772 filestr.append( ".scheme" );
773 QFile::remove ( filestr ); 773 QFile::remove ( filestr );
774 delete item; 774 delete item;
775 } 775 }
776 } 776 }
777 else 777 else
778 { 778 {
779 QMessageBox::information( this, tr( "Delete scheme" ), tr( "Unable to delete current scheme." )); 779 QMessageBox::information( this, tr( "Delete scheme" ), tr( "Unable to delete current scheme." ));
780 } 780 }
781} 781}
782 782
783 783
784void Appearance::addExcept ( ) 784void Appearance::addExcept ( )
785{ 785{
786 ExceptListItem *it = new ExceptListItem ( m_except, 0, tr( "<new>" ), true, true, true ); 786 ExceptListItem *it = new ExceptListItem ( m_except, 0, tr( "<new>" ), true, true, true );
787 m_except-> ensureItemVisible ( it ); 787 m_except-> ensureItemVisible ( it );
788 m_except-> setSelected ( it, true ); 788 m_except-> setSelected ( it, true );
789} 789}
790 790
791void Appearance::delExcept ( ) 791void Appearance::delExcept ( )
792{ 792{
793 if ( m_except-> selectedItem ( )) 793 if ( m_except-> selectedItem ( ))
794 { 794 {
795 m_except-> setFocus ( ); 795 m_except-> setFocus ( );
796 delete m_except-> selectedItem ( ); 796 delete m_except-> selectedItem ( );
797 } 797 }
798} 798}
799 799
800void Appearance::upExcept ( ) 800void Appearance::upExcept ( )
801{ 801{
802 ExceptListItem *it = (ExceptListItem *) m_except-> selectedItem ( ); 802 ExceptListItem *it = (ExceptListItem *) m_except-> selectedItem ( );
803 803
804 if ( it && it-> itemAbove ( )) 804 if ( it && it-> itemAbove ( ))
805 it-> itemAbove ( )-> moveItem ( it ); 805 it-> itemAbove ( )-> moveItem ( it );
806} 806}
807 807
808void Appearance::downExcept ( ) 808void Appearance::downExcept ( )
809{ 809{
810 ExceptListItem *it = (ExceptListItem *) m_except-> selectedItem ( ); 810 ExceptListItem *it = (ExceptListItem *) m_except-> selectedItem ( );
811 811
812 if ( it && it-> itemBelow ( )) 812 if ( it && it-> itemBelow ( ))
813 it-> moveItem ( it-> itemBelow ( )); 813 it-> moveItem ( it-> itemBelow ( ));
814} 814}
815 815
816class ExEdit : public QLineEdit 816class ExEdit : public QLineEdit
817{ 817{
818public: 818public:
819 ExEdit ( ExceptListItem *item ) 819 ExEdit ( ExceptListItem *item )
820 : QLineEdit ( item-> listView ( )-> viewport ( ), "exedit" ), it ( item ) 820 : QLineEdit ( item-> listView ( )-> viewport ( ), "exedit" ), it ( item )
821 { 821 {
822 setFrame ( false ); 822 setFrame ( false );
823 823
824 QRect r = it-> listView ( )-> itemRect ( it ); 824 QRect r = it-> listView ( )-> itemRect ( it );
825 825
826 int x = it-> listView ( )-> header ( )-> cellPos ( 3 ) - 1; 826 int x = it-> listView ( )-> header ( )-> cellPos ( 3 ) - 1;
827 int y = r. y ( ); 827 int y = r. y ( );
828 int w = it-> listView ( )-> viewport ( )-> width ( ) - x; 828 int w = it-> listView ( )-> viewport ( )-> width ( ) - x;
829 int h = r. height ( ); // + 2; 829 int h = r. height ( ); // + 2;
830 830
831 setText ( it-> pattern ( )); 831 setText ( it-> pattern ( ));
832 setGeometry ( x, y, w, h ); 832 setGeometry ( x, y, w, h );
833 833
834 qDebug ( "ExEdit: [%s] at %d,%d %d,%d", it->text(2).latin1(),x,y,w,h); 834 qDebug ( "ExEdit: [%s] at %d,%d %d,%d", it->text(2).latin1(),x,y,w,h);
835 835
836 m_out = true; 836 m_out = true;
837 837
838 show ( ); 838 show ( );
839 setFocus ( ); 839 setFocus ( );
840 selectAll ( ); 840 selectAll ( );
841 end ( true ); 841 end ( true );
842 } 842 }
843 843
844 virtual void focusOutEvent ( QFocusEvent * ) 844 virtual void focusOutEvent ( QFocusEvent * )
845 { 845 {
846 hide ( ); 846 hide ( );
847 if ( m_out ) 847 if ( m_out )
848 it-> setPattern ( text ( )); 848 it-> setPattern ( text ( ));
849 delete this; 849 delete this;
850 } 850 }
851 851
852 virtual void keyPressEvent ( QKeyEvent *e ) 852 virtual void keyPressEvent ( QKeyEvent *e )
853 { 853 {
854 if ( e-> key ( ) == Key_Return ) 854 if ( e-> key ( ) == Key_Return )
855 it-> listView ( )-> setFocus ( ); 855 it-> listView ( )-> setFocus ( );
856 else if ( e-> key ( ) == Key_Escape ) 856 else if ( e-> key ( ) == Key_Escape )
857 { 857 {
858 m_out = false; 858 m_out = false;
859 it-> listView ( )-> setFocus ( ); 859 it-> listView ( )-> setFocus ( );
860 } 860 }
861 else 861 else
862 QLineEdit::keyPressEvent ( e ); 862 QLineEdit::keyPressEvent ( e );
863 } 863 }
864 864
865private: 865private:
866 ExceptListItem *it; 866 ExceptListItem *it;
867 bool m_out; 867 bool m_out;
868}; 868};
869 869
870void Appearance::clickedExcept ( QListViewItem *item, const QPoint &, int c ) 870void Appearance::clickedExcept ( QListViewItem *item, const QPoint &, int c )
871{ 871{
872 if ( !item || c < 0 || c > 3 ) 872 if ( !item || c < 0 || c > 3 )
873 return; 873 return;
874 874
875 ExceptListItem *it = (ExceptListItem *) item; 875 ExceptListItem *it = (ExceptListItem *) item;
876 876
877 if ( c == 0 ) 877 if ( c == 0 )
878 it-> setNoStyle ( !it-> noStyle ( )); 878 it-> setNoStyle ( !it-> noStyle ( ));
879 else if ( c == 1 ) 879 else if ( c == 1 )
880 it-> setNoFont ( !it-> noFont ( )); 880 it-> setNoFont ( !it-> noFont ( ));
881 else if ( c == 2 ) 881 else if ( c == 2 )
882 it-> setNoDeco ( !it-> noDeco ( )); 882 it-> setNoDeco ( !it-> noDeco ( ));
883 else if ( c == 3 ) 883 else if ( c == 3 )
884 { 884 {
885 m_except-> ensureItemVisible ( it ); 885 m_except-> ensureItemVisible ( it );
886 new ExEdit ( it ); 886 new ExEdit ( it );
887 } 887 }
888} 888}
889 889
diff --git a/noncore/settings/appearance2/sample.cpp b/noncore/settings/appearance2/sample.cpp
index b3a9d48..f6c4dca 100644
--- a/noncore/settings/appearance2/sample.cpp
+++ b/noncore/settings/appearance2/sample.cpp
@@ -1,271 +1,271 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. Copyright (c) 2002 Trolltech AS <info@trolltech.com> 3 =. Copyright (c) 2002 Trolltech AS <info@trolltech.com>
4             .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> 4             .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include <qvbox.h> 29#include <qvbox.h>
30#include <qpopupmenu.h> 30#include <qpopupmenu.h>
31#include <qpainter.h> 31#include <qpainter.h>
32#include <qmenubar.h> 32#include <qmenubar.h>
33#include <qcheckbox.h> 33#include <qcheckbox.h>
34#include <qpushbutton.h> 34#include <qpushbutton.h>
35#include <qscrollbar.h> 35#include <qscrollbar.h>
36#include <qlayout.h> 36#include <qlayout.h>
37#include <qwhatsthis.h> 37#include <qwhatsthis.h>
38#include <qpixmapcache.h> 38#include <qpixmapcache.h>
39#include <qtimer.h> 39#include <qtimer.h>
40#include <qobjectlist.h> 40#include <qobjectlist.h>
41#include <qcommonstyle.h> 41#include <qcommonstyle.h>
42 42
43#include "sample.h" 43#include "sample.h"
44 44
45 45
46class SampleText : public QWidget 46class SampleText : public QWidget
47{ 47{
48public: 48public:
49 SampleText( const QString &t, bool h, QWidget *parent ) 49 SampleText( const QString &t, bool h, QWidget *parent )
50 : QWidget( parent ), hl(h), text(t) 50 : QWidget( parent ), hl(h), text(t)
51 { 51 {
52 if ( hl ) 52 if ( hl )
53 setBackgroundMode( PaletteHighlight ); 53 setBackgroundMode( PaletteHighlight );
54 else 54 else
55 setBackgroundMode( PaletteBase ); 55 setBackgroundMode( PaletteBase );
56 } 56 }
57 57
58 QSize sizeHint() const 58 QSize sizeHint() const
59 { 59 {
60 QFontMetrics fm(font()); 60 QFontMetrics fm(font());
61 return QSize( fm.width(text)+10, fm.height()+4 ); 61 return QSize( fm.width(text)+10, fm.height()+4 );
62 } 62 }
63 63
64 void paintEvent( QPaintEvent * ) 64 void paintEvent( QPaintEvent * )
65 { 65 {
66 QPainter p(this); 66 QPainter p(this);
67 if ( hl ) 67 if ( hl )
68 p.setPen( colorGroup().highlightedText() ); 68 p.setPen( colorGroup().highlightedText() );
69 else 69 else
70 p.setPen( colorGroup().text() ); 70 p.setPen( colorGroup().text() );
71 p.drawText( rect(), AlignCenter, text ); 71 p.drawText( rect(), AlignCenter, text );
72 } 72 }
73 73
74private: 74private:
75 bool hl; 75 bool hl;
76 QString text; 76 QString text;
77}; 77};
78 78
79 79
80SampleWindow::SampleWindow( QWidget *parent ) : QWidget(parent), iface(0) 80SampleWindow::SampleWindow( QWidget *parent ) : QWidget(parent), iface(0)
81{ 81{
82 init(); 82 init();
83} 83}
84 84
85QSize SampleWindow::sizeHint() const 85QSize SampleWindow::sizeHint() const
86{ 86{
87 return container->sizeHint() + QSize( 10, 35 ); 87 return container->sizeHint() + QSize( 10, 35 );
88} 88}
89 89
90void SampleWindow::setFont( const QFont &f ) 90void SampleWindow::setFont( const QFont &f )
91{ 91{
92 QWidget::setFont( f ); 92 QWidget::setFont( f );
93 popup->setFont( f ); 93 popup->setFont( f );
94 QTimer::singleShot ( 0, this, SLOT( fixGeometry ( ))); 94 QTimer::singleShot ( 0, this, SLOT( fixGeometry()));
95} 95}
96 96
97static void setStyleRecursive ( QWidget *w, QStyle *s ) 97static void setStyleRecursive ( QWidget *w, QStyle *s )
98{ 98{
99 w->setStyle( s ); 99 w->setStyle( s );
100 QObjectList *childObjects=(QObjectList*)w->children(); 100 QObjectList *childObjects=(QObjectList*)w->children();
101 if ( childObjects ) { 101 if ( childObjects ) {
102 QObject * o; 102 QObject * o;
103 for(o=childObjects->first();o!=0;o=childObjects->next()) { 103 for(o=childObjects->first();o!=0;o=childObjects->next()) {
104 if( o->isWidgetType() ) { 104 if( o->isWidgetType() ) {
105 setStyleRecursive((QWidget *)o,s); 105 setStyleRecursive((QWidget *)o,s);
106 } 106 }
107 } 107 }
108 } 108 }
109} 109}
110 110
111 111
112void SampleWindow::setStyle2 ( QStyle *sty, const QPalette &pal ) 112void SampleWindow::setStyle2 ( QStyle *sty, const QPalette &pal )
113{ 113{
114 typedef void (QStyle::*QDrawMenuBarItemImpl) (QPainter *, int, int, int, int, QMenuItem *, QColorGroup &, bool, bool); 114 typedef void (QStyle::*QDrawMenuBarItemImpl) (QPainter *, int, int, int, int, QMenuItem *, QColorGroup &, bool, bool);
115 115
116 extern QDrawMenuBarItemImpl qt_set_draw_menu_bar_impl(QDrawMenuBarItemImpl); 116 extern QDrawMenuBarItemImpl qt_set_draw_menu_bar_impl(QDrawMenuBarItemImpl);
117 117
118 QPixmapCache::clear ( ); 118 QPixmapCache::clear ( );
119 QPalette p = pal; // ette ( ); 119 QPalette p = pal; // ette ( );
120 sty-> polish ( p ); 120 sty-> polish ( p );
121 qt_set_draw_menu_bar_impl ( 0 ); 121 qt_set_draw_menu_bar_impl ( 0 );
122 setStyleRecursive ( this, sty ); 122 setStyleRecursive ( this, sty );
123 setPalette ( p ); 123 setPalette ( p );
124 QTimer::singleShot ( 0, this, SLOT( fixGeometry ( ))); 124 QTimer::singleShot ( 0, this, SLOT( fixGeometry()));
125} 125}
126 126
127 127
128void SampleWindow::setDecoration( WindowDecorationInterface *i ) 128void SampleWindow::setDecoration( WindowDecorationInterface *i )
129{ 129{
130 iface = i; 130 iface = i;
131 wd.rect = QRect( 0, 0, 150, 75 ); 131 wd.rect = QRect( 0, 0, 150, 75 );
132 wd.caption = tr("Sample"); 132 wd.caption = tr("Sample");
133 wd.palette = palette(); 133 wd.palette = palette();
134 wd.flags = WindowDecorationInterface::WindowData::Dialog | 134 wd.flags = WindowDecorationInterface::WindowData::Dialog |
135 WindowDecorationInterface::WindowData::Active; 135 WindowDecorationInterface::WindowData::Active;
136 wd.reserved = 1; 136 wd.reserved = 1;
137 137
138 th = iface->metric(WindowDecorationInterface::TitleHeight, &wd); 138 th = iface->metric(WindowDecorationInterface::TitleHeight, &wd);
139 tb = iface->metric(WindowDecorationInterface::TopBorder, &wd); 139 tb = iface->metric(WindowDecorationInterface::TopBorder, &wd);
140 lb = iface->metric(WindowDecorationInterface::LeftBorder, &wd); 140 lb = iface->metric(WindowDecorationInterface::LeftBorder, &wd);
141 rb = iface->metric(WindowDecorationInterface::RightBorder, &wd); 141 rb = iface->metric(WindowDecorationInterface::RightBorder, &wd);
142 bb = iface->metric(WindowDecorationInterface::BottomBorder, &wd); 142 bb = iface->metric(WindowDecorationInterface::BottomBorder, &wd);
143 143
144 int yoff = th + tb; 144 int yoff = th + tb;
145 int xoff = lb; 145 int xoff = lb;
146 146
147 wd.rect.setX( 0 ); 147 wd.rect.setX( 0 );
148 wd.rect.setWidth( width() - lb - rb ); 148 wd.rect.setWidth( width() - lb - rb );
149 wd.rect.setY( 0 ); 149 wd.rect.setY( 0 );
150 wd.rect.setHeight( height() - yoff - bb ); 150 wd.rect.setHeight( height() - yoff - bb );
151 151
152 container->setGeometry( xoff, yoff, wd.rect.width(), wd.rect.height() ); 152 container->setGeometry( xoff, yoff, wd.rect.width(), wd.rect.height() );
153 setMinimumSize( container->sizeHint().width()+lb+rb, 153 setMinimumSize( container->sizeHint().width()+lb+rb,
154 container->sizeHint().height()+tb+th+bb ); 154 container->sizeHint().height()+tb+th+bb );
155} 155}
156 156
157void SampleWindow::paintEvent( QPaintEvent * ) 157void SampleWindow::paintEvent( QPaintEvent * )
158{ 158{
159 if ( !iface ) 159 if ( !iface )
160 return; 160 return;
161 161
162 QPainter p( this ); 162 QPainter p( this );
163 163
164 p.translate( lb, th+tb ); 164 p.translate( lb, th+tb );
165 165
166 iface->drawArea(WindowDecorationInterface::Border, &p, &wd); 166 iface->drawArea(WindowDecorationInterface::Border, &p, &wd);
167 iface->drawArea(WindowDecorationInterface::Title, &p, &wd); 167 iface->drawArea(WindowDecorationInterface::Title, &p, &wd);
168 168
169 p.setPen(palette().active().color(QColorGroup::HighlightedText)); 169 p.setPen(palette().active().color(QColorGroup::HighlightedText));
170 QFont f( font() ); 170 QFont f( font() );
171 f.setWeight( QFont::Bold ); 171 f.setWeight( QFont::Bold );
172 p.setFont(f); 172 p.setFont(f);
173 iface->drawArea(WindowDecorationInterface::TitleText, &p, &wd); 173 iface->drawArea(WindowDecorationInterface::TitleText, &p, &wd);
174 174
175 QRect brect( 0, -th, iface->metric(WindowDecorationInterface::HelpWidth,&wd), th ); 175 QRect brect( 0, -th, iface->metric(WindowDecorationInterface::HelpWidth,&wd), th );
176 iface->drawButton( WindowDecorationInterface::Help, &p, &wd, 176 iface->drawButton( WindowDecorationInterface::Help, &p, &wd,
177 brect.x(), brect.y(), brect.width(), brect.height(), (QWSButton::State)0 ); 177 brect.x(), brect.y(), brect.width(), brect.height(), (QWSButton::State)0 );
178 brect.moveBy( wd.rect.width() - 178 brect.moveBy( wd.rect.width() -
179 iface->metric(WindowDecorationInterface::OKWidth,&wd) - 179 iface->metric(WindowDecorationInterface::OKWidth,&wd) -
180 iface->metric(WindowDecorationInterface::CloseWidth,&wd), 0 ); 180 iface->metric(WindowDecorationInterface::CloseWidth,&wd), 0 );
181 iface->drawButton( WindowDecorationInterface::Close, &p, &wd, 181 iface->drawButton( WindowDecorationInterface::Close, &p, &wd,
182 brect.x(), brect.y(), brect.width(), brect.height(), (QWSButton::State)0 ); 182 brect.x(), brect.y(), brect.width(), brect.height(), (QWSButton::State)0 );
183 brect.moveBy( iface->metric(WindowDecorationInterface::CloseWidth,&wd), 0 ); 183 brect.moveBy( iface->metric(WindowDecorationInterface::CloseWidth,&wd), 0 );
184 iface->drawButton( WindowDecorationInterface::OK, &p, &wd, 184 iface->drawButton( WindowDecorationInterface::OK, &p, &wd,
185 brect.x(), brect.y(), brect.width(), brect.height(), (QWSButton::State)0 ); 185 brect.x(), brect.y(), brect.width(), brect.height(), (QWSButton::State)0 );
186} 186}
187 187
188void SampleWindow::init() 188void SampleWindow::init()
189{ 189{
190 container = new QVBox( this ); 190 container = new QVBox( this );
191 popup = new QPopupMenu( this ); 191 popup = new QPopupMenu( this );
192 popup->insertItem( tr("Normal Item"), 1 ); 192 popup->insertItem( tr("Normal Item"), 1 );
193 popup->insertItem( tr("Disabled Item"), 2 ); 193 popup->insertItem( tr("Disabled Item"), 2 );
194 popup->setItemEnabled(2, FALSE); 194 popup->setItemEnabled(2, FALSE);
195 QMenuBar *mb = new QMenuBar( container ); 195 QMenuBar *mb = new QMenuBar( container );
196 mb->insertItem( tr("Menu"), popup ); 196 mb->insertItem( tr("Menu"), popup );
197 QHBox *hb = new QHBox( container ); 197 QHBox *hb = new QHBox( container );
198 QWidget *w = new QWidget( hb ); 198 QWidget *w = new QWidget( hb );
199 (void)new QScrollBar( 0, 0, 0, 0, 0, Vertical, hb ); 199 (void)new QScrollBar( 0, 0, 0, 0, 0, Vertical, hb );
200 200
201 QGridLayout *gl = new QGridLayout( w, 2, 2, 4 ); 201 QGridLayout *gl = new QGridLayout( w, 2, 2, 4 );
202 SampleText *l = new SampleText( tr("Normal Text"), FALSE, w ); 202 SampleText *l = new SampleText( tr("Normal Text"), FALSE, w );
203 gl->addWidget( l, 0, 0 ); 203 gl->addWidget( l, 0, 0 );
204 204
205 l = new SampleText( tr("Highlighted Text"), TRUE, w ); 205 l = new SampleText( tr("Highlighted Text"), TRUE, w );
206 gl->addWidget( l, 1, 0 ); 206 gl->addWidget( l, 1, 0 );
207 207
208 QPushButton *pb = new QPushButton( tr("Button"), w ); 208 QPushButton *pb = new QPushButton( tr("Button"), w );
209 gl->addWidget( pb, 0, 1 ); 209 gl->addWidget( pb, 0, 1 );
210 pb->setFocusPolicy( NoFocus ); 210 pb->setFocusPolicy( NoFocus );
211 211
212 QCheckBox *cb = new QCheckBox( tr("Check Box"), w ); 212 QCheckBox *cb = new QCheckBox( tr("Check Box"), w );
213 gl->addWidget( cb, 1, 1 ); 213 gl->addWidget( cb, 1, 1 );
214 cb->setFocusPolicy( NoFocus ); 214 cb->setFocusPolicy( NoFocus );
215 cb->setChecked( TRUE ); 215 cb->setChecked( TRUE );
216 216
217 QWhatsThis::add( this, tr("Sample window using the selected settings.") ); 217 QWhatsThis::add( this, tr("Sample window using the selected settings.") );
218} 218}
219 219
220bool SampleWindow::eventFilter( QObject *, QEvent *e ) 220bool SampleWindow::eventFilter( QObject *, QEvent *e )
221{ 221{
222 switch ( e->type() ) { 222 switch ( e->type() ) {
223 case QEvent::MouseButtonPress: 223 case QEvent::MouseButtonPress:
224 case QEvent::MouseButtonRelease: 224 case QEvent::MouseButtonRelease:
225 case QEvent::MouseButtonDblClick: 225 case QEvent::MouseButtonDblClick:
226 case QEvent::MouseMove: 226 case QEvent::MouseMove:
227 case QEvent::KeyPress: 227 case QEvent::KeyPress:
228 case QEvent::KeyRelease: 228 case QEvent::KeyRelease:
229 return TRUE; 229 return TRUE;
230 default: 230 default:
231 break; 231 break;
232 } 232 }
233 233
234 return FALSE; 234 return FALSE;
235} 235}
236 236
237void SampleWindow::paletteChange( const QPalette &old ) 237void SampleWindow::paletteChange( const QPalette &old )
238{ 238{
239 QWidget::paletteChange ( old ); 239 QWidget::paletteChange ( old );
240 wd. palette = palette ( ); 240 wd. palette = palette ( );
241 popup-> setPalette ( palette ( )); 241 popup-> setPalette ( palette ( ));
242} 242}
243 243
244 244
245void SampleWindow::setPalette ( const QPalette &pal ) 245void SampleWindow::setPalette ( const QPalette &pal )
246{ 246{
247 QPixmapCache::clear ( ); 247 QPixmapCache::clear ( );
248 QPalette p = pal; 248 QPalette p = pal;
249 style ( ). polish ( p ); 249 style ( ). polish ( p );
250 QWidget::setPalette ( p ); 250 QWidget::setPalette ( p );
251} 251}
252 252
253void SampleWindow::resizeEvent( QResizeEvent *re ) 253void SampleWindow::resizeEvent( QResizeEvent *re )
254{ 254{
255 wd.rect = QRect( 0, 0, 150, 75 ); 255 wd.rect = QRect( 0, 0, 150, 75 );
256 256
257 wd.rect.setX( 0 ); 257 wd.rect.setX( 0 );
258 wd.rect.setWidth( width() - lb - rb ); 258 wd.rect.setWidth( width() - lb - rb );
259 wd.rect.setY( 0 ); 259 wd.rect.setY( 0 );
260 wd.rect.setHeight( height() - th - tb - bb ); 260 wd.rect.setHeight( height() - th - tb - bb );
261 261
262 container->setGeometry( lb, th+tb, wd.rect.width(), wd.rect.height() ); 262 container->setGeometry( lb, th+tb, wd.rect.width(), wd.rect.height() );
263 QWidget::resizeEvent( re ); 263 QWidget::resizeEvent( re );
264} 264}
265 265
266void SampleWindow::fixGeometry() 266void SampleWindow::fixGeometry()
267{ 267{
268 setMinimumSize( container->sizeHint().width()+lb+rb, 268 setMinimumSize( container->sizeHint().width()+lb+rb,
269 container->sizeHint().height()+tb+th+bb ); 269 container->sizeHint().height()+tb+th+bb );
270} 270}
271 271
diff --git a/noncore/settings/aqpkg/inputdlg.cpp b/noncore/settings/aqpkg/inputdlg.cpp
index 06e934c..30f0527 100644
--- a/noncore/settings/aqpkg/inputdlg.cpp
+++ b/noncore/settings/aqpkg/inputdlg.cpp
@@ -1,134 +1,134 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk> 4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk>
5             .=l. Dan Williams <drw@handhelds.org> 5             .=l. Dan Williams <drw@handhelds.org>
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include <qlayout.h> 30#include <qlayout.h>
31#include <qlabel.h> 31#include <qlabel.h>
32#include <qlineedit.h> 32#include <qlineedit.h>
33#include <qpushbutton.h> 33#include <qpushbutton.h>
34#include <qspinbox.h> 34#include <qspinbox.h>
35#include <qcombobox.h> 35#include <qcombobox.h>
36#include <qwidgetstack.h> 36#include <qwidgetstack.h>
37#include <qvalidator.h> 37#include <qvalidator.h>
38#include <qapplication.h> 38#include <qapplication.h>
39 39
40#include "inputdlg.h" 40#include "inputdlg.h"
41#include "global.h" 41#include "global.h"
42 42
43 43
44InputDialog :: InputDialog( const QString &label, QWidget* parent, const char* name, 44InputDialog :: InputDialog( const QString &label, QWidget* parent, const char* name,
45 bool modal ) 45 bool modal )
46 : QDialog( parent, name, modal ) 46 : QDialog( parent, name, modal )
47{ 47{
48 lineEdit = 0; 48 lineEdit = 0;
49 49
50 QVBoxLayout *vbox = new QVBoxLayout( this, 6, 6 ); 50 QVBoxLayout *vbox = new QVBoxLayout( this, 6, 6 );
51 51
52 QLabel* l = new QLabel( label, this ); 52 QLabel* l = new QLabel( label, this );
53 vbox->addWidget( l ); 53 vbox->addWidget( l );
54 54
55 lineEdit = new QLineEdit( this ); 55 lineEdit = new QLineEdit( this );
56 vbox->addWidget( lineEdit ); 56 vbox->addWidget( lineEdit );
57 57
58 QHBoxLayout *hbox = new QHBoxLayout( 6 ); 58 QHBoxLayout *hbox = new QHBoxLayout( 6 );
59 vbox->addLayout( hbox, AlignRight ); 59 vbox->addLayout( hbox, AlignRight );
60 60
61 ok = new QPushButton( tr( "&OK" ), this ); 61 ok = new QPushButton( tr( "&OK" ), this );
62 ok->setDefault( TRUE ); 62 ok->setDefault( TRUE );
63 QPushButton *cancel = new QPushButton( tr( "&Cancel" ), this ); 63 QPushButton *cancel = new QPushButton( tr( "&Cancel" ), this );
64 64
65 QSize bs( ok->sizeHint() ); 65 QSize bs( ok->sizeHint() );
66 if ( cancel->sizeHint().width() > bs.width() ) 66 if ( cancel->sizeHint().width() > bs.width() )
67 bs.setWidth( cancel->sizeHint().width() ); 67 bs.setWidth( cancel->sizeHint().width() );
68 68
69 ok->setFixedSize( bs ); 69 ok->setFixedSize( bs );
70 cancel->setFixedSize( bs ); 70 cancel->setFixedSize( bs );
71 71
72 hbox->addWidget( new QWidget( this ) ); 72 hbox->addWidget( new QWidget( this ) );
73 hbox->addWidget( ok ); 73 hbox->addWidget( ok );
74 hbox->addWidget( cancel ); 74 hbox->addWidget( cancel );
75 75
76 connect( lineEdit, SIGNAL( returnPressed() ), 76 connect( lineEdit, SIGNAL( returnPressed() ),
77 this, SLOT( tryAccept() ) ); 77 this, SLOT( tryAccept() ) );
78 connect( lineEdit, SIGNAL( textChanged( const QString & ) ), 78 connect( lineEdit, SIGNAL( textChanged(const QString&) ),
79 this, SLOT( textChanged( const QString & ) ) ); 79 this, SLOT( textChanged(const QString&) ) );
80 80
81 connect( ok, SIGNAL( clicked() ), this, SLOT( accept() ) ); 81 connect( ok, SIGNAL( clicked() ), this, SLOT( accept() ) );
82 connect( cancel, SIGNAL( clicked() ), this, SLOT( reject() ) ); 82 connect( cancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
83 83
84 resize( QMAX( sizeHint().width(), 240 ), sizeHint().height() ); 84 resize( QMAX( sizeHint().width(), 240 ), sizeHint().height() );
85} 85}
86 86
87/*! 87/*!
88 Destructor. 88 Destructor.
89*/ 89*/
90 90
91InputDialog::~InputDialog() 91InputDialog::~InputDialog()
92{ 92{
93} 93}
94 94
95void InputDialog :: setText( const QString &text ) 95void InputDialog :: setText( const QString &text )
96{ 96{
97 lineEdit->setText( text ); 97 lineEdit->setText( text );
98 lineEdit->selectAll(); 98 lineEdit->selectAll();
99} 99}
100 100
101QString InputDialog :: getText() 101QString InputDialog :: getText()
102{ 102{
103 return lineEdit->text(); 103 return lineEdit->text();
104} 104}
105 105
106QString InputDialog::getText( const QString &caption, const QString &label, 106QString InputDialog::getText( const QString &caption, const QString &label,
107 const QString &text, bool *ok, QWidget *parent, 107 const QString &text, bool *ok, QWidget *parent,
108 const char *name ) 108 const char *name )
109{ 109{
110 InputDialog *dlg = new InputDialog( label, parent, name, true ); 110 InputDialog *dlg = new InputDialog( label, parent, name, true );
111 dlg->setCaption( caption ); 111 dlg->setCaption( caption );
112 dlg->setText( text ); 112 dlg->setText( text );
113 113
114 QString result; 114 QString result;
115 *ok = dlg->exec() == QDialog::Accepted; 115 *ok = dlg->exec() == QDialog::Accepted;
116 if ( *ok ) 116 if ( *ok )
117 result = dlg->getText(); 117 result = dlg->getText();
118 118
119 delete dlg; 119 delete dlg;
120 return result; 120 return result;
121} 121}
122 122
123 123
124 124
125void InputDialog :: textChanged( const QString &s ) 125void InputDialog :: textChanged( const QString &s )
126{ 126{
127 ok->setEnabled( !s.isEmpty() ); 127 ok->setEnabled( !s.isEmpty() );
128} 128}
129 129
130void InputDialog :: tryAccept() 130void InputDialog :: tryAccept()
131{ 131{
132 if ( !lineEdit->text().isEmpty() ) 132 if ( !lineEdit->text().isEmpty() )
133 accept(); 133 accept();
134} 134}
diff --git a/noncore/settings/aqpkg/installdlgimpl.cpp b/noncore/settings/aqpkg/installdlgimpl.cpp
index d927a36..d2babb4 100644
--- a/noncore/settings/aqpkg/installdlgimpl.cpp
+++ b/noncore/settings/aqpkg/installdlgimpl.cpp
@@ -1,476 +1,476 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk> 4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk>
5             .=l. Dan Williams <drw@handhelds.org> 5             .=l. Dan Williams <drw@handhelds.org>
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include <stdio.h> 30#include <stdio.h>
31 31
32#include <opie2/ofiledialog.h> 32#include <opie2/ofiledialog.h>
33 33
34#ifdef QWS 34#ifdef QWS
35#include <qpe/config.h> 35#include <qpe/config.h>
36#include <qpe/fileselector.h> 36#include <qpe/fileselector.h>
37#include <qpe/qpeapplication.h> 37#include <qpe/qpeapplication.h>
38#include <qpe/resource.h> 38#include <qpe/resource.h>
39#include <qpe/storage.h> 39#include <qpe/storage.h>
40#endif 40#endif
41 41
42#include <qcheckbox.h> 42#include <qcheckbox.h>
43#include <qcombobox.h> 43#include <qcombobox.h>
44#include <qdialog.h> 44#include <qdialog.h>
45#include <qfileinfo.h> 45#include <qfileinfo.h>
46#include <qgroupbox.h> 46#include <qgroupbox.h>
47#include <qmultilineedit.h> 47#include <qmultilineedit.h>
48#include <qlabel.h> 48#include <qlabel.h>
49#include <qlayout.h> 49#include <qlayout.h>
50#include <qpushbutton.h> 50#include <qpushbutton.h>
51 51
52#include "datamgr.h" 52#include "datamgr.h"
53#include "destination.h" 53#include "destination.h"
54#include "instoptionsimpl.h" 54#include "instoptionsimpl.h"
55#include "installdlgimpl.h" 55#include "installdlgimpl.h"
56#include "ipkg.h" 56#include "ipkg.h"
57#include "utils.h" 57#include "utils.h"
58#include "global.h" 58#include "global.h"
59 59
60enum { 60enum {
61 MAXLINES = 100, 61 MAXLINES = 100,
62}; 62};
63 63
64InstallDlgImpl::InstallDlgImpl( const QList<InstallData> &packageList, DataManager *dataManager, const char *title ) 64InstallDlgImpl::InstallDlgImpl( const QList<InstallData> &packageList, DataManager *dataManager, const char *title )
65 : QWidget( 0, 0, 0 ) 65 : QWidget( 0, 0, 0 )
66{ 66{
67 setCaption( title ); 67 setCaption( title );
68 init( TRUE ); 68 init( TRUE );
69 69
70 pIpkg = 0; 70 pIpkg = 0;
71 upgradePackages = false; 71 upgradePackages = false;
72 dataMgr = dataManager; 72 dataMgr = dataManager;
73 73
74 QString defaultDest = "root"; 74 QString defaultDest = "root";
75#ifdef QWS 75#ifdef QWS
76 Config cfg( "aqpkg" ); 76 Config cfg( "aqpkg" );
77 cfg.setGroup( "settings" ); 77 cfg.setGroup( "settings" );
78 defaultDest = cfg.readEntry( "dest", "root" ); 78 defaultDest = cfg.readEntry( "dest", "root" );
79 79
80 // Grab flags - Turn MAKE_LINKS on by default (if no flags found) 80 // Grab flags - Turn MAKE_LINKS on by default (if no flags found)
81 flags = cfg.readNumEntry( "installFlags", 0 ); 81 flags = cfg.readNumEntry( "installFlags", 0 );
82 infoLevel = cfg.readNumEntry( "infoLevel", 1 ); 82 infoLevel = cfg.readNumEntry( "infoLevel", 1 );
83#else 83#else
84 flags = 0; 84 flags = 0;
85#endif 85#endif
86 86
87 // Output text is read only 87 // Output text is read only
88 output->setReadOnly( true ); 88 output->setReadOnly( true );
89// QFont f( "helvetica" ); 89// QFont f( "helvetica" );
90// f.setPointSize( 10 ); 90// f.setPointSize( 10 );
91// output->setFont( f ); 91// output->setFont( f );
92 92
93 93
94 // setup destination data 94 // setup destination data
95 int defIndex = 0; 95 int defIndex = 0;
96 int i; 96 int i;
97 QListIterator<Destination> dit( dataMgr->getDestinationList() ); 97 QListIterator<Destination> dit( dataMgr->getDestinationList() );
98 for ( i = 0; dit.current(); ++dit, ++i ) 98 for ( i = 0; dit.current(); ++dit, ++i )
99 { 99 {
100 destination->insertItem( dit.current()->getDestinationName() ); 100 destination->insertItem( dit.current()->getDestinationName() );
101 if ( dit.current()->getDestinationName() == defaultDest ) 101 if ( dit.current()->getDestinationName() == defaultDest )
102 defIndex = i; 102 defIndex = i;
103 } 103 }
104 104
105 destination->setCurrentItem( defIndex ); 105 destination->setCurrentItem( defIndex );
106 106
107 QListIterator<InstallData> it( packageList ); 107 QListIterator<InstallData> it( packageList );
108 // setup package data 108 // setup package data
109 QString remove = tr( "Remove\n" ); 109 QString remove = tr( "Remove\n" );
110 QString install = tr( "Install\n" ); 110 QString install = tr( "Install\n" );
111 QString upgrade = tr( "Upgrade\n" ); 111 QString upgrade = tr( "Upgrade\n" );
112 for ( ; it.current(); ++it ) 112 for ( ; it.current(); ++it )
113 { 113 {
114 InstallData *item = it.current(); 114 InstallData *item = it.current();
115 InstallData *newitem = new InstallData(); 115 InstallData *newitem = new InstallData();
116 116
117 newitem->option = item->option; 117 newitem->option = item->option;
118 newitem->packageName = item->packageName; 118 newitem->packageName = item->packageName;
119 newitem->destination = item->destination; 119 newitem->destination = item->destination;
120 newitem->recreateLinks = item->recreateLinks; 120 newitem->recreateLinks = item->recreateLinks;
121 packages.append( newitem ); 121 packages.append( newitem );
122 122
123 if ( item->option == "I" ) 123 if ( item->option == "I" )
124 { 124 {
125 install.append( QString( " %1\n" ).arg( item->packageName ) ); 125 install.append( QString( " %1\n" ).arg( item->packageName ) );
126 } 126 }
127 else if ( item->option == "D" ) 127 else if ( item->option == "D" )
128 { 128 {
129 remove.append( QString( " %1\n" ).arg( item->packageName ) ); 129 remove.append( QString( " %1\n" ).arg( item->packageName ) );
130 } 130 }
131 else if ( item->option == "U" || item->option == "R" ) 131 else if ( item->option == "U" || item->option == "R" )
132 { 132 {
133 QString type; 133 QString type;
134 if ( item->option == "R" ) 134 if ( item->option == "R" )
135 type = tr( "(ReInstall)" ); 135 type = tr( "(ReInstall)" );
136 else 136 else
137 type = tr( "(Upgrade)" ); 137 type = tr( "(Upgrade)" );
138 upgrade.append( QString( " %1 %2\n" ).arg( item->packageName ).arg( type ) ); 138 upgrade.append( QString( " %1 %2\n" ).arg( item->packageName ).arg( type ) );
139 } 139 }
140 } 140 }
141 141
142 output->setText( QString( "%1\n%2\n%3\n" ).arg( remove ).arg( install ).arg( upgrade ) ); 142 output->setText( QString( "%1\n%2\n%3\n" ).arg( remove ).arg( install ).arg( upgrade ) );
143 143
144 displayAvailableSpace( destination->currentText() ); 144 displayAvailableSpace( destination->currentText() );
145} 145}
146 146
147InstallDlgImpl::InstallDlgImpl( Ipkg *ipkg, QString initialText, const char *title ) 147InstallDlgImpl::InstallDlgImpl( Ipkg *ipkg, QString initialText, const char *title )
148 : QWidget( 0, 0, 0 ) 148 : QWidget( 0, 0, 0 )
149{ 149{
150 setCaption( title ); 150 setCaption( title );
151 init( FALSE ); 151 init( FALSE );
152 pIpkg = ipkg; 152 pIpkg = ipkg;
153 output->setText( initialText ); 153 output->setText( initialText );
154} 154}
155 155
156 156
157InstallDlgImpl::~InstallDlgImpl() 157InstallDlgImpl::~InstallDlgImpl()
158{ 158{
159 if ( pIpkg ) 159 if ( pIpkg )
160 delete pIpkg; 160 delete pIpkg;
161} 161}
162 162
163void InstallDlgImpl :: init( bool displayextrainfo ) 163void InstallDlgImpl :: init( bool displayextrainfo )
164{ 164{
165 QGridLayout *layout = new QGridLayout( this ); 165 QGridLayout *layout = new QGridLayout( this );
166 layout->setSpacing( 4 ); 166 layout->setSpacing( 4 );
167 layout->setMargin( 4 ); 167 layout->setMargin( 4 );
168 168
169 if ( displayextrainfo ) 169 if ( displayextrainfo )
170 { 170 {
171 QLabel *label = new QLabel( tr( "Destination" ), this ); 171 QLabel *label = new QLabel( tr( "Destination" ), this );
172 layout->addWidget( label, 0, 0 ); 172 layout->addWidget( label, 0, 0 );
173 destination = new QComboBox( FALSE, this ); 173 destination = new QComboBox( FALSE, this );
174 layout->addWidget( destination, 0, 1 ); 174 layout->addWidget( destination, 0, 1 );
175 connect( destination, SIGNAL( highlighted( const QString & ) ), 175 connect( destination, SIGNAL( highlighted(const QString&) ),
176 this, SLOT( displayAvailableSpace( const QString & ) ) ); 176 this, SLOT( displayAvailableSpace(const QString&) ) );
177 177
178 QLabel *label2 = new QLabel( tr( "Space Avail" ), this ); 178 QLabel *label2 = new QLabel( tr( "Space Avail" ), this );
179 layout->addWidget( label2, 1, 0 ); 179 layout->addWidget( label2, 1, 0 );
180 txtAvailableSpace = new QLabel( "", this ); 180 txtAvailableSpace = new QLabel( "", this );
181 layout->addWidget( txtAvailableSpace, 1, 1 ); 181 layout->addWidget( txtAvailableSpace, 1, 1 );
182 } 182 }
183 else 183 else
184 { 184 {
185 destination = 0x0; 185 destination = 0x0;
186 txtAvailableSpace = 0x0; 186 txtAvailableSpace = 0x0;
187 } 187 }
188 188
189 QGroupBox *GroupBox2 = new QGroupBox( 0, Qt::Vertical, tr( "Output" ), this ); 189 QGroupBox *GroupBox2 = new QGroupBox( 0, Qt::Vertical, tr( "Output" ), this );
190 GroupBox2->layout()->setSpacing( 0 ); 190 GroupBox2->layout()->setSpacing( 0 );
191 GroupBox2->layout()->setMargin( 4 ); 191 GroupBox2->layout()->setMargin( 4 );
192 192
193 QVBoxLayout *GroupBox2Layout = new QVBoxLayout( GroupBox2->layout() ); 193 QVBoxLayout *GroupBox2Layout = new QVBoxLayout( GroupBox2->layout() );
194 output = new QMultiLineEdit( GroupBox2 ); 194 output = new QMultiLineEdit( GroupBox2 );
195 GroupBox2Layout->addWidget( output ); 195 GroupBox2Layout->addWidget( output );
196 layout->addMultiCellWidget( GroupBox2, 2, 2, 0, 1 ); 196 layout->addMultiCellWidget( GroupBox2, 2, 2, 0, 1 );
197 197
198 btnInstall = new QPushButton( Resource::loadPixmap( "aqpkg/apply" ), tr( "Start" ), this ); 198 btnInstall = new QPushButton( Resource::loadPixmap( "aqpkg/apply" ), tr( "Start" ), this );
199 layout->addWidget( btnInstall, 3, 0 ); 199 layout->addWidget( btnInstall, 3, 0 );
200 connect( btnInstall, SIGNAL( clicked() ), this, SLOT( installSelected() ) ); 200 connect( btnInstall, SIGNAL( clicked() ), this, SLOT( installSelected() ) );
201 201
202 btnOptions = new QPushButton( Resource::loadPixmap( "SettingsIcon" ), tr( "Options" ), this ); 202 btnOptions = new QPushButton( Resource::loadPixmap( "SettingsIcon" ), tr( "Options" ), this );
203 layout->addWidget( btnOptions, 3, 1 ); 203 layout->addWidget( btnOptions, 3, 1 );
204 connect( btnOptions, SIGNAL( clicked() ), this, SLOT( optionsSelected() ) ); 204 connect( btnOptions, SIGNAL( clicked() ), this, SLOT( optionsSelected() ) );
205} 205}
206 206
207void InstallDlgImpl :: optionsSelected() 207void InstallDlgImpl :: optionsSelected()
208{ 208{
209 if ( btnOptions->text() == tr( "Options" ) ) 209 if ( btnOptions->text() == tr( "Options" ) )
210 { 210 {
211 InstallOptionsDlgImpl opt( flags, infoLevel, this, "Option", true ); 211 InstallOptionsDlgImpl opt( flags, infoLevel, this, "Option", true );
212 if ( opt.exec() == QDialog::Accepted ) 212 if ( opt.exec() == QDialog::Accepted )
213 { 213 {
214 // set options selected from dialog 214 // set options selected from dialog
215 flags = opt.getFlags(); 215 flags = opt.getFlags();
216 infoLevel = opt.getInfoLevel(); 216 infoLevel = opt.getInfoLevel();
217 217
218#ifdef QWS 218#ifdef QWS
219 Config cfg( "aqpkg" ); 219 Config cfg( "aqpkg" );
220 cfg.setGroup( "settings" ); 220 cfg.setGroup( "settings" );
221 cfg.writeEntry( "installFlags", flags ); 221 cfg.writeEntry( "installFlags", flags );
222 cfg.writeEntry( "infoLevel", infoLevel ); 222 cfg.writeEntry( "infoLevel", infoLevel );
223#endif 223#endif
224 } 224 }
225 } 225 }
226 else // Save output 226 else // Save output
227 { 227 {
228 QMap<QString, QStringList> map; 228 QMap<QString, QStringList> map;
229 map.insert( tr( "All" ), QStringList() ); 229 map.insert( tr( "All" ), QStringList() );
230 QStringList text; 230 QStringList text;
231 text << "text/*"; 231 text << "text/*";
232 map.insert(tr( "Text" ), text ); 232 map.insert(tr( "Text" ), text );
233 text << "*"; 233 text << "*";
234 map.insert( tr( "All" ), text ); 234 map.insert( tr( "All" ), text );
235 235
236 QString filename = Opie::OFileDialog::getSaveFileName( 2, "/", "ipkg-output", map ); 236 QString filename = Opie::OFileDialog::getSaveFileName( 2, "/", "ipkg-output", map );
237 if( !filename.isEmpty() ) 237 if( !filename.isEmpty() )
238 { 238 {
239 QString currentFileName = QFileInfo( filename ).fileName(); 239 QString currentFileName = QFileInfo( filename ).fileName();
240 DocLnk doc; 240 DocLnk doc;
241 doc.setType( "text/plain" ); 241 doc.setType( "text/plain" );
242 doc.setFile( filename ); 242 doc.setFile( filename );
243 doc.setName( currentFileName ); 243 doc.setName( currentFileName );
244 FileManager fm; 244 FileManager fm;
245 fm.saveFile( doc, output->text() ); 245 fm.saveFile( doc, output->text() );
246 } 246 }
247 } 247 }
248} 248}
249 249
250void InstallDlgImpl :: installSelected() 250void InstallDlgImpl :: installSelected()
251{ 251{
252 if ( btnInstall->text() == tr( "Abort" ) ) 252 if ( btnInstall->text() == tr( "Abort" ) )
253 { 253 {
254 if ( pIpkg ) 254 if ( pIpkg )
255 { 255 {
256 displayText( tr( "\n**** User Clicked ABORT ***" ) ); 256 displayText( tr( "\n**** User Clicked ABORT ***" ) );
257 pIpkg->abort(); 257 pIpkg->abort();
258 displayText( tr( "**** Process Aborted ****" ) ); 258 displayText( tr( "**** Process Aborted ****" ) );
259 } 259 }
260 260
261 btnInstall->setText( tr( "Close" ) ); 261 btnInstall->setText( tr( "Close" ) );
262 btnInstall->setIconSet( Resource::loadPixmap( "enter" ) ); 262 btnInstall->setIconSet( Resource::loadPixmap( "enter" ) );
263 return; 263 return;
264 } 264 }
265 else if ( btnInstall->text() == tr( "Close" ) ) 265 else if ( btnInstall->text() == tr( "Close" ) )
266 { 266 {
267 emit reloadData( this ); 267 emit reloadData( this );
268 return; 268 return;
269 } 269 }
270 270
271 // Disable buttons 271 // Disable buttons
272 btnOptions->setEnabled( false ); 272 btnOptions->setEnabled( false );
273// btnInstall->setEnabled( false ); 273// btnInstall->setEnabled( false );
274 274
275 btnInstall->setText( tr( "Abort" ) ); 275 btnInstall->setText( tr( "Abort" ) );
276 btnInstall->setIconSet( Resource::loadPixmap( "close" ) ); 276 btnInstall->setIconSet( Resource::loadPixmap( "close" ) );
277 277
278 if ( pIpkg ) 278 if ( pIpkg )
279 { 279 {
280 output->setText( "" ); 280 output->setText( "" );
281 connect( pIpkg, SIGNAL(outputText(const QString &)), this, SLOT(displayText(const QString &))); 281 connect( pIpkg, SIGNAL(outputText(const QString&)), this, SLOT(displayText(const QString&)));
282 connect( pIpkg, SIGNAL(ipkgFinished()), this, SLOT(ipkgFinished())); 282 connect( pIpkg, SIGNAL(ipkgFinished()), this, SLOT(ipkgFinished()));
283 pIpkg->runIpkg(); 283 pIpkg->runIpkg();
284 } 284 }
285 else 285 else
286 { 286 {
287 output->setText( "" ); 287 output->setText( "" );
288 Destination *d = dataMgr->getDestination( destination->currentText() ); 288 Destination *d = dataMgr->getDestination( destination->currentText() );
289 QString dest = d->getDestinationName(); 289 QString dest = d->getDestinationName();
290 QString destDir = d->getDestinationPath(); 290 QString destDir = d->getDestinationPath();
291 int instFlags = flags; 291 int instFlags = flags;
292 if ( d->linkToRoot() ) 292 if ( d->linkToRoot() )
293 instFlags |= MAKE_LINKS; 293 instFlags |= MAKE_LINKS;
294 294
295#ifdef QWS 295#ifdef QWS
296 // Save settings 296 // Save settings
297 Config cfg( "aqpkg" ); 297 Config cfg( "aqpkg" );
298 cfg.setGroup( "settings" ); 298 cfg.setGroup( "settings" );
299 cfg.writeEntry( "dest", dest ); 299 cfg.writeEntry( "dest", dest );
300#endif 300#endif
301 301
302 pIpkg = new Ipkg; 302 pIpkg = new Ipkg;
303 connect( pIpkg, SIGNAL(outputText(const QString &)), this, SLOT(displayText(const QString &))); 303 connect( pIpkg, SIGNAL(outputText(const QString&)), this, SLOT(displayText(const QString&)));
304 connect( pIpkg, SIGNAL(ipkgFinished()), this, SLOT(ipkgFinished())); 304 connect( pIpkg, SIGNAL(ipkgFinished()), this, SLOT(ipkgFinished()));
305 305
306 firstPackage = TRUE; 306 firstPackage = TRUE;
307 ipkgFinished(); 307 ipkgFinished();
308 308
309 // First run through the remove list, then the install list then the upgrade list 309 // First run through the remove list, then the install list then the upgrade list
310/* 310/*
311 pIpkg->setOption( "remove" ); 311 pIpkg->setOption( "remove" );
312 QListIterator<InstallData> it( removeList ); 312 QListIterator<InstallData> it( removeList );
313 InstallData *idata; 313 InstallData *idata;
314 for ( ; it.current(); ++it ) 314 for ( ; it.current(); ++it )
315 { 315 {
316 idata = it.current(); 316 idata = it.current();
317 pIpkg->setDestination( idata->destination->getDestinationName() ); 317 pIpkg->setDestination( idata->destination->getDestinationName() );
318 pIpkg->setDestinationDir( idata->destination->getDestinationPath() ); 318 pIpkg->setDestinationDir( idata->destination->getDestinationPath() );
319 pIpkg->setPackage( idata->packageName ); 319 pIpkg->setPackage( idata->packageName );
320 320
321 int tmpFlags = flags; 321 int tmpFlags = flags;
322 if ( idata->destination->linkToRoot() ) 322 if ( idata->destination->linkToRoot() )
323 tmpFlags |= MAKE_LINKS; 323 tmpFlags |= MAKE_LINKS;
324 324
325 pIpkg->setFlags( tmpFlags, infoLevel ); 325 pIpkg->setFlags( tmpFlags, infoLevel );
326 pIpkg->runIpkg(); 326 pIpkg->runIpkg();
327 } 327 }
328 328
329 pIpkg->setOption( "install" ); 329 pIpkg->setOption( "install" );
330 pIpkg->setDestination( dest ); 330 pIpkg->setDestination( dest );
331 pIpkg->setDestinationDir( destDir ); 331 pIpkg->setDestinationDir( destDir );
332 pIpkg->setFlags( instFlags, infoLevel ); 332 pIpkg->setFlags( instFlags, infoLevel );
333 QListIterator<InstallData> it2( installList ); 333 QListIterator<InstallData> it2( installList );
334 for ( ; it2.current(); ++it2 ) 334 for ( ; it2.current(); ++it2 )
335 { 335 {
336 pIpkg->setPackage( it2.current()->packageName ); 336 pIpkg->setPackage( it2.current()->packageName );
337 pIpkg->runIpkg(); 337 pIpkg->runIpkg();
338 } 338 }
339 339
340 flags |= FORCE_REINSTALL; 340 flags |= FORCE_REINSTALL;
341 QListIterator<InstallData> it3( updateList ); 341 QListIterator<InstallData> it3( updateList );
342 for ( ; it3.current() ; ++it3 ) 342 for ( ; it3.current() ; ++it3 )
343 { 343 {
344 idata = it3.current(); 344 idata = it3.current();
345 if ( idata->option == "R" ) 345 if ( idata->option == "R" )
346 pIpkg->setOption( "reinstall" ); 346 pIpkg->setOption( "reinstall" );
347 else 347 else
348 pIpkg->setOption( "upgrade" ); 348 pIpkg->setOption( "upgrade" );
349 pIpkg->setDestination( idata->destination->getDestinationName() ); 349 pIpkg->setDestination( idata->destination->getDestinationName() );
350 pIpkg->setDestinationDir( idata->destination->getDestinationPath() ); 350 pIpkg->setDestinationDir( idata->destination->getDestinationPath() );
351 pIpkg->setPackage( idata->packageName ); 351 pIpkg->setPackage( idata->packageName );
352 352
353 int tmpFlags = flags; 353 int tmpFlags = flags;
354 if ( idata->destination->linkToRoot() && idata->recreateLinks ) 354 if ( idata->destination->linkToRoot() && idata->recreateLinks )
355 tmpFlags |= MAKE_LINKS; 355 tmpFlags |= MAKE_LINKS;
356 pIpkg->setFlags( tmpFlags, infoLevel ); 356 pIpkg->setFlags( tmpFlags, infoLevel );
357 pIpkg->runIpkg(); 357 pIpkg->runIpkg();
358 } 358 }
359 359
360 delete pIpkg; 360 delete pIpkg;
361 pIpkg = 0; 361 pIpkg = 0;
362*/ 362*/
363 } 363 }
364} 364}
365 365
366 366
367void InstallDlgImpl :: displayText(const QString &text ) 367void InstallDlgImpl :: displayText(const QString &text )
368{ 368{
369 QString newtext = QString( "%1\n%2" ).arg( output->text() ).arg( text ); 369 QString newtext = QString( "%1\n%2" ).arg( output->text() ).arg( text );
370 370
371 /* Set a max line count for the QMultiLineEdit, as users have reported 371 /* Set a max line count for the QMultiLineEdit, as users have reported
372 * performance issues when line count gets extreme. 372 * performance issues when line count gets extreme.
373 */ 373 */
374 if(output->numLines() >= MAXLINES) 374 if(output->numLines() >= MAXLINES)
375 output->removeLine(0); 375 output->removeLine(0);
376 output->setText( newtext ); 376 output->setText( newtext );
377 output->setCursorPosition( output->numLines(), 0 ); 377 output->setCursorPosition( output->numLines(), 0 );
378} 378}
379 379
380 380
381void InstallDlgImpl :: displayAvailableSpace( const QString &text ) 381void InstallDlgImpl :: displayAvailableSpace( const QString &text )
382{ 382{
383 Destination *d = dataMgr->getDestination( text ); 383 Destination *d = dataMgr->getDestination( text );
384 QString destDir = d->getDestinationPath(); 384 QString destDir = d->getDestinationPath();
385 385
386 long blockSize = 0; 386 long blockSize = 0;
387 long totalBlocks = 0; 387 long totalBlocks = 0;
388 long availBlocks = 0; 388 long availBlocks = 0;
389 QString space; 389 QString space;
390 if ( Utils::getStorageSpace( (const char *)destDir, &blockSize, &totalBlocks, &availBlocks ) ) 390 if ( Utils::getStorageSpace( (const char *)destDir, &blockSize, &totalBlocks, &availBlocks ) )
391 { 391 {
392 long mult = blockSize / 1024; 392 long mult = blockSize / 1024;
393 long div = 1024 / blockSize; 393 long div = 1024 / blockSize;
394 394
395 if ( !mult ) mult = 1; 395 if ( !mult ) mult = 1;
396 if ( !div ) div = 1; 396 if ( !div ) div = 1;
397 long avail = availBlocks * mult / div; 397 long avail = availBlocks * mult / div;
398 398
399 space = tr( "%1 Kb" ).arg( avail ); 399 space = tr( "%1 Kb" ).arg( avail );
400 } 400 }
401 else 401 else
402 space = tr( "Unknown" ); 402 space = tr( "Unknown" );
403 403
404 if ( txtAvailableSpace ) 404 if ( txtAvailableSpace )
405 txtAvailableSpace->setText( space ); 405 txtAvailableSpace->setText( space );
406} 406}
407 407
408void InstallDlgImpl :: ipkgFinished() 408void InstallDlgImpl :: ipkgFinished()
409{ 409{
410 InstallData *item; 410 InstallData *item;
411 if ( firstPackage ) 411 if ( firstPackage )
412 item = packages.first(); 412 item = packages.first();
413 else 413 else
414 { 414 {
415 // Create symlinks if necessary before moving on to next package 415 // Create symlinks if necessary before moving on to next package
416 pIpkg->createSymLinks(); 416 pIpkg->createSymLinks();
417 417
418 item = packages.next(); 418 item = packages.next();
419 } 419 }
420 420
421 firstPackage = FALSE; 421 firstPackage = FALSE;
422 if ( item ) 422 if ( item )
423 { 423 {
424 pIpkg->setPackage( item->packageName ); 424 pIpkg->setPackage( item->packageName );
425 int tmpFlags = flags; 425 int tmpFlags = flags;
426 426
427 if ( item->option == "I" ) 427 if ( item->option == "I" )
428 { 428 {
429 pIpkg->setOption( "install" ); 429 pIpkg->setOption( "install" );
430 Destination *d = dataMgr->getDestination( destination->currentText() ); 430 Destination *d = dataMgr->getDestination( destination->currentText() );
431 pIpkg->setDestination( d->getDestinationName() ); 431 pIpkg->setDestination( d->getDestinationName() );
432 pIpkg->setDestinationDir( d->getDestinationPath() ); 432 pIpkg->setDestinationDir( d->getDestinationPath() );
433 433
434 if ( d->linkToRoot() ) 434 if ( d->linkToRoot() )
435 tmpFlags |= MAKE_LINKS; 435 tmpFlags |= MAKE_LINKS;
436 } 436 }
437 else if ( item->option == "D" ) 437 else if ( item->option == "D" )
438 { 438 {
439 pIpkg->setOption( "remove" ); 439 pIpkg->setOption( "remove" );
440 pIpkg->setDestination( item->destination->getDestinationName() ); 440 pIpkg->setDestination( item->destination->getDestinationName() );
441 pIpkg->setDestinationDir( item->destination->getDestinationPath() ); 441 pIpkg->setDestinationDir( item->destination->getDestinationPath() );
442 442
443 if ( item->destination->linkToRoot() ) 443 if ( item->destination->linkToRoot() )
444 tmpFlags |= MAKE_LINKS; 444 tmpFlags |= MAKE_LINKS;
445 } 445 }
446 else 446 else
447 { 447 {
448 if ( item->option == "R" ) 448 if ( item->option == "R" )
449 pIpkg->setOption( "reinstall" ); 449 pIpkg->setOption( "reinstall" );
450 else 450 else
451 pIpkg->setOption( "upgrade" ); 451 pIpkg->setOption( "upgrade" );
452 452
453 pIpkg->setDestination( item->destination->getDestinationName() ); 453 pIpkg->setDestination( item->destination->getDestinationName() );
454 pIpkg->setDestinationDir( item->destination->getDestinationPath() ); 454 pIpkg->setDestinationDir( item->destination->getDestinationPath() );
455 pIpkg->setPackage( item->packageName ); 455 pIpkg->setPackage( item->packageName );
456 456
457 tmpFlags |= FORCE_REINSTALL; 457 tmpFlags |= FORCE_REINSTALL;
458 if ( item->destination->linkToRoot() && item->recreateLinks ) 458 if ( item->destination->linkToRoot() && item->recreateLinks )
459 tmpFlags |= MAKE_LINKS; 459 tmpFlags |= MAKE_LINKS;
460 } 460 }
461 pIpkg->setFlags( tmpFlags, infoLevel ); 461 pIpkg->setFlags( tmpFlags, infoLevel );
462 pIpkg->runIpkg(); 462 pIpkg->runIpkg();
463 } 463 }
464 else 464 else
465 { 465 {
466 btnOptions->setEnabled( true ); 466 btnOptions->setEnabled( true );
467 btnInstall->setText( tr( "Close" ) ); 467 btnInstall->setText( tr( "Close" ) );
468 btnInstall->setIconSet( Resource::loadPixmap( "enter" ) ); 468 btnInstall->setIconSet( Resource::loadPixmap( "enter" ) );
469 469
470 btnOptions->setText( tr( "Save output" ) ); 470 btnOptions->setText( tr( "Save output" ) );
471 btnOptions->setIconSet( Resource::loadPixmap( "save" ) ); 471 btnOptions->setIconSet( Resource::loadPixmap( "save" ) );
472 472
473 if ( destination && destination->currentText() != 0 && destination->currentText() != "" ) 473 if ( destination && destination->currentText() != 0 && destination->currentText() != "" )
474 displayAvailableSpace( destination->currentText() ); 474 displayAvailableSpace( destination->currentText() );
475 } 475 }
476} 476}
diff --git a/noncore/settings/aqpkg/ipkg.cpp b/noncore/settings/aqpkg/ipkg.cpp
index 3761b67..866afed 100644
--- a/noncore/settings/aqpkg/ipkg.cpp
+++ b/noncore/settings/aqpkg/ipkg.cpp
@@ -1,520 +1,520 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk> 4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk>
5             .=l. Dan Williams <drw@handhelds.org> 5             .=l. Dan Williams <drw@handhelds.org>
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include <opie2/oprocess.h> 30#include <opie2/oprocess.h>
31 31
32#ifdef QWS 32#ifdef QWS
33#include <qpe/qpeapplication.h> 33#include <qpe/qpeapplication.h>
34#else 34#else
35#include <qapplication.h> 35#include <qapplication.h>
36#endif 36#endif
37#include <qdir.h> 37#include <qdir.h>
38#include <qfile.h> 38#include <qfile.h>
39#include <qtextstream.h> 39#include <qtextstream.h>
40 40
41#include "utils.h" 41#include "utils.h"
42#include "ipkg.h" 42#include "ipkg.h"
43#include "global.h" 43#include "global.h"
44 44
45Ipkg :: Ipkg() 45Ipkg :: Ipkg()
46{ 46{
47 proc = 0; 47 proc = 0;
48} 48}
49 49
50Ipkg :: ~Ipkg() 50Ipkg :: ~Ipkg()
51{ 51{
52} 52}
53 53
54// Option is what we are going to do - install, upgrade, download, reinstall 54// Option is what we are going to do - install, upgrade, download, reinstall
55// package is the package name to install - either a fully qualified path and ipk 55// package is the package name to install - either a fully qualified path and ipk
56// file (if stored locally) or just the name of the package (for a network package) 56// file (if stored locally) or just the name of the package (for a network package)
57// packageName is the package name - (for a network package this will be the same as 57// packageName is the package name - (for a network package this will be the same as
58// package parameter) 58// package parameter)
59// dest is the destination alias (from ipk.conf) 59// dest is the destination alias (from ipk.conf)
60// destDir is the dir that the destination alias points to (used to link to root) 60// destDir is the dir that the destination alias points to (used to link to root)
61// flags is the ipkg options flags 61// flags is the ipkg options flags
62// dir is the directory to run ipkg in (defaults to "") 62// dir is the directory to run ipkg in (defaults to "")
63void Ipkg :: runIpkg() 63void Ipkg :: runIpkg()
64{ 64{
65 error = false; 65 error = false;
66 QStringList commands; 66 QStringList commands;
67 67
68 QDir::setCurrent( "/tmp" ); 68 QDir::setCurrent( "/tmp" );
69 69
70 if ( runtimeDir != "" ) 70 if ( runtimeDir != "" )
71 { 71 {
72 commands << "cd "; 72 commands << "cd ";
73 commands << runtimeDir; 73 commands << runtimeDir;
74 commands << ";"; 74 commands << ";";
75 } 75 }
76 commands << "ipkg" << "-V" << QString::number( infoLevel ) << "-force-defaults"; 76 commands << "ipkg" << "-V" << QString::number( infoLevel ) << "-force-defaults";
77 77
78 // only set the destination for an install operation 78 // only set the destination for an install operation
79 if ( option == "install" ) 79 if ( option == "install" )
80 commands << "-dest" << destination; 80 commands << "-dest" << destination;
81 81
82 82
83 if ( option != "update" && option != "download" ) 83 if ( option != "update" && option != "download" )
84 { 84 {
85 if ( flags & FORCE_DEPENDS ) 85 if ( flags & FORCE_DEPENDS )
86 commands << "-force-depends"; 86 commands << "-force-depends";
87 if ( flags & FORCE_REINSTALL ) 87 if ( flags & FORCE_REINSTALL )
88 commands << "-force-reinstall"; 88 commands << "-force-reinstall";
89 if ( flags & FORCE_REMOVE ) 89 if ( flags & FORCE_REMOVE )
90 commands << "-force-removal-of-essential-packages"; 90 commands << "-force-removal-of-essential-packages";
91 if ( flags & FORCE_OVERWRITE ) 91 if ( flags & FORCE_OVERWRITE )
92 commands << "-force-overwrite"; 92 commands << "-force-overwrite";
93 if ( infoLevel == 3 ) 93 if ( infoLevel == 3 )
94 commands << "-verbose_wget"; 94 commands << "-verbose_wget";
95 95
96 // Handle make links 96 // Handle make links
97 // Rules - If make links is switched on, create links to root 97 // Rules - If make links is switched on, create links to root
98 // if destDir is NOT / 98 // if destDir is NOT /
99 if ( flags & MAKE_LINKS ) 99 if ( flags & MAKE_LINKS )
100 { 100 {
101 // If destDir == / turn off make links as package is being insalled 101 // If destDir == / turn off make links as package is being insalled
102 // to root already. 102 // to root already.
103 if ( destDir == "/" ) 103 if ( destDir == "/" )
104 flags ^= MAKE_LINKS; 104 flags ^= MAKE_LINKS;
105 } 105 }
106 } 106 }
107 107
108#ifdef X86 108#ifdef X86
109 commands << "-f"; 109 commands << "-f";
110 commands << IPKG_CONF; 110 commands << IPKG_CONF;
111#endif 111#endif
112 112
113 113
114 if ( option == "reinstall" ) 114 if ( option == "reinstall" )
115 commands << "install"; 115 commands << "install";
116 else 116 else
117 commands << option; 117 commands << option;
118 if ( package != "" ) 118 if ( package != "" )
119 commands << package; 119 commands << package;
120 120
121 121
122 if ( package != "" ) 122 if ( package != "" )
123 emit outputText( tr( "Dealing with package %1" ).arg( package) ); 123 emit outputText( tr( "Dealing with package %1" ).arg( package) );
124 124
125 qApp->processEvents(); 125 qApp->processEvents();
126 126
127 // If we are removing, reinstalling or upgrading packages and make links option is selected 127 // If we are removing, reinstalling or upgrading packages and make links option is selected
128 // create the links 128 // create the links
129 if ( option == "remove" || option == "reinstall" || option == "upgrade" ) 129 if ( option == "remove" || option == "reinstall" || option == "upgrade" )
130 { 130 {
131 createLinks = false; 131 createLinks = false;
132 if ( flags & MAKE_LINKS ) 132 if ( flags & MAKE_LINKS )
133 { 133 {
134 emit outputText( tr( "Removing symbolic links...\n" ) ); 134 emit outputText( tr( "Removing symbolic links...\n" ) );
135 linkPackage( Utils::getPackageNameFromIpkFilename( package ), destination, destDir ); 135 linkPackage( Utils::getPackageNameFromIpkFilename( package ), destination, destDir );
136 emit outputText( QString( " " ) ); 136 emit outputText( QString( " " ) );
137 } 137 }
138 } 138 }
139 139
140 // Execute command 140 // Execute command
141 dependantPackages = new QList<QString>; 141 dependantPackages = new QList<QString>;
142 dependantPackages->setAutoDelete( true ); 142 dependantPackages->setAutoDelete( true );
143 143
144 executeIpkgCommand( commands, option ); 144 executeIpkgCommand( commands, option );
145 145
146} 146}
147 147
148void Ipkg :: createSymLinks() 148void Ipkg :: createSymLinks()
149{ 149{
150 if ( option == "install" || option == "reinstall" || option == "upgrade" ) 150 if ( option == "install" || option == "reinstall" || option == "upgrade" )
151 { 151 {
152 // If we are not removing packages and make links option is selected 152 // If we are not removing packages and make links option is selected
153 // create the links 153 // create the links
154 createLinks = true; 154 createLinks = true;
155 if ( flags & MAKE_LINKS ) 155 if ( flags & MAKE_LINKS )
156 { 156 {
157 emit outputText( " " ); 157 emit outputText( " " );
158 emit outputText( tr( "Creating symbolic links for %1." ).arg( package) ); 158 emit outputText( tr( "Creating symbolic links for %1." ).arg( package) );
159 159
160 linkPackage( Utils::getPackageNameFromIpkFilename( package ), destination, destDir ); 160 linkPackage( Utils::getPackageNameFromIpkFilename( package ), destination, destDir );
161 161
162 // link dependant packages that were installed with this release 162 // link dependant packages that were installed with this release
163 QString *pkg; 163 QString *pkg;
164 for ( pkg = dependantPackages->first(); pkg != 0; pkg = dependantPackages->next() ) 164 for ( pkg = dependantPackages->first(); pkg != 0; pkg = dependantPackages->next() )
165 { 165 {
166 if ( *pkg == package ) 166 if ( *pkg == package )
167 continue; 167 continue;
168 emit outputText( " " ); 168 emit outputText( " " );
169 emit outputText( tr( "Creating symbolic links for %1" ).arg( *pkg ) ); 169 emit outputText( tr( "Creating symbolic links for %1" ).arg( *pkg ) );
170 linkPackage( Utils::getPackageNameFromIpkFilename( *pkg ), destination, destDir ); 170 linkPackage( Utils::getPackageNameFromIpkFilename( *pkg ), destination, destDir );
171 } 171 }
172 } 172 }
173 } 173 }
174 174
175 delete dependantPackages; 175 delete dependantPackages;
176 176
177 emit outputText( tr("Finished") ); 177 emit outputText( tr("Finished") );
178 emit outputText( "" ); 178 emit outputText( "" );
179} 179}
180 180
181void Ipkg :: removeStatusEntry() 181void Ipkg :: removeStatusEntry()
182{ 182{
183 QString statusFile = destDir; 183 QString statusFile = destDir;
184 if ( statusFile.right( 1 ) != "/" ) 184 if ( statusFile.right( 1 ) != "/" )
185 statusFile.append( "/" ); 185 statusFile.append( "/" );
186 statusFile.append( "usr/lib/ipkg/status" ); 186 statusFile.append( "usr/lib/ipkg/status" );
187 QString outStatusFile = statusFile; 187 QString outStatusFile = statusFile;
188 outStatusFile.append( ".tmp" ); 188 outStatusFile.append( ".tmp" );
189 189
190 emit outputText( "" ); 190 emit outputText( "" );
191 emit outputText( tr("Removing status entry...") ); 191 emit outputText( tr("Removing status entry...") );
192 QString tempstr = tr("status file - "); 192 QString tempstr = tr("status file - ");
193 tempstr.append( statusFile ); 193 tempstr.append( statusFile );
194 emit outputText( tempstr ); 194 emit outputText( tempstr );
195 tempstr = tr("package - "); 195 tempstr = tr("package - ");
196 tempstr.append( package ); 196 tempstr.append( package );
197 emit outputText( tempstr ); 197 emit outputText( tempstr );
198 198
199 QFile readFile( statusFile ); 199 QFile readFile( statusFile );
200 QFile writeFile( outStatusFile ); 200 QFile writeFile( outStatusFile );
201 201
202 if ( !readFile.open( IO_ReadOnly ) ) 202 if ( !readFile.open( IO_ReadOnly ) )
203 { 203 {
204 tempstr = tr("Couldn't open status file - "); 204 tempstr = tr("Couldn't open status file - ");
205 tempstr.append( statusFile ); 205 tempstr.append( statusFile );
206 emit outputText( tempstr ); 206 emit outputText( tempstr );
207 return; 207 return;
208 } 208 }
209 209
210 if ( !writeFile.open( IO_WriteOnly ) ) 210 if ( !writeFile.open( IO_WriteOnly ) )
211 { 211 {
212 tempstr = tr("Couldn't create tempory status file - "); 212 tempstr = tr("Couldn't create tempory status file - ");
213 tempstr.append( outStatusFile ); 213 tempstr.append( outStatusFile );
214 emit outputText( tempstr ); 214 emit outputText( tempstr );
215 return; 215 return;
216 } 216 }
217 217
218 int i = 0; 218 int i = 0;
219 219
220 QTextStream readStream( &readFile ); 220 QTextStream readStream( &readFile );
221 QTextStream writeStream( &writeFile ); 221 QTextStream writeStream( &writeFile );
222 QString line; 222 QString line;
223 223
224 char k[21]; 224 char k[21];
225 char v[1001]; 225 char v[1001];
226 QString key; 226 QString key;
227 QString value; 227 QString value;
228 228
229 while ( !readStream.atEnd() ) 229 while ( !readStream.atEnd() )
230 { 230 {
231 //read new line 231 //read new line
232 line = readStream.readLine(); 232 line = readStream.readLine();
233 233
234 if ( line.contains( ":", TRUE ) ) 234 if ( line.contains( ":", TRUE ) )
235 { 235 {
236 //grep key and value from line 236 //grep key and value from line
237 k[0] = '\0'; 237 k[0] = '\0';
238 v[0] = '\0'; 238 v[0] = '\0';
239 sscanf( line, "%[^:]: %[^\n]", k, v ); 239 sscanf( line, "%[^:]: %[^\n]", k, v );
240 key = k; 240 key = k;
241 value = v; 241 value = v;
242 key = key.stripWhiteSpace(); 242 key = key.stripWhiteSpace();
243 value = value.stripWhiteSpace(); 243 value = value.stripWhiteSpace();
244 } else { 244 } else {
245 key = ""; 245 key = "";
246 value = ""; 246 value = "";
247 } 247 }
248 248
249 if ( key == "Package" && value == package ) 249 if ( key == "Package" && value == package )
250 { 250 {
251 //skip lines from the deleted package 251 //skip lines from the deleted package
252 while ( ( !readStream.atEnd() ) && ( line.stripWhiteSpace() != "" ) ) 252 while ( ( !readStream.atEnd() ) && ( line.stripWhiteSpace() != "" ) )
253 { 253 {
254 line = readStream.readLine(); 254 line = readStream.readLine();
255 } 255 }
256 } else { 256 } else {
257 257
258 //write other lines into the tempfile 258 //write other lines into the tempfile
259 writeStream << line << "\n"; 259 writeStream << line << "\n";
260 260
261 // Improve UI responsiveness 261 // Improve UI responsiveness
262 i++; 262 i++;
263 if ( ( i % 50 ) == 0 ) 263 if ( ( i % 50 ) == 0 )
264 qApp->processEvents(); 264 qApp->processEvents();
265 } 265 }
266 } 266 }
267 267
268 readFile.close(); 268 readFile.close();
269 writeFile.close(); 269 writeFile.close();
270 270
271 // Remove old status file and put tmp stats file in its place 271 // Remove old status file and put tmp stats file in its place
272 remove( statusFile ); 272 remove( statusFile );
273 rename( outStatusFile, statusFile ); 273 rename( outStatusFile, statusFile );
274 } 274 }
275 275
276int Ipkg :: executeIpkgCommand( QStringList &cmd, const QString /*option*/ ) 276int Ipkg :: executeIpkgCommand( QStringList &cmd, const QString /*option*/ )
277{ 277{
278 // If one is already running - should never be but just to be safe 278 // If one is already running - should never be but just to be safe
279 if ( proc ) 279 if ( proc )
280 { 280 {
281 delete proc; 281 delete proc;
282 proc = 0; 282 proc = 0;
283 } 283 }
284 284
285 // OK we're gonna use OProcess to run this thing 285 // OK we're gonna use OProcess to run this thing
286 proc = new OProcess(); 286 proc = new OProcess();
287 aborted = false; 287 aborted = false;
288 288
289 289
290 // Connect up our slots 290 // Connect up our slots
291 connect(proc, SIGNAL(processExited(OProcess *)), 291 connect(proc, SIGNAL(processExited(OProcess*)),
292 this, SLOT( processFinished())); 292 this, SLOT( processFinished()));
293 293
294 connect(proc, SIGNAL(receivedStdout(OProcess *, char *, int)), 294 connect(proc, SIGNAL(receivedStdout(OProcess*,char*,int)),
295 this, SLOT(commandStdout(OProcess *, char *, int))); 295 this, SLOT(commandStdout(OProcess*,char*,int)));
296 296
297 connect(proc, SIGNAL(receivedStderr(OProcess *, char *, int)), 297 connect(proc, SIGNAL(receivedStderr(OProcess*,char*,int)),
298 this, SLOT(commandStderr(OProcess *, char *, int))); 298 this, SLOT(commandStderr(OProcess*,char*,int)));
299 299
300 for ( QStringList::Iterator it = cmd.begin(); it != cmd.end(); ++it ) 300 for ( QStringList::Iterator it = cmd.begin(); it != cmd.end(); ++it )
301 { 301 {
302 *proc << (*it).latin1(); 302 *proc << (*it).latin1();
303 } 303 }
304 304
305 // Start the process going 305 // Start the process going
306 finished = false; 306 finished = false;
307 if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) 307 if(!proc->start(OProcess::NotifyOnExit, OProcess::All))
308 { 308 {
309 emit outputText( tr("Couldn't start ipkg process" ) ); 309 emit outputText( tr("Couldn't start ipkg process" ) );
310 } 310 }
311} 311}
312 312
313void Ipkg::commandStdout(OProcess*, char *buffer, int buflen) 313void Ipkg::commandStdout(OProcess*, char *buffer, int buflen)
314{ 314{
315 QString lineStr = buffer; 315 QString lineStr = buffer;
316 if ( lineStr[buflen-1] == '\n' ) 316 if ( lineStr[buflen-1] == '\n' )
317 buflen --; 317 buflen --;
318 lineStr = lineStr.left( buflen ); 318 lineStr = lineStr.left( buflen );
319 emit outputText( lineStr ); 319 emit outputText( lineStr );
320 320
321 // check if we are installing dependant packages 321 // check if we are installing dependant packages
322 if ( option == "install" || option == "reinstall" ) 322 if ( option == "install" || option == "reinstall" )
323 { 323 {
324 // Need to keep track of any dependant packages that get installed 324 // Need to keep track of any dependant packages that get installed
325 // so that we can create links to them as necessary 325 // so that we can create links to them as necessary
326 if ( lineStr.startsWith( "Installing " ) ) 326 if ( lineStr.startsWith( "Installing " ) )
327 { 327 {
328 int start = lineStr.find( " " ) + 1; 328 int start = lineStr.find( " " ) + 1;
329 int end = lineStr.find( " ", start ); 329 int end = lineStr.find( " ", start );
330 QString *package = new QString( lineStr.mid( start, end-start ) ); 330 QString *package = new QString( lineStr.mid( start, end-start ) );
331 dependantPackages->append( package ); 331 dependantPackages->append( package );
332 } 332 }
333 } 333 }
334 else if ( option == "remove" && !( flags & FORCE_DEPENDS ) && 334 else if ( option == "remove" && !( flags & FORCE_DEPENDS ) &&
335 lineStr.find( "is depended upon by packages:" ) != -1 ) 335 lineStr.find( "is depended upon by packages:" ) != -1 )
336 { 336 {
337 // Ipkg should send this to STDERR, but doesn't - so trap here 337 // Ipkg should send this to STDERR, but doesn't - so trap here
338 error = true; 338 error = true;
339 } 339 }
340 340
341 buffer[0] = '\0'; 341 buffer[0] = '\0';
342} 342}
343 343
344void Ipkg::commandStderr(OProcess*, char *buffer, int buflen) 344void Ipkg::commandStderr(OProcess*, char *buffer, int buflen)
345{ 345{
346 QString lineStr = buffer; 346 QString lineStr = buffer;
347 if ( lineStr[buflen-1] == '\n' ) 347 if ( lineStr[buflen-1] == '\n' )
348 buflen --; 348 buflen --;
349 lineStr=lineStr.left( buflen ); 349 lineStr=lineStr.left( buflen );
350 emit outputText( lineStr ); 350 emit outputText( lineStr );
351 buffer[0] = '\0'; 351 buffer[0] = '\0';
352 error = true; 352 error = true;
353} 353}
354 354
355void Ipkg::processFinished() 355void Ipkg::processFinished()
356{ 356{
357 // Finally, if we are removing a package, remove its entry from the <destdir>/usr/lib/ipkg/status file 357 // Finally, if we are removing a package, remove its entry from the <destdir>/usr/lib/ipkg/status file
358 // to workaround an ipkg bug which stops reinstall to a different location 358 // to workaround an ipkg bug which stops reinstall to a different location
359 359
360 if ( !error && option == "remove" ) 360 if ( !error && option == "remove" )
361 removeStatusEntry(); 361 removeStatusEntry();
362 362
363 delete proc; 363 delete proc;
364 proc = 0; 364 proc = 0;
365 finished = true; 365 finished = true;
366 366
367 emit ipkgFinished(); 367 emit ipkgFinished();
368} 368}
369 369
370 370
371void Ipkg :: abort() 371void Ipkg :: abort()
372{ 372{
373 if ( proc ) 373 if ( proc )
374 { 374 {
375 proc->kill(); 375 proc->kill();
376 aborted = true; 376 aborted = true;
377 } 377 }
378} 378}
379 379
380void Ipkg :: linkPackage( const QString &packFileName, const QString &dest, const QString &destDir ) 380void Ipkg :: linkPackage( const QString &packFileName, const QString &dest, const QString &destDir )
381{ 381{
382 if ( dest == "root" || dest == "/" ) 382 if ( dest == "root" || dest == "/" )
383 return; 383 return;
384 384
385 qApp->processEvents(); 385 qApp->processEvents();
386 QStringList *fileList = getList( packFileName, destDir ); 386 QStringList *fileList = getList( packFileName, destDir );
387 qApp->processEvents(); 387 qApp->processEvents();
388 processFileList( fileList, destDir ); 388 processFileList( fileList, destDir );
389 delete fileList; 389 delete fileList;
390} 390}
391 391
392QStringList* Ipkg :: getList( const QString &packageFilename, const QString &destDir ) 392QStringList* Ipkg :: getList( const QString &packageFilename, const QString &destDir )
393{ 393{
394 QString packageFileDir = destDir; 394 QString packageFileDir = destDir;
395 packageFileDir.append( "/usr/lib/ipkg/info/" ); 395 packageFileDir.append( "/usr/lib/ipkg/info/" );
396 packageFileDir.append( packageFilename ); 396 packageFileDir.append( packageFilename );
397 packageFileDir.append( ".list" ); 397 packageFileDir.append( ".list" );
398 QFile f( packageFileDir ); 398 QFile f( packageFileDir );
399 399
400 if ( !f.open(IO_ReadOnly) ) 400 if ( !f.open(IO_ReadOnly) )
401 { 401 {
402 // Couldn't open from dest, try from / 402 // Couldn't open from dest, try from /
403 f.close(); 403 f.close();
404 404
405 packageFileDir = "/usr/lib/ipkg/info/"; 405 packageFileDir = "/usr/lib/ipkg/info/";
406 packageFileDir.append( packageFilename ); 406 packageFileDir.append( packageFilename );
407 packageFileDir.append( ".list" ); 407 packageFileDir.append( ".list" );
408 f.setName( packageFileDir ); 408 f.setName( packageFileDir );
409 if ( ! f.open(IO_ReadOnly) ) 409 if ( ! f.open(IO_ReadOnly) )
410 { 410 {
411 QString tempstr = tr("Could not open :"); 411 QString tempstr = tr("Could not open :");
412 tempstr.append( packageFileDir ); 412 tempstr.append( packageFileDir );
413 emit outputText( tempstr ); 413 emit outputText( tempstr );
414 return (QStringList*)0; 414 return (QStringList*)0;
415 } 415 }
416 } 416 }
417 QStringList *fileList = new QStringList(); 417 QStringList *fileList = new QStringList();
418 QTextStream t( &f ); 418 QTextStream t( &f );
419 while ( !t.eof() ) 419 while ( !t.eof() )
420 *fileList += t.readLine(); 420 *fileList += t.readLine();
421 421
422 f.close(); 422 f.close();
423 return fileList; 423 return fileList;
424} 424}
425 425
426void Ipkg :: processFileList( const QStringList *fileList, const QString &destDir ) 426void Ipkg :: processFileList( const QStringList *fileList, const QString &destDir )
427{ 427{
428 if ( !fileList || fileList->isEmpty() ) 428 if ( !fileList || fileList->isEmpty() )
429 return; 429 return;
430 430
431 QString baseDir = ROOT; 431 QString baseDir = ROOT;
432 432
433 if ( createLinks == true ) 433 if ( createLinks == true )
434 { 434 {
435 for ( uint i=0; i < fileList->count(); i++ ) 435 for ( uint i=0; i < fileList->count(); i++ )
436 { 436 {
437 processLinkDir( (*fileList)[i], baseDir, destDir ); 437 processLinkDir( (*fileList)[i], baseDir, destDir );
438 qApp->processEvents(); 438 qApp->processEvents();
439 } 439 }
440 } 440 }
441 else 441 else
442 { 442 {
443 for ( int i = fileList->count()-1; i >= 0 ; i-- ) 443 for ( int i = fileList->count()-1; i >= 0 ; i-- )
444 { 444 {
445 processLinkDir( (*fileList)[i], baseDir, destDir ); 445 processLinkDir( (*fileList)[i], baseDir, destDir );
446 qApp->processEvents(); 446 qApp->processEvents();
447 } 447 }
448 } 448 }
449} 449}
450 450
451void Ipkg :: processLinkDir( const QString &file, const QString &destDir, const QString &baseDir ) 451void Ipkg :: processLinkDir( const QString &file, const QString &destDir, const QString &baseDir )
452{ 452{
453 453
454 QString sourceFile = baseDir; 454 QString sourceFile = baseDir;
455 sourceFile.append( file ); 455 sourceFile.append( file );
456 456
457 QString linkFile = destDir; 457 QString linkFile = destDir;
458 if ( file.startsWith( "/" ) && destDir.right( 1 ) == "/" ) 458 if ( file.startsWith( "/" ) && destDir.right( 1 ) == "/" )
459 { 459 {
460 linkFile.append( file.mid( 1 ) ); 460 linkFile.append( file.mid( 1 ) );
461 } 461 }
462 else 462 else
463 { 463 {
464 linkFile.append( file ); 464 linkFile.append( file );
465 } 465 }
466 QString text; 466 QString text;
467 if ( createLinks ) 467 if ( createLinks )
468 { 468 {
469 // If this file is a directory (ends with a /) and it doesn't exist, 469 // If this file is a directory (ends with a /) and it doesn't exist,
470 // we need to create it 470 // we need to create it
471 if ( file.right(1) == "/" ) 471 if ( file.right(1) == "/" )
472 { 472 {
473 QFileInfo f( linkFile ); 473 QFileInfo f( linkFile );
474 if ( !f.exists() ) 474 if ( !f.exists() )
475 { 475 {
476 QString tempstr = tr("Creating directory "); 476 QString tempstr = tr("Creating directory ");
477 tempstr.append( linkFile ); 477 tempstr.append( linkFile );
478 emit outputText( tempstr ); 478 emit outputText( tempstr );
479 QDir d; 479 QDir d;
480 d.mkdir( linkFile, true ); 480 d.mkdir( linkFile, true );
481 } 481 }
482// else 482// else
483// emit outputText( QString( "Directory " ) + linkFile + " already exists" ); 483// emit outputText( QString( "Directory " ) + linkFile + " already exists" );
484 484
485 } 485 }
486 else 486 else
487 { 487 {
488 int rc = symlink( sourceFile, linkFile ); 488 int rc = symlink( sourceFile, linkFile );
489 text = ( rc == 0 ? tr( "Linked %1 to %2" ) : tr( "Failed to link %1 to %2" ) ). 489 text = ( rc == 0 ? tr( "Linked %1 to %2" ) : tr( "Failed to link %1 to %2" ) ).
490 arg( sourceFile ). 490 arg( sourceFile ).
491 arg( linkFile ); 491 arg( linkFile );
492 emit outputText( text ); 492 emit outputText( text );
493 } 493 }
494 } 494 }
495 else 495 else
496 { 496 {
497 QFileInfo f( linkFile ); 497 QFileInfo f( linkFile );
498 if ( f.exists() ) 498 if ( f.exists() )
499 { 499 {
500 if ( f.isFile() ) 500 if ( f.isFile() )
501 { 501 {
502 QFile f( linkFile ); 502 QFile f( linkFile );
503 bool rc = f.remove(); 503 bool rc = f.remove();
504 504
505 text = ( rc ? tr( "Removed %1" ) : tr( "Failed to remove %1" ) ).arg( linkFile ); 505 text = ( rc ? tr( "Removed %1" ) : tr( "Failed to remove %1" ) ).arg( linkFile );
506 emit outputText( text ); 506 emit outputText( text );
507 } 507 }
508 else if ( f.isDir() ) 508 else if ( f.isDir() )
509 { 509 {
510 QDir d; 510 QDir d;
511 bool rc = d.rmdir( linkFile, true ); 511 bool rc = d.rmdir( linkFile, true );
512 if ( rc ) 512 if ( rc )
513 { 513 {
514 text = ( rc ? tr( "Removed " ) : tr( "Failed to remove " ) ).arg( linkFile ); 514 text = ( rc ? tr( "Removed " ) : tr( "Failed to remove " ) ).arg( linkFile );
515 emit outputText( text ); 515 emit outputText( text );
516 } 516 }
517 } 517 }
518 } 518 }
519 } 519 }
520} 520}
diff --git a/noncore/settings/aqpkg/mainwin.cpp b/noncore/settings/aqpkg/mainwin.cpp
index 6f5c712..6b31cd1 100644
--- a/noncore/settings/aqpkg/mainwin.cpp
+++ b/noncore/settings/aqpkg/mainwin.cpp
@@ -1,1244 +1,1244 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk> 4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk>
5             .=l. Dan Williams <drw@handhelds.org> 5             .=l. Dan Williams <drw@handhelds.org>
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include "categoryfilterimpl.h" 30#include "categoryfilterimpl.h"
31#include "datamgr.h" 31#include "datamgr.h"
32#include "global.h" 32#include "global.h"
33#include "inputdlg.h" 33#include "inputdlg.h"
34#include "ipkg.h" 34#include "ipkg.h"
35#include "installdlgimpl.h" 35#include "installdlgimpl.h"
36#include "letterpushbutton.h" 36#include "letterpushbutton.h"
37#include "mainwin.h" 37#include "mainwin.h"
38#include "packagewin.h" 38#include "packagewin.h"
39#include "settingsimpl.h" 39#include "settingsimpl.h"
40#include "utils.h" 40#include "utils.h"
41 41
42/* OPIE */ 42/* OPIE */
43#include <qpe/qcopenvelope_qws.h> 43#include <qpe/qcopenvelope_qws.h>
44#include <qpe/qpeapplication.h> 44#include <qpe/qpeapplication.h>
45#include <qpe/config.h> 45#include <qpe/config.h>
46#include <qpe/resource.h> 46#include <qpe/resource.h>
47 47
48/* QT */ 48/* QT */
49#include <qmenubar.h> 49#include <qmenubar.h>
50#include <qtoolbar.h> 50#include <qtoolbar.h>
51#include <qaction.h> 51#include <qaction.h>
52#include <qcombobox.h> 52#include <qcombobox.h>
53#include <qfile.h> 53#include <qfile.h>
54#include <qlabel.h> 54#include <qlabel.h>
55#include <qlayout.h> 55#include <qlayout.h>
56#include <qlineedit.h> 56#include <qlineedit.h>
57#include <qlistview.h> 57#include <qlistview.h>
58#include <qmenubar.h> 58#include <qmenubar.h>
59#include <qmessagebox.h> 59#include <qmessagebox.h>
60#include <qpopupmenu.h> 60#include <qpopupmenu.h>
61#include <qprogressbar.h> 61#include <qprogressbar.h>
62#include <qtimer.h> 62#include <qtimer.h>
63#include <qwhatsthis.h> 63#include <qwhatsthis.h>
64#include <qwidgetstack.h> 64#include <qwidgetstack.h>
65 65
66/* STD */ 66/* STD */
67#include <linux/limits.h> 67#include <linux/limits.h>
68#include <unistd.h> 68#include <unistd.h>
69 69
70extern int compareVersions( const char *v1, const char *v2 ); 70extern int compareVersions( const char *v1, const char *v2 );
71 71
72MainWindow :: MainWindow( QWidget* parent, const char* name, WFlags fl ) 72MainWindow :: MainWindow( QWidget* parent, const char* name, WFlags fl )
73 :QMainWindow( parent, name, fl || WStyle_ContextHelp ) 73 :QMainWindow( parent, name, fl || WStyle_ContextHelp )
74{ 74{
75 // Disable suspend mode 75 // Disable suspend mode
76 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend; 76 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend;
77 77
78 LOCAL_SERVER = QObject::tr( "Installed packages" ); 78 LOCAL_SERVER = QObject::tr( "Installed packages" );
79 LOCAL_IPKGS = QObject::tr( "Local packages" ); 79 LOCAL_IPKGS = QObject::tr( "Local packages" );
80 80
81 setCaption( tr( "AQPkg - Package Manager" ) ); 81 setCaption( tr( "AQPkg - Package Manager" ) );
82 82
83 // Create UI widgets 83 // Create UI widgets
84 initMainWidget(); 84 initMainWidget();
85 initProgressWidget(); 85 initProgressWidget();
86 86
87 // Build menu and tool bars 87 // Build menu and tool bars
88 setToolBarsMovable( FALSE ); 88 setToolBarsMovable( FALSE );
89 89
90 QToolBar *bar = new QToolBar( this ); 90 QToolBar *bar = new QToolBar( this );
91 bar->setHorizontalStretchable( TRUE ); 91 bar->setHorizontalStretchable( TRUE );
92 QMenuBar *mb = new QMenuBar( bar ); 92 QMenuBar *mb = new QMenuBar( bar );
93 mb->setMargin( 0 ); 93 mb->setMargin( 0 );
94 bar = new QToolBar( this ); 94 bar = new QToolBar( this );
95 95
96 // Find toolbar 96 // Find toolbar
97 findBar = new QToolBar( this ); 97 findBar = new QToolBar( this );
98 addToolBar( findBar, QMainWindow::Top, true ); 98 addToolBar( findBar, QMainWindow::Top, true );
99 findBar->setHorizontalStretchable( true ); 99 findBar->setHorizontalStretchable( true );
100 findEdit = new QLineEdit( findBar ); 100 findEdit = new QLineEdit( findBar );
101 QWhatsThis::add( findEdit, tr( "Type the text to search for here." ) ); 101 QWhatsThis::add( findEdit, tr( "Type the text to search for here." ) );
102 findBar->setStretchableWidget( findEdit ); 102 findBar->setStretchableWidget( findEdit );
103 connect( findEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( findPackage( const QString & ) ) ); 103 connect( findEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( findPackage(const QString&) ) );
104 104
105 // Quick jump toolbar 105 // Quick jump toolbar
106 jumpBar = new QToolBar( this ); 106 jumpBar = new QToolBar( this );
107 addToolBar( jumpBar, QMainWindow::Top, true ); 107 addToolBar( jumpBar, QMainWindow::Top, true );
108 jumpBar->setHorizontalStretchable( true ); 108 jumpBar->setHorizontalStretchable( true );
109 QWidget *w = new QWidget( jumpBar ); 109 QWidget *w = new QWidget( jumpBar );
110 jumpBar->setStretchableWidget( w ); 110 jumpBar->setStretchableWidget( w );
111 111
112 QGridLayout *layout = new QGridLayout( w ); 112 QGridLayout *layout = new QGridLayout( w );
113 113
114 char text[2]; 114 char text[2];
115 text[1] = '\0'; 115 text[1] = '\0';
116 for ( int i = 0 ; i < 26 ; ++i ) 116 for ( int i = 0 ; i < 26 ; ++i )
117 { 117 {
118 text[0] = 'A' + i; 118 text[0] = 'A' + i;
119 LetterPushButton *b = new LetterPushButton( text, w ); 119 LetterPushButton *b = new LetterPushButton( text, w );
120 connect( b, SIGNAL( released( QString ) ), this, SLOT( letterPushed( QString ) ) ); 120 connect( b, SIGNAL( released(QString) ), this, SLOT( letterPushed(QString) ) );
121 layout->addWidget( b, i / 13, i % 13); 121 layout->addWidget( b, i / 13, i % 13);
122 } 122 }
123 123
124 QAction *a = new QAction( QString::null, Resource::loadPixmap( "close" ), QString::null, 0, w, 0 ); 124 QAction *a = new QAction( QString::null, Resource::loadPixmap( "close" ), QString::null, 0, w, 0 );
125 a->setWhatsThis( tr( "Click here to hide the Quick Jump toolbar." ) ); 125 a->setWhatsThis( tr( "Click here to hide the Quick Jump toolbar." ) );
126 connect( a, SIGNAL( activated() ), this, SLOT( hideJumpBar() ) ); 126 connect( a, SIGNAL( activated() ), this, SLOT( hideJumpBar() ) );
127 a->addTo( jumpBar ); 127 a->addTo( jumpBar );
128 jumpBar->hide(); 128 jumpBar->hide();
129 129
130 // Packages menu 130 // Packages menu
131 QPopupMenu *popup = new QPopupMenu( this ); 131 QPopupMenu *popup = new QPopupMenu( this );
132 132
133 a = new QAction( tr( "Update lists" ), Resource::loadPixmap( "aqpkg/update" ), QString::null, 0, this, 0 ); 133 a = new QAction( tr( "Update lists" ), Resource::loadPixmap( "aqpkg/update" ), QString::null, 0, this, 0 );
134 a->setWhatsThis( tr( "Click here to update package lists from servers." ) ); 134 a->setWhatsThis( tr( "Click here to update package lists from servers." ) );
135 connect( a, SIGNAL( activated() ), this, SLOT( updateServer() ) ); 135 connect( a, SIGNAL( activated() ), this, SLOT( updateServer() ) );
136 a->addTo( popup ); 136 a->addTo( popup );
137 a->addTo( bar ); 137 a->addTo( bar );
138 138
139 actionUpgrade = new QAction( tr( "Upgrade" ), Resource::loadPixmap( "aqpkg/upgrade" ), QString::null, 0, this, 0 ); 139 actionUpgrade = new QAction( tr( "Upgrade" ), Resource::loadPixmap( "aqpkg/upgrade" ), QString::null, 0, this, 0 );
140 actionUpgrade->setWhatsThis( tr( "Click here to upgrade all installed packages if a newer version is available." ) ); 140 actionUpgrade->setWhatsThis( tr( "Click here to upgrade all installed packages if a newer version is available." ) );
141 connect( actionUpgrade, SIGNAL( activated() ), this, SLOT( upgradePackages() ) ); 141 connect( actionUpgrade, SIGNAL( activated() ), this, SLOT( upgradePackages() ) );
142 actionUpgrade->addTo( popup ); 142 actionUpgrade->addTo( popup );
143 actionUpgrade->addTo( bar ); 143 actionUpgrade->addTo( bar );
144 144
145 iconDownload = Resource::loadPixmap( "aqpkg/download" ); 145 iconDownload = Resource::loadPixmap( "aqpkg/download" );
146 iconRemove = Resource::loadPixmap( "aqpkg/remove" ); 146 iconRemove = Resource::loadPixmap( "aqpkg/remove" );
147 actionDownload = new QAction( tr( "Download" ), iconDownload, QString::null, 0, this, 0 ); 147 actionDownload = new QAction( tr( "Download" ), iconDownload, QString::null, 0, this, 0 );
148 actionDownload->setWhatsThis( tr( "Click here to download the currently selected package(s)." ) ); 148 actionDownload->setWhatsThis( tr( "Click here to download the currently selected package(s)." ) );
149 connect( actionDownload, SIGNAL( activated() ), this, SLOT( downloadPackage() ) ); 149 connect( actionDownload, SIGNAL( activated() ), this, SLOT( downloadPackage() ) );
150 actionDownload->addTo( popup ); 150 actionDownload->addTo( popup );
151 actionDownload->addTo( bar ); 151 actionDownload->addTo( bar );
152 152
153 a = new QAction( tr( "Apply changes" ), Resource::loadPixmap( "aqpkg/apply" ), QString::null, 0, this, 0 ); 153 a = new QAction( tr( "Apply changes" ), Resource::loadPixmap( "aqpkg/apply" ), QString::null, 0, this, 0 );
154 a->setWhatsThis( tr( "Click here to install, remove or upgrade currently selected package(s)." ) ); 154 a->setWhatsThis( tr( "Click here to install, remove or upgrade currently selected package(s)." ) );
155 connect( a, SIGNAL( activated() ), this, SLOT( applyChanges() ) ); 155 connect( a, SIGNAL( activated() ), this, SLOT( applyChanges() ) );
156 a->addTo( popup ); 156 a->addTo( popup );
157 a->addTo( bar ); 157 a->addTo( bar );
158 158
159 popup->insertSeparator(); 159 popup->insertSeparator();
160 160
161 a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); 161 a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 );
162 a->setWhatsThis( tr( "Click here to configure this application." ) ); 162 a->setWhatsThis( tr( "Click here to configure this application." ) );
163 connect( a, SIGNAL( activated() ), this, SLOT( displaySettings() ) ); 163 connect( a, SIGNAL( activated() ), this, SLOT( displaySettings() ) );
164 a->addTo( popup ); 164 a->addTo( popup );
165 mb->insertItem( tr( "Actions" ), popup ); 165 mb->insertItem( tr( "Actions" ), popup );
166 166
167 // View menu 167 // View menu
168 popup = new QPopupMenu( this ); 168 popup = new QPopupMenu( this );
169 169
170 actionUninstalled = new QAction( tr( "Show packages not installed" ), QString::null, 0, this, 0 ); 170 actionUninstalled = new QAction( tr( "Show packages not installed" ), QString::null, 0, this, 0 );
171 actionUninstalled->setToggleAction( TRUE ); 171 actionUninstalled->setToggleAction( TRUE );
172 actionUninstalled->setWhatsThis( tr( "Click here to show packages available which have not been installed." ) ); 172 actionUninstalled->setWhatsThis( tr( "Click here to show packages available which have not been installed." ) );
173 connect( actionUninstalled, SIGNAL( activated() ), this, SLOT( filterUninstalledPackages() ) ); 173 connect( actionUninstalled, SIGNAL( activated() ), this, SLOT( filterUninstalledPackages() ) );
174 actionUninstalled->addTo( popup ); 174 actionUninstalled->addTo( popup );
175 175
176 actionInstalled = new QAction( tr( "Show installed packages" ), QString::null, 0, this, 0 ); 176 actionInstalled = new QAction( tr( "Show installed packages" ), QString::null, 0, this, 0 );
177 actionInstalled->setToggleAction( TRUE ); 177 actionInstalled->setToggleAction( TRUE );
178 actionInstalled->setWhatsThis( tr( "Click here to show packages currently installed on this device." ) ); 178 actionInstalled->setWhatsThis( tr( "Click here to show packages currently installed on this device." ) );
179 connect( actionInstalled, SIGNAL( activated() ), this, SLOT( filterInstalledPackages() ) ); 179 connect( actionInstalled, SIGNAL( activated() ), this, SLOT( filterInstalledPackages() ) );
180 actionInstalled->addTo( popup ); 180 actionInstalled->addTo( popup );
181 181
182 actionUpdated = new QAction( tr( "Show updated packages" ), QString::null, 0, this, 0 ); 182 actionUpdated = new QAction( tr( "Show updated packages" ), QString::null, 0, this, 0 );
183 actionUpdated->setToggleAction( TRUE ); 183 actionUpdated->setToggleAction( TRUE );
184 actionUpdated->setWhatsThis( tr( "Click here to show packages currently installed on this device which have a newer version available." ) ); 184 actionUpdated->setWhatsThis( tr( "Click here to show packages currently installed on this device which have a newer version available." ) );
185 connect( actionUpdated, SIGNAL( activated() ), this, SLOT( filterUpgradedPackages() ) ); 185 connect( actionUpdated, SIGNAL( activated() ), this, SLOT( filterUpgradedPackages() ) );
186 actionUpdated->addTo( popup ); 186 actionUpdated->addTo( popup );
187 187
188 popup->insertSeparator(); 188 popup->insertSeparator();
189 189
190 actionFilter = new QAction( tr( "Filter by category" ), Resource::loadPixmap( "aqpkg/filter" ), QString::null, 0, this, 0 ); 190 actionFilter = new QAction( tr( "Filter by category" ), Resource::loadPixmap( "aqpkg/filter" ), QString::null, 0, this, 0 );
191 actionFilter->setToggleAction( TRUE ); 191 actionFilter->setToggleAction( TRUE );
192 actionFilter->setWhatsThis( tr( "Click here to list packages belonging to one category." ) ); 192 actionFilter->setWhatsThis( tr( "Click here to list packages belonging to one category." ) );
193 connect( actionFilter, SIGNAL( activated() ), this, SLOT( filterCategory() ) ); 193 connect( actionFilter, SIGNAL( activated() ), this, SLOT( filterCategory() ) );
194 actionFilter->addTo( popup ); 194 actionFilter->addTo( popup );
195 195
196 a = new QAction( tr( "Set filter category" ), QString::null, 0, this, 0 ); 196 a = new QAction( tr( "Set filter category" ), QString::null, 0, this, 0 );
197 a->setWhatsThis( tr( "Click here to change package category to used filter." ) ); 197 a->setWhatsThis( tr( "Click here to change package category to used filter." ) );
198 connect( a, SIGNAL( activated() ), this, SLOT( setFilterCategory() ) ); 198 connect( a, SIGNAL( activated() ), this, SLOT( setFilterCategory() ) );
199 a->addTo( popup ); 199 a->addTo( popup );
200 200
201 popup->insertSeparator(); 201 popup->insertSeparator();
202 202
203 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); 203 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 );
204 a->setWhatsThis( tr( "Click here to search for text in package names." ) ); 204 a->setWhatsThis( tr( "Click here to search for text in package names." ) );
205 connect( a, SIGNAL( activated() ), this, SLOT( displayFindBar() ) ); 205 connect( a, SIGNAL( activated() ), this, SLOT( displayFindBar() ) );
206 a->addTo( popup ); 206 a->addTo( popup );
207 207
208 actionFindNext = new QAction( tr( "Find next" ), Resource::loadIconSet( "next" ), QString::null, 0, this, 0 ); 208 actionFindNext = new QAction( tr( "Find next" ), Resource::loadIconSet( "next" ), QString::null, 0, this, 0 );
209 actionFindNext->setEnabled( FALSE ); 209 actionFindNext->setEnabled( FALSE );
210 actionFindNext->setWhatsThis( tr( "Click here to find the next package name containing the text you are searching for." ) ); 210 actionFindNext->setWhatsThis( tr( "Click here to find the next package name containing the text you are searching for." ) );
211 connect( actionFindNext, SIGNAL( activated() ), this, SLOT( repeatFind() ) ); 211 connect( actionFindNext, SIGNAL( activated() ), this, SLOT( repeatFind() ) );
212 actionFindNext->addTo( popup ); 212 actionFindNext->addTo( popup );
213 actionFindNext->addTo( findBar ); 213 actionFindNext->addTo( findBar );
214 214
215 215
216 popup->insertSeparator(); 216 popup->insertSeparator();
217 217
218 a = new QAction( tr( "Quick Jump keypad" ), Resource::loadPixmap( "aqpkg/keyboard" ), QString::null, 0, this, 0 ); 218 a = new QAction( tr( "Quick Jump keypad" ), Resource::loadPixmap( "aqpkg/keyboard" ), QString::null, 0, this, 0 );
219 a->setWhatsThis( tr( "Click here to display/hide keypad to allow quick movement through the package list." ) ); 219 a->setWhatsThis( tr( "Click here to display/hide keypad to allow quick movement through the package list." ) );
220 connect( a, SIGNAL( activated() ), this, SLOT( displayJumpBar() ) ); 220 connect( a, SIGNAL( activated() ), this, SLOT( displayJumpBar() ) );
221 a->addTo( popup ); 221 a->addTo( popup );
222 222
223 mb->insertItem( tr( "View" ), popup ); 223 mb->insertItem( tr( "View" ), popup );
224 224
225 // Finish find toolbar creation 225 // Finish find toolbar creation
226 a = new QAction( QString::null, Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); 226 a = new QAction( QString::null, Resource::loadPixmap( "close" ), QString::null, 0, this, 0 );
227 a->setWhatsThis( tr( "Click here to hide the find toolbar." ) ); 227 a->setWhatsThis( tr( "Click here to hide the find toolbar." ) );
228 connect( a, SIGNAL( activated() ), this, SLOT( hideFindBar() ) ); 228 connect( a, SIGNAL( activated() ), this, SLOT( hideFindBar() ) );
229 a->addTo( findBar ); 229 a->addTo( findBar );
230 findBar->hide(); 230 findBar->hide();
231 231
232 // Create widget stack and add UI widgets 232 // Create widget stack and add UI widgets
233 stack = new QWidgetStack( this ); 233 stack = new QWidgetStack( this );
234 stack->addWidget( progressWindow, 2 ); 234 stack->addWidget( progressWindow, 2 );
235 stack->addWidget( networkPkgWindow, 1 ); 235 stack->addWidget( networkPkgWindow, 1 );
236 setCentralWidget( stack ); 236 setCentralWidget( stack );
237 stack->raiseWidget( progressWindow ); 237 stack->raiseWidget( progressWindow );
238 238
239 // Delayed call to finish initialization 239 // Delayed call to finish initialization
240 QTimer::singleShot( 100, this, SLOT( init() ) ); 240 QTimer::singleShot( 100, this, SLOT( init() ) );
241} 241}
242 242
243MainWindow :: ~MainWindow() 243MainWindow :: ~MainWindow()
244{ 244{
245 delete mgr; 245 delete mgr;
246 246
247 // Reenable suspend mode 247 // Reenable suspend mode
248 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 248 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
249} 249}
250 250
251void MainWindow :: initMainWidget() 251void MainWindow :: initMainWidget()
252{ 252{
253 networkPkgWindow = new QWidget( this ); 253 networkPkgWindow = new QWidget( this );
254 254
255 QLabel *l = new QLabel( tr( "Servers:" ), networkPkgWindow ); 255 QLabel *l = new QLabel( tr( "Servers:" ), networkPkgWindow );
256 256
257 serversList = new QComboBox( networkPkgWindow ); 257 serversList = new QComboBox( networkPkgWindow );
258 connect( serversList, SIGNAL(activated(int)), this, SLOT(serverSelected(int)) ); 258 connect( serversList, SIGNAL(activated(int)), this, SLOT(serverSelected(int)) );
259 QWhatsThis::add( serversList, tr( "Click here to select a package feed." ) ); 259 QWhatsThis::add( serversList, tr( "Click here to select a package feed." ) );
260 260
261 installedIcon = Resource::loadPixmap( "installed" ); 261 installedIcon = Resource::loadPixmap( "installed" );
262 updatedIcon = Resource::loadPixmap( "aqpkg/updated" ); 262 updatedIcon = Resource::loadPixmap( "aqpkg/updated" );
263 263
264 packagesList = new QListView( networkPkgWindow ); 264 packagesList = new QListView( networkPkgWindow );
265 packagesList->addColumn( tr( "Packages" ), 225 ); 265 packagesList->addColumn( tr( "Packages" ), 225 );
266 QWhatsThis::add( packagesList, tr( "This is a listing of all packages for the server feed selected above.\n\nA blue dot next to the package name indicates that the package is currently installed.\n\nA blue dot with a star indicates that a newer version of the package is available from the server feed.\n\nClick inside the box at the left to select a package." ) ); 266 QWhatsThis::add( packagesList, tr( "This is a listing of all packages for the server feed selected above.\n\nA blue dot next to the package name indicates that the package is currently installed.\n\nA blue dot with a star indicates that a newer version of the package is available from the server feed.\n\nClick inside the box at the left to select a package." ) );
267 QPEApplication::setStylusOperation( packagesList->viewport(), QPEApplication::RightOnHold ); 267 QPEApplication::setStylusOperation( packagesList->viewport(), QPEApplication::RightOnHold );
268 connect( packagesList, SIGNAL(rightButtonPressed(QListViewItem *,const QPoint &,int)), 268 connect( packagesList, SIGNAL(rightButtonPressed(QListViewItem*,const QPoint&,int)),
269 this, SLOT(slotDisplayPackage(QListViewItem *)) ); 269 this, SLOT(slotDisplayPackage(QListViewItem*)) );
270 270
271 QVBoxLayout *vbox = new QVBoxLayout( networkPkgWindow, 0, -1 ); 271 QVBoxLayout *vbox = new QVBoxLayout( networkPkgWindow, 0, -1 );
272 QHBoxLayout *hbox1 = new QHBoxLayout( vbox, -1 ); 272 QHBoxLayout *hbox1 = new QHBoxLayout( vbox, -1 );
273 hbox1->addWidget( l ); 273 hbox1->addWidget( l );
274 hbox1->addWidget( serversList ); 274 hbox1->addWidget( serversList );
275 275
276 vbox->addWidget( packagesList ); 276 vbox->addWidget( packagesList );
277 277
278 downloadEnabled = TRUE; 278 downloadEnabled = TRUE;
279} 279}
280 280
281void MainWindow :: initProgressWidget() 281void MainWindow :: initProgressWidget()
282{ 282{
283 progressWindow = new QWidget( this ); 283 progressWindow = new QWidget( this );
284 284
285 QVBoxLayout *layout = new QVBoxLayout( progressWindow, 4, 4 ); 285 QVBoxLayout *layout = new QVBoxLayout( progressWindow, 4, 4 );
286 286
287 m_status = new QLabel( progressWindow ); 287 m_status = new QLabel( progressWindow );
288 m_status->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) ); 288 m_status->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
289 layout->addWidget( m_status ); 289 layout->addWidget( m_status );
290 290
291 m_progress = new QProgressBar( progressWindow ); 291 m_progress = new QProgressBar( progressWindow );
292 layout->addWidget( m_progress ); 292 layout->addWidget( m_progress );
293} 293}
294 294
295void MainWindow :: init() 295void MainWindow :: init()
296{ 296{
297#ifdef QWS 297#ifdef QWS
298 // read download directory from config file 298 // read download directory from config file
299 Config cfg( "aqpkg" ); 299 Config cfg( "aqpkg" );
300 cfg.setGroup( "settings" ); 300 cfg.setGroup( "settings" );
301 currentlySelectedServer = cfg.readEntry( "selectedServer", "local" ); 301 currentlySelectedServer = cfg.readEntry( "selectedServer", "local" );
302 // showJumpTo = cfg.readBoolEntry( "showJumpTo", "true" ); 302 // showJumpTo = cfg.readBoolEntry( "showJumpTo", "true" );
303 303
304#endif 304#endif
305 305
306 stack->raiseWidget( progressWindow ); 306 stack->raiseWidget( progressWindow );
307 307
308 mgr = new DataManager(); 308 mgr = new DataManager();
309 connect( mgr, SIGNAL( progressSetSteps( int ) ), this, SLOT( setProgressSteps( int ) ) ); 309 connect( mgr, SIGNAL( progressSetSteps(int) ), this, SLOT( setProgressSteps(int) ) );
310 connect( mgr, SIGNAL( progressSetMessage( const QString & ) ), 310 connect( mgr, SIGNAL( progressSetMessage(const QString&) ),
311 this, SLOT( setProgressMessage( const QString & ) ) ); 311 this, SLOT( setProgressMessage(const QString&) ) );
312 connect( mgr, SIGNAL( progressUpdate( int ) ), this, SLOT( updateProgress( int ) ) ); 312 connect( mgr, SIGNAL( progressUpdate(int) ), this, SLOT( updateProgress(int) ) );
313 mgr->loadServers(); 313 mgr->loadServers();
314 314
315 showUninstalledPkgs = false; 315 showUninstalledPkgs = false;
316 showInstalledPkgs = false; 316 showInstalledPkgs = false;
317 showUpgradedPkgs = false; 317 showUpgradedPkgs = false;
318 categoryFilterEnabled = false; 318 categoryFilterEnabled = false;
319 319
320 updateData(); 320 updateData();
321 321
322 stack->raiseWidget( networkPkgWindow ); 322 stack->raiseWidget( networkPkgWindow );
323} 323}
324 324
325void MainWindow :: setDocument( const QString &doc ) 325void MainWindow :: setDocument( const QString &doc )
326{ 326{
327 // Remove path from package 327 // Remove path from package
328 QString package = Utils::getPackageNameFromIpkFilename( doc ); 328 QString package = Utils::getPackageNameFromIpkFilename( doc );
329 329
330 // First select local server 330 // First select local server
331 for ( int i = 0 ; i < serversList->count() ; ++i ) 331 for ( int i = 0 ; i < serversList->count() ; ++i )
332 { 332 {
333 if ( serversList->text( i ) == LOCAL_IPKGS ) 333 if ( serversList->text( i ) == LOCAL_IPKGS )
334 { 334 {
335 serversList->setCurrentItem( i ); 335 serversList->setCurrentItem( i );
336 break; 336 break;
337 } 337 }
338 } 338 }
339 serverSelected( 0 ); 339 serverSelected( 0 );
340 340
341 // Now set the check box of the selected package 341 // Now set the check box of the selected package
342 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild(); 342 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild();
343 item != 0 ; 343 item != 0 ;
344 item = (QCheckListItem *)item->nextSibling() ) 344 item = (QCheckListItem *)item->nextSibling() )
345 { 345 {
346 if ( item->text().startsWith( package ) ) 346 if ( item->text().startsWith( package ) )
347 { 347 {
348 item->setOn( true ); 348 item->setOn( true );
349 break; 349 break;
350 } 350 }
351 } 351 }
352} 352}
353 353
354void MainWindow :: displaySettings() 354void MainWindow :: displaySettings()
355{ 355{
356 SettingsImpl *dlg = new SettingsImpl( mgr, this, "Settings", true ); 356 SettingsImpl *dlg = new SettingsImpl( mgr, this, "Settings", true );
357 if ( dlg->showDlg() ) 357 if ( dlg->showDlg() )
358 { 358 {
359 stack->raiseWidget( progressWindow ); 359 stack->raiseWidget( progressWindow );
360 updateData(); 360 updateData();
361 stack->raiseWidget( networkPkgWindow ); 361 stack->raiseWidget( networkPkgWindow );
362 } 362 }
363 delete dlg; 363 delete dlg;
364} 364}
365 365
366void MainWindow :: closeEvent( QCloseEvent *e ) 366void MainWindow :: closeEvent( QCloseEvent *e )
367{ 367{
368 // If install dialog is visible, return to main view, otherwise close app 368 // If install dialog is visible, return to main view, otherwise close app
369 QWidget *widget = stack->visibleWidget(); 369 QWidget *widget = stack->visibleWidget();
370 370
371 if ( widget != networkPkgWindow && widget != progressWindow ) 371 if ( widget != networkPkgWindow && widget != progressWindow )
372 { 372 {
373 if ( widget ) delete widget; 373 if ( widget ) delete widget;
374 stack->raiseWidget( networkPkgWindow ); 374 stack->raiseWidget( networkPkgWindow );
375 e->ignore(); 375 e->ignore();
376 } 376 }
377 else 377 else
378 { 378 {
379 e->accept(); 379 e->accept();
380 } 380 }
381} 381}
382 382
383void MainWindow :: displayFindBar() 383void MainWindow :: displayFindBar()
384{ 384{
385 findBar->show(); 385 findBar->show();
386 findEdit->setFocus(); 386 findEdit->setFocus();
387} 387}
388 388
389void MainWindow :: displayJumpBar() 389void MainWindow :: displayJumpBar()
390{ 390{
391 jumpBar->show(); 391 jumpBar->show();
392} 392}
393 393
394void MainWindow :: repeatFind() 394void MainWindow :: repeatFind()
395{ 395{
396 searchForPackage( findEdit->text() ); 396 searchForPackage( findEdit->text() );
397} 397}
398 398
399void MainWindow :: findPackage( const QString &text ) 399void MainWindow :: findPackage( const QString &text )
400{ 400{
401 actionFindNext->setEnabled( !text.isEmpty() ); 401 actionFindNext->setEnabled( !text.isEmpty() );
402 searchForPackage( text ); 402 searchForPackage( text );
403} 403}
404 404
405void MainWindow :: hideFindBar() 405void MainWindow :: hideFindBar()
406{ 406{
407 findBar->hide(); 407 findBar->hide();
408} 408}
409 409
410void MainWindow :: hideJumpBar() 410void MainWindow :: hideJumpBar()
411{ 411{
412 jumpBar->hide(); 412 jumpBar->hide();
413} 413}
414 414
415void MainWindow :: filterUninstalledPackages() 415void MainWindow :: filterUninstalledPackages()
416{ 416{
417 showUninstalledPkgs = actionUninstalled->isOn(); 417 showUninstalledPkgs = actionUninstalled->isOn();
418 if ( showUninstalledPkgs ) 418 if ( showUninstalledPkgs )
419 { 419 {
420 showInstalledPkgs = FALSE; 420 showInstalledPkgs = FALSE;
421 showUpgradedPkgs = FALSE; 421 showUpgradedPkgs = FALSE;
422 } 422 }
423 serverSelected( -1 ); 423 serverSelected( -1 );
424 424
425 actionInstalled->setOn( FALSE ); 425 actionInstalled->setOn( FALSE );
426 actionUpdated->setOn( FALSE ); 426 actionUpdated->setOn( FALSE );
427} 427}
428 428
429void MainWindow :: filterInstalledPackages() 429void MainWindow :: filterInstalledPackages()
430{ 430{
431 showInstalledPkgs = actionInstalled->isOn(); 431 showInstalledPkgs = actionInstalled->isOn();
432 if ( showInstalledPkgs ) 432 if ( showInstalledPkgs )
433 { 433 {
434 showUninstalledPkgs = FALSE; 434 showUninstalledPkgs = FALSE;
435 showUpgradedPkgs = FALSE; 435 showUpgradedPkgs = FALSE;
436 } 436 }
437 serverSelected( -1 ); 437 serverSelected( -1 );
438 438
439 actionUninstalled->setOn( FALSE ); 439 actionUninstalled->setOn( FALSE );
440 actionUpdated->setOn( FALSE ); 440 actionUpdated->setOn( FALSE );
441} 441}
442 442
443void MainWindow :: filterUpgradedPackages() 443void MainWindow :: filterUpgradedPackages()
444{ 444{
445 showUpgradedPkgs = actionUpdated->isOn(); 445 showUpgradedPkgs = actionUpdated->isOn();
446 if ( showUpgradedPkgs ) 446 if ( showUpgradedPkgs )
447 { 447 {
448 showUninstalledPkgs = FALSE; 448 showUninstalledPkgs = FALSE;
449 showInstalledPkgs = FALSE; 449 showInstalledPkgs = FALSE;
450 } 450 }
451 serverSelected( -1 ); 451 serverSelected( -1 );
452 452
453 actionUninstalled->setOn( FALSE ); 453 actionUninstalled->setOn( FALSE );
454 actionInstalled->setOn( FALSE ); 454 actionInstalled->setOn( FALSE );
455} 455}
456 456
457bool MainWindow :: setFilterCategory() 457bool MainWindow :: setFilterCategory()
458{ 458{
459 // Get categories; 459 // Get categories;
460 CategoryFilterImpl dlg( DataManager::getAvailableCategories(), categoryFilter, this ); 460 CategoryFilterImpl dlg( DataManager::getAvailableCategories(), categoryFilter, this );
461 if ( dlg.exec() == QDialog::Accepted ) 461 if ( dlg.exec() == QDialog::Accepted )
462 { 462 {
463 categoryFilter = dlg.getSelectedFilter(); 463 categoryFilter = dlg.getSelectedFilter();
464 464
465 if ( categoryFilter == "" ) 465 if ( categoryFilter == "" )
466 return false; 466 return false;
467 467
468 categoryFilterEnabled = true; 468 categoryFilterEnabled = true;
469 serverSelected( -1 ); 469 serverSelected( -1 );
470 actionFilter->setOn( TRUE ); 470 actionFilter->setOn( TRUE );
471 return true; 471 return true;
472 } 472 }
473 473
474 return false; 474 return false;
475} 475}
476 476
477void MainWindow :: filterCategory() 477void MainWindow :: filterCategory()
478{ 478{
479 if ( !actionFilter->isOn() ) 479 if ( !actionFilter->isOn() )
480 { 480 {
481 filterByCategory( FALSE ); 481 filterByCategory( FALSE );
482 } 482 }
483 else 483 else
484 { 484 {
485 actionFilter->setOn( filterByCategory( TRUE ) ); 485 actionFilter->setOn( filterByCategory( TRUE ) );
486 } 486 }
487} 487}
488 488
489bool MainWindow :: filterByCategory( bool val ) 489bool MainWindow :: filterByCategory( bool val )
490{ 490{
491 if ( val ) 491 if ( val )
492 { 492 {
493 if ( categoryFilter == "" ) 493 if ( categoryFilter == "" )
494 { 494 {
495 if ( !setFilterCategory() ) 495 if ( !setFilterCategory() )
496 return false; 496 return false;
497 } 497 }
498 498
499 categoryFilterEnabled = true; 499 categoryFilterEnabled = true;
500 serverSelected( -1 ); 500 serverSelected( -1 );
501 return true; 501 return true;
502 } 502 }
503 else 503 else
504 { 504 {
505 // Turn off filter 505 // Turn off filter
506 categoryFilterEnabled = false; 506 categoryFilterEnabled = false;
507 serverSelected( -1 ); 507 serverSelected( -1 );
508 return false; 508 return false;
509 } 509 }
510} 510}
511 511
512void MainWindow :: raiseMainWidget() 512void MainWindow :: raiseMainWidget()
513{ 513{
514 stack->raiseWidget( networkPkgWindow ); 514 stack->raiseWidget( networkPkgWindow );
515} 515}
516 516
517void MainWindow :: raiseProgressWidget() 517void MainWindow :: raiseProgressWidget()
518{ 518{
519 stack->raiseWidget( progressWindow ); 519 stack->raiseWidget( progressWindow );
520} 520}
521 521
522void MainWindow :: enableUpgrade( bool enabled ) 522void MainWindow :: enableUpgrade( bool enabled )
523{ 523{
524 actionUpgrade->setEnabled( enabled ); 524 actionUpgrade->setEnabled( enabled );
525} 525}
526 526
527void MainWindow :: enableDownload( bool enabled ) 527void MainWindow :: enableDownload( bool enabled )
528{ 528{
529 if ( enabled ) 529 if ( enabled )
530 { 530 {
531 actionDownload->setIconSet( iconDownload ); 531 actionDownload->setIconSet( iconDownload );
532 actionDownload->setText( tr( "Download" ) ); 532 actionDownload->setText( tr( "Download" ) );
533 actionDownload->setWhatsThis( tr( "Click here to download the currently selected package(s)." ) ); 533 actionDownload->setWhatsThis( tr( "Click here to download the currently selected package(s)." ) );
534 } 534 }
535 else 535 else
536 { 536 {
537 actionDownload->setIconSet( iconRemove ); 537 actionDownload->setIconSet( iconRemove );
538 actionDownload->setText( tr( "Remove" ) ); 538 actionDownload->setText( tr( "Remove" ) );
539 actionDownload->setWhatsThis( tr( "Click here to uninstall the currently selected package(s)." ) ); 539 actionDownload->setWhatsThis( tr( "Click here to uninstall the currently selected package(s)." ) );
540 } 540 }
541} 541}
542 542
543void MainWindow :: setProgressSteps( int numsteps ) 543void MainWindow :: setProgressSteps( int numsteps )
544{ 544{
545 m_progress->setTotalSteps( numsteps ); 545 m_progress->setTotalSteps( numsteps );
546} 546}
547 547
548void MainWindow :: setProgressMessage( const QString &msg ) 548void MainWindow :: setProgressMessage( const QString &msg )
549{ 549{
550 m_status->setText( msg ); 550 m_status->setText( msg );
551} 551}
552 552
553void MainWindow :: updateProgress( int progress ) 553void MainWindow :: updateProgress( int progress )
554{ 554{
555 m_progress->setProgress( progress ); 555 m_progress->setProgress( progress );
556} 556}
557 557
558void MainWindow :: updateData() 558void MainWindow :: updateData()
559{ 559{
560 m_progress->setTotalSteps( mgr->getServerList().count() ); 560 m_progress->setTotalSteps( mgr->getServerList().count() );
561 561
562 serversList->clear(); 562 serversList->clear();
563 packagesList->clear(); 563 packagesList->clear();
564 564
565 int activeItem = -1; 565 int activeItem = -1;
566 int i = 0; 566 int i = 0;
567 QString serverName; 567 QString serverName;
568 568
569 QListIterator<Server> it( mgr->getServerList() ); 569 QListIterator<Server> it( mgr->getServerList() );
570 Server *server; 570 Server *server;
571 571
572 for ( ; it.current(); ++it, ++i ) 572 for ( ; it.current(); ++it, ++i )
573 { 573 {
574 server = it.current(); 574 server = it.current();
575 serverName = server->getServerName(); 575 serverName = server->getServerName();
576 m_status->setText( tr( "Building server list:\n\t%1" ).arg( serverName ) ); 576 m_status->setText( tr( "Building server list:\n\t%1" ).arg( serverName ) );
577 m_progress->setProgress( i ); 577 m_progress->setProgress( i );
578 qApp->processEvents(); 578 qApp->processEvents();
579 579
580 if ( !server->isServerActive() ) 580 if ( !server->isServerActive() )
581 { 581 {
582 i--; 582 i--;
583 continue; 583 continue;
584 } 584 }
585 585
586 serversList->insertItem( serverName ); 586 serversList->insertItem( serverName );
587 if ( serverName == currentlySelectedServer ) 587 if ( serverName == currentlySelectedServer )
588 activeItem = i; 588 activeItem = i;
589 } 589 }
590 590
591 // set selected server to be active server 591 // set selected server to be active server
592 if ( activeItem != -1 ) 592 if ( activeItem != -1 )
593 serversList->setCurrentItem( activeItem ); 593 serversList->setCurrentItem( activeItem );
594 serverSelected( 0, FALSE ); 594 serverSelected( 0, FALSE );
595} 595}
596 596
597void MainWindow :: serverSelected( int index ) 597void MainWindow :: serverSelected( int index )
598{ 598{
599 serverSelected( index, TRUE ); 599 serverSelected( index, TRUE );
600} 600}
601 601
602void MainWindow :: serverSelected( int, bool raiseProgress ) 602void MainWindow :: serverSelected( int, bool raiseProgress )
603{ 603{
604 QPixmap nullIcon( installedIcon.size() ); 604 QPixmap nullIcon( installedIcon.size() );
605 nullIcon.fill( colorGroup().base() ); 605 nullIcon.fill( colorGroup().base() );
606 606
607 // display packages 607 // display packages
608 QString serverName = serversList->currentText(); 608 QString serverName = serversList->currentText();
609 currentlySelectedServer = serverName; 609 currentlySelectedServer = serverName;
610 610
611 Server *s = mgr->getServer( serverName ); 611 Server *s = mgr->getServer( serverName );
612 612
613 QList<Package> &list = s->getPackageList(); 613 QList<Package> &list = s->getPackageList();
614 QListIterator<Package> it( list ); 614 QListIterator<Package> it( list );
615 615
616 // Display progress widget while loading list 616 // Display progress widget while loading list
617 bool doProgress = ( list.count() > 200 ); 617 bool doProgress = ( list.count() > 200 );
618 if ( doProgress ) 618 if ( doProgress )
619 { 619 {
620 if ( raiseProgress ) 620 if ( raiseProgress )
621 { 621 {
622 stack->raiseWidget( progressWindow ); 622 stack->raiseWidget( progressWindow );
623 } 623 }
624 m_progress->setTotalSteps( list.count() ); 624 m_progress->setTotalSteps( list.count() );
625 m_status->setText( tr( "Building package list for:\n\t%1" ).arg( serverName ) ); 625 m_status->setText( tr( "Building package list for:\n\t%1" ).arg( serverName ) );
626 } 626 }
627 627
628 packagesList->clear(); 628 packagesList->clear();
629 629
630#ifdef QWS 630#ifdef QWS
631 // read download directory from config file 631 // read download directory from config file
632 Config cfg( "aqpkg" ); 632 Config cfg( "aqpkg" );
633 cfg.setGroup( "settings" ); 633 cfg.setGroup( "settings" );
634 cfg.writeEntry( "selectedServer", currentlySelectedServer ); 634 cfg.writeEntry( "selectedServer", currentlySelectedServer );
635#endif 635#endif
636 636
637 int i = 0; 637 int i = 0;
638 Package *package; 638 Package *package;
639 for ( ; it.current(); ++it ) 639 for ( ; it.current(); ++it )
640 { 640 {
641 // Update progress after every 100th package (arbitrary value, seems to give good balance) 641 // Update progress after every 100th package (arbitrary value, seems to give good balance)
642 i++; 642 i++;
643 if ( ( i % 100 ) == 0 ) 643 if ( ( i % 100 ) == 0 )
644 { 644 {
645 if ( doProgress ) 645 if ( doProgress )
646 { 646 {
647 m_progress->setProgress( i ); 647 m_progress->setProgress( i );
648 } 648 }
649 qApp->processEvents(); 649 qApp->processEvents();
650 } 650 }
651 651
652 QString text = ""; 652 QString text = "";
653 653
654 package = it.current(); 654 package = it.current();
655 655
656 // Apply show only uninstalled packages filter 656 // Apply show only uninstalled packages filter
657 if ( showUninstalledPkgs && package->isInstalled() ) 657 if ( showUninstalledPkgs && package->isInstalled() )
658 continue; 658 continue;
659 659
660 // Apply show only installed packages filter 660 // Apply show only installed packages filter
661 if ( showInstalledPkgs && !package->isInstalled() ) 661 if ( showInstalledPkgs && !package->isInstalled() )
662 continue; 662 continue;
663 663
664 // Apply show only new installed packages filter 664 // Apply show only new installed packages filter
665 if ( showUpgradedPkgs ) 665 if ( showUpgradedPkgs )
666 { 666 {
667 if ( !package->isInstalled() || !package->getNewVersionAvailable() ) 667 if ( !package->isInstalled() || !package->getNewVersionAvailable() )
668 continue; 668 continue;
669 } 669 }
670 670
671 // Apply the section filter 671 // Apply the section filter
672 if ( categoryFilterEnabled && categoryFilter != "" ) 672 if ( categoryFilterEnabled && categoryFilter != "" )
673 { 673 {
674 if ( package->getSection() == "" || categoryFilter.find( package->getSection().lower() ) == -1 ) 674 if ( package->getSection() == "" || categoryFilter.find( package->getSection().lower() ) == -1 )
675 continue; 675 continue;
676 } 676 }
677 677
678 // If the local server, only display installed packages 678 // If the local server, only display installed packages
679 if ( serverName == LOCAL_SERVER && !package->isInstalled() ) 679 if ( serverName == LOCAL_SERVER && !package->isInstalled() )
680 continue; 680 continue;
681 681
682 682
683 QCheckListItem *item = new QCheckListItem( packagesList, package->getPackageName(), 683 QCheckListItem *item = new QCheckListItem( packagesList, package->getPackageName(),
684 QCheckListItem::CheckBox ); 684 QCheckListItem::CheckBox );
685 685
686 if ( package->isInstalled() ) 686 if ( package->isInstalled() )
687 { 687 {
688 // If a different version of package is available, show update available icon 688 // If a different version of package is available, show update available icon
689 // Otherwise, show installed icon 689 // Otherwise, show installed icon
690 if ( package->getNewVersionAvailable()) 690 if ( package->getNewVersionAvailable())
691 { 691 {
692 692
693 item->setPixmap( 0, updatedIcon ); 693 item->setPixmap( 0, updatedIcon );
694 } 694 }
695 else 695 else
696 { 696 {
697 item->setPixmap( 0, installedIcon ); 697 item->setPixmap( 0, installedIcon );
698 } 698 }
699 } 699 }
700 else 700 else
701 { 701 {
702 item->setPixmap( 0, nullIcon ); 702 item->setPixmap( 0, nullIcon );
703 } 703 }
704 704
705 packagesList->insertItem( item ); 705 packagesList->insertItem( item );
706 } 706 }
707 707
708 // If the local server or the local ipkgs server disable the download button 708 // If the local server or the local ipkgs server disable the download button
709 if ( serverName == LOCAL_SERVER ) 709 if ( serverName == LOCAL_SERVER )
710 { 710 {
711 downloadEnabled = TRUE; 711 downloadEnabled = TRUE;
712 actionUpgrade->setEnabled( FALSE ); 712 actionUpgrade->setEnabled( FALSE );
713 } 713 }
714 else if ( serverName == LOCAL_IPKGS ) 714 else if ( serverName == LOCAL_IPKGS )
715 { 715 {
716 downloadEnabled = FALSE; 716 downloadEnabled = FALSE;
717 actionUpgrade->setEnabled( FALSE ); 717 actionUpgrade->setEnabled( FALSE );
718 } 718 }
719 else 719 else
720 { 720 {
721 downloadEnabled = TRUE; 721 downloadEnabled = TRUE;
722 actionUpgrade->setEnabled( TRUE ); 722 actionUpgrade->setEnabled( TRUE );
723 } 723 }
724 enableDownload( downloadEnabled ); 724 enableDownload( downloadEnabled );
725 725
726 // Display this widget once everything is done 726 // Display this widget once everything is done
727 if ( doProgress && raiseProgress ) 727 if ( doProgress && raiseProgress )
728 { 728 {
729 stack->raiseWidget( networkPkgWindow ); 729 stack->raiseWidget( networkPkgWindow );
730 } 730 }
731} 731}
732 732
733void MainWindow :: searchForPackage( const QString &text ) 733void MainWindow :: searchForPackage( const QString &text )
734{ 734{
735 if ( !text.isEmpty() ) 735 if ( !text.isEmpty() )
736 { 736 {
737 // look through package list for text startng at current position 737 // look through package list for text startng at current position
738 QCheckListItem *start = (QCheckListItem *)packagesList->currentItem(); 738 QCheckListItem *start = (QCheckListItem *)packagesList->currentItem();
739 739
740 if ( start == 0 ) 740 if ( start == 0 )
741 start = (QCheckListItem *)packagesList->firstChild(); 741 start = (QCheckListItem *)packagesList->firstChild();
742 742
743 for ( QCheckListItem *item = start; item != 0 ; 743 for ( QCheckListItem *item = start; item != 0 ;
744 item = (QCheckListItem *)item->nextSibling() ) 744 item = (QCheckListItem *)item->nextSibling() )
745 { 745 {
746 if ( item->text().lower().find( text ) != -1 ) 746 if ( item->text().lower().find( text ) != -1 )
747 { 747 {
748 packagesList->ensureItemVisible( item ); 748 packagesList->ensureItemVisible( item );
749 packagesList->setCurrentItem( item ); 749 packagesList->setCurrentItem( item );
750 break; 750 break;
751 } 751 }
752 } 752 }
753 } 753 }
754} 754}
755 755
756void MainWindow :: updateServer() 756void MainWindow :: updateServer()
757{ 757{
758 QString serverName = serversList->currentText(); 758 QString serverName = serversList->currentText();
759 759
760 // Update the current server 760 // Update the current server
761 // Display dialog 761 // Display dialog
762 762
763 // Disable buttons to stop silly people clicking lots on them :) 763 // Disable buttons to stop silly people clicking lots on them :)
764 764
765 // First, write out ipkg_conf file so that ipkg can use it 765 // First, write out ipkg_conf file so that ipkg can use it
766 mgr->writeOutIpkgConf(); 766 mgr->writeOutIpkgConf();
767 767
768 Ipkg *ipkg = new Ipkg; 768 Ipkg *ipkg = new Ipkg;
769 ipkg->setOption( "update" ); 769 ipkg->setOption( "update" );
770 770
771 InstallDlgImpl *dlg = new InstallDlgImpl( ipkg, tr( "Refreshing server package lists" ), 771 InstallDlgImpl *dlg = new InstallDlgImpl( ipkg, tr( "Refreshing server package lists" ),
772 tr( "Update lists" ) ); 772 tr( "Update lists" ) );
773 connect( dlg, SIGNAL( reloadData( InstallDlgImpl * ) ), this, SLOT( reloadData( InstallDlgImpl * ) ) ); 773 connect( dlg, SIGNAL( reloadData(InstallDlgImpl*) ), this, SLOT( reloadData(InstallDlgImpl*) ) );
774 reloadDocuments = FALSE; 774 reloadDocuments = FALSE;
775 stack->addWidget( dlg, 3 ); 775 stack->addWidget( dlg, 3 );
776 stack->raiseWidget( dlg ); 776 stack->raiseWidget( dlg );
777 777
778 // delete progDlg; 778 // delete progDlg;
779} 779}
780 780
781void MainWindow :: upgradePackages() 781void MainWindow :: upgradePackages()
782{ 782{
783 // We're gonna do an upgrade of all packages 783 // We're gonna do an upgrade of all packages
784 // First warn user that this isn't recommended 784 // First warn user that this isn't recommended
785 // TODO - ODevice???? 785 // TODO - ODevice????
786 QString text = tr( "WARNING: Upgrading while\nOpie/Qtopia is running\nis NOT recommended!\n\nAre you sure?\n" ); 786 QString text = tr( "WARNING: Upgrading while\nOpie/Qtopia is running\nis NOT recommended!\n\nAre you sure?\n" );
787 QMessageBox warn( tr( "Warning" ), text, QMessageBox::Warning, 787 QMessageBox warn( tr( "Warning" ), text, QMessageBox::Warning,
788 QMessageBox::Yes, 788 QMessageBox::Yes,
789 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default , 789 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ,
790 0, this ); 790 0, this );
791 warn.adjustSize(); 791 warn.adjustSize();
792 792
793 if ( warn.exec() == QMessageBox::Yes ) 793 if ( warn.exec() == QMessageBox::Yes )
794 { 794 {
795 // First, write out ipkg_conf file so that ipkg can use it 795 // First, write out ipkg_conf file so that ipkg can use it
796 mgr->writeOutIpkgConf(); 796 mgr->writeOutIpkgConf();
797 797
798 // Now run upgrade 798 // Now run upgrade
799 Ipkg *ipkg = new Ipkg; 799 Ipkg *ipkg = new Ipkg;
800 ipkg->setOption( "upgrade" ); 800 ipkg->setOption( "upgrade" );
801 801
802 InstallDlgImpl *dlg = new InstallDlgImpl( ipkg, tr( "Upgrading installed packages" ), 802 InstallDlgImpl *dlg = new InstallDlgImpl( ipkg, tr( "Upgrading installed packages" ),
803 tr ( "Upgrade" ) ); 803 tr ( "Upgrade" ) );
804 connect( dlg, SIGNAL( reloadData( InstallDlgImpl * ) ), this, SLOT( reloadData( InstallDlgImpl * ) ) ); 804 connect( dlg, SIGNAL( reloadData(InstallDlgImpl*) ), this, SLOT( reloadData(InstallDlgImpl*) ) );
805 reloadDocuments = TRUE; 805 reloadDocuments = TRUE;
806 stack->addWidget( dlg, 3 ); 806 stack->addWidget( dlg, 3 );
807 stack->raiseWidget( dlg ); 807 stack->raiseWidget( dlg );
808 } 808 }
809} 809}
810 810
811void MainWindow :: downloadPackage() 811void MainWindow :: downloadPackage()
812{ 812{
813 bool doUpdate = true; 813 bool doUpdate = true;
814 if ( downloadEnabled ) 814 if ( downloadEnabled )
815 { 815 {
816 // See if any packages are selected 816 // See if any packages are selected
817 bool found = false; 817 bool found = false;
818 if ( serversList->currentText() != LOCAL_SERVER ) 818 if ( serversList->currentText() != LOCAL_SERVER )
819 { 819 {
820 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild(); 820 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild();
821 item != 0 && !found; 821 item != 0 && !found;
822 item = (QCheckListItem *)item->nextSibling() ) 822 item = (QCheckListItem *)item->nextSibling() )
823 { 823 {
824 if ( item->isOn() ) 824 if ( item->isOn() )
825 found = true; 825 found = true;
826 } 826 }
827 } 827 }
828 828
829 // If user selected some packages then download the and store the locally 829 // If user selected some packages then download the and store the locally
830 // otherwise, display dialog asking user what package to download from an http server 830 // otherwise, display dialog asking user what package to download from an http server
831 // and whether to install it 831 // and whether to install it
832 if ( found ) 832 if ( found )
833 downloadSelectedPackages(); 833 downloadSelectedPackages();
834 else 834 else
835 downloadRemotePackage(); 835 downloadRemotePackage();
836 836
837 } 837 }
838 else 838 else
839 { 839 {
840 doUpdate = false; 840 doUpdate = false;
841 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild(); 841 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild();
842 item != 0 ; 842 item != 0 ;
843 item = (QCheckListItem *)item->nextSibling() ) 843 item = (QCheckListItem *)item->nextSibling() )
844 { 844 {
845 if ( item->isOn() ) 845 if ( item->isOn() )
846 { 846 {
847 QString name = item->text(); 847 QString name = item->text();
848 int pos = name.find( "*" ); 848 int pos = name.find( "*" );
849 name.truncate( pos ); 849 name.truncate( pos );
850 850
851 // if (there is a (installed), remove it 851 // if (there is a (installed), remove it
852 pos = name.find( "(installed)" ); 852 pos = name.find( "(installed)" );
853 if ( pos > 0 ) 853 if ( pos > 0 )
854 name.truncate( pos - 1 ); 854 name.truncate( pos - 1 );
855 855
856 Package *p = mgr->getServer( serversList->currentText() )->getPackage( name ); 856 Package *p = mgr->getServer( serversList->currentText() )->getPackage( name );
857 857
858 QString msgtext; 858 QString msgtext;
859 msgtext = tr( "Are you sure you wish to delete\n%1?" ).arg( (const char *)p->getPackageName() ); 859 msgtext = tr( "Are you sure you wish to delete\n%1?" ).arg( (const char *)p->getPackageName() );
860 if ( QMessageBox::information( this, tr( "Are you sure?" ), 860 if ( QMessageBox::information( this, tr( "Are you sure?" ),
861 msgtext, tr( "No" ), tr( "Yes" ) ) == 1 ) 861 msgtext, tr( "No" ), tr( "Yes" ) ) == 1 )
862 { 862 {
863 doUpdate = true; 863 doUpdate = true;
864 QFile f( p->getFilename() ); 864 QFile f( p->getFilename() );
865 f.remove(); 865 f.remove();
866 } 866 }
867 } 867 }
868 } 868 }
869 } 869 }
870 870
871 if ( doUpdate ) 871 if ( doUpdate )
872 { 872 {
873 reloadData( 0x0 ); 873 reloadData( 0x0 );
874 } 874 }
875} 875}
876 876
877void MainWindow :: downloadSelectedPackages() 877void MainWindow :: downloadSelectedPackages()
878{ 878{
879 // First, write out ipkg_conf file so that ipkg can use it 879 // First, write out ipkg_conf file so that ipkg can use it
880 mgr->writeOutIpkgConf(); 880 mgr->writeOutIpkgConf();
881 881
882 // Display dialog to user asking where to download the files to 882 // Display dialog to user asking where to download the files to
883 bool ok = FALSE; 883 bool ok = FALSE;
884 QString dir = ""; 884 QString dir = "";
885#ifdef QWS 885#ifdef QWS
886 // read download directory from config file 886 // read download directory from config file
887 Config cfg( "aqpkg" ); 887 Config cfg( "aqpkg" );
888 cfg.setGroup( "settings" ); 888 cfg.setGroup( "settings" );
889 dir = cfg.readEntry( "downloadDir", "/home/root/Documents/application/ipkg" ); 889 dir = cfg.readEntry( "downloadDir", "/home/root/Documents/application/ipkg" );
890#endif 890#endif
891 891
892 QString text = InputDialog::getText( tr( "Download to where" ), tr( "Enter path to download to" ), dir, &ok, this ); 892 QString text = InputDialog::getText( tr( "Download to where" ), tr( "Enter path to download to" ), dir, &ok, this );
893 if ( ok && !text.isEmpty() ) 893 if ( ok && !text.isEmpty() )
894 dir = text; // user entered something and pressed ok 894 dir = text; // user entered something and pressed ok
895 else 895 else
896 return; // user entered nothing or pressed cancel 896 return; // user entered nothing or pressed cancel
897 897
898#ifdef QWS 898#ifdef QWS
899 // Store download directory in config file 899 // Store download directory in config file
900 cfg.writeEntry( "downloadDir", dir ); 900 cfg.writeEntry( "downloadDir", dir );
901#endif 901#endif
902 902
903 // Get starting directory 903 // Get starting directory
904 char initDir[PATH_MAX]; 904 char initDir[PATH_MAX];
905 getcwd( initDir, PATH_MAX ); 905 getcwd( initDir, PATH_MAX );
906 906
907 // Download each package 907 // Download each package
908 Ipkg ipkg; 908 Ipkg ipkg;
909 connect( &ipkg, SIGNAL(outputText(const QString &)), this, SLOT(displayText(const QString &))); 909 connect( &ipkg, SIGNAL(outputText(const QString&)), this, SLOT(displayText(const QString&)));
910 910
911 ipkg.setOption( "download" ); 911 ipkg.setOption( "download" );
912 ipkg.setRuntimeDirectory( dir ); 912 ipkg.setRuntimeDirectory( dir );
913 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild(); 913 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild();
914 item != 0 ; 914 item != 0 ;
915 item = (QCheckListItem *)item->nextSibling() ) 915 item = (QCheckListItem *)item->nextSibling() )
916 { 916 {
917 if ( item->isOn() ) 917 if ( item->isOn() )
918 { 918 {
919 ipkg.setPackage( item->text() ); 919 ipkg.setPackage( item->text() );
920 ipkg.runIpkg( ); 920 ipkg.runIpkg( );
921 } 921 }
922 } 922 }
923} 923}
924 924
925void MainWindow :: downloadRemotePackage() 925void MainWindow :: downloadRemotePackage()
926{ 926{
927 // Display dialog 927 // Display dialog
928 bool ok; 928 bool ok;
929 QString package = InputDialog::getText( tr( "Install Remote Package" ), tr( "Enter package location" ), "http://", &ok, this ); 929 QString package = InputDialog::getText( tr( "Install Remote Package" ), tr( "Enter package location" ), "http://", &ok, this );
930 if ( !ok || package.isEmpty() ) 930 if ( !ok || package.isEmpty() )
931 return; 931 return;
932 // DownloadRemoteDlgImpl dlg( this, "Install", true ); 932 // DownloadRemoteDlgImpl dlg( this, "Install", true );
933 // if ( dlg.exec() == QDialog::Rejected ) 933 // if ( dlg.exec() == QDialog::Rejected )
934 // return; 934 // return;
935 935
936 // grab details from dialog 936 // grab details from dialog
937 // QString package = dlg.getPackageLocation(); 937 // QString package = dlg.getPackageLocation();
938 938
939 InstallData *item = new InstallData(); 939 InstallData *item = new InstallData();
940 item->option = "I"; 940 item->option = "I";
941 item->packageName = package; 941 item->packageName = package;
942 QList<InstallData> workingPackages; 942 QList<InstallData> workingPackages;
943 workingPackages.setAutoDelete( TRUE ); 943 workingPackages.setAutoDelete( TRUE );
944 workingPackages.append( item ); 944 workingPackages.append( item );
945 945
946 InstallDlgImpl *dlg = new InstallDlgImpl( workingPackages, mgr, tr( "Download" ) ); 946 InstallDlgImpl *dlg = new InstallDlgImpl( workingPackages, mgr, tr( "Download" ) );
947 connect( dlg, SIGNAL( reloadData( InstallDlgImpl * ) ), this, SLOT( reloadData( InstallDlgImpl * ) ) ); 947 connect( dlg, SIGNAL( reloadData(InstallDlgImpl*) ), this, SLOT( reloadData(InstallDlgImpl*) ) );
948 reloadDocuments = TRUE; 948 reloadDocuments = TRUE;
949 stack->addWidget( dlg, 3 ); 949 stack->addWidget( dlg, 3 );
950 stack->raiseWidget( dlg ); 950 stack->raiseWidget( dlg );
951} 951}
952 952
953 953
954void MainWindow :: applyChanges() 954void MainWindow :: applyChanges()
955{ 955{
956 stickyOption = ""; 956 stickyOption = "";
957 957
958 // First, write out ipkg_conf file so that ipkg can use it 958 // First, write out ipkg_conf file so that ipkg can use it
959 mgr->writeOutIpkgConf(); 959 mgr->writeOutIpkgConf();
960 960
961 // Now for each selected item 961 // Now for each selected item
962 // deal with it 962 // deal with it
963 963
964 QList<InstallData> workingPackages; 964 QList<InstallData> workingPackages;
965 workingPackages.setAutoDelete( TRUE ); 965 workingPackages.setAutoDelete( TRUE );
966 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild(); 966 for ( QCheckListItem *item = (QCheckListItem *)packagesList->firstChild();
967 item != 0 ; 967 item != 0 ;
968 item = (QCheckListItem *)item->nextSibling() ) 968 item = (QCheckListItem *)item->nextSibling() )
969 { 969 {
970 if ( item->isOn() ) 970 if ( item->isOn() )
971 { 971 {
972 InstallData *instdata = dealWithItem( item ); 972 InstallData *instdata = dealWithItem( item );
973 if ( instdata ) 973 if ( instdata )
974 workingPackages.append( instdata ); 974 workingPackages.append( instdata );
975 else 975 else
976 return; 976 return;
977 } 977 }
978 } 978 }
979 979
980 if ( workingPackages.count() == 0 ) 980 if ( workingPackages.count() == 0 )
981 { 981 {
982 // Nothing to do 982 // Nothing to do
983 QMessageBox::information( this, tr( "Nothing to do" ), 983 QMessageBox::information( this, tr( "Nothing to do" ),
984 tr( "No packages selected" ), tr( "OK" ) ); 984 tr( "No packages selected" ), tr( "OK" ) );
985 985
986 return; 986 return;
987 } 987 }
988 988
989 // do the stuff 989 // do the stuff
990 InstallDlgImpl *dlg = new InstallDlgImpl( workingPackages, mgr, tr( "Apply changes" ) ); 990 InstallDlgImpl *dlg = new InstallDlgImpl( workingPackages, mgr, tr( "Apply changes" ) );
991 connect( dlg, SIGNAL( reloadData( InstallDlgImpl * ) ), this, SLOT( reloadData( InstallDlgImpl * ) ) ); 991 connect( dlg, SIGNAL( reloadData(InstallDlgImpl*) ), this, SLOT( reloadData(InstallDlgImpl*) ) );
992 reloadDocuments = TRUE; 992 reloadDocuments = TRUE;
993 stack->addWidget( dlg, 3 ); 993 stack->addWidget( dlg, 3 );
994 stack->raiseWidget( dlg ); 994 stack->raiseWidget( dlg );
995} 995}
996 996
997// decide what to do - either remove, upgrade or install 997// decide what to do - either remove, upgrade or install
998// Current rules: 998// Current rules:
999// If not installed - install 999// If not installed - install
1000// If installed and different version available - upgrade 1000// If installed and different version available - upgrade
1001// If installed and version up to date - remove 1001// If installed and version up to date - remove
1002InstallData *MainWindow :: dealWithItem( QCheckListItem *item ) 1002InstallData *MainWindow :: dealWithItem( QCheckListItem *item )
1003{ 1003{
1004 QString name = item->text(); 1004 QString name = item->text();
1005 1005
1006 // Get package 1006 // Get package
1007 Server *s = mgr->getServer( serversList->currentText() ); 1007 Server *s = mgr->getServer( serversList->currentText() );
1008 Package *p = s->getPackage( name ); 1008 Package *p = s->getPackage( name );
1009 1009
1010 // If the package has a filename then it is a local file 1010 // If the package has a filename then it is a local file
1011 if ( p->isPackageStoredLocally() ) 1011 if ( p->isPackageStoredLocally() )
1012 name = p->getFilename(); 1012 name = p->getFilename();
1013 1013
1014 QString option; 1014 QString option;
1015 QString dest = "root"; 1015 QString dest = "root";
1016 if ( !p->isInstalled() ) 1016 if ( !p->isInstalled() )
1017 { 1017 {
1018 InstallData *newitem = new InstallData(); 1018 InstallData *newitem = new InstallData();
1019 newitem->option = "I"; 1019 newitem->option = "I";
1020 newitem->packageName = name; 1020 newitem->packageName = name;
1021 return newitem; 1021 return newitem;
1022 } 1022 }
1023 else 1023 else
1024 { 1024 {
1025 InstallData *newitem = new InstallData(); 1025 InstallData *newitem = new InstallData();
1026 newitem->option = "D"; 1026 newitem->option = "D";
1027 // If local file, remove using package name, not filename 1027 // If local file, remove using package name, not filename
1028 if ( p->isPackageStoredLocally() ) 1028 if ( p->isPackageStoredLocally() )
1029 name = item->text(); 1029 name = item->text();
1030 1030
1031 if ( !p->isPackageStoredLocally() ) 1031 if ( !p->isPackageStoredLocally() )
1032 newitem->packageName = p->getInstalledPackageName(); 1032 newitem->packageName = p->getInstalledPackageName();
1033 else 1033 else
1034 newitem->packageName = name; 1034 newitem->packageName = name;
1035 1035
1036 if ( p->getInstalledTo() ) 1036 if ( p->getInstalledTo() )
1037 { 1037 {
1038 newitem->destination = p->getInstalledTo(); 1038 newitem->destination = p->getInstalledTo();
1039 } 1039 }
1040 else 1040 else
1041 { 1041 {
1042 newitem->destination = p->getLocalPackage()->getInstalledTo(); 1042 newitem->destination = p->getLocalPackage()->getInstalledTo();
1043 } 1043 }
1044 1044
1045 // Now see if version is newer or not 1045 // Now see if version is newer or not
1046 int val = compareVersions( p->getInstalledVersion(), p->getVersion() ); 1046 int val = compareVersions( p->getInstalledVersion(), p->getVersion() );
1047 1047
1048 // If the version requested is older and user selected a local ipk file, then reinstall the file 1048 // If the version requested is older and user selected a local ipk file, then reinstall the file
1049 if ( p->isPackageStoredLocally() && val == -1 ) 1049 if ( p->isPackageStoredLocally() && val == -1 )
1050 val = 0; 1050 val = 0;
1051 1051
1052 if ( val == -2 ) 1052 if ( val == -2 )
1053 { 1053 {
1054 // Error - should handle 1054 // Error - should handle
1055 } 1055 }
1056 else if ( val == -1 ) 1056 else if ( val == -1 )
1057 { 1057 {
1058 // Version available is older - remove only 1058 // Version available is older - remove only
1059 newitem->option = "D"; 1059 newitem->option = "D";
1060 // If local file, remove using package name, not filename 1060 // If local file, remove using package name, not filename
1061 if ( p->isPackageStoredLocally() ) 1061 if ( p->isPackageStoredLocally() )
1062 name = item->text(); 1062 name = item->text();
1063 } 1063 }
1064 else 1064 else
1065 { 1065 {
1066 QString caption; 1066 QString caption;
1067 QString text; 1067 QString text;
1068 QString secondButton; 1068 QString secondButton;
1069 QString secondOption; 1069 QString secondOption;
1070 if ( val == 0 ) 1070 if ( val == 0 )
1071 { 1071 {
1072 // Version available is the same - option to remove or reinstall 1072 // Version available is the same - option to remove or reinstall
1073 caption = tr( "Do you wish to remove or reinstall\n%1?" ); 1073 caption = tr( "Do you wish to remove or reinstall\n%1?" );
1074 text = tr( "Remove or ReInstall" ); 1074 text = tr( "Remove or ReInstall" );
1075 secondButton = tr( "ReInstall" ); 1075 secondButton = tr( "ReInstall" );
1076 secondOption = "R"; // Internal action code, do not translate 1076 secondOption = "R"; // Internal action code, do not translate
1077 } 1077 }
1078 else if ( val == 1 ) 1078 else if ( val == 1 )
1079 { 1079 {
1080 // Version available is newer - option to remove or upgrade 1080 // Version available is newer - option to remove or upgrade
1081 caption = tr( "Do you wish to remove or upgrade\n%1?" ); 1081 caption = tr( "Do you wish to remove or upgrade\n%1?" );
1082 text = tr( "Remove or Upgrade" ); 1082 text = tr( "Remove or Upgrade" );
1083 secondButton = tr( "Upgrade" ); 1083 secondButton = tr( "Upgrade" );
1084 secondOption = "U"; // Internal action code, do not translate 1084 secondOption = "U"; // Internal action code, do not translate
1085 } 1085 }
1086 1086
1087 // Sticky option not implemented yet, but will eventually allow 1087 // Sticky option not implemented yet, but will eventually allow
1088 // the user to say something like 'remove all' 1088 // the user to say something like 'remove all'
1089 if ( stickyOption == "" ) 1089 if ( stickyOption == "" )
1090 { 1090 {
1091 QString msgtext; 1091 QString msgtext;
1092 msgtext = caption.arg( ( const char * )name ); 1092 msgtext = caption.arg( ( const char * )name );
1093 QuestionDlg dlg( text, msgtext, secondButton ); 1093 QuestionDlg dlg( text, msgtext, secondButton );
1094 switch( dlg.exec() ) 1094 switch( dlg.exec() )
1095 { 1095 {
1096 case 0: // Cancel 1096 case 0: // Cancel
1097 delete newitem; 1097 delete newitem;
1098 return 0x0; 1098 return 0x0;
1099 break; 1099 break;
1100 case 1: // Remove 1100 case 1: // Remove
1101 newitem->option = "D"; 1101 newitem->option = "D";
1102 // If local file, remove using package name, not filename 1102 // If local file, remove using package name, not filename
1103 if ( p->isPackageStoredLocally() ) 1103 if ( p->isPackageStoredLocally() )
1104 name = item->text(); 1104 name = item->text();
1105 break; 1105 break;
1106 case 2: // Reinstall or Upgrade 1106 case 2: // Reinstall or Upgrade
1107 newitem->option = secondOption; 1107 newitem->option = secondOption;
1108 break; 1108 break;
1109 } 1109 }
1110 } 1110 }
1111 else 1111 else
1112 { 1112 {
1113 // newitem->option = stickyOption; 1113 // newitem->option = stickyOption;
1114 } 1114 }
1115 } 1115 }
1116 1116
1117 1117
1118 // Check if we are reinstalling the same version 1118 // Check if we are reinstalling the same version
1119 if ( newitem->option != "R" ) 1119 if ( newitem->option != "R" )
1120 newitem->recreateLinks = true; 1120 newitem->recreateLinks = true;
1121 else 1121 else
1122 newitem->recreateLinks = false; 1122 newitem->recreateLinks = false;
1123 1123
1124 // User hit cancel (on dlg - assume remove) 1124 // User hit cancel (on dlg - assume remove)
1125 return newitem; 1125 return newitem;
1126 } 1126 }
1127} 1127}
1128 1128
1129void MainWindow :: reloadData( InstallDlgImpl *dlg ) 1129void MainWindow :: reloadData( InstallDlgImpl *dlg )
1130{ 1130{
1131 stack->raiseWidget( progressWindow ); 1131 stack->raiseWidget( progressWindow );
1132 1132
1133 if ( dlg ) 1133 if ( dlg )
1134 { 1134 {
1135 dlg->close(); 1135 dlg->close();
1136 delete dlg; 1136 delete dlg;
1137 } 1137 }
1138 1138
1139 mgr->reloadServerData(); 1139 mgr->reloadServerData();
1140 serverSelected( -1, FALSE ); 1140 serverSelected( -1, FALSE );
1141 1141
1142#ifdef QWS 1142#ifdef QWS
1143 if ( reloadDocuments ) 1143 if ( reloadDocuments )
1144 { 1144 {
1145 m_status->setText( tr( "Updating Launcher..." ) ); 1145 m_status->setText( tr( "Updating Launcher..." ) );
1146 1146
1147 // Finally let the main system update itself 1147 // Finally let the main system update itself
1148 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 1148 QCopEnvelope e("QPE/System", "linkChanged(QString)");
1149 QString lf = QString::null; 1149 QString lf = QString::null;
1150 e << lf; 1150 e << lf;
1151 } 1151 }
1152#endif 1152#endif
1153 1153
1154 stack->raiseWidget( networkPkgWindow ); 1154 stack->raiseWidget( networkPkgWindow );
1155} 1155}
1156 1156
1157void MainWindow :: letterPushed( QString t ) 1157void MainWindow :: letterPushed( QString t )
1158{ 1158{
1159 QCheckListItem *top = (QCheckListItem *)packagesList->firstChild(); 1159 QCheckListItem *top = (QCheckListItem *)packagesList->firstChild();
1160 QCheckListItem *start = (QCheckListItem *)packagesList->currentItem(); 1160 QCheckListItem *start = (QCheckListItem *)packagesList->currentItem();
1161 if ( packagesList->firstChild() == 0 ) 1161 if ( packagesList->firstChild() == 0 )
1162 return; 1162 return;
1163 1163
1164 QCheckListItem *item; 1164 QCheckListItem *item;
1165 if ( start == 0 ) 1165 if ( start == 0 )
1166 { 1166 {
1167 item = (QCheckListItem *)packagesList->firstChild(); 1167 item = (QCheckListItem *)packagesList->firstChild();
1168 start = top; 1168 start = top;
1169 } 1169 }
1170 else 1170 else
1171 item = (QCheckListItem *)start->nextSibling(); 1171 item = (QCheckListItem *)start->nextSibling();
1172 1172
1173 if ( item == 0 ) 1173 if ( item == 0 )
1174 item = (QCheckListItem *)packagesList->firstChild(); 1174 item = (QCheckListItem *)packagesList->firstChild();
1175 do 1175 do
1176 { 1176 {
1177 if ( item->text().lower().startsWith( t.lower() ) ) 1177 if ( item->text().lower().startsWith( t.lower() ) )
1178 { 1178 {
1179 packagesList->setSelected( item, true ); 1179 packagesList->setSelected( item, true );
1180 packagesList->ensureItemVisible( item ); 1180 packagesList->ensureItemVisible( item );
1181 break; 1181 break;
1182 } 1182 }
1183 1183
1184 item = (QCheckListItem *)item->nextSibling(); 1184 item = (QCheckListItem *)item->nextSibling();
1185 if ( !item ) 1185 if ( !item )
1186 item = (QCheckListItem *)packagesList->firstChild(); 1186 item = (QCheckListItem *)packagesList->firstChild();
1187 } 1187 }
1188 while ( item != start); 1188 while ( item != start);
1189} 1189}
1190 1190
1191void MainWindow :: slotDisplayPackage( QListViewItem *item ) 1191void MainWindow :: slotDisplayPackage( QListViewItem *item )
1192{ 1192{
1193 QString itemstr( ((QCheckListItem*)item)->text() ); 1193 QString itemstr( ((QCheckListItem*)item)->text() );
1194 PackageWindow *p = new PackageWindow( mgr->getServer( serversList->currentText() )->getPackage( itemstr ) ); 1194 PackageWindow *p = new PackageWindow( mgr->getServer( serversList->currentText() )->getPackage( itemstr ) );
1195 QPEApplication::showWidget( p ); 1195 QPEApplication::showWidget( p );
1196} 1196}
1197 1197
1198QuestionDlg::QuestionDlg( const QString &caption, const QString &text, const QString &secondbtn ) 1198QuestionDlg::QuestionDlg( const QString &caption, const QString &text, const QString &secondbtn )
1199 : QWidget( 0x0, 0x0, WType_Modal | WType_TopLevel | WStyle_Dialog ) 1199 : QWidget( 0x0, 0x0, WType_Modal | WType_TopLevel | WStyle_Dialog )
1200{ 1200{
1201 setCaption( caption ); 1201 setCaption( caption );
1202 resize( 175, 100 ); 1202 resize( 175, 100 );
1203 1203
1204 QGridLayout *layout = new QGridLayout( this ); 1204 QGridLayout *layout = new QGridLayout( this );
1205 1205
1206 QLabel *l = new QLabel( text, this ); 1206 QLabel *l = new QLabel( text, this );
1207 l->setAlignment( AlignCenter | WordBreak ); 1207 l->setAlignment( AlignCenter | WordBreak );
1208 layout->addMultiCellWidget( l, 0, 0, 0, 1 ); 1208 layout->addMultiCellWidget( l, 0, 0, 0, 1 );
1209 1209
1210 btn1 = new QPushButton( tr( "Remove" ), this ); 1210 btn1 = new QPushButton( tr( "Remove" ), this );
1211 connect( btn1, SIGNAL(clicked()), this, SLOT(slotButtonPressed()) ); 1211 connect( btn1, SIGNAL(clicked()), this, SLOT(slotButtonPressed()) );
1212 layout->addWidget( btn1, 1, 0 ); 1212 layout->addWidget( btn1, 1, 0 );
1213 1213
1214 btn2 = new QPushButton( secondbtn, this ); 1214 btn2 = new QPushButton( secondbtn, this );
1215 connect( btn2, SIGNAL(clicked()), this, SLOT(slotButtonPressed()) ); 1215 connect( btn2, SIGNAL(clicked()), this, SLOT(slotButtonPressed()) );
1216 layout->addWidget( btn2, 1, 1 ); 1216 layout->addWidget( btn2, 1, 1 );
1217 1217
1218 executing = FALSE; 1218 executing = FALSE;
1219} 1219}
1220 1220
1221int QuestionDlg::exec() 1221int QuestionDlg::exec()
1222{ 1222{
1223 show(); 1223 show();
1224 1224
1225 if ( !executing ) 1225 if ( !executing )
1226 { 1226 {
1227 executing = TRUE; 1227 executing = TRUE;
1228 qApp->enter_loop(); 1228 qApp->enter_loop();
1229 } 1229 }
1230 1230
1231 return buttonpressed; 1231 return buttonpressed;
1232} 1232}
1233 1233
1234void QuestionDlg::slotButtonPressed() 1234void QuestionDlg::slotButtonPressed()
1235{ 1235{
1236 if ( sender() == btn1 ) 1236 if ( sender() == btn1 )
1237 buttonpressed = 1; 1237 buttonpressed = 1;
1238 else if ( sender() == btn2 ) 1238 else if ( sender() == btn2 )
1239 buttonpressed = 2; 1239 buttonpressed = 2;
1240 else 1240 else
1241 buttonpressed = 0; 1241 buttonpressed = 0;
1242 1242
1243 qApp->exit_loop(); 1243 qApp->exit_loop();
1244} 1244}
diff --git a/noncore/settings/aqpkg/settingsimpl.cpp b/noncore/settings/aqpkg/settingsimpl.cpp
index 6e9dd99..b9dbb6e 100644
--- a/noncore/settings/aqpkg/settingsimpl.cpp
+++ b/noncore/settings/aqpkg/settingsimpl.cpp
@@ -1,494 +1,494 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk> 4 =. Copyright (c) 2002 Andy Qua <andy.qua@blueyonder.co.uk>
5             .=l. Dan Williams <drw@handhelds.org> 5             .=l. Dan Williams <drw@handhelds.org>
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include "settingsimpl.h" 30#include "settingsimpl.h"
31#include "global.h" 31#include "global.h"
32 32
33/* OPIE */ 33/* OPIE */
34#include <opie2/otabwidget.h> 34#include <opie2/otabwidget.h>
35#ifdef QWS 35#ifdef QWS
36#include <qpe/config.h> 36#include <qpe/config.h>
37#include <qpe/resource.h> 37#include <qpe/resource.h>
38#endif 38#endif
39#include <qpe/qpeapplication.h> 39#include <qpe/qpeapplication.h>
40 40
41/* QT */ 41/* QT */
42#include <qcheckbox.h> 42#include <qcheckbox.h>
43#include <qgroupbox.h> 43#include <qgroupbox.h>
44#include <qlabel.h> 44#include <qlabel.h>
45#include <qlayout.h> 45#include <qlayout.h>
46#include <qlineedit.h> 46#include <qlineedit.h>
47#include <qlistbox.h> 47#include <qlistbox.h>
48#include <qpushbutton.h> 48#include <qpushbutton.h>
49 49
50/* STD */ 50/* STD */
51#include <fstream> 51#include <fstream>
52#include <algorithm> 52#include <algorithm>
53using namespace std; 53using namespace std;
54 54
55SettingsImpl :: SettingsImpl( DataManager *dataManager, QWidget * parent, const char* name, bool modal, WFlags fl ) 55SettingsImpl :: SettingsImpl( DataManager *dataManager, QWidget * parent, const char* name, bool modal, WFlags fl )
56 : QDialog( parent, name, modal, fl ) 56 : QDialog( parent, name, modal, fl )
57{ 57{
58 setCaption( tr( "Configuration" ) ); 58 setCaption( tr( "Configuration" ) );
59 59
60 // Setup layout to make everything pretty 60 // Setup layout to make everything pretty
61 QVBoxLayout *layout = new QVBoxLayout( this ); 61 QVBoxLayout *layout = new QVBoxLayout( this );
62 layout->setMargin( 2 ); 62 layout->setMargin( 2 );
63 layout->setSpacing( 4 ); 63 layout->setSpacing( 4 );
64 64
65 // Setup tabs for all info 65 // Setup tabs for all info
66 Opie::OTabWidget *tabwidget = new Opie::OTabWidget( this ); 66 Opie::OTabWidget *tabwidget = new Opie::OTabWidget( this );
67 layout->addWidget( tabwidget ); 67 layout->addWidget( tabwidget );
68 68
69 tabwidget->addTab( initServerTab(), "aqpkg/servertab", tr( "Servers" ) ); 69 tabwidget->addTab( initServerTab(), "aqpkg/servertab", tr( "Servers" ) );
70 tabwidget->addTab( initDestinationTab(), "aqpkg/desttab", tr( "Destinations" ) ); 70 tabwidget->addTab( initDestinationTab(), "aqpkg/desttab", tr( "Destinations" ) );
71 tabwidget->addTab( initProxyTab(), "aqpkg/proxytab", tr( "Proxies" ) ); 71 tabwidget->addTab( initProxyTab(), "aqpkg/proxytab", tr( "Proxies" ) );
72 tabwidget->setCurrentTab( tr( "Servers" ) ); 72 tabwidget->setCurrentTab( tr( "Servers" ) );
73 73
74 dataMgr = dataManager; 74 dataMgr = dataManager;
75 setupData(); 75 setupData();
76 changed = false; 76 changed = false;
77 newserver = false; 77 newserver = false;
78 newdestination = false; 78 newdestination = false;
79} 79}
80 80
81SettingsImpl :: ~SettingsImpl() 81SettingsImpl :: ~SettingsImpl()
82{ 82{
83} 83}
84 84
85bool SettingsImpl :: showDlg() 85bool SettingsImpl :: showDlg()
86{ 86{
87 QPEApplication::execDialog( this ); 87 QPEApplication::execDialog( this );
88 if ( changed ) 88 if ( changed )
89 dataMgr->writeOutIpkgConf(); 89 dataMgr->writeOutIpkgConf();
90 90
91 return changed; 91 return changed;
92} 92}
93 93
94QWidget *SettingsImpl :: initServerTab() 94QWidget *SettingsImpl :: initServerTab()
95{ 95{
96 QWidget *control = new QWidget( this ); 96 QWidget *control = new QWidget( this );
97 97
98 QVBoxLayout *vb = new QVBoxLayout( control ); 98 QVBoxLayout *vb = new QVBoxLayout( control );
99 99
100 QScrollView *sv = new QScrollView( control ); 100 QScrollView *sv = new QScrollView( control );
101 vb->addWidget( sv, 0, 0 ); 101 vb->addWidget( sv, 0, 0 );
102 sv->setResizePolicy( QScrollView::AutoOneFit ); 102 sv->setResizePolicy( QScrollView::AutoOneFit );
103 sv->setFrameStyle( QFrame::NoFrame ); 103 sv->setFrameStyle( QFrame::NoFrame );
104 104
105 QWidget *container = new QWidget( sv->viewport() ); 105 QWidget *container = new QWidget( sv->viewport() );
106 sv->addChild( container ); 106 sv->addChild( container );
107 107
108 QGridLayout *layout = new QGridLayout( container ); 108 QGridLayout *layout = new QGridLayout( container );
109 layout->setSpacing( 2 ); 109 layout->setSpacing( 2 );
110 layout->setMargin( 4 ); 110 layout->setMargin( 4 );
111 111
112 servers = new QListBox( container ); 112 servers = new QListBox( container );
113 servers->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ) ); 113 servers->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ) );
114 connect( servers, SIGNAL( highlighted( int ) ), this, SLOT( editServer( int ) ) ); 114 connect( servers, SIGNAL( highlighted(int) ), this, SLOT( editServer(int) ) );
115 layout->addMultiCellWidget( servers, 0, 0, 0, 1 ); 115 layout->addMultiCellWidget( servers, 0, 0, 0, 1 );
116 116
117 QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), container ); 117 QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), container );
118 connect( btn, SIGNAL( clicked() ), this, SLOT( newServer() ) ); 118 connect( btn, SIGNAL( clicked() ), this, SLOT( newServer() ) );
119 layout->addWidget( btn, 1, 0 ); 119 layout->addWidget( btn, 1, 0 );
120 120
121 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), container ); 121 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), container );
122 connect( btn, SIGNAL( clicked() ), this, SLOT( removeServer() ) ); 122 connect( btn, SIGNAL( clicked() ), this, SLOT( removeServer() ) );
123 layout->addWidget( btn, 1, 1 ); 123 layout->addWidget( btn, 1, 1 );
124 124
125 QGroupBox *grpbox = new QGroupBox( 0, Qt::Vertical, tr( "Server" ), container ); 125 QGroupBox *grpbox = new QGroupBox( 0, Qt::Vertical, tr( "Server" ), container );
126 grpbox->layout()->setSpacing( 2 ); 126 grpbox->layout()->setSpacing( 2 );
127 grpbox->layout()->setMargin( 4 ); 127 grpbox->layout()->setMargin( 4 );
128 layout->addMultiCellWidget( grpbox, 2, 2, 0, 1 ); 128 layout->addMultiCellWidget( grpbox, 2, 2, 0, 1 );
129 129
130 QGridLayout *grplayout = new QGridLayout( grpbox->layout() ); 130 QGridLayout *grplayout = new QGridLayout( grpbox->layout() );
131 131
132 QLabel *label = new QLabel( tr( "Name:" ), grpbox ); 132 QLabel *label = new QLabel( tr( "Name:" ), grpbox );
133 grplayout->addWidget( label, 0, 0 ); 133 grplayout->addWidget( label, 0, 0 );
134 servername = new QLineEdit( grpbox ); 134 servername = new QLineEdit( grpbox );
135 grplayout->addWidget( servername, 0, 1 ); 135 grplayout->addWidget( servername, 0, 1 );
136 136
137 label = new QLabel( tr( "Address:" ), grpbox ); 137 label = new QLabel( tr( "Address:" ), grpbox );
138 grplayout->addWidget( label, 1, 0 ); 138 grplayout->addWidget( label, 1, 0 );
139 serverurl = new QLineEdit( grpbox ); 139 serverurl = new QLineEdit( grpbox );
140 grplayout->addWidget( serverurl, 1, 1 ); 140 grplayout->addWidget( serverurl, 1, 1 );
141 141
142 active = new QCheckBox( tr( "Active Server" ), grpbox ); 142 active = new QCheckBox( tr( "Active Server" ), grpbox );
143 grplayout->addMultiCellWidget( active, 2, 2, 0, 1 ); 143 grplayout->addMultiCellWidget( active, 2, 2, 0, 1 );
144 144
145 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Update" ), grpbox ); 145 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Update" ), grpbox );
146 connect( btn, SIGNAL( clicked() ), this, SLOT( changeServerDetails() ) ); 146 connect( btn, SIGNAL( clicked() ), this, SLOT( changeServerDetails() ) );
147 grplayout->addMultiCellWidget( btn, 3, 3, 0, 1 ); 147 grplayout->addMultiCellWidget( btn, 3, 3, 0, 1 );
148 148
149 return control; 149 return control;
150} 150}
151 151
152QWidget *SettingsImpl :: initDestinationTab() 152QWidget *SettingsImpl :: initDestinationTab()
153{ 153{
154 QWidget *control = new QWidget( this ); 154 QWidget *control = new QWidget( this );
155 155
156 QVBoxLayout *vb = new QVBoxLayout( control ); 156 QVBoxLayout *vb = new QVBoxLayout( control );
157 157
158 QScrollView *sv = new QScrollView( control ); 158 QScrollView *sv = new QScrollView( control );
159 vb->addWidget( sv, 0, 0 ); 159 vb->addWidget( sv, 0, 0 );
160 sv->setResizePolicy( QScrollView::AutoOneFit ); 160 sv->setResizePolicy( QScrollView::AutoOneFit );
161 sv->setFrameStyle( QFrame::NoFrame ); 161 sv->setFrameStyle( QFrame::NoFrame );
162 162
163 QWidget *container = new QWidget( sv->viewport() ); 163 QWidget *container = new QWidget( sv->viewport() );
164 sv->addChild( container ); 164 sv->addChild( container );
165 165
166 QGridLayout *layout = new QGridLayout( container ); 166 QGridLayout *layout = new QGridLayout( container );
167 layout->setSpacing( 2 ); 167 layout->setSpacing( 2 );
168 layout->setMargin( 4 ); 168 layout->setMargin( 4 );
169 169
170 destinations = new QListBox( container ); 170 destinations = new QListBox( container );
171 destinations->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ) ); 171 destinations->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ) );
172 connect( destinations, SIGNAL( highlighted( int ) ), this, SLOT( editDestination( int ) ) ); 172 connect( destinations, SIGNAL( highlighted(int) ), this, SLOT( editDestination(int) ) );
173 layout->addMultiCellWidget( destinations, 0, 0, 0, 1 ); 173 layout->addMultiCellWidget( destinations, 0, 0, 0, 1 );
174 174
175 QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), container ); 175 QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), container );
176 connect( btn, SIGNAL( clicked() ), this, SLOT( newDestination() ) ); 176 connect( btn, SIGNAL( clicked() ), this, SLOT( newDestination() ) );
177 layout->addWidget( btn, 1, 0 ); 177 layout->addWidget( btn, 1, 0 );
178 178
179 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), container ); 179 btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), container );
180 connect( btn, SIGNAL( clicked() ), this, SLOT( removeDestination() ) ); 180 connect( btn, SIGNAL( clicked() ), this, SLOT( removeDestination() ) );
181 layout->addWidget( btn, 1, 1 ); 181 layout->addWidget( btn, 1, 1 );
182 182
183 QGroupBox *grpbox = new QGroupBox( 0, Qt::Vertical, tr( "Destination" ), container ); 183 QGroupBox *grpbox = new QGroupBox( 0, Qt::Vertical, tr( "Destination" ), container );
184 grpbox->layout()->setSpacing( 2 ); 184 grpbox->layout()->setSpacing( 2 );
185 grpbox->layout()->setMargin( 4 ); 185 grpbox->layout()->setMargin( 4 );
186 layout->addMultiCellWidget( grpbox, 2, 2, 0, 1 ); 186 layout->addMultiCellWidget( grpbox, 2, 2, 0, 1 );
187 187
188 QGridLayout *grplayout = new QGridLayout( grpbox->layout() ); 188 QGridLayout *grplayout = new QGridLayout( grpbox->layout() );
189 189
190 QLabel *label = new QLabel( tr( "Name:" ), grpbox ); 190 QLabel *label = new QLabel( tr( "Name:" ), grpbox );
191 grplayout->addWidget( label, 0, 0 ); 191 grplayout->addWidget( label, 0, 0 );
192 destinationname = new QLineEdit( grpbox ); 192 destinationname = new QLineEdit( grpbox );
193 grplayout->addWidget( destinationname, 0, 1 ); 193 grplayout->addWidget( destinationname, 0, 1 );
194 194
195 label = new QLabel( tr( "Location:" ), grpbox ); 195 label = new QLabel( tr( "Location:" ), grpbox );
196 grplayout->addWidget( label, 1, 0 ); 196 grplayout->addWidget( label, 1, 0 );
197 destinationurl = new QLineEdit( grpbox ); 197 destinationurl = new QLineEdit( grpbox );
198 grplayout->addWidget( destinationurl, 1, 1 ); 198 grplayout->addWidget( destinationurl, 1, 1 );
199 199
200 linkToRoot = new QCheckBox( tr( "Link to root" ), grpbox ); 200 linkToRoot = new QCheckBox( tr( "Link to root" ), grpbox );
201 grplayout->addMultiCellWidget( linkToRoot, 2, 2, 0, 1 ); 201 grplayout->addMultiCellWidget( linkToRoot, 2, 2, 0, 1 );
202 202
203 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Update" ), grpbox ); 203 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Update" ), grpbox );
204 connect( btn, SIGNAL( clicked() ), this, SLOT( changeDestinationDetails() ) ); 204 connect( btn, SIGNAL( clicked() ), this, SLOT( changeDestinationDetails() ) );
205 grplayout->addMultiCellWidget( btn, 3, 3, 0, 1 ); 205 grplayout->addMultiCellWidget( btn, 3, 3, 0, 1 );
206 206
207 return control; 207 return control;
208} 208}
209 209
210QWidget *SettingsImpl :: initProxyTab() 210QWidget *SettingsImpl :: initProxyTab()
211{ 211{
212 QWidget *control = new QWidget( this ); 212 QWidget *control = new QWidget( this );
213 213
214 QVBoxLayout *vb = new QVBoxLayout( control ); 214 QVBoxLayout *vb = new QVBoxLayout( control );
215 215
216 QScrollView *sv = new QScrollView( control ); 216 QScrollView *sv = new QScrollView( control );
217 vb->addWidget( sv, 0, 0 ); 217 vb->addWidget( sv, 0, 0 );
218 sv->setResizePolicy( QScrollView::AutoOneFit ); 218 sv->setResizePolicy( QScrollView::AutoOneFit );
219 sv->setFrameStyle( QFrame::NoFrame ); 219 sv->setFrameStyle( QFrame::NoFrame );
220 220
221 QWidget *container = new QWidget( sv->viewport() ); 221 QWidget *container = new QWidget( sv->viewport() );
222 sv->addChild( container ); 222 sv->addChild( container );
223 223
224 QGridLayout *layout = new QGridLayout( container ); 224 QGridLayout *layout = new QGridLayout( container );
225 layout->setSpacing( 2 ); 225 layout->setSpacing( 2 );
226 layout->setMargin( 4 ); 226 layout->setMargin( 4 );
227 227
228 QGroupBox *grpbox = new QGroupBox( 0, Qt::Vertical, tr( "HTTP Proxy" ), container ); 228 QGroupBox *grpbox = new QGroupBox( 0, Qt::Vertical, tr( "HTTP Proxy" ), container );
229 grpbox->layout()->setSpacing( 2 ); 229 grpbox->layout()->setSpacing( 2 );
230 grpbox->layout()->setMargin( 4 ); 230 grpbox->layout()->setMargin( 4 );
231 layout->addMultiCellWidget( grpbox, 0, 0, 0, 1 ); 231 layout->addMultiCellWidget( grpbox, 0, 0, 0, 1 );
232 QVBoxLayout *grplayout = new QVBoxLayout( grpbox->layout() ); 232 QVBoxLayout *grplayout = new QVBoxLayout( grpbox->layout() );
233 txtHttpProxy = new QLineEdit( grpbox ); 233 txtHttpProxy = new QLineEdit( grpbox );
234 grplayout->addWidget( txtHttpProxy ); 234 grplayout->addWidget( txtHttpProxy );
235 chkHttpProxyEnabled = new QCheckBox( tr( "Enabled" ), grpbox ); 235 chkHttpProxyEnabled = new QCheckBox( tr( "Enabled" ), grpbox );
236 grplayout->addWidget( chkHttpProxyEnabled ); 236 grplayout->addWidget( chkHttpProxyEnabled );
237 237
238 grpbox = new QGroupBox( 0, Qt::Vertical, tr( "FTP Proxy" ), container ); 238 grpbox = new QGroupBox( 0, Qt::Vertical, tr( "FTP Proxy" ), container );
239 grpbox->layout()->setSpacing( 2 ); 239 grpbox->layout()->setSpacing( 2 );
240 grpbox->layout()->setMargin( 4 ); 240 grpbox->layout()->setMargin( 4 );
241 layout->addMultiCellWidget( grpbox, 1, 1, 0, 1 ); 241 layout->addMultiCellWidget( grpbox, 1, 1, 0, 1 );
242 grplayout = new QVBoxLayout( grpbox->layout() ); 242 grplayout = new QVBoxLayout( grpbox->layout() );
243 txtFtpProxy = new QLineEdit( grpbox ); 243 txtFtpProxy = new QLineEdit( grpbox );
244 grplayout->addWidget( txtFtpProxy ); 244 grplayout->addWidget( txtFtpProxy );
245 chkFtpProxyEnabled = new QCheckBox( tr( "Enabled" ), grpbox ); 245 chkFtpProxyEnabled = new QCheckBox( tr( "Enabled" ), grpbox );
246 grplayout->addWidget( chkFtpProxyEnabled ); 246 grplayout->addWidget( chkFtpProxyEnabled );
247 247
248 QLabel *label = new QLabel( tr( "Username:" ), container ); 248 QLabel *label = new QLabel( tr( "Username:" ), container );
249 layout->addWidget( label, 2, 0 ); 249 layout->addWidget( label, 2, 0 );
250 txtUsername = new QLineEdit( container ); 250 txtUsername = new QLineEdit( container );
251 layout->addWidget( txtUsername, 2, 1 ); 251 layout->addWidget( txtUsername, 2, 1 );
252 252
253 label = new QLabel( tr( "Password:" ), container ); 253 label = new QLabel( tr( "Password:" ), container );
254 layout->addWidget( label, 3, 0 ); 254 layout->addWidget( label, 3, 0 );
255 txtPassword = new QLineEdit( container ); 255 txtPassword = new QLineEdit( container );
256 layout->addWidget( txtPassword, 3, 1 ); 256 layout->addWidget( txtPassword, 3, 1 );
257 257
258 QPushButton *btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Update" ), container ); 258 QPushButton *btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Update" ), container );
259 connect( btn, SIGNAL( clicked() ), this, SLOT( proxyApplyChanges() ) ); 259 connect( btn, SIGNAL( clicked() ), this, SLOT( proxyApplyChanges() ) );
260 layout->addMultiCellWidget( btn, 4, 4, 0, 1 ); 260 layout->addMultiCellWidget( btn, 4, 4, 0, 1 );
261 261
262 return control; 262 return control;
263} 263}
264 264
265void SettingsImpl :: setupData() 265void SettingsImpl :: setupData()
266{ 266{
267 // add servers 267 // add servers
268 QString serverName; 268 QString serverName;
269 QListIterator<Server> it( dataMgr->getServerList() ); 269 QListIterator<Server> it( dataMgr->getServerList() );
270 for ( ; it.current(); ++it ) 270 for ( ; it.current(); ++it )
271 { 271 {
272 serverName = it.current()->getServerName(); 272 serverName = it.current()->getServerName();
273 if ( serverName == LOCAL_SERVER || serverName == LOCAL_IPKGS ) 273 if ( serverName == LOCAL_SERVER || serverName == LOCAL_IPKGS )
274 continue; 274 continue;
275 275
276 servers->insertItem( serverName ); 276 servers->insertItem( serverName );
277 } 277 }
278 278
279 279
280 // add destinations 280 // add destinations
281 QListIterator<Destination> it2( dataMgr->getDestinationList() ); 281 QListIterator<Destination> it2( dataMgr->getDestinationList() );
282 for ( ; it2.current(); ++it2 ) 282 for ( ; it2.current(); ++it2 )
283 destinations->insertItem( it2.current()->getDestinationName() ); 283 destinations->insertItem( it2.current()->getDestinationName() );
284 284
285 // setup proxy tab 285 // setup proxy tab
286 txtHttpProxy->setText( dataMgr->getHttpProxy() ); 286 txtHttpProxy->setText( dataMgr->getHttpProxy() );
287 txtFtpProxy->setText( dataMgr->getFtpProxy() ); 287 txtFtpProxy->setText( dataMgr->getFtpProxy() );
288 txtUsername->setText( dataMgr->getProxyUsername() ); 288 txtUsername->setText( dataMgr->getProxyUsername() );
289 txtPassword->setText( dataMgr->getProxyPassword() ); 289 txtPassword->setText( dataMgr->getProxyPassword() );
290 chkHttpProxyEnabled->setChecked( dataMgr->getHttpProxyEnabled() ); 290 chkHttpProxyEnabled->setChecked( dataMgr->getHttpProxyEnabled() );
291 chkFtpProxyEnabled->setChecked( dataMgr->getFtpProxyEnabled() ); 291 chkFtpProxyEnabled->setChecked( dataMgr->getFtpProxyEnabled() );
292} 292}
293 293
294//------------------ Servers tab ---------------------- 294//------------------ Servers tab ----------------------
295 295
296void SettingsImpl :: editServer( int sel ) 296void SettingsImpl :: editServer( int sel )
297{ 297{
298 currentSelectedServer = sel; 298 currentSelectedServer = sel;
299 Server *s = dataMgr->getServer( servers->currentText() ); 299 Server *s = dataMgr->getServer( servers->currentText() );
300 if ( s ) 300 if ( s )
301 { 301 {
302 serverName = s->getServerName(); 302 serverName = s->getServerName();
303 servername->setText( s->getServerName() ); 303 servername->setText( s->getServerName() );
304 serverurl->setText( s->getServerUrl() ); 304 serverurl->setText( s->getServerUrl() );
305 active->setChecked( s->isServerActive() ); 305 active->setChecked( s->isServerActive() );
306 } 306 }
307 else 307 else
308 { 308 {
309 serverName = ""; 309 serverName = "";
310 servername->setText( "" ); 310 servername->setText( "" );
311 serverurl->setText( "" ); 311 serverurl->setText( "" );
312 active->setChecked( false ); 312 active->setChecked( false );
313 } 313 }
314} 314}
315 315
316void SettingsImpl :: newServer() 316void SettingsImpl :: newServer()
317{ 317{
318 newserver = true; 318 newserver = true;
319 servername->setText( "" ); 319 servername->setText( "" );
320 serverurl->setText( "" ); 320 serverurl->setText( "" );
321 servername->setFocus(); 321 servername->setFocus();
322 active->setChecked( true ); 322 active->setChecked( true );
323} 323}
324 324
325void SettingsImpl :: removeServer() 325void SettingsImpl :: removeServer()
326{ 326{
327 changed = true; 327 changed = true;
328 Server *s = dataMgr->getServer( servers->currentText() ); 328 Server *s = dataMgr->getServer( servers->currentText() );
329 if ( s ) 329 if ( s )
330 { 330 {
331 dataMgr->getServerList().removeRef( s ); 331 dataMgr->getServerList().removeRef( s );
332 servers->removeItem( currentSelectedServer ); 332 servers->removeItem( currentSelectedServer );
333 } 333 }
334} 334}
335 335
336void SettingsImpl :: changeServerDetails() 336void SettingsImpl :: changeServerDetails()
337{ 337{
338 changed = true; 338 changed = true;
339 339
340 QString newName = servername->text(); 340 QString newName = servername->text();
341 341
342 // Convert any spaces to underscores 342 // Convert any spaces to underscores
343 char *tmpStr = new char[newName.length() + 1]; 343 char *tmpStr = new char[newName.length() + 1];
344 for ( unsigned int i = 0 ; i < newName.length() ; ++i ) 344 for ( unsigned int i = 0 ; i < newName.length() ; ++i )
345 { 345 {
346 if ( newName[i] == ' ' ) 346 if ( newName[i] == ' ' )
347 tmpStr[i] = '_'; 347 tmpStr[i] = '_';
348 else 348 else
349 tmpStr[i] = newName[i].latin1(); 349 tmpStr[i] = newName[i].latin1();
350 } 350 }
351 tmpStr[newName.length()] = '\0'; 351 tmpStr[newName.length()] = '\0';
352 352
353 newName = tmpStr; 353 newName = tmpStr;
354 delete tmpStr; 354 delete tmpStr;
355 355
356 if ( !newserver ) 356 if ( !newserver )
357 { 357 {
358 Server *s = dataMgr->getServer( servers->currentText() ); 358 Server *s = dataMgr->getServer( servers->currentText() );
359 if ( s ) 359 if ( s )
360 { 360 {
361 // Update url 361 // Update url
362 s->setServerUrl( serverurl->text() ); 362 s->setServerUrl( serverurl->text() );
363 s->setActive( active->isChecked() ); 363 s->setActive( active->isChecked() );
364 364
365 // Check if server name has changed, if it has then we need to replace the key in the map 365 // Check if server name has changed, if it has then we need to replace the key in the map
366 if ( serverName != newName ) 366 if ( serverName != newName )
367 { 367 {
368 // Update server name 368 // Update server name
369 s->setServerName( newName ); 369 s->setServerName( newName );
370 } 370 }
371 371
372 // Update list box 372 // Update list box
373 servers->changeItem( newName, currentSelectedServer ); 373 servers->changeItem( newName, currentSelectedServer );
374 } 374 }
375 } 375 }
376 else 376 else
377 { 377 {
378 Server s( newName, serverurl->text() ); 378 Server s( newName, serverurl->text() );
379 dataMgr->getServerList().append( new Server( newName, serverurl->text() ) ); 379 dataMgr->getServerList().append( new Server( newName, serverurl->text() ) );
380 dataMgr->getServerList().last()->setActive( active->isChecked() ); 380 dataMgr->getServerList().last()->setActive( active->isChecked() );
381 servers->insertItem( newName ); 381 servers->insertItem( newName );
382 servers->setCurrentItem( servers->count() ); 382 servers->setCurrentItem( servers->count() );
383 newserver = false; 383 newserver = false;
384 } 384 }
385} 385}
386 386
387//------------------ Destinations tab ---------------------- 387//------------------ Destinations tab ----------------------
388 388
389void SettingsImpl :: editDestination( int sel ) 389void SettingsImpl :: editDestination( int sel )
390{ 390{
391 currentSelectedDestination = sel; 391 currentSelectedDestination = sel;
392 Destination *d = dataMgr->getDestination( destinations->currentText() ); 392 Destination *d = dataMgr->getDestination( destinations->currentText() );
393 if ( d ) 393 if ( d )
394 { 394 {
395 destinationName = d->getDestinationName(); 395 destinationName = d->getDestinationName();
396 destinationname->setText( d->getDestinationName() ); 396 destinationname->setText( d->getDestinationName() );
397 destinationurl->setText( d->getDestinationPath() ); 397 destinationurl->setText( d->getDestinationPath() );
398 linkToRoot->setChecked( d->linkToRoot() ); 398 linkToRoot->setChecked( d->linkToRoot() );
399 } 399 }
400 else 400 else
401 { 401 {
402 destinationName = ""; 402 destinationName = "";
403 destinationname->setText( "" ); 403 destinationname->setText( "" );
404 destinationurl->setText( "" ); 404 destinationurl->setText( "" );
405 linkToRoot->setChecked( false ); 405 linkToRoot->setChecked( false );
406 } 406 }
407} 407}
408 408
409void SettingsImpl :: newDestination() 409void SettingsImpl :: newDestination()
410{ 410{
411 newdestination = true; 411 newdestination = true;
412 destinationname->setText( "" ); 412 destinationname->setText( "" );
413 destinationurl->setText( "" ); 413 destinationurl->setText( "" );
414 destinationname->setFocus(); 414 destinationname->setFocus();
415 linkToRoot->setChecked( true ); 415 linkToRoot->setChecked( true );
416} 416}
417 417
418void SettingsImpl :: removeDestination() 418void SettingsImpl :: removeDestination()
419{ 419{
420 changed = true; 420 changed = true;
421 Destination *d = dataMgr->getDestination( destinations->currentText() ); 421 Destination *d = dataMgr->getDestination( destinations->currentText() );
422 if ( d ) 422 if ( d )
423 { 423 {
424 dataMgr->getDestinationList().removeRef( d ); 424 dataMgr->getDestinationList().removeRef( d );
425 destinations->removeItem( currentSelectedDestination ); 425 destinations->removeItem( currentSelectedDestination );
426 } 426 }
427} 427}
428 428
429void SettingsImpl :: changeDestinationDetails() 429void SettingsImpl :: changeDestinationDetails()
430{ 430{
431 changed = true; 431 changed = true;
432 432
433#ifdef QWS 433#ifdef QWS
434 Config cfg( "aqpkg" ); 434 Config cfg( "aqpkg" );
435 cfg.setGroup( "destinations" ); 435 cfg.setGroup( "destinations" );
436#endif 436#endif
437 437
438 QString newName = destinationname->text(); 438 QString newName = destinationname->text();
439 if ( !newdestination ) 439 if ( !newdestination )
440 { 440 {
441 Destination *d = dataMgr->getDestination( destinations->currentText() ); 441 Destination *d = dataMgr->getDestination( destinations->currentText() );
442 if ( d ) 442 if ( d )
443 { 443 {
444 // Update url 444 // Update url
445 d->setDestinationPath( destinationurl->text() ); 445 d->setDestinationPath( destinationurl->text() );
446 d->linkToRoot( linkToRoot->isChecked() ); 446 d->linkToRoot( linkToRoot->isChecked() );
447 447
448 // Check if server name has changed, if it has then we need to replace the key in the map 448 // Check if server name has changed, if it has then we need to replace the key in the map
449 if ( destinationName != newName ) 449 if ( destinationName != newName )
450 { 450 {
451 // Update server name 451 // Update server name
452 d->setDestinationName( newName ); 452 d->setDestinationName( newName );
453 453
454 // Update list box 454 // Update list box
455 destinations->changeItem( newName, currentSelectedDestination ); 455 destinations->changeItem( newName, currentSelectedDestination );
456 } 456 }
457 457
458#ifdef QWS 458#ifdef QWS
459 QString key = newName; 459 QString key = newName;
460 key += "_linkToRoot"; 460 key += "_linkToRoot";
461 int val = d->linkToRoot(); 461 int val = d->linkToRoot();
462 cfg.writeEntry( key, val ); 462 cfg.writeEntry( key, val );
463#endif 463#endif
464 464
465 } 465 }
466 } 466 }
467 else 467 else
468 { 468 {
469 dataMgr->getDestinationList().append( new Destination( newName, destinationurl->text() ) ); 469 dataMgr->getDestinationList().append( new Destination( newName, destinationurl->text() ) );
470 destinations->insertItem( newName ); 470 destinations->insertItem( newName );
471 destinations->setCurrentItem( destinations->count() ); 471 destinations->setCurrentItem( destinations->count() );
472 newdestination = false; 472 newdestination = false;
473 473
474#ifdef QWS 474#ifdef QWS
475 QString key = newName; 475 QString key = newName;
476 key += "_linkToRoot"; 476 key += "_linkToRoot";
477 cfg.writeEntry( key, true ); 477 cfg.writeEntry( key, true );
478#endif 478#endif
479 479
480 } 480 }
481} 481}
482 482
483//------------------ Proxy tab ---------------------- 483//------------------ Proxy tab ----------------------
484void SettingsImpl :: proxyApplyChanges() 484void SettingsImpl :: proxyApplyChanges()
485{ 485{
486 changed = true; 486 changed = true;
487 dataMgr->setHttpProxy( txtHttpProxy->text() ); 487 dataMgr->setHttpProxy( txtHttpProxy->text() );
488 dataMgr->setFtpProxy( txtFtpProxy->text() ); 488 dataMgr->setFtpProxy( txtFtpProxy->text() );
489 dataMgr->setProxyUsername( txtUsername->text() ); 489 dataMgr->setProxyUsername( txtUsername->text() );
490 dataMgr->setProxyPassword( txtPassword->text() ); 490 dataMgr->setProxyPassword( txtPassword->text() );
491 491
492 dataMgr->setHttpProxyEnabled( chkHttpProxyEnabled->isChecked() ); 492 dataMgr->setHttpProxyEnabled( chkHttpProxyEnabled->isChecked() );
493 dataMgr->setFtpProxyEnabled( chkFtpProxyEnabled->isChecked() ); 493 dataMgr->setFtpProxyEnabled( chkFtpProxyEnabled->isChecked() );
494} 494}
diff --git a/noncore/settings/backup/backuprestore.cpp b/noncore/settings/backup/backuprestore.cpp
index 977c283..6b83bc9 100644
--- a/noncore/settings/backup/backuprestore.cpp
+++ b/noncore/settings/backup/backuprestore.cpp
@@ -1,481 +1,481 @@
1 1
2#include "backuprestore.h" 2#include "backuprestore.h"
3#include "errordialog.h" 3#include "errordialog.h"
4 4
5/* OPIE */ 5/* OPIE */
6#include <opie2/ostorageinfo.h> 6#include <opie2/ostorageinfo.h>
7#include <qpe/qpeapplication.h> 7#include <qpe/qpeapplication.h>
8 8
9/* QT */ 9/* QT */
10#include <qapplication.h> 10#include <qapplication.h>
11#include <qmultilineedit.h> 11#include <qmultilineedit.h>
12#include <qdir.h> 12#include <qdir.h>
13#include <qfile.h> 13#include <qfile.h>
14#include <qfileinfo.h> 14#include <qfileinfo.h>
15#include <qlistview.h> 15#include <qlistview.h>
16#include <qpushbutton.h> 16#include <qpushbutton.h>
17#include <qheader.h> 17#include <qheader.h>
18#include <qpe/resource.h> 18#include <qpe/resource.h>
19#include <qpe/config.h> 19#include <qpe/config.h>
20#include <qmessagebox.h> 20#include <qmessagebox.h>
21#include <qcombobox.h> 21#include <qcombobox.h>
22#include <qlist.h> 22#include <qlist.h>
23#include <stdlib.h> 23#include <stdlib.h>
24#include <qregexp.h> 24#include <qregexp.h>
25#include <qtextstream.h> 25#include <qtextstream.h>
26#include <qtextview.h> 26#include <qtextview.h>
27 27
28/* STD */ 28/* STD */
29#include <errno.h> 29#include <errno.h>
30#include <stdlib.h> 30#include <stdlib.h>
31#include <unistd.h> 31#include <unistd.h>
32#include <sys/stat.h> 32#include <sys/stat.h>
33#include <dirent.h> 33#include <dirent.h>
34 34
35#define HEADER_NAME 0 35#define HEADER_NAME 0
36#define HEADER_BACKUP 1 36#define HEADER_BACKUP 1
37#define BACKUP_LOCATION 2 37#define BACKUP_LOCATION 2
38 38
39#define EXTENSION ".bck" 39#define EXTENSION ".bck"
40 40
41const QString tempFileName = "/tmp/backup.err"; 41const QString tempFileName = "/tmp/backup.err";
42 42
43 43
44BackupAndRestore::BackupAndRestore( QWidget* parent, const char* name, WFlags fl) 44BackupAndRestore::BackupAndRestore( QWidget* parent, const char* name, WFlags fl)
45 : BackupAndRestoreBase(parent, name, fl) 45 : BackupAndRestoreBase(parent, name, fl)
46{ 46{
47 backupList->header()->hide(); 47 backupList->header()->hide();
48 restoreList->header()->hide(); 48 restoreList->header()->hide();
49 connect(backupButton, SIGNAL(clicked()), 49 connect(backupButton, SIGNAL(clicked()),
50 this, SLOT(backup())); 50 this, SLOT(backup()));
51 connect(restoreButton, SIGNAL(clicked()), 51 connect(restoreButton, SIGNAL(clicked()),
52 this, SLOT(restore())); 52 this, SLOT(restore()));
53 connect(backupList, SIGNAL(clicked( QListViewItem * )), 53 connect(backupList, SIGNAL(clicked(QListViewItem*)),
54 this, SLOT(selectItem(QListViewItem*))); 54 this, SLOT(selectItem(QListViewItem*)));
55 connect(restoreSource, SIGNAL(activated( int )), 55 connect(restoreSource, SIGNAL(activated(int)),
56 this, SLOT(sourceDirChanged(int))); 56 this, SLOT(sourceDirChanged(int)));
57 connect(updateList, SIGNAL(clicked()), 57 connect(updateList, SIGNAL(clicked()),
58 this, SLOT( fileListUpdate())); 58 this, SLOT( fileListUpdate()));
59 59
60 //add directorys for backing up 60 //add directorys for backing up
61 applicationSettings = new QListViewItem(backupList, "Application Settings", "", "Settings/"); 61 applicationSettings = new QListViewItem(backupList, "Application Settings", "", "Settings/");
62 selectItem(applicationSettings); 62 selectItem(applicationSettings);
63 applicationSettings = new QListViewItem(backupList, "Application Data", "", "Applications/"); 63 applicationSettings = new QListViewItem(backupList, "Application Data", "", "Applications/");
64 selectItem(applicationSettings); 64 selectItem(applicationSettings);
65 documents= new QListViewItem(backupList, "Documents", "", "Documents/"); 65 documents= new QListViewItem(backupList, "Documents", "", "Documents/");
66 selectItem(documents); 66 selectItem(documents);
67 67
68 scanForApplicationSettings(); 68 scanForApplicationSettings();
69 69
70 OStorageInfo storage; 70 OStorageInfo storage;
71 71
72 backupLocations.insert( "Documents", QDir::homeDirPath() + "/Documents" ); 72 backupLocations.insert( "Documents", QDir::homeDirPath() + "/Documents" );
73 if ( storage.hasCf() ) 73 if ( storage.hasCf() )
74 { 74 {
75 backupLocations.insert( "CF", storage.cfPath() ); 75 backupLocations.insert( "CF", storage.cfPath() );
76 qDebug( "Cf Path: " + storage.cfPath() ); 76 qDebug( "Cf Path: " + storage.cfPath() );
77 } 77 }
78 if ( storage.hasSd() ) 78 if ( storage.hasSd() )
79 { 79 {
80 backupLocations.insert( "SD", storage.sdPath() ); 80 backupLocations.insert( "SD", storage.sdPath() );
81 qDebug( " Sd Path: " + storage.sdPath() ); 81 qDebug( " Sd Path: " + storage.sdPath() );
82 } 82 }
83 if ( storage.hasMmc() ) 83 if ( storage.hasMmc() )
84 { 84 {
85 backupLocations.insert( "MMC", storage.mmcPath() ); 85 backupLocations.insert( "MMC", storage.mmcPath() );
86 qDebug( "Mmc Path: " + storage.mmcPath() ); 86 qDebug( "Mmc Path: " + storage.mmcPath() );
87 } 87 }
88 88
89 Config config("BackupAndRestore"); 89 Config config("BackupAndRestore");
90 //read last locations 90 //read last locations
91 config.setGroup("LastLocation"); 91 config.setGroup("LastLocation");
92 QString lastStoreLocation = config.readEntry( "LastStoreLocation", "" ); 92 QString lastStoreLocation = config.readEntry( "LastStoreLocation", "" );
93 QString lastRestoreLocation = config.readEntry( "LastRestoreLocation", "" ); 93 QString lastRestoreLocation = config.readEntry( "LastRestoreLocation", "" );
94 int locationIndex = 0; 94 int locationIndex = 0;
95 95
96 QMap<QString, QString>::Iterator it; 96 QMap<QString, QString>::Iterator it;
97 for( it = backupLocations.begin(); it != backupLocations.end(); ++it ) 97 for( it = backupLocations.begin(); it != backupLocations.end(); ++it )
98 { 98 {
99 storeToLocation->insertItem(it.key()); 99 storeToLocation->insertItem(it.key());
100 restoreSource->insertItem(it.key()); 100 restoreSource->insertItem(it.key());
101 101
102 //check for last locations 102 //check for last locations
103 if ( it.key() == lastStoreLocation ) 103 if ( it.key() == lastStoreLocation )
104 storeToLocation->setCurrentItem( locationIndex ); 104 storeToLocation->setCurrentItem( locationIndex );
105 if ( it.key() == lastRestoreLocation ) 105 if ( it.key() == lastRestoreLocation )
106 restoreSource->setCurrentItem( locationIndex ); 106 restoreSource->setCurrentItem( locationIndex );
107 locationIndex++; 107 locationIndex++;
108 } 108 }
109 109
110 // Read the list of items to ignore. 110 // Read the list of items to ignore.
111 QList<QString> dontBackupList; 111 QList<QString> dontBackupList;
112 dontBackupList.setAutoDelete(true); 112 dontBackupList.setAutoDelete(true);
113 config.setGroup("DontBackup"); 113 config.setGroup("DontBackup");
114 int total = config.readNumEntry("Total", 0); 114 int total = config.readNumEntry("Total", 0);
115 for(int i = 0; i < total; i++) 115 for(int i = 0; i < total; i++)
116 { 116 {
117 dontBackupList.append(new QString(config.readEntry(QString("%1").arg(i), ""))); 117 dontBackupList.append(new QString(config.readEntry(QString("%1").arg(i), "")));
118 } 118 }
119 119
120 QList<QListViewItem> list; 120 QList<QListViewItem> list;
121 getAllItems(backupList->firstChild(), list); 121 getAllItems(backupList->firstChild(), list);
122 122
123 for(uint i = 0; i < list.count(); i++) 123 for(uint i = 0; i < list.count(); i++)
124 { 124 {
125 QString text = list.at(i)->text(HEADER_NAME); 125 QString text = list.at(i)->text(HEADER_NAME);
126 for(uint i2 = 0; i2 < dontBackupList.count(); i2++) 126 for(uint i2 = 0; i2 < dontBackupList.count(); i2++)
127 { 127 {
128 if(*dontBackupList.at(i2) == text) 128 if(*dontBackupList.at(i2) == text)
129 { 129 {
130 selectItem(list.at(i)); 130 selectItem(list.at(i));
131 break; 131 break;
132 } 132 }
133 } 133 }
134 } 134 }
135 QPEApplication::showWidget( this ); 135 QPEApplication::showWidget( this );
136} 136}
137 137
138BackupAndRestore::~BackupAndRestore() 138BackupAndRestore::~BackupAndRestore()
139{ 139{
140 QList<QListViewItem> list; 140 QList<QListViewItem> list;
141 getAllItems(backupList->firstChild(), list); 141 getAllItems(backupList->firstChild(), list);
142 142
143 Config config("BackupAndRestore"); 143 Config config("BackupAndRestore");
144 config.setGroup("DontBackup"); 144 config.setGroup("DontBackup");
145 config.clearGroup(); 145 config.clearGroup();
146 146
147 int count = 0; 147 int count = 0;
148 for(uint i = 0; i < list.count(); i++) 148 for(uint i = 0; i < list.count(); i++)
149 { 149 {
150 if(list.at(i)->text(HEADER_BACKUP) == "") 150 if(list.at(i)->text(HEADER_BACKUP) == "")
151 { 151 {
152 config.writeEntry(QString("%1").arg(count), list.at(i)->text(HEADER_NAME)); 152 config.writeEntry(QString("%1").arg(count), list.at(i)->text(HEADER_NAME));
153 count++; 153 count++;
154 } 154 }
155 } 155 }
156 config.writeEntry("Total", count); 156 config.writeEntry("Total", count);
157 157
158 // Remove Temp File 158 // Remove Temp File
159 if ( QFile::exists( tempFileName ) ) 159 if ( QFile::exists( tempFileName ) )
160 QFile::remove( tempFileName ); 160 QFile::remove( tempFileName );
161} 161}
162 162
163QList<QListViewItem> BackupAndRestore::getAllItems(QListViewItem *item, QList<QListViewItem> &list) 163QList<QListViewItem> BackupAndRestore::getAllItems(QListViewItem *item, QList<QListViewItem> &list)
164{ 164{
165 while(item) 165 while(item)
166 { 166 {
167 if(item->childCount() > 0) 167 if(item->childCount() > 0)
168 getAllItems(item->firstChild(), list); 168 getAllItems(item->firstChild(), list);
169 list.append(item); 169 list.append(item);
170 item = item->nextSibling(); 170 item = item->nextSibling();
171 } 171 }
172 return list; 172 return list;
173} 173}
174 174
175/** 175/**
176 * Selects and unselects the item by setting the HEADER_BACKUP to B or !. 176 * Selects and unselects the item by setting the HEADER_BACKUP to B or !.
177 * and changing the icon to match 177 * and changing the icon to match
178 * @param currentItem the item to swich the selection choice. 178 * @param currentItem the item to swich the selection choice.
179 */ 179 */
180void BackupAndRestore::selectItem(QListViewItem *currentItem) 180void BackupAndRestore::selectItem(QListViewItem *currentItem)
181{ 181{
182 if(!currentItem) 182 if(!currentItem)
183 return; 183 return;
184 184
185 if(currentItem->text(HEADER_BACKUP) == "B") 185 if(currentItem->text(HEADER_BACKUP) == "B")
186 { 186 {
187 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/null")); 187 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/null"));
188 currentItem->setText(HEADER_BACKUP, ""); 188 currentItem->setText(HEADER_BACKUP, "");
189 } 189 }
190 else 190 else
191 { 191 {
192 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/check")); 192 currentItem->setPixmap(HEADER_NAME, Resource::loadPixmap("backup/check"));
193 currentItem->setText(HEADER_BACKUP, "B"); 193 currentItem->setText(HEADER_BACKUP, "B");
194 } 194 }
195} 195}
196 196
197void BackupAndRestore::scanForApplicationSettings() 197void BackupAndRestore::scanForApplicationSettings()
198{ 198{
199 QDir d( QDir::homeDirPath() + "/" + QString( applicationSettings->text(BACKUP_LOCATION) ) ); 199 QDir d( QDir::homeDirPath() + "/" + QString( applicationSettings->text(BACKUP_LOCATION) ) );
200 d.setFilter( QDir::Dirs | QDir::Files | QDir::NoSymLinks ); 200 d.setFilter( QDir::Dirs | QDir::Files | QDir::NoSymLinks );
201 const QFileInfoList *list = d.entryInfoList(); 201 const QFileInfoList *list = d.entryInfoList();
202 QFileInfoListIterator it( *list ); 202 QFileInfoListIterator it( *list );
203 QFileInfo *fi; 203 QFileInfo *fi;
204 while ( (fi=it.current()) ) 204 while ( (fi=it.current()) )
205 { 205 {
206 //qDebug((d.path()+"/"+fi->fileName()).latin1()); 206 //qDebug((d.path()+"/"+fi->fileName()).latin1());
207 if ( ( fi->fileName() != "." ) && ( fi->fileName() != ".." ) ) 207 if ( ( fi->fileName() != "." ) && ( fi->fileName() != ".." ) )
208 { 208 {
209 QListViewItem *newItem = new QListViewItem(applicationSettings, fi->fileName()); 209 QListViewItem *newItem = new QListViewItem(applicationSettings, fi->fileName());
210 selectItem(newItem); 210 selectItem(newItem);
211 } 211 }
212 ++it; 212 ++it;
213 } 213 }
214} 214}
215 215
216/** 216/**
217 * The "Backup" button has been pressed. Get a list of all of the files that 217 * The "Backup" button has been pressed. Get a list of all of the files that
218 * should be backed up. If there are no files, emit and error and exit. 218 * should be backed up. If there are no files, emit and error and exit.
219 * Determine the file name to store the backup in. Backup the file(s) using 219 * Determine the file name to store the backup in. Backup the file(s) using
220 * tar and gzip --best. Report failure or success 220 * tar and gzip --best. Report failure or success
221 */ 221 */
222void BackupAndRestore::backup() 222void BackupAndRestore::backup()
223{ 223{
224 QString backupFiles; 224 QString backupFiles;
225 if(getBackupFiles(backupFiles, NULL) == 0) 225 if(getBackupFiles(backupFiles, NULL) == 0)
226 { 226 {
227 QMessageBox::critical(this, "Message", 227 QMessageBox::critical(this, "Message",
228 "No items selected.",QString("Ok") ); 228 "No items selected.",QString("Ok") );
229 return; 229 return;
230 } 230 }
231 231
232 setCaption(tr("Backup and Restore... working...")); 232 setCaption(tr("Backup and Restore... working..."));
233 QString outputFile = backupLocations[storeToLocation->currentText()]; 233 QString outputFile = backupLocations[storeToLocation->currentText()];
234 234
235 QDateTime datetime = QDateTime::currentDateTime(); 235 QDateTime datetime = QDateTime::currentDateTime();
236 QString dateString = QString::number( datetime.date().year() ) + QString::number( datetime.date().month() ).rightJustify(2, '0') + 236 QString dateString = QString::number( datetime.date().year() ) + QString::number( datetime.date().month() ).rightJustify(2, '0') +
237 QString::number( datetime.date().day() ).rightJustify(2, '0'); 237 QString::number( datetime.date().day() ).rightJustify(2, '0');
238 238
239 outputFile += "/" + dateString; 239 outputFile += "/" + dateString;
240 240
241 QString t = outputFile; 241 QString t = outputFile;
242 int c = 1; 242 int c = 1;
243 while(QFile::exists(outputFile + EXTENSION)) 243 while(QFile::exists(outputFile + EXTENSION))
244 { 244 {
245 outputFile = t + QString("%1").arg(c); 245 outputFile = t + QString("%1").arg(c);
246 c++; 246 c++;
247 } 247 }
248 248
249 // We execute tar and compressing its output with gzip.. 249 // We execute tar and compressing its output with gzip..
250 // The error output will be written into a temp-file which could be provided 250 // The error output will be written into a temp-file which could be provided
251 // for debugging.. 251 // for debugging..
252 qDebug( "Storing file: %s", outputFile.latin1() ); 252 qDebug( "Storing file: %s", outputFile.latin1() );
253 outputFile += EXTENSION; 253 outputFile += EXTENSION;
254 254
255 QString commandLine = QString( "(tar -C %1 -z --exclude=*.bck -c %2 > %3 ) 2> %4" ).arg( QDir::homeDirPath() ) 255 QString commandLine = QString( "(tar -C %1 -z --exclude=*.bck -c %2 > %3 ) 2> %4" ).arg( QDir::homeDirPath() )
256 .arg( backupFiles ) 256 .arg( backupFiles )
257 .arg( outputFile.latin1() ) 257 .arg( outputFile.latin1() )
258 .arg( tempFileName.latin1() ); 258 .arg( tempFileName.latin1() );
259 259
260 qDebug( commandLine ); 260 qDebug( commandLine );
261 261
262 int r = system( commandLine ); 262 int r = system( commandLine );
263 263
264 if(r != 0) 264 if(r != 0)
265 { 265 {
266 perror("Error: "); 266 perror("Error: ");
267 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno ); 267 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno );
268 268
269 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Backup Failed!" ) + "\n" 269 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Backup Failed!" ) + "\n"
270 + errorMsg, QString( tr( "Ok" ) ), QString( tr( "Details" ) ) ) ) 270 + errorMsg, QString( tr( "Ok" ) ), QString( tr( "Details" ) ) ) )
271 { 271 {
272 272
273 case 1: 273 case 1:
274 qWarning("Details pressed !"); 274 qWarning("Details pressed !");
275 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true ); 275 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true );
276 QFile errorFile( tempFileName ); 276 QFile errorFile( tempFileName );
277 if ( errorFile.open(IO_ReadOnly) ) 277 if ( errorFile.open(IO_ReadOnly) )
278 { 278 {
279 QTextStream t( &errorFile ); 279 QTextStream t( &errorFile );
280 QString s; 280 QString s;
281 while ( !t.eof() ) 281 while ( !t.eof() )
282 { // until end of file... 282 { // until end of file...
283 s += t.readLine(); // line of text excluding '\n' 283 s += t.readLine(); // line of text excluding '\n'
284 } 284 }
285 errorFile.close(); 285 errorFile.close();
286 286
287 pErrDialog->m_textarea->setText( s ); 287 pErrDialog->m_textarea->setText( s );
288 } 288 }
289 else 289 else
290 { 290 {
291 pErrDialog->m_textarea->setText( "Unable to open File: /tmp/backup.er" ); 291 pErrDialog->m_textarea->setText( "Unable to open File: /tmp/backup.er" );
292 } 292 }
293 QPEApplication::execDialog( pErrDialog ); 293 QPEApplication::execDialog( pErrDialog );
294 delete pErrDialog; 294 delete pErrDialog;
295 break; 295 break;
296 } 296 }
297 setCaption(tr("Backup and Restore.. Failed !!")); 297 setCaption(tr("Backup and Restore.. Failed !!"));
298 return; 298 return;
299 } 299 }
300 else 300 else
301 { 301 {
302 QMessageBox::information(this, tr( "Message" ), tr( "Backup Successful." ), QString(tr( "Ok" ) ) ); 302 QMessageBox::information(this, tr( "Message" ), tr( "Backup Successful." ), QString(tr( "Ok" ) ) );
303 303
304 } 304 }
305 305
306 //write store-location 306 //write store-location
307 Config config( "BackupAndRestore" ); 307 Config config( "BackupAndRestore" );
308 config.setGroup( "LastLocation" ); 308 config.setGroup( "LastLocation" );
309 config.writeEntry( "LastStoreLocation", storeToLocation->currentText() ); 309 config.writeEntry( "LastStoreLocation", storeToLocation->currentText() );
310 310
311 setCaption(tr("Backup and Restore")); 311 setCaption(tr("Backup and Restore"));
312} 312}
313 313
314/*** 314/***
315 * Get a list of all of the files to backup. 315 * Get a list of all of the files to backup.
316 */ 316 */
317int BackupAndRestore::getBackupFiles(QString &backupFiles, QListViewItem *parent) 317int BackupAndRestore::getBackupFiles(QString &backupFiles, QListViewItem *parent)
318{ 318{
319 QListViewItem * currentItem; 319 QListViewItem * currentItem;
320 QString currentHome; 320 QString currentHome;
321 if(!parent) 321 if(!parent)
322 currentItem = backupList->firstChild(); 322 currentItem = backupList->firstChild();
323 else 323 else
324 { 324 {
325 currentItem = parent->firstChild(); 325 currentItem = parent->firstChild();
326 currentHome = parent->text(BACKUP_LOCATION); 326 currentHome = parent->text(BACKUP_LOCATION);
327 } 327 }
328 328
329 uint count = 0; 329 uint count = 0;
330 while( currentItem != 0 ) 330 while( currentItem != 0 )
331 { 331 {
332 if(currentItem->text(HEADER_BACKUP) == "B" ) 332 if(currentItem->text(HEADER_BACKUP) == "B" )
333 { 333 {
334 if(currentItem->childCount() == 0 ) 334 if(currentItem->childCount() == 0 )
335 { 335 {
336 if(parent == NULL) 336 if(parent == NULL)
337 backupFiles += currentItem->text(BACKUP_LOCATION); 337 backupFiles += currentItem->text(BACKUP_LOCATION);
338 else 338 else
339 backupFiles += currentHome + currentItem->text(HEADER_NAME); 339 backupFiles += currentHome + currentItem->text(HEADER_NAME);
340 backupFiles += " "; 340 backupFiles += " ";
341 count++; 341 count++;
342 } 342 }
343 else 343 else
344 { 344 {
345 count += getBackupFiles(backupFiles, currentItem); 345 count += getBackupFiles(backupFiles, currentItem);
346 } 346 }
347 } 347 }
348 currentItem = currentItem->nextSibling(); 348 currentItem = currentItem->nextSibling();
349 } 349 }
350 return count; 350 return count;
351} 351}
352 352
353void BackupAndRestore::sourceDirChanged(int selection) 353void BackupAndRestore::sourceDirChanged(int selection)
354{ 354{
355 restoreList->clear(); 355 restoreList->clear();
356 rescanFolder(backupLocations[restoreSource->text(selection)]); 356 rescanFolder(backupLocations[restoreSource->text(selection)]);
357} 357}
358 358
359void BackupAndRestore::fileListUpdate() 359void BackupAndRestore::fileListUpdate()
360{ 360{
361 qWarning("void BackupAndRestore::fileListUpdate()"); 361 qWarning("void BackupAndRestore::fileListUpdate()");
362 restoreList->clear(); 362 restoreList->clear();
363 rescanFolder( backupLocations[restoreSource->currentText()] ); 363 rescanFolder( backupLocations[restoreSource->currentText()] );
364} 364}
365 365
366/** 366/**
367 * Scans directory for any backup files. Will recursivly go down, 367 * Scans directory for any backup files. Will recursivly go down,
368 * but will not follow symlinks. 368 * but will not follow symlinks.
369 * @param directory - the directory to look in. 369 * @param directory - the directory to look in.
370 */ 370 */
371void BackupAndRestore::rescanFolder(QString directory) 371void BackupAndRestore::rescanFolder(QString directory)
372{ 372{
373 //qDebug(QString("rescanFolder: ") + directory.latin1()); 373 //qDebug(QString("rescanFolder: ") + directory.latin1());
374 QDir d(directory); 374 QDir d(directory);
375 if(!d.exists()) 375 if(!d.exists())
376 return; 376 return;
377 377
378 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs); 378 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs);
379 const QFileInfoList *list = d.entryInfoList(); 379 const QFileInfoList *list = d.entryInfoList();
380 QFileInfoListIterator it( *list ); 380 QFileInfoListIterator it( *list );
381 QFileInfo *file; 381 QFileInfo *file;
382 while ( (file=it.current()) ) 382 while ( (file=it.current()) )
383 { // for each file... 383 { // for each file...
384 // If it is a dir and not .. or . then add it as a tab and go down. 384 // If it is a dir and not .. or . then add it as a tab and go down.
385 if(file->isDir()) 385 if(file->isDir())
386 { 386 {
387 if(file->fileName() != ".." && file->fileName() != ".") 387 if(file->fileName() != ".." && file->fileName() != ".")
388 { 388 {
389 rescanFolder(directory + "/" + file->fileName()); 389 rescanFolder(directory + "/" + file->fileName());
390 } 390 }
391 } 391 }
392 else 392 else
393 { 393 {
394 // If it is a backup file add to list. 394 // If it is a backup file add to list.
395 if(file->fileName().contains(EXTENSION)) 395 if(file->fileName().contains(EXTENSION))
396 (void)new QListViewItem(restoreList, file->fileName()); 396 (void)new QListViewItem(restoreList, file->fileName());
397 } 397 }
398 ++it; 398 ++it;
399 } 399 }
400} 400}
401 401
402/** 402/**
403 * Restore a backup file. 403 * Restore a backup file.
404 * Report errors or success 404 * Report errors or success
405 */ 405 */
406void BackupAndRestore::restore() 406void BackupAndRestore::restore()
407{ 407{
408 QListViewItem *restoreItem = restoreList->currentItem(); 408 QListViewItem *restoreItem = restoreList->currentItem();
409 if(!restoreItem) 409 if(!restoreItem)
410 { 410 {
411 QMessageBox::critical(this, tr( "Message" ), 411 QMessageBox::critical(this, tr( "Message" ),
412 tr( "Please select something to restore." ),QString( tr( "Ok") ) ); 412 tr( "Please select something to restore." ),QString( tr( "Ok") ) );
413 return; 413 return;
414 } 414 }
415 setCaption(tr("Backup and Restore... working...")); 415 setCaption(tr("Backup and Restore... working..."));
416 416
417 QString restoreFile = backupLocations[restoreSource->currentText()]; 417 QString restoreFile = backupLocations[restoreSource->currentText()];
418 418
419 restoreFile += "/" + restoreItem->text(0); 419 restoreFile += "/" + restoreItem->text(0);
420 420
421 qDebug( restoreFile ); 421 qDebug( restoreFile );
422 422
423 QString commandLine = QString( "tar -C %1 -zxf %2 2> %3" ).arg( QDir::homeDirPath() ) 423 QString commandLine = QString( "tar -C %1 -zxf %2 2> %3" ).arg( QDir::homeDirPath() )
424 .arg( restoreFile.latin1() ) 424 .arg( restoreFile.latin1() )
425 .arg( tempFileName.latin1() ); 425 .arg( tempFileName.latin1() );
426 426
427 qDebug( commandLine ); 427 qDebug( commandLine );
428 428
429 int r = system( commandLine ); 429 int r = system( commandLine );
430 430
431 if(r != 0) 431 if(r != 0)
432 { 432 {
433 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno ); 433 QString errorMsg= tr( "Error from System:\n" ) + (QString)strerror( errno );
434 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Restore Failed." ) + "\n" 434 switch( QMessageBox::critical(this, tr( "Message" ), tr( "Restore Failed." ) + "\n"
435 + errorMsg, QString( tr( "Ok") ), QString( tr( "Details" ) ) ) ) 435 + errorMsg, QString( tr( "Ok") ), QString( tr( "Details" ) ) ) )
436 { 436 {
437 case 1: 437 case 1:
438 qWarning("Details pressed !"); 438 qWarning("Details pressed !");
439 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true ); 439 ErrorDialog* pErrDialog = new ErrorDialog( this, NULL, true );
440 QFile errorFile( tempFileName ); 440 QFile errorFile( tempFileName );
441 if ( errorFile.open(IO_ReadOnly) ) 441 if ( errorFile.open(IO_ReadOnly) )
442 { 442 {
443 QTextStream t( &errorFile ); 443 QTextStream t( &errorFile );
444 QString s; 444 QString s;
445 while ( !t.eof() ) 445 while ( !t.eof() )
446 { // until end of file... 446 { // until end of file...
447 s += t.readLine(); // line of text excluding '\n' 447 s += t.readLine(); // line of text excluding '\n'
448 } 448 }
449 errorFile.close(); 449 errorFile.close();
450 450
451 pErrDialog->m_textarea->setText( s ); 451 pErrDialog->m_textarea->setText( s );
452 } 452 }
453 else 453 else
454 { 454 {
455 pErrDialog->m_textarea->setText( tr( "Unable to open File: %1" ).arg( "/tmp/backup.er" ) ); 455 pErrDialog->m_textarea->setText( tr( "Unable to open File: %1" ).arg( "/tmp/backup.er" ) );
456 } 456 }
457 QPEApplication::execDialog( pErrDialog ); 457 QPEApplication::execDialog( pErrDialog );
458 delete pErrDialog; 458 delete pErrDialog;
459 459
460 setCaption(tr("Backup and Restore.. Failed !!")); 460 setCaption(tr("Backup and Restore.. Failed !!"));
461 return; 461 return;
462 462
463 break; 463 break;
464 464
465 } 465 }
466 } 466 }
467 else 467 else
468 { 468 {
469 QMessageBox::information(this, tr( "Message" ), tr( "Restore Successful." ), QString( tr( "Ok") ) ); 469 QMessageBox::information(this, tr( "Message" ), tr( "Restore Successful." ), QString( tr( "Ok") ) );
470 } 470 }
471 471
472 //write restore-location 472 //write restore-location
473 Config config( "BackupAndRestore" ); 473 Config config( "BackupAndRestore" );
474 config.setGroup( "LastLocation" ); 474 config.setGroup( "LastLocation" );
475 config.writeEntry( "LastRestoreLocation", restoreSource->currentText() ); 475 config.writeEntry( "LastRestoreLocation", restoreSource->currentText() );
476 476
477 setCaption(tr("Backup and Restore")); 477 setCaption(tr("Backup and Restore"));
478} 478}
479 479
480// backuprestore.cpp 480// backuprestore.cpp
481 481
diff --git a/noncore/settings/netsystemtime/mainwindow.cpp b/noncore/settings/netsystemtime/mainwindow.cpp
index 7df41d4..c995d6e 100644
--- a/noncore/settings/netsystemtime/mainwindow.cpp
+++ b/noncore/settings/netsystemtime/mainwindow.cpp
@@ -1,396 +1,396 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 OPIE team <opie@handhelds.org?> 4             .=l. Copyright (c) 2002 OPIE team <opie@handhelds.org?>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "mainwindow.h" 29#include "mainwindow.h"
30#include "timetabwidget.h" 30#include "timetabwidget.h"
31#include "formattabwidget.h" 31#include "formattabwidget.h"
32#include "settingstabwidget.h" 32#include "settingstabwidget.h"
33#include "ntptabwidget.h" 33#include "ntptabwidget.h"
34#include "predicttabwidget.h" 34#include "predicttabwidget.h"
35 35
36#include <qpe/config.h> 36#include <qpe/config.h>
37#include <qpe/datebookdb.h> 37#include <qpe/datebookdb.h>
38#include <qpe/qpeapplication.h> 38#include <qpe/qpeapplication.h>
39#include <qpe/qpedialog.h> 39#include <qpe/qpedialog.h>
40 40
41#if ( defined Q_WS_QWS || defined(_WS_QWS_) ) && !defined(QT_NO_COP) 41#if ( defined Q_WS_QWS || defined(_WS_QWS_) ) && !defined(QT_NO_COP)
42#include <qpe/qcopenvelope_qws.h> 42#include <qpe/qcopenvelope_qws.h>
43#endif 43#endif
44 44
45#include <qlayout.h> 45#include <qlayout.h>
46#include <qmessagebox.h> 46#include <qmessagebox.h>
47#include <qsocket.h> 47#include <qsocket.h>
48#include <qstring.h> 48#include <qstring.h>
49#include <qtimer.h> 49#include <qtimer.h>
50 50
51MainWindow::MainWindow( QWidget *parent , const char *name, bool modal, WFlags f ) 51MainWindow::MainWindow( QWidget *parent , const char *name, bool modal, WFlags f )
52 : QDialog( 0x0, 0x0, TRUE, 0 ) 52 : QDialog( 0x0, 0x0, TRUE, 0 )
53{ 53{
54 setCaption( tr( "SystemTime" ) ); 54 setCaption( tr( "SystemTime" ) );
55 55
56 QVBoxLayout *layout = new QVBoxLayout( this ); 56 QVBoxLayout *layout = new QVBoxLayout( this );
57 layout->setMargin( 2 ); 57 layout->setMargin( 2 );
58 layout->setSpacing( 4 ); 58 layout->setSpacing( 4 );
59 59
60 // Create main tabbed control 60 // Create main tabbed control
61 mainWidget = new OTabWidget( this ); 61 mainWidget = new OTabWidget( this );
62 62
63 // Default object pointers to null 63 // Default object pointers to null
64 ntpProcess = 0x0; 64 ntpProcess = 0x0;
65 ntpTab = 0x0; 65 ntpTab = 0x0;
66 66
67 // Add tab widgets 67 // Add tab widgets
68 mainWidget->addTab( timeTab = new TimeTabWidget( mainWidget ), "netsystemtime/DateTime", tr( "Time" ) ); 68 mainWidget->addTab( timeTab = new TimeTabWidget( mainWidget ), "netsystemtime/DateTime", tr( "Time" ) );
69 mainWidget->addTab( formatTab = new FormatTabWidget( mainWidget ), "netsystemtime/formattab", tr( "Format" ) ); 69 mainWidget->addTab( formatTab = new FormatTabWidget( mainWidget ), "netsystemtime/formattab", tr( "Format" ) );
70 mainWidget->addTab( settingsTab = new SettingsTabWidget( mainWidget ), "SettingsIcon", tr( "Settings" ) ); 70 mainWidget->addTab( settingsTab = new SettingsTabWidget( mainWidget ), "SettingsIcon", tr( "Settings" ) );
71 mainWidget->addTab( predictTab = new PredictTabWidget( mainWidget ), "netsystemtime/predicttab", tr( "Predict" ) ); 71 mainWidget->addTab( predictTab = new PredictTabWidget( mainWidget ), "netsystemtime/predicttab", tr( "Predict" ) );
72 Config config( "ntp" ); 72 Config config( "ntp" );
73 config.setGroup( "settings" ); 73 config.setGroup( "settings" );
74 slotDisplayNTPTab( config.readBoolEntry( "displayNtpTab", FALSE ) ); 74 slotDisplayNTPTab( config.readBoolEntry( "displayNtpTab", FALSE ) );
75 slotDisplayPredictTab( config.readBoolEntry( "displayPredictTab", FALSE ) ); 75 slotDisplayPredictTab( config.readBoolEntry( "displayPredictTab", FALSE ) );
76 76
77 mainWidget->setCurrentTab( tr( "Time" ) ); 77 mainWidget->setCurrentTab( tr( "Time" ) );
78 layout->addWidget( mainWidget ); 78 layout->addWidget( mainWidget );
79 79
80 connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), 80 connect( qApp, SIGNAL(appMessage(const QCString&,const QByteArray&)),
81 this, SLOT(slotQCopReceive(const QCString&, const QByteArray&)) ); 81 this, SLOT(slotQCopReceive(const QCString&,const QByteArray&)) );
82 82
83 83
84 // Create NTP socket 84 // Create NTP socket
85 ntpSock = new QSocket( this ); 85 ntpSock = new QSocket( this );
86 connect( ntpSock, SIGNAL(error(int)),SLOT(slotCheckNtp(int)) ); 86 connect( ntpSock, SIGNAL(error(int)),SLOT(slotCheckNtp(int)) );
87 slotProbeNTPServer(); 87 slotProbeNTPServer();
88 88
89 // Create timer for automatic time lookups 89 // Create timer for automatic time lookups
90 ntpTimer = new QTimer( this ); 90 ntpTimer = new QTimer( this );
91 91
92 // Connect everything together 92 // Connect everything together
93 connect( timeTab, SIGNAL(getNTPTime()), this, SLOT(slotGetNTPTime()) ); 93 connect( timeTab, SIGNAL(getNTPTime()), this, SLOT(slotGetNTPTime()) );
94 connect( timeTab, SIGNAL(tzChanged(const QString &)), predictTab, SLOT(slotTZChanged(const QString &)) ); 94 connect( timeTab, SIGNAL(tzChanged(const QString&)), predictTab, SLOT(slotTZChanged(const QString&)) );
95 connect( timeTab, SIGNAL(getPredictedTime()), predictTab, SLOT(slotSetPredictedTime()) ); 95 connect( timeTab, SIGNAL(getPredictedTime()), predictTab, SLOT(slotSetPredictedTime()) );
96 connect( formatTab, SIGNAL(show12HourTime(int)), timeTab, SLOT(slotUse12HourTime( int )) ); 96 connect( formatTab, SIGNAL(show12HourTime(int)), timeTab, SLOT(slotUse12HourTime(int)) );
97 connect( formatTab, SIGNAL(dateFormatChanged(const DateFormat &)), 97 connect( formatTab, SIGNAL(dateFormatChanged(const DateFormat&)),
98 timeTab, SLOT(slotDateFormatChanged(const DateFormat &)) ); 98 timeTab, SLOT(slotDateFormatChanged(const DateFormat&)) );
99 connect( formatTab, SIGNAL(weekStartChanged(int)), timeTab, SLOT(slotWeekStartChanged(int)) ); 99 connect( formatTab, SIGNAL(weekStartChanged(int)), timeTab, SLOT(slotWeekStartChanged(int)) );
100 connect( settingsTab, SIGNAL(ntpDelayChanged(int)), this, SLOT(slotNTPDelayChanged(int)) ); 100 connect( settingsTab, SIGNAL(ntpDelayChanged(int)), this, SLOT(slotNTPDelayChanged(int)) );
101 connect( settingsTab, SIGNAL(displayNTPTab(bool)), this, SLOT(slotDisplayNTPTab(bool)) ); 101 connect( settingsTab, SIGNAL(displayNTPTab(bool)), this, SLOT(slotDisplayNTPTab(bool)) );
102 connect( settingsTab, SIGNAL(displayPredictTab(bool)), this, SLOT(slotDisplayPredictTab(bool)) ); 102 connect( settingsTab, SIGNAL(displayPredictTab(bool)), this, SLOT(slotDisplayPredictTab(bool)) );
103 connect( predictTab, SIGNAL(setTime(const QDateTime &)), this, SLOT(slotSetTime(const QDateTime &)) ); 103 connect( predictTab, SIGNAL(setTime(const QDateTime&)), this, SLOT(slotSetTime(const QDateTime&)) );
104 104
105 // Do initial time server check 105 // Do initial time server check
106 slotNTPDelayChanged( config.readNumEntry( "ntpRefreshFreq", 1440 ) ); 106 slotNTPDelayChanged( config.readNumEntry( "ntpRefreshFreq", 1440 ) );
107 slotCheckNtp( -1 ); 107 slotCheckNtp( -1 );
108 108
109 // Display app 109 // Display app
110 //showMaximized(); 110 //showMaximized();
111 (void)new QPEDialogListener(this); 111 (void)new QPEDialogListener(this);
112} 112}
113 113
114MainWindow::~MainWindow() 114MainWindow::~MainWindow()
115{ 115{
116 if ( ntpProcess ) 116 if ( ntpProcess )
117 delete ntpProcess; 117 delete ntpProcess;
118} 118}
119 119
120void MainWindow::accept() 120void MainWindow::accept()
121{ 121{
122 // Turn off the screensaver (Note: needs to be encased in { } so that it deconstructs and sends) 122 // Turn off the screensaver (Note: needs to be encased in { } so that it deconstructs and sends)
123 { 123 {
124 QCopEnvelope disableScreenSaver( "QPE/System", "setScreenSaverIntervals(int,int,int)" ); 124 QCopEnvelope disableScreenSaver( "QPE/System", "setScreenSaverIntervals(int,int,int)" );
125 disableScreenSaver << 0 << 0 << 0; 125 disableScreenSaver << 0 << 0 << 0;
126 } 126 }
127 127
128 // Update the systemtime 128 // Update the systemtime
129 timeTab->saveSettings( TRUE ); 129 timeTab->saveSettings( TRUE );
130 130
131 // Save format options 131 // Save format options
132 formatTab->saveSettings( TRUE ); 132 formatTab->saveSettings( TRUE );
133 133
134 // Save settings options 134 // Save settings options
135 settingsTab->saveSettings(); 135 settingsTab->saveSettings();
136 136
137 // Since time has changed quickly load in the DateBookDB to allow the alarm server to get a better 137 // Since time has changed quickly load in the DateBookDB to allow the alarm server to get a better
138 // grip on itself (example re-trigger alarms for when we travel back in time). 138 // grip on itself (example re-trigger alarms for when we travel back in time).
139 DateBookDB db; 139 DateBookDB db;
140 140
141 // Turn back on the screensaver 141 // Turn back on the screensaver
142 QCopEnvelope enableScreenSaver( "QPE/System", "setScreenSaverIntervals(int,int,int)" ); 142 QCopEnvelope enableScreenSaver( "QPE/System", "setScreenSaverIntervals(int,int,int)" );
143 enableScreenSaver << -1 << -1 << -1; 143 enableScreenSaver << -1 << -1 << -1;
144 144
145 // Exit app 145 // Exit app
146 qApp->quit(); 146 qApp->quit();
147} 147}
148 148
149void MainWindow::reject() 149void MainWindow::reject()
150{ 150{
151 // Reset time settings 151 // Reset time settings
152 timeTab->saveSettings( FALSE ); 152 timeTab->saveSettings( FALSE );
153 153
154 // Send notifications but do not save settings 154 // Send notifications but do not save settings
155 formatTab->saveSettings( FALSE ); 155 formatTab->saveSettings( FALSE );
156 156
157 // Exit app 157 // Exit app
158 qApp->quit(); 158 qApp->quit();
159} 159}
160 160
161void MainWindow::runNTP() 161void MainWindow::runNTP()
162{ 162{
163 if ( !ntpDelayElapsed() && ntpInteractive ) 163 if ( !ntpDelayElapsed() && ntpInteractive )
164 { 164 {
165 QString msg = tr( "You asked for a delay of %1 minutes, but only %2 minutes elapsed since last lookup.<br>Continue?" ).arg( QString::number( ntpDelay ) ).arg( QString::number( _lookupDiff / 60 ) ); 165 QString msg = tr( "You asked for a delay of %1 minutes, but only %2 minutes elapsed since last lookup.<br>Continue?" ).arg( QString::number( ntpDelay ) ).arg( QString::number( _lookupDiff / 60 ) );
166 166
167 switch ( 167 switch (
168 QMessageBox::warning( this, tr( "Continue?" ), msg, QMessageBox::Yes, QMessageBox::No ) 168 QMessageBox::warning( this, tr( "Continue?" ), msg, QMessageBox::Yes, QMessageBox::No )
169 ) 169 )
170 { 170 {
171 case QMessageBox::Yes: break; 171 case QMessageBox::Yes: break;
172 case QMessageBox::No: return; 172 case QMessageBox::No: return;
173 default: return; 173 default: return;
174 } 174 }
175 } 175 }
176 176
177 QString srv = settingsTab->ntpServer(); 177 QString srv = settingsTab->ntpServer();
178 178
179 // Send information to time server tab if enabled 179 // Send information to time server tab if enabled
180 if ( ntpTabEnabled ) 180 if ( ntpTabEnabled )
181 { 181 {
182 ntpTab->setStartTime( QDateTime::currentDateTime().toString() ); 182 ntpTab->setStartTime( QDateTime::currentDateTime().toString() );
183 QString output = tr( "Running:\nntpdate " ); 183 QString output = tr( "Running:\nntpdate " );
184 output.append( srv ); 184 output.append( srv );
185 ntpTab->addNtpOutput( output ); 185 ntpTab->addNtpOutput( output );
186 } 186 }
187 187
188 if ( !ntpProcess ) 188 if ( !ntpProcess )
189 { 189 {
190 ntpProcess = new OProcess(); 190 ntpProcess = new OProcess();
191 connect( ntpProcess, SIGNAL(receivedStdout(OProcess*,char*,int)), 191 connect( ntpProcess, SIGNAL(receivedStdout(OProcess*,char*,int)),
192 this, SLOT(slotNtpOutput(OProcess*,char*,int)) ); 192 this, SLOT(slotNtpOutput(OProcess*,char*,int)) );
193 connect( ntpProcess, SIGNAL(processExited(OProcess*)), 193 connect( ntpProcess, SIGNAL(processExited(OProcess*)),
194 this, SLOT(slotNtpFinished(OProcess*)) ); 194 this, SLOT(slotNtpFinished(OProcess*)) );
195 } 195 }
196 196
197 else 197 else
198 ntpProcess->clearArguments(); 198 ntpProcess->clearArguments();
199 199
200 *ntpProcess << "ntpdate" << srv; 200 *ntpProcess << "ntpdate" << srv;
201 bool ret = ntpProcess->start( OProcess::NotifyOnExit, OProcess::AllOutput ); 201 bool ret = ntpProcess->start( OProcess::NotifyOnExit, OProcess::AllOutput );
202 if ( !ret ) 202 if ( !ret )
203 { 203 {
204 QMessageBox::critical( this, tr( "Error" ), tr( "Error while getting time from network." ) ); 204 QMessageBox::critical( this, tr( "Error" ), tr( "Error while getting time from network." ) );
205 if ( ntpTabEnabled ) 205 if ( ntpTabEnabled )
206 ntpTab->addNtpOutput( tr( "Error while executing ntpdate" ) ); 206 ntpTab->addNtpOutput( tr( "Error while executing ntpdate" ) );
207 } 207 }
208} 208}
209 209
210bool MainWindow::ntpDelayElapsed() 210bool MainWindow::ntpDelayElapsed()
211{ 211{
212 // Determine if time elapsed is greater than time delay 212 // Determine if time elapsed is greater than time delay
213 Config config( "ntp" ); 213 Config config( "ntp" );
214 config.setGroup( "lookups" ); 214 config.setGroup( "lookups" );
215 _lookupDiff = TimeConversion::toUTC( QDateTime::currentDateTime() ) - config.readNumEntry( "time", 0 ); 215 _lookupDiff = TimeConversion::toUTC( QDateTime::currentDateTime() ) - config.readNumEntry( "time", 0 );
216 if ( _lookupDiff < 0 ) 216 if ( _lookupDiff < 0 )
217 return true; 217 return true;
218 return ( _lookupDiff - ( ntpDelay * 60) ) > 0; 218 return ( _lookupDiff - ( ntpDelay * 60) ) > 0;
219} 219}
220 220
221void MainWindow::slotSetTime( const QDateTime &dt ) 221void MainWindow::slotSetTime( const QDateTime &dt )
222{ 222{
223 timeTab->setDateTime( dt ); 223 timeTab->setDateTime( dt );
224} 224}
225 225
226void MainWindow::slotQCopReceive( const QCString &msg, const QByteArray & ) 226void MainWindow::slotQCopReceive( const QCString &msg, const QByteArray & )
227{ 227{
228 if ( msg == "ntpLookup(QString)" ) 228 if ( msg == "ntpLookup(QString)" )
229 { 229 {
230 ntpInteractive = false; 230 ntpInteractive = false;
231 runNTP(); 231 runNTP();
232 } 232 }
233 if ( msg == "setPredictedTime(QString)" ) 233 if ( msg == "setPredictedTime(QString)" )
234 { 234 {
235 //setPredictTime(); 235 //setPredictTime();
236 } 236 }
237} 237}
238 238
239void MainWindow::slotDisplayNTPTab( bool display ) 239void MainWindow::slotDisplayNTPTab( bool display )
240{ 240{
241 ntpTabEnabled = display; 241 ntpTabEnabled = display;
242 242
243 // Create widget if it hasn't needed 243 // Create widget if it hasn't needed
244 if ( display && !ntpTab ) 244 if ( display && !ntpTab )
245 { 245 {
246 ntpTab = new NTPTabWidget( mainWidget ); 246 ntpTab = new NTPTabWidget( mainWidget );
247 connect( ntpTab, SIGNAL(getNTPTime()), this, SLOT(slotGetNTPTime()) ); 247 connect( ntpTab, SIGNAL(getNTPTime()), this, SLOT(slotGetNTPTime()) );
248 } 248 }
249 249
250 // Display/hide tab 250 // Display/hide tab
251 display ? mainWidget->addTab( ntpTab, "netsystemtime/ntptab", tr( "Time Server" ) ) 251 display ? mainWidget->addTab( ntpTab, "netsystemtime/ntptab", tr( "Time Server" ) )
252 : mainWidget->removePage( ntpTab ); 252 : mainWidget->removePage( ntpTab );
253} 253}
254 254
255void MainWindow::slotDisplayPredictTab( bool display ) 255void MainWindow::slotDisplayPredictTab( bool display )
256{ 256{
257 predictTabEnabled = display; 257 predictTabEnabled = display;
258 258
259 // Create widget if it hasn't needed 259 // Create widget if it hasn't needed
260 if ( display && !predictTab ) 260 if ( display && !predictTab )
261 { 261 {
262 } 262 }
263 // Display/hide tab 263 // Display/hide tab
264 display ? mainWidget->addTab( predictTab, "netsystemtime/predicttab", tr( "Predict" ) ) 264 display ? mainWidget->addTab( predictTab, "netsystemtime/predicttab", tr( "Predict" ) )
265 : mainWidget->removePage( predictTab ); 265 : mainWidget->removePage( predictTab );
266} 266}
267 267
268void MainWindow::slotGetNTPTime() 268void MainWindow::slotGetNTPTime()
269{ 269{
270 ntpInteractive = TRUE; 270 ntpInteractive = TRUE;
271 runNTP(); 271 runNTP();
272} 272}
273 273
274void MainWindow::slotTimerGetNTPTime() 274void MainWindow::slotTimerGetNTPTime()
275{ 275{
276 ntpInteractive = FALSE; 276 ntpInteractive = FALSE;
277 runNTP(); 277 runNTP();
278} 278}
279 279
280void MainWindow::slotProbeNTPServer() 280void MainWindow::slotProbeNTPServer()
281{ 281{
282 ntpSock->connectToHost( settingsTab->ntpServer(), 123 ); 282 ntpSock->connectToHost( settingsTab->ntpServer(), 123 );
283} 283}
284 284
285void MainWindow::slotNtpOutput( OProcess *, char *buffer, int buflen ) 285void MainWindow::slotNtpOutput( OProcess *, char *buffer, int buflen )
286{ 286{
287 QString output = QString( buffer ).left( buflen ); 287 QString output = QString( buffer ).left( buflen );
288 ntpOutput.append( output ); 288 ntpOutput.append( output );
289 289
290 if ( ntpTabEnabled ) 290 if ( ntpTabEnabled )
291 ntpTab->addNtpOutput( output ); 291 ntpTab->addNtpOutput( output );
292} 292}
293 293
294void MainWindow::slotNtpFinished( OProcess *p ) 294void MainWindow::slotNtpFinished( OProcess *p )
295{ 295{
296 QString output; 296 QString output;
297 QDateTime dt = QDateTime::currentDateTime(); 297 QDateTime dt = QDateTime::currentDateTime();
298 298
299 // Verify run was successful 299 // Verify run was successful
300 if ( p->exitStatus() != 0 || !p->normalExit() ) 300 if ( p->exitStatus() != 0 || !p->normalExit() )
301 { 301 {
302 if ( isVisible() && ntpInteractive ) 302 if ( isVisible() && ntpInteractive )
303 { 303 {
304 output = tr( "Error while getting time from\n server: " ); 304 output = tr( "Error while getting time from\n server: " );
305 output.append( settingsTab->ntpServer() ); 305 output.append( settingsTab->ntpServer() );
306 QMessageBox::critical(this, tr( "Error" ), output ); 306 QMessageBox::critical(this, tr( "Error" ), output );
307 } 307 }
308 // slotCheckNtp(-1); 308 // slotCheckNtp(-1);
309 return; 309 return;
310 } 310 }
311 311
312 // Set controls on time tab to new time value 312 // Set controls on time tab to new time value
313 timeTab->setDateTime( dt ); 313 timeTab->setDateTime( dt );
314 314
315 // Write out lookup information 315 // Write out lookup information
316 Config config( "ntp" ); 316 Config config( "ntp" );
317 config.setGroup( "lookups" ); 317 config.setGroup( "lookups" );
318 int lastLookup = config.readNumEntry( "time", 0 ); 318 int lastLookup = config.readNumEntry( "time", 0 );
319 int lookupCount = config.readNumEntry( "count", 0 ); 319 int lookupCount = config.readNumEntry( "count", 0 );
320 bool lastNtp = config.readBoolEntry( "lastNtp", FALSE ); 320 bool lastNtp = config.readBoolEntry( "lastNtp", FALSE );
321 int time = TimeConversion::toUTC( QDateTime::currentDateTime() ); 321 int time = TimeConversion::toUTC( QDateTime::currentDateTime() );
322 config.writeEntry( "time", time ); 322 config.writeEntry( "time", time );
323 323
324 // Calculate new time/time shift 324 // Calculate new time/time shift
325 QString _offset = "offset"; 325 QString _offset = "offset";
326 QString _sec = "sec"; 326 QString _sec = "sec";
327 QRegExp _reOffset = QRegExp( _offset ); 327 QRegExp _reOffset = QRegExp( _offset );
328 QRegExp _reEndOffset = QRegExp( _sec ); 328 QRegExp _reEndOffset = QRegExp( _sec );
329 int posOffset = _reOffset.match( ntpOutput ); 329 int posOffset = _reOffset.match( ntpOutput );
330 int posEndOffset = _reEndOffset.match( ntpOutput, posOffset ); 330 int posEndOffset = _reEndOffset.match( ntpOutput, posOffset );
331 posOffset += _offset.length() + 1; 331 posOffset += _offset.length() + 1;
332 QString diff = ntpOutput.mid( posOffset, posEndOffset - posOffset - 1 ); 332 QString diff = ntpOutput.mid( posOffset, posEndOffset - posOffset - 1 );
333 333
334 float timeShift = diff.toFloat(); 334 float timeShift = diff.toFloat();
335 if ( timeShift == 0.0 ) 335 if ( timeShift == 0.0 )
336 return; 336 return;
337 int secsSinceLast = time - lastLookup; 337 int secsSinceLast = time - lastLookup;
338 output = tr( "%1 seconds").arg(QString::number( timeShift )); 338 output = tr( "%1 seconds").arg(QString::number( timeShift ));
339 339
340 // Display information on time server tab 340 // Display information on time server tab
341 if ( ntpTabEnabled ) 341 if ( ntpTabEnabled )
342 { 342 {
343 ntpTab->setTimeShift( output ); 343 ntpTab->setTimeShift( output );
344 ntpTab->setNewTime( dt.toString() ); 344 ntpTab->setNewTime( dt.toString() );
345 } 345 }
346 346
347 if ( lastNtp && lastLookup > 0 && secsSinceLast > 60 * ntpDelay ) 347 if ( lastNtp && lastLookup > 0 && secsSinceLast > 60 * ntpDelay )
348 { 348 {
349 QString grpname = QString( "lookup_" ).append( QString::number( lookupCount ) ); 349 QString grpname = QString( "lookup_" ).append( QString::number( lookupCount ) );
350 config.setGroup( grpname ); 350 config.setGroup( grpname );
351 lookupCount++; 351 lookupCount++;
352 predictTab->setShiftPerSec( timeShift / secsSinceLast ); 352 predictTab->setShiftPerSec( timeShift / secsSinceLast );
353 config.writeEntry( "secsSinceLast", secsSinceLast ); 353 config.writeEntry( "secsSinceLast", secsSinceLast );
354 config.writeEntry( "timeShift", QString::number( timeShift ) ); 354 config.writeEntry( "timeShift", QString::number( timeShift ) );
355 config.setGroup( "lookups" ); 355 config.setGroup( "lookups" );
356 config.writeEntry( "count", lookupCount ); 356 config.writeEntry( "count", lookupCount );
357 config.writeEntry( "lastNtp", TRUE ); 357 config.writeEntry( "lastNtp", TRUE );
358 } 358 }
359} 359}
360 360
361void MainWindow::slotNTPDelayChanged( int delay ) 361void MainWindow::slotNTPDelayChanged( int delay )
362{ 362{
363 ntpTimer->changeInterval( delay * 1000 * 60 ); 363 ntpTimer->changeInterval( delay * 1000 * 60 );
364 ntpDelay = delay; 364 ntpDelay = delay;
365} 365}
366 366
367void MainWindow::slotCheckNtp( int i ) 367void MainWindow::slotCheckNtp( int i )
368{ 368{
369 if ( i == 0 ) 369 if ( i == 0 )
370 { 370 {
371 if ( ntpDelayElapsed() ) 371 if ( ntpDelayElapsed() )
372 { 372 {
373 runNTP(); 373 runNTP();
374 disconnect( ntpTimer, SIGNAL(timeout()), this, SLOT(slotProbeNTPServer()) ); 374 disconnect( ntpTimer, SIGNAL(timeout()), this, SLOT(slotProbeNTPServer()) );
375 connect( ntpTimer, SIGNAL(timeout()), SLOT(slotTimerGetNTPTime()) ); 375 connect( ntpTimer, SIGNAL(timeout()), SLOT(slotTimerGetNTPTime()) );
376 } 376 }
377 else 377 else
378 { 378 {
379 disconnect(ntpTimer, SIGNAL(timeout()), this, SLOT(slotTimerGetNTPTime()) ); 379 disconnect(ntpTimer, SIGNAL(timeout()), this, SLOT(slotTimerGetNTPTime()) );
380 connect(ntpTimer, SIGNAL(timeout()), SLOT(slotProbeNTPServer()) ); 380 connect(ntpTimer, SIGNAL(timeout()), SLOT(slotProbeNTPServer()) );
381 } 381 }
382 } 382 }
383 else 383 else
384 { 384 {
385 predictTab->slotPredictTime(); 385 predictTab->slotPredictTime();
386 if ( i > 0 ) 386 if ( i > 0 )
387 { 387 {
388 QString output = tr( "Could not connect to server " ); 388 QString output = tr( "Could not connect to server " );
389 output.append( settingsTab->ntpServer() ); 389 output.append( settingsTab->ntpServer() );
390 ntpOutput.append( output ); 390 ntpOutput.append( output );
391 if ( ntpTabEnabled ) 391 if ( ntpTabEnabled )
392 ntpTab->addNtpOutput( output ); 392 ntpTab->addNtpOutput( output );
393 } 393 }
394 connect( ntpTimer, SIGNAL(timeout()), SLOT(slotProbeNTPServer()) ); 394 connect( ntpTimer, SIGNAL(timeout()), SLOT(slotProbeNTPServer()) );
395 } 395 }
396} 396}
diff --git a/noncore/settings/netsystemtime/settingstabwidget.cpp b/noncore/settings/netsystemtime/settingstabwidget.cpp
index 2a7e28d..ad80e05 100644
--- a/noncore/settings/netsystemtime/settingstabwidget.cpp
+++ b/noncore/settings/netsystemtime/settingstabwidget.cpp
@@ -1,159 +1,159 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 OPIE team <opie@handhelds.org?> 4             .=l. Copyright (c) 2002 OPIE team <opie@handhelds.org?>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "settingstabwidget.h" 29#include "settingstabwidget.h"
30 30
31#include <qpe/config.h> 31#include <qpe/config.h>
32#include <qpe/qpeapplication.h> 32#include <qpe/qpeapplication.h>
33 33
34#include <qcheckbox.h> 34#include <qcheckbox.h>
35#include <qcombobox.h> 35#include <qcombobox.h>
36#include <qlabel.h> 36#include <qlabel.h>
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qscrollview.h> 38#include <qscrollview.h>
39#include <qspinbox.h> 39#include <qspinbox.h>
40 40
41SettingsTabWidget::SettingsTabWidget( QWidget *parent ) 41SettingsTabWidget::SettingsTabWidget( QWidget *parent )
42 : QWidget( parent, 0x0, 0 ) 42 : QWidget( parent, 0x0, 0 )
43{ 43{
44 QVBoxLayout *tmpvb = new QVBoxLayout( this ); 44 QVBoxLayout *tmpvb = new QVBoxLayout( this );
45 QScrollView *sv = new QScrollView( this ); 45 QScrollView *sv = new QScrollView( this );
46 tmpvb->addWidget( sv, 0, 0 ); 46 tmpvb->addWidget( sv, 0, 0 );
47 sv->setResizePolicy( QScrollView::AutoOneFit ); 47 sv->setResizePolicy( QScrollView::AutoOneFit );
48 sv->setFrameStyle( QFrame::NoFrame ); 48 sv->setFrameStyle( QFrame::NoFrame );
49 QWidget *container = new QWidget( sv->viewport() ); 49 QWidget *container = new QWidget( sv->viewport() );
50 sv->addChild( container ); 50 sv->addChild( container );
51 51
52 QGridLayout *layout = new QGridLayout( container ); 52 QGridLayout *layout = new QGridLayout( container );
53 layout->setMargin( 2 ); 53 layout->setMargin( 2 );
54 layout->setSpacing( 4 ); 54 layout->setSpacing( 4 );
55 55
56 // Time server selector 56 // Time server selector
57 layout->addWidget( new QLabel( tr( "Time server" ), container ), 0, 0 ); 57 layout->addWidget( new QLabel( tr( "Time server" ), container ), 0, 0 );
58 cbTimeServer = new QComboBox( TRUE, container ); 58 cbTimeServer = new QComboBox( TRUE, container );
59 layout->addMultiCellWidget( cbTimeServer, 1, 1, 0, 1 ); 59 layout->addMultiCellWidget( cbTimeServer, 1, 1, 0, 1 );
60 60
61 // Lookup delay selector 61 // Lookup delay selector
62 layout->addWidget( new QLabel( tr( "minutes between time updates" ), container ), 2, 1 ); 62 layout->addWidget( new QLabel( tr( "minutes between time updates" ), container ), 2, 1 );
63 sbNtpDelay = new QSpinBox( 1, 9999999, 1, container ); 63 sbNtpDelay = new QSpinBox( 1, 9999999, 1, container );
64 sbNtpDelay->setWrapping( TRUE ); 64 sbNtpDelay->setWrapping( TRUE );
65 sbNtpDelay->setMaximumWidth( 50 ); 65 sbNtpDelay->setMaximumWidth( 50 );
66 connect( sbNtpDelay, SIGNAL(valueChanged(int)), this, SIGNAL(ntpDelayChanged(int)) ); 66 connect( sbNtpDelay, SIGNAL(valueChanged(int)), this, SIGNAL(ntpDelayChanged(int)) );
67 layout->addWidget( sbNtpDelay, 2, 0 ); 67 layout->addWidget( sbNtpDelay, 2, 0 );
68 68
69 // Prediction delay selector 69 // Prediction delay selector
70 layout->addWidget( new QLabel( tr( "minutes between prediction updates" ), container ), 3, 1 ); 70 layout->addWidget( new QLabel( tr( "minutes between prediction updates" ), container ), 3, 1 );
71 sbPredictDelay = new QSpinBox( 42, 9999999, 1, container ); 71 sbPredictDelay = new QSpinBox( 42, 9999999, 1, container );
72 sbPredictDelay->setWrapping( TRUE ); 72 sbPredictDelay->setWrapping( TRUE );
73 sbPredictDelay->setMaximumWidth( 50 ); 73 sbPredictDelay->setMaximumWidth( 50 );
74 layout->addWidget( sbPredictDelay, 3, 0 ); 74 layout->addWidget( sbPredictDelay, 3, 0 );
75 75
76 // Space filler 76 // Space filler
77 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 4, 0 ); 77 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 4, 0 );
78 78
79 // Display time server information selector 79 // Display time server information selector
80 chNtpTab = new QCheckBox( tr( "Display time server information" ), container ); 80 chNtpTab = new QCheckBox( tr( "Display time server information" ), container );
81 connect( chNtpTab, SIGNAL( toggled( bool ) ), this, SIGNAL( displayNTPTab( bool ) ) ); 81 connect( chNtpTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayNTPTab(bool) ) );
82 layout->addMultiCellWidget( chNtpTab, 5, 5, 0, 1 ); 82 layout->addMultiCellWidget( chNtpTab, 5, 5, 0, 1 );
83 83
84 // Display time prediction information selector 84 // Display time prediction information selector
85 chPredictTab = new QCheckBox( tr( "Display time prediction information" ), container ); 85 chPredictTab = new QCheckBox( tr( "Display time prediction information" ), container );
86 connect( chPredictTab, SIGNAL( toggled( bool ) ), this, SIGNAL( displayPredictTab( bool ) ) ); 86 connect( chPredictTab, SIGNAL( toggled(bool) ), this, SIGNAL( displayPredictTab(bool) ) );
87 layout->addMultiCellWidget( chPredictTab, 6, 6, 0, 1 ); 87 layout->addMultiCellWidget( chPredictTab, 6, 6, 0, 1 );
88 88
89 // Space filler 89 // Space filler
90 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 ); 90 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 );
91 91
92 // Initialize values 92 // Initialize values
93 QString ntpSrvsFile = QPEApplication::qpeDir(); 93 QString ntpSrvsFile = QPEApplication::qpeDir();
94 ntpSrvsFile.append( "etc/ntpservers" ); 94 ntpSrvsFile.append( "etc/ntpservers" );
95 Config ntpSrvs( ntpSrvsFile, Config::File ); 95 Config ntpSrvs( ntpSrvsFile, Config::File );
96 ntpSrvs.setGroup( "servers" ); 96 ntpSrvs.setGroup( "servers" );
97 int srvCount = ntpSrvs.readNumEntry( "count", 0 ); 97 int srvCount = ntpSrvs.readNumEntry( "count", 0 );
98 for ( int i = 0; i < srvCount; i++ ) 98 for ( int i = 0; i < srvCount; i++ )
99 { 99 {
100 ntpSrvs.setGroup( QString::number( i ) ); 100 ntpSrvs.setGroup( QString::number( i ) );
101 cbTimeServer->insertItem( ntpSrvs.readEntry( "name" ) ); 101 cbTimeServer->insertItem( ntpSrvs.readEntry( "name" ) );
102 } 102 }
103 if ( srvCount==0 ) 103 if ( srvCount==0 )
104 cbTimeServer->insertItem( "time.fu-berlin.de" ); 104 cbTimeServer->insertItem( "time.fu-berlin.de" );
105 105
106 Config config( "ntp" ); 106 Config config( "ntp" );
107 config.setGroup( "settings" ); 107 config.setGroup( "settings" );
108 sbPredictDelay->setValue( config.readNumEntry( "minLookupDiff", 720 ) ); 108 sbPredictDelay->setValue( config.readNumEntry( "minLookupDiff", 720 ) );
109 sbNtpDelay->setValue( config.readNumEntry( "ntpRefreshFreq", 1440 ) ); 109 sbNtpDelay->setValue( config.readNumEntry( "ntpRefreshFreq", 1440 ) );
110 cbTimeServer->setCurrentItem( config.readNumEntry( "ntpServer", 0 ) ); 110 cbTimeServer->setCurrentItem( config.readNumEntry( "ntpServer", 0 ) );
111 chNtpTab->setChecked( config.readBoolEntry( "displayNtpTab", FALSE ) ); 111 chNtpTab->setChecked( config.readBoolEntry( "displayNtpTab", FALSE ) );
112 chPredictTab->setChecked( config.readBoolEntry( "displayPredictTab", FALSE ) ); 112 chPredictTab->setChecked( config.readBoolEntry( "displayPredictTab", FALSE ) );
113} 113}
114 114
115SettingsTabWidget::~SettingsTabWidget() 115SettingsTabWidget::~SettingsTabWidget()
116{ 116{
117} 117}
118 118
119void SettingsTabWidget::saveSettings() 119void SettingsTabWidget::saveSettings()
120{ 120{
121 int srvCount = cbTimeServer->count(); 121 int srvCount = cbTimeServer->count();
122 bool serversChanged = TRUE; 122 bool serversChanged = TRUE;
123 int curSrv = cbTimeServer->currentItem(); 123 int curSrv = cbTimeServer->currentItem();
124 QString edit = cbTimeServer->currentText(); 124 QString edit = cbTimeServer->currentText();
125 for ( int i = 0; i < srvCount; i++ ) 125 for ( int i = 0; i < srvCount; i++ )
126 { 126 {
127 if ( edit == cbTimeServer->text( i ) ) 127 if ( edit == cbTimeServer->text( i ) )
128 serversChanged = FALSE; 128 serversChanged = FALSE;
129 } 129 }
130 if ( serversChanged ) 130 if ( serversChanged )
131 { 131 {
132 QString ntpSrvsFile = QPEApplication::qpeDir(); 132 QString ntpSrvsFile = QPEApplication::qpeDir();
133 ntpSrvsFile.append( "etc/ntpservers" ); 133 ntpSrvsFile.append( "etc/ntpservers" );
134 Config ntpSrvs( ntpSrvsFile, Config::File ); 134 Config ntpSrvs( ntpSrvsFile, Config::File );
135 ntpSrvs.setGroup( "servers" ); 135 ntpSrvs.setGroup( "servers" );
136 ntpSrvs.writeEntry( "count", ++srvCount ); 136 ntpSrvs.writeEntry( "count", ++srvCount );
137 ntpSrvs.setGroup( "0" ); 137 ntpSrvs.setGroup( "0" );
138 ntpSrvs.writeEntry( "name", edit ); 138 ntpSrvs.writeEntry( "name", edit );
139 curSrv = 0; 139 curSrv = 0;
140 for ( int i = 1; i < srvCount; i++ ) 140 for ( int i = 1; i < srvCount; i++ )
141 { 141 {
142 // qDebug( "ntpSrvs[%i/%i]=%s", i, srvCount, cbTimeServer->text( i ).latin1() ); 142 // qDebug( "ntpSrvs[%i/%i]=%s", i, srvCount, cbTimeServer->text( i ).latin1() );
143 ntpSrvs.setGroup( QString::number( i ) ); 143 ntpSrvs.setGroup( QString::number( i ) );
144 ntpSrvs.writeEntry( "name", cbTimeServer->text( i-1 ) ); 144 ntpSrvs.writeEntry( "name", cbTimeServer->text( i-1 ) );
145 } 145 }
146 } 146 }
147 Config config( "ntp", Config::User ); 147 Config config( "ntp", Config::User );
148 config.setGroup( "settings" ); 148 config.setGroup( "settings" );
149 config.writeEntry( "ntpServer", curSrv ); 149 config.writeEntry( "ntpServer", curSrv );
150 config.writeEntry( "minLookupDiff", sbPredictDelay->value() ); 150 config.writeEntry( "minLookupDiff", sbPredictDelay->value() );
151 config.writeEntry( "ntpRefreshFreq", sbNtpDelay->value() ); 151 config.writeEntry( "ntpRefreshFreq", sbNtpDelay->value() );
152 config.writeEntry( "displayNtpTab", chNtpTab->isChecked() ); 152 config.writeEntry( "displayNtpTab", chNtpTab->isChecked() );
153 config.writeEntry( "displayPredictTab", chPredictTab->isChecked() ); 153 config.writeEntry( "displayPredictTab", chPredictTab->isChecked() );
154} 154}
155 155
156QString SettingsTabWidget::ntpServer() 156QString SettingsTabWidget::ntpServer()
157{ 157{
158 return cbTimeServer->currentText(); 158 return cbTimeServer->currentText();
159} 159}
diff --git a/noncore/settings/netsystemtime/timetabwidget.cpp b/noncore/settings/netsystemtime/timetabwidget.cpp
index 6f24462..1ea460e 100644
--- a/noncore/settings/netsystemtime/timetabwidget.cpp
+++ b/noncore/settings/netsystemtime/timetabwidget.cpp
@@ -1,292 +1,292 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 OPIE team <opie@handhelds.org?> 4             .=l. Copyright (c) 2002 OPIE team <opie@handhelds.org?>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include "timetabwidget.h" 29#include "timetabwidget.h"
30 30
31#include <qpe/config.h> 31#include <qpe/config.h>
32#include <qpe/datebookmonth.h> 32#include <qpe/datebookmonth.h>
33#include <qpe/global.h> 33#include <qpe/global.h>
34#include <qpe/resource.h> 34#include <qpe/resource.h>
35#include <qpe/tzselect.h> 35#include <qpe/tzselect.h>
36 36
37#if ( defined Q_WS_QWS || defined(_WS_QWS_) ) && !defined(QT_NO_COP) 37#if ( defined Q_WS_QWS || defined(_WS_QWS_) ) && !defined(QT_NO_COP)
38#include <qpe/qcopenvelope_qws.h> 38#include <qpe/qcopenvelope_qws.h>
39#endif 39#endif
40 40
41#include <qcombobox.h> 41#include <qcombobox.h>
42#include <qdatetime.h> 42#include <qdatetime.h>
43#include <qframe.h> 43#include <qframe.h>
44#include <qlabel.h> 44#include <qlabel.h>
45#include <qlayout.h> 45#include <qlayout.h>
46#include <qpushbutton.h> 46#include <qpushbutton.h>
47#include <qscrollview.h> 47#include <qscrollview.h>
48#include <qspinbox.h> 48#include <qspinbox.h>
49 49
50#include <stdlib.h> 50#include <stdlib.h>
51#include <sys/time.h> 51#include <sys/time.h>
52 52
53static const int ValueAM = 0; 53static const int ValueAM = 0;
54static const int ValuePM = 1; 54static const int ValuePM = 1;
55 55
56TimeTabWidget::TimeTabWidget( QWidget *parent ) 56TimeTabWidget::TimeTabWidget( QWidget *parent )
57 : QWidget( parent, 0x0, 0 ) 57 : QWidget( parent, 0x0, 0 )
58{ 58{
59 // Synchronize HW clock to systemtime 59 // Synchronize HW clock to systemtime
60 // This app will update systemtime 60 // This app will update systemtime
61 // - if Cancel is clicked, will reset systemtime to HW clock's time 61 // - if Cancel is clicked, will reset systemtime to HW clock's time
62 // - if Ok is clicked, will leave systemtime as is 62 // - if Ok is clicked, will leave systemtime as is
63 system("/sbin/hwclock --systohc --utc"); 63 system("/sbin/hwclock --systohc --utc");
64 64
65 QVBoxLayout *tmpvb = new QVBoxLayout( this ); 65 QVBoxLayout *tmpvb = new QVBoxLayout( this );
66 QScrollView *sv = new QScrollView( this ); 66 QScrollView *sv = new QScrollView( this );
67 tmpvb->addWidget( sv, 0, 0 ); 67 tmpvb->addWidget( sv, 0, 0 );
68 sv->setResizePolicy( QScrollView::AutoOneFit ); 68 sv->setResizePolicy( QScrollView::AutoOneFit );
69 sv->setFrameStyle( QFrame::NoFrame ); 69 sv->setFrameStyle( QFrame::NoFrame );
70 QWidget *container = new QWidget( sv->viewport() ); 70 QWidget *container = new QWidget( sv->viewport() );
71 sv->addChild( container ); 71 sv->addChild( container );
72 72
73 QGridLayout *layout = new QGridLayout( container ); 73 QGridLayout *layout = new QGridLayout( container );
74 layout->setMargin( 2 ); 74 layout->setMargin( 2 );
75 layout->setSpacing( 4 ); 75 layout->setSpacing( 4 );
76 76
77 // Hours 77 // Hours
78 layout->addMultiCellWidget( new QLabel( tr( "Hour" ), container ), 1, 1, 0, 1 ); 78 layout->addMultiCellWidget( new QLabel( tr( "Hour" ), container ), 1, 1, 0, 1 );
79 sbHour = new QSpinBox( container ); 79 sbHour = new QSpinBox( container );
80 sbHour->setWrapping( TRUE ); 80 sbHour->setWrapping( TRUE );
81 layout->addMultiCellWidget( sbHour, 2, 2, 0, 1 ); 81 layout->addMultiCellWidget( sbHour, 2, 2, 0, 1 );
82 82
83 // Minutes 83 // Minutes
84 layout->addMultiCellWidget( new QLabel( tr( "Minute" ), container ), 1, 1, 2, 3 ); 84 layout->addMultiCellWidget( new QLabel( tr( "Minute" ), container ), 1, 1, 2, 3 );
85 sbMin = new QSpinBox( container ); 85 sbMin = new QSpinBox( container );
86 sbMin->setWrapping( TRUE ); 86 sbMin->setWrapping( TRUE );
87 sbMin->setMinValue( 0 ); 87 sbMin->setMinValue( 0 );
88 sbMin->setMaxValue( 59 ); 88 sbMin->setMaxValue( 59 );
89 layout->addMultiCellWidget( sbMin, 2, 2, 2, 3 ); 89 layout->addMultiCellWidget( sbMin, 2, 2, 2, 3 );
90 90
91 // AM/PM 91 // AM/PM
92 cbAmpm = new QComboBox( container ); 92 cbAmpm = new QComboBox( container );
93 cbAmpm->insertItem( tr( "AM" ), ValueAM ); 93 cbAmpm->insertItem( tr( "AM" ), ValueAM );
94 cbAmpm->insertItem( tr( "PM" ), ValuePM ); 94 cbAmpm->insertItem( tr( "PM" ), ValuePM );
95 layout->addMultiCellWidget( cbAmpm, 2, 2, 4, 5 ); 95 layout->addMultiCellWidget( cbAmpm, 2, 2, 4, 5 );
96 96
97 // Date 97 // Date
98 layout->addWidget( new QLabel( tr( "Date" ), container ), 4, 0 ); 98 layout->addWidget( new QLabel( tr( "Date" ), container ), 4, 0 );
99 btnDate = new DateButton( TRUE, container ); 99 btnDate = new DateButton( TRUE, container );
100 layout->addMultiCellWidget( btnDate, 4, 4, 1, 5 ); 100 layout->addMultiCellWidget( btnDate, 4, 4, 1, 5 );
101 101
102 // Timezone 102 // Timezone
103 layout->addMultiCellWidget( new QLabel( tr( "Time zone" ), container ), 6, 6, 0, 1 ); 103 layout->addMultiCellWidget( new QLabel( tr( "Time zone" ), container ), 6, 6, 0, 1 );
104 selTimeZone = new TimeZoneSelector( container ); 104 selTimeZone = new TimeZoneSelector( container );
105 connect( selTimeZone, SIGNAL(signalNewTz(const QString &)), this, SLOT(slotTZChanged(const QString &)) ); 105 connect( selTimeZone, SIGNAL(signalNewTz(const QString&)), this, SLOT(slotTZChanged(const QString&)) );
106 layout->addMultiCellWidget( selTimeZone, 6, 6, 2, 5 ); 106 layout->addMultiCellWidget( selTimeZone, 6, 6, 2, 5 );
107 107
108 // Space filler 108 // Space filler
109 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 ); 109 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 7, 0 );
110 110
111 // Set NTP time button 111 // Set NTP time button
112 QPushButton *pb = new QPushButton( Resource::loadPixmap( "netsystemtime/ntptab" ), 112 QPushButton *pb = new QPushButton( Resource::loadPixmap( "netsystemtime/ntptab" ),
113 tr( "Get time from the network" ), container ); 113 tr( "Get time from the network" ), container );
114 connect( pb, SIGNAL(clicked()), this, SIGNAL(getNTPTime()) ); 114 connect( pb, SIGNAL(clicked()), this, SIGNAL(getNTPTime()) );
115 layout->addMultiCellWidget( pb, 8, 8, 0, 5 ); 115 layout->addMultiCellWidget( pb, 8, 8, 0, 5 );
116 116
117 // Set predicted time button 117 // Set predicted time button
118 pb = new QPushButton( Resource::loadPixmap( "netsystemtime/predicttab" ), tr( "Set predicted time" ), 118 pb = new QPushButton( Resource::loadPixmap( "netsystemtime/predicttab" ), tr( "Set predicted time" ),
119 container ); 119 container );
120 connect( pb, SIGNAL(clicked()), this, SIGNAL(getPredictedTime()) ); 120 connect( pb, SIGNAL(clicked()), this, SIGNAL(getPredictedTime()) );
121 layout->addMultiCellWidget( pb, 9, 9, 0, 5 ); 121 layout->addMultiCellWidget( pb, 9, 9, 0, 5 );
122 122
123 // Space filler at bottom of widget 123 // Space filler at bottom of widget
124 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 10, 0 ); 124 layout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Minimum, QSizePolicy::Expanding ), 10, 0 );
125 125
126 // Initialize values 126 // Initialize values
127 Config config( "locale" ); 127 Config config( "locale" );
128 config.setGroup( "Location" ); 128 config.setGroup( "Location" );
129 selTimeZone->setCurrentZone( config.readEntry( "Timezone", "America/New_York" ) ); 129 selTimeZone->setCurrentZone( config.readEntry( "Timezone", "America/New_York" ) );
130 use12HourTime = FALSE; 130 use12HourTime = FALSE;
131 setDateTime( QDateTime::currentDateTime() ); 131 setDateTime( QDateTime::currentDateTime() );
132} 132}
133 133
134TimeTabWidget::~TimeTabWidget() 134TimeTabWidget::~TimeTabWidget()
135{ 135{
136} 136}
137 137
138void TimeTabWidget::saveSettings( bool commit ) 138void TimeTabWidget::saveSettings( bool commit )
139{ 139{
140 if ( commit ) 140 if ( commit )
141 { 141 {
142 // Set timezone and announce to world 142 // Set timezone and announce to world
143 QString tz = selTimeZone->currentZone(); 143 QString tz = selTimeZone->currentZone();
144 Config config("locale"); 144 Config config("locale");
145 config.setGroup( "Location" ); 145 config.setGroup( "Location" );
146 config.writeEntry( "Timezone", tz ); 146 config.writeEntry( "Timezone", tz );
147 setenv( "TZ", tz, 1 ); 147 setenv( "TZ", tz, 1 );
148 QCopEnvelope setTimeZone( "QPE/System", "timeChange(QString)" ); 148 QCopEnvelope setTimeZone( "QPE/System", "timeChange(QString)" );
149 setTimeZone << tz; 149 setTimeZone << tz;
150 150
151 // If controls have a valid date & time, update systemtime 151 // If controls have a valid date & time, update systemtime
152 int hour = sbHour->value(); 152 int hour = sbHour->value();
153 if ( use12HourTime && cbAmpm->currentItem() == ValuePM ) 153 if ( use12HourTime && cbAmpm->currentItem() == ValuePM )
154 hour += 12; 154 hour += 12;
155 QDateTime dt( btnDate->date(), QTime ( hour, sbMin->value(), QTime::currentTime().second() ) ); 155 QDateTime dt( btnDate->date(), QTime ( hour, sbMin->value(), QTime::currentTime().second() ) );
156 setSystemTime( dt ); 156 setSystemTime( dt );
157 } 157 }
158 else 158 else
159 { 159 {
160 // Reset systemtime to hardware clock (i.e. undo any changes made by this app) 160 // Reset systemtime to hardware clock (i.e. undo any changes made by this app)
161 system("/sbin/hwclock --hctosys --utc"); 161 system("/sbin/hwclock --hctosys --utc");
162 } 162 }
163} 163}
164 164
165void TimeTabWidget::setDateTime( const QDateTime &dt ) 165void TimeTabWidget::setDateTime( const QDateTime &dt )
166{ 166{
167 // Set time 167 // Set time
168 QTime t = dt.time(); 168 QTime t = dt.time();
169 if( use12HourTime ) 169 if( use12HourTime )
170 { 170 {
171 int show_hour = t.hour(); 171 int show_hour = t.hour();
172 if ( t.hour() >= 12 ) 172 if ( t.hour() >= 12 )
173 { 173 {
174 show_hour -= 12; 174 show_hour -= 12;
175 cbAmpm->setCurrentItem( ValuePM ); 175 cbAmpm->setCurrentItem( ValuePM );
176 } 176 }
177 else 177 else
178 { 178 {
179 cbAmpm->setCurrentItem( ValueAM ); 179 cbAmpm->setCurrentItem( ValueAM );
180 } 180 }
181 if ( show_hour == 0 ) 181 if ( show_hour == 0 )
182 show_hour = 12; 182 show_hour = 12;
183 sbHour->setValue( show_hour ); 183 sbHour->setValue( show_hour );
184 } 184 }
185 else 185 else
186 { 186 {
187 sbHour->setValue( t.hour() ); 187 sbHour->setValue( t.hour() );
188 } 188 }
189 sbMin->setValue( t.minute() ); 189 sbMin->setValue( t.minute() );
190 190
191 // Set date 191 // Set date
192 btnDate->setDate( dt.date() ); 192 btnDate->setDate( dt.date() );
193} 193}
194 194
195void TimeTabWidget::setSystemTime( const QDateTime &dt ) 195void TimeTabWidget::setSystemTime( const QDateTime &dt )
196{ 196{
197 // Set system clock 197 // Set system clock
198 if ( dt.isValid() ) 198 if ( dt.isValid() )
199 { 199 {
200 struct timeval myTv; 200 struct timeval myTv;
201 int t = TimeConversion::toUTC( dt ); 201 int t = TimeConversion::toUTC( dt );
202 myTv.tv_sec = t; 202 myTv.tv_sec = t;
203 myTv.tv_usec = 0; 203 myTv.tv_usec = 0;
204 204
205 if ( myTv.tv_sec != -1 ) 205 if ( myTv.tv_sec != -1 )
206 ::settimeofday( &myTv, 0 ); 206 ::settimeofday( &myTv, 0 );
207 } 207 }
208} 208}
209 209
210void TimeTabWidget::slotUse12HourTime( int i ) 210void TimeTabWidget::slotUse12HourTime( int i )
211{ 211{
212 use12HourTime = (i == 1); 212 use12HourTime = (i == 1);
213 213
214 cbAmpm->setEnabled( use12HourTime ); 214 cbAmpm->setEnabled( use12HourTime );
215 215
216 int show_hour = sbHour->value(); 216 int show_hour = sbHour->value();
217 217
218 if ( use12HourTime ) 218 if ( use12HourTime )
219 { 219 {
220 sbHour->setMinValue( 1 ); 220 sbHour->setMinValue( 1 );
221 sbHour->setMaxValue( 12 ); 221 sbHour->setMaxValue( 12 );
222 222
223 if ( show_hour >= 12 ) 223 if ( show_hour >= 12 )
224 { 224 {
225 show_hour -= 12; 225 show_hour -= 12;
226 cbAmpm->setCurrentItem( ValuePM ); 226 cbAmpm->setCurrentItem( ValuePM );
227 } 227 }
228 else 228 else
229 { 229 {
230 cbAmpm->setCurrentItem( ValueAM ); 230 cbAmpm->setCurrentItem( ValueAM );
231 } 231 }
232 if ( show_hour == 0 ) 232 if ( show_hour == 0 )
233 show_hour = 12; 233 show_hour = 12;
234 } 234 }
235 else 235 else
236 { 236 {
237 sbHour->setMinValue( 0 ); 237 sbHour->setMinValue( 0 );
238 sbHour->setMaxValue( 23 ); 238 sbHour->setMaxValue( 23 );
239 239
240 if ( cbAmpm->currentItem() == ValuePM ) 240 if ( cbAmpm->currentItem() == ValuePM )
241 { 241 {
242 show_hour += 12; 242 show_hour += 12;
243 if ( show_hour == 24 ) 243 if ( show_hour == 24 )
244 show_hour = 0; 244 show_hour = 0;
245 } 245 }
246 } 246 }
247 247
248 sbHour->setValue( show_hour ); 248 sbHour->setValue( show_hour );
249} 249}
250 250
251void TimeTabWidget::slotDateFormatChanged( const DateFormat &df ) 251void TimeTabWidget::slotDateFormatChanged( const DateFormat &df )
252{ 252{
253 btnDate->setDateFormat( df ); 253 btnDate->setDateFormat( df );
254} 254}
255 255
256void TimeTabWidget::slotWeekStartChanged( int monday ) 256void TimeTabWidget::slotWeekStartChanged( int monday )
257{ 257{
258 btnDate->setWeekStartsMonday( monday ); 258 btnDate->setWeekStartsMonday( monday );
259} 259}
260 260
261void TimeTabWidget::slotTZChanged( const QString &newtz ) 261void TimeTabWidget::slotTZChanged( const QString &newtz )
262{ 262{
263 // If controls have a valid date & time, update systemtime 263 // If controls have a valid date & time, update systemtime
264 int hour = sbHour->value(); 264 int hour = sbHour->value();
265 if ( use12HourTime && cbAmpm->currentItem() == ValuePM ) 265 if ( use12HourTime && cbAmpm->currentItem() == ValuePM )
266 hour += 12; 266 hour += 12;
267 QDateTime dt( btnDate->date(), QTime ( hour, sbMin->value(), QTime::currentTime().second() ) ); 267 QDateTime dt( btnDate->date(), QTime ( hour, sbMin->value(), QTime::currentTime().second() ) );
268 setSystemTime( dt ); 268 setSystemTime( dt );
269 QCopEnvelope setTimeZone( "QPE/System", "timeChange(QString)" ); 269 QCopEnvelope setTimeZone( "QPE/System", "timeChange(QString)" );
270 setTimeZone << newtz; 270 setTimeZone << newtz;
271 271
272 // Set system timezone 272 // Set system timezone
273 QString currtz = getenv( "TZ" ); 273 QString currtz = getenv( "TZ" );
274 setenv( "TZ", newtz, 1 ); 274 setenv( "TZ", newtz, 1 );
275 275
276 // Get new date/time 276 // Get new date/time
277 hour = sbHour->value(); 277 hour = sbHour->value();
278 if ( use12HourTime && cbAmpm->currentItem() == ValuePM ) 278 if ( use12HourTime && cbAmpm->currentItem() == ValuePM )
279 hour += 12; 279 hour += 12;
280 dt = QDateTime::currentDateTime(); 280 dt = QDateTime::currentDateTime();
281 281
282 // Reset system timezone 282 // Reset system timezone
283 if ( !currtz.isNull() ) 283 if ( !currtz.isNull() )
284 { 284 {
285 setenv( "TZ", currtz, 1 ); 285 setenv( "TZ", currtz, 1 );
286 } 286 }
287 287
288 // Set controls to new time 288 // Set controls to new time
289 setDateTime( dt ); 289 setDateTime( dt );
290 290
291 emit tzChanged( newtz ); 291 emit tzChanged( newtz );
292} 292}
diff --git a/noncore/settings/networksettings/interfaces/interfaceinformationimp.cpp b/noncore/settings/networksettings/interfaces/interfaceinformationimp.cpp
index 698dfd3..ff65424 100644
--- a/noncore/settings/networksettings/interfaces/interfaceinformationimp.cpp
+++ b/noncore/settings/networksettings/interfaces/interfaceinformationimp.cpp
@@ -1,104 +1,104 @@
1 1
2#include "interfaceinformationimp.h" 2#include "interfaceinformationimp.h"
3#include "interfaceadvanced.h" 3#include "interfaceadvanced.h"
4 4
5/* OPIE */ 5/* OPIE */
6#include <qpe/config.h> 6#include <qpe/config.h>
7#include <qpe/qpeapplication.h> 7#include <qpe/qpeapplication.h>
8 8
9/* QT */ 9/* QT */
10#include <qcheckbox.h> 10#include <qcheckbox.h>
11#include <qpushbutton.h> 11#include <qpushbutton.h>
12#include <qlabel.h> 12#include <qlabel.h>
13#include <qgroupbox.h> 13#include <qgroupbox.h>
14#include <qmessagebox.h> 14#include <qmessagebox.h>
15 15
16 16
17#ifdef QWS 17#ifdef QWS
18#else 18#else
19 #define showMaximized show 19 #define showMaximized show
20#endif 20#endif
21 21
22/** 22/**
23 * Constructor for the InterfaceInformationImp class. This class pretty much 23 * Constructor for the InterfaceInformationImp class. This class pretty much
24 * just display's information about the interface that is passed to it. 24 * just display's information about the interface that is passed to it.
25 */ 25 */
26InterfaceInformationImp::InterfaceInformationImp(QWidget *parent, const char *name, Interface *i, WFlags f):InterfaceInformation(parent, name, f), interface(i) 26InterfaceInformationImp::InterfaceInformationImp(QWidget *parent, const char *name, Interface *i, WFlags f):InterfaceInformation(parent, name, f), interface(i)
27{ 27{
28 connect(i, SIGNAL(updateInterface(Interface *)), this, SLOT(updateInterface(Interface *))); 28 connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*)));
29 connect(i, SIGNAL(updateMessage(const QString &)), this, SLOT(showMessage(const QString &))); 29 connect(i, SIGNAL(updateMessage(const QString&)), this, SLOT(showMessage(const QString&)));
30 updateInterface(interface); 30 updateInterface(interface);
31 connect(startButton, SIGNAL(clicked()), interface, SLOT(start())); 31 connect(startButton, SIGNAL(clicked()), interface, SLOT(start()));
32 connect(stopButton, SIGNAL(clicked()), interface, SLOT(stop())); 32 connect(stopButton, SIGNAL(clicked()), interface, SLOT(stop()));
33 connect(restartButton, SIGNAL(clicked()), interface, SLOT(restart())); 33 connect(restartButton, SIGNAL(clicked()), interface, SLOT(restart()));
34 connect(refreshButton, SIGNAL(clicked()), interface, SLOT(refresh())); 34 connect(refreshButton, SIGNAL(clicked()), interface, SLOT(refresh()));
35 connect(advancedButton, SIGNAL(clicked()), this, SLOT(advanced())); 35 connect(advancedButton, SIGNAL(clicked()), this, SLOT(advanced()));
36 Config cfg("networksettings", Config::User); 36 Config cfg("networksettings", Config::User);
37 cfg.setGroup("interface"); 37 cfg.setGroup("interface");
38 CheckBoxSilent->setChecked( cfg.readBoolEntry("silent", false) ); 38 CheckBoxSilent->setChecked( cfg.readBoolEntry("silent", false) );
39} 39}
40 40
41InterfaceInformationImp::~InterfaceInformationImp() 41InterfaceInformationImp::~InterfaceInformationImp()
42{ 42{
43 Config cfg("networksettings", Config::User); 43 Config cfg("networksettings", Config::User);
44 cfg.setGroup("interface"); 44 cfg.setGroup("interface");
45 cfg.writeEntry("silent", CheckBoxSilent->isChecked() ); 45 cfg.writeEntry("silent", CheckBoxSilent->isChecked() );
46} 46}
47 47
48/** 48/**
49 * Update the interface information and buttons. 49 * Update the interface information and buttons.
50 * @param Intarface *i the interface to update (should be the one we already 50 * @param Intarface *i the interface to update (should be the one we already
51 * know about). 51 * know about).
52 */ 52 */
53void InterfaceInformationImp::updateInterface(Interface *) 53void InterfaceInformationImp::updateInterface(Interface *)
54{ 54{
55 if(interface->getStatus()) 55 if(interface->getStatus())
56 { 56 {
57 startButton->setEnabled(false); 57 startButton->setEnabled(false);
58 stopButton->setEnabled(true); 58 stopButton->setEnabled(true);
59 restartButton->setEnabled(true); 59 restartButton->setEnabled(true);
60 } 60 }
61 else 61 else
62 { 62 {
63 startButton->setEnabled(true); 63 startButton->setEnabled(true);
64 stopButton->setEnabled(false); 64 stopButton->setEnabled(false);
65 restartButton->setEnabled(false); 65 restartButton->setEnabled(false);
66 } 66 }
67 macAddressLabel->setText(interface->getMacAddress()); 67 macAddressLabel->setText(interface->getMacAddress());
68 ipAddressLabel->setText(interface->getIp()); 68 ipAddressLabel->setText(interface->getIp());
69 subnetMaskLabel->setText(interface->getSubnetMask()); 69 subnetMaskLabel->setText(interface->getSubnetMask());
70 broadcastLabel->setText(interface->getBroadcast()); 70 broadcastLabel->setText(interface->getBroadcast());
71} 71}
72 72
73/** 73/**
74 * Create the advanced widget. Fill it with the current interface's information. 74 * Create the advanced widget. Fill it with the current interface's information.
75 * Display it. 75 * Display it.
76 */ 76 */
77void InterfaceInformationImp::advanced() 77void InterfaceInformationImp::advanced()
78{ 78{
79 InterfaceAdvanced *a = new InterfaceAdvanced(this, "InterfaceAdvanced", Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog); 79 InterfaceAdvanced *a = new InterfaceAdvanced(this, "InterfaceAdvanced", Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog);
80 a->interfaceName->setText(interface->getInterfaceName()); 80 a->interfaceName->setText(interface->getInterfaceName());
81 a->macAddressLabel->setText(interface->getMacAddress()); 81 a->macAddressLabel->setText(interface->getMacAddress());
82 a->ipAddressLabel->setText(interface->getIp()); 82 a->ipAddressLabel->setText(interface->getIp());
83 a->subnetMaskLabel->setText(interface->getSubnetMask()); 83 a->subnetMaskLabel->setText(interface->getSubnetMask());
84 a->broadcastLabel->setText(interface->getBroadcast()); 84 a->broadcastLabel->setText(interface->getBroadcast());
85 a->dhcpServerLabel->setText(interface->getDhcpServerIp()); 85 a->dhcpServerLabel->setText(interface->getDhcpServerIp());
86 a->leaseObtainedLabel->setText(interface->getLeaseObtained()); 86 a->leaseObtainedLabel->setText(interface->getLeaseObtained());
87 a->leaseExpiresLabel->setText(interface->getLeaseExpires()); 87 a->leaseExpiresLabel->setText(interface->getLeaseExpires());
88 a->dhcpInformation->setEnabled(interface->isDhcp()); 88 a->dhcpInformation->setEnabled(interface->isDhcp());
89 QPEApplication::showWidget( a ); 89 QPEApplication::showWidget( a );
90} 90}
91 91
92/** 92/**
93 * Messages from the interface if start/stop went as planned. 93 * Messages from the interface if start/stop went as planned.
94 * Purly for user feedback. 94 * Purly for user feedback.
95 * @param message the message to display. 95 * @param message the message to display.
96 */ 96 */
97void InterfaceInformationImp::showMessage(const QString &message) 97void InterfaceInformationImp::showMessage(const QString &message)
98{ 98{
99 if (CheckBoxSilent->isChecked()) return; 99 if (CheckBoxSilent->isChecked()) return;
100 QMessageBox::information(this, "Message", message, QMessageBox::Ok); 100 QMessageBox::information(this, "Message", message, QMessageBox::Ok);
101} 101}
102 102
103// infoimp.cpp 103// infoimp.cpp
104 104
diff --git a/noncore/settings/networksettings/mainwindowimp.cpp b/noncore/settings/networksettings/mainwindowimp.cpp
index b0a1dd9..1e16b97 100644
--- a/noncore/settings/networksettings/mainwindowimp.cpp
+++ b/noncore/settings/networksettings/mainwindowimp.cpp
@@ -1,748 +1,748 @@
1 1
2#include "mainwindowimp.h" 2#include "mainwindowimp.h"
3#include "addconnectionimp.h" 3#include "addconnectionimp.h"
4#include "interfaceinformationimp.h" 4#include "interfaceinformationimp.h"
5#include "interfacesetupimp.h" 5#include "interfacesetupimp.h"
6#include "interfaces.h" 6#include "interfaces.h"
7#include "module.h" 7#include "module.h"
8 8
9/* OPIE */ 9/* OPIE */
10#include <qpe/qcopenvelope_qws.h> 10#include <qpe/qcopenvelope_qws.h>
11#include <qpe/qpeapplication.h> 11#include <qpe/qpeapplication.h>
12#include <qpe/config.h> 12#include <qpe/config.h>
13#include <qpe/qlibrary.h> 13#include <qpe/qlibrary.h>
14#include <qpe/resource.h> 14#include <qpe/resource.h>
15 15
16/* QT */ 16/* QT */
17#include <qpushbutton.h> 17#include <qpushbutton.h>
18#include <qlistbox.h> 18#include <qlistbox.h>
19#include <qlineedit.h> 19#include <qlineedit.h>
20#include <qlistview.h> 20#include <qlistview.h>
21#include <qheader.h> 21#include <qheader.h>
22#include <qlabel.h> 22#include <qlabel.h>
23#include <qtabwidget.h> // in order to disable the profiles tab 23#include <qtabwidget.h> // in order to disable the profiles tab
24#include <qmessagebox.h> 24#include <qmessagebox.h>
25 25
26 26
27#if QT_VERSION < 300 27#if QT_VERSION < 300
28#include <qlist.h> 28#include <qlist.h>
29#else 29#else
30#include <qptrlist.h> 30#include <qptrlist.h>
31#endif 31#endif
32#include <qdir.h> 32#include <qdir.h>
33#include <qfile.h> 33#include <qfile.h>
34#include <qtextstream.h> 34#include <qtextstream.h>
35#include <qregexp.h> 35#include <qregexp.h>
36 36
37/* STD */ 37/* STD */
38#include <net/if.h> 38#include <net/if.h>
39#include <sys/ioctl.h> 39#include <sys/ioctl.h>
40#include <sys/socket.h> 40#include <sys/socket.h>
41 41
42#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme" 42#define DEFAULT_SCHEME "/var/lib/pcmcia/scheme"
43#define _PROCNETDEV "/proc/net/dev" 43#define _PROCNETDEV "/proc/net/dev"
44 44
45MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME) 45MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME)
46{ 46{
47 connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked())); 47 connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked()));
48 connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked())); 48 connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked()));
49 connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked())); 49 connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked()));
50 connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked())); 50 connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked()));
51 51
52 connect(newProfileButton, SIGNAL(clicked()), this, SLOT(addProfile())); 52 connect(newProfileButton, SIGNAL(clicked()), this, SLOT(addProfile()));
53 connect(removeProfileButton, SIGNAL(clicked()), this, SLOT(removeProfile())); 53 connect(removeProfileButton, SIGNAL(clicked()), this, SLOT(removeProfile()));
54 connect(setCurrentProfileButton, SIGNAL(clicked()), this, SLOT(changeProfile())); 54 connect(setCurrentProfileButton, SIGNAL(clicked()), this, SLOT(changeProfile()));
55 55
56 connect(newProfile, SIGNAL(textChanged(const QString&)), this, SLOT(newProfileChanged(const QString&))); 56 connect(newProfile, SIGNAL(textChanged(const QString&)), this, SLOT(newProfileChanged(const QString&)));
57 57
58 //FIXME: disable profiles for the moment: 58 //FIXME: disable profiles for the moment:
59 tabWidget->setTabEnabled( tab, false ); 59 tabWidget->setTabEnabled( tab, false );
60 60
61 // Load connections. 61 // Load connections.
62 // /usr/local/kde/lib/libinterfaces.la 62 // /usr/local/kde/lib/libinterfaces.la
63#ifdef QWS 63#ifdef QWS
64 loadModules(QPEApplication::qpeDir() + "plugins/networksettings"); 64 loadModules(QPEApplication::qpeDir() + "plugins/networksettings");
65#else 65#else
66 loader = KLibLoader::self(); 66 loader = KLibLoader::self();
67 loadModules(QString("/usr/")+KStandardDirs::kde_default("lib")); 67 loadModules(QString("/usr/")+KStandardDirs::kde_default("lib"));
68#endif 68#endif
69 getAllInterfaces(); 69 getAllInterfaces();
70 70
71 Interfaces i; 71 Interfaces i;
72 QStringList list = i.getInterfaceList(); 72 QStringList list = i.getInterfaceList();
73 QMap<QString, Interface*>::Iterator it; 73 QMap<QString, Interface*>::Iterator it;
74 for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni ) 74 for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni )
75 { 75 {
76 /* 76 /*
77 * we skipped it in getAllInterfaces now 77 * we skipped it in getAllInterfaces now
78 * we need to ignore it as well 78 * we need to ignore it as well
79 */ 79 */
80 if (m_handledIfaces.contains( *ni) ) 80 if (m_handledIfaces.contains( *ni) )
81 { 81 {
82 qDebug("Not up iface handled by module"); 82 qDebug("Not up iface handled by module");
83 continue; 83 continue;
84 } 84 }
85 bool found = false; 85 bool found = false;
86 for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it ) 86 for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it )
87 { 87 {
88 if(it.key() == (*ni)) 88 if(it.key() == (*ni))
89 found = true; 89 found = true;
90 } 90 }
91 if(!found) 91 if(!found)
92 { 92 {
93 if(!(*ni).contains("_")) 93 if(!(*ni).contains("_"))
94 { 94 {
95 Interface *i = new Interface(this, *ni, false); 95 Interface *i = new Interface(this, *ni, false);
96 i->setAttached(false); 96 i->setAttached(false);
97 i->setHardwareName(tr("Disconnected")); 97 i->setHardwareName(tr("Disconnected"));
98 interfaceNames.insert(i->getInterfaceName(), i); 98 interfaceNames.insert(i->getInterfaceName(), i);
99 updateInterface(i); 99 updateInterface(i);
100 connect(i, SIGNAL(updateInterface(Interface *)), this, SLOT(updateInterface(Interface *))); 100 connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*)));
101 } 101 }
102 } 102 }
103 } 103 }
104 104
105 //getInterfaceList(); 105 //getInterfaceList();
106 connectionList->header()->hide(); 106 connectionList->header()->hide();
107 107
108 Config cfg("NetworkSetup"); 108 Config cfg("NetworkSetup");
109 profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All")); 109 profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All"));
110 for ( QStringList::Iterator it = profiles.begin(); 110 for ( QStringList::Iterator it = profiles.begin();
111 it != profiles.end(); ++it) 111 it != profiles.end(); ++it)
112 profilesList->insertItem((*it)); 112 profilesList->insertItem((*it));
113 currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All")); 113 currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All"));
114 advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false); 114 advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false);
115 scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME); 115 scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME);
116 116
117 QFile file(scheme); 117 QFile file(scheme);
118 if ( file.open(IO_ReadOnly) ) 118 if ( file.open(IO_ReadOnly) )
119 { // file opened successfully 119 { // file opened successfully
120 QTextStream stream( &file ); // use a text stream 120 QTextStream stream( &file ); // use a text stream
121 while ( !stream.eof() ) 121 while ( !stream.eof() )
122 { // until end of file... 122 { // until end of file...
123 QString line = stream.readLine(); // line of text excluding '\n' 123 QString line = stream.readLine(); // line of text excluding '\n'
124 if(line.contains("SCHEME")) 124 if(line.contains("SCHEME"))
125 { 125 {
126 line = line.mid(7, line.length()); 126 line = line.mid(7, line.length());
127 currentProfileLabel->setText(line); 127 currentProfileLabel->setText(line);
128 break; 128 break;
129 } 129 }
130 } 130 }
131 file.close(); 131 file.close();
132 } 132 }
133 makeChannel(); 133 makeChannel();
134} 134}
135 135
136/** 136/**
137 * Deconstructor. Save profiles. Delete loaded libraries. 137 * Deconstructor. Save profiles. Delete loaded libraries.
138 */ 138 */
139MainWindowImp::~MainWindowImp() 139MainWindowImp::~MainWindowImp()
140{ 140{
141 // Save profiles. 141 // Save profiles.
142 Config cfg("NetworkSetup"); 142 Config cfg("NetworkSetup");
143 cfg.setGroup("General"); 143 cfg.setGroup("General");
144 cfg.writeEntry("Profiles", profiles.join(" ")); 144 cfg.writeEntry("Profiles", profiles.join(" "));
145 145
146 // Delete all interfaces that don't have owners. 146 // Delete all interfaces that don't have owners.
147 QMap<Interface*, QListViewItem*>::Iterator iIt; 147 QMap<Interface*, QListViewItem*>::Iterator iIt;
148 for( iIt = items.begin(); iIt != items.end(); ++iIt ) 148 for( iIt = items.begin(); iIt != items.end(); ++iIt )
149 { 149 {
150 if(iIt.key()->getModuleOwner() == NULL) 150 if(iIt.key()->getModuleOwner() == NULL)
151 delete iIt.key(); 151 delete iIt.key();
152 } 152 }
153 153
154#ifdef QWS 154#ifdef QWS
155 // Delete Modules and Libraries 155 // Delete Modules and Libraries
156 QMap<Module*, QLibrary*>::Iterator it; 156 QMap<Module*, QLibrary*>::Iterator it;
157 for( it = libraries.begin(); it != libraries.end(); ++it ) 157 for( it = libraries.begin(); it != libraries.end(); ++it )
158 { 158 {
159 delete it.key(); 159 delete it.key();
160 // I wonder why I can't delete the libraries 160 // I wonder why I can't delete the libraries
161 // What fucking shit this is. 161 // What fucking shit this is.
162 //delete it.data(); 162 //delete it.data();
163 } 163 }
164#else 164#else
165 // klibloader automaticly deletes the libraries for us... 165 // klibloader automaticly deletes the libraries for us...
166#endif 166#endif
167} 167}
168 168
169/** 169/**
170 * Query the kernel for all of the interfaces. 170 * Query the kernel for all of the interfaces.
171 */ 171 */
172void MainWindowImp::getAllInterfaces() 172void MainWindowImp::getAllInterfaces()
173{ 173{
174 int sockfd = socket(PF_INET, SOCK_DGRAM, 0); 174 int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
175 if(sockfd == -1) 175 if(sockfd == -1)
176 return; 176 return;
177 177
178 struct ifreq ifr; 178 struct ifreq ifr;
179 QStringList ifaces; 179 QStringList ifaces;
180 QFile procFile(QString(_PROCNETDEV)); 180 QFile procFile(QString(_PROCNETDEV));
181 int result; 181 int result;
182 Interface *i; 182 Interface *i;
183 183
184 if (! procFile.exists()) 184 if (! procFile.exists())
185 { 185 {
186 struct ifreq ifrs[100]; 186 struct ifreq ifrs[100];
187 struct ifconf ifc; 187 struct ifconf ifc;
188 ifc.ifc_len = sizeof(ifrs); 188 ifc.ifc_len = sizeof(ifrs);
189 ifc.ifc_req = ifrs; 189 ifc.ifc_req = ifrs;
190 result = ioctl(sockfd, SIOCGIFCONF, &ifc); 190 result = ioctl(sockfd, SIOCGIFCONF, &ifc);
191 191
192 for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++) 192 for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++)
193 { 193 {
194 struct ifreq *pifr = &ifrs[i]; 194 struct ifreq *pifr = &ifrs[i];
195 195
196 ifaces += pifr->ifr_name; 196 ifaces += pifr->ifr_name;
197 } 197 }
198 } 198 }
199 else 199 else
200 { 200 {
201 procFile.open(IO_ReadOnly); 201 procFile.open(IO_ReadOnly);
202 QString line; 202 QString line;
203 QTextStream procTs(&procFile); 203 QTextStream procTs(&procFile);
204 int loc = -1; 204 int loc = -1;
205 205
206 procTs.readLine(); // eat a line 206 procTs.readLine(); // eat a line
207 procTs.readLine(); // eat a line 207 procTs.readLine(); // eat a line
208 while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null) 208 while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null)
209 { 209 {
210 if((loc = line.find(":")) != -1) 210 if((loc = line.find(":")) != -1)
211 { 211 {
212 ifaces += line.left(loc); 212 ifaces += line.left(loc);
213 } 213 }
214 } 214 }
215 } 215 }
216 216
217 for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it) 217 for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it)
218 { 218 {
219 int flags = 0; 219 int flags = 0;
220 if ( m_handledIfaces.contains( (*it) ) ) 220 if ( m_handledIfaces.contains( (*it) ) )
221 { 221 {
222 qDebug(" %s is handled by a module", (*it).latin1() ); 222 qDebug(" %s is handled by a module", (*it).latin1() );
223 continue; 223 continue;
224 } 224 }
225 // int family; 225 // int family;
226 i = NULL; 226 i = NULL;
227 227
228 strcpy(ifr.ifr_name, (*it).latin1()); 228 strcpy(ifr.ifr_name, (*it).latin1());
229 229
230 struct ifreq ifcopy; 230 struct ifreq ifcopy;
231 ifcopy = ifr; 231 ifcopy = ifr;
232 result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy); 232 result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy);
233 flags = ifcopy.ifr_flags; 233 flags = ifcopy.ifr_flags;
234 i = new Interface(this, ifr.ifr_name, false); 234 i = new Interface(this, ifr.ifr_name, false);
235 i->setAttached(true); 235 i->setAttached(true);
236 if ((flags & IFF_UP) == IFF_UP) 236 if ((flags & IFF_UP) == IFF_UP)
237 i->setStatus(true); 237 i->setStatus(true);
238 else 238 else
239 i->setStatus(false); 239 i->setStatus(false);
240 240
241 if ((flags & IFF_BROADCAST) == IFF_BROADCAST) 241 if ((flags & IFF_BROADCAST) == IFF_BROADCAST)
242 i->setHardwareName("Ethernet"); 242 i->setHardwareName("Ethernet");
243 else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT) 243 else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT)
244 i->setHardwareName("Point to Point"); 244 i->setHardwareName("Point to Point");
245 else if ((flags & IFF_MULTICAST) == IFF_MULTICAST) 245 else if ((flags & IFF_MULTICAST) == IFF_MULTICAST)
246 i->setHardwareName("Multicast"); 246 i->setHardwareName("Multicast");
247 else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK) 247 else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK)
248 i->setHardwareName("Loopback"); 248 i->setHardwareName("Loopback");
249 else 249 else
250 i->setHardwareName("Unknown"); 250 i->setHardwareName("Unknown");
251 251
252 qWarning("Adding interface %s to interfaceNames\n", ifr.ifr_name); 252 qWarning("Adding interface %s to interfaceNames\n", ifr.ifr_name);
253 interfaceNames.insert(i->getInterfaceName(), i); 253 interfaceNames.insert(i->getInterfaceName(), i);
254 updateInterface(i); 254 updateInterface(i);
255 connect(i, SIGNAL(updateInterface(Interface *)), 255 connect(i, SIGNAL(updateInterface(Interface*)),
256 this, SLOT(updateInterface(Interface *))); 256 this, SLOT(updateInterface(Interface*)));
257 } 257 }
258 // now lets ask the plugins too ;) 258 // now lets ask the plugins too ;)
259 QMap<Module*, QLibrary*>::Iterator it; 259 QMap<Module*, QLibrary*>::Iterator it;
260 QList<Interface> ilist; 260 QList<Interface> ilist;
261 for( it = libraries.begin(); it != libraries.end(); ++it ) 261 for( it = libraries.begin(); it != libraries.end(); ++it )
262 { 262 {
263 if(it.key()) 263 if(it.key())
264 { 264 {
265 ilist = it.key()->getInterfaces(); 265 ilist = it.key()->getInterfaces();
266 for( i = ilist.first(); i != 0; i = ilist.next() ) 266 for( i = ilist.first(); i != 0; i = ilist.next() )
267 { 267 {
268 qWarning("Adding interface %s to interfaceNames\n", i->getInterfaceName().latin1() ); 268 qWarning("Adding interface %s to interfaceNames\n", i->getInterfaceName().latin1() );
269 interfaceNames.insert(i->getInterfaceName(), i); 269 interfaceNames.insert(i->getInterfaceName(), i);
270 updateInterface(i); 270 updateInterface(i);
271 connect(i, SIGNAL(updateInterface(Interface *)), 271 connect(i, SIGNAL(updateInterface(Interface*)),
272 this, SLOT(updateInterface(Interface *))); 272 this, SLOT(updateInterface(Interface*)));
273 } 273 }
274 } 274 }
275 } 275 }
276} 276}
277 277
278/** 278/**
279 * Load all modules that are found in the path 279 * Load all modules that are found in the path
280 * @param path a directory that is scaned for any plugins that can be loaded 280 * @param path a directory that is scaned for any plugins that can be loaded
281 * and attempts to load them 281 * and attempts to load them
282 */ 282 */
283void MainWindowImp::loadModules(const QString &path) 283void MainWindowImp::loadModules(const QString &path)
284{ 284{
285#ifdef DEBUG 285#ifdef DEBUG
286 qDebug("MainWindowImp::loadModules: %s", path.latin1()); 286 qDebug("MainWindowImp::loadModules: %s", path.latin1());
287#endif 287#endif
288 QDir d(path); 288 QDir d(path);
289 if(!d.exists()) 289 if(!d.exists())
290 return; 290 return;
291 291
292 // Don't want sym links 292 // Don't want sym links
293 d.setFilter( QDir::Files | QDir::NoSymLinks ); 293 d.setFilter( QDir::Files | QDir::NoSymLinks );
294 const QFileInfoList *list = d.entryInfoList(); 294 const QFileInfoList *list = d.entryInfoList();
295 QFileInfoListIterator it( *list ); 295 QFileInfoListIterator it( *list );
296 QFileInfo *fi; 296 QFileInfo *fi;
297 while ( (fi=it.current()) ) 297 while ( (fi=it.current()) )
298 { 298 {
299#ifdef QWS 299#ifdef QWS
300 if(fi->fileName().contains(".so")) 300 if(fi->fileName().contains(".so"))
301 { 301 {
302#else 302#else
303 if(fi->fileName().contains(".so") && fi->fileName().contains("networksettings_")) 303 if(fi->fileName().contains(".so") && fi->fileName().contains("networksettings_"))
304 { 304 {
305#endif 305#endif
306 loadPlugin(path + "/" + fi->fileName()); 306 loadPlugin(path + "/" + fi->fileName());
307 qDebug("loaded plugin: >%s< ",QString(path + "/" + fi->fileName()).latin1()); 307 qDebug("loaded plugin: >%s< ",QString(path + "/" + fi->fileName()).latin1());
308 } 308 }
309 ++it; 309 ++it;
310 } 310 }
311} 311}
312 312
313/** 313/**
314 * Attempt to load a function and resolve a function. 314 * Attempt to load a function and resolve a function.
315 * @param pluginFileName - the name of the file in which to attempt to load 315 * @param pluginFileName - the name of the file in which to attempt to load
316 * @param resolveString - function pointer to resolve 316 * @param resolveString - function pointer to resolve
317 * @return pointer to the function with name resolveString or NULL 317 * @return pointer to the function with name resolveString or NULL
318 */ 318 */
319Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString) 319Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString)
320{ 320{
321#ifdef DEBUG 321#ifdef DEBUG
322 qDebug("MainWindowImp::loadPlugin: %s: resolving %s", pluginFileName.latin1(), resolveString.latin1()); 322 qDebug("MainWindowImp::loadPlugin: %s: resolving %s", pluginFileName.latin1(), resolveString.latin1());
323#endif 323#endif
324#ifdef QWS 324#ifdef QWS
325 QLibrary *lib = new QLibrary(pluginFileName); 325 QLibrary *lib = new QLibrary(pluginFileName);
326 void *functionPointer = lib->resolve(resolveString); 326 void *functionPointer = lib->resolve(resolveString);
327 if( !functionPointer ) 327 if( !functionPointer )
328 { 328 {
329#ifdef DEBUG 329#ifdef DEBUG
330 qDebug("MainWindowImp::loadPlugin: Warning: %s is not a plugin", pluginFileName.latin1()); 330 qDebug("MainWindowImp::loadPlugin: Warning: %s is not a plugin", pluginFileName.latin1());
331#endif 331#endif
332 delete lib; 332 delete lib;
333 return NULL; 333 return NULL;
334 } 334 }
335 // Try to get an object. 335 // Try to get an object.
336 Module *object = ((Module* (*)()) functionPointer)(); 336 Module *object = ((Module* (*)()) functionPointer)();
337 if(object == NULL) 337 if(object == NULL)
338 { 338 {
339#ifdef DEBUG 339#ifdef DEBUG
340 qDebug("MainWindowImp: Couldn't create object, but did load library!"); 340 qDebug("MainWindowImp: Couldn't create object, but did load library!");
341#endif 341#endif
342 delete lib; 342 delete lib;
343 return NULL; 343 return NULL;
344 } 344 }
345 345
346 m_handledIfaces += object->handledInterfaceNames(); 346 m_handledIfaces += object->handledInterfaceNames();
347 // Store for deletion later 347 // Store for deletion later
348 libraries.insert(object, lib); 348 libraries.insert(object, lib);
349 return object; 349 return object;
350 350
351#else 351#else
352 QLibrary *lib = loader->library(pluginFileName); 352 QLibrary *lib = loader->library(pluginFileName);
353 if( !lib || !lib->hasSymbol(resolveString) ) 353 if( !lib || !lib->hasSymbol(resolveString) )
354 { 354 {
355 qDebug(QString("MainWindowImp::loadPlugin: File: %1 is not a plugin, but though was.").arg(pluginFileName).latin1()); 355 qDebug(QString("MainWindowImp::loadPlugin: File: %1 is not a plugin, but though was.").arg(pluginFileName).latin1());
356 return NULL; 356 return NULL;
357 } 357 }
358 // Try to get an object. 358 // Try to get an object.
359 Module *object = ((Module* (*)()) lib->symbol(resolveString))(); 359 Module *object = ((Module* (*)()) lib->symbol(resolveString))();
360 if(object == NULL) 360 if(object == NULL)
361 { 361 {
362#ifdef DEBUG 362#ifdef DEBUG
363 qDebug("MainWindowImp: Couldn't create object, but did load library!"); 363 qDebug("MainWindowImp: Couldn't create object, but did load library!");
364#endif 364#endif
365 return NULL; 365 return NULL;
366 } 366 }
367#ifdef DEBUG 367#ifdef DEBUG
368 qDebug("MainWindowImp::loadPlugin:: Found object, storing."); 368 qDebug("MainWindowImp::loadPlugin:: Found object, storing.");
369#endif 369#endif
370 // Store for deletion later 370 // Store for deletion later
371 libraries.insert(object, lib); 371 libraries.insert(object, lib);
372 return object; 372 return object;
373#endif 373#endif
374} 374}
375 375
376/** 376/**
377 * The Add button was clicked. Bring up the add dialog and if OK is hit 377 * The Add button was clicked. Bring up the add dialog and if OK is hit
378 * load the plugin and append it to the list 378 * load the plugin and append it to the list
379 */ 379 */
380void MainWindowImp::addClicked() 380void MainWindowImp::addClicked()
381{ 381{
382 QMap<Module*, QLibrary*>::Iterator it; 382 QMap<Module*, QLibrary*>::Iterator it;
383 QMap<QString, QString> list; 383 QMap<QString, QString> list;
384 QMap<QString, Module*> newInterfaceOwners; 384 QMap<QString, Module*> newInterfaceOwners;
385 385
386 for( it = libraries.begin(); it != libraries.end(); ++it ) 386 for( it = libraries.begin(); it != libraries.end(); ++it )
387 { 387 {
388 if(it.key()) 388 if(it.key())
389 { 389 {
390 (it.key())->possibleNewInterfaces(list); 390 (it.key())->possibleNewInterfaces(list);
391 } 391 }
392 } 392 }
393 // See if the list has anything that we can add. 393 // See if the list has anything that we can add.
394 if(list.count() == 0) 394 if(list.count() == 0)
395 { 395 {
396 QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok); 396 QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok);
397 return; 397 return;
398 } 398 }
399 AddConnectionImp addNewConnection(this, "AddConnectionImp", true); 399 AddConnectionImp addNewConnection(this, "AddConnectionImp", true);
400 addNewConnection.addConnections(list); 400 addNewConnection.addConnections(list);
401 if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) ) 401 if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) )
402 { 402 {
403 QListViewItem *item = addNewConnection.registeredServicesList->currentItem(); 403 QListViewItem *item = addNewConnection.registeredServicesList->currentItem();
404 if(!item) 404 if(!item)
405 return; 405 return;
406 406
407 for( it = libraries.begin(); it != libraries.end(); ++it ) 407 for( it = libraries.begin(); it != libraries.end(); ++it )
408 { 408 {
409 if(it.key()) 409 if(it.key())
410 { 410 {
411 Interface *i = (it.key())->addNewInterface(item->text(0)); 411 Interface *i = (it.key())->addNewInterface(item->text(0));
412 if(i) 412 if(i)
413 { 413 {
414 qDebug("iface name %s",i->getInterfaceName().latin1()); 414 qDebug("iface name %s",i->getInterfaceName().latin1());
415 interfaceNames.insert(i->getInterfaceName(), i); 415 interfaceNames.insert(i->getInterfaceName(), i);
416 updateInterface(i); 416 updateInterface(i);
417 } 417 }
418 } 418 }
419 } 419 }
420 } 420 }
421} 421}
422 422
423/** 423/**
424 * Prompt the user to see if they really want to do this. 424 * Prompt the user to see if they really want to do this.
425 * If they do then remove from the list and unload. 425 * If they do then remove from the list and unload.
426 */ 426 */
427void MainWindowImp::removeClicked() 427void MainWindowImp::removeClicked()
428{ 428{
429 QListViewItem *item = connectionList->currentItem(); 429 QListViewItem *item = connectionList->currentItem();
430 if(!item) 430 if(!item)
431 { 431 {
432 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); 432 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
433 return; 433 return;
434 } 434 }
435 435
436 Interface *i = interfaceItems[item]; 436 Interface *i = interfaceItems[item];
437 if(i->getModuleOwner() == NULL) 437 if(i->getModuleOwner() == NULL)
438 { 438 {
439 QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok); 439 QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok);
440 } 440 }
441 else 441 else
442 { 442 {
443 if(!i->getModuleOwner()->remove(i)) 443 if(!i->getModuleOwner()->remove(i))
444 QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok); 444 QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok);
445 else 445 else
446 { 446 {
447 delete item; 447 delete item;
448 // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok); 448 // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok);
449 } 449 }
450 } 450 }
451} 451}
452 452
453/** 453/**
454 * Pull up the configure about the currently selected interface. 454 * Pull up the configure about the currently selected interface.
455 * Report an error if no interface is selected. 455 * Report an error if no interface is selected.
456 * If the interface has a module owner then request its configure. 456 * If the interface has a module owner then request its configure.
457 */ 457 */
458void MainWindowImp::configureClicked() 458void MainWindowImp::configureClicked()
459{ 459{
460 QListViewItem *item = connectionList->currentItem(); 460 QListViewItem *item = connectionList->currentItem();
461 if(!item) 461 if(!item)
462 { 462 {
463 QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok); 463 QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok);
464 return; 464 return;
465 } 465 }
466 466
467 QString currentProfileText = currentProfileLabel->text(); 467 QString currentProfileText = currentProfileLabel->text();
468 if(currentProfileText.upper() == "ALL"); 468 if(currentProfileText.upper() == "ALL");
469 currentProfileText = ""; 469 currentProfileText = "";
470 470
471 Interface *i = interfaceItems[item]; 471 Interface *i = interfaceItems[item];
472 472
473 if(i->getModuleOwner()) 473 if(i->getModuleOwner())
474 { 474 {
475 QWidget *moduleConfigure = i->getModuleOwner()->configure(i); 475 QWidget *moduleConfigure = i->getModuleOwner()->configure(i);
476 if(moduleConfigure != NULL) 476 if(moduleConfigure != NULL)
477 { 477 {
478 i->getModuleOwner()->setProfile(currentProfileText); 478 i->getModuleOwner()->setProfile(currentProfileText);
479 QPEApplication::showWidget( moduleConfigure ); 479 QPEApplication::showWidget( moduleConfigure );
480 return; 480 return;
481 } 481 }
482 } 482 }
483 483
484 InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp ); 484 InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp );
485 configure->setProfile(currentProfileText); 485 configure->setProfile(currentProfileText);
486 QPEApplication::showDialog( configure ); 486 QPEApplication::showDialog( configure );
487} 487}
488 488
489/** 489/**
490 * Pull up the information about the currently selected interface. 490 * Pull up the information about the currently selected interface.
491 * Report an error if no interface is selected. 491 * Report an error if no interface is selected.
492 * If the interface has a module owner then request its configure. 492 * If the interface has a module owner then request its configure.
493 */ 493 */
494void MainWindowImp::informationClicked() 494void MainWindowImp::informationClicked()
495{ 495{
496 QListViewItem *item = connectionList->currentItem(); 496 QListViewItem *item = connectionList->currentItem();
497 if(!item) 497 if(!item)
498 { 498 {
499 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); 499 QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok);
500 return; 500 return;
501 } 501 }
502 502
503 Interface *i = interfaceItems[item]; 503 Interface *i = interfaceItems[item];
504 // if(!i->isAttached()){ 504 // if(!i->isAttached()){
505 // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok); 505 // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok);
506 // return; 506 // return;
507 // } 507 // }
508 508
509 if(i->getModuleOwner()) 509 if(i->getModuleOwner())
510 { 510 {
511 QWidget *moduleInformation = i->getModuleOwner()->information(i); 511 QWidget *moduleInformation = i->getModuleOwner()->information(i);
512 if(moduleInformation != NULL) 512 if(moduleInformation != NULL)
513 { 513 {
514 QPEApplication::showWidget( moduleInformation ); 514 QPEApplication::showWidget( moduleInformation );
515#ifdef DEBUG 515#ifdef DEBUG
516 qDebug("MainWindowImp::informationClicked:: Module owner has created, we showed."); 516 qDebug("MainWindowImp::informationClicked:: Module owner has created, we showed.");
517#endif 517#endif
518 return; 518 return;
519 } 519 }
520 } 520 }
521 InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp); 521 InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp);
522 QPEApplication::showWidget( information ); 522 QPEApplication::showWidget( information );
523} 523}
524 524
525/** 525/**
526 * Update this interface. If no QListViewItem exists create one. 526 * Update this interface. If no QListViewItem exists create one.
527 * @param Interface* pointer to the interface that needs to be updated. 527 * @param Interface* pointer to the interface that needs to be updated.
528 */ 528 */
529void MainWindowImp::updateInterface(Interface *i) 529void MainWindowImp::updateInterface(Interface *i)
530{ 530{
531 if(!advancedUserMode) 531 if(!advancedUserMode)
532 { 532 {
533 if(i->getInterfaceName() == "lo") 533 if(i->getInterfaceName() == "lo")
534 return; 534 return;
535 } 535 }
536 536
537 QListViewItem *item = NULL; 537 QListViewItem *item = NULL;
538 538
539 // Find the interface, making it if needed. 539 // Find the interface, making it if needed.
540 if(items.find(i) == items.end()) 540 if(items.find(i) == items.end())
541 { 541 {
542 item = new QListViewItem(connectionList, "", "", ""); 542 item = new QListViewItem(connectionList, "", "", "");
543 // See if you can't find a module owner for this interface 543 // See if you can't find a module owner for this interface
544 QMap<Module*, QLibrary*>::Iterator it; 544 QMap<Module*, QLibrary*>::Iterator it;
545 for( it = libraries.begin(); it != libraries.end(); ++it ) 545 for( it = libraries.begin(); it != libraries.end(); ++it )
546 { 546 {
547 if(it.key()->isOwner(i)) 547 if(it.key()->isOwner(i))
548 i->setModuleOwner(it.key()); 548 i->setModuleOwner(it.key());
549 } 549 }
550 items.insert(i, item); 550 items.insert(i, item);
551 interfaceItems.insert(item, i); 551 interfaceItems.insert(item, i);
552 } 552 }
553 else 553 else
554 item = items[i]; 554 item = items[i];
555 555
556 // Update the icons and information 556 // Update the icons and information
557#ifdef QWS 557#ifdef QWS
558 item->setPixmap(0, (Resource::loadPixmap(i->getStatus() ? "up": "down"))); 558 item->setPixmap(0, (Resource::loadPixmap(i->getStatus() ? "up": "down")));
559#else 559#else
560 item->setPixmap(0, (SmallIcon(i->getStatus() ? "up": "down"))); 560 item->setPixmap(0, (SmallIcon(i->getStatus() ? "up": "down")));
561#endif 561#endif
562 562
563 QString typeName = "lan"; 563 QString typeName = "lan";
564 if(i->getInterfaceName() == "lo") 564 if(i->getInterfaceName() == "lo")
565 typeName = "lo"; 565 typeName = "lo";
566 if(i->getInterfaceName().contains("irda")) 566 if(i->getInterfaceName().contains("irda"))
567 typeName = "irda"; 567 typeName = "irda";
568 if(i->getInterfaceName().contains("wlan")) 568 if(i->getInterfaceName().contains("wlan"))
569 typeName = "wlan"; 569 typeName = "wlan";
570 if(i->getInterfaceName().contains("usb")) 570 if(i->getInterfaceName().contains("usb"))
571 typeName = "usb"; 571 typeName = "usb";
572 572
573 if(!i->isAttached()) 573 if(!i->isAttached())
574 typeName = "connect_no"; 574 typeName = "connect_no";
575 // Actually try to use the Module 575 // Actually try to use the Module
576 if(i->getModuleOwner() != NULL) 576 if(i->getModuleOwner() != NULL)
577 typeName = i->getModuleOwner()->getPixmapName(i); 577 typeName = i->getModuleOwner()->getPixmapName(i);
578 578
579#ifdef QWS 579#ifdef QWS
580 item->setPixmap(1, (Resource::loadPixmap(QString("networksettings/") + typeName))); 580 item->setPixmap(1, (Resource::loadPixmap(QString("networksettings/") + typeName)));
581#else 581#else
582 item->setPixmap(1, (SmallIcon(typeName))); 582 item->setPixmap(1, (SmallIcon(typeName)));
583#endif 583#endif
584 item->setText(2, i->getHardwareName()); 584 item->setText(2, i->getHardwareName());
585 item->setText(3, QString("(%1)").arg(i->getInterfaceName())); 585 item->setText(3, QString("(%1)").arg(i->getInterfaceName()));
586 item->setText(4, (i->getStatus()) ? i->getIp() : QString("")); 586 item->setText(4, (i->getStatus()) ? i->getIp() : QString(""));
587} 587}
588 588
589void MainWindowImp::newProfileChanged(const QString& newText) 589void MainWindowImp::newProfileChanged(const QString& newText)
590{ 590{
591 if(newText.length() > 0) 591 if(newText.length() > 0)
592 newProfileButton->setEnabled(true); 592 newProfileButton->setEnabled(true);
593 else 593 else
594 newProfileButton->setEnabled(false); 594 newProfileButton->setEnabled(false);
595} 595}
596 596
597/** 597/**
598 * Adds a new profile to the list of profiles. 598 * Adds a new profile to the list of profiles.
599 * Don't add profiles that already exists. 599 * Don't add profiles that already exists.
600 * Appends to the list and QStringList 600 * Appends to the list and QStringList
601 */ 601 */
602void MainWindowImp::addProfile() 602void MainWindowImp::addProfile()
603{ 603{
604 QString newProfileName = newProfile->text(); 604 QString newProfileName = newProfile->text();
605 if(profiles.grep(newProfileName).count() > 0) 605 if(profiles.grep(newProfileName).count() > 0)
606 { 606 {
607 QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok); 607 QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok);
608 return; 608 return;
609 } 609 }
610 profiles.append(newProfileName); 610 profiles.append(newProfileName);
611 profilesList->insertItem(newProfileName); 611 profilesList->insertItem(newProfileName);
612} 612}
613 613
614/** 614/**
615 * Removes the currently selected profile in the combo. 615 * Removes the currently selected profile in the combo.
616 * Doesn't delete if there are less then 2 profiles. 616 * Doesn't delete if there are less then 2 profiles.
617 */ 617 */
618void MainWindowImp::removeProfile() 618void MainWindowImp::removeProfile()
619{ 619{
620 if(profilesList->count() <= 1) 620 if(profilesList->count() <= 1)
621 { 621 {
622 QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok); 622 QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok);
623 return; 623 return;
624 } 624 }
625 QString profileToRemove = profilesList->currentText(); 625 QString profileToRemove = profilesList->currentText();
626 if(profileToRemove == "All") 626 if(profileToRemove == "All")
627 { 627 {
628 QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok); 628 QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok);
629 return; 629 return;
630 } 630 }
631 // Can't remove the curent profile 631 // Can't remove the curent profile
632 if(profileToRemove == currentProfileLabel->text()) 632 if(profileToRemove == currentProfileLabel->text())
633 { 633 {
634 QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok); 634 QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok);
635 return; 635 return;
636 636
637 } 637 }
638 638
639 if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) 639 if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
640 { 640 {
641 profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), "")); 641 profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), ""));
642 profilesList->clear(); 642 profilesList->clear();
643 for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it) 643 for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it)
644 profilesList->insertItem((*it)); 644 profilesList->insertItem((*it));
645 645
646 // Remove any interface settings and mappings. 646 // Remove any interface settings and mappings.
647 Interfaces interfaces; 647 Interfaces interfaces;
648 // Go through them one by one 648 // Go through them one by one
649 QMap<Interface*, QListViewItem*>::Iterator it; 649 QMap<Interface*, QListViewItem*>::Iterator it;
650 for( it = items.begin(); it != items.end(); ++it ) 650 for( it = items.begin(); it != items.end(); ++it )
651 { 651 {
652 QString interfaceName = it.key()->getInterfaceName(); 652 QString interfaceName = it.key()->getInterfaceName();
653 qDebug(interfaceName.latin1()); 653 qDebug(interfaceName.latin1());
654 if(interfaces.setInterface(interfaceName + "_" + profileToRemove)) 654 if(interfaces.setInterface(interfaceName + "_" + profileToRemove))
655 { 655 {
656 interfaces.removeInterface(); 656 interfaces.removeInterface();
657 if(interfaces.setMapping(interfaceName)) 657 if(interfaces.setMapping(interfaceName))
658 { 658 {
659 if(profilesList->count() == 1) 659 if(profilesList->count() == 1)
660 interfaces.removeMapping(); 660 interfaces.removeMapping();
661 else 661 else
662 { 662 {
663 interfaces.removeMap("map", interfaceName + "_" + profileToRemove); 663 interfaces.removeMap("map", interfaceName + "_" + profileToRemove);
664 } 664 }
665 } 665 }
666 interfaces.write(); 666 interfaces.write();
667 break; 667 break;
668 } 668 }
669 } 669 }
670 } 670 }
671} 671}
672 672
673/** 673/**
674 * A new profile has been selected, change. 674 * A new profile has been selected, change.
675 * @param newProfile the new profile. 675 * @param newProfile the new profile.
676 */ 676 */
677void MainWindowImp::changeProfile() 677void MainWindowImp::changeProfile()
678{ 678{
679 if(profilesList->currentItem() == -1) 679 if(profilesList->currentItem() == -1)
680 { 680 {
681 QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok); 681 QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok);
682 return; 682 return;
683 } 683 }
684 QString newProfile = profilesList->text(profilesList->currentItem()); 684 QString newProfile = profilesList->text(profilesList->currentItem());
685 if(newProfile != currentProfileLabel->text()) 685 if(newProfile != currentProfileLabel->text())
686 { 686 {
687 currentProfileLabel->setText(newProfile); 687 currentProfileLabel->setText(newProfile);
688 QFile::remove(scheme); 688 QFile::remove(scheme);
689 QFile file(scheme); 689 QFile file(scheme);
690 if ( file.open(IO_ReadWrite) ) 690 if ( file.open(IO_ReadWrite) )
691 { 691 {
692 QTextStream stream( &file ); 692 QTextStream stream( &file );
693 stream << QString("SCHEME=%1").arg(newProfile); 693 stream << QString("SCHEME=%1").arg(newProfile);
694 file.close(); 694 file.close();
695 } 695 }
696 // restart all up devices? 696 // restart all up devices?
697 if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok) 697 if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok)
698 { 698 {
699 // Go through them one by one 699 // Go through them one by one
700 QMap<Interface*, QListViewItem*>::Iterator it; 700 QMap<Interface*, QListViewItem*>::Iterator it;
701 for( it = items.begin(); it != items.end(); ++it ) 701 for( it = items.begin(); it != items.end(); ++it )
702 { 702 {
703 if(it.key()->getStatus() == true) 703 if(it.key()->getStatus() == true)
704 it.key()->restart(); 704 it.key()->restart();
705 } 705 }
706 } 706 }
707 } 707 }
708 // TODO change the profile in the modules 708 // TODO change the profile in the modules
709} 709}
710 710
711 711
712void MainWindowImp::makeChannel() 712void MainWindowImp::makeChannel()
713{ 713{
714 channel = new QCopChannel( "QPE/Application/networksettings", this ); 714 channel = new QCopChannel( "QPE/Application/networksettings", this );
715 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 715 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
716 this, SLOT(receive(const QCString&, const QByteArray&)) ); 716 this, SLOT(receive(const QCString&,const QByteArray&)) );
717} 717}
718 718
719void MainWindowImp::receive(const QCString &msg, const QByteArray &arg) 719void MainWindowImp::receive(const QCString &msg, const QByteArray &arg)
720{ 720{
721 bool found = false; 721 bool found = false;
722 qDebug("MainWindowImp::receive QCop msg >"+msg+"<"); 722 qDebug("MainWindowImp::receive QCop msg >"+msg+"<");
723 if (msg == "raise") 723 if (msg == "raise")
724 { 724 {
725 raise(); 725 raise();
726 return; 726 return;
727 } 727 }
728 728
729 QString dest = msg.left(msg.find("(")); 729 QString dest = msg.left(msg.find("("));
730 QCString param = msg.right(msg.length() - msg.find("(") - 1); 730 QCString param = msg.right(msg.length() - msg.find("(") - 1);
731 param = param.left( param.length() - 1 ); 731 param = param.left( param.length() - 1 );
732 qDebug("dest >%s< param >"+param+"<",dest.latin1()); 732 qDebug("dest >%s< param >"+param+"<",dest.latin1());
733 733
734 QMap<Module*, QLibrary*>::Iterator it; 734 QMap<Module*, QLibrary*>::Iterator it;
735 for( it = libraries.begin(); it != libraries.end(); ++it ) 735 for( it = libraries.begin(); it != libraries.end(); ++it )
736 { 736 {
737 qDebug("plugin >%s<", it.key()->type().latin1() ); 737 qDebug("plugin >%s<", it.key()->type().latin1() );
738 if(it.key()->type() == dest) 738 if(it.key()->type() == dest)
739 { 739 {
740 it.key()->receive( param, arg ); 740 it.key()->receive( param, arg );
741 found = true; 741 found = true;
742 } 742 }
743 } 743 }
744 744
745 745
746 if (found) QPEApplication::setKeepRunning(); 746 if (found) QPEApplication::setKeepRunning();
747 else qDebug("Huh what do ya want"); 747 else qDebug("Huh what do ya want");
748} 748}
diff --git a/noncore/settings/networksettings/ppp/edit.cpp b/noncore/settings/networksettings/ppp/edit.cpp
index 7d21605..3b2393c 100644
--- a/noncore/settings/networksettings/ppp/edit.cpp
+++ b/noncore/settings/networksettings/ppp/edit.cpp
@@ -1,1211 +1,1211 @@
1/* 1/*
2 * kPPP: A pppd Front End for the KDE project 2 * kPPP: A pppd Front End for the KDE project
3 * 3 *
4 * $Id$ 4 * $Id$
5 * Copyright (C) 1997 Bernd Johannes Wuebben 5 * Copyright (C) 1997 Bernd Johannes Wuebben
6 * wuebben@math.cornell.edu 6 * wuebben@math.cornell.edu
7 * 7 *
8 * based on EzPPP: 8 * based on EzPPP:
9 * Copyright (C) 1997 Jay Painter 9 * Copyright (C) 1997 Jay Painter
10 * 10 *
11 * This program is free software; you can redistribute it and/or 11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public 12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either 13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version. 14 * version 2 of the License, or (at your option) any later version.
15 * 15 *
16 * This program is distributed in the hope that it will be useful, 16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details. 19 * Library General Public License for more details.
20 * 20 *
21 * You should have received a copy of the GNU Library General Public 21 * You should have received a copy of the GNU Library General Public
22 * License along with this program; if not, write to the Free 22 * License along with this program; if not, write to the Free
23 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 23 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */ 24 */
25 25
26#include "edit.h" 26#include "edit.h"
27#include "pppdata.h" 27#include "pppdata.h"
28#include "iplined.h" 28#include "iplined.h"
29#include "auth.h" 29#include "auth.h"
30 30
31/* OPIE */ 31/* OPIE */
32#include <qpe/resource.h> 32#include <qpe/resource.h>
33#include <qpe/qpeapplication.h> 33#include <qpe/qpeapplication.h>
34 34
35/* QT */ 35/* QT */
36#include <qlayout.h> 36#include <qlayout.h>
37#include <qmessagebox.h> 37#include <qmessagebox.h>
38#include <qwhatsthis.h> 38#include <qwhatsthis.h>
39#include <qregexp.h> 39#include <qregexp.h>
40#include <qapplication.h> 40#include <qapplication.h>
41#include <qbuttongroup.h> 41#include <qbuttongroup.h>
42#include <qvgroupbox.h> 42#include <qvgroupbox.h>
43#include <qhbox.h> 43#include <qhbox.h>
44#include <qdialog.h> 44#include <qdialog.h>
45 45
46/* STD */ 46/* STD */
47 47
48#include <string.h> 48#include <string.h>
49#include <termios.h> 49#include <termios.h>
50 50
51DialWidget::DialWidget( PPPData *pd, QWidget *parent, bool isnewaccount 51DialWidget::DialWidget( PPPData *pd, QWidget *parent, bool isnewaccount
52 , const char *name ) 52 , const char *name )
53 : QWidget(parent, name), _pppdata(pd) 53 : QWidget(parent, name), _pppdata(pd)
54{ 54{
55 const int GRIDROWS = 6; 55 const int GRIDROWS = 6;
56 56
57 QGridLayout *tl = new QGridLayout(this, GRIDROWS, 2, 0 ); 57 QGridLayout *tl = new QGridLayout(this, GRIDROWS, 2, 0 );
58 58
59 connect_label = new QLabel(tr("Connection name:"), this); 59 connect_label = new QLabel(tr("Connection name:"), this);
60 tl->addWidget(connect_label, 0, 0); 60 tl->addWidget(connect_label, 0, 0);
61 61
62 connectname_l = new QLineEdit(this); 62 connectname_l = new QLineEdit(this);
63 // connectname_l->setMaxLength(ACCNAME_SIZE); 63 // connectname_l->setMaxLength(ACCNAME_SIZE);
64 tl->addWidget(connectname_l, 0, 1); 64 tl->addWidget(connectname_l, 0, 1);
65 QString tmp = tr("Type in a unique name for this connection"); 65 QString tmp = tr("Type in a unique name for this connection");
66 66
67 QWhatsThis::add(connect_label,tmp); 67 QWhatsThis::add(connect_label,tmp);
68 QWhatsThis::add(connectname_l,tmp); 68 QWhatsThis::add(connectname_l,tmp);
69 69
70 70
71 number_label = new QLabel(tr("Phone number:"), this); 71 number_label = new QLabel(tr("Phone number:"), this);
72 number_label->setAlignment(AlignTop|AlignLeft); 72 number_label->setAlignment(AlignTop|AlignLeft);
73 tl->addWidget(number_label, 1, 0); 73 tl->addWidget(number_label, 1, 0);
74 74
75 QHBoxLayout *lpn = new QHBoxLayout(5); 75 QHBoxLayout *lpn = new QHBoxLayout(5);
76 tl->addLayout(lpn, 1, 1); 76 tl->addLayout(lpn, 1, 1);
77 numbers = new QListBox(this); 77 numbers = new QListBox(this);
78 // numbers->setMinimumSize(120, 70); 78 // numbers->setMinimumSize(120, 70);
79 lpn->addWidget(numbers); 79 lpn->addWidget(numbers);
80 QVBoxLayout *lpn1 = new QVBoxLayout; 80 QVBoxLayout *lpn1 = new QVBoxLayout;
81 lpn->addLayout(lpn1); 81 lpn->addLayout(lpn1);
82 add = new QPushButton(tr("&Add..."), this); 82 add = new QPushButton(tr("&Add..."), this);
83 del = new QPushButton(tr("&Remove"), this); 83 del = new QPushButton(tr("&Remove"), this);
84 84
85 up = new QPushButton(this); 85 up = new QPushButton(this);
86 up->setPixmap( Resource::loadPixmap("up") ); 86 up->setPixmap( Resource::loadPixmap("up") );
87 down = new QPushButton(this); 87 down = new QPushButton(this);
88 down->setPixmap( Resource::loadPixmap("down") ); 88 down->setPixmap( Resource::loadPixmap("down") );
89 lpn1->addWidget(add); 89 lpn1->addWidget(add);
90 lpn1->addWidget(del); 90 lpn1->addWidget(del);
91 lpn1->addStretch(1); 91 lpn1->addStretch(1);
92 lpn1->addWidget(up); 92 lpn1->addWidget(up);
93 lpn1->addWidget(down); 93 lpn1->addWidget(down);
94 connect(add, SIGNAL(clicked()), 94 connect(add, SIGNAL(clicked()),
95 this, SLOT(addNumber())); 95 this, SLOT(addNumber()));
96 connect(del, SIGNAL(clicked()), 96 connect(del, SIGNAL(clicked()),
97 this, SLOT(delNumber())); 97 this, SLOT(delNumber()));
98 connect(up, SIGNAL(clicked()), 98 connect(up, SIGNAL(clicked()),
99 this, SLOT(upNumber())); 99 this, SLOT(upNumber()));
100 connect(down, SIGNAL(clicked()), 100 connect(down, SIGNAL(clicked()),
101 this, SLOT(downNumber())); 101 this, SLOT(downNumber()));
102 connect(numbers, SIGNAL(highlighted(int)), 102 connect(numbers, SIGNAL(highlighted(int)),
103 this, SLOT(selectionChanged(int))); 103 this, SLOT(selectionChanged(int)));
104 numbersChanged(); 104 numbersChanged();
105 105
106 tmp = tr("<p>Specifies the phone numbers to dial. You\n" 106 tmp = tr("<p>Specifies the phone numbers to dial. You\n"
107 "can supply multiple numbers here, simply\n" 107 "can supply multiple numbers here, simply\n"
108 "click on \"Add\". You can arrange the\n" 108 "click on \"Add\". You can arrange the\n"
109 "order the numbers are tried by using the\n" 109 "order the numbers are tried by using the\n"
110 "arrow buttons.\n\n" 110 "arrow buttons.\n\n"
111 "When a number is busy or fails, <i>kppp</i> will \n" 111 "When a number is busy or fails, <i>kppp</i> will \n"
112 "try the next number and so on"); 112 "try the next number and so on");
113 113
114 QWhatsThis::add(number_label,tmp); 114 QWhatsThis::add(number_label,tmp);
115 QWhatsThis::add(numbers,tmp); 115 QWhatsThis::add(numbers,tmp);
116 116
117 pppdargs = new QPushButton(tr("Customize pppd Arguments..."), this); 117 pppdargs = new QPushButton(tr("Customize pppd Arguments..."), this);
118 connect(pppdargs, SIGNAL(clicked()), SLOT(pppdargsbutton())); 118 connect(pppdargs, SIGNAL(clicked()), SLOT(pppdargsbutton()));
119 tl->addMultiCellWidget(pppdargs, 5, 5, 0, 1, AlignCenter); 119 tl->addMultiCellWidget(pppdargs, 5, 5, 0, 1, AlignCenter);
120 120
121 // Set defaults if editing an existing connection 121 // Set defaults if editing an existing connection
122 if(!isnewaccount) 122 if(!isnewaccount)
123 { 123 {
124 connectname_l->setText(_pppdata->accname()); 124 connectname_l->setText(_pppdata->accname());
125 125
126 // insert the phone numbers into the listbox 126 // insert the phone numbers into the listbox
127 QString n = _pppdata->phonenumber(); 127 QString n = _pppdata->phonenumber();
128 QString tmp = ""; 128 QString tmp = "";
129 uint idx = 0; 129 uint idx = 0;
130 while(idx != n.length()) 130 while(idx != n.length())
131 { 131 {
132 if(n[idx] == ':') 132 if(n[idx] == ':')
133 { 133 {
134 if(tmp.length() > 0) 134 if(tmp.length() > 0)
135 numbers->insertItem(tmp); 135 numbers->insertItem(tmp);
136 tmp = ""; 136 tmp = "";
137 } 137 }
138 else 138 else
139 tmp += n[idx]; 139 tmp += n[idx];
140 idx++; 140 idx++;
141 } 141 }
142 if(tmp.length() > 0) 142 if(tmp.length() > 0)
143 numbers->insertItem(tmp); 143 numbers->insertItem(tmp);
144 144
145 } 145 }
146 146
147 numbersChanged(); 147 numbersChanged();
148 tl->activate(); 148 tl->activate();
149} 149}
150 150
151bool DialWidget::save() 151bool DialWidget::save()
152{ 152{
153 //first check to make sure that the account name is unique! 153 //first check to make sure that the account name is unique!
154 if(connectname_l->text().isEmpty() || 154 if(connectname_l->text().isEmpty() ||
155 !_pppdata->isUniqueAccname(connectname_l->text())) 155 !_pppdata->isUniqueAccname(connectname_l->text()))
156 { 156 {
157 return false; 157 return false;
158 } 158 }
159 else 159 else
160 { 160 {
161 _pppdata->setAccname(connectname_l->text()); 161 _pppdata->setAccname(connectname_l->text());
162 162
163 QString number = ""; 163 QString number = "";
164 for(uint i = 0; i < numbers->count(); i++) 164 for(uint i = 0; i < numbers->count(); i++)
165 { 165 {
166 if(i != 0) 166 if(i != 0)
167 number += ":"; 167 number += ":";
168 number += numbers->text(i); 168 number += numbers->text(i);
169 } 169 }
170 170
171 _pppdata->setPhonenumber(number); 171 _pppdata->setPhonenumber(number);
172 return true; 172 return true;
173 } 173 }
174} 174}
175 175
176 176
177void DialWidget::numbersChanged() 177void DialWidget::numbersChanged()
178{ 178{
179 int sel = numbers->currentItem(); 179 int sel = numbers->currentItem();
180 180
181 del->setEnabled(sel != -1); 181 del->setEnabled(sel != -1);
182 up->setEnabled(sel != -1 && sel != 0); 182 up->setEnabled(sel != -1 && sel != 0);
183 down->setEnabled(sel != -1 && sel != (int)numbers->count()-1); 183 down->setEnabled(sel != -1 && sel != (int)numbers->count()-1);
184} 184}
185 185
186 186
187void DialWidget::selectionChanged(int) 187void DialWidget::selectionChanged(int)
188{ 188{
189 numbersChanged(); 189 numbersChanged();
190} 190}
191 191
192 192
193void DialWidget::addNumber() 193void DialWidget::addNumber()
194{ 194{
195 PhoneNumberDialog dlg(this); 195 PhoneNumberDialog dlg(this);
196 if(dlg.exec()) 196 if(dlg.exec())
197 { 197 {
198 numbers->insertItem(dlg.phoneNumber()); 198 numbers->insertItem(dlg.phoneNumber());
199 numbersChanged(); 199 numbersChanged();
200 } 200 }
201} 201}
202 202
203 203
204void DialWidget::delNumber() 204void DialWidget::delNumber()
205{ 205{
206 if(numbers->currentItem() != -1) 206 if(numbers->currentItem() != -1)
207 { 207 {
208 numbers->removeItem(numbers->currentItem()); 208 numbers->removeItem(numbers->currentItem());
209 numbersChanged(); 209 numbersChanged();
210 } 210 }
211} 211}
212 212
213 213
214void DialWidget::upNumber() 214void DialWidget::upNumber()
215{ 215{
216 int idx = numbers->currentItem(); 216 int idx = numbers->currentItem();
217 if(idx != -1) 217 if(idx != -1)
218 { 218 {
219 QString item = numbers->text(idx); 219 QString item = numbers->text(idx);
220 numbers->removeItem(idx); 220 numbers->removeItem(idx);
221 numbers->insertItem(item, idx-1); 221 numbers->insertItem(item, idx-1);
222 numbers->setCurrentItem(idx-1); 222 numbers->setCurrentItem(idx-1);
223 numbersChanged(); 223 numbersChanged();
224 } 224 }
225} 225}
226 226
227 227
228void DialWidget::downNumber() 228void DialWidget::downNumber()
229{ 229{
230 int idx = numbers->currentItem(); 230 int idx = numbers->currentItem();
231 if(idx != -1) 231 if(idx != -1)
232 { 232 {
233 QString item = numbers->text(idx); 233 QString item = numbers->text(idx);
234 numbers->removeItem(idx); 234 numbers->removeItem(idx);
235 numbers->insertItem(item, idx+1); 235 numbers->insertItem(item, idx+1);
236 numbers->setCurrentItem(idx+1); 236 numbers->setCurrentItem(idx+1);
237 numbersChanged(); 237 numbersChanged();
238 } 238 }
239} 239}
240 240
241 241
242void DialWidget::pppdargsbutton() 242void DialWidget::pppdargsbutton()
243{ 243{
244 PPPdArguments pa(_pppdata, this); 244 PPPdArguments pa(_pppdata, this);
245 QPEApplication::execDialog( &pa ); 245 QPEApplication::execDialog( &pa );
246} 246}
247 247
248 248
249 249
250///////////////////////////////////////////////////////////////////////////// 250/////////////////////////////////////////////////////////////////////////////
251// ExecWidget 251// ExecWidget
252///////////////////////////////////////////////////////////////////////////// 252/////////////////////////////////////////////////////////////////////////////
253ExecWidget::ExecWidget(PPPData *pd, QWidget *parent, bool isnewaccount, const char *name) : 253ExecWidget::ExecWidget(PPPData *pd, QWidget *parent, bool isnewaccount, const char *name) :
254 QWidget(parent, name), _pppdata(pd) 254 QWidget(parent, name), _pppdata(pd)
255{ 255{
256 QVBoxLayout *tl = new QVBoxLayout(this, 0 );//, KDialog::spacingHint()); 256 QVBoxLayout *tl = new QVBoxLayout(this, 0 );//, KDialog::spacingHint());
257 257
258 QLabel *l = new QLabel( tr("Here you can select commands to run at certain stages of the connection. The commands are run with your real user id, so you cannot run any commands here requiring root permissions (unless, of course, you are root).<br><br>Be sure to supply the whole path to the program otherwise we might be unable to find it."), this); 258 QLabel *l = new QLabel( tr("Here you can select commands to run at certain stages of the connection. The commands are run with your real user id, so you cannot run any commands here requiring root permissions (unless, of course, you are root).<br><br>Be sure to supply the whole path to the program otherwise we might be unable to find it."), this);
259 259
260 tl->addWidget(l); 260 tl->addWidget(l);
261 tl->addStretch(1); 261 tl->addStretch(1);
262 262
263 QGridLayout *l1 = new QGridLayout(4, 2, 10); 263 QGridLayout *l1 = new QGridLayout(4, 2, 10);
264 tl->addLayout(l1); 264 tl->addLayout(l1);
265 l1->setColStretch(0, 0); 265 l1->setColStretch(0, 0);
266 l1->setColStretch(1, 1); 266 l1->setColStretch(1, 1);
267 267
268 before_connect_l = new QLabel(tr("Before connect:"), this); 268 before_connect_l = new QLabel(tr("Before connect:"), this);
269 before_connect_l->setAlignment(AlignVCenter); 269 before_connect_l->setAlignment(AlignVCenter);
270 l1->addWidget(before_connect_l, 0, 0); 270 l1->addWidget(before_connect_l, 0, 0);
271 before_connect = new QLineEdit(this); 271 before_connect = new QLineEdit(this);
272 // before_connect->setMaxLength(COMMAND_SIZE); 272 // before_connect->setMaxLength(COMMAND_SIZE);
273 l1->addWidget(before_connect, 0, 1); 273 l1->addWidget(before_connect, 0, 1);
274 QString tmp = tr("Allows you to run a program <b>before</b> a connection\n" 274 QString tmp = tr("Allows you to run a program <b>before</b> a connection\n"
275 "is established. It is called immediately before\n" 275 "is established. It is called immediately before\n"
276 "dialing has begun.\n\n" 276 "dialing has begun.\n\n"
277 "This might be useful, e.g. to stop HylaFAX blocking the\n" 277 "This might be useful, e.g. to stop HylaFAX blocking the\n"
278 "modem."); 278 "modem.");
279 279
280 QWhatsThis::add(before_connect_l,tmp); 280 QWhatsThis::add(before_connect_l,tmp);
281 QWhatsThis::add(before_connect,tmp); 281 QWhatsThis::add(before_connect,tmp);
282 282
283 command_label = new QLabel(tr("Upon connect:"), this); 283 command_label = new QLabel(tr("Upon connect:"), this);
284 command_label->setAlignment(AlignVCenter); 284 command_label->setAlignment(AlignVCenter);
285 l1->addWidget(command_label, 1, 0); 285 l1->addWidget(command_label, 1, 0);
286 command = new QLineEdit(this); 286 command = new QLineEdit(this);
287 // command->setMaxLength(COMMAND_SIZE); 287 // command->setMaxLength(COMMAND_SIZE);
288 l1->addWidget(command, 1, 1); 288 l1->addWidget(command, 1, 1);
289 tmp = tr("Allows you to run a program <b>after</b> a connection\n" 289 tmp = tr("Allows you to run a program <b>after</b> a connection\n"
290 "is established. When your program is called, all\n" 290 "is established. When your program is called, all\n"
291 "preparations for an Internet connection are finished.\n" 291 "preparations for an Internet connection are finished.\n"
292 "\n" 292 "\n"
293 "Very useful for fetching mail and news"); 293 "Very useful for fetching mail and news");
294 294
295 QWhatsThis::add(command_label,tmp); 295 QWhatsThis::add(command_label,tmp);
296 QWhatsThis::add(command,tmp); 296 QWhatsThis::add(command,tmp);
297 297
298 predisconnect_label = new QLabel(tr("Before disconnect:"), 298 predisconnect_label = new QLabel(tr("Before disconnect:"),
299 this); 299 this);
300 predisconnect_label->setAlignment(AlignVCenter); 300 predisconnect_label->setAlignment(AlignVCenter);
301 l1->addWidget(predisconnect_label, 2, 0); 301 l1->addWidget(predisconnect_label, 2, 0);
302 predisconnect = new QLineEdit(this); 302 predisconnect = new QLineEdit(this);
303 // predisconnect->setMaxLength(COMMAND_SIZE); 303 // predisconnect->setMaxLength(COMMAND_SIZE);
304 l1->addWidget(predisconnect, 2, 1); 304 l1->addWidget(predisconnect, 2, 1);
305 tmp = tr("Allows you to run a program <b>before</b> a connection\n" 305 tmp = tr("Allows you to run a program <b>before</b> a connection\n"
306 "is closed. The connection will stay open until\n" 306 "is closed. The connection will stay open until\n"
307 "the program exits."); 307 "the program exits.");
308 308
309 QWhatsThis::add(predisconnect_label,tmp); 309 QWhatsThis::add(predisconnect_label,tmp);
310 QWhatsThis::add(predisconnect,tmp); 310 QWhatsThis::add(predisconnect,tmp);
311 311
312 discommand_label = new QLabel(tr("Upon disconnect:"), 312 discommand_label = new QLabel(tr("Upon disconnect:"),
313 this); 313 this);
314 discommand_label->setAlignment(AlignVCenter); 314 discommand_label->setAlignment(AlignVCenter);
315 l1->addWidget(discommand_label, 3, 0); 315 l1->addWidget(discommand_label, 3, 0);
316 316
317 discommand = new QLineEdit(this); 317 discommand = new QLineEdit(this);
318 // discommand->setMaxLength(COMMAND_SIZE); 318 // discommand->setMaxLength(COMMAND_SIZE);
319 l1->addWidget(discommand, 3, 1); 319 l1->addWidget(discommand, 3, 1);
320 tmp = tr("Allows you to run a program <b>after</b> a connection\n" 320 tmp = tr("Allows you to run a program <b>after</b> a connection\n"
321 "has been closed."); 321 "has been closed.");
322 322
323 QWhatsThis::add(discommand_label,tmp); 323 QWhatsThis::add(discommand_label,tmp);
324 QWhatsThis::add(discommand,tmp); 324 QWhatsThis::add(discommand,tmp);
325 325
326 // extra space between entries 326 // extra space between entries
327 l1->addRowSpacing(1, 5); 327 l1->addRowSpacing(1, 5);
328 l1->addRowSpacing(3, 5); 328 l1->addRowSpacing(3, 5);
329 329
330 tl->addStretch(1); 330 tl->addStretch(1);
331 tl->activate(); 331 tl->activate();
332 332
333 // Set defaults if editing an existing connection 333 // Set defaults if editing an existing connection
334 if(!isnewaccount) 334 if(!isnewaccount)
335 { 335 {
336 before_connect->setText(_pppdata->command_before_connect()); 336 before_connect->setText(_pppdata->command_before_connect());
337 command->setText(_pppdata->command_on_connect()); 337 command->setText(_pppdata->command_on_connect());
338 discommand->setText(_pppdata->command_on_disconnect()); 338 discommand->setText(_pppdata->command_on_disconnect());
339 predisconnect->setText(_pppdata->command_before_disconnect()); 339 predisconnect->setText(_pppdata->command_before_disconnect());
340 } 340 }
341} 341}
342 342
343 343
344bool ExecWidget::save() 344bool ExecWidget::save()
345{ 345{
346 _pppdata->setCommand_before_connect(before_connect->text()); 346 _pppdata->setCommand_before_connect(before_connect->text());
347 _pppdata->setCommand_on_connect(command->text()); 347 _pppdata->setCommand_on_connect(command->text());
348 _pppdata->setCommand_before_disconnect(predisconnect->text()); 348 _pppdata->setCommand_before_disconnect(predisconnect->text());
349 _pppdata->setCommand_on_disconnect(discommand->text()); 349 _pppdata->setCommand_on_disconnect(discommand->text());
350 return true; 350 return true;
351} 351}
352 352
353 353
354 354
355///////////////////////////////////////////////////////////////////////////// 355/////////////////////////////////////////////////////////////////////////////
356// 356//
357// IPWidget 357// IPWidget
358// 358//
359///////////////////////////////////////////////////////////////////////////// 359/////////////////////////////////////////////////////////////////////////////
360IPWidget::IPWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name ) 360IPWidget::IPWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name )
361 : QWidget(parent, name), _pppdata(pd) 361 : QWidget(parent, name), _pppdata(pd)
362{ 362{
363 QVBoxLayout *topLayout = new QVBoxLayout(this); 363 QVBoxLayout *topLayout = new QVBoxLayout(this);
364 topLayout->setSpacing( 3 );//KDialog::spacingHint()); 364 topLayout->setSpacing( 3 );//KDialog::spacingHint());
365 365
366 box = new QVGroupBox(tr("Configuration"), this); 366 box = new QVGroupBox(tr("Configuration"), this);
367 // box->setInsideSpacing( 1 );//KDialog::spacingHint()); 367 // box->setInsideSpacing( 1 );//KDialog::spacingHint());
368 368
369 rb = new QButtonGroup(this); 369 rb = new QButtonGroup(this);
370 rb->hide(); 370 rb->hide();
371 connect(rb, SIGNAL(clicked(int)), 371 connect(rb, SIGNAL(clicked(int)),
372 SLOT(hitIPSelect(int))); 372 SLOT(hitIPSelect(int)));
373 373
374 dynamicadd_rb = new QRadioButton(box); 374 dynamicadd_rb = new QRadioButton(box);
375 dynamicadd_rb->setText(tr("Dynamic IP address")); 375 dynamicadd_rb->setText(tr("Dynamic IP address"));
376 QWhatsThis::add(dynamicadd_rb, 376 QWhatsThis::add(dynamicadd_rb,
377 tr("Select this option when your computer gets an\n" 377 tr("Select this option when your computer gets an\n"
378 "internet address (IP) every time a\n" 378 "internet address (IP) every time a\n"
379 "connection is made.\n" 379 "connection is made.\n"
380 "\n" 380 "\n"
381 "Almost every Internet Service Provider uses\n" 381 "Almost every Internet Service Provider uses\n"
382 "this method, so this should be turned on.")); 382 "this method, so this should be turned on."));
383 383
384 staticadd_rb = new QRadioButton(box); 384 staticadd_rb = new QRadioButton(box);
385 staticadd_rb->setText(tr("Static IP address")); 385 staticadd_rb->setText(tr("Static IP address"));
386 rb->insert(dynamicadd_rb, 0); 386 rb->insert(dynamicadd_rb, 0);
387 rb->insert(staticadd_rb, 1); 387 rb->insert(staticadd_rb, 1);
388 QWhatsThis::add(staticadd_rb, 388 QWhatsThis::add(staticadd_rb,
389 tr("Select this option when your computer has a\n" 389 tr("Select this option when your computer has a\n"
390 "fixed internet address (IP). Most computers\n" 390 "fixed internet address (IP). Most computers\n"
391 "don't have this, so you should probably select\n" 391 "don't have this, so you should probably select\n"
392 "dynamic IP addressing unless you know what you\n" 392 "dynamic IP addressing unless you know what you\n"
393 "are doing.")); 393 "are doing."));
394 394
395 QWidget *ipWidget = new QWidget(box); 395 QWidget *ipWidget = new QWidget(box);
396 QGridLayout *ipLayout = new QGridLayout(ipWidget, 2, 2); 396 QGridLayout *ipLayout = new QGridLayout(ipWidget, 2, 2);
397 ipLayout->setSpacing( 2 );//KDialog::spacingHint()); 397 ipLayout->setSpacing( 2 );//KDialog::spacingHint());
398 398
399 ipaddress_label = new QLabel(tr("IP address:"), ipWidget); 399 ipaddress_label = new QLabel(tr("IP address:"), ipWidget);
400 QString tmp = tr("If your computer has a permanent internet\n" 400 QString tmp = tr("If your computer has a permanent internet\n"
401 "address, you must supply your IP address here."); 401 "address, you must supply your IP address here.");
402 ipLayout->addWidget(ipaddress_label, 0, 0); 402 ipLayout->addWidget(ipaddress_label, 0, 0);
403 403
404 ipaddress_l = new IPLineEdit(ipWidget); 404 ipaddress_l = new IPLineEdit(ipWidget);
405 ipLayout->addWidget(ipaddress_l, 0, 1); 405 ipLayout->addWidget(ipaddress_l, 0, 1);
406 406
407 QWhatsThis::add(ipaddress_label,tmp); 407 QWhatsThis::add(ipaddress_label,tmp);
408 QWhatsThis::add(ipaddress_l,tmp); 408 QWhatsThis::add(ipaddress_l,tmp);
409 409
410 sub_label = new QLabel(tr("Subnet mask:"), ipWidget); 410 sub_label = new QLabel(tr("Subnet mask:"), ipWidget);
411 tmp = tr("<p>If your computer has a static Internet address,\n" 411 tmp = tr("<p>If your computer has a static Internet address,\n"
412 "you must supply a network mask here. In almost\n" 412 "you must supply a network mask here. In almost\n"
413 "all cases this netmask will be <b>255.255.255.0</b>,\n" 413 "all cases this netmask will be <b>255.255.255.0</b>,\n"
414 "but your mileage may vary.\n" 414 "but your mileage may vary.\n"
415 "\n" 415 "\n"
416 "If unsure, contact your Internet Service Provider"); 416 "If unsure, contact your Internet Service Provider");
417 ipLayout->addWidget(sub_label, 1, 0); 417 ipLayout->addWidget(sub_label, 1, 0);
418 418
419 subnetmask_l = new IPLineEdit(ipWidget); 419 subnetmask_l = new IPLineEdit(ipWidget);
420 ipLayout->addWidget(subnetmask_l, 1, 1); 420 ipLayout->addWidget(subnetmask_l, 1, 1);
421 421
422 QWhatsThis::add(sub_label,tmp); 422 QWhatsThis::add(sub_label,tmp);
423 QWhatsThis::add(subnetmask_l,tmp); 423 QWhatsThis::add(subnetmask_l,tmp);
424 424
425 autoname = new QCheckBox(tr("Auto-configure hostname from this IP"), this); 425 autoname = new QCheckBox(tr("Auto-configure hostname from this IP"), this);
426 autoname->setChecked(_pppdata->autoname()); 426 autoname->setChecked(_pppdata->autoname());
427 connect(autoname,SIGNAL(toggled(bool)), 427 connect(autoname,SIGNAL(toggled(bool)),
428 this,SLOT(autoname_t(bool))); 428 this,SLOT(autoname_t(bool)));
429 429
430 QWhatsThis::add(autoname, 430 QWhatsThis::add(autoname,
431 tr("<p>Whenever you connect, this reconfigures\n" 431 tr("<p>Whenever you connect, this reconfigures\n"
432 "your hostname to match the IP address you\n" 432 "your hostname to match the IP address you\n"
433 "got from the PPP server. This may be useful\n" 433 "got from the PPP server. This may be useful\n"
434 "if you need to use a protocol which depends\n" 434 "if you need to use a protocol which depends\n"
435 "on this information, but it can also cause several\n" 435 "on this information, but it can also cause several\n"
436 "<a href=\"kppp-7.html#autohostname\">problems</a>.\n" 436 "<a href=\"kppp-7.html#autohostname\">problems</a>.\n"
437 "\n" 437 "\n"
438 "Don't enable this unless you really need it.")); 438 "Don't enable this unless you really need it."));
439 439
440 topLayout->addWidget(box); 440 topLayout->addWidget(box);
441 topLayout->addWidget(autoname); 441 topLayout->addWidget(autoname);
442 topLayout->addStretch(); 442 topLayout->addStretch();
443 443
444 //load info from gpppdata 444 //load info from gpppdata
445 if(!isnewaccount) 445 if(!isnewaccount)
446 { 446 {
447 if(_pppdata->ipaddr() == "0.0.0.0" && 447 if(_pppdata->ipaddr() == "0.0.0.0" &&
448 _pppdata->subnetmask() == "0.0.0.0") 448 _pppdata->subnetmask() == "0.0.0.0")
449 { 449 {
450 dynamicadd_rb->setChecked(true); 450 dynamicadd_rb->setChecked(true);
451 hitIPSelect(0); 451 hitIPSelect(0);
452 autoname->setChecked(_pppdata->autoname()); 452 autoname->setChecked(_pppdata->autoname());
453 } 453 }
454 else 454 else
455 { 455 {
456 ipaddress_l->setText(_pppdata->ipaddr()); 456 ipaddress_l->setText(_pppdata->ipaddr());
457 subnetmask_l->setText(_pppdata->subnetmask()); 457 subnetmask_l->setText(_pppdata->subnetmask());
458 staticadd_rb->setChecked(true); 458 staticadd_rb->setChecked(true);
459 autoname->setChecked(false); 459 autoname->setChecked(false);
460 } 460 }
461 } 461 }
462 else 462 else
463 { 463 {
464 dynamicadd_rb->setChecked(true); 464 dynamicadd_rb->setChecked(true);
465 hitIPSelect(0); 465 hitIPSelect(0);
466 } 466 }
467 467
468} 468}
469 469
470void IPWidget::autoname_t(bool on) 470void IPWidget::autoname_t(bool on)
471{ 471{
472 static bool was_warned = false; 472 static bool was_warned = false;
473 473
474 // big-fat warning when selecting the auto configure hostname option 474 // big-fat warning when selecting the auto configure hostname option
475 if(on && !was_warned) 475 if(on && !was_warned)
476 { 476 {
477 QMessageBox::information(this, 477 QMessageBox::information(this,
478 tr("Selecting this option might cause some weird " 478 tr("Selecting this option might cause some weird "
479 "problems with the X-server and applications " 479 "problems with the X-server and applications "
480 "while kppp is connected. Don't use it until " 480 "while kppp is connected. Don't use it until "
481 "you know what you are doing!\n" 481 "you know what you are doing!\n"
482 "For more information take a look at the " 482 "For more information take a look at the "
483 "handbook (or help) in the section \"Frequently " 483 "handbook (or help) in the section \"Frequently "
484 "asked questions\"."), 484 "asked questions\"."),
485 tr("Warning")); 485 tr("Warning"));
486 was_warned = true; 486 was_warned = true;
487 } 487 }
488} 488}
489 489
490 490
491void IPWidget::save() 491void IPWidget::save()
492{ 492{
493 if(dynamicadd_rb->isChecked()) 493 if(dynamicadd_rb->isChecked())
494 { 494 {
495 _pppdata->setIpaddr("0.0.0.0"); 495 _pppdata->setIpaddr("0.0.0.0");
496 _pppdata->setSubnetmask("0.0.0.0"); 496 _pppdata->setSubnetmask("0.0.0.0");
497 } 497 }
498 else 498 else
499 { 499 {
500 _pppdata->setIpaddr(ipaddress_l->text()); 500 _pppdata->setIpaddr(ipaddress_l->text());
501 _pppdata->setSubnetmask(subnetmask_l->text()); 501 _pppdata->setSubnetmask(subnetmask_l->text());
502 } 502 }
503 _pppdata->setAutoname(autoname->isChecked()); 503 _pppdata->setAutoname(autoname->isChecked());
504} 504}
505 505
506 506
507void IPWidget::hitIPSelect( int i ) 507void IPWidget::hitIPSelect( int i )
508{ 508{
509 if(i == 0) 509 if(i == 0)
510 { 510 {
511 ipaddress_label->setEnabled(false); 511 ipaddress_label->setEnabled(false);
512 sub_label->setEnabled(false); 512 sub_label->setEnabled(false);
513 ipaddress_l->setEnabled(false); 513 ipaddress_l->setEnabled(false);
514 subnetmask_l->setEnabled(false); 514 subnetmask_l->setEnabled(false);
515 } 515 }
516 else 516 else
517 { 517 {
518 ipaddress_label->setEnabled(true); 518 ipaddress_label->setEnabled(true);
519 sub_label->setEnabled(true); 519 sub_label->setEnabled(true);
520 ipaddress_l->setEnabled(true); 520 ipaddress_l->setEnabled(true);
521 subnetmask_l->setEnabled(true); 521 subnetmask_l->setEnabled(true);
522 } 522 }
523} 523}
524 524
525 525
526 526
527DNSWidget::DNSWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name ) 527DNSWidget::DNSWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name )
528 : QWidget(parent, name), _pppdata(pd) 528 : QWidget(parent, name), _pppdata(pd)
529{ 529{
530 QGridLayout *tl = new QGridLayout(this, 7, 2, 0 ); 530 QGridLayout *tl = new QGridLayout(this, 7, 2, 0 );
531 531
532 dnsdomain_label = new QLabel(tr("Domain name:"), this); 532 dnsdomain_label = new QLabel(tr("Domain name:"), this);
533 tl->addWidget(dnsdomain_label, 0, 0); 533 tl->addWidget(dnsdomain_label, 0, 0);
534 534
535 dnsdomain = new QLineEdit(this); 535 dnsdomain = new QLineEdit(this);
536 536
537 tl->addWidget(dnsdomain, 0, 1); 537 tl->addWidget(dnsdomain, 0, 1);
538 QString tmp = tr("If you enter a domain name here, this domain\n" 538 QString tmp = tr("If you enter a domain name here, this domain\n"
539 "name is used for your computer while you are\n" 539 "name is used for your computer while you are\n"
540 "connected. When the connection is closed, the\n" 540 "connected. When the connection is closed, the\n"
541 "original domain name of your computer is\n" 541 "original domain name of your computer is\n"
542 "restored.\n" 542 "restored.\n"
543 "\n" 543 "\n"
544 "If you leave this field blank, no changes are\n" 544 "If you leave this field blank, no changes are\n"
545 "made to the domain name."); 545 "made to the domain name.");
546 546
547 QWhatsThis::add(dnsdomain_label,tmp); 547 QWhatsThis::add(dnsdomain_label,tmp);
548 QWhatsThis::add(dnsdomain,tmp); 548 QWhatsThis::add(dnsdomain,tmp);
549 549
550 conf_label = new QLabel(tr("Configuration:"), this); 550 conf_label = new QLabel(tr("Configuration:"), this);
551 tl->addWidget(conf_label, 1, 0); 551 tl->addWidget(conf_label, 1, 0);
552 552
553 bg = new QButtonGroup("Group", this); 553 bg = new QButtonGroup("Group", this);
554 connect(bg, SIGNAL(clicked(int)), SLOT(DNS_Mode_Selected(int))); 554 connect(bg, SIGNAL(clicked(int)), SLOT(DNS_Mode_Selected(int)));
555 bg->hide(); 555 bg->hide();
556 556
557 autodns = new QRadioButton(tr("Automatic"), this); 557 autodns = new QRadioButton(tr("Automatic"), this);
558 bg->insert(autodns, 0); 558 bg->insert(autodns, 0);
559 tl->addWidget(autodns, 1, 1); 559 tl->addWidget(autodns, 1, 1);
560 if(!_pppdata->pppdVersionMin(2, 3, 7)) 560 if(!_pppdata->pppdVersionMin(2, 3, 7))
561 autodns->setEnabled(false); 561 autodns->setEnabled(false);
562 562
563 mandns = new QRadioButton(tr("Manual"), this); 563 mandns = new QRadioButton(tr("Manual"), this);
564 bg->insert(mandns, 1); 564 bg->insert(mandns, 1);
565 tl->addWidget(mandns, 2, 1); 565 tl->addWidget(mandns, 2, 1);
566 566
567 dns_label = new QLabel(tr("DNS IP address:"), this); 567 dns_label = new QLabel(tr("DNS IP address:"), this);
568 tl->addWidget(dns_label, 3, 0); 568 tl->addWidget(dns_label, 3, 0);
569 569
570 QHBoxLayout *l2 = new QHBoxLayout; 570 QHBoxLayout *l2 = new QHBoxLayout;
571 tl->addLayout(l2, 3, 1); 571 tl->addLayout(l2, 3, 1);
572 dnsipaddr = new IPLineEdit(this); 572 dnsipaddr = new IPLineEdit(this);
573 connect(dnsipaddr, SIGNAL(returnPressed()), 573 connect(dnsipaddr, SIGNAL(returnPressed()),
574 SLOT(adddns())); 574 SLOT(adddns()));
575 connect(dnsipaddr, SIGNAL(textChanged(const QString &)), 575 connect(dnsipaddr, SIGNAL(textChanged(const QString&)),
576 SLOT(DNS_Edit_Changed(const QString &))); 576 SLOT(DNS_Edit_Changed(const QString&)));
577 l2->addWidget(dnsipaddr, 1); 577 l2->addWidget(dnsipaddr, 1);
578 l2->addStretch(1); 578 l2->addStretch(1);
579 tmp = tr("<p>Allows you to specify a new DNS server to be\n" 579 tmp = tr("<p>Allows you to specify a new DNS server to be\n"
580 "used while you are connected. When the\n" 580 "used while you are connected. When the\n"
581 "connection is closed, this DNS entry will be\n" 581 "connection is closed, this DNS entry will be\n"
582 "removed again.\n" 582 "removed again.\n"
583 "\n" 583 "\n"
584 "To add a DNS server, type in the IP address of\n" 584 "To add a DNS server, type in the IP address of\n"
585 "the DNS server here and click on <b>Add</b>"); 585 "the DNS server here and click on <b>Add</b>");
586 586
587 QWhatsThis::add(dns_label, tmp); 587 QWhatsThis::add(dns_label, tmp);
588 QWhatsThis::add(dnsipaddr, tmp); 588 QWhatsThis::add(dnsipaddr, tmp);
589 589
590 QHBoxLayout *l1 = new QHBoxLayout; 590 QHBoxLayout *l1 = new QHBoxLayout;
591 tl->addLayout(l1, 4, 1); 591 tl->addLayout(l1, 4, 1);
592 add = new QPushButton(tr("Add"), this); 592 add = new QPushButton(tr("Add"), this);
593 connect(add, SIGNAL(clicked()), SLOT(adddns())); 593 connect(add, SIGNAL(clicked()), SLOT(adddns()));
594 l1->addWidget(add); 594 l1->addWidget(add);
595 // l1->addStretch(1); 595 // l1->addStretch(1);
596 QWhatsThis::add(add, 596 QWhatsThis::add(add,
597 tr("Click this button to add the DNS server\n" 597 tr("Click this button to add the DNS server\n"
598 "specified in the field above. The entry\n" 598 "specified in the field above. The entry\n"
599 "will then be added to the list below")); 599 "will then be added to the list below"));
600 600
601 remove = new QPushButton(tr("Remove"), this); 601 remove = new QPushButton(tr("Remove"), this);
602 connect(remove, SIGNAL(clicked()), SLOT(removedns())); 602 connect(remove, SIGNAL(clicked()), SLOT(removedns()));
603 l1->addWidget(remove); 603 l1->addWidget(remove);
604 QWhatsThis::add(remove, 604 QWhatsThis::add(remove,
605 tr("Click this button to remove the selected DNS\n" 605 tr("Click this button to remove the selected DNS\n"
606 "server entry from the list below")); 606 "server entry from the list below"));
607 607
608 servers_label = new QLabel(tr("DNS address list:"), this); 608 servers_label = new QLabel(tr("DNS address list:"), this);
609 servers_label->setAlignment(AlignTop|AlignLeft); 609 servers_label->setAlignment(AlignTop|AlignLeft);
610 tl->addWidget(servers_label, 5, 0); 610 tl->addWidget(servers_label, 5, 0);
611 611
612 dnsservers = new QListBox(this); 612 dnsservers = new QListBox(this);
613 dnsservers->setMinimumSize(150, 80); 613 dnsservers->setMinimumSize(150, 80);
614 connect(dnsservers, SIGNAL(highlighted(int)), 614 connect(dnsservers, SIGNAL(highlighted(int)),
615 SLOT(DNS_Entry_Selected(int))); 615 SLOT(DNS_Entry_Selected(int)));
616 tl->addWidget(dnsservers, 5, 1); 616 tl->addWidget(dnsservers, 5, 1);
617 tmp = tr("<p>This shows all defined DNS servers to use\n" 617 tmp = tr("<p>This shows all defined DNS servers to use\n"
618 "while you are connected. Use the <b>Add</b> and\n" 618 "while you are connected. Use the <b>Add</b> and\n"
619 "<b>Remove</b> buttons to modify the list"); 619 "<b>Remove</b> buttons to modify the list");
620 620
621 QWhatsThis::add(servers_label,tmp); 621 QWhatsThis::add(servers_label,tmp);
622 QWhatsThis::add(dnsservers,tmp); 622 QWhatsThis::add(dnsservers,tmp);
623 623
624 exdnsdisabled_toggle = new QCheckBox(tr("Disable DNS servers during connection"), this); 624 exdnsdisabled_toggle = new QCheckBox(tr("Disable DNS servers during connection"), this);
625 // exdnsdisabled_toggle = new QCheckBox(tr("Disable existing DNS servers during connection"), this); 625 // exdnsdisabled_toggle = new QCheckBox(tr("Disable existing DNS servers during connection"), this);
626 exdnsdisabled_toggle->setChecked(_pppdata->exDNSDisabled()); 626 exdnsdisabled_toggle->setChecked(_pppdata->exDNSDisabled());
627 tl->addMultiCellWidget(exdnsdisabled_toggle, 6, 6, 0, 1, AlignCenter); 627 tl->addMultiCellWidget(exdnsdisabled_toggle, 6, 6, 0, 1, AlignCenter);
628 QWhatsThis::add(exdnsdisabled_toggle, 628 QWhatsThis::add(exdnsdisabled_toggle,
629 tr("<p>When this option is selected, all DNS\n" 629 tr("<p>When this option is selected, all DNS\n"
630 "servers specified in <tt>/etc/resolv.conf</tt> are\n" 630 "servers specified in <tt>/etc/resolv.conf</tt> are\n"
631 "temporary disabled while the dialup connection\n" 631 "temporary disabled while the dialup connection\n"
632 "is established. After the connection is\n" 632 "is established. After the connection is\n"
633 "closed, the servers will be re-enabled\n" 633 "closed, the servers will be re-enabled\n"
634 "\n" 634 "\n"
635 "Typically, there is no reason to use this\n" 635 "Typically, there is no reason to use this\n"
636 "option, but it may become useful under \n" 636 "option, but it may become useful under \n"
637 "some circumstances.")); 637 "some circumstances."));
638 638
639 639
640 // restore data if editing 640 // restore data if editing
641 if(!isnewaccount) 641 if(!isnewaccount)
642 { 642 {
643 dnsservers->insertStringList(_pppdata->dns()); 643 dnsservers->insertStringList(_pppdata->dns());
644 dnsdomain->setText(_pppdata->domain()); 644 dnsdomain->setText(_pppdata->domain());
645 } 645 }
646 646
647 int mode = _pppdata->autoDNS() ? 0 : 1; 647 int mode = _pppdata->autoDNS() ? 0 : 1;
648 bg->setButton(mode); 648 bg->setButton(mode);
649 DNS_Mode_Selected(mode); 649 DNS_Mode_Selected(mode);
650 650
651 tl->activate(); 651 tl->activate();
652} 652}
653 653
654void DNSWidget::DNS_Edit_Changed(const QString &text) 654void DNSWidget::DNS_Edit_Changed(const QString &text)
655{ 655{
656 QRegExp r("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"); 656 QRegExp r("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+");
657 add->setEnabled(text.find(r) != -1); 657 add->setEnabled(text.find(r) != -1);
658} 658}
659 659
660void DNSWidget::DNS_Entry_Selected(int) 660void DNSWidget::DNS_Entry_Selected(int)
661{ 661{
662 remove->setEnabled(true); 662 remove->setEnabled(true);
663} 663}
664 664
665void DNSWidget::DNS_Mode_Selected(int mode) 665void DNSWidget::DNS_Mode_Selected(int mode)
666{ 666{
667 bool on = (mode == 1); 667 bool on = (mode == 1);
668 dns_label->setEnabled(on); 668 dns_label->setEnabled(on);
669 servers_label->setEnabled(on); 669 servers_label->setEnabled(on);
670 dnsipaddr->setText(""); 670 dnsipaddr->setText("");
671 dnsipaddr->setEnabled(on); 671 dnsipaddr->setEnabled(on);
672 add->setEnabled(false); 672 add->setEnabled(false);
673 remove->setEnabled(dnsservers->count()>0 && on); 673 remove->setEnabled(dnsservers->count()>0 && on);
674 dnsservers->clearSelection(); 674 dnsservers->clearSelection();
675 dnsservers->setEnabled(on); 675 dnsservers->setEnabled(on);
676 dnsservers->triggerUpdate(false); 676 dnsservers->triggerUpdate(false);
677} 677}
678 678
679void DNSWidget::save() 679void DNSWidget::save()
680{ 680{
681 _pppdata->setAutoDNS(bg->id(bg->selected()) == 0); 681 _pppdata->setAutoDNS(bg->id(bg->selected()) == 0);
682 QStringList serverlist; 682 QStringList serverlist;
683 for(uint i=0; i < dnsservers->count(); i++) 683 for(uint i=0; i < dnsservers->count(); i++)
684 serverlist.append(dnsservers->text(i)); 684 serverlist.append(dnsservers->text(i));
685 _pppdata->setDns(serverlist); 685 _pppdata->setDns(serverlist);
686 686
687 // strip leading dot 687 // strip leading dot
688 QString s(dnsdomain->text()); 688 QString s(dnsdomain->text());
689 if(s.left(1) == ".") 689 if(s.left(1) == ".")
690 _pppdata->setDomain(s.mid(1)); 690 _pppdata->setDomain(s.mid(1));
691 else 691 else
692 _pppdata->setDomain(dnsdomain->text()); 692 _pppdata->setDomain(dnsdomain->text());
693 693
694 _pppdata->setExDNSDisabled(exdnsdisabled_toggle->isChecked()); 694 _pppdata->setExDNSDisabled(exdnsdisabled_toggle->isChecked());
695} 695}
696 696
697 697
698void DNSWidget::adddns() 698void DNSWidget::adddns()
699{ 699{
700 if(dnsservers->count() < MAX_DNS_ENTRIES) 700 if(dnsservers->count() < MAX_DNS_ENTRIES)
701 { 701 {
702 dnsservers->insertItem(dnsipaddr->text()); 702 dnsservers->insertItem(dnsipaddr->text());
703 dnsipaddr->setText(""); 703 dnsipaddr->setText("");
704 } 704 }
705} 705}
706 706
707 707
708void DNSWidget::removedns() 708void DNSWidget::removedns()
709{ 709{
710 int i; 710 int i;
711 i = dnsservers->currentItem(); 711 i = dnsservers->currentItem();
712 if(i != -1) 712 if(i != -1)
713 dnsservers->removeItem(i); 713 dnsservers->removeItem(i);
714 remove->setEnabled(dnsservers->count()>0); 714 remove->setEnabled(dnsservers->count()>0);
715} 715}
716 716
717 717
718// 718//
719// GatewayWidget 719// GatewayWidget
720// 720//
721GatewayWidget::GatewayWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name ) 721GatewayWidget::GatewayWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name )
722 : QWidget(parent, name), _pppdata(pd) 722 : QWidget(parent, name), _pppdata(pd)
723{ 723{
724 QVBoxLayout *topLayout = new QVBoxLayout(this); 724 QVBoxLayout *topLayout = new QVBoxLayout(this);
725 topLayout->setSpacing( 2 ); 725 topLayout->setSpacing( 2 );
726 topLayout->setMargin( 0 ); 726 topLayout->setMargin( 0 );
727 727
728 box = new QVGroupBox(tr("Configuration"), this); 728 box = new QVGroupBox(tr("Configuration"), this);
729 729
730 rb = new QButtonGroup(this); 730 rb = new QButtonGroup(this);
731 rb->hide(); 731 rb->hide();
732 connect(rb, SIGNAL(clicked(int)), SLOT(hitGatewaySelect(int))); 732 connect(rb, SIGNAL(clicked(int)), SLOT(hitGatewaySelect(int)));
733 733
734 defaultgateway = new QRadioButton(box); 734 defaultgateway = new QRadioButton(box);
735 defaultgateway->setText(tr("Default gateway")); 735 defaultgateway->setText(tr("Default gateway"));
736 rb->insert(defaultgateway, 0); 736 rb->insert(defaultgateway, 0);
737 QWhatsThis::add(defaultgateway, 737 QWhatsThis::add(defaultgateway,
738 tr("This makes the PPP peer computer (the computer\n" 738 tr("This makes the PPP peer computer (the computer\n"
739 "you are connected to with your modem) to act as\n" 739 "you are connected to with your modem) to act as\n"
740 "a gateway. Your computer will send all packets not\n" 740 "a gateway. Your computer will send all packets not\n"
741 "going to a computer inside your local net to this\n" 741 "going to a computer inside your local net to this\n"
742 "computer, which will route these packets.\n" 742 "computer, which will route these packets.\n"
743 "\n" 743 "\n"
744 "This is the default for most ISPs, so you should\n" 744 "This is the default for most ISPs, so you should\n"
745 "probably leave this option on.")); 745 "probably leave this option on."));
746 746
747 747
748 staticgateway = new QRadioButton(box); 748 staticgateway = new QRadioButton(box);
749 staticgateway->setText(tr("Static gateway")); 749 staticgateway->setText(tr("Static gateway"));
750 rb->insert(staticgateway, 1); 750 rb->insert(staticgateway, 1);
751 QWhatsThis::add(staticgateway, 751 QWhatsThis::add(staticgateway,
752 tr("<p>Allows you to specify which computer you want\n" 752 tr("<p>Allows you to specify which computer you want\n"
753 "to use as gateway (see <i>Default Gateway</i> above)")); 753 "to use as gateway (see <i>Default Gateway</i> above)"));
754 754
755 QHBox *gateBox = new QHBox(box); 755 QHBox *gateBox = new QHBox(box);
756 gate_label = new QLabel(tr("Gateway IP address:"), gateBox); 756 gate_label = new QLabel(tr("Gateway IP address:"), gateBox);
757 gatewayaddr = new IPLineEdit(gateBox); 757 gatewayaddr = new IPLineEdit(gateBox);
758 758
759 defaultroute = new QCheckBox(tr("Assign the default route to this gateway"), 759 defaultroute = new QCheckBox(tr("Assign the default route to this gateway"),
760 this); 760 this);
761 QWhatsThis::add(defaultroute, 761 QWhatsThis::add(defaultroute,
762 tr("If this option is enabled, all packets not\n" 762 tr("If this option is enabled, all packets not\n"
763 "going to the local net are routed through\n" 763 "going to the local net are routed through\n"
764 "the PPP connection.\n" 764 "the PPP connection.\n"
765 "\n" 765 "\n"
766 "Normally, you should turn this on")); 766 "Normally, you should turn this on"));
767 767
768 topLayout->addWidget(box); 768 topLayout->addWidget(box);
769 topLayout->addWidget(defaultroute); 769 topLayout->addWidget(defaultroute);
770 topLayout->addStretch(); 770 topLayout->addStretch();
771 771
772 //load info from gpppdata 772 //load info from gpppdata
773 if(!isnewaccount) 773 if(!isnewaccount)
774 { 774 {
775 if(_pppdata->gateway() == "0.0.0.0") 775 if(_pppdata->gateway() == "0.0.0.0")
776 { 776 {
777 defaultgateway->setChecked(true); 777 defaultgateway->setChecked(true);
778 hitGatewaySelect(0); 778 hitGatewaySelect(0);
779 } 779 }
780 else 780 else
781 { 781 {
782 gatewayaddr->setText(_pppdata->gateway()); 782 gatewayaddr->setText(_pppdata->gateway());
783 staticgateway->setChecked(true); 783 staticgateway->setChecked(true);
784 } 784 }
785 defaultroute->setChecked(_pppdata->defaultroute()); 785 defaultroute->setChecked(_pppdata->defaultroute());
786 } 786 }
787 else 787 else
788 { 788 {
789 defaultgateway->setChecked(true); 789 defaultgateway->setChecked(true);
790 hitGatewaySelect(0); 790 hitGatewaySelect(0);
791 defaultroute->setChecked(true); 791 defaultroute->setChecked(true);
792 } 792 }
793} 793}
794 794
795void GatewayWidget::save() 795void GatewayWidget::save()
796{ 796{
797 _pppdata->setGateway(gatewayaddr->text()); 797 _pppdata->setGateway(gatewayaddr->text());
798 _pppdata->setDefaultroute(defaultroute->isChecked()); 798 _pppdata->setDefaultroute(defaultroute->isChecked());
799} 799}
800 800
801 801
802void GatewayWidget::hitGatewaySelect( int i ) 802void GatewayWidget::hitGatewaySelect( int i )
803{ 803{
804 if(i == 0) 804 if(i == 0)
805 { 805 {
806 gatewayaddr->setText("0.0.0.0"); 806 gatewayaddr->setText("0.0.0.0");
807 gatewayaddr->setEnabled(false); 807 gatewayaddr->setEnabled(false);
808 gate_label->setEnabled(false); 808 gate_label->setEnabled(false);
809 } 809 }
810 else 810 else
811 { 811 {
812 gatewayaddr->setEnabled(true); 812 gatewayaddr->setEnabled(true);
813 gatewayaddr->setText(""); 813 gatewayaddr->setText("");
814 gate_label->setEnabled(true); 814 gate_label->setEnabled(true);
815 } 815 }
816} 816}
817 817
818 818
819 819
820ScriptWidget::ScriptWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name ) 820ScriptWidget::ScriptWidget( PPPData *pd, QWidget *parent, bool isnewaccount, const char *name )
821 : QWidget(parent, name),_pppdata(pd) 821 : QWidget(parent, name),_pppdata(pd)
822{ 822{
823 823
824 QVBoxLayout *tl = new QVBoxLayout(this, 0 ); 824 QVBoxLayout *tl = new QVBoxLayout(this, 0 );
825 se = new ScriptEdit(this); 825 se = new ScriptEdit(this);
826 connect(se, SIGNAL(returnPressed()), SLOT(addButton())); 826 connect(se, SIGNAL(returnPressed()), SLOT(addButton()));
827 tl->addWidget(se); 827 tl->addWidget(se);
828 828
829 // insert equal-sized buttons 829 // insert equal-sized buttons
830 QHBoxLayout *hl = new QHBoxLayout( this ); 830 QHBoxLayout *hl = new QHBoxLayout( this );
831 tl->addLayout( hl ); 831 tl->addLayout( hl );
832 add = new QPushButton( tr("Add"), this ); 832 add = new QPushButton( tr("Add"), this );
833 hl->addWidget( add ); 833 hl->addWidget( add );
834 connect(add, SIGNAL(clicked()), SLOT(addButton())); 834 connect(add, SIGNAL(clicked()), SLOT(addButton()));
835 insert = new QPushButton( tr("Insert"), this ); 835 insert = new QPushButton( tr("Insert"), this );
836 hl->addWidget( insert ); 836 hl->addWidget( insert );
837 connect(insert, SIGNAL(clicked()), SLOT(insertButton())); 837 connect(insert, SIGNAL(clicked()), SLOT(insertButton()));
838 remove = new QPushButton( tr("Remove"), this ); 838 remove = new QPushButton( tr("Remove"), this );
839 hl->addWidget( remove ); 839 hl->addWidget( remove );
840 connect(remove, SIGNAL(clicked()), SLOT(removeButton())); 840 connect(remove, SIGNAL(clicked()), SLOT(removeButton()));
841 841
842 QHBoxLayout *l12 = new QHBoxLayout(0); 842 QHBoxLayout *l12 = new QHBoxLayout(0);
843 tl->addLayout(l12); 843 tl->addLayout(l12);
844 stl = new QListBox(this); 844 stl = new QListBox(this);
845 // stl->setVScrollBarMode( QScrollView::AlwaysOff ); 845 // stl->setVScrollBarMode( QScrollView::AlwaysOff );
846 connect(stl, SIGNAL(highlighted(int)), SLOT(stlhighlighted(int))); 846 connect(stl, SIGNAL(highlighted(int)), SLOT(stlhighlighted(int)));
847 // stl->setMinimumSize(QSize(70, 140)); 847 // stl->setMinimumSize(QSize(70, 140));
848 848
849 sl = new QListBox(this); 849 sl = new QListBox(this);
850 // sl->setVScrollBarMode( QScrollView::AlwaysOff ); 850 // sl->setVScrollBarMode( QScrollView::AlwaysOff );
851 connect(sl, SIGNAL(highlighted(int)), SLOT(slhighlighted(int))); 851 connect(sl, SIGNAL(highlighted(int)), SLOT(slhighlighted(int)));
852 // sl->setMinimumSize(QSize(150, 140)); 852 // sl->setMinimumSize(QSize(150, 140));
853 853
854 slb = new QScrollBar(this); 854 slb = new QScrollBar(this);
855 // slb->setFixedWidth(slb->sizeHint().width()); 855 // slb->setFixedWidth(slb->sizeHint().width());
856 connect(slb, SIGNAL(valueChanged(int)), SLOT(scrolling(int))); 856 connect(slb, SIGNAL(valueChanged(int)), SLOT(scrolling(int)));
857 857
858 l12->addWidget(stl, 1); 858 l12->addWidget(stl, 1);
859 l12->addWidget(sl, 3); 859 l12->addWidget(sl, 3);
860 l12->addWidget(slb, 0); 860 l12->addWidget(slb, 0);
861 861
862 //load data from gpppdata 862 //load data from gpppdata
863 if(!isnewaccount) 863 if(!isnewaccount)
864 { 864 {
865 QStringList &comlist = _pppdata->scriptType(); 865 QStringList &comlist = _pppdata->scriptType();
866 QStringList &arglist = _pppdata->script(); 866 QStringList &arglist = _pppdata->script();
867 QStringList::Iterator itcom = comlist.begin(); 867 QStringList::Iterator itcom = comlist.begin();
868 QStringList::Iterator itarg = arglist.begin(); 868 QStringList::Iterator itarg = arglist.begin();
869 869
870 for ( ; 870 for ( ;
871 itcom != comlist.end() && itarg != arglist.end(); 871 itcom != comlist.end() && itarg != arglist.end();
872 ++itcom, ++itarg ) 872 ++itcom, ++itarg )
873 { 873 {
874 stl->insertItem(*itcom); 874 stl->insertItem(*itcom);
875 sl->insertItem(*itarg); 875 sl->insertItem(*itarg);
876 } 876 }
877 } 877 }
878 878
879 insert->setEnabled(false); 879 insert->setEnabled(false);
880 remove->setEnabled(false); 880 remove->setEnabled(false);
881 adjustScrollBar(); 881 adjustScrollBar();
882 tl->activate(); 882 tl->activate();
883} 883}
884 884
885bool ScriptWidget::check() 885bool ScriptWidget::check()
886{ 886{
887 uint lstart = 0; 887 uint lstart = 0;
888 uint lend = 0; 888 uint lend = 0;
889 uint errcnt = 0; 889 uint errcnt = 0;
890 890
891 if(sl->count() > 0) 891 if(sl->count() > 0)
892 { 892 {
893 for( uint i=0; i <= sl->count()-1; i++) 893 for( uint i=0; i <= sl->count()-1; i++)
894 { 894 {
895 if(stl->text(i) == "LoopStart") 895 if(stl->text(i) == "LoopStart")
896 { 896 {
897 lstart++; 897 lstart++;
898 } 898 }
899 if (stl->text(i) == "LoopEnd") 899 if (stl->text(i) == "LoopEnd")
900 { 900 {
901 lend++; 901 lend++;
902 } 902 }
903 if ( lend > lstart ) errcnt++; 903 if ( lend > lstart ) errcnt++;
904 } 904 }
905 return ( (errcnt == 0 ) && (lstart == lend) ); 905 return ( (errcnt == 0 ) && (lstart == lend) );
906 } 906 }
907 return true; 907 return true;
908} 908}
909 909
910 910
911void ScriptWidget::save() 911void ScriptWidget::save()
912{ 912{
913 QStringList typelist, arglist; 913 QStringList typelist, arglist;
914 for(uint i=0; i < sl->count(); i++) 914 for(uint i=0; i < sl->count(); i++)
915 { 915 {
916 typelist.append(stl->text(i)); 916 typelist.append(stl->text(i));
917 arglist.append(sl->text(i)); 917 arglist.append(sl->text(i));
918 } 918 }
919 _pppdata->setScriptType(typelist); 919 _pppdata->setScriptType(typelist);
920 _pppdata->setScript(arglist); 920 _pppdata->setScript(arglist);
921} 921}
922 922
923 923
924 924
925void ScriptWidget::adjustScrollBar() 925void ScriptWidget::adjustScrollBar()
926{ 926{
927 if((int)sl->count() <= sl->numItemsVisible()) 927 if((int)sl->count() <= sl->numItemsVisible())
928 slb->setRange(0, 0); 928 slb->setRange(0, 0);
929 else 929 else
930 slb->setRange(0, (sl->count() - sl->numItemsVisible())+1); 930 slb->setRange(0, (sl->count() - sl->numItemsVisible())+1);
931} 931}
932 932
933 933
934void ScriptWidget::scrolling(int i) 934void ScriptWidget::scrolling(int i)
935{ 935{
936 sl->setTopItem(i); 936 sl->setTopItem(i);
937 stl->setTopItem(i); 937 stl->setTopItem(i);
938} 938}
939 939
940 940
941void ScriptWidget::slhighlighted(int i) 941void ScriptWidget::slhighlighted(int i)
942{ 942{
943 insert->setEnabled(true); 943 insert->setEnabled(true);
944 remove->setEnabled(true); 944 remove->setEnabled(true);
945 stl->setCurrentItem(i); 945 stl->setCurrentItem(i);
946} 946}
947 947
948 948
949void ScriptWidget::stlhighlighted(int i) 949void ScriptWidget::stlhighlighted(int i)
950{ 950{
951 insert->setEnabled(true); 951 insert->setEnabled(true);
952 remove->setEnabled(true); 952 remove->setEnabled(true);
953 sl->setCurrentItem(i); 953 sl->setCurrentItem(i);
954} 954}
955 955
956 956
957void ScriptWidget::addButton() 957void ScriptWidget::addButton()
958{ 958{
959 //don't allow more than the maximum script entries 959 //don't allow more than the maximum script entries
960 if(sl->count() == MAX_SCRIPT_ENTRIES-1) 960 if(sl->count() == MAX_SCRIPT_ENTRIES-1)
961 return; 961 return;
962 962
963 switch(se->type()) 963 switch(se->type())
964 { 964 {
965 case ScriptEdit::Expect: 965 case ScriptEdit::Expect:
966 stl->insertItem("Expect"); 966 stl->insertItem("Expect");
967 sl->insertItem(se->text()); 967 sl->insertItem(se->text());
968 break; 968 break;
969 969
970 case ScriptEdit::Send: 970 case ScriptEdit::Send:
971 stl->insertItem("Send"); 971 stl->insertItem("Send");
972 sl->insertItem(se->text()); 972 sl->insertItem(se->text());
973 break; 973 break;
974 974
975 case ScriptEdit::SendNoEcho: 975 case ScriptEdit::SendNoEcho:
976 stl->insertItem("SendNoEcho"); 976 stl->insertItem("SendNoEcho");
977 sl->insertItem(se->text()); 977 sl->insertItem(se->text());
978 break; 978 break;
979 979
980 case ScriptEdit::Pause: 980 case ScriptEdit::Pause:
981 stl->insertItem("Pause"); 981 stl->insertItem("Pause");
982 sl->insertItem(se->text()); 982 sl->insertItem(se->text());
983 break; 983 break;
984 984
985 case ScriptEdit::Hangup: 985 case ScriptEdit::Hangup:
986 stl->insertItem("Hangup"); 986 stl->insertItem("Hangup");
987 sl->insertItem(""); 987 sl->insertItem("");
988 break; 988 break;
989 989
990 case ScriptEdit::Answer: 990 case ScriptEdit::Answer:
991 stl->insertItem("Answer"); 991 stl->insertItem("Answer");
992 sl->insertItem(""); 992 sl->insertItem("");
993 break; 993 break;
994 994
995 case ScriptEdit::Timeout: 995 case ScriptEdit::Timeout:
996 stl->insertItem("Timeout"); 996 stl->insertItem("Timeout");
997 sl->insertItem(se->text()); 997 sl->insertItem(se->text());
998 break; 998 break;
999 999
1000 case ScriptEdit::Password: 1000 case ScriptEdit::Password:
1001 stl->insertItem("Password"); 1001 stl->insertItem("Password");
1002 sl->insertItem(se->text()); 1002 sl->insertItem(se->text());
1003 break; 1003 break;
1004 1004
1005 case ScriptEdit::ID: 1005 case ScriptEdit::ID:
1006 stl->insertItem("ID"); 1006 stl->insertItem("ID");
1007 sl->insertItem(se->text()); 1007 sl->insertItem(se->text());
1008 break; 1008 break;
1009 1009
1010 case ScriptEdit::Prompt: 1010 case ScriptEdit::Prompt:
1011 stl->insertItem("Prompt"); 1011 stl->insertItem("Prompt");
1012 sl->insertItem(se->text()); 1012 sl->insertItem(se->text());
1013 break; 1013 break;
1014 1014
1015 case ScriptEdit::PWPrompt: 1015 case ScriptEdit::PWPrompt:
1016 stl->insertItem("PWPrompt"); 1016 stl->insertItem("PWPrompt");
1017 sl->insertItem(se->text()); 1017 sl->insertItem(se->text());
1018 break; 1018 break;
1019 1019
1020 case ScriptEdit::LoopStart: 1020 case ScriptEdit::LoopStart:
1021 stl->insertItem("LoopStart"); 1021 stl->insertItem("LoopStart");
1022 sl->insertItem(se->text()); 1022 sl->insertItem(se->text());
1023 break; 1023 break;
1024 1024
1025 case ScriptEdit::LoopEnd: 1025 case ScriptEdit::LoopEnd:
1026 stl->insertItem("LoopEnd"); 1026 stl->insertItem("LoopEnd");
1027 sl->insertItem(se->text()); 1027 sl->insertItem(se->text());
1028 break; 1028 break;
1029 1029
1030 case ScriptEdit::Scan: 1030 case ScriptEdit::Scan:
1031 stl->insertItem("Scan"); 1031 stl->insertItem("Scan");
1032 sl->insertItem(se->text()); 1032 sl->insertItem(se->text());
1033 break; 1033 break;
1034 1034
1035 case ScriptEdit::Save: 1035 case ScriptEdit::Save:
1036 stl->insertItem("Save"); 1036 stl->insertItem("Save");
1037 sl->insertItem(se->text()); 1037 sl->insertItem(se->text());
1038 break; 1038 break;
1039 1039
1040 default: 1040 default:
1041 break; 1041 break;
1042 } 1042 }
1043 1043
1044 //get the scrollbar adjusted, and scroll the list so we can see what 1044 //get the scrollbar adjusted, and scroll the list so we can see what
1045 //we're adding to 1045 //we're adding to
1046 adjustScrollBar(); 1046 adjustScrollBar();
1047 slb->setValue(slb->maxValue()); 1047 slb->setValue(slb->maxValue());
1048 1048
1049 //clear the text in the entry box 1049 //clear the text in the entry box
1050 se->setText(""); 1050 se->setText("");
1051} 1051}
1052 1052
1053 1053
1054void ScriptWidget::insertButton() 1054void ScriptWidget::insertButton()
1055{ 1055{
1056 //exit if there is no highlighted item, or we've reached the 1056 //exit if there is no highlighted item, or we've reached the
1057 //maximum entries in the script list 1057 //maximum entries in the script list
1058 if(sl->currentItem() < 0 || (sl->count() == MAX_SCRIPT_ENTRIES-1)) 1058 if(sl->currentItem() < 0 || (sl->count() == MAX_SCRIPT_ENTRIES-1))
1059 return; 1059 return;
1060 1060
1061 switch(se->type()) 1061 switch(se->type())
1062 { 1062 {
1063 case ScriptEdit::Expect: 1063 case ScriptEdit::Expect:
1064 stl->insertItem("Expect", stl->currentItem()); 1064 stl->insertItem("Expect", stl->currentItem());
1065 sl->insertItem(se->text(), sl->currentItem()); 1065 sl->insertItem(se->text(), sl->currentItem());
1066 break; 1066 break;
1067 1067
1068 case ScriptEdit::Send: 1068 case ScriptEdit::Send:
1069 stl->insertItem("Send", stl->currentItem()); 1069 stl->insertItem("Send", stl->currentItem());
1070 sl->insertItem(se->text(), sl->currentItem()); 1070 sl->insertItem(se->text(), sl->currentItem());
1071 break; 1071 break;
1072 1072
1073 case ScriptEdit::SendNoEcho: 1073 case ScriptEdit::SendNoEcho:
1074 stl->insertItem("SendNoEcho", stl->currentItem()); 1074 stl->insertItem("SendNoEcho", stl->currentItem());
1075 sl->insertItem(se->text(), sl->currentItem()); 1075 sl->insertItem(se->text(), sl->currentItem());
1076 break; 1076 break;
1077 1077
1078 case ScriptEdit::Pause: 1078 case ScriptEdit::Pause:
1079 stl->insertItem("Pause", stl->currentItem()); 1079 stl->insertItem("Pause", stl->currentItem());
1080 sl->insertItem(se->text(), sl->currentItem()); 1080 sl->insertItem(se->text(), sl->currentItem());
1081 break; 1081 break;
1082 1082
1083 case ScriptEdit::Hangup: 1083 case ScriptEdit::Hangup:
1084 stl->insertItem("Hangup", stl->currentItem()); 1084 stl->insertItem("Hangup", stl->currentItem());
1085 sl->insertItem("", sl->currentItem()); 1085 sl->insertItem("", sl->currentItem());
1086 break; 1086 break;
1087 1087
1088 case ScriptEdit::Answer: 1088 case ScriptEdit::Answer:
1089 stl->insertItem("Answer", stl->currentItem()); 1089 stl->insertItem("Answer", stl->currentItem());
1090 sl->insertItem("", sl->currentItem()); 1090 sl->insertItem("", sl->currentItem());
1091 break; 1091 break;
1092 1092
1093 case ScriptEdit::Timeout: 1093 case ScriptEdit::Timeout:
1094 stl->insertItem("Timeout", stl->currentItem()); 1094 stl->insertItem("Timeout", stl->currentItem());
1095 sl->insertItem(se->text(), sl->currentItem()); 1095 sl->insertItem(se->text(), sl->currentItem());
1096 break; 1096 break;
1097 1097
1098 case ScriptEdit::Password: 1098 case ScriptEdit::Password:
1099 stl->insertItem("Password", stl->currentItem()); 1099 stl->insertItem("Password", stl->currentItem());
1100 sl->insertItem(se->text(), sl->currentItem()); 1100 sl->insertItem(se->text(), sl->currentItem());
1101 break; 1101 break;
1102 1102
1103 case ScriptEdit::ID: 1103 case ScriptEdit::ID:
1104 stl->insertItem("ID", stl->currentItem()); 1104 stl->insertItem("ID", stl->currentItem());
1105 sl->insertItem(se->text(), sl->currentItem()); 1105 sl->insertItem(se->text(), sl->currentItem());
1106 break; 1106 break;
1107 1107
1108 case ScriptEdit::Prompt: 1108 case ScriptEdit::Prompt:
1109 stl->insertItem("Prompt", stl->currentItem()); 1109 stl->insertItem("Prompt", stl->currentItem());
1110 sl->insertItem(se->text(), sl->currentItem()); 1110 sl->insertItem(se->text(), sl->currentItem());
1111 break; 1111 break;
1112 1112
1113 case ScriptEdit::PWPrompt: 1113 case ScriptEdit::PWPrompt:
1114 stl->insertItem("PWPrompt", stl->currentItem()); 1114 stl->insertItem("PWPrompt", stl->currentItem());
1115 sl->insertItem(se->text(), sl->currentItem()); 1115 sl->insertItem(se->text(), sl->currentItem());
1116 break; 1116 break;
1117 1117
1118 case ScriptEdit::LoopStart: 1118 case ScriptEdit::LoopStart:
1119 stl->insertItem("LoopStart", stl->currentItem()); 1119 stl->insertItem("LoopStart", stl->currentItem());
1120 sl->insertItem(se->text(), sl->currentItem()); 1120 sl->insertItem(se->text(), sl->currentItem());
1121 break; 1121 break;
1122 1122
1123 case ScriptEdit::LoopEnd: 1123 case ScriptEdit::LoopEnd:
1124 stl->insertItem("LoopEnd", stl->currentItem()); 1124 stl->insertItem("LoopEnd", stl->currentItem());
1125 sl->insertItem(se->text(), sl->currentItem()); 1125 sl->insertItem(se->text(), sl->currentItem());
1126 break; 1126 break;
1127 1127
1128 case ScriptEdit::Scan: 1128 case ScriptEdit::Scan:
1129 stl->insertItem("Scan", stl->currentItem()); 1129 stl->insertItem("Scan", stl->currentItem());
1130 sl->insertItem(se->text(), sl->currentItem()); 1130 sl->insertItem(se->text(), sl->currentItem());
1131 break; 1131 break;
1132 1132
1133 case ScriptEdit::Save: 1133 case ScriptEdit::Save:
1134 stl->insertItem("Save", stl->currentItem()); 1134 stl->insertItem("Save", stl->currentItem());
1135 sl->insertItem(se->text(), sl->currentItem()); 1135 sl->insertItem(se->text(), sl->currentItem());
1136 break; 1136 break;
1137 1137
1138 default: 1138 default:
1139 break; 1139 break;
1140 } 1140 }
1141 adjustScrollBar(); 1141 adjustScrollBar();
1142 se->setText(""); 1142 se->setText("");
1143} 1143}
1144 1144
1145 1145
1146void ScriptWidget::removeButton() 1146void ScriptWidget::removeButton()
1147{ 1147{
1148 if(sl->currentItem() >= 0) 1148 if(sl->currentItem() >= 0)
1149 { 1149 {
1150 int stlc = stl->currentItem(); 1150 int stlc = stl->currentItem();
1151 sl->removeItem(sl->currentItem()); 1151 sl->removeItem(sl->currentItem());
1152 stl->removeItem(stlc); 1152 stl->removeItem(stlc);
1153 adjustScrollBar(); 1153 adjustScrollBar();
1154 insert->setEnabled(sl->currentItem() != -1); 1154 insert->setEnabled(sl->currentItem() != -1);
1155 remove->setEnabled(sl->currentItem() != -1); 1155 remove->setEnabled(sl->currentItem() != -1);
1156 } 1156 }
1157} 1157}
1158 1158
1159 1159
1160 1160
1161///////////////////////////////////////////////////////////////////////////// 1161/////////////////////////////////////////////////////////////////////////////
1162// 1162//
1163// Used to specify a new phone number 1163// Used to specify a new phone number
1164// 1164//
1165///////////////////////////////////////////////////////////////////////////// 1165/////////////////////////////////////////////////////////////////////////////
1166PhoneNumberDialog::PhoneNumberDialog(QWidget *parent) 1166PhoneNumberDialog::PhoneNumberDialog(QWidget *parent)
1167 : QDialog(parent,"PhoneNumberDialog",true) 1167 : QDialog(parent,"PhoneNumberDialog",true)
1168{ 1168{
1169 setCaption( tr("Add Phone Number") ); 1169 setCaption( tr("Add Phone Number") );
1170 1170
1171 1171
1172 QVBoxLayout *layout = new QVBoxLayout( this ); 1172 QVBoxLayout *layout = new QVBoxLayout( this );
1173 layout->setSpacing( 3 ); 1173 layout->setSpacing( 3 );
1174 layout->setMargin( 3 ); 1174 layout->setMargin( 3 );
1175 1175
1176 // QHBox *hbox = new QHBox(this); 1176 // QHBox *hbox = new QHBox(this);
1177 // setMainWidget(hbox); 1177 // setMainWidget(hbox);
1178 1178
1179 // hbox->setSpacing( 2 );//KDialog::spacingHint()); 1179 // hbox->setSpacing( 2 );//KDialog::spacingHint());
1180 1180
1181 QLabel *label = new QLabel(this, tr("Enter a phone number:")); 1181 QLabel *label = new QLabel(this, tr("Enter a phone number:"));
1182 layout->addWidget( label ); 1182 layout->addWidget( label );
1183 1183
1184 le = new QLineEdit(this, "lineEdit"); 1184 le = new QLineEdit(this, "lineEdit");
1185 layout->addWidget( le ); 1185 layout->addWidget( le );
1186 1186
1187 connect(le, SIGNAL(textChanged(const QString &)), 1187 connect(le, SIGNAL(textChanged(const QString&)),
1188 this, SLOT(textChanged(const QString &))); 1188 this, SLOT(textChanged(const QString&)));
1189 1189
1190 le->setFocus(); 1190 le->setFocus();
1191 textChanged(""); 1191 textChanged("");
1192 1192
1193 1193
1194} 1194}
1195 1195
1196 1196
1197QString PhoneNumberDialog::phoneNumber() 1197QString PhoneNumberDialog::phoneNumber()
1198{ 1198{
1199 QString s = le->text(); 1199 QString s = le->text();
1200 1200
1201 return s; 1201 return s;
1202} 1202}
1203 1203
1204 1204
1205void PhoneNumberDialog::textChanged(const QString &s) 1205void PhoneNumberDialog::textChanged(const QString &s)
1206{ 1206{
1207 // enableButtonOK(s.length() > 0); 1207 // enableButtonOK(s.length() > 0);
1208} 1208}
1209 1209
1210 1210
1211//#include "edit.moc" 1211//#include "edit.moc"
diff --git a/noncore/settings/networksettings/ppp/general.cpp b/noncore/settings/networksettings/ppp/general.cpp
index ff1b11b..81dab38 100644
--- a/noncore/settings/networksettings/ppp/general.cpp
+++ b/noncore/settings/networksettings/ppp/general.cpp
@@ -1,526 +1,526 @@
1/* 1/*
2 * kPPP: A pppd front end for the KDE project 2 * kPPP: A pppd front end for the KDE project
3 * 3 *
4 * $Id$ 4 * $Id$
5 * 5 *
6 * Copyright (C) 1997 Bernd Johannes Wuebben 6 * Copyright (C) 1997 Bernd Johannes Wuebben
7 * wuebben@math.cornell.edu 7 * wuebben@math.cornell.edu
8 * 8 *
9 * based on EzPPP: 9 * based on EzPPP:
10 * Copyright (C) 1997 Jay Painter 10 * Copyright (C) 1997 Jay Painter
11 * 11 *
12 * This program is free software; you can redistribute it and/or 12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public 13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either 14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version. 15 * version 2 of the License, or (at your option) any later version.
16 * 16 *
17 * This program is distributed in the hope that it will be useful, 17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details. 20 * Library General Public License for more details.
21 * 21 *
22 * You should have received a copy of the GNU Library General Public 22 * You should have received a copy of the GNU Library General Public
23 * License along with this program; if not, write to the Free 23 * License along with this program; if not, write to the Free
24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */ 25 */
26 26
27#include "general.h" 27#include "general.h"
28#include "interfaceppp.h" 28#include "interfaceppp.h"
29#include "modeminfo.h" 29#include "modeminfo.h"
30#include "modemcmds.h" 30#include "modemcmds.h"
31#include "pppdata.h" 31#include "pppdata.h"
32 32
33/* OPIE */ 33/* OPIE */
34#include <qpe/config.h> 34#include <qpe/config.h>
35#include <qpe/qpeapplication.h> 35#include <qpe/qpeapplication.h>
36 36
37/* QT */ 37/* QT */
38#include <qcheckbox.h> 38#include <qcheckbox.h>
39#include <qcombobox.h> 39#include <qcombobox.h>
40#include <qlabel.h> 40#include <qlabel.h>
41#include <qlayout.h> 41#include <qlayout.h>
42#include <qpushbutton.h> 42#include <qpushbutton.h>
43#include <qslider.h> 43#include <qslider.h>
44#include <qspinbox.h> 44#include <qspinbox.h>
45#include <qwhatsthis.h> 45#include <qwhatsthis.h>
46 46
47/* STD */ 47/* STD */
48#include <termios.h> 48#include <termios.h>
49#include <string.h> 49#include <string.h>
50 50
51 51
52ModemWidget::ModemWidget( PPPData *pd, QWidget *parent, const char *name ) 52ModemWidget::ModemWidget( PPPData *pd, QWidget *parent, const char *name )
53 : QWidget(parent, name), _pppdata(pd) 53 : QWidget(parent, name), _pppdata(pd)
54{ 54{
55 int k; 55 int k;
56 56
57 QGridLayout *tl = new QGridLayout(this, 8, 2, 0 );//, KDialog::spacingHint()); 57 QGridLayout *tl = new QGridLayout(this, 8, 2, 0 );//, KDialog::spacingHint());
58 58
59 QLabel *label1; 59 QLabel *label1;
60 60
61 label1 = new QLabel(tr("Modem &name:"), this); 61 label1 = new QLabel(tr("Modem &name:"), this);
62 tl->addWidget(label1, 0, 0); 62 tl->addWidget(label1, 0, 0);
63 63
64 modemname = new QLineEdit(this, "modemName"); 64 modemname = new QLineEdit(this, "modemName");
65 modemname->setText( _pppdata->devname() ); 65 modemname->setText( _pppdata->devname() );
66 label1->setBuddy(modemname); 66 label1->setBuddy(modemname);
67 tl->addWidget(modemname, 0, 1); 67 tl->addWidget(modemname, 0, 1);
68 68
69 label1 = new QLabel(tr("Modem de&vice:"), this); 69 label1 = new QLabel(tr("Modem de&vice:"), this);
70 tl->addWidget(label1, 1, 0); 70 tl->addWidget(label1, 1, 0);
71 71
72 modemdevice = new QComboBox(false, this); 72 modemdevice = new QComboBox(false, this);
73 modemdevice->setEditable( true ); 73 modemdevice->setEditable( true );
74 modemdevice->setDuplicatesEnabled ( false ); 74 modemdevice->setDuplicatesEnabled ( false );
75 modemdevice->setInsertionPolicy( QComboBox::AtTop ); 75 modemdevice->setInsertionPolicy( QComboBox::AtTop );
76 label1->setBuddy(modemdevice); 76 label1->setBuddy(modemdevice);
77 77
78 Config cfg("NetworkSetupPPP"); 78 Config cfg("NetworkSetupPPP");
79 cfg.setGroup("Devices_General"); 79 cfg.setGroup("Devices_General");
80 QStringList devs = cfg.readListEntry("devices",','); 80 QStringList devs = cfg.readListEntry("devices",',');
81 if (devs.isEmpty()) devs << "/dev/modem" << "/dev/ircomm0" << "/dev/ttyS0"; 81 if (devs.isEmpty()) devs << "/dev/modem" << "/dev/ircomm0" << "/dev/ttyS0";
82 modemdevice->insertStringList( devs ); 82 modemdevice->insertStringList( devs );
83 tl->addWidget(modemdevice, 1, 1); 83 tl->addWidget(modemdevice, 1, 1);
84 84
85 // connect(modemdevice, SIGNAL(activated(int)), 85 // connect(modemdevice, SIGNAL(activated(int)),
86 // SLOT(setmodemdc(int))); 86 // SLOT(setmodemdc(int)));
87 // connect(modemdevice, SIGNAL(textChanged( const QString & ) ), 87 // connect(modemdevice, SIGNAL(textChanged(const QString&) ),
88 // SLOT( setmodemdc( const QString &) ) ); 88 // SLOT( setmodemdc(const QString&) ) );
89 89
90 QString tmp = tr("This specifies the serial port your modem is attached \n" 90 QString tmp = tr("This specifies the serial port your modem is attached \n"
91 "to. On Linux/x86, typically this is either /dev/ttyS0 \n" 91 "to. On Linux/x86, typically this is either /dev/ttyS0 \n"
92 "(COM1 under DOS) or /dev/ttyS1 (COM2 under DOS).\n" 92 "(COM1 under DOS) or /dev/ttyS1 (COM2 under DOS).\n"
93 "\n" 93 "\n"
94 "If you have an internal ISDN card with AT command\n" 94 "If you have an internal ISDN card with AT command\n"
95 "emulation (most cards under Linux support this), you\n" 95 "emulation (most cards under Linux support this), you\n"
96 "should select one of the /dev/ttyIx devices."); 96 "should select one of the /dev/ttyIx devices.");
97 97
98 QWhatsThis::add(label1,tmp); 98 QWhatsThis::add(label1,tmp);
99 QWhatsThis::add(modemdevice,tmp); 99 QWhatsThis::add(modemdevice,tmp);
100 100
101 101
102 label1 = new QLabel(tr("&Flow control:"), this); 102 label1 = new QLabel(tr("&Flow control:"), this);
103 tl->addWidget(label1, 2, 0); 103 tl->addWidget(label1, 2, 0);
104 104
105 flowcontrol = new QComboBox(false, this); 105 flowcontrol = new QComboBox(false, this);
106 label1->setBuddy(flowcontrol); 106 label1->setBuddy(flowcontrol);
107 flowcontrol->insertItem(tr("Hardware [CRTSCTS]")); 107 flowcontrol->insertItem(tr("Hardware [CRTSCTS]"));
108 flowcontrol->insertItem(tr("Software [XON/XOFF]")); 108 flowcontrol->insertItem(tr("Software [XON/XOFF]"));
109 flowcontrol->insertItem(tr("None")); 109 flowcontrol->insertItem(tr("None"));
110 tl->addWidget(flowcontrol, 2, 1); 110 tl->addWidget(flowcontrol, 2, 1);
111 // connect(flowcontrol, SIGNAL(activated(int)), 111 // connect(flowcontrol, SIGNAL(activated(int)),
112 // SLOT(setflowcontrol(int))); 112 // SLOT(setflowcontrol(int)));
113 113
114 tmp = tr("<p>Specifies how the serial port and modem\n" 114 tmp = tr("<p>Specifies how the serial port and modem\n"
115 "communicate. You should not change this unless\n" 115 "communicate. You should not change this unless\n"
116 "you know what you are doing.\n" 116 "you know what you are doing.\n"
117 "\n" 117 "\n"
118 "<b>Default</b>: CRTSCTS"); 118 "<b>Default</b>: CRTSCTS");
119 119
120 QWhatsThis::add(label1,tmp); 120 QWhatsThis::add(label1,tmp);
121 QWhatsThis::add(flowcontrol,tmp); 121 QWhatsThis::add(flowcontrol,tmp);
122 122
123 QLabel *labelenter = new QLabel(tr("&Line termination:"), this); 123 QLabel *labelenter = new QLabel(tr("&Line termination:"), this);
124 tl->addWidget(labelenter, 3, 0); 124 tl->addWidget(labelenter, 3, 0);
125 125
126 enter = new QComboBox(false, this); 126 enter = new QComboBox(false, this);
127 labelenter->setBuddy(enter); 127 labelenter->setBuddy(enter);
128 enter->insertItem("CR"); 128 enter->insertItem("CR");
129 enter->insertItem("LF"); 129 enter->insertItem("LF");
130 enter->insertItem("CR/LF"); 130 enter->insertItem("CR/LF");
131 tl->addWidget(enter, 3, 1); 131 tl->addWidget(enter, 3, 1);
132 // connect(enter, SIGNAL(activated(int)), SLOT(setenter(int))); 132 // connect(enter, SIGNAL(activated(int)), SLOT(setenter(int)));
133 tmp = tr("<p>Specifies how AT commands are sent to your\n" 133 tmp = tr("<p>Specifies how AT commands are sent to your\n"
134 "modem. Most modems will work fine with the\n" 134 "modem. Most modems will work fine with the\n"
135 "default <i>CR/LF</i>. If your modem does not react\n" 135 "default <i>CR/LF</i>. If your modem does not react\n"
136 "to the init string, you should try different\n" 136 "to the init string, you should try different\n"
137 "settings here\n" 137 "settings here\n"
138 "\n" 138 "\n"
139 "<b>Default</b>: CR/LF"); 139 "<b>Default</b>: CR/LF");
140 140
141 QWhatsThis::add(labelenter,tmp); 141 QWhatsThis::add(labelenter,tmp);
142 QWhatsThis::add(enter, tmp); 142 QWhatsThis::add(enter, tmp);
143 143
144 QLabel *baud_label = new QLabel(tr("Co&nnection speed:"), this); 144 QLabel *baud_label = new QLabel(tr("Co&nnection speed:"), this);
145 tl->addWidget(baud_label, 4, 0); 145 tl->addWidget(baud_label, 4, 0);
146 baud_c = new QComboBox(this); 146 baud_c = new QComboBox(this);
147 baud_label->setBuddy(baud_c); 147 baud_label->setBuddy(baud_c);
148 148
149 static const char *baudrates[] = 149 static const char *baudrates[] =
150 { 150 {
151 151
152#ifdef B460800 152#ifdef B460800
153 "460800", 153 "460800",
154#endif 154#endif
155 155
156#ifdef B230400 156#ifdef B230400
157 "230400", 157 "230400",
158#endif 158#endif
159 159
160#ifdef B115200 160#ifdef B115200
161 "115200", 161 "115200",
162#endif 162#endif
163 163
164#ifdef B57600 164#ifdef B57600
165 "57600", 165 "57600",
166#endif 166#endif
167 167
168 "38400", 168 "38400",
169 "19200", 169 "19200",
170 "9600", 170 "9600",
171 "2400", 171 "2400",
172 0 172 0
173 }; 173 };
174 174
175 for(k = 0; baudrates[k]; k++) 175 for(k = 0; baudrates[k]; k++)
176 baud_c->insertItem(baudrates[k]); 176 baud_c->insertItem(baudrates[k]);
177 177
178 baud_c->setCurrentItem(3); 178 baud_c->setCurrentItem(3);
179 // connect(baud_c, SIGNAL(activated(int)), 179 // connect(baud_c, SIGNAL(activated(int)),
180 // this, SLOT(speed_selection(int))); 180 // this, SLOT(speed_selection(int)));
181 tl->addWidget(baud_c, 4, 1); 181 tl->addWidget(baud_c, 4, 1);
182 182
183 tmp = tr("Specifies the speed your modem and the serial\n" 183 tmp = tr("Specifies the speed your modem and the serial\n"
184 "port talk to each other. You should begin with\n" 184 "port talk to each other. You should begin with\n"
185 "the default of 38400 bits/sec. If everything\n" 185 "the default of 38400 bits/sec. If everything\n"
186 "works you can try to increase this value, but to\n" 186 "works you can try to increase this value, but to\n"
187 "no more than 115200 bits/sec (unless you know\n" 187 "no more than 115200 bits/sec (unless you know\n"
188 "that your serial port supports higher speeds)."); 188 "that your serial port supports higher speeds).");
189 189
190 QWhatsThis::add(baud_label,tmp); 190 QWhatsThis::add(baud_label,tmp);
191 QWhatsThis::add(baud_c,tmp); 191 QWhatsThis::add(baud_c,tmp);
192 192
193 for(int i=0; i <= enter->count()-1; i++) 193 for(int i=0; i <= enter->count()-1; i++)
194 { 194 {
195 if(_pppdata->enter() == enter->text(i)) 195 if(_pppdata->enter() == enter->text(i))
196 enter->setCurrentItem(i); 196 enter->setCurrentItem(i);
197 } 197 }
198 198
199 tl->addRowSpacing(5, 10); 199 tl->addRowSpacing(5, 10);
200 200
201 //Modem Lock File 201 //Modem Lock File
202 modemlockfile = new QCheckBox(tr("&Use lock file"), this); 202 modemlockfile = new QCheckBox(tr("&Use lock file"), this);
203 203
204 modemlockfile->setChecked(_pppdata->modemLockFile()); 204 modemlockfile->setChecked(_pppdata->modemLockFile());
205 // connect(modemlockfile, SIGNAL(toggled(bool)), 205 // connect(modemlockfile, SIGNAL(toggled(bool)),
206 // SLOT(modemlockfilechanged(bool))); 206 // SLOT(modemlockfilechanged(bool)));
207 tl->addMultiCellWidget(modemlockfile, 6, 6, 0, 1); 207 tl->addMultiCellWidget(modemlockfile, 6, 6, 0, 1);
208 // l12->addStretch(1); 208 // l12->addStretch(1);
209 QWhatsThis::add(modemlockfile, 209 QWhatsThis::add(modemlockfile,
210 tr("<p>To prevent other programs from accessing the\n" 210 tr("<p>To prevent other programs from accessing the\n"
211 "modem while a connection is established, a\n" 211 "modem while a connection is established, a\n"
212 "file can be created to indicate that the modem\n" 212 "file can be created to indicate that the modem\n"
213 "is in use. On Linux an example file would be\n" 213 "is in use. On Linux an example file would be\n"
214 "<tt>/var/lock/LCK..ttyS1</tt>\n" 214 "<tt>/var/lock/LCK..ttyS1</tt>\n"
215 "Here you can select whether this locking will\n" 215 "Here you can select whether this locking will\n"
216 "be done.\n" 216 "be done.\n"
217 "\n" 217 "\n"
218 "<b>Default</b>: On")); 218 "<b>Default</b>: On"));
219 219
220 // Modem Timeout Line Edit Box 220 // Modem Timeout Line Edit Box
221 QHBoxLayout *timeoutLayout = new QHBoxLayout( this ); 221 QHBoxLayout *timeoutLayout = new QHBoxLayout( this );
222 QLabel *timeoutlabel = new QLabel( tr("Modem timeout:") ,this, "timeout" ); 222 QLabel *timeoutlabel = new QLabel( tr("Modem timeout:") ,this, "timeout" );
223 modemtimeout = new QSpinBox( 1, 120, 1, this, "modemTimeout" ); 223 modemtimeout = new QSpinBox( 1, 120, 1, this, "modemTimeout" );
224 // modemtimeout = new KIntNumInput(_pppdata->modemTimeout(), this); 224 // modemtimeout = new KIntNumInput(_pppdata->modemTimeout(), this);
225 // modemtimeout->setLabel(tr("Modem &timeout:")); 225 // modemtimeout->setLabel(tr("Modem &timeout:"));
226 // modemtimeout->setRange(1, 120, 1); 226 // modemtimeout->setRange(1, 120, 1);
227 modemtimeout->setSuffix(tr(" sec")); 227 modemtimeout->setSuffix(tr(" sec"));
228 modemtimeout->setValue( _pppdata->modemTimeout() ); 228 modemtimeout->setValue( _pppdata->modemTimeout() );
229 // connect(modemtimeout, SIGNAL(valueChanged(int)), 229 // connect(modemtimeout, SIGNAL(valueChanged(int)),
230 // SLOT(modemtimeoutchanged(int))); 230 // SLOT(modemtimeoutchanged(int)));
231 timeoutLayout->addWidget(timeoutlabel); 231 timeoutLayout->addWidget(timeoutlabel);
232 timeoutLayout->addWidget(modemtimeout); 232 timeoutLayout->addWidget(modemtimeout);
233 tl->addMultiCellLayout(timeoutLayout, 7, 7, 0, 1); 233 tl->addMultiCellLayout(timeoutLayout, 7, 7, 0, 1);
234 234
235 QWhatsThis::add(modemtimeout, 235 QWhatsThis::add(modemtimeout,
236 tr("This specifies how long <i>kppp</i> waits for a\n" 236 tr("This specifies how long <i>kppp</i> waits for a\n"
237 "<i>CONNECT</i> response from your modem. The\n" 237 "<i>CONNECT</i> response from your modem. The\n"
238 "recommended value is 30 seconds.")); 238 "recommended value is 30 seconds."));
239 239
240 //set stuff from gpppdata 240 //set stuff from gpppdata
241 for(int i=0; i <= enter->count()-1; i++) 241 for(int i=0; i <= enter->count()-1; i++)
242 { 242 {
243 if(_pppdata->enter() == enter->text(i)) 243 if(_pppdata->enter() == enter->text(i))
244 enter->setCurrentItem(i); 244 enter->setCurrentItem(i);
245 } 245 }
246 246
247 for(int i=0; i <= modemdevice->count()-1; i++) 247 for(int i=0; i <= modemdevice->count()-1; i++)
248 { 248 {
249 if(_pppdata->modemDevice() == modemdevice->text(i)) 249 if(_pppdata->modemDevice() == modemdevice->text(i))
250 modemdevice->setCurrentItem(i); 250 modemdevice->setCurrentItem(i);
251 } 251 }
252 252
253 for(int i=0; i <= flowcontrol->count()-1; i++) 253 for(int i=0; i <= flowcontrol->count()-1; i++)
254 { 254 {
255 if(_pppdata->flowcontrol() == flowcontrol->text(i)) 255 if(_pppdata->flowcontrol() == flowcontrol->text(i))
256 flowcontrol->setCurrentItem(i); 256 flowcontrol->setCurrentItem(i);
257 } 257 }
258 258
259 //set the modem speed 259 //set the modem speed
260 for(int i=0; i < baud_c->count(); i++) 260 for(int i=0; i < baud_c->count(); i++)
261 if(baud_c->text(i) == _pppdata->speed()) 261 if(baud_c->text(i) == _pppdata->speed())
262 baud_c->setCurrentItem(i); 262 baud_c->setCurrentItem(i);
263 263
264 tl->setRowStretch(1, 1); 264 tl->setRowStretch(1, 1);
265} 265}
266 266
267ModemWidget::~ModemWidget() 267ModemWidget::~ModemWidget()
268{ 268{
269 QStringList devs; 269 QStringList devs;
270 270
271 for (int i=0;i<modemdevice->count();i++) 271 for (int i=0;i<modemdevice->count();i++)
272 { 272 {
273 QString s = modemdevice->text(i); 273 QString s = modemdevice->text(i);
274 s.simplifyWhiteSpace(); 274 s.simplifyWhiteSpace();
275 if (! s.isEmpty() ) devs << s; 275 if (! s.isEmpty() ) devs << s;
276 } 276 }
277 277
278 278
279 QString edited = modemdevice->currentText(); 279 QString edited = modemdevice->currentText();
280 if ( !( edited ).isEmpty() ) 280 if ( !( edited ).isEmpty() )
281 { 281 {
282 edited.simplifyWhiteSpace(); 282 edited.simplifyWhiteSpace();
283 if ( devs.contains( edited ) == 0 ) 283 if ( devs.contains( edited ) == 0 )
284 { 284 {
285 devs << edited; 285 devs << edited;
286 } 286 }
287 _pppdata->setModemDevice( edited ); 287 _pppdata->setModemDevice( edited );
288 } 288 }
289 289
290 290
291 Config cfg("NetworkSetupPPP"); 291 Config cfg("NetworkSetupPPP");
292 cfg.setGroup("Devices_General"); 292 cfg.setGroup("Devices_General");
293 cfg.writeEntry("devices",devs,','); 293 cfg.writeEntry("devices",devs,',');
294 294
295} 295}
296 296
297// void ModemWidget::speed_selection(int) { 297// void ModemWidget::speed_selection(int) {
298// _pppdata->setSpeed(baud_c->text(baud_c->currentItem())); 298// _pppdata->setSpeed(baud_c->text(baud_c->currentItem()));
299// } 299// }
300 300
301 301
302// void ModemWidget::setenter(int ) { 302// void ModemWidget::setenter(int ) {
303// _pppdata->setEnter(enter->text(enter->currentItem())); 303// _pppdata->setEnter(enter->text(enter->currentItem()));
304// } 304// }
305 305
306 306
307// void ModemWidget::setmodemdc(int i) { 307// void ModemWidget::setmodemdc(int i) {
308// _pppdata->setModemDevice(modemdevice->text(i)); 308// _pppdata->setModemDevice(modemdevice->text(i));
309// } 309// }
310 310
311// void ModemWidget::setmodemdc( const QString &string ) { 311// void ModemWidget::setmodemdc( const QString &string ) {
312// _pppdata->setModemDevice( string ); 312// _pppdata->setModemDevice( string );
313// } 313// }
314 314
315// void ModemWidget::setflowcontrol(int i) { 315// void ModemWidget::setflowcontrol(int i) {
316// _pppdata->setFlowcontrol(flowcontrol->text(i)); 316// _pppdata->setFlowcontrol(flowcontrol->text(i));
317// } 317// }
318 318
319 319
320// void ModemWidget::modemlockfilechanged(bool set) { 320// void ModemWidget::modemlockfilechanged(bool set) {
321// _pppdata->setModemLockFile(set); 321// _pppdata->setModemLockFile(set);
322// } 322// }
323 323
324 324
325// void ModemWidget::modemtimeoutchanged(int n) { 325// void ModemWidget::modemtimeoutchanged(int n) {
326// _pppdata->setModemTimeout(n); 326// _pppdata->setModemTimeout(n);
327// } 327// }
328 328
329 329
330 330
331bool ModemWidget::save() 331bool ModemWidget::save()
332{ 332{
333 //first check to make sure that the device name is unique! 333 //first check to make sure that the device name is unique!
334 if(modemname->text().isEmpty() || 334 if(modemname->text().isEmpty() ||
335 !_pppdata->isUniqueDevname(modemname->text())) 335 !_pppdata->isUniqueDevname(modemname->text()))
336 return false; 336 return false;
337 337
338 qDebug("ModemWidget::save saving modem1 data"); 338 qDebug("ModemWidget::save saving modem1 data");
339 _pppdata->setDevname( modemname->text() ); 339 _pppdata->setDevname( modemname->text() );
340 _pppdata->setModemDevice( modemdevice->currentText() ); 340 _pppdata->setModemDevice( modemdevice->currentText() );
341 _pppdata->setFlowcontrol(flowcontrol->currentText()); 341 _pppdata->setFlowcontrol(flowcontrol->currentText());
342 _pppdata->setFlowcontrol(flowcontrol->currentText()); 342 _pppdata->setFlowcontrol(flowcontrol->currentText());
343 _pppdata->setSpeed(baud_c->currentText()); 343 _pppdata->setSpeed(baud_c->currentText());
344 _pppdata->setModemLockFile( modemlockfile->isChecked()); 344 _pppdata->setModemLockFile( modemlockfile->isChecked());
345 _pppdata->setModemTimeout( modemtimeout->value() ); 345 _pppdata->setModemTimeout( modemtimeout->value() );
346 return true; 346 return true;
347 347
348} 348}
349 349
350ModemWidget2::ModemWidget2( PPPData *pd, InterfacePPP *ip, QWidget *parent, 350ModemWidget2::ModemWidget2( PPPData *pd, InterfacePPP *ip, QWidget *parent,
351 const char *name) 351 const char *name)
352 : QWidget(parent, name), _pppdata(pd), _ifaceppp(ip) 352 : QWidget(parent, name), _pppdata(pd), _ifaceppp(ip)
353{ 353{
354 QVBoxLayout *l1 = new QVBoxLayout(this, 0 );//, KDialog::spacingHint()); 354 QVBoxLayout *l1 = new QVBoxLayout(this, 0 );//, KDialog::spacingHint());
355 355
356 356
357 waitfordt = new QCheckBox(tr("&Wait for dial tone before dialing"), this); 357 waitfordt = new QCheckBox(tr("&Wait for dial tone before dialing"), this);
358 waitfordt->setChecked(_pppdata->waitForDialTone()); 358 waitfordt->setChecked(_pppdata->waitForDialTone());
359 // connect(waitfordt, SIGNAL(toggled(bool)), SLOT(waitfordtchanged(bool))); 359 // connect(waitfordt, SIGNAL(toggled(bool)), SLOT(waitfordtchanged(bool)));
360 l1->addWidget(waitfordt); 360 l1->addWidget(waitfordt);
361 QWhatsThis::add(waitfordt, 361 QWhatsThis::add(waitfordt,
362 tr("<p>Normally the modem waits for a dial tone\n" 362 tr("<p>Normally the modem waits for a dial tone\n"
363 "from your phone line, indicating that it can\n" 363 "from your phone line, indicating that it can\n"
364 "start to dial a number. If your modem does not\n" 364 "start to dial a number. If your modem does not\n"
365 "recognize this sound, or your local phone system\n" 365 "recognize this sound, or your local phone system\n"
366 "does not emit such a tone, uncheck this option\n" 366 "does not emit such a tone, uncheck this option\n"
367 "\n" 367 "\n"
368 "<b>Default:</b>: On")); 368 "<b>Default:</b>: On"));
369 369
370 QHBoxLayout *waitLayout = new QHBoxLayout( this ); 370 QHBoxLayout *waitLayout = new QHBoxLayout( this );
371 QLabel *waitLabel = new QLabel( tr("Busy wait:"), this, "busyWait" ); 371 QLabel *waitLabel = new QLabel( tr("Busy wait:"), this, "busyWait" );
372 busywait = new QSpinBox( 0, 300, 5, this, "busyWait" ); 372 busywait = new QSpinBox( 0, 300, 5, this, "busyWait" );
373 // busywait = new KIntNumInput(_pppdata->busyWait(), this); 373 // busywait = new KIntNumInput(_pppdata->busyWait(), this);
374 // busywait->setLabel(tr("B&usy wait:")); 374 // busywait->setLabel(tr("B&usy wait:"));
375 // busywait->setRange(0, 300, 5, true); 375 // busywait->setRange(0, 300, 5, true);
376 busywait->setSuffix(tr(" sec")); 376 busywait->setSuffix(tr(" sec"));
377 // connect(busywait, SIGNAL(valueChanged(int)), SLOT(busywaitchanged(int))); 377 // connect(busywait, SIGNAL(valueChanged(int)), SLOT(busywaitchanged(int)));
378 waitLayout->addWidget(waitLabel); 378 waitLayout->addWidget(waitLabel);
379 waitLayout->addWidget(busywait); 379 waitLayout->addWidget(busywait);
380 l1->addLayout( waitLayout ); 380 l1->addLayout( waitLayout );
381 381
382 QWhatsThis::add(busywait, 382 QWhatsThis::add(busywait,
383 tr("Specifies the number of seconds to wait before\n" 383 tr("Specifies the number of seconds to wait before\n"
384 "redial if all dialed numbers are busy. This is\n" 384 "redial if all dialed numbers are busy. This is\n"
385 "necessary because some modems get stuck if the\n" 385 "necessary because some modems get stuck if the\n"
386 "same number is busy too often.\n" 386 "same number is busy too often.\n"
387 "\n" 387 "\n"
388 "The default is 0 seconds, you should not change\n" 388 "The default is 0 seconds, you should not change\n"
389 "this unless you need to.")); 389 "this unless you need to."));
390 390
391 l1->addSpacing(10); 391 l1->addSpacing(10);
392 392
393 QHBoxLayout *hbl = new QHBoxLayout; 393 QHBoxLayout *hbl = new QHBoxLayout;
394 hbl->setSpacing(2);//KDialog::spacingHint()); 394 hbl->setSpacing(2);//KDialog::spacingHint());
395 395
396 QLabel *volumeLabel = new QLabel(tr("Modem &volume:"), this); 396 QLabel *volumeLabel = new QLabel(tr("Modem &volume:"), this);
397 hbl->addWidget(volumeLabel); 397 hbl->addWidget(volumeLabel);
398 volume = new QSlider(0, 2, 1, _pppdata->volume(), 398 volume = new QSlider(0, 2, 1, _pppdata->volume(),
399 QSlider::Horizontal, this); 399 QSlider::Horizontal, this);
400 volumeLabel->setBuddy(volume); 400 volumeLabel->setBuddy(volume);
401 volume->setTickmarks(QSlider::Below); 401 volume->setTickmarks(QSlider::Below);
402 hbl->addWidget(volume); 402 hbl->addWidget(volume);
403 403
404 l1->addLayout(hbl); 404 l1->addLayout(hbl);
405 405
406 // connect(volume, SIGNAL(valueChanged(int)), 406 // connect(volume, SIGNAL(valueChanged(int)),
407 // this, SLOT(volumeChanged(int))); 407 // this, SLOT(volumeChanged(int)));
408 QString tmp = tr("Most modems have a speaker which makes\n" 408 QString tmp = tr("Most modems have a speaker which makes\n"
409 "a lot of noise when dialing. Here you can\n" 409 "a lot of noise when dialing. Here you can\n"
410 "either turn this completely off or select a\n" 410 "either turn this completely off or select a\n"
411 "lower volume.\n" 411 "lower volume.\n"
412 "\n" 412 "\n"
413 "If this does not work for your modem,\n" 413 "If this does not work for your modem,\n"
414 "you must modify the modem volume command."); 414 "you must modify the modem volume command.");
415 415
416 QWhatsThis::add(volumeLabel,tmp); 416 QWhatsThis::add(volumeLabel,tmp);
417 QWhatsThis::add(volume, tmp); 417 QWhatsThis::add(volume, tmp);
418 418
419 l1->addSpacing(20); 419 l1->addSpacing(20);
420 420
421#if 0 421#if 0
422 chkbox1 = new QCheckBox(tr("Modem asserts CD line"), this); 422 chkbox1 = new QCheckBox(tr("Modem asserts CD line"), this);
423 chkbox1->setChecked(_pppdata->UseCDLine()); 423 chkbox1->setChecked(_pppdata->UseCDLine());
424 connect(chkbox1,SIGNAL(toggled(bool)), 424 connect(chkbox1,SIGNAL(toggled(bool)),
425 this,SLOT(use_cdline_toggled(bool))); 425 this,SLOT(use_cdline_toggled(bool)));
426 l12->addWidget(chkbox1); 426 l12->addWidget(chkbox1);
427 l12->addStretch(1); 427 l12->addStretch(1);
428 l1->addStretch(1); 428 l1->addStretch(1);
429 QWhatsThis::add(chkbox1, 429 QWhatsThis::add(chkbox1,
430 tr("This controls how <i>kppp</i> detects that the modem\n" 430 tr("This controls how <i>kppp</i> detects that the modem\n"
431 "is not responding. Unless you are having\n" 431 "is not responding. Unless you are having\n"
432 "problems with this, do not modify this setting.\n" 432 "problems with this, do not modify this setting.\n"
433 "\n" 433 "\n"
434 "<b>Default</b>: Off")); 434 "<b>Default</b>: Off"));
435#endif 435#endif
436 436
437 modemcmds = new QPushButton(tr("Mod&em Commands..."), this); 437 modemcmds = new QPushButton(tr("Mod&em Commands..."), this);
438 QWhatsThis::add(modemcmds, 438 QWhatsThis::add(modemcmds,
439 tr("Allows you to change the AT command for\n" 439 tr("Allows you to change the AT command for\n"
440 "your modem.")); 440 "your modem."));
441 441
442 modeminfo_button = new QPushButton(tr("&Query Modem..."), this); 442 modeminfo_button = new QPushButton(tr("&Query Modem..."), this);
443 QWhatsThis::add(modeminfo_button, 443 QWhatsThis::add(modeminfo_button,
444 tr("Most modems support the ATI command set to\n" 444 tr("Most modems support the ATI command set to\n"
445 "find out vendor and revision of your modem.\n" 445 "find out vendor and revision of your modem.\n"
446 "\n" 446 "\n"
447 "Press this button to query your modem for\n" 447 "Press this button to query your modem for\n"
448 "this information. It can be useful to help\n" 448 "this information. It can be useful to help\n"
449 "you setup the modem")); 449 "you setup the modem"));
450 450
451 // terminal_button = new QPushButton(tr("&Terminal..."), this); 451 // terminal_button = new QPushButton(tr("&Terminal..."), this);
452 // QWhatsThis::add(terminal_button, 452 // QWhatsThis::add(terminal_button,
453 // tr("Opens the built-in terminal program. You\n" 453 // tr("Opens the built-in terminal program. You\n"
454 // "can use this if you want to play around\n" 454 // "can use this if you want to play around\n"
455 // "with your modem's AT command set")); 455 // "with your modem's AT command set"));
456 456
457 QHBoxLayout *hbox = new QHBoxLayout(); 457 QHBoxLayout *hbox = new QHBoxLayout();
458 l1->addLayout(hbox); 458 l1->addLayout(hbox);
459 hbox->addStretch(1); 459 hbox->addStretch(1);
460 QVBoxLayout *vbox = new QVBoxLayout(); 460 QVBoxLayout *vbox = new QVBoxLayout();
461 hbox->addLayout(vbox); 461 hbox->addLayout(vbox);
462 462
463 vbox->addWidget(modemcmds); 463 vbox->addWidget(modemcmds);
464 vbox->addWidget(modeminfo_button); 464 vbox->addWidget(modeminfo_button);
465 // vbox->addWidget(terminal_button); 465 // vbox->addWidget(terminal_button);
466 466
467 hbox->addStretch(1); 467 hbox->addStretch(1);
468 l1->addStretch(1); 468 l1->addStretch(1);
469 469
470 connect(modemcmds, SIGNAL(clicked()), 470 connect(modemcmds, SIGNAL(clicked()),
471 SLOT(modemcmdsbutton())); 471 SLOT(modemcmdsbutton()));
472 connect(modeminfo_button, SIGNAL(clicked()), 472 connect(modeminfo_button, SIGNAL(clicked()),
473 SLOT(query_modem())); 473 SLOT(query_modem()));
474 // connect(terminal_button, SIGNAL(clicked()), 474 // connect(terminal_button, SIGNAL(clicked()),
475 // SLOT(terminal())); 475 // SLOT(terminal()));
476} 476}
477 477
478 478
479void ModemWidget2::modemcmdsbutton() 479void ModemWidget2::modemcmdsbutton()
480{ 480{
481 ModemCommands mc(_ifaceppp->data(), this, "commands" , true, Qt::WStyle_ContextHelp); 481 ModemCommands mc(_ifaceppp->data(), this, "commands" , true, Qt::WStyle_ContextHelp);
482 482
483 QPEApplication::execDialog( &mc ); 483 QPEApplication::execDialog( &mc );
484} 484}
485 485
486 486
487void ModemWidget2::query_modem() 487void ModemWidget2::query_modem()
488{ 488{
489 ModemTransfer mt(_ifaceppp->modem(), this); 489 ModemTransfer mt(_ifaceppp->modem(), this);
490 mt.exec(); 490 mt.exec();
491} 491}
492 492
493 493
494// void ModemWidget2::terminal() { 494// void ModemWidget2::terminal() {
495// MiniTerm terminal(NULL,NULL); 495// MiniTerm terminal(NULL,NULL);
496// terminal.exec(); 496// terminal.exec();
497// } 497// }
498 498
499 499
500// #if 0 500// #if 0
501// void ModemWidget2::use_cdline_toggled(bool on) { 501// void ModemWidget2::use_cdline_toggled(bool on) {
502// _pppdata->setUseCDLine(on); 502// _pppdata->setUseCDLine(on);
503// } 503// }
504// #endif 504// #endif
505 505
506// void ModemWidget2::waitfordtchanged(bool b) { 506// void ModemWidget2::waitfordtchanged(bool b) {
507// _pppdata->setWaitForDialTone((int)b); 507// _pppdata->setWaitForDialTone((int)b);
508// } 508// }
509 509
510// void ModemWidget2::busywaitchanged(int n) { 510// void ModemWidget2::busywaitchanged(int n) {
511// _pppdata->setbusyWait(n); 511// _pppdata->setbusyWait(n);
512// } 512// }
513 513
514 514
515// void ModemWidget2::volumeChanged(int v) { 515// void ModemWidget2::volumeChanged(int v) {
516// _pppdata->setVolume(v); 516// _pppdata->setVolume(v);
517// } 517// }
518 518
519bool ModemWidget2::save() 519bool ModemWidget2::save()
520{ 520{
521 _pppdata->setWaitForDialTone(waitfordt->isChecked()); 521 _pppdata->setWaitForDialTone(waitfordt->isChecked());
522 _pppdata->setbusyWait(busywait->value()); 522 _pppdata->setbusyWait(busywait->value());
523 _pppdata->setVolume(volume->value()); 523 _pppdata->setVolume(volume->value());
524 return true; 524 return true;
525} 525}
526 526
diff --git a/noncore/settings/networksettings/ppp/kpppwidget.cpp b/noncore/settings/networksettings/ppp/kpppwidget.cpp
index e466358..e21bbc7 100644
--- a/noncore/settings/networksettings/ppp/kpppwidget.cpp
+++ b/noncore/settings/networksettings/ppp/kpppwidget.cpp
@@ -1,877 +1,877 @@
1/* 1/*
2 * 2 *
3 * kPPP: A pppd front end for the KDE project 3 * kPPP: A pppd front end for the KDE project
4 * 4 *
5 * $Id$ 5 * $Id$
6 * 6 *
7 * Copyright (C) 1997 Bernd Johannes Wuebben 7 * Copyright (C) 1997 Bernd Johannes Wuebben
8 * wuebben@math.cornell.edu 8 * wuebben@math.cornell.edu
9 * 9 *
10 * Copyright (C) 1998-2002 Harri Porten <porten@kde.org> 10 * Copyright (C) 1998-2002 Harri Porten <porten@kde.org>
11 * 11 *
12 * This program is free software; you can redistribute it and/or 12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public 13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either 14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version. 15 * version 2 of the License, or (at your option) any later version.
16 * 16 *
17 * This program is distributed in the hope that it will be useful, 17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details. 20 * Library General Public License for more details.
21 * 21 *
22 * You should have received a copy of the GNU Library General Public 22 * You should have received a copy of the GNU Library General Public
23 * License along with this program; if not, write to the Free 23 * License along with this program; if not, write to the Free
24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 24 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */ 25 */
26 26
27#include "kpppwidget.h" 27#include "kpppwidget.h"
28 28
29#include <qapplication.h> 29#include <qapplication.h>
30#include <qcombobox.h> 30#include <qcombobox.h>
31#include <qdir.h> 31#include <qdir.h>
32#include <qevent.h> 32#include <qevent.h>
33#include <qdialog.h> 33#include <qdialog.h>
34#include <qlabel.h> 34#include <qlabel.h>
35#include <qpushbutton.h> 35#include <qpushbutton.h>
36#include <qregexp.h> 36#include <qregexp.h>
37#include <qtabwidget.h> 37#include <qtabwidget.h>
38#include <qdialog.h> 38#include <qdialog.h>
39#include <qwhatsthis.h> 39#include <qwhatsthis.h>
40#include <qcheckbox.h> 40#include <qcheckbox.h>
41 41
42// #include <kaboutdata.h> 42// #include <kaboutdata.h>
43// #include <kapplication.h> 43// #include <kapplication.h>
44#include <qbuttongroup.h> 44#include <qbuttongroup.h>
45#include <qmessagebox.h> 45#include <qmessagebox.h>
46#include <qpushbutton.h> 46#include <qpushbutton.h>
47 47
48#include <stdlib.h> 48#include <stdlib.h>
49#include <errno.h> 49#include <errno.h>
50#include <signal.h> 50#include <signal.h>
51 51
52#include "runtests.h" 52#include "runtests.h"
53 53
54//#include "main.h" 54//#include "main.h"
55#include "auth.h" 55#include "auth.h"
56#include "modem.h" 56#include "modem.h"
57//#include "ppplog.h" 57//#include "ppplog.h"
58//#include "opener.h" 58//#include "opener.h"
59//#include "requester.h" 59//#include "requester.h"
60//#include "pppstats.h" 60//#include "pppstats.h"
61#include "pppdata.h" 61#include "pppdata.h"
62#include "general.h" 62#include "general.h"
63#include "interface.h" 63#include "interface.h"
64 64
65#define execute_command system 65#define execute_command system
66 66
67KPPPWidget *p_kppp = 0; 67KPPPWidget *p_kppp = 0;
68 68
69KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *name, bool modal, WFlags fl ) 69KPPPWidget::KPPPWidget(PPPData*pd, Interface *i, QWidget *parent, const char *name, bool modal, WFlags fl )
70 : QDialog(parent, name, modal, Qt::WStyle_ContextHelp ), _pppdata(pd) 70 : QDialog(parent, name, modal, Qt::WStyle_ContextHelp ), _pppdata(pd)
71{ 71{
72// tabWindow = 0; 72// tabWindow = 0;
73 p_kppp = this; 73 p_kppp = this;
74 // before doing anything else, run a few tests 74 // before doing anything else, run a few tests
75 if (!_pppdata->setModemDevice( i->getInterfaceName() )) 75 if (!_pppdata->setModemDevice( i->getInterfaceName() ))
76 _pppdata->setModemDevice("/dev/modem"); 76 _pppdata->setModemDevice("/dev/modem");
77 qDebug("PPPConfigWidget::PPPConfigWidget"); 77 qDebug("PPPConfigWidget::PPPConfigWidget");
78 qDebug(" interface->getHardwareName >%s<", i->getHardwareName().latin1()); 78 qDebug(" interface->getHardwareName >%s<", i->getHardwareName().latin1());
79 if (!_pppdata->setAccount( i->getHardwareName() )) 79 if (!_pppdata->setAccount( i->getHardwareName() ))
80 _pppdata->setAccount( 0 ); 80 _pppdata->setAccount( 0 );
81 81
82 qDebug(" _pppdata->accname >%s<",_pppdata->accname().latin1()); 82 qDebug(" _pppdata->accname >%s<",_pppdata->accname().latin1());
83 qDebug(" _pppdata->currentAccountID() >%i<",_pppdata->currentAccountID()); 83 qDebug(" _pppdata->currentAccountID() >%i<",_pppdata->currentAccountID());
84 84
85 int result = runTests(); 85 int result = runTests();
86 if(result == TEST_CRITICAL) 86 if(result == TEST_CRITICAL)
87 exit(4); 87 exit(4);
88 88
89// installEventFilter(this); 89// installEventFilter(this);
90 90
91 QVBoxLayout *tl = new QVBoxLayout(this, 10, 10); 91 QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
92 92
93 QGridLayout *l1 = new QGridLayout(3, 4); 93 QGridLayout *l1 = new QGridLayout(3, 4);
94 tl->addLayout(l1); 94 tl->addLayout(l1);
95 l1->addColSpacing(0, 10); 95 l1->addColSpacing(0, 10);
96 l1->addColSpacing(3, 10); 96 l1->addColSpacing(3, 10);
97 l1->setColStretch(1, 3); 97 l1->setColStretch(1, 3);
98 l1->setColStretch(2, 4); 98 l1->setColStretch(2, 4);
99 99
100 label1 = new QLabel(QObject::tr("C&onnect to: "), this); 100 label1 = new QLabel(QObject::tr("C&onnect to: "), this);
101 l1->addWidget(label1, 0, 1); 101 l1->addWidget(label1, 0, 1);
102 102
103 connectto_c = new QComboBox(false, this); 103 connectto_c = new QComboBox(false, this);
104 label1->setBuddy(connectto_c); 104 label1->setBuddy(connectto_c);
105 105
106 connect(connectto_c, SIGNAL(activated(int)), 106 connect(connectto_c, SIGNAL(activated(int)),
107 SLOT(newdefaultaccount(int))); 107 SLOT(newdefaultaccount(int)));
108 l1->addWidget(connectto_c, 0, 2); 108 l1->addWidget(connectto_c, 0, 2);
109 109
110 ID_Label = new QLabel(QObject::tr("&Login ID:"), this); 110 ID_Label = new QLabel(QObject::tr("&Login ID:"), this);
111 l1->addWidget(ID_Label, 1, 1); 111 l1->addWidget(ID_Label, 1, 1);
112 112
113 // the entry line for usernames 113 // the entry line for usernames
114 ID_Edit = new QLineEdit(this); 114 ID_Edit = new QLineEdit(this);
115 ID_Label->setBuddy(ID_Edit); 115 ID_Label->setBuddy(ID_Edit);
116 l1->addWidget(ID_Edit, 1, 2); 116 l1->addWidget(ID_Edit, 1, 2);
117 connect(ID_Edit, SIGNAL(returnPressed()), 117 connect(ID_Edit, SIGNAL(returnPressed()),
118 this, SLOT(enterPressedInID())); 118 this, SLOT(enterPressedInID()));
119 QString tmp = QObject::tr("<p>Type in the username that you got from your\n" 119 QString tmp = QObject::tr("<p>Type in the username that you got from your\n"
120 "ISP. This is especially important for PAP\n" 120 "ISP. This is especially important for PAP\n"
121 "and CHAP. You may omit this when you use\n" 121 "and CHAP. You may omit this when you use\n"
122 "terminal-based or script-based authentication.\n" 122 "terminal-based or script-based authentication.\n"
123 "\n" 123 "\n"
124 "<b>Important</b>: case is important here:\n" 124 "<b>Important</b>: case is important here:\n"
125 "<i>myusername</i> is not the same as <i>MyUserName</i>!"); 125 "<i>myusername</i> is not the same as <i>MyUserName</i>!");
126 126
127 QWhatsThis::add(ID_Label,tmp); 127 QWhatsThis::add(ID_Label,tmp);
128 QWhatsThis::add(ID_Edit,tmp); 128 QWhatsThis::add(ID_Edit,tmp);
129 129
130 PW_Label = new QLabel(QObject::tr("&Password:"), this); 130 PW_Label = new QLabel(QObject::tr("&Password:"), this);
131 l1->addWidget(PW_Label, 2, 1); 131 l1->addWidget(PW_Label, 2, 1);
132 132
133 PW_Edit= new QLineEdit(this); 133 PW_Edit= new QLineEdit(this);
134 PW_Label->setBuddy(PW_Edit); 134 PW_Label->setBuddy(PW_Edit);
135 PW_Edit->setEchoMode(QLineEdit::Password); 135 PW_Edit->setEchoMode(QLineEdit::Password);
136 l1->addWidget(PW_Edit, 2, 2); 136 l1->addWidget(PW_Edit, 2, 2);
137 connect(PW_Edit, SIGNAL(returnPressed()), 137 connect(PW_Edit, SIGNAL(returnPressed()),
138 this, SLOT(enterPressedInPW())); 138 this, SLOT(enterPressedInPW()));
139 139
140 tmp = QObject::tr("<p>Type in the password that you got from your\n" 140 tmp = QObject::tr("<p>Type in the password that you got from your\n"
141 "ISP. This is especially important for PAP\n" 141 "ISP. This is especially important for PAP\n"
142 "and CHAP. You may omit this when you use\n" 142 "and CHAP. You may omit this when you use\n"
143 "terminal-based or script-based authentication.\n" 143 "terminal-based or script-based authentication.\n"
144 "\n" 144 "\n"
145 "<b>Important</b>: case is important here:\n" 145 "<b>Important</b>: case is important here:\n"
146 "<i>mypassword</i> is not the same as <i>MyPassword</i>!"); 146 "<i>mypassword</i> is not the same as <i>MyPassword</i>!");
147 147
148 QWhatsThis::add(PW_Label,tmp); 148 QWhatsThis::add(PW_Label,tmp);
149 QWhatsThis::add(PW_Edit,tmp); 149 QWhatsThis::add(PW_Edit,tmp);
150 150
151 QHBoxLayout *l3 = new QHBoxLayout; 151 QHBoxLayout *l3 = new QHBoxLayout;
152 tl->addSpacing(5); 152 tl->addSpacing(5);
153 tl->addLayout(l3); 153 tl->addLayout(l3);
154 tl->addSpacing(5); 154 tl->addSpacing(5);
155 l3->addSpacing(10); 155 l3->addSpacing(10);
156 log = new QCheckBox(QObject::tr("Show lo&g window"), this); 156 log = new QCheckBox(QObject::tr("Show lo&g window"), this);
157 connect(log, SIGNAL(toggled(bool)), 157 connect(log, SIGNAL(toggled(bool)),
158 this, SLOT(log_window_toggled(bool))); 158 this, SLOT(log_window_toggled(bool)));
159 log->setChecked(_pppdata->get_show_log_window()); 159 log->setChecked(_pppdata->get_show_log_window());
160 l3->addWidget(log); 160 l3->addWidget(log);
161 161
162 QWhatsThis::add(log, 162 QWhatsThis::add(log,
163 QObject::tr("<p>This controls whether a log window is shown.\n" 163 QObject::tr("<p>This controls whether a log window is shown.\n"
164 "A log window shows the communication between\n" 164 "A log window shows the communication between\n"
165 "<i>kppp</i> and your modem. This will help you\n" 165 "<i>kppp</i> and your modem. This will help you\n"
166 "in tracking down problems.\n" 166 "in tracking down problems.\n"
167 "\n" 167 "\n"
168 "Turn it off if <i>kppp</i> routinely connects without\n" 168 "Turn it off if <i>kppp</i> routinely connects without\n"
169 "problems")); 169 "problems"));
170 170
171// fline = new QSeparator( KSeparator::HLine, this); 171// fline = new QSeparator( KSeparator::HLine, this);
172// tl->addWidget(fline); 172// tl->addWidget(fline);
173 173
174 QHBoxLayout *l2 = new QHBoxLayout(this); 174 QHBoxLayout *l2 = new QHBoxLayout(this);
175 tl->addLayout(l2); 175 tl->addLayout(l2);
176 176
177 int minw = 0; 177 int minw = 0;
178 quit_b = new QPushButton(QObject::tr("&Quit"), this); 178 quit_b = new QPushButton(QObject::tr("&Quit"), this);
179 // quit_b-> setGuiItem (KGuiItem(QObject::tr("&Quit"), "exit" ) ); 179 // quit_b-> setGuiItem (KGuiItem(QObject::tr("&Quit"), "exit" ) );
180 connect( quit_b, SIGNAL(clicked()), SLOT(quitbutton())); 180 connect( quit_b, SIGNAL(clicked()), SLOT(quitbutton()));
181 if(quit_b->sizeHint().width() > minw) 181 if(quit_b->sizeHint().width() > minw)
182 minw = quit_b->sizeHint().width(); 182 minw = quit_b->sizeHint().width();
183 183
184 setup_b = new QPushButton(QObject::tr("&Setup..."), this); 184 setup_b = new QPushButton(QObject::tr("&Setup..."), this);
185// setup_b->setGuiItem (KGuiItem(QObject::tr("&Setup...")) ); 185// setup_b->setGuiItem (KGuiItem(QObject::tr("&Setup...")) );
186 connect( setup_b, SIGNAL(clicked()), SLOT(expandbutton())); 186 connect( setup_b, SIGNAL(clicked()), SLOT(expandbutton()));
187 if(setup_b->sizeHint().width() > minw) 187 if(setup_b->sizeHint().width() > minw)
188 minw = setup_b->sizeHint().width(); 188 minw = setup_b->sizeHint().width();
189 189
190 190
191 191
192// if(_pppdata->access() != KConfig::ReadWrite) 192// if(_pppdata->access() != KConfig::ReadWrite)
193 // setup_b->setEnabled(false); 193 // setup_b->setEnabled(false);
194 194
195// help_b = new QPushButton(QObject::tr("&Help"), this); 195// help_b = new QPushButton(QObject::tr("&Help"), this);
196// connect( help_b, SIGNAL(clicked()), SLOT(helpbutton())); 196// connect( help_b, SIGNAL(clicked()), SLOT(helpbutton()));
197 197
198// KHelpMenu *helpMenu = new KHelpMenu(this, KGlobal::instance()->aboutData(), true); 198// KHelpMenu *helpMenu = new KHelpMenu(this, KGlobal::instance()->aboutData(), true);
199// help_b->setPopup((QPopupMenu*)helpMenu->menu()); 199// help_b->setPopup((QPopupMenu*)helpMenu->menu());
200// help_b->setGuiItem (KGuiItem(QObject::tr("&Help"), "help" ) ); 200// help_b->setGuiItem (KGuiItem(QObject::tr("&Help"), "help" ) );
201 201
202// if(help_b->sizeHint().width() > minw) 202// if(help_b->sizeHint().width() > minw)
203// minw = help_b->sizeHint().width(); 203// minw = help_b->sizeHint().width();
204 204
205 connect_b = new QPushButton(QObject::tr("&Connect"), this); 205 connect_b = new QPushButton(QObject::tr("&Connect"), this);
206 connect_b->setDefault(true); 206 connect_b->setDefault(true);
207 connect_b->setFocus(); 207 connect_b->setFocus();
208 connect(connect_b, SIGNAL(clicked()), SLOT(beginConnect())); 208 connect(connect_b, SIGNAL(clicked()), SLOT(beginConnect()));
209 if(connect_b->sizeHint().width() > minw) 209 if(connect_b->sizeHint().width() > minw)
210 minw = connect_b->sizeHint().width(); 210 minw = connect_b->sizeHint().width();
211 211
212 quit_b->setFixedWidth(minw); 212 quit_b->setFixedWidth(minw);
213 setup_b->setFixedWidth(minw); 213 setup_b->setFixedWidth(minw);
214// help_b->setFixedWidth(help_b->sizeHint().width()); 214// help_b->setFixedWidth(help_b->sizeHint().width());
215 connect_b->setFixedWidth(minw); 215 connect_b->setFixedWidth(minw);
216 216
217 l2->addWidget(quit_b); 217 l2->addWidget(quit_b);
218 l2->addWidget(setup_b); 218 l2->addWidget(setup_b);
219// l2->addWidget(help_b); 219// l2->addWidget(help_b);
220 l2->addSpacing(20); 220 l2->addSpacing(20);
221 l2->addWidget(connect_b); 221 l2->addWidget(connect_b);
222 222
223 setFixedSize(sizeHint()); 223 setFixedSize(sizeHint());
224 224
225 (void)new Modem(_pppdata); 225 (void)new Modem(_pppdata);
226 226
227 // we also connect cmld_start to the beginConnect so that I can run 227 // we also connect cmld_start to the beginConnect so that I can run
228 // the dialer through a command line argument 228 // the dialer through a command line argument
229 connect(this,SIGNAL(cmdl_start()),this,SLOT(beginConnect())); 229 connect(this,SIGNAL(cmdl_start()),this,SLOT(beginConnect()));
230 230
231// stats = new PPPStats; 231// stats = new PPPStats;
232 232
233 // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); 233 // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
234 234
235 // constructor of con_win reads position from config file 235 // constructor of con_win reads position from config file
236 con_win = new ConWindow(_pppdata, 0, "conw", this); 236 con_win = new ConWindow(_pppdata, 0, "conw", this);
237 // KWin::setIcons(con_win->winId(), kapp->icon(), kapp->miniIcon()); 237 // KWin::setIcons(con_win->winId(), kapp->icon(), kapp->miniIcon());
238 238
239// statdlg = new PPPStatsDlg(0, "stats", this, stats); 239// statdlg = new PPPStatsDlg(0, "stats", this, stats);
240// statdlg->hide(); 240// statdlg->hide();
241 241
242 // load up the accounts combo box 242 // load up the accounts combo box
243 243
244// resetaccounts(); 244// resetaccounts();
245 con = new ConnectWidget(_pppdata, 0, "con"); 245 con = new ConnectWidget(_pppdata, 0, "con");
246 //KWin::setIcons(con->winId(), kapp->icon(), kapp->miniIcon() ); 246 //KWin::setIcons(con->winId(), kapp->icon(), kapp->miniIcon() );
247 connect(this, SIGNAL(begin_connect()),con, SLOT(preinit())); 247 connect(this, SIGNAL(begin_connect()),con, SLOT(preinit()));
248 // Is this the best we can do here? it's not right. 248 // Is this the best we can do here? it's not right.
249// QRect desk = QApplication::desktop()->screenGeometry( 249// QRect desk = QApplication::desktop()->screenGeometry(
250// QApplication::desktop()->screenNumber(topLevelWidget())); 250// QApplication::desktop()->screenNumber(topLevelWidget()));
251// con->setGeometry(desk.center().x()-175, desk.center().y()-55, 350,110); 251// con->setGeometry(desk.center().x()-175, desk.center().y()-55, 350,110);
252 252
253 // connect the ConnectWidgets various signals 253 // connect the ConnectWidgets various signals
254 connect(con, SIGNAL(startAccounting()), 254 connect(con, SIGNAL(startAccounting()),
255 this, SLOT(startAccounting())); 255 this, SLOT(startAccounting()));
256 connect(con, SIGNAL(stopAccounting()), 256 connect(con, SIGNAL(stopAccounting()),
257 this, SLOT(stopAccounting())); 257 this, SLOT(stopAccounting()));
258 connect(qApp, SIGNAL(saveYourself()), 258 connect(qApp, SIGNAL(saveYourself()),
259 this, SLOT(saveMyself())); 259 this, SLOT(saveMyself()));
260 connect(qApp, SIGNAL(shutDown()), 260 connect(qApp, SIGNAL(shutDown()),
261 this, SLOT(shutDown())); 261 this, SLOT(shutDown()));
262 262
263 263
264// KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); 264// KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
265 265
266// m_strCmdlAccount = args->getOption("c"); 266// m_strCmdlAccount = args->getOption("c");
267// m_bQuitOnDisconnect = args->isSet("q"); 267// m_bQuitOnDisconnect = args->isSet("q");
268 268
269// if(!m_strCmdlAccount.isEmpty()) { 269// if(!m_strCmdlAccount.isEmpty()) {
270// m_bCmdlAccount = true; 270// m_bCmdlAccount = true;
271// kdDebug(5002) << "cmdl_account: " << m_bCmdlAccount << endl; 271// kdDebug(5002) << "cmdl_account: " << m_bCmdlAccount << endl;
272// } 272// }
273 273
274// if(m_bCmdlAccount){ 274// if(m_bCmdlAccount){
275// bool result = _pppdata->setAccount(m_strCmdlAccount); 275// bool result = _pppdata->setAccount(m_strCmdlAccount);
276// if (!result){ 276// if (!result){
277// QString string; 277// QString string;
278// string = QObject::tr("No such Account:\n%1").arg(m_strCmdlAccount); 278// string = QObject::tr("No such Account:\n%1").arg(m_strCmdlAccount);
279// KMessageBox::error(this, string); 279// KMessageBox::error(this, string);
280// m_bCmdlAccount = false; 280// m_bCmdlAccount = false;
281// this->show(); 281// this->show();
282// } else { 282// } else {
283// beginConnect(); 283// beginConnect();
284// } 284// }
285// } else 285// } else
286// expandbutton(); 286// expandbutton();
287// show(); 287// show();
288 288
289 289
290//#define KPPP_SHOW_NEWS 290//#define KPPP_SHOW_NEWS
291#ifdef KPPP_SHOW_NEWS 291#ifdef KPPP_SHOW_NEWS
292 // keep user informed about recent changes 292 // keep user informed about recent changes
293 if(!m_bCmdlAccount) 293 if(!m_bCmdlAccount)
294 showNews(); 294 showNews();
295#endif 295#endif
296} 296}
297 297
298KPPPWidget::~KPPPWidget() 298KPPPWidget::~KPPPWidget()
299{ 299{
300 p_kppp = 0; 300 p_kppp = 0;
301// delete stats; 301// delete stats;
302} 302}
303 303
304// bool KPPPWidget::eventFilter(QObject *o, QEvent *e) { 304// bool KPPPWidget::eventFilter(QObject *o, QEvent *e) {
305// if(e->type() == QEvent::User) { 305// if(e->type() == QEvent::User) {
306// switch(((SignalEvent*)e)->sigType()) { 306// switch(((SignalEvent*)e)->sigType()) {
307// case SIGINT: 307// case SIGINT:
308// qDebug( "Received a SIGINT" ); 308// qDebug( "Received a SIGINT" );
309// interruptConnection(); 309// interruptConnection();
310// break; 310// break;
311// case SIGCHLD: 311// case SIGCHLD:
312// sigChld(); 312// sigChld();
313// break; 313// break;
314// case SIGUSR1: 314// case SIGUSR1:
315// sigPPPDDied(); 315// sigPPPDDied();
316// break; 316// break;
317// } 317// }
318// return true; 318// return true;
319// } 319// }
320 320
321// if(o == connect_b) { 321// if(o == connect_b) {
322// if(e->type() == QEvent::KeyPress) { 322// if(e->type() == QEvent::KeyPress) {
323// if(connect_b->hasFocus() && ((QKeyEvent *)e)->key() == Qt::Key_Return) { 323// if(connect_b->hasFocus() && ((QKeyEvent *)e)->key() == Qt::Key_Return) {
324// beginConnect(); 324// beginConnect();
325// return true; 325// return true;
326// } 326// }
327// } 327// }
328// } 328// }
329 329
330// return false; 330// return false;
331// } 331// }
332 332
333 333
334 334
335 335
336void KPPPWidget::enterPressedInID() { 336void KPPPWidget::enterPressedInID() {
337 PW_Edit->setFocus(); 337 PW_Edit->setFocus();
338} 338}
339 339
340 340
341void KPPPWidget::enterPressedInPW() { 341void KPPPWidget::enterPressedInPW() {
342 connect_b->setFocus(); 342 connect_b->setFocus();
343} 343}
344 344
345// triggered by the session manager 345// triggered by the session manager
346void KPPPWidget::saveMyself() { 346void KPPPWidget::saveMyself() {
347 _pppdata->save(); 347 _pppdata->save();
348} 348}
349 349
350void KPPPWidget::shutDown() { 350void KPPPWidget::shutDown() {
351 interruptConnection(); 351 interruptConnection();
352 saveMyself(); 352 saveMyself();
353} 353}
354 354
355void KPPPWidget::log_window_toggled(bool on) { 355void KPPPWidget::log_window_toggled(bool on) {
356 _pppdata->set_show_log_window(on); 356 _pppdata->set_show_log_window(on);
357} 357}
358 358
359 359
360 360
361 361
362// void KPPPWidget::resetaccounts() { 362// void KPPPWidget::resetaccounts() {
363// connectto_c->clear(); 363// connectto_c->clear();
364 364
365// int count = _pppdata->count(); 365// int count = _pppdata->count();
366 366
367// // enable/disable controls 367// // enable/disable controls
368// connectto_c->setEnabled(count > 0); 368// connectto_c->setEnabled(count > 0);
369// connect_b->setEnabled(count > 0); 369// connect_b->setEnabled(count > 0);
370// log->setEnabled(count > 0); 370// log->setEnabled(count > 0);
371// ID_Edit->setEnabled(count > 0); 371// ID_Edit->setEnabled(count > 0);
372// PW_Edit->setEnabled(count > 0); 372// PW_Edit->setEnabled(count > 0);
373 373
374// //load the accounts 374// //load the accounts
375// for(int i=0; i < count; i++) { 375// for(int i=0; i < count; i++) {
376// _pppdata->setAccountbyIndex(i); 376// _pppdata->setAccountbyIndex(i);
377// connectto_c->insertItem(_pppdata->accname()); 377// connectto_c->insertItem(_pppdata->accname());
378// } 378// }
379 379
380// //set the default account 380// //set the default account
381// if(!_pppdata->defaultAccount().isEmpty()) { 381// if(!_pppdata->defaultAccount().isEmpty()) {
382// for(int i=0; i < count; i++) 382// for(int i=0; i < count; i++)
383// if(_pppdata->defaultAccount() == connectto_c->text(i)) { 383// if(_pppdata->defaultAccount() == connectto_c->text(i)) {
384 // connectto_c->setCurrentItem(i); 384 // connectto_c->setCurrentItem(i);
385 // _pppdata->setAccountbyIndex(i); 385 // _pppdata->setAccountbyIndex(i);
386 386
387 // ID_Edit->setText(_pppdata->storedUsername()); 387 // ID_Edit->setText(_pppdata->storedUsername());
388 // PW_Edit->setText(_pppdata->storedPassword()); 388 // PW_Edit->setText(_pppdata->storedPassword());
389// } 389// }
390// } 390// }
391// else 391// else
392// if(count > 0) { 392// if(count > 0) {
393// _pppdata->setDefaultAccount(connectto_c->text(0)); 393// _pppdata->setDefaultAccount(connectto_c->text(0));
394// _pppdata->save(); 394// _pppdata->save();
395 // ID_Edit->setText(_pppdata->storedUsername()); 395 // ID_Edit->setText(_pppdata->storedUsername());
396 // PW_Edit->setText(_pppdata->storedPassword()); 396 // PW_Edit->setText(_pppdata->storedPassword());
397// } 397// }
398 398
399// connect(ID_Edit, SIGNAL(textChanged(const QString &)), 399// connect(ID_Edit, SIGNAL(textChanged(const QString&)),
400 // this, SLOT(usernameChanged(const QString &))); 400 // this, SLOT(usernameChanged(const QString&)));
401 401
402// connect(PW_Edit, SIGNAL(textChanged(const QString &)), 402// connect(PW_Edit, SIGNAL(textChanged(const QString&)),
403 // this, SLOT(passwordChanged(const QString &))); 403 // this, SLOT(passwordChanged(const QString&)));
404 404
405// if (ID_Edit->text().isEmpty()) 405// if (ID_Edit->text().isEmpty())
406// ID_Edit->setFocus(); 406// ID_Edit->setFocus();
407// else if (PW_Edit->text().isEmpty()) 407// else if (PW_Edit->text().isEmpty())
408// PW_Edit->setFocus(); 408// PW_Edit->setFocus();
409// } 409// }
410 410
411 411
412void KPPPWidget::interruptConnection() { 412void KPPPWidget::interruptConnection() {
413 // interrupt dial up 413 // interrupt dial up
414// 414//
415 415
416 if (con->isVisible()) 416 if (con->isVisible())
417 emit con->cancelbutton(); 417 emit con->cancelbutton();
418 418
419 // disconnect if online 419 // disconnect if online
420 if (_pppdata->pppdRunning()) 420 if (_pppdata->pppdRunning())
421 emit disconnect(); 421 emit disconnect();
422} 422}
423 423
424 424
425void KPPPWidget::sigPPPDDied() { 425void KPPPWidget::sigPPPDDied() {
426 qDebug( "Received a SIGUSR1" ); 426 qDebug( "Received a SIGUSR1" );
427 427
428 // if we are not connected pppdpid is -1 so have have to check for that 428 // if we are not connected pppdpid is -1 so have have to check for that
429 // in the followin line to make sure that we don't raise a false alarm 429 // in the followin line to make sure that we don't raise a false alarm
430 // such as would be the case when the log file viewer exits. 430 // such as would be the case when the log file viewer exits.
431 if(_pppdata->pppdRunning() || _pppdata->pppdError()) { 431 if(_pppdata->pppdRunning() || _pppdata->pppdError()) {
432 qDebug( "It was pppd that died" ); 432 qDebug( "It was pppd that died" );
433 433
434 // when we killpppd() on Cancel in ConnectWidget 434 // when we killpppd() on Cancel in ConnectWidget
435 // we set pppid to -1 so we won't 435 // we set pppid to -1 so we won't
436 // enter this block 436 // enter this block
437 437
438 // just to be sure 438 // just to be sure
439 439
440 Modem::modem->removeSecret(AUTH_PAP); 440 Modem::modem->removeSecret(AUTH_PAP);
441 Modem::modem->removeSecret(AUTH_CHAP); 441 Modem::modem->removeSecret(AUTH_CHAP);
442 442
443 _pppdata->setpppdRunning(false); 443 _pppdata->setpppdRunning(false);
444 444
445 qDebug( "Executing command on disconnect since pppd has died." ); 445 qDebug( "Executing command on disconnect since pppd has died." );
446 QApplication::flushX(); 446 QApplication::flushX();
447 execute_command(_pppdata->command_on_disconnect()); 447 execute_command(_pppdata->command_on_disconnect());
448 448
449// stopAccounting(); 449// stopAccounting();
450 450
451 con_win->stopClock(); 451 con_win->stopClock();
452// DockWidget::dock_widget->stop_stats(); 452// DockWidget::dock_widget->stop_stats();
453// DockWidget::dock_widget->hide(); 453// DockWidget::dock_widget->hide();
454 454
455 if(!_pppdata->pppdError()) 455 if(!_pppdata->pppdError())
456 _pppdata->setpppdError(E_PPPD_DIED); 456 _pppdata->setpppdError(E_PPPD_DIED);
457 removedns(); 457 removedns();
458 Modem::modem->unlockdevice(); 458 Modem::modem->unlockdevice();
459 // 459 //
460 con->pppdDied(); 460 con->pppdDied();
461 461
462 if(!_pppdata->automatic_redial()) { 462 if(!_pppdata->automatic_redial()) {
463 quit_b->setFocus(); 463 quit_b->setFocus();
464 show(); 464 show();
465 con_win->stopClock(); 465 con_win->stopClock();
466 //stopAccounting(); 466 //stopAccounting();
467 con_win->hide(); 467 con_win->hide();
468 con->hide(); 468 con->hide();
469 469
470 _pppdata->setpppdRunning(false); 470 _pppdata->setpppdRunning(false);
471 // // not in a signal handler !!! KNotifyClient::beep(); 471 // // not in a signal handler !!! KNotifyClient::beep();
472 QString msg; 472 QString msg;
473 if (_pppdata->pppdError() == E_IF_TIMEOUT) 473 if (_pppdata->pppdError() == E_IF_TIMEOUT)
474 msg = QObject::tr("Timeout expired while waiting for the PPP interface " 474 msg = QObject::tr("Timeout expired while waiting for the PPP interface "
475 "to come up!"); 475 "to come up!");
476 else { 476 else {
477 msg = QObject::tr("<p>The pppd daemon died unexpectedly!</p>"); 477 msg = QObject::tr("<p>The pppd daemon died unexpectedly!</p>");
478 Modem::modem->pppdExitStatus(); 478 Modem::modem->pppdExitStatus();
479 if (Modem::modem->lastStatus != 99) {// more recent pppds only 479 if (Modem::modem->lastStatus != 99) {// more recent pppds only
480 msg += QObject::tr("<p>Exit status: %1").arg(Modem::modem->lastStatus); 480 msg += QObject::tr("<p>Exit status: %1").arg(Modem::modem->lastStatus);
481 msg += QObject::tr("</p><p>See 'man pppd' for an explanation of the error " 481 msg += QObject::tr("</p><p>See 'man pppd' for an explanation of the error "
482 "codes or take a look at the kppp FAQ on " 482 "codes or take a look at the kppp FAQ on "
483 " <a href=http://devel-home.kde.org/~kppp/index.html>" 483 " <a href=http://devel-home.kde.org/~kppp/index.html>"
484 "http://devel-home.kde.org/~kppp/index.html</a></p>"); 484 "http://devel-home.kde.org/~kppp/index.html</a></p>");
485 } 485 }
486 } 486 }
487 487
488 // if(QMessageBox::warning(0, msg, QObject::tr("Error"), QObject::tr("&OK"), QObject::tr("&Details...")) == QMessageBox::No) 488 // if(QMessageBox::warning(0, msg, QObject::tr("Error"), QObject::tr("&OK"), QObject::tr("&Details...")) == QMessageBox::No)
489 // // PPPL_ShowLog(); 489 // // PPPL_ShowLog();
490// } else { /* reconnect on disconnect */ 490// } else { /* reconnect on disconnect */
491 if (false){ 491 if (false){
492 qDebug( "Trying to reconnect... " ); 492 qDebug( "Trying to reconnect... " );
493 493
494 if(_pppdata->authMethod() == AUTH_PAP || 494 if(_pppdata->authMethod() == AUTH_PAP ||
495 _pppdata->authMethod() == AUTH_CHAP || 495 _pppdata->authMethod() == AUTH_CHAP ||
496 _pppdata->authMethod() == AUTH_PAPCHAP) 496 _pppdata->authMethod() == AUTH_PAPCHAP)
497 Modem::modem->setSecret(_pppdata->authMethod(), 497 Modem::modem->setSecret(_pppdata->authMethod(),
498 encodeWord(_pppdata->storedUsername()), 498 encodeWord(_pppdata->storedUsername()),
499 encodeWord(_pppdata->password())); 499 encodeWord(_pppdata->password()));
500 500
501 con_win->hide(); 501 con_win->hide();
502 con_win->stopClock(); 502 con_win->stopClock();
503 //stopAccounting(); 503 //stopAccounting();
504 _pppdata->setpppdRunning(false); 504 _pppdata->setpppdRunning(false);
505 // not in a signal handler !!!KNotifyClient::beep(); 505 // not in a signal handler !!!KNotifyClient::beep();
506 emit cmdl_start(); 506 emit cmdl_start();
507 } 507 }
508 } 508 }
509 _pppdata->setpppdError(0); 509 _pppdata->setpppdError(0);
510 } 510 }
511} 511}
512 512
513// void KPPPWidget::sigChld() { 513// void KPPPWidget::sigChld() {
514// qDebug( "sigchld()" ); 514// qDebug( "sigchld()" );
515// // pid_t id = wait(0L); 515// // pid_t id = wait(0L);
516// // if(id == helperPid && helperPid != -1) { 516// // if(id == helperPid && helperPid != -1) {
517// // kdDebug(5002) << "It was the setuid child that died" << endl; 517// // kdDebug(5002) << "It was the setuid child that died" << endl;
518// // helperPid = -1; 518// // helperPid = -1;
519// QString msg = QObject::tr("kppp's helper process just died.\n" 519// QString msg = QObject::tr("kppp's helper process just died.\n"
520// "Since a further execution would be pointless, " 520// "Since a further execution would be pointless, "
521// "kppp will shut down now."); 521// "kppp will shut down now.");
522// QMessageBox::warning(0L,"error", msg); 522// QMessageBox::warning(0L,"error", msg);
523// //remove_pidfile(); 523// //remove_pidfile();
524// exit(1); 524// exit(1);
525// // } 525// // }
526// } 526// }
527 527
528 528
529void KPPPWidget::newdefaultaccount(int i) { 529void KPPPWidget::newdefaultaccount(int i) {
530 _pppdata->setDefaultAccount(connectto_c->text(i)); 530 _pppdata->setDefaultAccount(connectto_c->text(i));
531 _pppdata->save(); 531 _pppdata->save();
532 ID_Edit->setText(_pppdata->storedUsername()); 532 ID_Edit->setText(_pppdata->storedUsername());
533 PW_Edit->setText(_pppdata->storedPassword()); 533 PW_Edit->setText(_pppdata->storedPassword());
534} 534}
535 535
536 536
537 537
538 538
539void KPPPWidget::beginConnect() { 539void KPPPWidget::beginConnect() {
540 // make sure to connect to the account that is selected in the combo box 540 // make sure to connect to the account that is selected in the combo box
541 // (exeption: an account given by a command line argument) 541 // (exeption: an account given by a command line argument)
542 // if(!m_bCmdlAccount) { 542 // if(!m_bCmdlAccount) {
543// _pppdata->setAccount(connectto_c->currentText()); 543// _pppdata->setAccount(connectto_c->currentText());
544// _pppdata->setPassword(PW_Edit->text()); 544// _pppdata->setPassword(PW_Edit->text());
545// } else { 545// } else {
546 _pppdata->setPassword(_pppdata->storedPassword()); 546 _pppdata->setPassword(_pppdata->storedPassword());
547// } 547// }
548 548
549 QFileInfo info(pppdPath()); 549 QFileInfo info(pppdPath());
550 550
551 if(!info.exists()){ 551 if(!info.exists()){
552 QMessageBox::warning(this, "error", QObject::tr("Cannot find the PPP daemon!\n" 552 QMessageBox::warning(this, "error", QObject::tr("Cannot find the PPP daemon!\n"
553 "Make sure that pppd is installed and " 553 "Make sure that pppd is installed and "
554 "that you have entered the correct path.")); 554 "that you have entered the correct path."));
555 return; 555 return;
556 } 556 }
557#if 0 557#if 0
558 if(!info.isExecutable()){ 558 if(!info.isExecutable()){
559 559
560 QString string; 560 QString string;
561 string = QObject::tr("kppp cannot execute:\n %1\n" 561 string = QObject::tr("kppp cannot execute:\n %1\n"
562 "Please make sure that you have given kppp " 562 "Please make sure that you have given kppp "
563 "setuid permission and that " 563 "setuid permission and that "
564 "pppd is executable.").arg(_pppdata->pppdPath()); 564 "pppd is executable.").arg(_pppdata->pppdPath());
565 KMessageBox::error(this, string); 565 KMessageBox::error(this, string);
566 return; 566 return;
567 567
568 } 568 }
569#endif 569#endif
570 570
571 QFileInfo info2(_pppdata->modemDevice()); 571 QFileInfo info2(_pppdata->modemDevice());
572 572
573 if(!info2.exists()){ 573 if(!info2.exists()){
574 QString string; 574 QString string;
575 string = QObject::tr("kppp can not find:\n %1\nPlease make sure you have setup " 575 string = QObject::tr("kppp can not find:\n %1\nPlease make sure you have setup "
576 "your modem device properly " 576 "your modem device properly "
577 "and/or adjust the location of the modem device on " 577 "and/or adjust the location of the modem device on "
578 "the modem tab of " 578 "the modem tab of "
579 "the setup dialog.").arg(_pppdata->modemDevice()); 579 "the setup dialog.").arg(_pppdata->modemDevice());
580 QMessageBox::warning(this, "error", string); 580 QMessageBox::warning(this, "error", string);
581 return; 581 return;
582 } 582 }
583 583
584 // if this is a PAP or CHAP account, ensure that username is 584 // if this is a PAP or CHAP account, ensure that username is
585 // supplied 585 // supplied
586 if(_pppdata->authMethod() == AUTH_PAP || 586 if(_pppdata->authMethod() == AUTH_PAP ||
587 _pppdata->authMethod() == AUTH_CHAP || 587 _pppdata->authMethod() == AUTH_CHAP ||
588 _pppdata->authMethod() == AUTH_PAPCHAP ) { 588 _pppdata->authMethod() == AUTH_PAPCHAP ) {
589 if(ID_Edit->text().isEmpty()) { 589 if(ID_Edit->text().isEmpty()) {
590 QMessageBox::warning(this,"error", 590 QMessageBox::warning(this,"error",
591 QObject::tr("You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!")); 591 QObject::tr("You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!"));
592 return; 592 return;
593 } else { 593 } else {
594 if(!Modem::modem->setSecret(_pppdata->authMethod(), 594 if(!Modem::modem->setSecret(_pppdata->authMethod(),
595 encodeWord(_pppdata->storedUsername()), 595 encodeWord(_pppdata->storedUsername()),
596 encodeWord(_pppdata->password()))) { 596 encodeWord(_pppdata->password()))) {
597 QString s; 597 QString s;
598 s = QObject::tr("Cannot create PAP/CHAP authentication\n" 598 s = QObject::tr("Cannot create PAP/CHAP authentication\n"
599 "file \"%1\"").arg(PAP_AUTH_FILE); 599 "file \"%1\"").arg(PAP_AUTH_FILE);
600 QMessageBox::warning(this, "error", s); 600 QMessageBox::warning(this, "error", s);
601 return; 601 return;
602 } 602 }
603 } 603 }
604 } 604 }
605 605
606 if (_pppdata->phonenumber().isEmpty()) { 606 if (_pppdata->phonenumber().isEmpty()) {
607 QString s = QObject::tr("You must specify a telephone number!"); 607 QString s = QObject::tr("You must specify a telephone number!");
608 QMessageBox::warning(this, "error", s); 608 QMessageBox::warning(this, "error", s);
609 return; 609 return;
610 } 610 }
611 611
612 this->hide(); 612 this->hide();
613 613
614 QString tit = QObject::tr("Connecting to: %1").arg(_pppdata->accname()); 614 QString tit = QObject::tr("Connecting to: %1").arg(_pppdata->accname());
615// con->setCaption(tit); 615// con->setCaption(tit);
616 616
617// con->show(); 617// con->show();
618 618
619 619
620 emit begin_connect(); 620 emit begin_connect();
621} 621}
622 622
623 623
624void KPPPWidget::disconnect() { 624void KPPPWidget::disconnect() {
625 if (!_pppdata->command_before_disconnect().isEmpty()) { 625 if (!_pppdata->command_before_disconnect().isEmpty()) {
626 con_win->hide(); 626 con_win->hide();
627 con->show(); 627 con->show();
628 con->setCaption(QObject::tr("Disconnecting...")); 628 con->setCaption(QObject::tr("Disconnecting..."));
629 con->setMsg(QObject::tr("Executing command before disconnection.")); 629 con->setMsg(QObject::tr("Executing command before disconnection."));
630 630
631 qApp->processEvents(); 631 qApp->processEvents();
632 QApplication::flushX(); 632 QApplication::flushX();
633// pid_t id = 633// pid_t id =
634 execute_command(_pppdata->command_before_disconnect()); 634 execute_command(_pppdata->command_before_disconnect());
635// int i, status; 635// int i, status;
636 636
637// do { 637// do {
638// kapp->processEvents(); 638// kapp->processEvents();
639// i = waitpid(id, &status, WNOHANG); 639// i = waitpid(id, &status, WNOHANG);
640// usleep(500000); 640// usleep(500000);
641// } while (i == 0 && errno == 0); 641// } while (i == 0 && errno == 0);
642 642
643 con->hide(); 643 con->hide();
644 } 644 }
645 645
646 qApp->processEvents(); 646 qApp->processEvents();
647 647
648// statdlg->stop_stats(); 648// statdlg->stop_stats();
649 Modem::modem->killPPPDaemon(); 649 Modem::modem->killPPPDaemon();
650 650
651 QApplication::flushX(); 651 QApplication::flushX();
652 execute_command(_pppdata->command_on_disconnect()); 652 execute_command(_pppdata->command_on_disconnect());
653 653
654 Modem::modem->removeSecret(AUTH_PAP); 654 Modem::modem->removeSecret(AUTH_PAP);
655 Modem::modem->removeSecret(AUTH_CHAP); 655 Modem::modem->removeSecret(AUTH_CHAP);
656 656
657 removedns(); 657 removedns();
658 Modem::modem->unlockdevice(); 658 Modem::modem->unlockdevice();
659 659
660 con_win->stopClock(); 660 con_win->stopClock();
661// p_kppp->stopAccounting(); 661// p_kppp->stopAccounting();
662 con_win->hide(); 662 con_win->hide();
663 663
664// DockWidget::dock_widget->stop_stats(); 664// DockWidget::dock_widget->stop_stats();
665// DockWidget::dock_widget->hide(); 665// DockWidget::dock_widget->hide();
666 666
667// if(m_bQuitOnDisconnect) 667// if(m_bQuitOnDisconnect)
668// kapp->exit(0); 668// kapp->exit(0);
669// else { 669// else {
670 this->quit_b->setFocus(); 670 this->quit_b->setFocus();
671 this->show(); 671 this->show();
672// } 672// }
673} 673}
674 674
675 675
676// void KPPPWidget::helpbutton() { 676// void KPPPWidget::helpbutton() {
677// kapp->invokeHelp(); 677// kapp->invokeHelp();
678// } 678// }
679 679
680 680
681void KPPPWidget::quitbutton() { 681void KPPPWidget::quitbutton() {
682 if(_pppdata->pppdRunning()) { 682 if(_pppdata->pppdRunning()) {
683 int ok = QMessageBox::warning(this, 683 int ok = QMessageBox::warning(this,
684 QObject::tr("Exiting kPPP will close your PPP Session."), 684 QObject::tr("Exiting kPPP will close your PPP Session."),
685 QObject::tr("Quit kPPP?")); 685 QObject::tr("Quit kPPP?"));
686 if(ok == QMessageBox::Yes) { 686 if(ok == QMessageBox::Yes) {
687 Modem::modem->killPPPDaemon(); 687 Modem::modem->killPPPDaemon();
688 QApplication::flushX(); 688 QApplication::flushX();
689 execute_command(_pppdata->command_on_disconnect()); 689 execute_command(_pppdata->command_on_disconnect());
690 removedns(); 690 removedns();
691 Modem::modem->unlockdevice(); 691 Modem::modem->unlockdevice();
692 } 692 }
693 } else { 693 } else {
694 if (!_pppdata->accname().isEmpty() && !_pppdata->storePassword()) 694 if (!_pppdata->accname().isEmpty() && !_pppdata->storePassword())
695 _pppdata->setStoredPassword(""); 695 _pppdata->setStoredPassword("");
696 } 696 }
697 _pppdata->save(); 697 _pppdata->save();
698 qApp->quit(); 698 qApp->quit();
699} 699}
700 700
701 701
702// void KPPPWidget::rulesetLoadError() { 702// void KPPPWidget::rulesetLoadError() {
703// QMessageBox::warning(this,"error", ruleset_load_errmsg); 703// QMessageBox::warning(this,"error", ruleset_load_errmsg);
704// } 704// }
705 705
706 706
707// void KPPPWidget::startAccounting() { 707// void KPPPWidget::startAccounting() {
708// // volume accounting 708// // volume accounting
709// stats->totalbytes = 0; 709// stats->totalbytes = 0;
710 710
711// kdDebug() << "AcctEnabled: " << _pppdata->AcctEnabled() << endl; 711// kdDebug() << "AcctEnabled: " << _pppdata->AcctEnabled() << endl;
712 712
713// // load the ruleset 713// // load the ruleset
714// if(!_pppdata->AcctEnabled()) 714// if(!_pppdata->AcctEnabled())
715// return; 715// return;
716 716
717// QString d = AccountingBase::getAccountingFile(_pppdata->accountingFile()); 717// QString d = AccountingBase::getAccountingFile(_pppdata->accountingFile());
718// // if(::access(d.data(), X_OK) != 0) 718// // if(::access(d.data(), X_OK) != 0)
719// acct = new Accounting(this, stats); 719// acct = new Accounting(this, stats);
720// // else 720// // else
721// // acct = new ExecutableAccounting(this); 721// // acct = new ExecutableAccounting(this);
722 722
723// // connect to the accounting object 723// // connect to the accounting object
724// connect(acct, SIGNAL(changed(QString, QString)), 724// connect(acct, SIGNAL(changed(QString,QString)),
725 // con_win, SLOT(slotAccounting(QString, QString))); 725 // con_win, SLOT(slotAccounting(QString,QString)));
726 726
727// // if(!acct->loadRuleSet(_pppdata->accountingFile())) { 727// // if(!acct->loadRuleSet(_pppdata->accountingFile())) {
728// // QString s= QObject::tr("Can not load the accounting " 728// // QString s= QObject::tr("Can not load the accounting "
729 // // "ruleset \"%1\"!").arg(_pppdata->accountingFile()); 729 // // "ruleset \"%1\"!").arg(_pppdata->accountingFile());
730 730
731// // starting the messagebox with a timer will prevent us 731// // starting the messagebox with a timer will prevent us
732// // from blocking the calling function ConnectWidget::timerEvent 732// // from blocking the calling function ConnectWidget::timerEvent
733// ruleset_load_errmsg = s; 733// ruleset_load_errmsg = s;
734// QTimer::singleShot(0, this, SLOT(rulesetLoadError())); 734// QTimer::singleShot(0, this, SLOT(rulesetLoadError()));
735// return; 735// return;
736// } 736// }
737// //else 737// //else
738// // acct->slotStart(); 738// // acct->slotStart();
739// } 739// }
740 740
741// void KPPPWidget::stopAccounting() { 741// void KPPPWidget::stopAccounting() {
742// // store volume accounting 742// // store volume accounting
743// // if(stats->totalbytes != 0) 743// // if(stats->totalbytes != 0)
744// // _pppdata->setTotalBytes(stats->totalbytes); 744// // _pppdata->setTotalBytes(stats->totalbytes);
745 745
746// if(!_pppdata->AcctEnabled()) 746// if(!_pppdata->AcctEnabled())
747// return; 747// return;
748 748
749// // if(acct != 0) { 749// // if(acct != 0) {
750// // acct->slotStop(); 750// // acct->slotStop();
751// // delete acct; 751// // delete acct;
752// // acct = 0; 752// // acct = 0;
753// // } 753// // }
754// } 754// }
755 755
756 756
757// void KPPPWidget::showStats() { 757// void KPPPWidget::showStats() {
758// if(statdlg) { 758// if(statdlg) {
759// statdlg->show(); 759// statdlg->show();
760// statdlg->raise(); 760// statdlg->raise();
761// } 761// }
762// } 762// }
763 763
764 764
765void KPPPWidget::usernameChanged(const QString &) { 765void KPPPWidget::usernameChanged(const QString &) {
766 // store username for later use 766 // store username for later use
767 _pppdata->setStoredUsername(ID_Edit->text()); 767 _pppdata->setStoredUsername(ID_Edit->text());
768} 768}
769 769
770 770
771void KPPPWidget::passwordChanged(const QString &) { 771void KPPPWidget::passwordChanged(const QString &) {
772 // store the password if so requested 772 // store the password if so requested
773 if(_pppdata->storePassword()) 773 if(_pppdata->storePassword())
774 _pppdata->setStoredPassword(PW_Edit->text()); 774 _pppdata->setStoredPassword(PW_Edit->text());
775 else 775 else
776 _pppdata->setStoredPassword(""); 776 _pppdata->setStoredPassword("");
777} 777}
778 778
779 779
780void KPPPWidget::setPW_Edit(const QString &pw) { 780void KPPPWidget::setPW_Edit(const QString &pw) {
781 PW_Edit->setText(pw); 781 PW_Edit->setText(pw);
782} 782}
783 783
784 784
785// void KPPPWidget::resetCosts(const QString &s) { 785// void KPPPWidget::resetCosts(const QString &s) {
786// AccountingBase::resetCosts(s); 786// AccountingBase::resetCosts(s);
787// } 787// }
788 788
789 789
790// void KPPPWidget::resetVolume(const QString &s) { 790// void KPPPWidget::resetVolume(const QString &s) {
791// AccountingBase::resetVolume(s); 791// AccountingBase::resetVolume(s);
792// } 792// }
793 793
794/** 794/**
795 * pppd's getword() function knows about escape characters. 795 * pppd's getword() function knows about escape characters.
796 * If we write the username and password to the secrets file 796 * If we write the username and password to the secrets file
797 * we'll therefore have to escape back slashes. 797 * we'll therefore have to escape back slashes.
798 */ 798 */
799QString KPPPWidget::encodeWord(const QString &s) { 799QString KPPPWidget::encodeWord(const QString &s) {
800 QString r = s; 800 QString r = s;
801 r.replace(QRegExp("\\"), "\\\\"); 801 r.replace(QRegExp("\\"), "\\\\");
802 return r; 802 return r;
803} 803}
804 804
805// void KPPPWidget::setQuitOnDisconnect (bool b) 805// void KPPPWidget::setQuitOnDisconnect (bool b)
806// { 806// {
807// m_bQuitOnDisconnect = b; 807// m_bQuitOnDisconnect = b;
808// } 808// }
809 809
810void KPPPWidget::showNews() { 810void KPPPWidget::showNews() {
811#ifdef KPPP_SHOW_NEWS 811#ifdef KPPP_SHOW_NEWS
812 /* 812 /*
813 * Introduce the QuickHelp feature to new users of this version 813 * Introduce the QuickHelp feature to new users of this version
814 */ 814 */
815 #define QUICKHELP_HINT "Hint_QuickHelp" 815 #define QUICKHELP_HINT "Hint_QuickHelp"
816 if(_pppdata->readNumConfig(GENERAL_GRP, QUICKHELP_HINT, 0) == 0) { 816 if(_pppdata->readNumConfig(GENERAL_GRP, QUICKHELP_HINT, 0) == 0) {
817 QDialog dlg(0, 0, true); 817 QDialog dlg(0, 0, true);
818 dlg.setCaption(QObject::tr("Recent Changes in KPPP")); 818 dlg.setCaption(QObject::tr("Recent Changes in KPPP"));
819 819
820 QVBoxLayout *tl = new QVBoxLayout(&dlg, 10, 10); 820 QVBoxLayout *tl = new QVBoxLayout(&dlg, 10, 10);
821 QHBoxLayout *l1 = new QHBoxLayout(10); 821 QHBoxLayout *l1 = new QHBoxLayout(10);
822 QVBoxLayout *l2 = new QVBoxLayout(10); 822 QVBoxLayout *l2 = new QVBoxLayout(10);
823 tl->addLayout(l1); 823 tl->addLayout(l1);
824 824
825 QLabel *icon = new QLabel(&dlg); 825 QLabel *icon = new QLabel(&dlg);
826 icon->setPixmap(BarIcon("exclamation")); 826 icon->setPixmap(BarIcon("exclamation"));
827 icon->setFixedSize(icon->sizeHint()); 827 icon->setFixedSize(icon->sizeHint());
828 l1->addWidget(icon); 828 l1->addWidget(icon);
829 l1->addLayout(l2); 829 l1->addLayout(l2);
830 830
831 QLabel *l = new QLabel(QObject::tr("From version 1.4.8 on, kppp has a new feature\n" 831 QLabel *l = new QLabel(QObject::tr("From version 1.4.8 on, kppp has a new feature\n"
832 "called \"Quickhelp\". It's similar to a tooltip,\n" 832 "called \"Quickhelp\". It's similar to a tooltip,\n"
833 "but you can activate it whenever you want.\n" 833 "but you can activate it whenever you want.\n"
834 "\n" 834 "\n"
835 "To activate it, simply click on a control like\n" 835 "To activate it, simply click on a control like\n"
836 "a button or a label with the right mouse button.\n" 836 "a button or a label with the right mouse button.\n"
837 "If the item supports Quickhelp, a popup menu\n" 837 "If the item supports Quickhelp, a popup menu\n"
838 "will appear leading to Quickhelp.\n" 838 "will appear leading to Quickhelp.\n"
839 "\n" 839 "\n"
840 "To test it, right-click somewhere in this text."), 840 "To test it, right-click somewhere in this text."),
841 &dlg); 841 &dlg);
842 842
843 QCheckBox *cb = new QCheckBox(QObject::tr("Don't show this hint again"), &dlg); 843 QCheckBox *cb = new QCheckBox(QObject::tr("Don't show this hint again"), &dlg);
844 cb->setFixedSize(cb->sizeHint()); 844 cb->setFixedSize(cb->sizeHint());
845 845
846 KButtonBox *bbox = new KButtonBox(&dlg); 846 KButtonBox *bbox = new KButtonBox(&dlg);
847 bbox->addStretch(1); 847 bbox->addStretch(1);
848 QPushButton *ok = bbox->addButton(QObject::tr("OK")); 848 QPushButton *ok = bbox->addButton(QObject::tr("OK"));
849 ok->setDefault(true); 849 ok->setDefault(true);
850 dlg.connect(ok, SIGNAL(clicked()), 850 dlg.connect(ok, SIGNAL(clicked()),
851 &dlg, SLOT(accept())); 851 &dlg, SLOT(accept()));
852 bbox->addStretch(1); 852 bbox->addStretch(1);
853 bbox->layout(); 853 bbox->layout();
854 854
855 l2->addWidget(l); 855 l2->addWidget(l);
856 l2->addWidget(cb); 856 l2->addWidget(cb);
857 tl->addWidget(bbox); 857 tl->addWidget(bbox);
858 858
859 QString tmp = QObject::tr("This is an example of <b>QuickHelp</b>.\n" 859 QString tmp = QObject::tr("This is an example of <b>QuickHelp</b>.\n"
860 "This window will stay open until you\n" 860 "This window will stay open until you\n"
861 "click a mouse button or a press a key.\n"); 861 "click a mouse button or a press a key.\n");
862 862
863 QWhatsThis::add(cb,tmp); 863 QWhatsThis::add(cb,tmp);
864 QWhatsThis::add(l, tmp); 864 QWhatsThis::add(l, tmp);
865 865
866 dlg.exec(); 866 dlg.exec();
867 if(cb->isChecked()) { 867 if(cb->isChecked()) {
868 _pppdata->writeConfig(GENERAL_GRP, QUICKHELP_HINT, 1); 868 _pppdata->writeConfig(GENERAL_GRP, QUICKHELP_HINT, 1);
869 _pppdata->save(); 869 _pppdata->save();
870 } 870 }
871 } 871 }
872#endif 872#endif
873} 873}
874 874
875 875
876//#include "kpppwidget.moc" 876//#include "kpppwidget.moc"
877 877
diff --git a/noncore/settings/networksettings/ppp/pppdargs.cpp b/noncore/settings/networksettings/ppp/pppdargs.cpp
index 66a4d82..d6d8d88 100644
--- a/noncore/settings/networksettings/ppp/pppdargs.cpp
+++ b/noncore/settings/networksettings/ppp/pppdargs.cpp
@@ -1,151 +1,151 @@
1/* 1/*
2 * kPPP: A pppd front end for the KDE project 2 * kPPP: A pppd front end for the KDE project
3 * 3 *
4 * $Id$ 4 * $Id$
5 * 5 *
6 * Copyright (C) 1997 Bernd Johannes Wuebben 6 * Copyright (C) 1997 Bernd Johannes Wuebben
7 * wuebben@math.cornell.edu 7 * wuebben@math.cornell.edu
8 * 8 *
9 * based on EzPPP: 9 * based on EzPPP:
10 * Copyright (C) 1997 Jay Painter 10 * Copyright (C) 1997 Jay Painter
11 * 11 *
12 * 12 *
13 * This library is free software; you can redistribute it and/or 13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Library General Public 14 * modify it under the terms of the GNU Library General Public
15 * License as published by the Free Software Foundation; either 15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version. 16 * version 2 of the License, or (at your option) any later version.
17 * 17 *
18 * This library is distributed in the hope that it will be useful, 18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of 19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Library General Public License for more details. 21 * Library General Public License for more details.
22 * 22 *
23 * You should have received a copy of the GNU Library General Public 23 * You should have received a copy of the GNU Library General Public
24 * License along with this program; if not, write to the Free 24 * License along with this program; if not, write to the Free
25 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 25 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 */ 26 */
27 27
28#include <qlayout.h> 28#include <qlayout.h>
29#include <qbuttongroup.h> 29#include <qbuttongroup.h>
30#include <qapplication.h> 30#include <qapplication.h>
31#include "pppdargs.h" 31#include "pppdargs.h"
32#include "pppdata.h" 32#include "pppdata.h"
33 33
34 34
35PPPdArguments::PPPdArguments( PPPData *pd, QWidget *parent, const char *name) 35PPPdArguments::PPPdArguments( PPPData *pd, QWidget *parent, const char *name)
36 : QDialog(parent, name, TRUE), _pppdata(pd) 36 : QDialog(parent, name, TRUE), _pppdata(pd)
37{ 37{
38 setCaption(tr("Customize pppd Arguments")); 38 setCaption(tr("Customize pppd Arguments"));
39// KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); 39// KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
40 QVBoxLayout *l = new QVBoxLayout(this, 10, 10); 40 QVBoxLayout *l = new QVBoxLayout(this, 10, 10);
41 QHBoxLayout *tl = new QHBoxLayout(10); 41 QHBoxLayout *tl = new QHBoxLayout(10);
42 l->addLayout(tl); 42 l->addLayout(tl);
43 QVBoxLayout *l1 = new QVBoxLayout(); 43 QVBoxLayout *l1 = new QVBoxLayout();
44 QVBoxLayout *l2 = new QVBoxLayout(); 44 QVBoxLayout *l2 = new QVBoxLayout();
45 tl->addLayout(l1, 1); 45 tl->addLayout(l1, 1);
46 tl->addLayout(l2, 0); 46 tl->addLayout(l2, 0);
47 47
48 QHBoxLayout *l11 = new QHBoxLayout(10); 48 QHBoxLayout *l11 = new QHBoxLayout(10);
49 l1->addLayout(l11); 49 l1->addLayout(l11);
50 50
51 argument_label = new QLabel(tr("Argument:"), this); 51 argument_label = new QLabel(tr("Argument:"), this);
52 l11->addWidget(argument_label); 52 l11->addWidget(argument_label);
53 53
54 argument = new QLineEdit(this); 54 argument = new QLineEdit(this);
55 connect(argument, SIGNAL(returnPressed()), 55 connect(argument, SIGNAL(returnPressed()),
56 SLOT(addbutton())); 56 SLOT(addbutton()));
57 l11->addWidget(argument); 57 l11->addWidget(argument);
58 connect(argument, SIGNAL(textChanged(const QString &)), 58 connect(argument, SIGNAL(textChanged(const QString&)),
59 this, SLOT(textChanged(const QString &))); 59 this, SLOT(textChanged(const QString&)));
60 60
61 arguments = new QListBox(this); 61 arguments = new QListBox(this);
62 arguments->setMinimumSize(1, fontMetrics().lineSpacing()*10); 62 arguments->setMinimumSize(1, fontMetrics().lineSpacing()*10);
63 connect(arguments, SIGNAL(highlighted(int)), 63 connect(arguments, SIGNAL(highlighted(int)),
64 this, SLOT(itemSelected(int))); 64 this, SLOT(itemSelected(int)));
65 l1->addWidget(arguments, 1); 65 l1->addWidget(arguments, 1);
66 66
67 add = new QPushButton(tr("Add"), this); 67 add = new QPushButton(tr("Add"), this);
68 connect(add, SIGNAL(clicked()), SLOT(addbutton())); 68 connect(add, SIGNAL(clicked()), SLOT(addbutton()));
69 l2->addWidget(add); 69 l2->addWidget(add);
70 l2->addStretch(1); 70 l2->addStretch(1);
71 71
72 remove = new QPushButton(tr("Remove"), this); 72 remove = new QPushButton(tr("Remove"), this);
73 connect(remove, SIGNAL(clicked()), SLOT(removebutton())); 73 connect(remove, SIGNAL(clicked()), SLOT(removebutton()));
74 l2->addWidget(remove); 74 l2->addWidget(remove);
75 75
76 defaults = new QPushButton(tr("Defaults"), this); 76 defaults = new QPushButton(tr("Defaults"), this);
77 connect(defaults, SIGNAL(clicked()), SLOT(defaultsbutton())); 77 connect(defaults, SIGNAL(clicked()), SLOT(defaultsbutton()));
78 l2->addWidget(defaults); 78 l2->addWidget(defaults);
79 79
80 l->addSpacing(5); 80 l->addSpacing(5);
81 81
82 82
83 //load info from gpppdata 83 //load info from gpppdata
84 init(); 84 init();
85 85
86 add->setEnabled(false); 86 add->setEnabled(false);
87 remove->setEnabled(false); 87 remove->setEnabled(false);
88 argument->setFocus(); 88 argument->setFocus();
89} 89}
90 90
91 91
92void PPPdArguments::addbutton() { 92void PPPdArguments::addbutton() {
93 if(!argument->text().isEmpty() && arguments->count() < MAX_PPPD_ARGUMENTS) { 93 if(!argument->text().isEmpty() && arguments->count() < MAX_PPPD_ARGUMENTS) {
94 arguments->insertItem(argument->text()); 94 arguments->insertItem(argument->text());
95 argument->setText(""); 95 argument->setText("");
96 } 96 }
97} 97}
98 98
99 99
100void PPPdArguments::removebutton() { 100void PPPdArguments::removebutton() {
101 if(arguments->currentItem() >= 0) 101 if(arguments->currentItem() >= 0)
102 arguments->removeItem(arguments->currentItem()); 102 arguments->removeItem(arguments->currentItem());
103} 103}
104 104
105 105
106void PPPdArguments::defaultsbutton() { 106void PPPdArguments::defaultsbutton() {
107 // all of this is a hack 107 // all of this is a hack
108 // save current list 108 // save current list
109 QStringList arglist(_pppdata->pppdArgument()); 109 QStringList arglist(_pppdata->pppdArgument());
110 110
111 // get defaults 111 // get defaults
112 _pppdata->setpppdArgumentDefaults(); 112 _pppdata->setpppdArgumentDefaults();
113 init(); 113 init();
114 114
115 // restore old list 115 // restore old list
116 _pppdata->setpppdArgument(arglist); 116 _pppdata->setpppdArgument(arglist);
117} 117}
118 118
119 119
120void PPPdArguments::accept() { 120void PPPdArguments::accept() {
121 QStringList arglist; 121 QStringList arglist;
122 for(uint i=0; i < arguments->count(); i++) 122 for(uint i=0; i < arguments->count(); i++)
123 arglist.append(arguments->text(i)); 123 arglist.append(arguments->text(i));
124 _pppdata->setpppdArgument(arglist); 124 _pppdata->setpppdArgument(arglist);
125 125
126 QDialog::accept(); 126 QDialog::accept();
127} 127}
128 128
129 129
130void PPPdArguments::init() { 130void PPPdArguments::init() {
131 while(arguments->count()) 131 while(arguments->count())
132 arguments->removeItem(0); 132 arguments->removeItem(0);
133 133
134 QStringList &arglist = _pppdata->pppdArgument(); 134 QStringList &arglist = _pppdata->pppdArgument();
135 for ( QStringList::Iterator it = arglist.begin(); 135 for ( QStringList::Iterator it = arglist.begin();
136 it != arglist.end(); 136 it != arglist.end();
137 ++it ) 137 ++it )
138 arguments->insertItem(*it); 138 arguments->insertItem(*it);
139} 139}
140 140
141 141
142void PPPdArguments::textChanged(const QString &s) { 142void PPPdArguments::textChanged(const QString &s) {
143 add->setEnabled(s.length() > 0); 143 add->setEnabled(s.length() > 0);
144} 144}
145 145
146 146
147void PPPdArguments::itemSelected(int idx) { 147void PPPdArguments::itemSelected(int idx) {
148 remove->setEnabled(idx != -1); 148 remove->setEnabled(idx != -1);
149} 149}
150 150
151 151
diff --git a/noncore/settings/networksettings/wlan/wlanimp2.cpp b/noncore/settings/networksettings/wlan/wlanimp2.cpp
index 92339d6..dd1db28 100644
--- a/noncore/settings/networksettings/wlan/wlanimp2.cpp
+++ b/noncore/settings/networksettings/wlan/wlanimp2.cpp
@@ -1,490 +1,490 @@
1#include "wlanimp2.h" 1#include "wlanimp2.h"
2#include "keyedit.h" 2#include "keyedit.h"
3#include "interfacesetupimp.h" 3#include "interfacesetupimp.h"
4 4
5#include "../interfaces/interface.h" 5#include "../interfaces/interface.h"
6 6
7#include <assert.h> 7#include <assert.h>
8#include <errno.h> 8#include <errno.h>
9#include <string.h> 9#include <string.h>
10 10
11#include <qapplication.h> 11#include <qapplication.h>
12#include <qfile.h> 12#include <qfile.h>
13#include <qdir.h> 13#include <qdir.h>
14#include <qdialog.h> 14#include <qdialog.h>
15#include <qtextstream.h> 15#include <qtextstream.h>
16#include <qmessagebox.h> 16#include <qmessagebox.h>
17#include <qlineedit.h> 17#include <qlineedit.h>
18#include <qlabel.h> 18#include <qlabel.h>
19#include <qspinbox.h> 19#include <qspinbox.h>
20#include <qradiobutton.h> 20#include <qradiobutton.h>
21#include <qpushbutton.h> 21#include <qpushbutton.h>
22#include <qcheckbox.h> 22#include <qcheckbox.h>
23#include <qtabwidget.h> 23#include <qtabwidget.h>
24#include <qcombobox.h> 24#include <qcombobox.h>
25#include <qlistview.h> 25#include <qlistview.h>
26#include <qvbox.h> 26#include <qvbox.h>
27#include <qprogressbar.h> 27#include <qprogressbar.h>
28 28
29#ifdef QWS 29#ifdef QWS
30 #include <qpe/resource.h> 30 #include <qpe/resource.h>
31 #include <opie2/oprocess.h> 31 #include <opie2/oprocess.h>
32 #include <opie2/onetwork.h> 32 #include <opie2/onetwork.h>
33 #include <opie2/opcap.h> 33 #include <opie2/opcap.h>
34#else 34#else
35 #define OProcess KProcess 35 #define OProcess KProcess
36 #include <kprocess.h> 36 #include <kprocess.h>
37#endif 37#endif
38 38
39#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts" 39#define WIRELESS_OPTS "/etc/pcmcia/wireless.opts"
40#define PREUP "/etc/network/if-pre-up.d/wireless-tools" 40#define PREUP "/etc/network/if-pre-up.d/wireless-tools"
41 41
42/** 42/**
43 * Constructor, read in the wireless.opts file for parsing later. 43 * Constructor, read in the wireless.opts file for parsing later.
44 */ 44 */
45WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl) : WLAN(parent, name, modal, fl), interface(i), currentProfile("*") { 45WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl) : WLAN(parent, name, modal, fl), interface(i), currentProfile("*") {
46 interfaces = new Interfaces(); 46 interfaces = new Interfaces();
47 interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i, interfaces); 47 interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i, interfaces);
48 tabWidget->insertTab(interfaceSetup, "TCP/IP"); 48 tabWidget->insertTab(interfaceSetup, "TCP/IP");
49 49
50 // Check sanity - the existance of the wireless-tools if-pre-up script 50 // Check sanity - the existance of the wireless-tools if-pre-up script
51 QFile file(QString(PREUP)); 51 QFile file(QString(PREUP));
52 if (file.exists()) { 52 if (file.exists()) {
53 qWarning(QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools")); 53 qWarning(QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools"));
54 } 54 }
55 55
56 connect( rescanButton, SIGNAL( clicked() ), this, SLOT( rescanNeighbourhood() ) ); 56 connect( rescanButton, SIGNAL( clicked() ), this, SLOT( rescanNeighbourhood() ) );
57 connect( netView, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( selectNetwork( QListViewItem* ) ) ); 57 connect( netView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( selectNetwork(QListViewItem*) ) );
58 netView->setColumnAlignment( col_chn, AlignCenter ); 58 netView->setColumnAlignment( col_chn, AlignCenter );
59 netView->setItemMargin( 3 ); 59 netView->setItemMargin( 3 );
60 netView->setAllColumnsShowFocus( true ); 60 netView->setAllColumnsShowFocus( true );
61 61
62} 62}
63 63
64WLANImp::~WLANImp() { 64WLANImp::~WLANImp() {
65//FIXME: delete interfaces; 65//FIXME: delete interfaces;
66} 66}
67 67
68/** 68/**
69 * Change the profile for both wireless settings and network settings. 69 * Change the profile for both wireless settings and network settings.
70 */ 70 */
71void WLANImp::setProfile(const QString &profile){ 71void WLANImp::setProfile(const QString &profile){
72 interfaceSetup->setProfile(profile); 72 interfaceSetup->setProfile(profile);
73 parseOpts(); 73 parseOpts();
74} 74}
75 75
76void WLANImp::parseOpts() { 76void WLANImp::parseOpts() {
77 bool error; 77 bool error;
78 QString opt; 78 QString opt;
79 79
80 if (! interfaces->isInterfaceSet()) 80 if (! interfaces->isInterfaceSet())
81 return; 81 return;
82 82
83 83
84 opt = interfaces->getInterfaceOption("wireless_essid", error); 84 opt = interfaces->getInterfaceOption("wireless_essid", error);
85 if(opt == "any" || opt == "off" || opt.isNull()){ 85 if(opt == "any" || opt == "off" || opt.isNull()){
86 essid->setEditText("any"); 86 essid->setEditText("any");
87 } else { 87 } else {
88 essid->setEditText(opt); 88 essid->setEditText(opt);
89 } 89 }
90 90
91 opt = interfaces->getInterfaceOption("wireless_mode", error).simplifyWhiteSpace(); 91 opt = interfaces->getInterfaceOption("wireless_mode", error).simplifyWhiteSpace();
92 92
93 for ( int i = 0; i < mode->count(); i++) 93 for ( int i = 0; i < mode->count(); i++)
94 if ( mode->text( i ) == opt ) mode->setCurrentItem( i ); 94 if ( mode->text( i ) == opt ) mode->setCurrentItem( i );
95 95
96 opt = interfaces->getInterfaceOption("wireless_ap", error).simplifyWhiteSpace(); 96 opt = interfaces->getInterfaceOption("wireless_ap", error).simplifyWhiteSpace();
97 if (! opt.isNull()) { 97 if (! opt.isNull()) {
98 specifyAp->setChecked(true); 98 specifyAp->setChecked(true);
99 macEdit->setText(opt); 99 macEdit->setText(opt);
100 } 100 }
101 101
102 opt = interfaces->getInterfaceOption("wireless_channel", error).simplifyWhiteSpace(); 102 opt = interfaces->getInterfaceOption("wireless_channel", error).simplifyWhiteSpace();
103 if (! opt.isNull()) { 103 if (! opt.isNull()) {
104 specifyChan->setChecked(true); 104 specifyChan->setChecked(true);
105 networkChannel->setValue(opt.toInt()); 105 networkChannel->setValue(opt.toInt());
106 } 106 }
107 107
108 opt = interfaces->getInterfaceOption("wireless_key", error).simplifyWhiteSpace(); 108 opt = interfaces->getInterfaceOption("wireless_key", error).simplifyWhiteSpace();
109 if (opt.isNull()) 109 if (opt.isNull())
110 opt = interfaces->getInterfaceOption("wireless_enc", error).simplifyWhiteSpace(); 110 opt = interfaces->getInterfaceOption("wireless_enc", error).simplifyWhiteSpace();
111 parseKeyStr(opt); 111 parseKeyStr(opt);
112} 112}
113 113
114void WLANImp::parseKeyStr(QString keystr) { 114void WLANImp::parseKeyStr(QString keystr) {
115 int loc = 0; 115 int loc = 0;
116 int index = 1; 116 int index = 1;
117 QString key; 117 QString key;
118 QStringList keys = QStringList::split(QRegExp("\\s+"), keystr); 118 QStringList keys = QStringList::split(QRegExp("\\s+"), keystr);
119 int enc = -1; // encryption state 119 int enc = -1; // encryption state
120 120
121 for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) { 121 for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) {
122 if ((*it).left(3) == "off") { 122 if ((*it).left(3) == "off") {
123 // encryption disabled 123 // encryption disabled
124 enc = 0; 124 enc = 0;
125 } else if ((*it).left(2) == "on") { 125 } else if ((*it).left(2) == "on") {
126 // encryption enabled 126 // encryption enabled
127 enc = 1; 127 enc = 1;
128 } else if ((*it).left(4) == "open") { 128 } else if ((*it).left(4) == "open") {
129 // open mode, accept non encrypted packets 129 // open mode, accept non encrypted packets
130 acceptNonEnc->setChecked(true); 130 acceptNonEnc->setChecked(true);
131 } else if ((*it).left(10) == "restricted") { 131 } else if ((*it).left(10) == "restricted") {
132 // restricted mode, only accept encrypted packets 132 // restricted mode, only accept encrypted packets
133 rejectNonEnc->setChecked(true); 133 rejectNonEnc->setChecked(true);
134 } else if ((*it).left(3) == "key") { 134 } else if ((*it).left(3) == "key") {
135 // new set of options 135 // new set of options
136 } else if ((*it).left(1) == "[") { 136 } else if ((*it).left(1) == "[") {
137 index = (*it).mid(1, 1).toInt(); 137 index = (*it).mid(1, 1).toInt();
138 // switch current key to index 138 // switch current key to index
139 switch (index) { 139 switch (index) {
140 case 1: 140 case 1:
141 keyRadio0->setChecked(true); 141 keyRadio0->setChecked(true);
142 break; 142 break;
143 case 2: 143 case 2:
144 keyRadio1->setChecked(true); 144 keyRadio1->setChecked(true);
145 break; 145 break;
146 case 3: 146 case 3:
147 keyRadio2->setChecked(true); 147 keyRadio2->setChecked(true);
148 break; 148 break;
149 case 4: 149 case 4:
150 keyRadio3->setChecked(true); 150 keyRadio3->setChecked(true);
151 break; 151 break;
152 } 152 }
153 } else { 153 } else {
154 // key 154 // key
155 key = (*it); 155 key = (*it);
156 } 156 }
157 if (! key.isNull()) { 157 if (! key.isNull()) {
158 if (enc == -1) 158 if (enc == -1)
159 enc = 1; 159 enc = 1;
160 QStringList::Iterator next = ++it; 160 QStringList::Iterator next = ++it;
161 if (it == keys.end()) { 161 if (it == keys.end()) {
162 break; 162 break;
163 } 163 }
164 if ((*(next)).left(1) == "[") { 164 if ((*(next)).left(1) == "[") {
165 // set key at index 165 // set key at index
166 index = (*(next)).mid(1, 1).toInt(); 166 index = (*(next)).mid(1, 1).toInt();
167 } else { 167 } else {
168 index = 1; 168 index = 1;
169 } 169 }
170 switch (index) { 170 switch (index) {
171 case 1: 171 case 1:
172 keyLineEdit0->setText(key); 172 keyLineEdit0->setText(key);
173 break; 173 break;
174 case 2: 174 case 2:
175 keyLineEdit1->setText(key); 175 keyLineEdit1->setText(key);
176 break; 176 break;
177 case 3: 177 case 3:
178 keyLineEdit2->setText(key); 178 keyLineEdit2->setText(key);
179 break; 179 break;
180 case 4: 180 case 4:
181 keyLineEdit3->setText(key); 181 keyLineEdit3->setText(key);
182 break; 182 break;
183 } 183 }
184 key = QString::null; 184 key = QString::null;
185 } 185 }
186 } 186 }
187 if (enc == 1) { 187 if (enc == 1) {
188 wepEnabled->setChecked(true); 188 wepEnabled->setChecked(true);
189 } else { 189 } else {
190 wepEnabled->setChecked(false); 190 wepEnabled->setChecked(false);
191 } 191 }
192} 192}
193 193
194/** 194/**
195 * Check to see if the current config is valid 195 * Check to see if the current config is valid
196 * Save interfaces 196 * Save interfaces
197 */ 197 */
198void WLANImp::accept() { 198void WLANImp::accept() {
199 if (wepEnabled->isChecked()) { 199 if (wepEnabled->isChecked()) {
200 if ((keyRadio0->isChecked() && keyLineEdit0->text().isEmpty()) || 200 if ((keyRadio0->isChecked() && keyLineEdit0->text().isEmpty()) ||
201 (keyRadio1->isChecked() && keyLineEdit1->text().isEmpty()) || 201 (keyRadio1->isChecked() && keyLineEdit1->text().isEmpty()) ||
202 (keyRadio2->isChecked() && keyLineEdit2->text().isEmpty()) || 202 (keyRadio2->isChecked() && keyLineEdit2->text().isEmpty()) ||
203 (keyRadio3->isChecked() && keyLineEdit3->text().isEmpty())) { 203 (keyRadio3->isChecked() && keyLineEdit3->text().isEmpty())) {
204 QMessageBox::information(this, "Error", "Please enter a WEP key.", QMessageBox::Ok); 204 QMessageBox::information(this, "Error", "Please enter a WEP key.", QMessageBox::Ok);
205 return; 205 return;
206 } 206 }
207 } 207 }
208 208
209 if (essid->currentText().isEmpty()) { 209 if (essid->currentText().isEmpty()) {
210 QMessageBox::information(this, "Error", "Please select/enter an ESSID.", QMessageBox::Ok); 210 QMessageBox::information(this, "Error", "Please select/enter an ESSID.", QMessageBox::Ok);
211 return; 211 return;
212 } 212 }
213 213
214 if (specifyAp->isChecked() && macEdit->text().isEmpty()) { 214 if (specifyAp->isChecked() && macEdit->text().isEmpty()) {
215 QMessageBox::information(this, "Error", "Please enter the MAC address of the Access Point.", QMessageBox::Ok); 215 QMessageBox::information(this, "Error", "Please enter the MAC address of the Access Point.", QMessageBox::Ok);
216 return; 216 return;
217 } 217 }
218 218
219 // Try to save the interfaces settings. 219 // Try to save the interfaces settings.
220 writeOpts(); 220 writeOpts();
221 221
222 // Close out the dialog 222 // Close out the dialog
223// FIXME: QDialog::accept(); 223// FIXME: QDialog::accept();
224} 224}
225 225
226void WLANImp::writeOpts() { 226void WLANImp::writeOpts() {
227 // eh can't really do anything about it other then return. :-D 227 // eh can't really do anything about it other then return. :-D
228 if(!interfaces->isInterfaceSet()){ 228 if(!interfaces->isInterfaceSet()){
229 QMessageBox::warning(0,"Inface not set","should not happen!!!"); 229 QMessageBox::warning(0,"Inface not set","should not happen!!!");
230 return; 230 return;
231 } 231 }
232 bool error = false; 232 bool error = false;
233 233
234 qDebug("setting wlan interface %s", interfaces->getInterfaceName( error ).latin1() ); 234 qDebug("setting wlan interface %s", interfaces->getInterfaceName( error ).latin1() );
235 235
236 if (error) QMessageBox::warning(0,"Inface not set","should not happen!!!"); 236 if (error) QMessageBox::warning(0,"Inface not set","should not happen!!!");
237 237
238 interfaces->setInterfaceOption(QString("wireless_mode"), mode->currentText()); 238 interfaces->setInterfaceOption(QString("wireless_mode"), mode->currentText());
239 interfaces->setInterfaceOption(QString("wireless_essid"), essid->currentText()); 239 interfaces->setInterfaceOption(QString("wireless_essid"), essid->currentText());
240 240
241 if (specifyAp->isChecked()) { 241 if (specifyAp->isChecked()) {
242 interfaces->setInterfaceOption(QString("wireless_ap"), macEdit->text()); 242 interfaces->setInterfaceOption(QString("wireless_ap"), macEdit->text());
243 } else { 243 } else {
244 interfaces->removeInterfaceOption(QString("wireless_ap")); 244 interfaces->removeInterfaceOption(QString("wireless_ap"));
245 } 245 }
246 246
247 if (specifyChan->isChecked()) { 247 if (specifyChan->isChecked()) {
248 interfaces->setInterfaceOption(QString("wireless_channel"), networkChannel->text()); 248 interfaces->setInterfaceOption(QString("wireless_channel"), networkChannel->text());
249 } else { 249 } else {
250 interfaces->removeInterfaceOption(QString("wireless_channel")); 250 interfaces->removeInterfaceOption(QString("wireless_channel"));
251 } 251 }
252 252
253 if (wepEnabled->isChecked()) { 253 if (wepEnabled->isChecked()) {
254 QStringList keyList; 254 QStringList keyList;
255 255
256 if (! keyLineEdit0->text().isNull()) { 256 if (! keyLineEdit0->text().isNull()) {
257 keyList += keyLineEdit0->text(); 257 keyList += keyLineEdit0->text();
258 keyList += "[1]"; 258 keyList += "[1]";
259 } //else 259 } //else
260 if (! keyLineEdit1->text().isNull()) { 260 if (! keyLineEdit1->text().isNull()) {
261 keyList += keyLineEdit1->text(); 261 keyList += keyLineEdit1->text();
262 keyList += "[2]"; 262 keyList += "[2]";
263 } //else 263 } //else
264 if (! keyLineEdit2->text().isNull()) { 264 if (! keyLineEdit2->text().isNull()) {
265 keyList += keyLineEdit2->text(); 265 keyList += keyLineEdit2->text();
266 keyList += "[3]"; 266 keyList += "[3]";
267 } //else 267 } //else
268 if (! keyLineEdit3->text().isNull()) { 268 if (! keyLineEdit3->text().isNull()) {
269 keyList += keyLineEdit3->text(); 269 keyList += keyLineEdit3->text();
270 keyList += "[4]"; 270 keyList += "[4]";
271 } 271 }
272 if (acceptNonEnc->isChecked()) { 272 if (acceptNonEnc->isChecked()) {
273 keyList += "open"; 273 keyList += "open";
274 } else { 274 } else {
275 keyList += "restricted"; 275 keyList += "restricted";
276 } 276 }
277 277
278 keyList += "key"; 278 keyList += "key";
279 if (keyRadio0->isChecked()) { 279 if (keyRadio0->isChecked()) {
280 keyList += "[1]"; 280 keyList += "[1]";
281 } else if (keyRadio1->isChecked()) { 281 } else if (keyRadio1->isChecked()) {
282 keyList += "[2]"; 282 keyList += "[2]";
283 } else if (keyRadio2->isChecked()) { 283 } else if (keyRadio2->isChecked()) {
284 keyList += "[3]"; 284 keyList += "[3]";
285 } else if (keyRadio3->isChecked()) { 285 } else if (keyRadio3->isChecked()) {
286 keyList += "[4]"; 286 keyList += "[4]";
287 } 287 }
288 interfaces->setInterfaceOption(QString("wireless_key"), keyList.join(QString(" "))); 288 interfaces->setInterfaceOption(QString("wireless_key"), keyList.join(QString(" ")));
289 } else { 289 } else {
290 interfaces->removeInterfaceOption(QString("wireless_key")); 290 interfaces->removeInterfaceOption(QString("wireless_key"));
291 } 291 }
292 interfaces->removeInterfaceOption(QString("wireless_enc")); 292 interfaces->removeInterfaceOption(QString("wireless_enc"));
293 293
294 if(!interfaceSetup->saveChanges()) 294 if(!interfaceSetup->saveChanges())
295 return; 295 return;
296 296
297 QDialog::accept(); 297 QDialog::accept();
298} 298}
299 299
300/* 300/*
301 * Scan for possible wireless networks around... 301 * Scan for possible wireless networks around...
302 * ... powered by Wellenreiter II technology (C) Michael 'Mickey' Lauer <mickeyl@handhelds.org> 302 * ... powered by Wellenreiter II technology (C) Michael 'Mickey' Lauer <mickeyl@handhelds.org>
303 */ 303 */
304 304
305void WLANImp::rescanNeighbourhood() 305void WLANImp::rescanNeighbourhood()
306{ 306{
307 QString name = interface->getInterfaceName(); 307 QString name = interface->getInterfaceName();
308 qDebug( "rescanNeighbourhood via '%s'", (const char*) name ); 308 qDebug( "rescanNeighbourhood via '%s'", (const char*) name );
309 309
310 OWirelessNetworkInterface* wiface = static_cast<OWirelessNetworkInterface*>( ONetwork::instance()->interface( name ) ); 310 OWirelessNetworkInterface* wiface = static_cast<OWirelessNetworkInterface*>( ONetwork::instance()->interface( name ) );
311 assert( wiface ); 311 assert( wiface );
312 312
313 // try to guess device type 313 // try to guess device type
314 QString devicetype; 314 QString devicetype;
315 QFile m( "/proc/modules" ); 315 QFile m( "/proc/modules" );
316 if ( m.open( IO_ReadOnly ) ) 316 if ( m.open( IO_ReadOnly ) )
317 { 317 {
318 QString line; 318 QString line;
319 QTextStream modules( &m ); 319 QTextStream modules( &m );
320 while( !modules.atEnd() && !devicetype ) 320 while( !modules.atEnd() && !devicetype )
321 { 321 {
322 modules >> line; 322 modules >> line;
323 if ( line.contains( "cisco" ) ) devicetype = "cisco"; 323 if ( line.contains( "cisco" ) ) devicetype = "cisco";
324 else if ( line.contains( "hostap" ) ) devicetype = "hostap"; 324 else if ( line.contains( "hostap" ) ) devicetype = "hostap";
325 else if ( line.contains( "prism" ) ) devicetype = "wlan-ng"; /* puke */ 325 else if ( line.contains( "prism" ) ) devicetype = "wlan-ng"; /* puke */
326 else if ( line.contains( "orinoco" ) ) devicetype = "orinoco"; 326 else if ( line.contains( "orinoco" ) ) devicetype = "orinoco";
327 } 327 }
328 } 328 }
329 if ( devicetype.isEmpty() ) 329 if ( devicetype.isEmpty() )
330 { 330 {
331 qWarning( "rescanNeighbourhood(): couldn't guess device type :(" ); 331 qWarning( "rescanNeighbourhood(): couldn't guess device type :(" );
332 return; 332 return;
333 } 333 }
334 else 334 else
335 { 335 {
336 qDebug( "rescanNeighbourhood(): device type seems to be '%s'", (const char*) devicetype ); 336 qDebug( "rescanNeighbourhood(): device type seems to be '%s'", (const char*) devicetype );
337 } 337 }
338 338
339 // configure interface to receive 802.11 management frames 339 // configure interface to receive 802.11 management frames
340 340
341 wiface->setUp( true ); 341 wiface->setUp( true );
342 wiface->setPromiscuousMode( true ); 342 wiface->setPromiscuousMode( true );
343 343
344 if ( devicetype == "cisco" ) wiface->setMonitoring( new OCiscoMonitoringInterface( wiface, false ) ); 344 if ( devicetype == "cisco" ) wiface->setMonitoring( new OCiscoMonitoringInterface( wiface, false ) );
345 else if ( devicetype == "hostap" ) wiface->setMonitoring( new OHostAPMonitoringInterface( wiface, false ) ); 345 else if ( devicetype == "hostap" ) wiface->setMonitoring( new OHostAPMonitoringInterface( wiface, false ) );
346 else if ( devicetype == "wlan-ng" ) wiface->setMonitoring( new OWlanNGMonitoringInterface( wiface, false ) ); 346 else if ( devicetype == "wlan-ng" ) wiface->setMonitoring( new OWlanNGMonitoringInterface( wiface, false ) );
347 else if ( devicetype == "orinoco" ) wiface->setMonitoring( new OOrinocoMonitoringInterface( wiface, false ) ); 347 else if ( devicetype == "orinoco" ) wiface->setMonitoring( new OOrinocoMonitoringInterface( wiface, false ) );
348 else 348 else
349 { 349 {
350 qDebug( "rescanNeighbourhood(): unsupported device type for monitoring :(" ); 350 qDebug( "rescanNeighbourhood(): unsupported device type for monitoring :(" );
351 return; 351 return;
352 } 352 }
353 353
354 wiface->setMode( "monitor" ); 354 wiface->setMode( "monitor" );
355 if ( wiface->mode() != "monitor" ) 355 if ( wiface->mode() != "monitor" )
356 { 356 {
357 qWarning( "rescanNeighbourhood(): Unable to bring device into monitor mode (%s).", strerror( errno ) ); 357 qWarning( "rescanNeighbourhood(): Unable to bring device into monitor mode (%s).", strerror( errno ) );
358 return; 358 return;
359 } 359 }
360 360
361 // open a packet capturer 361 // open a packet capturer
362 OPacketCapturer* cap = new OPacketCapturer(); 362 OPacketCapturer* cap = new OPacketCapturer();
363 cap->open( name ); 363 cap->open( name );
364 if ( !cap->isOpen() ) 364 if ( !cap->isOpen() )
365 { 365 {
366 qWarning( "rescanNeighbourhood(): Unable to open libpcap (%s).", strerror( errno ) ); 366 qWarning( "rescanNeighbourhood(): Unable to open libpcap (%s).", strerror( errno ) );
367 return; 367 return;
368 } 368 }
369 369
370 // display splash screen 370 // display splash screen
371 QFrame* splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize ); 371 QFrame* splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize );
372 splash->setLineWidth( 2 ); 372 splash->setLineWidth( 2 );
373 splash->setFrameStyle( QFrame::Panel | QFrame::Raised ); 373 splash->setFrameStyle( QFrame::Panel | QFrame::Raised );
374 QVBoxLayout* vbox = new QVBoxLayout( splash, 4, 4 ); 374 QVBoxLayout* vbox = new QVBoxLayout( splash, 4, 4 );
375 QLabel* lab = new QLabel( "<center><b>Scanning...</b><br>Please Wait...</center>", splash ); 375 QLabel* lab = new QLabel( "<center><b>Scanning...</b><br>Please Wait...</center>", splash );
376 QProgressBar* pb = new QProgressBar( wiface->channels(), splash ); 376 QProgressBar* pb = new QProgressBar( wiface->channels(), splash );
377 vbox->addWidget( lab ); 377 vbox->addWidget( lab );
378 vbox->addWidget( pb ); 378 vbox->addWidget( pb );
379 pb->setCenterIndicator( true ); 379 pb->setCenterIndicator( true );
380 pb->setFixedHeight( pb->sizeHint().height() ); 380 pb->setFixedHeight( pb->sizeHint().height() );
381 QWidget* widgetDesktop = qApp->desktop(); 381 QWidget* widgetDesktop = qApp->desktop();
382 int dw = widgetDesktop->width(); 382 int dw = widgetDesktop->width();
383 int dh = widgetDesktop->height(); 383 int dh = widgetDesktop->height();
384 int pw = vbox->sizeHint().width(); 384 int pw = vbox->sizeHint().width();
385 int ph = vbox->sizeHint().height(); 385 int ph = vbox->sizeHint().height();
386 splash->setGeometry((dw-pw)/2,(dh-ph)/2,pw,ph); 386 splash->setGeometry((dw-pw)/2,(dh-ph)/2,pw,ph);
387 splash->show(); 387 splash->show();
388 splash->raise(); 388 splash->raise();
389 qApp->processEvents(); 389 qApp->processEvents();
390 390
391 // set capturer to non-blocking mode 391 // set capturer to non-blocking mode
392 cap->setBlocking( false ); 392 cap->setBlocking( false );
393 393
394 for ( int i = 1; i <= wiface->channels(); ++i ) 394 for ( int i = 1; i <= wiface->channels(); ++i )
395 { 395 {
396 wiface->setChannel( i ); 396 wiface->setChannel( i );
397 pb->setProgress( i ); 397 pb->setProgress( i );
398 qApp->processEvents(); 398 qApp->processEvents();
399 qDebug( "rescanNeighbourhood(): listening on channel %d...", i ); 399 qDebug( "rescanNeighbourhood(): listening on channel %d...", i );
400 OPacket* p = cap->next( 1000 ); 400 OPacket* p = cap->next( 1000 );
401 if ( !p ) 401 if ( !p )
402 { 402 {
403 qDebug( "rescanNeighbourhood(): nothing received on channel %d", i ); 403 qDebug( "rescanNeighbourhood(): nothing received on channel %d", i );
404 } 404 }
405 else 405 else
406 { 406 {
407 qDebug( "rescanNeighbourhood(): TADAA - something came in on channel %d", i ); 407 qDebug( "rescanNeighbourhood(): TADAA - something came in on channel %d", i );
408 handlePacket( p ); 408 handlePacket( p );
409 } 409 }
410 } 410 }
411 411
412 cap->close(); 412 cap->close();
413 wiface->setMode( "managed" ); // TODO: use previous mode 413 wiface->setMode( "managed" ); // TODO: use previous mode
414 wiface->setPromiscuousMode( false ); 414 wiface->setPromiscuousMode( false );
415 415
416 splash->hide(); 416 splash->hide();
417 delete splash; 417 delete splash;
418 418
419} 419}
420 420
421void WLANImp::handlePacket( OPacket* p ) 421void WLANImp::handlePacket( OPacket* p )
422{ 422{
423 423
424 // check if we received a beacon frame 424 // check if we received a beacon frame
425 OWaveLanManagementPacket* beacon = static_cast<OWaveLanManagementPacket*>( p->child( "802.11 Management" ) ); 425 OWaveLanManagementPacket* beacon = static_cast<OWaveLanManagementPacket*>( p->child( "802.11 Management" ) );
426 if ( beacon && beacon->managementType() == "Beacon" ) 426 if ( beacon && beacon->managementType() == "Beacon" )
427 { 427 {
428 428
429 QString type; 429 QString type;
430 if ( beacon->canIBSS() ) 430 if ( beacon->canIBSS() )
431 { 431 {
432 type = "adhoc"; 432 type = "adhoc";
433 } 433 }
434 else if ( beacon->canESS() ) 434 else if ( beacon->canESS() )
435 { 435 {
436 type = "managed"; 436 type = "managed";
437 } 437 }
438 else 438 else
439 { 439 {
440 qWarning( "handlePacket(): invalid frame [possibly noise] detected!" ); 440 qWarning( "handlePacket(): invalid frame [possibly noise] detected!" );
441 return; 441 return;
442 } 442 }
443 443
444 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) ); 444 OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) );
445 QString essid = ssid ? ssid->ID() : QString("<unknown>"); 445 QString essid = ssid ? ssid->ID() : QString("<unknown>");
446 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) ); 446 OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) );
447 int channel = ds ? ds->channel() : -1; 447 int channel = ds ? ds->channel() : -1;
448 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) ); 448 OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) );
449 displayFoundNetwork( type, channel, essid, header->macAddress2() ); 449 displayFoundNetwork( type, channel, essid, header->macAddress2() );
450 } 450 }
451} 451}
452 452
453 453
454void WLANImp::displayFoundNetwork( const QString& mode, int channel, const QString& ssid, const OMacAddress& mac ) 454void WLANImp::displayFoundNetwork( const QString& mode, int channel, const QString& ssid, const OMacAddress& mac )
455{ 455{
456 456
457 qDebug( "found network: <%s>, chn %d, ssid '%s', mac '%s'", (const char*) mode, channel, 457 qDebug( "found network: <%s>, chn %d, ssid '%s', mac '%s'", (const char*) mode, channel,
458 (const char*) ssid, 458 (const char*) ssid,
459 (const char*) mac.toString() ); 459 (const char*) mac.toString() );
460 460
461 QListViewItemIterator it( netView ); 461 QListViewItemIterator it( netView );
462 while ( it.current() && it.current()->text( col_ssid ) != ssid ) ++it; 462 while ( it.current() && it.current()->text( col_ssid ) != ssid ) ++it;
463 if ( !it.current() ) // ssid didn't show up yet 463 if ( !it.current() ) // ssid didn't show up yet
464 { 464 {
465 QListViewItem* item = new QListViewItem( netView, mode.left( 1 ).upper(), ssid, QString::number( channel ), mac.toString() ); 465 QListViewItem* item = new QListViewItem( netView, mode.left( 1 ).upper(), ssid, QString::number( channel ), mac.toString() );
466 QString name; 466 QString name;
467 name.sprintf( "networksettings/%s", (const char*) mode ); 467 name.sprintf( "networksettings/%s", (const char*) mode );
468 item->setPixmap( col_mode, Resource::loadPixmap( name ) ); 468 item->setPixmap( col_mode, Resource::loadPixmap( name ) );
469 qApp->processEvents(); 469 qApp->processEvents();
470 } 470 }
471 471
472} 472}
473 473
474 474
475void WLANImp::selectNetwork( QListViewItem* item ) 475void WLANImp::selectNetwork( QListViewItem* item )
476{ 476{
477 bool ok; 477 bool ok;
478 if ( item ) 478 if ( item )
479 { 479 {
480 specifyAp->setChecked(true); 480 specifyAp->setChecked(true);
481 macEdit->setText( item->text( col_mac ) ); 481 macEdit->setText( item->text( col_mac ) );
482 specifyChan->setChecked( item->text( col_mode ) == "A" ); 482 specifyChan->setChecked( item->text( col_mode ) == "A" );
483 networkChannel->setValue( item->text( col_chn ).toInt( &ok ) ); 483 networkChannel->setValue( item->text( col_chn ).toInt( &ok ) );
484 essid->setEditText( item->text( col_ssid ) ); 484 essid->setEditText( item->text( col_ssid ) );
485 if ( item->text( col_mode ) == "A" ) 485 if ( item->text( col_mode ) == "A" )
486 mode->setCurrentItem( 3 ); 486 mode->setCurrentItem( 3 );
487 else 487 else
488 mode->setCurrentItem( 2 ); 488 mode->setCurrentItem( 2 );
489 } 489 }
490} 490}
diff --git a/noncore/settings/packagemanager/filterdlg.cpp b/noncore/settings/packagemanager/filterdlg.cpp
index 0da9d19..eeed398 100644
--- a/noncore/settings/packagemanager/filterdlg.cpp
+++ b/noncore/settings/packagemanager/filterdlg.cpp
@@ -1,179 +1,179 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2003 Dan Williams <drw@handhelds.org> 4 =. Copyright (c) 2003 Dan Williams <drw@handhelds.org>
5             .=l. 5             .=l.
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include "filterdlg.h" 30#include "filterdlg.h"
31 31
32FilterDlg::FilterDlg( QWidget *parent, OPackageManager *pm, const QString &name, 32FilterDlg::FilterDlg( QWidget *parent, OPackageManager *pm, const QString &name,
33 const QString &server, const QString &destination, 33 const QString &server, const QString &destination,
34 OPackageManager::Status status, const QString &category ) 34 OPackageManager::Status status, const QString &category )
35 : QDialog( parent, QString::null, true ) 35 : QDialog( parent, QString::null, true )
36{ 36{
37 setCaption( tr( "Filter packages" ) ); 37 setCaption( tr( "Filter packages" ) );
38 38
39 QVBoxLayout *layout = new QVBoxLayout( this ); 39 QVBoxLayout *layout = new QVBoxLayout( this );
40 QScrollView *sv = new QScrollView( this ); 40 QScrollView *sv = new QScrollView( this );
41 layout->addWidget( sv, 0, 0 ); 41 layout->addWidget( sv, 0, 0 );
42 sv->setResizePolicy( QScrollView::AutoOneFit ); 42 sv->setResizePolicy( QScrollView::AutoOneFit );
43 sv->setFrameStyle( QFrame::NoFrame ); 43 sv->setFrameStyle( QFrame::NoFrame );
44 QWidget *container = new QWidget( sv->viewport() ); 44 QWidget *container = new QWidget( sv->viewport() );
45 sv->addChild( container ); 45 sv->addChild( container );
46 layout = new QVBoxLayout( container, 4, 4 ); 46 layout = new QVBoxLayout( container, 4, 4 );
47 47
48 // Category 48 // Category
49 m_categoryCB = new QCheckBox( tr( "Category:" ), container ); 49 m_categoryCB = new QCheckBox( tr( "Category:" ), container );
50 connect( m_categoryCB, SIGNAL(toggled(bool)), this, SLOT(slotCategorySelected(bool)) ); 50 connect( m_categoryCB, SIGNAL(toggled(bool)), this, SLOT(slotCategorySelected(bool)) );
51 m_category = new QComboBox( container ); 51 m_category = new QComboBox( container );
52 m_category->insertStringList( pm->categories() ); 52 m_category->insertStringList( pm->categories() );
53 initItem( m_category, m_categoryCB, category ); 53 initItem( m_category, m_categoryCB, category );
54 layout->addWidget( m_categoryCB ); 54 layout->addWidget( m_categoryCB );
55 layout->addWidget( m_category ); 55 layout->addWidget( m_category );
56 56
57 // Package name 57 // Package name
58 m_nameCB = new QCheckBox( tr( "Names containing:" ), container ); 58 m_nameCB = new QCheckBox( tr( "Names containing:" ), container );
59 connect( m_nameCB, SIGNAL(toggled(bool)), this, SLOT(slotNameSelected(bool)) ); 59 connect( m_nameCB, SIGNAL(toggled(bool)), this, SLOT(slotNameSelected(bool)) );
60 m_name = new QLineEdit( name, container ); 60 m_name = new QLineEdit( name, container );
61 if ( !name.isNull() ) 61 if ( !name.isNull() )
62 m_nameCB->setChecked( true ); 62 m_nameCB->setChecked( true );
63 m_name->setEnabled( !name.isNull() ); 63 m_name->setEnabled( !name.isNull() );
64 layout->addWidget( m_nameCB ); 64 layout->addWidget( m_nameCB );
65 layout->addWidget( m_name ); 65 layout->addWidget( m_name );
66 66
67 // Status 67 // Status
68 m_statusCB = new QCheckBox( tr( "With the status:" ), container ); 68 m_statusCB = new QCheckBox( tr( "With the status:" ), container );
69 connect( m_statusCB, SIGNAL(toggled(bool)), this, SLOT(slotStatusSelected(bool)) ); 69 connect( m_statusCB, SIGNAL(toggled(bool)), this, SLOT(slotStatusSelected(bool)) );
70 m_status = new QComboBox( container ); 70 m_status = new QComboBox( container );
71 connect( m_status, SIGNAL(activated(const QString &)), this, SLOT(slotStatusChanged(const QString &)) ); 71 connect( m_status, SIGNAL(activated(const QString&)), this, SLOT(slotStatusChanged(const QString&)) );
72 QString currStatus; 72 QString currStatus;
73 switch ( status ) 73 switch ( status )
74 { 74 {
75 case OPackageManager::All : currStatus = tr( "All" ); 75 case OPackageManager::All : currStatus = tr( "All" );
76 break; 76 break;
77 case OPackageManager::Installed : currStatus = tr( "Installed" ); 77 case OPackageManager::Installed : currStatus = tr( "Installed" );
78 break; 78 break;
79 case OPackageManager::NotInstalled : currStatus = tr( "Not installed" ); 79 case OPackageManager::NotInstalled : currStatus = tr( "Not installed" );
80 break; 80 break;
81 case OPackageManager::Updated : currStatus = tr( "Updated" ); 81 case OPackageManager::Updated : currStatus = tr( "Updated" );
82 break; 82 break;
83 default : currStatus = QString::null; 83 default : currStatus = QString::null;
84 }; 84 };
85 m_status->insertItem( tr( "All" ) ); 85 m_status->insertItem( tr( "All" ) );
86 m_status->insertItem( tr( "Installed" ) ); 86 m_status->insertItem( tr( "Installed" ) );
87 m_status->insertItem( tr( "Not installed" ) ); 87 m_status->insertItem( tr( "Not installed" ) );
88 m_status->insertItem( tr( "Updated" ) ); 88 m_status->insertItem( tr( "Updated" ) );
89 initItem( m_status, m_statusCB, currStatus ); 89 initItem( m_status, m_statusCB, currStatus );
90 layout->addWidget( m_statusCB ); 90 layout->addWidget( m_statusCB );
91 layout->addWidget( m_status ); 91 layout->addWidget( m_status );
92 92
93 // Server 93 // Server
94 m_serverCB = new QCheckBox( tr( "Available from the following server:" ), container ); 94 m_serverCB = new QCheckBox( tr( "Available from the following server:" ), container );
95 connect( m_serverCB, SIGNAL(toggled(bool)), this, SLOT(slotServerSelected(bool)) ); 95 connect( m_serverCB, SIGNAL(toggled(bool)), this, SLOT(slotServerSelected(bool)) );
96 m_server = new QComboBox( container ); 96 m_server = new QComboBox( container );
97 m_server->insertStringList( *(pm->servers()) ); 97 m_server->insertStringList( *(pm->servers()) );
98 initItem( m_server, m_serverCB, server ); 98 initItem( m_server, m_serverCB, server );
99 layout->addWidget( m_serverCB ); 99 layout->addWidget( m_serverCB );
100 layout->addWidget( m_server ); 100 layout->addWidget( m_server );
101 101
102 // Destination 102 // Destination
103 m_destCB = new QCheckBox( tr( "Installed on device at:" ), container ); 103 m_destCB = new QCheckBox( tr( "Installed on device at:" ), container );
104 connect( m_destCB, SIGNAL(toggled(bool)), this, SLOT(slotDestSelected(bool)) ); 104 connect( m_destCB, SIGNAL(toggled(bool)), this, SLOT(slotDestSelected(bool)) );
105 m_destination = new QComboBox( container ); 105 m_destination = new QComboBox( container );
106 m_destination->insertStringList( *(pm->destinations()) ); 106 m_destination->insertStringList( *(pm->destinations()) );
107 initItem( m_destination, m_destCB, destination ); 107 initItem( m_destination, m_destCB, destination );
108 layout->addWidget( m_destCB ); 108 layout->addWidget( m_destCB );
109 layout->addWidget( m_destination ); 109 layout->addWidget( m_destination );
110 110
111 //showMaximized(); 111 //showMaximized();
112} 112}
113 113
114void FilterDlg::initItem( QComboBox *comboBox, QCheckBox *checkBox, const QString &selection ) 114void FilterDlg::initItem( QComboBox *comboBox, QCheckBox *checkBox, const QString &selection )
115{ 115{
116 if ( !selection.isNull() ) 116 if ( !selection.isNull() )
117 { 117 {
118 checkBox->setChecked( true ); 118 checkBox->setChecked( true );
119 119
120 for ( int i = 0; i < comboBox->count(); i++ ) 120 for ( int i = 0; i < comboBox->count(); i++ )
121 { 121 {
122 if ( comboBox->text( i ) == selection ) 122 if ( comboBox->text( i ) == selection )
123 { 123 {
124 comboBox->setCurrentItem( i ); 124 comboBox->setCurrentItem( i );
125 return; 125 return;
126 } 126 }
127 } 127 }
128 } 128 }
129 comboBox->setEnabled( !selection.isNull() ); 129 comboBox->setEnabled( !selection.isNull() );
130} 130}
131 131
132void FilterDlg::slotNameSelected( bool selected ) 132void FilterDlg::slotNameSelected( bool selected )
133{ 133{
134 m_name->setEnabled( selected ); 134 m_name->setEnabled( selected );
135} 135}
136 136
137void FilterDlg::slotServerSelected( bool selected ) 137void FilterDlg::slotServerSelected( bool selected )
138{ 138{
139 m_server->setEnabled( selected ); 139 m_server->setEnabled( selected );
140} 140}
141 141
142void FilterDlg::slotDestSelected( bool selected ) 142void FilterDlg::slotDestSelected( bool selected )
143{ 143{
144 m_destination->setEnabled( selected ); 144 m_destination->setEnabled( selected );
145} 145}
146 146
147void FilterDlg::slotStatusSelected( bool selected ) 147void FilterDlg::slotStatusSelected( bool selected )
148{ 148{
149 m_status->setEnabled( selected ); 149 m_status->setEnabled( selected );
150 150
151 if ( !selected && !m_destCB->isEnabled() ) 151 if ( !selected && !m_destCB->isEnabled() )
152 { 152 {
153 // If status check box has been deselected and destination option was previously deselected 153 // If status check box has been deselected and destination option was previously deselected
154 // (because status == "Not installed"), re-enable destination option 154 // (because status == "Not installed"), re-enable destination option
155 m_destCB->setEnabled( true ); 155 m_destCB->setEnabled( true );
156 m_destination->setEnabled( true ); 156 m_destination->setEnabled( true );
157 } 157 }
158 else if ( selected && m_destCB->isEnabled() && m_status->currentText() == tr( "Not installed" ) ) 158 else if ( selected && m_destCB->isEnabled() && m_status->currentText() == tr( "Not installed" ) )
159 { 159 {
160 // If status check box has been selected and status == "Not installed", disable destination option 160 // If status check box has been selected and status == "Not installed", disable destination option
161 m_destCB->setEnabled( false ); 161 m_destCB->setEnabled( false );
162 m_destCB->setChecked( false ); 162 m_destCB->setChecked( false );
163 m_destination->setEnabled( false ); 163 m_destination->setEnabled( false );
164 } 164 }
165} 165}
166 166
167void FilterDlg::slotStatusChanged( const QString &category ) 167void FilterDlg::slotStatusChanged( const QString &category )
168{ 168{
169 bool notInstalled = ( category == tr( "Not installed" ) ); 169 bool notInstalled = ( category == tr( "Not installed" ) );
170 m_destCB->setEnabled( !notInstalled ); 170 m_destCB->setEnabled( !notInstalled );
171 m_destination->setEnabled( !notInstalled ); 171 m_destination->setEnabled( !notInstalled );
172 if ( notInstalled ) 172 if ( notInstalled )
173 m_destCB->setChecked( false ); 173 m_destCB->setChecked( false );
174} 174}
175 175
176void FilterDlg::slotCategorySelected( bool selected ) 176void FilterDlg::slotCategorySelected( bool selected )
177{ 177{
178 m_category->setEnabled( selected ); 178 m_category->setEnabled( selected );
179} 179}
diff --git a/noncore/settings/packagemanager/mainwindow.cpp b/noncore/settings/packagemanager/mainwindow.cpp
index 8fd960f..b334bca 100644
--- a/noncore/settings/packagemanager/mainwindow.cpp
+++ b/noncore/settings/packagemanager/mainwindow.cpp
@@ -1,719 +1,719 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 3
4 =. Copyright (c) 2003 Dan Williams <drw@handhelds.org> 4 =. Copyright (c) 2003 Dan Williams <drw@handhelds.org>
5             .=l. 5             .=l.
6           .>+-= 6           .>+-=
7 _;:,     .>    :=|. This file is free software; you can 7 _;:,     .>    :=|. This file is free software; you can
8.> <`_,   >  .   <= redistribute it and/or modify it under 8.> <`_,   >  .   <= redistribute it and/or modify it under
9:`=1 )Y*s>-.--   : the terms of the GNU General Public 9:`=1 )Y*s>-.--   : the terms of the GNU General Public
10.="- .-=="i,     .._ License as published by the Free Software 10.="- .-=="i,     .._ License as published by the Free Software
11 - .   .-<_>     .<> Foundation; either version 2 of the License, 11 - .   .-<_>     .<> Foundation; either version 2 of the License,
12     ._= =}       : or (at your option) any later version. 12     ._= =}       : or (at your option) any later version.
13    .%`+i>       _;_. 13    .%`+i>       _;_.
14    .i_,=:_.      -<s. This file is distributed in the hope that 14    .i_,=:_.      -<s. This file is distributed in the hope that
15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 15     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
16    : ..    .:,     . . . without even the implied warranty of 16    : ..    .:,     . . . without even the implied warranty of
17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 17    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 18  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
19..}^=.=       =       ; Public License for more details. 19..}^=.=       =       ; Public License for more details.
20++=   -.     .`     .: 20++=   -.     .`     .:
21 :     =  ...= . :.=- You should have received a copy of the GNU 21 :     =  ...= . :.=- You should have received a copy of the GNU
22 -.   .:....=;==+<; General Public License along with this file; 22 -.   .:....=;==+<; General Public License along with this file;
23  -_. . .   )=.  = see the file COPYING. If not, write to the 23  -_. . .   )=.  = see the file COPYING. If not, write to the
24    --        :-=` Free Software Foundation, Inc., 24    --        :-=` Free Software Foundation, Inc.,
25 59 Temple Place - Suite 330, 25 59 Temple Place - Suite 330,
26 Boston, MA 02111-1307, USA. 26 Boston, MA 02111-1307, USA.
27 27
28*/ 28*/
29 29
30#include <qaction.h> 30#include <qaction.h>
31#include <qdir.h> 31#include <qdir.h>
32#include <qlayout.h> 32#include <qlayout.h>
33#include <qlineedit.h> 33#include <qlineedit.h>
34#include <qmenubar.h> 34#include <qmenubar.h>
35#include <qmessagebox.h> 35#include <qmessagebox.h>
36#include <qpopupmenu.h> 36#include <qpopupmenu.h>
37#include <qtimer.h> 37#include <qtimer.h>
38#include <qtoolbar.h> 38#include <qtoolbar.h>
39#include <qwhatsthis.h> 39#include <qwhatsthis.h>
40 40
41#include <qpe/qcopenvelope_qws.h> 41#include <qpe/qcopenvelope_qws.h>
42#include <qpe/qpeapplication.h> 42#include <qpe/qpeapplication.h>
43#include <qpe/resource.h> 43#include <qpe/resource.h>
44 44
45#include "mainwindow.h" 45#include "mainwindow.h"
46#include "installdlg.h" 46#include "installdlg.h"
47#include "filterdlg.h" 47#include "filterdlg.h"
48#include "promptdlg.h" 48#include "promptdlg.h"
49#include "entrydlg.h" 49#include "entrydlg.h"
50#include "packageinfodlg.h" 50#include "packageinfodlg.h"
51 51
52MainWindow::MainWindow( QWidget *parent, const char *name, WFlags /*fl*/ ) 52MainWindow::MainWindow( QWidget *parent, const char *name, WFlags /*fl*/ )
53 : QMainWindow( parent, name, WStyle_ContextHelp ) 53 : QMainWindow( parent, name, WStyle_ContextHelp )
54 , m_config( "packman" ) 54 , m_config( "packman" )
55 , m_packman( &m_config, this ) 55 , m_packman( &m_config, this )
56 , m_menuBar( this ) 56 , m_menuBar( this )
57 , m_toolBar( this ) 57 , m_toolBar( this )
58 , m_findBar( this ) 58 , m_findBar( this )
59 , m_widgetStack( this ) 59 , m_widgetStack( this )
60 , m_packageList( this ) 60 , m_packageList( this )
61 , m_statusWidget( this ) 61 , m_statusWidget( this )
62 , m_statusText( &m_statusWidget ) 62 , m_statusText( &m_statusWidget )
63 , m_statusBar( &m_statusWidget ) 63 , m_statusBar( &m_statusWidget )
64 , m_iconUpdated( Resource::loadPixmap( "packagemanager/updated" ) ) 64 , m_iconUpdated( Resource::loadPixmap( "packagemanager/updated" ) )
65 , m_iconInstalled( Resource::loadPixmap( "installed" ) ) 65 , m_iconInstalled( Resource::loadPixmap( "installed" ) )
66 , m_iconNull( m_iconUpdated.size() ) 66 , m_iconNull( m_iconUpdated.size() )
67 , m_filterName( QString::null ) 67 , m_filterName( QString::null )
68 , m_filterServer( QString::null ) 68 , m_filterServer( QString::null )
69 , m_filterDest( QString::null ) 69 , m_filterDest( QString::null )
70 , m_filterStatus( OPackageManager::NotDefined ) 70 , m_filterStatus( OPackageManager::NotDefined )
71 , m_filterCategory( QString::null ) 71 , m_filterCategory( QString::null )
72 72
73{ 73{
74// setCaption( tr( "Package Manager" ) ); 74// setCaption( tr( "Package Manager" ) );
75 75
76 m_iconNull.fill( colorGroup().base() ); 76 m_iconNull.fill( colorGroup().base() );
77 77
78 connect( &m_widgetStack, SIGNAL(aboutToShow(QWidget*)), this, SLOT(slotWidgetStackShow(QWidget*)) ); 78 connect( &m_widgetStack, SIGNAL(aboutToShow(QWidget*)), this, SLOT(slotWidgetStackShow(QWidget*)) );
79 79
80 // Initialize widget stack, package list and status widget 80 // Initialize widget stack, package list and status widget
81 initStatusWidget(); 81 initStatusWidget();
82 initPackageList(); 82 initPackageList();
83 83
84 m_widgetStack.addWidget( &m_statusWidget, 2 ); 84 m_widgetStack.addWidget( &m_statusWidget, 2 );
85 m_widgetStack.addWidget( &m_packageList, 1 ); 85 m_widgetStack.addWidget( &m_packageList, 1 );
86 setCentralWidget( &m_widgetStack ); 86 setCentralWidget( &m_widgetStack );
87 87
88 // Initialize remaining user interface items 88 // Initialize remaining user interface items
89 initUI(); 89 initUI();
90 90
91 // Initialize package information 91 // Initialize package information
92 QTimer::singleShot( 100, this, SLOT( initPackageInfo() ) ); 92 QTimer::singleShot( 100, this, SLOT( initPackageInfo() ) );
93} 93}
94 94
95void MainWindow::closeEvent( QCloseEvent *event ) 95void MainWindow::closeEvent( QCloseEvent *event )
96{ 96{
97 // Close app only if either the package or status widgets are currently active 97 // Close app only if either the package or status widgets are currently active
98 bool close = m_widgetStack.visibleWidget() == &m_packageList || 98 bool close = m_widgetStack.visibleWidget() == &m_packageList ||
99 m_widgetStack.visibleWidget() == &m_statusWidget; 99 m_widgetStack.visibleWidget() == &m_statusWidget;
100 if ( close ) 100 if ( close )
101 { 101 {
102 // TODO - write out application configuration settings 102 // TODO - write out application configuration settings
103 103
104 // Write out package manager configuration settings 104 // Write out package manager configuration settings
105 m_packman.saveSettings(); 105 m_packman.saveSettings();
106 event->accept(); 106 event->accept();
107 } 107 }
108 else 108 else
109 { 109 {
110 delete m_widgetStack.visibleWidget(); 110 delete m_widgetStack.visibleWidget();
111 m_widgetStack.raiseWidget( &m_packageList ); 111 m_widgetStack.raiseWidget( &m_packageList );
112 event->ignore(); 112 event->ignore();
113 } 113 }
114} 114}
115 115
116void MainWindow::initPackageList() 116void MainWindow::initPackageList()
117{ 117{
118 m_packageList.addColumn( tr( "Packages" ) ); 118 m_packageList.addColumn( tr( "Packages" ) );
119 QWhatsThis::add( &m_packageList, tr( "This is a listing of all packages.\n\nA blue dot next to the package name indicates that the package is currently installed.\n\nA blue dot with a star indicates that a newer version of the package is available from the server feed.\n\nClick inside the box at the left to select a package." ) ); 119 QWhatsThis::add( &m_packageList, tr( "This is a listing of all packages.\n\nA blue dot next to the package name indicates that the package is currently installed.\n\nA blue dot with a star indicates that a newer version of the package is available from the server feed.\n\nClick inside the box at the left to select a package." ) );
120 QPEApplication::setStylusOperation( m_packageList.viewport(), QPEApplication::RightOnHold ); 120 QPEApplication::setStylusOperation( m_packageList.viewport(), QPEApplication::RightOnHold );
121 connect( &m_packageList, SIGNAL(rightButtonPressed(QListViewItem *,const QPoint &,int)), 121 connect( &m_packageList, SIGNAL(rightButtonPressed(QListViewItem*,const QPoint&,int)),
122 this, SLOT(slotDisplayPackageInfo(QListViewItem *)) ); 122 this, SLOT(slotDisplayPackageInfo(QListViewItem*)) );
123} 123}
124 124
125void MainWindow::initStatusWidget() 125void MainWindow::initStatusWidget()
126{ 126{
127 QVBoxLayout *layout = new QVBoxLayout( &m_statusWidget, 4, 4 ); 127 QVBoxLayout *layout = new QVBoxLayout( &m_statusWidget, 4, 4 );
128 128
129 m_statusText.setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) ); 129 m_statusText.setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
130 layout->addWidget( &m_statusText ); 130 layout->addWidget( &m_statusText );
131 131
132 connect( &m_packman, SIGNAL(initStatus(int)), this, SLOT(slotInitStatusBar(int)) ); 132 connect( &m_packman, SIGNAL(initStatus(int)), this, SLOT(slotInitStatusBar(int)) );
133 connect( &m_packman, SIGNAL(statusText(const QString &)), this, SLOT(slotStatusText(const QString &)) ); 133 connect( &m_packman, SIGNAL(statusText(const QString&)), this, SLOT(slotStatusText(const QString&)) );
134 connect( &m_packman, SIGNAL(statusBar(int)), this, SLOT(slotStatusBar(int)) ); 134 connect( &m_packman, SIGNAL(statusBar(int)), this, SLOT(slotStatusBar(int)) );
135 135
136 layout->addWidget( &m_statusBar ); 136 layout->addWidget( &m_statusBar );
137} 137}
138 138
139void MainWindow::initUI() 139void MainWindow::initUI()
140{ 140{
141 // Build menu and tool bars 141 // Build menu and tool bars
142 setToolBarsMovable( false ); 142 setToolBarsMovable( false );
143 143
144 m_menuBar.setHorizontalStretchable( true ); 144 m_menuBar.setHorizontalStretchable( true );
145 QMenuBar *mb = new QMenuBar( &m_menuBar ); 145 QMenuBar *mb = new QMenuBar( &m_menuBar );
146 mb->setMargin( 0 ); 146 mb->setMargin( 0 );
147 147
148 // Find toolbar 148 // Find toolbar
149 addToolBar( &m_findBar, QMainWindow::Top, true ); 149 addToolBar( &m_findBar, QMainWindow::Top, true );
150 m_findBar.setHorizontalStretchable( true ); 150 m_findBar.setHorizontalStretchable( true );
151 m_findEdit = new QLineEdit( &m_findBar ); 151 m_findEdit = new QLineEdit( &m_findBar );
152 QWhatsThis::add( m_findEdit, tr( "Type the text to search for here." ) ); 152 QWhatsThis::add( m_findEdit, tr( "Type the text to search for here." ) );
153 m_findBar.setStretchableWidget( m_findEdit ); 153 m_findBar.setStretchableWidget( m_findEdit );
154 connect( m_findEdit, SIGNAL(textChanged(const QString &)), this, SLOT(slotFindChanged(const QString &)) ); 154 connect( m_findEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotFindChanged(const QString&)) );
155 155
156 // Packages menu 156 // Packages menu
157 QPopupMenu *popup = new QPopupMenu( this ); 157 QPopupMenu *popup = new QPopupMenu( this );
158 158
159 QAction *a = new QAction( tr( "Update lists" ), Resource::loadPixmap( "packagemanager/update" ), QString::null, 0, this, 0 ); 159 QAction *a = new QAction( tr( "Update lists" ), Resource::loadPixmap( "packagemanager/update" ), QString::null, 0, this, 0 );
160 a->setWhatsThis( tr( "Click here to update package lists from servers." ) ); 160 a->setWhatsThis( tr( "Click here to update package lists from servers." ) );
161 connect( a, SIGNAL(activated()), this, SLOT(slotUpdate()) ); 161 connect( a, SIGNAL(activated()), this, SLOT(slotUpdate()) );
162 a->addTo( popup ); 162 a->addTo( popup );
163 a->addTo( &m_toolBar ); 163 a->addTo( &m_toolBar );
164 164
165 QAction *actionUpgrade = new QAction( tr( "Upgrade" ), Resource::loadPixmap( "packagemanager/upgrade" ), QString::null, 0, this, 0 ); 165 QAction *actionUpgrade = new QAction( tr( "Upgrade" ), Resource::loadPixmap( "packagemanager/upgrade" ), QString::null, 0, this, 0 );
166 actionUpgrade->setWhatsThis( tr( "Click here to upgrade all installed packages if a newer version is available." ) ); 166 actionUpgrade->setWhatsThis( tr( "Click here to upgrade all installed packages if a newer version is available." ) );
167 connect( actionUpgrade, SIGNAL(activated()), this, SLOT(slotUpgrade()) ); 167 connect( actionUpgrade, SIGNAL(activated()), this, SLOT(slotUpgrade()) );
168 actionUpgrade->addTo( popup ); 168 actionUpgrade->addTo( popup );
169 actionUpgrade->addTo( &m_toolBar ); 169 actionUpgrade->addTo( &m_toolBar );
170 170
171 QPixmap iconDownload = Resource::loadPixmap( "packagemanager/download" ); 171 QPixmap iconDownload = Resource::loadPixmap( "packagemanager/download" );
172 QPixmap iconRemove = Resource::loadPixmap( "packagemanager/remove" ); 172 QPixmap iconRemove = Resource::loadPixmap( "packagemanager/remove" );
173 QAction *actionDownload = new QAction( tr( "Download" ), iconDownload, QString::null, 0, this, 0 ); 173 QAction *actionDownload = new QAction( tr( "Download" ), iconDownload, QString::null, 0, this, 0 );
174 actionDownload->setWhatsThis( tr( "Click here to download the currently selected package(s)." ) ); 174 actionDownload->setWhatsThis( tr( "Click here to download the currently selected package(s)." ) );
175 connect( actionDownload, SIGNAL(activated()), this, SLOT(slotDownload()) ); 175 connect( actionDownload, SIGNAL(activated()), this, SLOT(slotDownload()) );
176 actionDownload->addTo( popup ); 176 actionDownload->addTo( popup );
177 actionDownload->addTo( &m_toolBar ); 177 actionDownload->addTo( &m_toolBar );
178 178
179 a = new QAction( tr( "Apply changes" ), Resource::loadPixmap( "packagemanager/apply" ), QString::null, 0, this, 0 ); 179 a = new QAction( tr( "Apply changes" ), Resource::loadPixmap( "packagemanager/apply" ), QString::null, 0, this, 0 );
180 a->setWhatsThis( tr( "Click here to install, remove or upgrade currently selected package(s)." ) ); 180 a->setWhatsThis( tr( "Click here to install, remove or upgrade currently selected package(s)." ) );
181 connect( a, SIGNAL(activated()), this, SLOT(slotApply()) ); 181 connect( a, SIGNAL(activated()), this, SLOT(slotApply()) );
182 a->addTo( popup ); 182 a->addTo( popup );
183 a->addTo( &m_toolBar ); 183 a->addTo( &m_toolBar );
184 184
185 popup->insertSeparator(); 185 popup->insertSeparator();
186 186
187 a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); 187 a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 );
188 a->setWhatsThis( tr( "Click here to configure this application." ) ); 188 a->setWhatsThis( tr( "Click here to configure this application." ) );
189 connect( a, SIGNAL(activated()), this, SLOT(slotConfigure()) ); 189 connect( a, SIGNAL(activated()), this, SLOT(slotConfigure()) );
190 a->addTo( popup ); 190 a->addTo( popup );
191 mb->insertItem( tr( "Actions" ), popup ); 191 mb->insertItem( tr( "Actions" ), popup );
192 192
193 // View menu 193 // View menu
194 popup = new QPopupMenu( this ); 194 popup = new QPopupMenu( this );
195 195
196 m_actionShowNotInstalled = new QAction( tr( "Show packages not installed" ), QString::null, 0, this, 0 ); 196 m_actionShowNotInstalled = new QAction( tr( "Show packages not installed" ), QString::null, 0, this, 0 );
197 m_actionShowNotInstalled->setToggleAction( true ); 197 m_actionShowNotInstalled->setToggleAction( true );
198 m_actionShowNotInstalled->setWhatsThis( tr( "Click here to show packages available which have not been installed." ) ); 198 m_actionShowNotInstalled->setWhatsThis( tr( "Click here to show packages available which have not been installed." ) );
199 connect( m_actionShowNotInstalled, SIGNAL(activated()), this, SLOT(slotShowNotInstalled()) ); 199 connect( m_actionShowNotInstalled, SIGNAL(activated()), this, SLOT(slotShowNotInstalled()) );
200 m_actionShowNotInstalled->addTo( popup ); 200 m_actionShowNotInstalled->addTo( popup );
201 201
202 m_actionShowInstalled = new QAction( tr( "Show installed packages" ), QString::null, 0, this, 0 ); 202 m_actionShowInstalled = new QAction( tr( "Show installed packages" ), QString::null, 0, this, 0 );
203 m_actionShowInstalled->setToggleAction( true ); 203 m_actionShowInstalled->setToggleAction( true );
204 m_actionShowInstalled->setWhatsThis( tr( "Click here to show packages currently installed on this device." ) ); 204 m_actionShowInstalled->setWhatsThis( tr( "Click here to show packages currently installed on this device." ) );
205 connect( m_actionShowInstalled, SIGNAL(activated()), this, SLOT(slotShowInstalled()) ); 205 connect( m_actionShowInstalled, SIGNAL(activated()), this, SLOT(slotShowInstalled()) );
206 m_actionShowInstalled->addTo( popup ); 206 m_actionShowInstalled->addTo( popup );
207 207
208 m_actionShowUpdated = new QAction( tr( "Show updated packages" ), QString::null, 0, this, 0 ); 208 m_actionShowUpdated = new QAction( tr( "Show updated packages" ), QString::null, 0, this, 0 );
209 m_actionShowUpdated->setToggleAction( true ); 209 m_actionShowUpdated->setToggleAction( true );
210 m_actionShowUpdated->setWhatsThis( tr( "Click here to show packages currently installed on this device which have a newer version available." ) ); 210 m_actionShowUpdated->setWhatsThis( tr( "Click here to show packages currently installed on this device which have a newer version available." ) );
211 connect( m_actionShowUpdated, SIGNAL(activated()), this, SLOT(slotShowUpdated()) ); 211 connect( m_actionShowUpdated, SIGNAL(activated()), this, SLOT(slotShowUpdated()) );
212 m_actionShowUpdated->addTo( popup ); 212 m_actionShowUpdated->addTo( popup );
213 213
214 popup->insertSeparator(); 214 popup->insertSeparator();
215 215
216 m_actionFilter = new QAction( tr( "Filter" ), Resource::loadPixmap( "packagemanager/filter" ), 216 m_actionFilter = new QAction( tr( "Filter" ), Resource::loadPixmap( "packagemanager/filter" ),
217 QString::null, 0, this, 0 ); 217 QString::null, 0, this, 0 );
218 m_actionFilter->setToggleAction( true ); 218 m_actionFilter->setToggleAction( true );
219 m_actionFilter->setWhatsThis( tr( "Click here to apply current filter." ) ); 219 m_actionFilter->setWhatsThis( tr( "Click here to apply current filter." ) );
220 connect( m_actionFilter, SIGNAL(toggled(bool)), this, SLOT(slotFilter(bool)) ); 220 connect( m_actionFilter, SIGNAL(toggled(bool)), this, SLOT(slotFilter(bool)) );
221 m_actionFilter->addTo( popup ); 221 m_actionFilter->addTo( popup );
222 222
223 a = new QAction( tr( "Filter settings" ), QString::null, 0, this, 0 ); 223 a = new QAction( tr( "Filter settings" ), QString::null, 0, this, 0 );
224 a->setWhatsThis( tr( "Click here to change the package filter criteria." ) ); 224 a->setWhatsThis( tr( "Click here to change the package filter criteria." ) );
225 connect( a, SIGNAL(activated()), this, SLOT(slotFilterChange()) ); 225 connect( a, SIGNAL(activated()), this, SLOT(slotFilterChange()) );
226 a->addTo( popup ); 226 a->addTo( popup );
227 227
228 popup->insertSeparator(); 228 popup->insertSeparator();
229 229
230 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); 230 a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 );
231 a->setWhatsThis( tr( "Click here to search for text in package names." ) ); 231 a->setWhatsThis( tr( "Click here to search for text in package names." ) );
232 connect( a, SIGNAL(activated()), this, SLOT(slotFindShowToolbar()) ); 232 connect( a, SIGNAL(activated()), this, SLOT(slotFindShowToolbar()) );
233 a->addTo( popup ); 233 a->addTo( popup );
234 234
235 m_actionFindNext = new QAction( tr( "Find next" ), Resource::loadIconSet( "next" ), QString::null, 0, this, 0 ); 235 m_actionFindNext = new QAction( tr( "Find next" ), Resource::loadIconSet( "next" ), QString::null, 0, this, 0 );
236 m_actionFindNext->setEnabled( false ); 236 m_actionFindNext->setEnabled( false );
237 m_actionFindNext->setWhatsThis( tr( "Click here to find the next package name containing the text you are searching for." ) ); 237 m_actionFindNext->setWhatsThis( tr( "Click here to find the next package name containing the text you are searching for." ) );
238 connect( m_actionFindNext, SIGNAL(activated()), this, SLOT(slotFindNext()) ); 238 connect( m_actionFindNext, SIGNAL(activated()), this, SLOT(slotFindNext()) );
239 m_actionFindNext->addTo( popup ); 239 m_actionFindNext->addTo( popup );
240 m_actionFindNext->addTo( &m_findBar ); 240 m_actionFindNext->addTo( &m_findBar );
241 241
242 mb->insertItem( tr( "View" ), popup ); 242 mb->insertItem( tr( "View" ), popup );
243 243
244 // Finish find toolbar creation 244 // Finish find toolbar creation
245 a = new QAction( QString::null, Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); 245 a = new QAction( QString::null, Resource::loadPixmap( "close" ), QString::null, 0, this, 0 );
246 a->setWhatsThis( tr( "Click here to hide the find toolbar." ) ); 246 a->setWhatsThis( tr( "Click here to hide the find toolbar." ) );
247 connect( a, SIGNAL(activated()), this, SLOT(slotFindHideToolbar()) ); 247 connect( a, SIGNAL(activated()), this, SLOT(slotFindHideToolbar()) );
248 a->addTo( &m_findBar ); 248 a->addTo( &m_findBar );
249 m_findBar.hide(); 249 m_findBar.hide();
250} 250}
251 251
252void MainWindow::loadPackageList( OPackageList *packages, bool clearList ) 252void MainWindow::loadPackageList( OPackageList *packages, bool clearList )
253{ 253{
254 if ( clearList ) 254 if ( clearList )
255 m_packageList.clear(); 255 m_packageList.clear();
256 256
257 if ( packages ) 257 if ( packages )
258 { 258 {
259 for ( OPackageListIterator packageIt( *packages ); packageIt.current(); ++packageIt ) 259 for ( OPackageListIterator packageIt( *packages ); packageIt.current(); ++packageIt )
260 { 260 {
261 OPackage *package = packageIt.current(); 261 OPackage *package = packageIt.current();
262 QCheckListItem *item = new QCheckListItem( &m_packageList, package->name(), 262 QCheckListItem *item = new QCheckListItem( &m_packageList, package->name(),
263 QCheckListItem::CheckBox ); 263 QCheckListItem::CheckBox );
264 m_packageList.insertItem( item ); 264 m_packageList.insertItem( item );
265 265
266 // If a different version of package is available, show update available icon 266 // If a different version of package is available, show update available icon
267 // Otherwise, show installed icon 267 // Otherwise, show installed icon
268 if ( !package->versionInstalled().isNull() ) 268 if ( !package->versionInstalled().isNull() )
269 { 269 {
270 if ( m_packman.compareVersions( package->version(), package->versionInstalled() ) == 1 ) 270 if ( m_packman.compareVersions( package->version(), package->versionInstalled() ) == 1 )
271 item->setPixmap( 0, m_iconUpdated ); 271 item->setPixmap( 0, m_iconUpdated );
272 else 272 else
273 item->setPixmap( 0, m_iconInstalled ); 273 item->setPixmap( 0, m_iconInstalled );
274 } 274 }
275 else 275 else
276 item->setPixmap( 0, m_iconNull ); 276 item->setPixmap( 0, m_iconNull );
277 } 277 }
278 } 278 }
279} 279}
280 280
281void MainWindow::searchForPackage( const QString &text ) 281void MainWindow::searchForPackage( const QString &text )
282{ 282{
283 if ( !text.isEmpty() ) 283 if ( !text.isEmpty() )
284 { 284 {
285 // look through package list for text startng at current position 285 // look through package list for text startng at current position
286 QCheckListItem *start = static_cast<QCheckListItem *>(m_packageList.currentItem()); 286 QCheckListItem *start = static_cast<QCheckListItem *>(m_packageList.currentItem());
287 if ( start == 0 ) 287 if ( start == 0 )
288 start = static_cast<QCheckListItem *>(m_packageList.firstChild()); 288 start = static_cast<QCheckListItem *>(m_packageList.firstChild());
289 289
290// for ( QCheckListItem *item = static_cast<QCheckListItem *>(start->nextSibling()); item != 0 ; 290// for ( QCheckListItem *item = static_cast<QCheckListItem *>(start->nextSibling()); item != 0 ;
291 for ( QCheckListItem *item = static_cast<QCheckListItem *>(start); item != 0 ; 291 for ( QCheckListItem *item = static_cast<QCheckListItem *>(start); item != 0 ;
292 item = static_cast<QCheckListItem *>(item->nextSibling()) ) 292 item = static_cast<QCheckListItem *>(item->nextSibling()) )
293 { 293 {
294 if ( item->text().lower().find( text ) != -1 ) 294 if ( item->text().lower().find( text ) != -1 )
295 { 295 {
296 m_packageList.ensureItemVisible( item ); 296 m_packageList.ensureItemVisible( item );
297 m_packageList.setCurrentItem( item ); 297 m_packageList.setCurrentItem( item );
298 break; 298 break;
299 } 299 }
300 } 300 }
301 } 301 }
302} 302}
303 303
304void MainWindow::initPackageInfo() 304void MainWindow::initPackageInfo()
305{ 305{
306 m_widgetStack.raiseWidget( &m_statusWidget ); 306 m_widgetStack.raiseWidget( &m_statusWidget );
307 307
308 // Load package list 308 // Load package list
309 m_packman.loadAvailablePackages(); 309 m_packman.loadAvailablePackages();
310 m_packman.loadInstalledPackages(); 310 m_packman.loadInstalledPackages();
311 311
312 OPackageList *packageList = m_packman.packages(); 312 OPackageList *packageList = m_packman.packages();
313 if ( packageList ) 313 if ( packageList )
314 { 314 {
315 loadPackageList( packageList, true ); 315 loadPackageList( packageList, true );
316 delete packageList; 316 delete packageList;
317 } 317 }
318 318
319 m_widgetStack.raiseWidget( &m_packageList ); 319 m_widgetStack.raiseWidget( &m_packageList );
320} 320}
321 321
322void MainWindow::slotWidgetStackShow( QWidget *widget ) 322void MainWindow::slotWidgetStackShow( QWidget *widget )
323{ 323{
324 if ( widget == &m_packageList ) 324 if ( widget == &m_packageList )
325 { 325 {
326 setCaption( tr( "Package Manager" ) ); 326 setCaption( tr( "Package Manager" ) );
327 327
328 m_menuBar.show(); 328 m_menuBar.show();
329 m_toolBar.show(); 329 m_toolBar.show();
330 } 330 }
331 else 331 else
332 { 332 {
333 m_menuBar.hide(); 333 m_menuBar.hide();
334 m_toolBar.hide(); 334 m_toolBar.hide();
335 } 335 }
336} 336}
337 337
338void MainWindow::slotInitStatusBar( int numSteps ) 338void MainWindow::slotInitStatusBar( int numSteps )
339{ 339{
340 m_statusBar.setTotalSteps( numSteps ); 340 m_statusBar.setTotalSteps( numSteps );
341} 341}
342 342
343void MainWindow::slotStatusText( const QString &status ) 343void MainWindow::slotStatusText( const QString &status )
344{ 344{
345 m_statusText.setText( status ); 345 m_statusText.setText( status );
346} 346}
347 347
348void MainWindow::slotStatusBar( int currStep ) 348void MainWindow::slotStatusBar( int currStep )
349{ 349{
350 m_statusBar.setProgress( currStep ); 350 m_statusBar.setProgress( currStep );
351} 351}
352 352
353void MainWindow::slotUpdate() 353void MainWindow::slotUpdate()
354{ 354{
355 // Create package manager output widget 355 // Create package manager output widget
356 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Update package information" ), false, 356 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Update package information" ), false,
357 OPackage::Update ); 357 OPackage::Update );
358 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) ); 358 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) );
359 359
360 // Display widget 360 // Display widget
361 m_widgetStack.addWidget( dlg, 3 ); 361 m_widgetStack.addWidget( dlg, 3 );
362 m_widgetStack.raiseWidget( dlg ); 362 m_widgetStack.raiseWidget( dlg );
363} 363}
364 364
365void MainWindow::slotUpgrade() 365void MainWindow::slotUpgrade()
366{ 366{
367 // Create package manager output widget 367 // Create package manager output widget
368 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Upgrade installed packages" ), false, 368 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Upgrade installed packages" ), false,
369 OPackage::Upgrade ); 369 OPackage::Upgrade );
370 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) ); 370 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) );
371 371
372 // Display widget 372 // Display widget
373 m_widgetStack.addWidget( dlg, 3 ); 373 m_widgetStack.addWidget( dlg, 3 );
374 m_widgetStack.raiseWidget( dlg ); 374 m_widgetStack.raiseWidget( dlg );
375} 375}
376 376
377void MainWindow::slotDownload() 377void MainWindow::slotDownload()
378{ 378{
379 // Retrieve list of packages selected for download (if any) 379 // Retrieve list of packages selected for download (if any)
380 QStringList *workingPackages = new QStringList(); 380 QStringList *workingPackages = new QStringList();
381 381
382 for ( QCheckListItem *item = static_cast<QCheckListItem *>(m_packageList.firstChild()); 382 for ( QCheckListItem *item = static_cast<QCheckListItem *>(m_packageList.firstChild());
383 item != 0 ; 383 item != 0 ;
384 item = static_cast<QCheckListItem *>(item->nextSibling()) ) 384 item = static_cast<QCheckListItem *>(item->nextSibling()) )
385 { 385 {
386 if ( item->isOn() ) 386 if ( item->isOn() )
387 workingPackages->append( item->text() ); 387 workingPackages->append( item->text() );
388 } 388 }
389 389
390 if ( workingPackages->isEmpty() ) 390 if ( workingPackages->isEmpty() )
391 { 391 {
392 QMessageBox::information( this, tr( "Nothing to do" ), tr( "No packages selected" ), tr( "OK" ) ); 392 QMessageBox::information( this, tr( "Nothing to do" ), tr( "No packages selected" ), tr( "OK" ) );
393 return; 393 return;
394 } 394 }
395 else 395 else
396 { 396 {
397 // Download selected packages 397 // Download selected packages
398 m_config.setGroup( "settings" ); 398 m_config.setGroup( "settings" );
399 QString workingDir = m_config.readEntry( "DownloadDir", "/tmp" ); 399 QString workingDir = m_config.readEntry( "DownloadDir", "/tmp" );
400 400
401 bool ok = false; 401 bool ok = false;
402 QString text = EntryDlg::getText( tr( "Download" ), tr( "Enter path to download package to:" ), workingDir, &ok, this ); 402 QString text = EntryDlg::getText( tr( "Download" ), tr( "Enter path to download package to:" ), workingDir, &ok, this );
403 if ( ok && !text.isEmpty() ) 403 if ( ok && !text.isEmpty() )
404 workingDir = text; // user entered something and pressed ok 404 workingDir = text; // user entered something and pressed ok
405 else 405 else
406 return; // user entered nothing or pressed cancel 406 return; // user entered nothing or pressed cancel
407 407
408 // Store download directory in config file 408 // Store download directory in config file
409 m_config.writeEntry( "DownloadDir", workingDir ); 409 m_config.writeEntry( "DownloadDir", workingDir );
410 410
411 // Get starting directory 411 // Get starting directory
412 QDir::setCurrent( workingDir ); 412 QDir::setCurrent( workingDir );
413 413
414 // Create package manager output widget 414 // Create package manager output widget
415 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Download packages" ), false, 415 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Download packages" ), false,
416 OPackage::Download, workingPackages ); 416 OPackage::Download, workingPackages );
417 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) ); 417 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) );
418 418
419 // Display widget 419 // Display widget
420 m_widgetStack.addWidget( dlg, 3 ); 420 m_widgetStack.addWidget( dlg, 3 );
421 m_widgetStack.raiseWidget( dlg ); 421 m_widgetStack.raiseWidget( dlg );
422 } 422 }
423} 423}
424 424
425void MainWindow::slotApply() 425void MainWindow::slotApply()
426{ 426{
427 QStringList *removeList = 0x0; 427 QStringList *removeList = 0x0;
428 QStringList *installList = 0x0; 428 QStringList *installList = 0x0;
429 QStringList *upgradeList = 0x0; 429 QStringList *upgradeList = 0x0;
430 430
431 for ( QCheckListItem *item = static_cast<QCheckListItem *>(m_packageList.firstChild()); 431 for ( QCheckListItem *item = static_cast<QCheckListItem *>(m_packageList.firstChild());
432 item != 0 ; 432 item != 0 ;
433 item = static_cast<QCheckListItem *>(item->nextSibling()) ) 433 item = static_cast<QCheckListItem *>(item->nextSibling()) )
434 { 434 {
435 if ( item->isOn() ) 435 if ( item->isOn() )
436 { 436 {
437 OPackage *package = m_packman.findPackage( item->text() ); 437 OPackage *package = m_packman.findPackage( item->text() );
438 if ( package ) 438 if ( package )
439 { 439 {
440 if ( !package->versionInstalled().isNull() ) 440 if ( !package->versionInstalled().isNull() )
441 { 441 {
442 if ( m_packman.compareVersions( package->version(), package->versionInstalled() ) == 1 ) 442 if ( m_packman.compareVersions( package->version(), package->versionInstalled() ) == 1 )
443 { 443 {
444 // Remove/upgrade package 444 // Remove/upgrade package
445 int answer = PromptDlg::ask( tr( "Remove or upgrade" ), 445 int answer = PromptDlg::ask( tr( "Remove or upgrade" ),
446 tr( QString( "Do you wish to remove or upgrade\n%1?" ).arg( item->text() ) ), 446 tr( QString( "Do you wish to remove or upgrade\n%1?" ).arg( item->text() ) ),
447 tr( "Remove" ), tr( "Upgrade" ), this ); 447 tr( "Remove" ), tr( "Upgrade" ), this );
448 if ( answer == 1 ) // Remove 448 if ( answer == 1 ) // Remove
449 { 449 {
450 if ( !removeList ) 450 if ( !removeList )
451 removeList = new QStringList(); 451 removeList = new QStringList();
452 removeList->append( item->text() ); 452 removeList->append( item->text() );
453 } 453 }
454 else if ( answer == 2 ) // Upgrade 454 else if ( answer == 2 ) // Upgrade
455 { 455 {
456 if ( !upgradeList ) 456 if ( !upgradeList )
457 upgradeList = new QStringList(); 457 upgradeList = new QStringList();
458 upgradeList->append( item->text() ); 458 upgradeList->append( item->text() );
459 } 459 }
460 } 460 }
461 else 461 else
462 { 462 {
463 // Remove/reinstall package 463 // Remove/reinstall package
464 int answer = PromptDlg::ask( tr( "Remove or reinstall" ), 464 int answer = PromptDlg::ask( tr( "Remove or reinstall" ),
465 tr( QString( "Do you wish to remove or reinstall\n%1?" ).arg( item->text() ) ), 465 tr( QString( "Do you wish to remove or reinstall\n%1?" ).arg( item->text() ) ),
466 tr( "Remove" ), tr( "Reinstall" ), this ); 466 tr( "Remove" ), tr( "Reinstall" ), this );
467 if ( answer == 1 ) // Remove 467 if ( answer == 1 ) // Remove
468 { 468 {
469 if ( !removeList ) 469 if ( !removeList )
470 removeList = new QStringList(); 470 removeList = new QStringList();
471 removeList->append( item->text() ); 471 removeList->append( item->text() );
472 } 472 }
473 else if ( answer == 2 ) // Reinstall 473 else if ( answer == 2 ) // Reinstall
474 { 474 {
475 if ( !installList ) 475 if ( !installList )
476 installList = new QStringList(); 476 installList = new QStringList();
477 installList->append( item->text() ); 477 installList->append( item->text() );
478 } 478 }
479 } 479 }
480 } 480 }
481 else 481 else
482 { 482 {
483 // Install package 483 // Install package
484 if ( !installList ) 484 if ( !installList )
485 installList = new QStringList(); 485 installList = new QStringList();
486 installList->append( item->text() ); 486 installList->append( item->text() );
487 } 487 }
488 } 488 }
489 } 489 }
490 } 490 }
491 491
492 // If nothing is selected, display message and exit 492 // If nothing is selected, display message and exit
493 if ( !removeList && !installList && !upgradeList ) 493 if ( !removeList && !installList && !upgradeList )
494 { 494 {
495 QMessageBox::information( this, tr( "Nothing to do" ), tr( "No packages selected" ), tr( "OK" ) ); 495 QMessageBox::information( this, tr( "Nothing to do" ), tr( "No packages selected" ), tr( "OK" ) );
496 return; 496 return;
497 } 497 }
498 498
499 // Send command only if there are packages to process 499 // Send command only if there are packages to process
500 OPackage::Command removeCmd = OPackage::NotDefined; 500 OPackage::Command removeCmd = OPackage::NotDefined;
501 if ( removeList && !removeList->isEmpty() ) 501 if ( removeList && !removeList->isEmpty() )
502 removeCmd = OPackage::Remove; 502 removeCmd = OPackage::Remove;
503 OPackage::Command installCmd = OPackage::NotDefined; 503 OPackage::Command installCmd = OPackage::NotDefined;
504 if ( installList && !installList->isEmpty() ) 504 if ( installList && !installList->isEmpty() )
505 installCmd = OPackage::Install; 505 installCmd = OPackage::Install;
506 OPackage::Command upgradeCmd = OPackage::NotDefined; 506 OPackage::Command upgradeCmd = OPackage::NotDefined;
507 if ( upgradeList && !upgradeList->isEmpty() ) 507 if ( upgradeList && !upgradeList->isEmpty() )
508 upgradeCmd = OPackage::Upgrade; 508 upgradeCmd = OPackage::Upgrade;
509 509
510 // Create package manager output widget 510 // Create package manager output widget
511 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Apply changes" ), true, 511 InstallDlg *dlg = new InstallDlg( this, &m_packman, tr( "Apply changes" ), true,
512 removeCmd, removeList, 512 removeCmd, removeList,
513 installCmd, installList, 513 installCmd, installList,
514 upgradeCmd, upgradeList ); 514 upgradeCmd, upgradeList );
515 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) ); 515 connect( dlg, SIGNAL(closeInstallDlg()), this, SLOT(slotCloseDlg()) );
516 516
517 // Display widget 517 // Display widget
518 m_widgetStack.addWidget( dlg, 3 ); 518 m_widgetStack.addWidget( dlg, 3 );
519 m_widgetStack.raiseWidget( dlg ); 519 m_widgetStack.raiseWidget( dlg );
520} 520}
521 521
522void MainWindow::slotCloseDlg() 522void MainWindow::slotCloseDlg()
523{ 523{
524 // Close install dialog 524 // Close install dialog
525 delete m_widgetStack.visibleWidget(); 525 delete m_widgetStack.visibleWidget();
526 526
527 // Reload package list 527 // Reload package list
528 initPackageInfo(); 528 initPackageInfo();
529 529
530 // Update Opie launcher links 530 // Update Opie launcher links
531 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 531 QCopEnvelope e("QPE/System", "linkChanged(QString)");
532 QString lf = QString::null; 532 QString lf = QString::null;
533 e << lf; 533 e << lf;
534} 534}
535 535
536void MainWindow::slotConfigure() 536void MainWindow::slotConfigure()
537{ 537{
538 if ( m_packman.configureDlg( false ) ) 538 if ( m_packman.configureDlg( false ) )
539 { 539 {
540 if ( PromptDlg::ask( tr( "Config updated" ), 540 if ( PromptDlg::ask( tr( "Config updated" ),
541 tr( "The configuration has been updated. Do you want to update server and package information now?" ), 541 tr( "The configuration has been updated. Do you want to update server and package information now?" ),
542 tr( "Yes" ), tr( "No" ), this ) == 1 ) 542 tr( "Yes" ), tr( "No" ), this ) == 1 )
543 { 543 {
544 // Update package list and reload package info 544 // Update package list and reload package info
545 slotUpdate(); 545 slotUpdate();
546 } 546 }
547 } 547 }
548} 548}
549 549
550void MainWindow::slotShowNotInstalled() 550void MainWindow::slotShowNotInstalled()
551{ 551{
552 OPackageList *packageList; 552 OPackageList *packageList;
553 if ( m_actionShowNotInstalled->isOn() ) 553 if ( m_actionShowNotInstalled->isOn() )
554 { 554 {
555 m_actionShowInstalled->setOn( false ); 555 m_actionShowInstalled->setOn( false );
556 m_actionShowUpdated->setOn( false ); 556 m_actionShowUpdated->setOn( false );
557 m_actionFilter->setOn( false ); 557 m_actionFilter->setOn( false );
558 packageList = m_packman.filterPackages( QString::null, QString::null, QString::null, 558 packageList = m_packman.filterPackages( QString::null, QString::null, QString::null,
559 OPackageManager::NotInstalled, QString::null ); 559 OPackageManager::NotInstalled, QString::null );
560 } 560 }
561 else 561 else
562 packageList = m_packman.packages(); 562 packageList = m_packman.packages();
563 563
564 if ( packageList ) 564 if ( packageList )
565 { 565 {
566 loadPackageList( packageList, true ); 566 loadPackageList( packageList, true );
567 delete packageList; 567 delete packageList;
568 } 568 }
569} 569}
570 570
571void MainWindow::slotShowInstalled() 571void MainWindow::slotShowInstalled()
572{ 572{
573 OPackageList *packageList; 573 OPackageList *packageList;
574 if ( m_actionShowInstalled->isOn() ) 574 if ( m_actionShowInstalled->isOn() )
575 { 575 {
576 m_actionShowNotInstalled->setOn( false ); 576 m_actionShowNotInstalled->setOn( false );
577 m_actionShowUpdated->setOn( false ); 577 m_actionShowUpdated->setOn( false );
578 m_actionFilter->setOn( false ); 578 m_actionFilter->setOn( false );
579 packageList = m_packman.filterPackages( QString::null, QString::null, QString::null, 579 packageList = m_packman.filterPackages( QString::null, QString::null, QString::null,
580 OPackageManager::Installed, QString::null ); 580 OPackageManager::Installed, QString::null );
581 } 581 }
582 else 582 else
583 packageList = m_packman.packages(); 583 packageList = m_packman.packages();
584 584
585 if ( packageList ) 585 if ( packageList )
586 { 586 {
587 loadPackageList( packageList, true ); 587 loadPackageList( packageList, true );
588 delete packageList; 588 delete packageList;
589 } 589 }
590} 590}
591 591
592void MainWindow::slotShowUpdated() 592void MainWindow::slotShowUpdated()
593{ 593{
594 OPackageList *packageList; 594 OPackageList *packageList;
595 if ( m_actionShowUpdated->isOn() ) 595 if ( m_actionShowUpdated->isOn() )
596 { 596 {
597 m_actionShowInstalled->setOn( false ); 597 m_actionShowInstalled->setOn( false );
598 m_actionShowNotInstalled->setOn( false ); 598 m_actionShowNotInstalled->setOn( false );
599 m_actionFilter->setOn( false ); 599 m_actionFilter->setOn( false );
600 packageList = m_packman.filterPackages( QString::null, QString::null, QString::null, 600 packageList = m_packman.filterPackages( QString::null, QString::null, QString::null,
601 OPackageManager::Updated, QString::null ); 601 OPackageManager::Updated, QString::null );
602 } 602 }
603 else 603 else
604 packageList = m_packman.packages(); 604 packageList = m_packman.packages();
605 605
606 if ( packageList ) 606 if ( packageList )
607 { 607 {
608 loadPackageList( packageList, true ); 608 loadPackageList( packageList, true );
609 delete packageList; 609 delete packageList;
610 } 610 }
611} 611}
612 612
613void MainWindow::slotFilterChange() 613void MainWindow::slotFilterChange()
614{ 614{
615 FilterDlg dlg( this, &m_packman, m_filterName, m_filterServer, m_filterDest, m_filterStatus, 615 FilterDlg dlg( this, &m_packman, m_filterName, m_filterServer, m_filterDest, m_filterStatus,
616 m_filterCategory ); 616 m_filterCategory );
617 if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted ) 617 if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted )
618 { 618 {
619 m_filterName = dlg.name(); 619 m_filterName = dlg.name();
620 m_filterServer = dlg.server(); 620 m_filterServer = dlg.server();
621 m_filterDest = dlg.destination(); 621 m_filterDest = dlg.destination();
622 m_filterStatus = dlg.status(); 622 m_filterStatus = dlg.status();
623 m_filterCategory = dlg.category(); 623 m_filterCategory = dlg.category();
624 m_actionFilter->setOn( true ); 624 m_actionFilter->setOn( true );
625 slotFilter( true ); 625 slotFilter( true );
626 } 626 }
627 else 627 else
628 { 628 {
629 m_actionFilter->setOn( false ); 629 m_actionFilter->setOn( false );
630 slotFilter( false ); 630 slotFilter( false );
631 } 631 }
632} 632}
633 633
634void MainWindow::slotFilter( bool isOn ) 634void MainWindow::slotFilter( bool isOn )
635{ 635{
636 OPackageList *packageList; 636 OPackageList *packageList;
637 if ( isOn ) 637 if ( isOn )
638 { 638 {
639 // Turn off other filtering options 639 // Turn off other filtering options
640 m_actionShowNotInstalled->setOn( false ); 640 m_actionShowNotInstalled->setOn( false );
641 m_actionShowInstalled->setOn( false ); 641 m_actionShowInstalled->setOn( false );
642 m_actionShowUpdated->setOn( false ); 642 m_actionShowUpdated->setOn( false );
643 643
644 // If the filter settings have not been set yet, display filter dialog 644 // If the filter settings have not been set yet, display filter dialog
645 if ( m_filterName.isNull() && m_filterServer.isNull() && m_filterDest.isNull() && 645 if ( m_filterName.isNull() && m_filterServer.isNull() && m_filterDest.isNull() &&
646 m_filterStatus == OPackageManager::NotDefined && m_filterCategory.isNull() ) 646 m_filterStatus == OPackageManager::NotDefined && m_filterCategory.isNull() )
647 { 647 {
648 FilterDlg dlg( this, &m_packman, m_filterName, m_filterServer, m_filterDest, m_filterStatus, 648 FilterDlg dlg( this, &m_packman, m_filterName, m_filterServer, m_filterDest, m_filterStatus,
649 m_filterCategory ); 649 m_filterCategory );
650 if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted ) 650 if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted )
651 { 651 {
652 m_filterName = dlg.name(); 652 m_filterName = dlg.name();
653 m_filterServer = dlg.server(); 653 m_filterServer = dlg.server();
654 m_filterDest = dlg.destination(); 654 m_filterDest = dlg.destination();
655 m_filterStatus = dlg.status(); 655 m_filterStatus = dlg.status();
656 m_filterCategory = dlg.category(); 656 m_filterCategory = dlg.category();
657 m_actionFilter->setOn( true ); 657 m_actionFilter->setOn( true );
658 packageList = m_packman.filterPackages( m_filterName, m_filterServer, m_filterDest, 658 packageList = m_packman.filterPackages( m_filterName, m_filterServer, m_filterDest,
659 m_filterStatus, m_filterCategory ); 659 m_filterStatus, m_filterCategory );
660 } 660 }
661 else 661 else
662 { 662 {
663 m_actionFilter->setOn( false ); 663 m_actionFilter->setOn( false );
664 packageList = m_packman.packages(); 664 packageList = m_packman.packages();
665 } 665 }
666 } 666 }
667 else 667 else
668 { 668 {
669 m_actionFilter->setOn( true ); 669 m_actionFilter->setOn( true );
670 packageList = m_packman.filterPackages( m_filterName, m_filterServer, m_filterDest, 670 packageList = m_packman.filterPackages( m_filterName, m_filterServer, m_filterDest,
671 m_filterStatus, m_filterCategory ); 671 m_filterStatus, m_filterCategory );
672 } 672 }
673 673
674 674
675 } 675 }
676 else 676 else
677 packageList = m_packman.packages(); 677 packageList = m_packman.packages();
678 678
679 if ( packageList ) 679 if ( packageList )
680 { 680 {
681 loadPackageList( packageList, true ); 681 loadPackageList( packageList, true );
682 delete packageList; 682 delete packageList;
683 } 683 }
684} 684}
685 685
686void MainWindow::slotFindShowToolbar() 686void MainWindow::slotFindShowToolbar()
687{ 687{
688 m_findBar.show(); 688 m_findBar.show();
689 m_findEdit->setFocus(); 689 m_findEdit->setFocus();
690} 690}
691 691
692void MainWindow::slotFindHideToolbar() 692void MainWindow::slotFindHideToolbar()
693{ 693{
694 m_findBar.hide(); 694 m_findBar.hide();
695} 695}
696 696
697void MainWindow::slotFindChanged( const QString &findText ) 697void MainWindow::slotFindChanged( const QString &findText )
698{ 698{
699 699
700 m_actionFindNext->setEnabled( !findText.isEmpty() ); 700 m_actionFindNext->setEnabled( !findText.isEmpty() );
701 searchForPackage( findText ); 701 searchForPackage( findText );
702} 702}
703 703
704void MainWindow::slotFindNext() 704void MainWindow::slotFindNext()
705{ 705{
706 searchForPackage( m_findEdit->text() ); 706 searchForPackage( m_findEdit->text() );
707} 707}
708 708
709void MainWindow::slotDisplayPackageInfo( QListViewItem *packageItem ) 709void MainWindow::slotDisplayPackageInfo( QListViewItem *packageItem )
710{ 710{
711 QString packageName( ( static_cast<QCheckListItem*>( packageItem ) )->text() ); 711 QString packageName( ( static_cast<QCheckListItem*>( packageItem ) )->text() );
712 712
713 // Create package manager output widget 713 // Create package manager output widget
714 PackageInfoDlg *dlg = new PackageInfoDlg( this, &m_packman, packageName ); 714 PackageInfoDlg *dlg = new PackageInfoDlg( this, &m_packman, packageName );
715 715
716 // Display widget 716 // Display widget
717 m_widgetStack.addWidget( dlg, 3 ); 717 m_widgetStack.addWidget( dlg, 3 );
718 m_widgetStack.raiseWidget( dlg ); 718 m_widgetStack.raiseWidget( dlg );
719} 719}
diff --git a/noncore/settings/packagemanager/oipkg.cpp b/noncore/settings/packagemanager/oipkg.cpp
index 086e91b..1dc23a4 100644
--- a/noncore/settings/packagemanager/oipkg.cpp
+++ b/noncore/settings/packagemanager/oipkg.cpp
@@ -1,509 +1,509 @@
1/* 1/*
2                This file is part of the Opie Project 2                This file is part of the Opie Project
3 3
4              Copyright (c) 2003 Dan Williams <drw@handhelds.org> 4              Copyright (c) 2003 Dan Williams <drw@handhelds.org>
5 =. 5 =.
6 .=l. 6 .=l.
7           .>+-= 7           .>+-=
8 _;:,     .>    :=|. This program is free software; you can 8 _;:,     .>    :=|. This program is free software; you can
9.> <`_,   >  .   <= redistribute it and/or modify it under 9.> <`_,   >  .   <= redistribute it and/or modify it under
10:`=1 )Y*s>-.--   : the terms of the GNU Library General Public 10:`=1 )Y*s>-.--   : the terms of the GNU Library General Public
11.="- .-=="i,     .._ License as published by the Free Software 11.="- .-=="i,     .._ License as published by the Free Software
12 - .   .-<_>     .<> Foundation; either version 2 of the License, 12 - .   .-<_>     .<> Foundation; either version 2 of the License,
13     ._= =}       : or (at your option) any later version. 13     ._= =}       : or (at your option) any later version.
14    .%`+i>       _;_. 14    .%`+i>       _;_.
15    .i_,=:_.      -<s. This program is distributed in the hope that 15    .i_,=:_.      -<s. This program is distributed in the hope that
16     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 16     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
17    : ..    .:,     . . . without even the implied warranty of 17    : ..    .:,     . . . without even the implied warranty of
18    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 18    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
19  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU 19  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU
20..}^=.=       =       ; Library General Public License for more 20..}^=.=       =       ; Library General Public License for more
21++=   -.     .`     .: details. 21++=   -.     .`     .: details.
22 :     =  ...= . :.=- 22 :     =  ...= . :.=-
23 -.   .:....=;==+<; You should have received a copy of the GNU 23 -.   .:....=;==+<; You should have received a copy of the GNU
24  -_. . .   )=.  = Library General Public License along with 24  -_. . .   )=.  = Library General Public License along with
25    --        :-=` this library; see the file COPYING.LIB. 25    --        :-=` this library; see the file COPYING.LIB.
26 If not, write to the Free Software Foundation, 26 If not, write to the Free Software Foundation,
27 Inc., 59 Temple Place - Suite 330, 27 Inc., 59 Temple Place - Suite 330,
28 Boston, MA 02111-1307, USA. 28 Boston, MA 02111-1307, USA.
29 29
30*/ 30*/
31 31
32#include "oipkg.h" 32#include "oipkg.h"
33 33
34#include <stdlib.h> 34#include <stdlib.h>
35#include <string.h> 35#include <string.h>
36 36
37#include <qdir.h> 37#include <qdir.h>
38#include <qfile.h> 38#include <qfile.h>
39#include <qmessagebox.h> 39#include <qmessagebox.h>
40#include <qtextstream.h> 40#include <qtextstream.h>
41 41
42const QString IPKG_CONF = "/etc/ipkg.conf"; // Fully-qualified name of Ipkg primary configuration file 42const QString IPKG_CONF = "/etc/ipkg.conf"; // Fully-qualified name of Ipkg primary configuration file
43const QString IPKG_CONF_DIR = "/etc/ipkg"; // Directory of secondary Ipkg configuration files 43const QString IPKG_CONF_DIR = "/etc/ipkg"; // Directory of secondary Ipkg configuration files
44const QString IPKG_PKG_PATH = "/usr/lib/ipkg/lists"; // Directory containing server package lists 44const QString IPKG_PKG_PATH = "/usr/lib/ipkg/lists"; // Directory containing server package lists
45const QString IPKG_STATUS_PATH = "usr/lib/ipkg/status"; // Destination status file location 45const QString IPKG_STATUS_PATH = "usr/lib/ipkg/status"; // Destination status file location
46 46
47OIpkg *oipkg; 47OIpkg *oipkg;
48 48
49// Ipkg callback functions 49// Ipkg callback functions
50 50
51int fsignalIpkgMessage( ipkg_conf_t */*conf*/, message_level_t /*level*/, char *msg ) 51int fsignalIpkgMessage( ipkg_conf_t */*conf*/, message_level_t /*level*/, char *msg )
52{ 52{
53 oipkg->ipkgMessage( msg ); 53 oipkg->ipkgMessage( msg );
54 return 0; 54 return 0;
55} 55}
56 56
57char *fIpkgResponse( char */*question*/ ) 57char *fIpkgResponse( char */*question*/ )
58{ 58{
59 return 0x0; 59 return 0x0;
60} 60}
61 61
62int fIpkgStatus( char */*name*/, int /*status*/, char *desc, void */*userdata*/ ) 62int fIpkgStatus( char */*name*/, int /*status*/, char *desc, void */*userdata*/ )
63{ 63{
64 oipkg->ipkgStatus( desc ); 64 oipkg->ipkgStatus( desc );
65 return 0; 65 return 0;
66} 66}
67 67
68int fIpkgFiles( char */*name*/, char *desc, char */*version*/, pkg_state_status_t /*status*/, 68int fIpkgFiles( char */*name*/, char *desc, char */*version*/, pkg_state_status_t /*status*/,
69 void */*userdata*/ ) 69 void */*userdata*/ )
70{ 70{
71 oipkg->ipkgList( desc ); 71 oipkg->ipkgList( desc );
72 return 0; 72 return 0;
73} 73}
74 74
75OIpkg::OIpkg( Config *config, QObject *parent, const char *name ) 75OIpkg::OIpkg( Config *config, QObject *parent, const char *name )
76 : QObject( parent, name ) 76 : QObject( parent, name )
77 , m_config( config ) 77 , m_config( config )
78 , m_confInfo( NULL ) 78 , m_confInfo( NULL )
79 , m_ipkgExecOptions( 0 ) 79 , m_ipkgExecOptions( 0 )
80 , m_ipkgExecVerbosity( 1 ) 80 , m_ipkgExecVerbosity( 1 )
81{ 81{
82 oipkg = this; 82 oipkg = this;
83 83
84 // Initialize libipkg 84 // Initialize libipkg
85 if ( ipkg_init( &fsignalIpkgMessage, &fIpkgResponse, &m_ipkgArgs ) ) 85 if ( ipkg_init( &fsignalIpkgMessage, &fIpkgResponse, &m_ipkgArgs ) )
86 QMessageBox::critical( 0, tr( "OIpkg" ), tr( "Error initialing libipkg" ) ); 86 QMessageBox::critical( 0, tr( "OIpkg" ), tr( "Error initialing libipkg" ) );
87 87
88 // Default ipkg run-time arguments 88 // Default ipkg run-time arguments
89 m_ipkgArgs.noaction = false; 89 m_ipkgArgs.noaction = false;
90 m_ipkgArgs.force_defaults = true; 90 m_ipkgArgs.force_defaults = true;
91} 91}
92 92
93OIpkg::~OIpkg() 93OIpkg::~OIpkg()
94{ 94{
95 // Upon destruction, ensure that items in config list are deleted with list 95 // Upon destruction, ensure that items in config list are deleted with list
96 if ( m_confInfo ) 96 if ( m_confInfo )
97 m_confInfo->setAutoDelete( true ); 97 m_confInfo->setAutoDelete( true );
98 98
99 // Free up libipkg resources 99 // Free up libipkg resources
100 if ( ipkg_deinit( &m_ipkgArgs ) ) 100 if ( ipkg_deinit( &m_ipkgArgs ) )
101 QMessageBox::critical( 0, tr( "OIpkg" ), tr( "Error freeing libipkg" ) ); 101 QMessageBox::critical( 0, tr( "OIpkg" ), tr( "Error freeing libipkg" ) );
102} 102}
103 103
104OConfItemList *OIpkg::configItems() 104OConfItemList *OIpkg::configItems()
105{ 105{
106 // Retrieve all configuration items 106 // Retrieve all configuration items
107 return filterConfItems(); 107 return filterConfItems();
108} 108}
109 109
110OConfItemList *OIpkg::servers() 110OConfItemList *OIpkg::servers()
111{ 111{
112 // Retrieve only servers 112 // Retrieve only servers
113 return filterConfItems( OConfItem::Source ); 113 return filterConfItems( OConfItem::Source );
114} 114}
115 115
116OConfItemList *OIpkg::destinations() 116OConfItemList *OIpkg::destinations()
117{ 117{
118 // Retrieve only destinations 118 // Retrieve only destinations
119 return filterConfItems( OConfItem::Destination ); 119 return filterConfItems( OConfItem::Destination );
120} 120}
121 121
122OConfItemList *OIpkg::options() 122OConfItemList *OIpkg::options()
123{ 123{
124 // Retrieve only destinations 124 // Retrieve only destinations
125 return filterConfItems( OConfItem::Option ); 125 return filterConfItems( OConfItem::Option );
126} 126}
127 127
128void OIpkg::setConfigItems( OConfItemList *configList ) 128void OIpkg::setConfigItems( OConfItemList *configList )
129{ 129{
130 if ( m_confInfo ) 130 if ( m_confInfo )
131 delete m_confInfo; 131 delete m_confInfo;
132 132
133 m_confInfo = configList; 133 m_confInfo = configList;
134} 134}
135 135
136void OIpkg::saveSettings() 136void OIpkg::saveSettings()
137{ 137{
138 // Save Ipkg execution options to application configuration file 138 // Save Ipkg execution options to application configuration file
139 if ( m_config ) 139 if ( m_config )
140 { 140 {
141 m_config->setGroup( "Ipkg" ); 141 m_config->setGroup( "Ipkg" );
142 m_config->writeEntry( "ExecOptions", m_ipkgExecOptions ); 142 m_config->writeEntry( "ExecOptions", m_ipkgExecOptions );
143 m_config->writeEntry( "Verbosity", m_ipkgExecVerbosity ); 143 m_config->writeEntry( "Verbosity", m_ipkgExecVerbosity );
144 } 144 }
145} 145}
146 146
147OPackageList *OIpkg::availablePackages( const QString &server ) 147OPackageList *OIpkg::availablePackages( const QString &server )
148{ 148{
149 // Load Ipkg configuration info if not already cached 149 // Load Ipkg configuration info if not already cached
150 if ( !m_confInfo ) 150 if ( !m_confInfo )
151 loadConfiguration(); 151 loadConfiguration();
152 152
153 // Build new server list (caller is responsible for deleting) 153 // Build new server list (caller is responsible for deleting)
154 OPackageList *pl = new OPackageList; 154 OPackageList *pl = new OPackageList;
155 155
156 // Open package list file 156 // Open package list file
157 QFile f( IPKG_PKG_PATH + "/" + server ); 157 QFile f( IPKG_PKG_PATH + "/" + server );
158 if ( !f.open( IO_ReadOnly ) ) 158 if ( !f.open( IO_ReadOnly ) )
159 return NULL; 159 return NULL;
160 QTextStream t( &f ); 160 QTextStream t( &f );
161 161
162 // Process all information in package list file 162 // Process all information in package list file
163 OPackage *package = NULL; 163 OPackage *package = NULL;
164 QString line = t.readLine(); 164 QString line = t.readLine();
165 while ( !t.eof() ) 165 while ( !t.eof() )
166 { 166 {
167 // Determine key/value pair 167 // Determine key/value pair
168 int pos = line.find( ':', 0 ); 168 int pos = line.find( ':', 0 );
169 QString key; 169 QString key;
170 if ( pos > -1 ) 170 if ( pos > -1 )
171 key = line.mid( 0, pos ); 171 key = line.mid( 0, pos );
172 else 172 else
173 key = QString::null; 173 key = QString::null;
174 QString value = line.mid( pos+2, line.length()-pos ); 174 QString value = line.mid( pos+2, line.length()-pos );
175 175
176 // Allocate new package and insert into list 176 // Allocate new package and insert into list
177 if ( package == NULL && !key.isEmpty() ) 177 if ( package == NULL && !key.isEmpty() )
178 { 178 {
179 package = new OPackage( value ); 179 package = new OPackage( value );
180 package->setSource( server ); 180 package->setSource( server );
181 pl->append( package ); 181 pl->append( package );
182 } 182 }
183 183
184 // Update package data 184 // Update package data
185 if ( key == "Package" ) 185 if ( key == "Package" )
186 package->setName( value ); 186 package->setName( value );
187 else if ( key == "Version" ) 187 else if ( key == "Version" )
188 package->setVersion( value ); 188 package->setVersion( value );
189 else if ( key == "Section" ) 189 else if ( key == "Section" )
190 package->setCategory( value ); 190 package->setCategory( value );
191 //DataManager::setAvailableCategories( value ); 191 //DataManager::setAvailableCategories( value );
192 else if ( key.isEmpty() && value.isEmpty() ) 192 else if ( key.isEmpty() && value.isEmpty() )
193 package = NULL; 193 package = NULL;
194 194
195 // Skip past all description lines 195 // Skip past all description lines
196 if ( key == "Description" ) 196 if ( key == "Description" )
197 { 197 {
198 line = t.readLine(); 198 line = t.readLine();
199 while ( !line.isEmpty() && line.find( ':', 0 ) == -1 && !t.eof() ) 199 while ( !line.isEmpty() && line.find( ':', 0 ) == -1 && !t.eof() )
200 line = t.readLine(); 200 line = t.readLine();
201 } 201 }
202 else 202 else
203 line = t.readLine(); 203 line = t.readLine();
204 } 204 }
205 205
206 f.close(); 206 f.close();
207 207
208 return pl; 208 return pl;
209} 209}
210 210
211OPackageList *OIpkg::installedPackages( const QString &destName, const QString &destPath ) 211OPackageList *OIpkg::installedPackages( const QString &destName, const QString &destPath )
212{ 212{
213 // Load Ipkg configuration info if not already cached 213 // Load Ipkg configuration info if not already cached
214 if ( !m_confInfo ) 214 if ( !m_confInfo )
215 loadConfiguration(); 215 loadConfiguration();
216 216
217 // Build new server list (caller is responsible for deleting) 217 // Build new server list (caller is responsible for deleting)
218 OPackageList *pl = new OPackageList; 218 OPackageList *pl = new OPackageList;
219 219
220 // Open status file 220 // Open status file
221 QString path = destPath; 221 QString path = destPath;
222 if ( path.right( 1 ) != "/" ) 222 if ( path.right( 1 ) != "/" )
223 path.append( "/" ); 223 path.append( "/" );
224 path.append( IPKG_STATUS_PATH ); 224 path.append( IPKG_STATUS_PATH );
225 225
226 QFile f( path ); 226 QFile f( path );
227 if ( !f.open( IO_ReadOnly ) ) 227 if ( !f.open( IO_ReadOnly ) )
228 return NULL; 228 return NULL;
229 QTextStream t( &f ); 229 QTextStream t( &f );
230 230
231 // Process all information in status file 231 // Process all information in status file
232 bool newPackage = false; 232 bool newPackage = false;
233 QString line = t.readLine(); 233 QString line = t.readLine();
234 QString name; 234 QString name;
235 QString version; 235 QString version;
236 QString status; 236 QString status;
237 237
238 while ( !t.eof() ) 238 while ( !t.eof() )
239 { 239 {
240 // Determine key/value pair 240 // Determine key/value pair
241 int pos = line.find( ':', 0 ); 241 int pos = line.find( ':', 0 );
242 QString key; 242 QString key;
243 if ( pos > -1 ) 243 if ( pos > -1 )
244 key = line.mid( 0, pos ); 244 key = line.mid( 0, pos );
245 else 245 else
246 key = QString::null; 246 key = QString::null;
247 QString value = line.mid( pos+2, line.length()-pos ); 247 QString value = line.mid( pos+2, line.length()-pos );
248 248
249 // Allocate new package and insert into list 249 // Allocate new package and insert into list
250 if ( newPackage && !key.isEmpty() ) 250 if ( newPackage && !key.isEmpty() )
251 { 251 {
252 // Add to list only if it has a valid name and is installed 252 // Add to list only if it has a valid name and is installed
253 if ( !name.isNull() && status.contains( " installed" ) ) 253 if ( !name.isNull() && status.contains( " installed" ) )
254 { 254 {
255 pl->append( new OPackage( name, QString::null, version, QString::null, destName ) ); 255 pl->append( new OPackage( name, QString::null, version, QString::null, destName ) );
256 name = QString::null; 256 name = QString::null;
257 version = QString::null; 257 version = QString::null;
258 status = QString::null; 258 status = QString::null;
259 259
260 newPackage = false; 260 newPackage = false;
261 } 261 }
262 } 262 }
263 263
264 // Update package data 264 // Update package data
265 if ( key == "Package" ) 265 if ( key == "Package" )
266 name = value; 266 name = value;
267 else if ( key == "Version" ) 267 else if ( key == "Version" )
268 version = value; 268 version = value;
269 else if ( key == "Status" ) 269 else if ( key == "Status" )
270 status = value; 270 status = value;
271 else if ( key.isEmpty() && value.isEmpty() ) 271 else if ( key.isEmpty() && value.isEmpty() )
272 newPackage = true; 272 newPackage = true;
273 273
274 // Skip past all description lines 274 // Skip past all description lines
275 if ( key == "Description" ) 275 if ( key == "Description" )
276 { 276 {
277 line = t.readLine(); 277 line = t.readLine();
278 while ( !line.isEmpty() && line.find( ':', 0 ) == -1 && !t.eof() ) 278 while ( !line.isEmpty() && line.find( ':', 0 ) == -1 && !t.eof() )
279 line = t.readLine(); 279 line = t.readLine();
280 } 280 }
281 else 281 else
282 line = t.readLine(); 282 line = t.readLine();
283 } 283 }
284 284
285 f.close(); 285 f.close();
286 286
287 return pl; 287 return pl;
288} 288}
289 289
290bool OIpkg::executeCommand( OPackage::Command command, QStringList *parameters, const QString &destination, 290bool OIpkg::executeCommand( OPackage::Command command, QStringList *parameters, const QString &destination,
291 const QObject *receiver, const char *slotOutput, bool rawOutput ) 291 const QObject *receiver, const char *slotOutput, bool rawOutput )
292{ 292{
293 if ( command == OPackage::NotDefined ) 293 if ( command == OPackage::NotDefined )
294 return false; 294 return false;
295 295
296 // Set ipkg run-time options/arguments 296 // Set ipkg run-time options/arguments
297 m_ipkgArgs.force_depends = ( m_ipkgExecOptions & FORCE_DEPENDS ); 297 m_ipkgArgs.force_depends = ( m_ipkgExecOptions & FORCE_DEPENDS );
298 m_ipkgArgs.force_reinstall = ( m_ipkgExecOptions & FORCE_REINSTALL ); 298 m_ipkgArgs.force_reinstall = ( m_ipkgExecOptions & FORCE_REINSTALL );
299 // TODO m_ipkgArgs.force_remove = ( m_ipkgExecOptions & FORCE_REMOVE ); 299 // TODO m_ipkgArgs.force_remove = ( m_ipkgExecOptions & FORCE_REMOVE );
300 m_ipkgArgs.force_overwrite = ( m_ipkgExecOptions & FORCE_OVERWRITE ); 300 m_ipkgArgs.force_overwrite = ( m_ipkgExecOptions & FORCE_OVERWRITE );
301 m_ipkgArgs.verbosity = m_ipkgExecVerbosity; 301 m_ipkgArgs.verbosity = m_ipkgExecVerbosity;
302 if ( m_ipkgArgs.dest ) 302 if ( m_ipkgArgs.dest )
303 free( m_ipkgArgs.dest ); 303 free( m_ipkgArgs.dest );
304 if ( !destination.isNull() ) 304 if ( !destination.isNull() )
305 { 305 {
306 int len = destination.length() + 1; 306 int len = destination.length() + 1;
307 m_ipkgArgs.dest = (char *)malloc( len ); 307 m_ipkgArgs.dest = (char *)malloc( len );
308 strncpy( m_ipkgArgs.dest, destination, destination.length() ); 308 strncpy( m_ipkgArgs.dest, destination, destination.length() );
309 m_ipkgArgs.dest[ len - 1 ] = '\0'; 309 m_ipkgArgs.dest[ len - 1 ] = '\0';
310 } 310 }
311 else 311 else
312 m_ipkgArgs.dest = 0x0; 312 m_ipkgArgs.dest = 0x0;
313 313
314 // Connect output signal to widget 314 // Connect output signal to widget
315 315
316 if ( rawOutput ) 316 if ( rawOutput )
317 { 317 {
318// if ( slotOutput ) 318// if ( slotOutput )
319// connect( this, SIGNAL(signalIpkgMessage(char *)), receiver, slotOutput ); 319// connect( this, SIGNAL(signalIpkgMessage(char*)), receiver, slotOutput );
320 } 320 }
321 else 321 else
322 { 322 {
323 // TODO - connect to local slot and parse output before emitting signalIpkgMessage 323 // TODO - connect to local slot and parse output before emitting signalIpkgMessage
324 } 324 }
325 325
326 switch( command ) 326 switch( command )
327 { 327 {
328 case OPackage::Update : { 328 case OPackage::Update : {
329 connect( this, SIGNAL(signalIpkgMessage(char *)), receiver, slotOutput ); 329 connect( this, SIGNAL(signalIpkgMessage(char*)), receiver, slotOutput );
330 ipkg_lists_update( &m_ipkgArgs ); 330 ipkg_lists_update( &m_ipkgArgs );
331 }; 331 };
332 break; 332 break;
333 case OPackage::Upgrade : { 333 case OPackage::Upgrade : {
334 connect( this, SIGNAL(signalIpkgMessage(char *)), receiver, slotOutput ); 334 connect( this, SIGNAL(signalIpkgMessage(char*)), receiver, slotOutput );
335 ipkg_packages_upgrade( &m_ipkgArgs ); 335 ipkg_packages_upgrade( &m_ipkgArgs );
336 }; 336 };
337 break; 337 break;
338 case OPackage::Install : { 338 case OPackage::Install : {
339 connect( this, SIGNAL(signalIpkgMessage(char *)), receiver, slotOutput ); 339 connect( this, SIGNAL(signalIpkgMessage(char*)), receiver, slotOutput );
340 for ( QStringList::Iterator it = parameters->begin(); it != parameters->end(); ++it ) 340 for ( QStringList::Iterator it = parameters->begin(); it != parameters->end(); ++it )
341 { 341 {
342 ipkg_packages_install( &m_ipkgArgs, (*it) ); 342 ipkg_packages_install( &m_ipkgArgs, (*it) );
343 } 343 }
344 }; 344 };
345 break; 345 break;
346 case OPackage::Remove : { 346 case OPackage::Remove : {
347 connect( this, SIGNAL(signalIpkgMessage(char *)), receiver, slotOutput ); 347 connect( this, SIGNAL(signalIpkgMessage(char*)), receiver, slotOutput );
348 for ( QStringList::Iterator it = parameters->begin(); it != parameters->end(); ++it ) 348 for ( QStringList::Iterator it = parameters->begin(); it != parameters->end(); ++it )
349 { 349 {
350 ipkg_packages_remove( &m_ipkgArgs, (*it), true ); 350 ipkg_packages_remove( &m_ipkgArgs, (*it), true );
351 } 351 }
352 }; 352 };
353 break; 353 break;
354 case OPackage::Download : { 354 case OPackage::Download : {
355 connect( this, SIGNAL(signalIpkgMessage(char *)), receiver, slotOutput ); 355 connect( this, SIGNAL(signalIpkgMessage(char*)), receiver, slotOutput );
356 for ( QStringList::Iterator it = parameters->begin(); it != parameters->end(); ++it ) 356 for ( QStringList::Iterator it = parameters->begin(); it != parameters->end(); ++it )
357 { 357 {
358 ipkg_packages_download( &m_ipkgArgs, (*it) ); 358 ipkg_packages_download( &m_ipkgArgs, (*it) );
359 } 359 }
360 }; 360 };
361 break; 361 break;
362 case OPackage::Info : { 362 case OPackage::Info : {
363 connect( this, SIGNAL(signalIpkgStatus(char *)), receiver, slotOutput ); 363 connect( this, SIGNAL(signalIpkgStatus(char*)), receiver, slotOutput );
364 ipkg_packages_info( &m_ipkgArgs, (*parameters->begin()), &fIpkgStatus, 0x0 ); 364 ipkg_packages_info( &m_ipkgArgs, (*parameters->begin()), &fIpkgStatus, 0x0 );
365 }; 365 };
366 break; 366 break;
367 case OPackage::Files : { 367 case OPackage::Files : {
368 connect( this, SIGNAL(signalIpkgList(char *)), receiver, slotOutput ); 368 connect( this, SIGNAL(signalIpkgList(char*)), receiver, slotOutput );
369 ipkg_package_files( &m_ipkgArgs, (*parameters->begin()), &fIpkgFiles, 0x0 ); 369 ipkg_package_files( &m_ipkgArgs, (*parameters->begin()), &fIpkgFiles, 0x0 );
370 }; 370 };
371 break; 371 break;
372 default : break; 372 default : break;
373 }; 373 };
374 374
375 return true; 375 return true;
376} 376}
377 377
378void OIpkg::ipkgMessage( char *msg ) 378void OIpkg::ipkgMessage( char *msg )
379{ 379{
380 emit signalIpkgMessage( msg ); 380 emit signalIpkgMessage( msg );
381} 381}
382 382
383void OIpkg::ipkgStatus( char *status ) 383void OIpkg::ipkgStatus( char *status )
384{ 384{
385 emit signalIpkgStatus( status ); 385 emit signalIpkgStatus( status );
386} 386}
387 387
388void OIpkg::ipkgList( char *filelist ) 388void OIpkg::ipkgList( char *filelist )
389{ 389{
390 emit signalIpkgList( filelist ); 390 emit signalIpkgList( filelist );
391} 391}
392 392
393void OIpkg::loadConfiguration() 393void OIpkg::loadConfiguration()
394{ 394{
395 if ( m_confInfo ) 395 if ( m_confInfo )
396 delete m_confInfo; 396 delete m_confInfo;
397 397
398 // Load configuration item list 398 // Load configuration item list
399 m_confInfo = new OConfItemList(); 399 m_confInfo = new OConfItemList();
400 400
401 QStringList confFiles; 401 QStringList confFiles;
402 QDir confDir( IPKG_CONF_DIR ); 402 QDir confDir( IPKG_CONF_DIR );
403 if ( confDir.exists() ) 403 if ( confDir.exists() )
404 { 404 {
405 confDir.setNameFilter( "*.conf" ); 405 confDir.setNameFilter( "*.conf" );
406 confDir.setFilter( QDir::Files ); 406 confDir.setFilter( QDir::Files );
407 confFiles = confDir.entryList( "*.conf", QDir::Files ); 407 confFiles = confDir.entryList( "*.conf", QDir::Files );
408 confFiles << IPKG_CONF; 408 confFiles << IPKG_CONF;
409 409
410 for ( QStringList::Iterator it = confFiles.begin(); it != confFiles.end(); ++it ) 410 for ( QStringList::Iterator it = confFiles.begin(); it != confFiles.end(); ++it )
411 { 411 {
412 // Create absolute file path if necessary 412 // Create absolute file path if necessary
413 QString absFile = (*it); 413 QString absFile = (*it);
414 if ( !absFile.startsWith( "/" ) ) 414 if ( !absFile.startsWith( "/" ) )
415 absFile.prepend( QString( IPKG_CONF_DIR ) + "/" ); 415 absFile.prepend( QString( IPKG_CONF_DIR ) + "/" );
416 416
417 // Read in file 417 // Read in file
418 QFile f( absFile ); 418 QFile f( absFile );
419 if ( f.open( IO_ReadOnly ) ) 419 if ( f.open( IO_ReadOnly ) )
420 { 420 {
421 QTextStream s( &f ); 421 QTextStream s( &f );
422 while ( !s.eof() ) 422 while ( !s.eof() )
423 { 423 {
424 424
425 QString line = s.readLine().simplifyWhiteSpace(); 425 QString line = s.readLine().simplifyWhiteSpace();
426 426
427 // Parse line and save info to the conf options list 427 // Parse line and save info to the conf options list
428 if ( !line.isEmpty() ) 428 if ( !line.isEmpty() )
429 { 429 {
430 if ( !line.startsWith( "#" ) || 430 if ( !line.startsWith( "#" ) ||
431 line.startsWith( "#src" ) || 431 line.startsWith( "#src" ) ||
432 line.startsWith( "#dest" ) || 432 line.startsWith( "#dest" ) ||
433 line.startsWith( "#arch" ) || 433 line.startsWith( "#arch" ) ||
434 line.startsWith( "#option" ) ) 434 line.startsWith( "#option" ) )
435 { 435 {
436 int pos = line.find( ' ', 1 ); 436 int pos = line.find( ' ', 1 );
437 437
438 // Type 438 // Type
439 QString typeStr = line.left( pos ); 439 QString typeStr = line.left( pos );
440 OConfItem::Type type; 440 OConfItem::Type type;
441 if ( typeStr == "src" || typeStr == "#src" ) 441 if ( typeStr == "src" || typeStr == "#src" )
442 type = OConfItem::Source; 442 type = OConfItem::Source;
443 else if ( typeStr == "dest" || typeStr == "#dest" ) 443 else if ( typeStr == "dest" || typeStr == "#dest" )
444 type = OConfItem::Destination; 444 type = OConfItem::Destination;
445 else if ( typeStr == "option" || typeStr == "#option" ) 445 else if ( typeStr == "option" || typeStr == "#option" )
446 type = OConfItem::Option; 446 type = OConfItem::Option;
447 else if ( typeStr == "arch" || typeStr == "#arch" ) 447 else if ( typeStr == "arch" || typeStr == "#arch" )
448 type = OConfItem::Arch; 448 type = OConfItem::Arch;
449 else 449 else
450 type = OConfItem::NotDefined; 450 type = OConfItem::NotDefined;
451 ++pos; 451 ++pos;
452 int endpos = line.find( ' ', pos ); 452 int endpos = line.find( ' ', pos );
453 453
454 // Name 454 // Name
455 QString name = line.mid( pos, endpos - pos ); 455 QString name = line.mid( pos, endpos - pos );
456 456
457 // Value 457 // Value
458 QString value = ""; 458 QString value = "";
459 if ( endpos > -1 ) 459 if ( endpos > -1 )
460 value = line.right( line.length() - endpos - 1 ); 460 value = line.right( line.length() - endpos - 1 );
461 461
462 // Active 462 // Active
463 bool active = !line.startsWith( "#" ); 463 bool active = !line.startsWith( "#" );
464 464
465 // Add to list 465 // Add to list
466 m_confInfo->append( new OConfItem( absFile, type, name, value, active ) ); 466 m_confInfo->append( new OConfItem( absFile, type, name, value, active ) );
467 } 467 }
468 } 468 }
469 } 469 }
470 470
471 f.close(); 471 f.close();
472 } 472 }
473 } 473 }
474 } 474 }
475 475
476 // Load Ipkg execution options from application configuration file 476 // Load Ipkg execution options from application configuration file
477 if ( m_config ) 477 if ( m_config )
478 { 478 {
479 m_config->setGroup( "Ipkg" ); 479 m_config->setGroup( "Ipkg" );
480 m_ipkgExecOptions = m_config->readNumEntry( "ExecOptions", m_ipkgExecOptions ); 480 m_ipkgExecOptions = m_config->readNumEntry( "ExecOptions", m_ipkgExecOptions );
481 m_ipkgExecVerbosity = m_config->readNumEntry( "Verbosity", m_ipkgExecVerbosity ); 481 m_ipkgExecVerbosity = m_config->readNumEntry( "Verbosity", m_ipkgExecVerbosity );
482 } 482 }
483} 483}
484 484
485OConfItemList *OIpkg::filterConfItems( OConfItem::Type typefilter ) 485OConfItemList *OIpkg::filterConfItems( OConfItem::Type typefilter )
486{ 486{
487 // Load Ipkg configuration info if not already cached 487 // Load Ipkg configuration info if not already cached
488 if ( !m_confInfo ) 488 if ( !m_confInfo )
489 loadConfiguration(); 489 loadConfiguration();
490 490
491 // Build new server list (caller is responsible for deleting) 491 // Build new server list (caller is responsible for deleting)
492 OConfItemList *sl = new OConfItemList; 492 OConfItemList *sl = new OConfItemList;
493 493
494 // If typefilter is empty, retrieve all items 494 // If typefilter is empty, retrieve all items
495 bool retrieveAll = ( typefilter == OConfItem::NotDefined ); 495 bool retrieveAll = ( typefilter == OConfItem::NotDefined );
496 496
497 // Parse configuration info for servers 497 // Parse configuration info for servers
498 OConfItemListIterator it( *m_confInfo ); 498 OConfItemListIterator it( *m_confInfo );
499 for ( ; it.current(); ++it ) 499 for ( ; it.current(); ++it )
500 { 500 {
501 OConfItem *item = it.current(); 501 OConfItem *item = it.current();
502 if ( retrieveAll || item->type() == typefilter ) 502 if ( retrieveAll || item->type() == typefilter )
503 { 503 {
504 sl->append( item ); 504 sl->append( item );
505 } 505 }
506 } 506 }
507 507
508 return sl; 508 return sl;
509} 509}
diff --git a/noncore/settings/sound/soundsettings.cpp b/noncore/settings/sound/soundsettings.cpp
index 4bc86fa..8ad0a3f 100644
--- a/noncore/settings/sound/soundsettings.cpp
+++ b/noncore/settings/sound/soundsettings.cpp
@@ -1,220 +1,220 @@
1/********************************************************************** 1/**********************************************************************
2 ** Copyright (C) 2000 Trolltech AS. All rights reserved. 2 ** Copyright (C) 2000 Trolltech AS. All rights reserved.
3 ** 3 **
4 ** This file is part of Qtopia Environment. 4 ** This file is part of Qtopia Environment.
5 ** 5 **
6 ** This file may be distributed and/or modified under the terms of the 6 ** This file may be distributed and/or modified under the terms of the
7 ** GNU General Public License version 2 as published by the Free Software 7 ** GNU General Public License version 2 as published by the Free Software
8 ** Foundation and appearing in the file LICENSE.GPL included in the 8 ** Foundation and appearing in the file LICENSE.GPL included in the
9 ** packaging of this file. 9 ** packaging of this file.
10 ** 10 **
11 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13 ** 13 **
14 ** See http://www.trolltech.com/gpl/ for GPL licensing information. 14 ** See http://www.trolltech.com/gpl/ for GPL licensing information.
15 ** 15 **
16 ** Contact info@trolltech.com if any conditions of this licensing are 16 ** Contact info@trolltech.com if any conditions of this licensing are
17 ** not clear to you. 17 ** not clear to you.
18 ** 18 **
19 **********************************************************************/ 19 **********************************************************************/
20// parts copyright 2002 L.J. Potter 20// parts copyright 2002 L.J. Potter
21 21
22#include "soundsettings.h" 22#include "soundsettings.h"
23 23
24#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25#include <qpe/config.h> 25#include <qpe/config.h>
26#include <qpe/qcopenvelope_qws.h> 26#include <qpe/qcopenvelope_qws.h>
27#include <qpe/storage.h> 27#include <qpe/storage.h>
28 28
29#include <qcheckbox.h> 29#include <qcheckbox.h>
30#include <qcombobox.h> 30#include <qcombobox.h>
31#include <qlabel.h> 31#include <qlabel.h>
32 32
33#include <sys/utsname.h> 33#include <sys/utsname.h>
34#include <sys/time.h> 34#include <sys/time.h>
35#include <sys/types.h> 35#include <sys/types.h>
36#include <unistd.h> 36#include <unistd.h>
37#include <stdio.h> 37#include <stdio.h>
38#include <sys/stat.h> 38#include <sys/stat.h>
39 39
40 40
41SoundSettings::SoundSettings( QWidget* parent, const char* objname, WFlags fl ) 41SoundSettings::SoundSettings( QWidget* parent, const char* objname, WFlags fl )
42 : SoundSettingsBase( parent, objname, TRUE, fl ) 42 : SoundSettingsBase( parent, objname, TRUE, fl )
43{ 43{
44 keyReset=FALSE; 44 keyReset=FALSE;
45 noWarning=false; 45 noWarning=false;
46 Config config( "qpe"); 46 Config config( "qpe");
47 config.setGroup( "Volume" ); 47 config.setGroup( "Volume" );
48 Config cfg("Vmemo"); 48 Config cfg("Vmemo");
49 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 49 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
50 AlertCheckBox->setChecked(cfg.readBoolEntry("Alert")); 50 AlertCheckBox->setChecked(cfg.readBoolEntry("Alert"));
51 51
52 cfg.setGroup("Record"); 52 cfg.setGroup("Record");
53 int rate=config.readNumEntry("SampleRate", 22050); 53 int rate=config.readNumEntry("SampleRate", 22050);
54 if(rate == 8000) 54 if(rate == 8000)
55 sampleRate->setCurrentItem(0); 55 sampleRate->setCurrentItem(0);
56 else if(rate == 11025) 56 else if(rate == 11025)
57 sampleRate->setCurrentItem(1); 57 sampleRate->setCurrentItem(1);
58 else if(rate == 22050) 58 else if(rate == 22050)
59 sampleRate->setCurrentItem(2); 59 sampleRate->setCurrentItem(2);
60 else if(rate == 33075) 60 else if(rate == 33075)
61 sampleRate->setCurrentItem(3); 61 sampleRate->setCurrentItem(3);
62 else if(rate==44100) 62 else if(rate==44100)
63 sampleRate->setCurrentItem(4); 63 sampleRate->setCurrentItem(4);
64 64
65 stereoCheckBox->setChecked(cfg.readNumEntry("Stereo", 0)); 65 stereoCheckBox->setChecked(cfg.readNumEntry("Stereo", 0));
66//TODO hide if zaurus- mono only 66//TODO hide if zaurus- mono only
67 67
68#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) 68#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX)
69//since ipaq and zaurus have particular 69//since ipaq and zaurus have particular
70//devices 70//devices
71 bool systemZaurus=FALSE; 71 bool systemZaurus=FALSE;
72 struct utsname name; /* check for embedix kernel running on the zaurus*/ 72 struct utsname name; /* check for embedix kernel running on the zaurus*/
73 if (uname(&name) != -1) {// TODO change this here,... 73 if (uname(&name) != -1) {// TODO change this here,...
74 QString release=name.release; 74 QString release=name.release;
75 if( release.find("embedix",0,TRUE) != -1) { 75 if( release.find("embedix",0,TRUE) != -1) {
76 qDebug("IS System Zaurus"); 76 qDebug("IS System Zaurus");
77 systemZaurus=TRUE; 77 systemZaurus=TRUE;
78 } 78 }
79 } 79 }
80 if(!systemZaurus) { 80 if(!systemZaurus) {
81 stereoCheckBox->setChecked(TRUE); 81 stereoCheckBox->setChecked(TRUE);
82 } 82 }
83 stereoCheckBox->setEnabled(FALSE); 83 stereoCheckBox->setEnabled(FALSE);
84 sixteenBitCheckBox->setEnabled(FALSE); 84 sixteenBitCheckBox->setEnabled(FALSE);
85#else 85#else
86#endif 86#endif
87 int sRate=cfg.readNumEntry("SizeLimit", 30); 87 int sRate=cfg.readNumEntry("SizeLimit", 30);
88 qDebug("%d",sRate); 88 qDebug("%d",sRate);
89 89
90 if(sRate ==30) 90 if(sRate ==30)
91 timeLimitComboBox->setCurrentItem(0); 91 timeLimitComboBox->setCurrentItem(0);
92 else if(sRate==20) 92 else if(sRate==20)
93 timeLimitComboBox->setCurrentItem(1); 93 timeLimitComboBox->setCurrentItem(1);
94 else if(sRate == 15) 94 else if(sRate == 15)
95 timeLimitComboBox->setCurrentItem(2); 95 timeLimitComboBox->setCurrentItem(2);
96 else if(sRate == 10) 96 else if(sRate == 10)
97 timeLimitComboBox->setCurrentItem(3); 97 timeLimitComboBox->setCurrentItem(3);
98 else if(sRate == 5) 98 else if(sRate == 5)
99 timeLimitComboBox->setCurrentItem(4); 99 timeLimitComboBox->setCurrentItem(4);
100 else 100 else
101 timeLimitComboBox->setCurrentItem(5); 101 timeLimitComboBox->setCurrentItem(5);
102 102
103 sixteenBitCheckBox->setChecked(cfg.readNumEntry("SixteenBit", 1)); 103 sixteenBitCheckBox->setChecked(cfg.readNumEntry("SixteenBit", 1));
104 104
105 cfg.setGroup("Defaults"); 105 cfg.setGroup("Defaults");
106 keyComboBox->setCurrentItem(cfg.readNumEntry("toggleKey") ); 106 keyComboBox->setCurrentItem(cfg.readNumEntry("toggleKey") );
107 107
108 updateStorageCombo(); 108 updateStorageCombo();
109 109
110 Config vmCfg("Vmemo"); 110 Config vmCfg("Vmemo");
111 vmCfg.setGroup("Defaults"); 111 vmCfg.setGroup("Defaults");
112 adpcmCheckBox->setChecked( vmCfg.readBoolEntry("use_ADPCM", 0)); 112 adpcmCheckBox->setChecked( vmCfg.readBoolEntry("use_ADPCM", 0));
113 113
114 connect( LocationComboBox,SIGNAL(activated(const QString &)), this, 114 connect( LocationComboBox,SIGNAL(activated(const QString&)), this,
115 SLOT( setLocation(const QString &))); 115 SLOT( setLocation(const QString&)));
116 connect( keyComboBox,SIGNAL(activated( int)), this, 116 connect( keyComboBox,SIGNAL(activated(int)), this,
117 SLOT( setKeyButton( int))); 117 SLOT( setKeyButton(int)));
118 connect( timeLimitComboBox,SIGNAL(activated( const QString &)), this, 118 connect( timeLimitComboBox,SIGNAL(activated(const QString&)), this,
119 SLOT( setSizeLimitButton(const QString &))); 119 SLOT( setSizeLimitButton(const QString&)));
120 connect( restartCheckBox,SIGNAL( toggled( bool)), this, 120 connect( restartCheckBox,SIGNAL( toggled(bool)), this,
121 SLOT( restartOpie( bool))); 121 SLOT( restartOpie(bool)));
122 connect( adpcmCheckBox,SIGNAL( toggled( bool)), this, 122 connect( adpcmCheckBox,SIGNAL( toggled(bool)), this,
123 SLOT( slotAdpcm( bool))); 123 SLOT( slotAdpcm(bool)));
124 124
125 // connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 125 // connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
126} 126}
127 127
128void SoundSettings::updateStorageCombo() { 128void SoundSettings::updateStorageCombo() {
129 129
130 Config config( "Vmemo" ); 130 Config config( "Vmemo" );
131 config.setGroup( "System" ); 131 config.setGroup( "System" );
132 QString loc = config.readEntry("RecLocation","/"); 132 QString loc = config.readEntry("RecLocation","/");
133 int i=0; 133 int i=0;
134 int set=0; 134 int set=0;
135 StorageInfo storageInfo; 135 StorageInfo storageInfo;
136 QString sName, sPath; 136 QString sName, sPath;
137 QStringList list; 137 QStringList list;
138 list << "Documents : "+QPEApplication::documentDir(); 138 list << "Documents : "+QPEApplication::documentDir();
139 list << "tmp : /tmp"; 139 list << "tmp : /tmp";
140 140
141 const QList<FileSystem> &fs = storageInfo.fileSystems(); 141 const QList<FileSystem> &fs = storageInfo.fileSystems();
142 QListIterator<FileSystem> it ( fs ); 142 QListIterator<FileSystem> it ( fs );
143 for( ; it.current(); ++it ){ 143 for( ; it.current(); ++it ){
144 const QString name = (*it)->name(); 144 const QString name = (*it)->name();
145 const QString path = (*it)->path(); 145 const QString path = (*it)->path();
146 qDebug("storage name "+name +" storage path is "+path); 146 qDebug("storage name "+name +" storage path is "+path);
147 list << name + ": " +path; 147 list << name + ": " +path;
148 if( loc.find( path,0,TRUE) != -1) 148 if( loc.find( path,0,TRUE) != -1)
149 set = i; 149 set = i;
150// if(dit.current()->file().find(path) != -1 ) storage=name; 150// if(dit.current()->file().find(path) != -1 ) storage=name;
151 i++; 151 i++;
152 } 152 }
153 153
154 LocationComboBox->insertStringList(list); 154 LocationComboBox->insertStringList(list);
155 qDebug("set item %d", set); 155 qDebug("set item %d", set);
156 LocationComboBox->setCurrentItem(set); 156 LocationComboBox->setCurrentItem(set);
157} 157}
158 158
159void SoundSettings::setLocation(const QString & string) { 159void SoundSettings::setLocation(const QString & string) {
160 Config config( "Vmemo" ); 160 Config config( "Vmemo" );
161 config.setGroup( "System" ); 161 config.setGroup( "System" );
162 config.writeEntry("RecLocation",string); 162 config.writeEntry("RecLocation",string);
163 qDebug("set location "+string); 163 qDebug("set location "+string);
164 config.write(); 164 config.write();
165} 165}
166 166
167void SoundSettings::cleanUp() { 167void SoundSettings::cleanUp() {
168 Config cfg("Vmemo"); 168 Config cfg("Vmemo");
169 cfg.writeEntry("Alert",AlertCheckBox->isChecked()); 169 cfg.writeEntry("Alert",AlertCheckBox->isChecked());
170 170
171 cfg.setGroup("Record"); 171 cfg.setGroup("Record");
172 cfg.writeEntry("SampleRate",sampleRate->currentText()); 172 cfg.writeEntry("SampleRate",sampleRate->currentText());
173 cfg.writeEntry("Stereo",stereoCheckBox->isChecked()); 173 cfg.writeEntry("Stereo",stereoCheckBox->isChecked());
174 cfg.writeEntry("SixteenBit",sixteenBitCheckBox->isChecked()); 174 cfg.writeEntry("SixteenBit",sixteenBitCheckBox->isChecked());
175 if(keyReset && noWarning) { 175 if(keyReset && noWarning) {
176 QCopEnvelope ("QPE/System", "restart()"); 176 QCopEnvelope ("QPE/System", "restart()");
177 } 177 }
178} 178}
179 179
180void SoundSettings::setKeyButton( int index) { 180void SoundSettings::setKeyButton( int index) {
181 Config cfg("Vmemo"); 181 Config cfg("Vmemo");
182 cfg.setGroup("Defaults"); 182 cfg.setGroup("Defaults");
183 cfg.writeEntry( "toggleKey", index ); 183 cfg.writeEntry( "toggleKey", index );
184 keyReset = TRUE; 184 keyReset = TRUE;
185 if( index == 1) { 185 if( index == 1) {
186 cfg.writeEntry( "hideIcon", 0 ); 186 cfg.writeEntry( "hideIcon", 0 );
187 keyLabel->setText(tr("Shows icon")); 187 keyLabel->setText(tr("Shows icon"));
188 } 188 }
189 else { 189 else {
190 cfg.writeEntry( "hideIcon", 1); 190 cfg.writeEntry( "hideIcon", 1);
191 keyLabel->setText(tr("Hides icon")); 191 keyLabel->setText(tr("Hides icon"));
192 } 192 }
193 cfg.write(); 193 cfg.write();
194} 194}
195 195
196void SoundSettings::updateLocationCombo() { 196void SoundSettings::updateLocationCombo() {
197 197
198} 198}
199 199
200void SoundSettings::setSizeLimitButton(const QString &index) { 200void SoundSettings::setSizeLimitButton(const QString &index) {
201 201
202 Config cfg("Vmemo"); 202 Config cfg("Vmemo");
203 cfg.setGroup("Record"); 203 cfg.setGroup("Record");
204 if(index.find("Unlimited",0,TRUE) != -1) 204 if(index.find("Unlimited",0,TRUE) != -1)
205 cfg.writeEntry("SizeLimit", -1); 205 cfg.writeEntry("SizeLimit", -1);
206 else 206 else
207 cfg.writeEntry("SizeLimit", index); 207 cfg.writeEntry("SizeLimit", index);
208 cfg.write(); 208 cfg.write();
209} 209}
210 210
211void SoundSettings::restartOpie(bool b) { 211void SoundSettings::restartOpie(bool b) {
212 noWarning=b; 212 noWarning=b;
213} 213}
214 214
215void SoundSettings::slotAdpcm(bool b) { 215void SoundSettings::slotAdpcm(bool b) {
216 Config vmCfg("Vmemo"); 216 Config vmCfg("Vmemo");
217 vmCfg.setGroup("Defaults"); 217 vmCfg.setGroup("Defaults");
218 vmCfg.writeEntry("use_ADPCM", b); 218 vmCfg.writeEntry("use_ADPCM", b);
219 vmCfg.write(); 219 vmCfg.write();
220} 220}
diff --git a/noncore/settings/sysinfo/benchmarkinfo.cpp b/noncore/settings/sysinfo/benchmarkinfo.cpp
index 0aeb251..d6ecec5 100644
--- a/noncore/settings/sysinfo/benchmarkinfo.cpp
+++ b/noncore/settings/sysinfo/benchmarkinfo.cpp
@@ -1,468 +1,468 @@
1/********************************************************************** 1/**********************************************************************
2** BenchmarkInfo 2** BenchmarkInfo
3** 3**
4** A benchmark for Qt/Embedded 4** A benchmark for Qt/Embedded
5** 5**
6** Copyright (C) 2004 Michael Lauer <mickey@vanille.de> 6** Copyright (C) 2004 Michael Lauer <mickey@vanille.de>
7** Inspired by ZBench (C) 2002 Satoshi <af230533@im07.alpha-net.ne.jp> 7** Inspired by ZBench (C) 2002 Satoshi <af230533@im07.alpha-net.ne.jp>
8** 8**
9** This file may be distributed and/or modified under the terms of the 9** This file may be distributed and/or modified under the terms of the
10** GNU General Public License version 2 as published by the Free Software 10** GNU General Public License version 2 as published by the Free Software
11** Foundation and appearing in the file LICENSE.GPL included in the 11** Foundation and appearing in the file LICENSE.GPL included in the
12** packaging of this file. 12** packaging of this file.
13** 13**
14** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 14** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
15** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 15** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16** 16**
17**********************************************************************/ 17**********************************************************************/
18 18
19/* OPIE */ 19/* OPIE */
20#include <opie2/ostorageinfo.h> 20#include <opie2/ostorageinfo.h>
21#include <qpe/qpeapplication.h> 21#include <qpe/qpeapplication.h>
22#include <qpe/qcopenvelope_qws.h> 22#include <qpe/qcopenvelope_qws.h>
23#include <qpe/qpedecoration_qws.h> 23#include <qpe/qpedecoration_qws.h>
24#include <qpe/resource.h> 24#include <qpe/resource.h>
25#include <qpe/config.h> 25#include <qpe/config.h>
26 26
27/* QT */ 27/* QT */
28#include <qclipboard.h> 28#include <qclipboard.h>
29#include <qcolor.h> 29#include <qcolor.h>
30#include <qcombobox.h> 30#include <qcombobox.h>
31#include <qdirectpainter_qws.h> 31#include <qdirectpainter_qws.h>
32#include <qfile.h> 32#include <qfile.h>
33#include <qtextstream.h> 33#include <qtextstream.h>
34#include <qfiledialog.h> 34#include <qfiledialog.h>
35#include <qlabel.h> 35#include <qlabel.h>
36#include <qlayout.h> 36#include <qlayout.h>
37#include <qpainter.h> 37#include <qpainter.h>
38#include <qpushbutton.h> 38#include <qpushbutton.h>
39#include <qtimer.h> 39#include <qtimer.h>
40 40
41/* STD */ 41/* STD */
42#include <time.h> 42#include <time.h>
43#include <stdio.h> 43#include <stdio.h>
44#include <stdlib.h> 44#include <stdlib.h>
45#include <math.h> 45#include <math.h>
46 46
47#include "benchmarkinfo.h" 47#include "benchmarkinfo.h"
48 48
49extern "C" 49extern "C"
50{ 50{
51 void BenchFFT( void ); 51 void BenchFFT( void );
52 double dhry_main( int ); 52 double dhry_main( int );
53} 53}
54 54
55#define DHRYSTONE_RUNS 20000000 55#define DHRYSTONE_RUNS 20000000
56#define TEST_DURATION 3 56#define TEST_DURATION 3
57 57
58#define BUFF_SIZE 8192 58#define BUFF_SIZE 8192
59#define FILE_SIZE 1024 * 1024 // 1Mb 59#define FILE_SIZE 1024 * 1024 // 1Mb
60 60
61//=========================================================================== 61//===========================================================================
62 62
63class BenchmarkPaintWidget : public QWidget 63class BenchmarkPaintWidget : public QWidget
64{ 64{
65 public: 65 public:
66 BenchmarkPaintWidget() : QWidget( 0, "Benchmark Paint Widget", WStyle_Customize|WStyle_StaysOnTop|WPaintUnclipped|WPaintClever ) 66 BenchmarkPaintWidget() : QWidget( 0, "Benchmark Paint Widget", WStyle_Customize|WStyle_StaysOnTop|WPaintUnclipped|WPaintClever )
67 { 67 {
68 resize( QApplication::desktop()->size() ); 68 resize( QApplication::desktop()->size() );
69 show(); 69 show();
70 p.begin( this ); 70 p.begin( this );
71 }; 71 };
72 72
73 ~BenchmarkPaintWidget() 73 ~BenchmarkPaintWidget()
74 { 74 {
75 p.end(); 75 p.end();
76 hide(); 76 hide();
77 }; 77 };
78 78
79 QPainter p; 79 QPainter p;
80}; 80};
81 81
82//=========================================================================== 82//===========================================================================
83 83
84BenchmarkInfo::BenchmarkInfo( QWidget *parent, const char *name, int wFlags ) 84BenchmarkInfo::BenchmarkInfo( QWidget *parent, const char *name, int wFlags )
85 : QWidget( parent, name, wFlags ) 85 : QWidget( parent, name, wFlags )
86{ 86{
87 87
88 setMinimumSize( 200, 150 ); 88 setMinimumSize( 200, 150 );
89 89
90 QVBoxLayout* vb = new QVBoxLayout( this ); 90 QVBoxLayout* vb = new QVBoxLayout( this );
91 vb->setSpacing( 4 ); 91 vb->setSpacing( 4 );
92 vb->setMargin( 4 ); 92 vb->setMargin( 4 );
93 93
94 tests = new QListView( this ); 94 tests = new QListView( this );
95 tests->setMargin( 0 ); 95 tests->setMargin( 0 );
96 tests->addColumn( tr( "Tests" ) ); 96 tests->addColumn( tr( "Tests" ) );
97 tests->addColumn( tr( "Results" ) ); 97 tests->addColumn( tr( "Results" ) );
98 tests->addColumn( tr( "Comparison" ) ); 98 tests->addColumn( tr( "Comparison" ) );
99 tests->setShowSortIndicator( true ); 99 tests->setShowSortIndicator( true );
100 100
101 test_alu = new QCheckListItem( tests, tr( "1. Integer Arithmetic " ), QCheckListItem::CheckBox ); 101 test_alu = new QCheckListItem( tests, tr( "1. Integer Arithmetic " ), QCheckListItem::CheckBox );
102 test_fpu = new QCheckListItem( tests, tr( "2. Floating Point Unit " ), QCheckListItem::CheckBox ); 102 test_fpu = new QCheckListItem( tests, tr( "2. Floating Point Unit " ), QCheckListItem::CheckBox );
103 test_txt = new QCheckListItem( tests, tr( "3. Text Rendering " ), QCheckListItem::CheckBox ); 103 test_txt = new QCheckListItem( tests, tr( "3. Text Rendering " ), QCheckListItem::CheckBox );
104 test_gfx = new QCheckListItem( tests, tr( "4. Gfx Rendering " ), QCheckListItem::CheckBox ); 104 test_gfx = new QCheckListItem( tests, tr( "4. Gfx Rendering " ), QCheckListItem::CheckBox );
105 test_ram = new QCheckListItem( tests, tr( "5. RAM Performance " ), QCheckListItem::CheckBox ); 105 test_ram = new QCheckListItem( tests, tr( "5. RAM Performance " ), QCheckListItem::CheckBox );
106 test_sd = new QCheckListItem( tests, tr( "6. SD Card Performance " ), QCheckListItem::CheckBox ); 106 test_sd = new QCheckListItem( tests, tr( "6. SD Card Performance " ), QCheckListItem::CheckBox );
107 test_cf = new QCheckListItem( tests, tr( "7. CF Card Performance " ), QCheckListItem::CheckBox ); 107 test_cf = new QCheckListItem( tests, tr( "7. CF Card Performance " ), QCheckListItem::CheckBox );
108 108
109 test_alu->setText( 1, "n/a" ); 109 test_alu->setText( 1, "n/a" );
110 test_fpu->setText( 1, "n/a" ); 110 test_fpu->setText( 1, "n/a" );
111 test_txt->setText( 1, "n/a" ); 111 test_txt->setText( 1, "n/a" );
112 test_gfx->setText( 1, "n/a" ); 112 test_gfx->setText( 1, "n/a" );
113 test_ram->setText( 1, "n/a" ); 113 test_ram->setText( 1, "n/a" );
114 test_sd->setText( 1, "n/a" ); 114 test_sd->setText( 1, "n/a" );
115 test_cf->setText( 1, "n/a" ); 115 test_cf->setText( 1, "n/a" );
116 116
117 test_alu->setText( 2, "n/a" ); 117 test_alu->setText( 2, "n/a" );
118 test_fpu->setText( 2, "n/a" ); 118 test_fpu->setText( 2, "n/a" );
119 test_txt->setText( 2, "n/a" ); 119 test_txt->setText( 2, "n/a" );
120 test_gfx->setText( 2, "n/a" ); 120 test_gfx->setText( 2, "n/a" );
121 test_ram->setText( 2, "n/a" ); 121 test_ram->setText( 2, "n/a" );
122 test_sd->setText( 2, "n/a" ); 122 test_sd->setText( 2, "n/a" );
123 test_cf->setText( 2, "n/a" ); 123 test_cf->setText( 2, "n/a" );
124 124
125 startButton = new QPushButton( tr( "&Start Tests!" ), this ); 125 startButton = new QPushButton( tr( "&Start Tests!" ), this );
126 connect( startButton, SIGNAL( clicked() ), this, SLOT( run() ) ); 126 connect( startButton, SIGNAL( clicked() ), this, SLOT( run() ) );
127 127
128 vb->addWidget( tests, 2 ); 128 vb->addWidget( tests, 2 );
129 129
130 QFile f( QPEApplication::qpeDir() + "/share/sysinfo/results" ); 130 QFile f( QPEApplication::qpeDir() + "/share/sysinfo/results" );
131 if ( f.open( IO_ReadOnly ) ) 131 if ( f.open( IO_ReadOnly ) )
132 { 132 {
133 machineCombo = new QComboBox( this ); 133 machineCombo = new QComboBox( this );
134 134
135 QTextStream ts( &f ); 135 QTextStream ts( &f );
136 while( !ts.eof() ) 136 while( !ts.eof() )
137 { 137 {
138 QString machline = ts.readLine(); 138 QString machline = ts.readLine();
139 qDebug( "sysinfo: parsing benchmark results for '%s'", (const char*) machline ); 139 qDebug( "sysinfo: parsing benchmark results for '%s'", (const char*) machline );
140 QString resline = ts.readLine(); 140 QString resline = ts.readLine();
141 machines.insert( machline, new QStringList( QStringList::split( ",", resline ) ) ); 141 machines.insert( machline, new QStringList( QStringList::split( ",", resline ) ) );
142 machineCombo->insertItem( machline ); 142 machineCombo->insertItem( machline );
143 } 143 }
144 144
145 QHBoxLayout* hb = new QHBoxLayout( vb ); 145 QHBoxLayout* hb = new QHBoxLayout( vb );
146 hb->addWidget( new QLabel( tr( "Compare To:" ), this ) ); 146 hb->addWidget( new QLabel( tr( "Compare To:" ), this ) );
147 hb->addWidget( machineCombo, 2 ); 147 hb->addWidget( machineCombo, 2 );
148 connect( machineCombo, SIGNAL( activated( int ) ), this, SLOT( machineActivated( int ) ) ); 148 connect( machineCombo, SIGNAL( activated(int) ), this, SLOT( machineActivated(int) ) );
149 } 149 }
150 150
151 vb->addWidget( startButton, 2 ); 151 vb->addWidget( startButton, 2 );
152} 152}
153 153
154 154
155BenchmarkInfo::~BenchmarkInfo() 155BenchmarkInfo::~BenchmarkInfo()
156{} 156{}
157 157
158 158
159void BenchmarkInfo::machineActivated( int index ) 159void BenchmarkInfo::machineActivated( int index )
160{ 160{
161 QStringList* results = machines[ machineCombo->text( index ) ]; 161 QStringList* results = machines[ machineCombo->text( index ) ];
162 if ( !results ) 162 if ( !results )
163 { 163 {
164 qDebug( "sysinfo: no results available." ); 164 qDebug( "sysinfo: no results available." );
165 return; 165 return;
166 } 166 }
167 QStringList::Iterator it = results->begin(); 167 QStringList::Iterator it = results->begin();
168 test_alu->setText( 2, *(it++) ); 168 test_alu->setText( 2, *(it++) );
169 test_fpu->setText( 2, *(it++) ); 169 test_fpu->setText( 2, *(it++) );
170 test_txt->setText( 2, *(it++) ); 170 test_txt->setText( 2, *(it++) );
171 test_gfx->setText( 2, *(it++) ); 171 test_gfx->setText( 2, *(it++) );
172 test_ram->setText( 2, *(it++) ); 172 test_ram->setText( 2, *(it++) );
173 test_sd->setText( 2, *(it++) ); 173 test_sd->setText( 2, *(it++) );
174 test_cf->setText( 2, *(it++) ); 174 test_cf->setText( 2, *(it++) );
175} 175}
176 176
177 177
178void BenchmarkInfo::run() 178void BenchmarkInfo::run()
179{ 179{
180 startButton->setText( "> Don't touch! Running Tests! Don't touch! <" ); 180 startButton->setText( "> Don't touch! Running Tests! Don't touch! <" );
181 qApp->processEvents(); 181 qApp->processEvents();
182 QTime t; 182 QTime t;
183 183
184 if ( test_alu->isOn() ) 184 if ( test_alu->isOn() )
185 { 185 {
186 int d = round( dhry_main( DHRYSTONE_RUNS ) ); 186 int d = round( dhry_main( DHRYSTONE_RUNS ) );
187 test_alu->setText( 1, QString( "%1 dhrys" ).arg( QString::number( d ) ) ); 187 test_alu->setText( 1, QString( "%1 dhrys" ).arg( QString::number( d ) ) );
188 test_alu->setOn( false ); 188 test_alu->setOn( false );
189 } 189 }
190 190
191 if ( test_fpu->isOn() ) 191 if ( test_fpu->isOn() )
192 { 192 {
193 t.start(); 193 t.start();
194 BenchFFT(); 194 BenchFFT();
195 test_fpu->setText( 1, QString( "%1 secs" ).arg( QString::number( t.elapsed() / 1000.0 ) ) ); 195 test_fpu->setText( 1, QString( "%1 secs" ).arg( QString::number( t.elapsed() / 1000.0 ) ) );
196 test_fpu->setOn( false ); 196 test_fpu->setOn( false );
197 } 197 }
198 198
199 if ( test_txt->isOn() ) 199 if ( test_txt->isOn() )
200 { 200 {
201 int value = textRendering( TEST_DURATION ); 201 int value = textRendering( TEST_DURATION );
202 test_txt->setText( 1, QString( "%1 chars/sec" ).arg( QString::number( value / TEST_DURATION ) ) ); 202 test_txt->setText( 1, QString( "%1 chars/sec" ).arg( QString::number( value / TEST_DURATION ) ) );
203 test_txt->setOn( false ); 203 test_txt->setOn( false );
204 } 204 }
205 205
206 if ( test_gfx->isOn() ) 206 if ( test_gfx->isOn() )
207 { 207 {
208 int value = gfxRendering( TEST_DURATION ); 208 int value = gfxRendering( TEST_DURATION );
209 test_gfx->setText( 1, QString( "%1 gops/sec" ).arg( QString::number( value / 4 / TEST_DURATION ) ) ); // 4 tests 209 test_gfx->setText( 1, QString( "%1 gops/sec" ).arg( QString::number( value / 4 / TEST_DURATION ) ) ); // 4 tests
210 test_gfx->setOn( false ); 210 test_gfx->setOn( false );
211 } 211 }
212 212
213 if ( test_ram->isOn() ) // /tmp is supposed to be in RAM on a PDA 213 if ( test_ram->isOn() ) // /tmp is supposed to be in RAM on a PDA
214 { 214 {
215 performFileTest( "/tmp/benchmarkFile.dat", test_ram ); 215 performFileTest( "/tmp/benchmarkFile.dat", test_ram );
216 } 216 }
217 217
218 if ( test_cf->isOn() ) 218 if ( test_cf->isOn() )
219 { 219 {
220 OStorageInfo storage; 220 OStorageInfo storage;
221 performFileTest( storage.cfPath() + "/benchmarkFile.dat", test_cf ); 221 performFileTest( storage.cfPath() + "/benchmarkFile.dat", test_cf );
222 } 222 }
223 223
224 if ( test_sd->isOn() ) 224 if ( test_sd->isOn() )
225 { 225 {
226 OStorageInfo storage; 226 OStorageInfo storage;
227 performFileTest( storage.sdPath() + "/benchmarkFile.dat", test_sd ); 227 performFileTest( storage.sdPath() + "/benchmarkFile.dat", test_sd );
228 } 228 }
229 229
230 startButton->setText( tr( "&Start Tests!" ) ); 230 startButton->setText( tr( "&Start Tests!" ) );
231} 231}
232 232
233 233
234int BenchmarkInfo::textRendering( int seconds ) 234int BenchmarkInfo::textRendering( int seconds )
235{ 235{
236 QTime t; 236 QTime t;
237 t.start(); 237 t.start();
238 int stop = t.elapsed() + seconds * 1000; 238 int stop = t.elapsed() + seconds * 1000;
239 239
240 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 }; 240 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 };
241 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 }; 241 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 };
242 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 }; 242 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 };
243 const QString text( "Opie Benchmark Test" ); 243 const QString text( "Opie Benchmark Test" );
244 244
245 int w = QApplication::desktop()->width(); 245 int w = QApplication::desktop()->width();
246 int h = QApplication::desktop()->height(); 246 int h = QApplication::desktop()->height();
247 247
248 srand( time( NULL ) ); 248 srand( time( NULL ) );
249 249
250 BenchmarkPaintWidget bpw; 250 BenchmarkPaintWidget bpw;
251 251
252 int loops = 0; 252 int loops = 0;
253 253
254 while ( t.elapsed() < stop ) 254 while ( t.elapsed() < stop )
255 { 255 {
256 int k = rand() % 9; 256 int k = rand() % 9;
257 int s = rand() % 100; 257 int s = rand() % 100;
258 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 258 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
259 bpw.p.setFont( QFont( "Vera", s ) ); 259 bpw.p.setFont( QFont( "Vera", s ) );
260 bpw.p.drawText( rand() % w, rand() % h, text, text.length() ); 260 bpw.p.drawText( rand() % w, rand() % h, text, text.length() );
261 ++loops; 261 ++loops;
262 } 262 }
263 263
264 return loops * text.length(); 264 return loops * text.length();
265} 265}
266 266
267int BenchmarkInfo::gfxRendering( int seconds ) 267int BenchmarkInfo::gfxRendering( int seconds )
268{ 268{
269 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 }; 269 int rr[] = { 255, 255, 255, 0, 0, 0, 0, 128, 128 };
270 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 }; 270 int gg[] = { 0, 255, 0, 0, 255, 255, 0, 128, 128 };
271 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 }; 271 int bb[] = { 0, 0, 255, 0, 0, 255, 255, 128, 0 };
272 272
273 int w = QApplication::desktop()->width(); 273 int w = QApplication::desktop()->width();
274 int h = QApplication::desktop()->height(); 274 int h = QApplication::desktop()->height();
275 275
276 srand( time( NULL ) ); 276 srand( time( NULL ) );
277 277
278 BenchmarkPaintWidget bpw; 278 BenchmarkPaintWidget bpw;
279 279
280 QTime t; 280 QTime t;
281 t.start(); 281 t.start();
282 int stop = t.elapsed() + seconds*1000; 282 int stop = t.elapsed() + seconds*1000;
283 int loops = 0; 283 int loops = 0;
284 284
285 while ( t.elapsed() < stop ) 285 while ( t.elapsed() < stop )
286 { 286 {
287 int k = rand() % 9; 287 int k = rand() % 9;
288 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 288 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
289 bpw.p.drawLine( rand()%w, rand()%h, rand()%w, rand()%h ); 289 bpw.p.drawLine( rand()%w, rand()%h, rand()%w, rand()%h );
290 ++loops; 290 ++loops;
291 } 291 }
292 292
293 t.restart(); 293 t.restart();
294 stop = t.elapsed() + seconds*1000; 294 stop = t.elapsed() + seconds*1000;
295 295
296 while ( t.elapsed() < stop ) 296 while ( t.elapsed() < stop )
297 { 297 {
298 int k = rand() % 9; 298 int k = rand() % 9;
299 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 299 bpw.p.setPen( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
300 bpw.p.drawArc( rand()%w, rand()%h, rand()%w, rand()%h, 360 * 16, 360 * 16 ); 300 bpw.p.drawArc( rand()%w, rand()%h, rand()%w, rand()%h, 360 * 16, 360 * 16 );
301 ++loops; 301 ++loops;
302 } 302 }
303 303
304 QBrush br1; 304 QBrush br1;
305 br1.setStyle( SolidPattern ); 305 br1.setStyle( SolidPattern );
306 t.restart(); 306 t.restart();
307 stop = t.elapsed() + seconds*1000; 307 stop = t.elapsed() + seconds*1000;
308 308
309 while ( t.elapsed() < stop ) 309 while ( t.elapsed() < stop )
310 { 310 {
311 int k = rand() % 9; 311 int k = rand() % 9;
312 br1.setColor( QColor( rr[ k ], gg[ k ], bb[ k ] ) ); 312 br1.setColor( QColor( rr[ k ], gg[ k ], bb[ k ] ) );
313 bpw.p.fillRect( rand()%w, rand()%h, rand()%w, rand()%h, br1 ); 313 bpw.p.fillRect( rand()%w, rand()%h, rand()%w, rand()%h, br1 );
314 ++loops; 314 ++loops;
315 } 315 }
316 316
317 QPixmap p = Resource::loadPixmap( "sysinfo/pattern" ); 317 QPixmap p = Resource::loadPixmap( "sysinfo/pattern" );
318 t.restart(); 318 t.restart();
319 stop = t.elapsed() + seconds*1000; 319 stop = t.elapsed() + seconds*1000;
320 320
321 while ( t.elapsed() < stop ) 321 while ( t.elapsed() < stop )
322 { 322 {
323 bpw.p.drawPixmap( rand()%w, rand()%h, p ); 323 bpw.p.drawPixmap( rand()%w, rand()%h, p );
324 ++loops; 324 ++loops;
325 } 325 }
326 326
327 return loops; 327 return loops;
328 328
329} 329}
330 330
331void BenchmarkInfo::performFileTest( const QString& fname, QCheckListItem* item ) 331void BenchmarkInfo::performFileTest( const QString& fname, QCheckListItem* item )
332{ 332{
333 QTime time; 333 QTime time;
334 time.start(); 334 time.start();
335 if ( writeFile( fname ) && 335 if ( writeFile( fname ) &&
336 readFile( fname ) ) 336 readFile( fname ) )
337 { 337 {
338 QFile::remove( fname ); 338 QFile::remove( fname );
339 item->setText( 1, QString( "%1 kb/sec" ).arg( QString::number( 1024.0 / ( time.elapsed() / 1000.0 ) ) ) ); 339 item->setText( 1, QString( "%1 kb/sec" ).arg( QString::number( 1024.0 / ( time.elapsed() / 1000.0 ) ) ) );
340 item->setOn( false ); 340 item->setOn( false );
341 } 341 }
342 else 342 else
343 { 343 {
344 item->setText( 1, tr( "error" ) ); 344 item->setText( 1, tr( "error" ) );
345 } 345 }
346} 346}
347 347
348char FileBuf[ BUFF_SIZE + 1 ]; 348char FileBuf[ BUFF_SIZE + 1 ];
349 349
350bool BenchmarkInfo::writeFile( const QString& w_path ) 350bool BenchmarkInfo::writeFile( const QString& w_path )
351{ 351{
352 int i; 352 int i;
353 int k; 353 int k;
354 int n; 354 int n;
355 int pos; 355 int pos;
356 int len; 356 int len;
357 char *data = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 62 357 char *data = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 62
358 358
359 359
360 // /*------------------------------------ 360 // /*------------------------------------
361 int w_len; 361 int w_len;
362 362
363 QFile writeFile( w_path ); 363 QFile writeFile( w_path );
364 srand( time( NULL ) ); 364 srand( time( NULL ) );
365 365
366 for ( n = 0 ; n < 20 ; n++ ) 366 for ( n = 0 ; n < 20 ; n++ )
367 { 367 {
368 if ( ! writeFile.open( IO_WriteOnly ) ) 368 if ( ! writeFile.open( IO_WriteOnly ) )
369 { 369 {
370 writeFile.close(); 370 writeFile.close();
371 writeFile.remove(); 371 writeFile.remove();
372 return ( false ); 372 return ( false );
373 } 373 }
374 // ------------------------------------------ sequential write 374 // ------------------------------------------ sequential write
375 for ( k = 0 ; k < 256 ; k++ ) 375 for ( k = 0 ; k < 256 ; k++ )
376 { 376 {
377 n = rand() % 30; 377 n = rand() % 30;
378 memcpy( &FileBuf[ k * 32 ], &data[ n ], 32 ); 378 memcpy( &FileBuf[ k * 32 ], &data[ n ], 32 );
379 } 379 }
380 380
381 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ ) 381 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ )
382 { 382 {
383 w_len = writeFile.writeBlock( FileBuf, BUFF_SIZE ); 383 w_len = writeFile.writeBlock( FileBuf, BUFF_SIZE );
384 if ( w_len != BUFF_SIZE ) 384 if ( w_len != BUFF_SIZE )
385 { 385 {
386 writeFile.close(); 386 writeFile.close();
387 writeFile.remove(); 387 writeFile.remove();
388 return ( false ); 388 return ( false );
389 } 389 }
390 writeFile.flush(); 390 writeFile.flush();
391 } 391 }
392 // ------------------------------------------ random write 392 // ------------------------------------------ random write
393 for ( i = 0 ; i < 400 ; i++ ) 393 for ( i = 0 ; i < 400 ; i++ )
394 { 394 {
395 len = rand() % 90 + 4000; 395 len = rand() % 90 + 4000;
396 for ( k = 0 ; k < 128 ; k++ ) 396 for ( k = 0 ; k < 128 ; k++ )
397 { 397 {
398 n = rand() % 30; 398 n = rand() % 30;
399 memcpy( &FileBuf[ k * 8 ], &data[ n ], 32 ); 399 memcpy( &FileBuf[ k * 8 ], &data[ n ], 32 );
400 } 400 }
401 pos = rand() % ( FILE_SIZE - BUFF_SIZE ); 401 pos = rand() % ( FILE_SIZE - BUFF_SIZE );
402 402
403 writeFile.at( pos ); 403 writeFile.at( pos );
404 w_len = writeFile.writeBlock( FileBuf, len ); 404 w_len = writeFile.writeBlock( FileBuf, len );
405 if ( w_len != len ) 405 if ( w_len != len )
406 { 406 {
407 writeFile.close(); 407 writeFile.close();
408 writeFile.remove(); 408 writeFile.remove();
409 return ( false ); 409 return ( false );
410 } 410 }
411 writeFile.flush(); 411 writeFile.flush();
412 } 412 }
413 writeFile.close(); 413 writeFile.close();
414 } 414 }
415 return ( true ); 415 return ( true );
416 416
417} 417}
418 418
419 419
420bool BenchmarkInfo::readFile( const QString& r_path ) 420bool BenchmarkInfo::readFile( const QString& r_path )
421{ 421{
422 int i; 422 int i;
423 int k; 423 int k;
424 int len; 424 int len;
425 int pos; 425 int pos;
426 int r_len; 426 int r_len;
427 427
428 QFile readFile( r_path ); 428 QFile readFile( r_path );
429 srand( time( NULL ) ); 429 srand( time( NULL ) );
430 430
431 for ( k = 0 ; k < 200 ; k++ ) 431 for ( k = 0 ; k < 200 ; k++ )
432 { 432 {
433 if ( ! readFile.open( IO_ReadOnly ) ) 433 if ( ! readFile.open( IO_ReadOnly ) )
434 { 434 {
435 readFile.remove(); 435 readFile.remove();
436 return ( false ); 436 return ( false );
437 } 437 }
438 // ------------------------------------------ sequential read 438 // ------------------------------------------ sequential read
439 readFile.at( 0 ); 439 readFile.at( 0 );
440 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ ) 440 for ( i = 0 ; i < FILE_SIZE / BUFF_SIZE ; i++ )
441 { 441 {
442 readFile.at( i * BUFF_SIZE ); 442 readFile.at( i * BUFF_SIZE );
443 r_len = readFile.readBlock( FileBuf, BUFF_SIZE ); 443 r_len = readFile.readBlock( FileBuf, BUFF_SIZE );
444 if ( r_len != BUFF_SIZE ) 444 if ( r_len != BUFF_SIZE )
445 { 445 {
446 readFile.close(); 446 readFile.close();
447 readFile.remove(); 447 readFile.remove();
448 return ( false ); 448 return ( false );
449 } 449 }
450 } 450 }
451 // ------------------------------------------ random read 451 // ------------------------------------------ random read
452 for ( i = 0 ; i < 1000 ; i++ ) 452 for ( i = 0 ; i < 1000 ; i++ )
453 { 453 {
454 len = rand() % 120 + 8; 454 len = rand() % 120 + 8;
455 pos = rand() % ( FILE_SIZE / BUFF_SIZE - BUFF_SIZE ); 455 pos = rand() % ( FILE_SIZE / BUFF_SIZE - BUFF_SIZE );
456 readFile.at( pos ); 456 readFile.at( pos );
457 r_len = readFile.readBlock( FileBuf, len ); 457 r_len = readFile.readBlock( FileBuf, len );
458 if ( r_len != len ) 458 if ( r_len != len )
459 { 459 {
460 readFile.close(); 460 readFile.close();
461 readFile.remove(); 461 readFile.remove();
462 return ( false ); 462 return ( false );
463 } 463 }
464 } 464 }
465 readFile.close(); 465 readFile.close();
466 } 466 }
467 return ( true ); 467 return ( true );
468} 468}
diff --git a/noncore/settings/sysinfo/modulesinfo.cpp b/noncore/settings/sysinfo/modulesinfo.cpp
index 9cb8ad2..e688a29 100644
--- a/noncore/settings/sysinfo/modulesinfo.cpp
+++ b/noncore/settings/sysinfo/modulesinfo.cpp
@@ -1,190 +1,190 @@
1/********************************************************************** 1/**********************************************************************
2** ModulesInfo 2** ModulesInfo
3** 3**
4** Display Modules information 4** Display Modules information
5** 5**
6** Copyright (C) 2002, Michael Lauer 6** Copyright (C) 2002, Michael Lauer
7** mickey@tm.informatik.uni-frankfurt.de 7** mickey@tm.informatik.uni-frankfurt.de
8** http://www.Vanille.de 8** http://www.Vanille.de
9** 9**
10** Based on ProcessInfo by Dan Williams <williamsdr@acm.org> 10** Based on ProcessInfo by Dan Williams <williamsdr@acm.org>
11** 11**
12** This file may be distributed and/or modified under the terms of the 12** This file may be distributed and/or modified under the terms of the
13** GNU General Public License version 2 as published by the Free Software 13** GNU General Public License version 2 as published by the Free Software
14** Foundation and appearing in the file LICENSE.GPL included in the 14** Foundation and appearing in the file LICENSE.GPL included in the
15** packaging of this file. 15** packaging of this file.
16** 16**
17** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 17** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
18** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 18** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19** 19**
20**********************************************************************/ 20**********************************************************************/
21 21
22#include "modulesinfo.h" 22#include "modulesinfo.h"
23#include "detail.h" 23#include "detail.h"
24 24
25/* OPIE */ 25/* OPIE */
26#include <qpe/qpeapplication.h> 26#include <qpe/qpeapplication.h>
27 27
28/* QT */ 28/* QT */
29#include <qfile.h> 29#include <qfile.h>
30#include <qlayout.h> 30#include <qlayout.h>
31#include <qmessagebox.h> 31#include <qmessagebox.h>
32#include <qtimer.h> 32#include <qtimer.h>
33#include <qwhatsthis.h> 33#include <qwhatsthis.h>
34 34
35ModulesInfo::ModulesInfo( QWidget* parent, const char* name, WFlags fl ) 35ModulesInfo::ModulesInfo( QWidget* parent, const char* name, WFlags fl )
36 : QWidget( parent, name, fl ) 36 : QWidget( parent, name, fl )
37{ 37{
38 QGridLayout *layout = new QGridLayout( this ); 38 QGridLayout *layout = new QGridLayout( this );
39 layout->setSpacing( 4 ); 39 layout->setSpacing( 4 );
40 layout->setMargin( 4 ); 40 layout->setMargin( 4 );
41 41
42 ModulesView = new QListView( this ); 42 ModulesView = new QListView( this );
43 int colnum = ModulesView->addColumn( tr( "Module" ) ); 43 int colnum = ModulesView->addColumn( tr( "Module" ) );
44 colnum = ModulesView->addColumn( tr( "Size" ) ); 44 colnum = ModulesView->addColumn( tr( "Size" ) );
45 ModulesView->setColumnAlignment( colnum, Qt::AlignRight ); 45 ModulesView->setColumnAlignment( colnum, Qt::AlignRight );
46 colnum = ModulesView->addColumn( tr( "Use#" ) ); 46 colnum = ModulesView->addColumn( tr( "Use#" ) );
47 ModulesView->setColumnAlignment( colnum, Qt::AlignRight ); 47 ModulesView->setColumnAlignment( colnum, Qt::AlignRight );
48 colnum = ModulesView->addColumn( tr( "Used by" ) ); 48 colnum = ModulesView->addColumn( tr( "Used by" ) );
49 ModulesView->setAllColumnsShowFocus( TRUE ); 49 ModulesView->setAllColumnsShowFocus( TRUE );
50 layout->addMultiCellWidget( ModulesView, 0, 0, 0, 1 ); 50 layout->addMultiCellWidget( ModulesView, 0, 0, 0, 1 );
51 QWhatsThis::add( ModulesView, tr( "This is a list of all the kernel modules currently loaded on this handheld device.\n\nClick and hold on a module to see additional information about the module, or to unload it." ) ); 51 QWhatsThis::add( ModulesView, tr( "This is a list of all the kernel modules currently loaded on this handheld device.\n\nClick and hold on a module to see additional information about the module, or to unload it." ) );
52 52
53 // Test if we have /sbin/modinfo, and if so, allow module detail window 53 // Test if we have /sbin/modinfo, and if so, allow module detail window
54 if ( QFile::exists( "/sbin/modinfo" ) ) 54 if ( QFile::exists( "/sbin/modinfo" ) )
55 { 55 {
56 QPEApplication::setStylusOperation( ModulesView->viewport(), QPEApplication::RightOnHold ); 56 QPEApplication::setStylusOperation( ModulesView->viewport(), QPEApplication::RightOnHold );
57 connect( ModulesView, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), 57 connect( ModulesView, SIGNAL( rightButtonPressed(QListViewItem*,const QPoint&,int) ),
58 this, SLOT( viewModules( QListViewItem * ) ) ); 58 this, SLOT( viewModules(QListViewItem*) ) );
59 } 59 }
60 60
61 CommandCB = new QComboBox( FALSE, this ); 61 CommandCB = new QComboBox( FALSE, this );
62 CommandCB->insertItem( "modprobe -r" ); 62 CommandCB->insertItem( "modprobe -r" );
63 CommandCB->insertItem( "rmmod" ); 63 CommandCB->insertItem( "rmmod" );
64 // I can't think of other useful commands yet. Anyone? 64 // I can't think of other useful commands yet. Anyone?
65 layout->addWidget( CommandCB, 1, 0 ); 65 layout->addWidget( CommandCB, 1, 0 );
66 QWhatsThis::add( CommandCB, tr( "Select a command here and then click the Send button to the right to send the command to module selected above." ) ); 66 QWhatsThis::add( CommandCB, tr( "Select a command here and then click the Send button to the right to send the command to module selected above." ) );
67 67
68 QPushButton *btn = new QPushButton( this ); 68 QPushButton *btn = new QPushButton( this );
69 btn->setMinimumSize( QSize( 50, 24 ) ); 69 btn->setMinimumSize( QSize( 50, 24 ) );
70 btn->setMaximumSize( QSize( 50, 24 ) ); 70 btn->setMaximumSize( QSize( 50, 24 ) );
71 btn->setText( tr( "Send" ) ); 71 btn->setText( tr( "Send" ) );
72 connect( btn, SIGNAL( clicked() ), this, SLOT( slotSendClicked() ) ); 72 connect( btn, SIGNAL( clicked() ), this, SLOT( slotSendClicked() ) );
73 layout->addWidget( btn, 1, 1 ); 73 layout->addWidget( btn, 1, 1 );
74 QWhatsThis::add( btn, tr( "Click here to send the selected command to the module selected above." ) ); 74 QWhatsThis::add( btn, tr( "Click here to send the selected command to the module selected above." ) );
75 75
76 QTimer *t = new QTimer( this ); 76 QTimer *t = new QTimer( this );
77 connect( t, SIGNAL( timeout() ), this, SLOT( updateData() ) ); 77 connect( t, SIGNAL( timeout() ), this, SLOT( updateData() ) );
78 t->start( 5000 ); 78 t->start( 5000 );
79 79
80 updateData(); 80 updateData();
81 81
82 ModulesDtl = new Detail(); 82 ModulesDtl = new Detail();
83 QWhatsThis::add( ModulesDtl->detailView, tr( "This area shows detailed information about this module." ) ); 83 QWhatsThis::add( ModulesDtl->detailView, tr( "This area shows detailed information about this module." ) );
84} 84}
85 85
86ModulesInfo::~ModulesInfo() 86ModulesInfo::~ModulesInfo()
87{} 87{}
88 88
89void ModulesInfo::updateData() 89void ModulesInfo::updateData()
90{ 90{
91 char modname[64]; 91 char modname[64];
92 char usage[200]; 92 char usage[200];
93 int modsize, usecount; 93 int modsize, usecount;
94 94
95 QString selectedmod; 95 QString selectedmod;
96 QListViewItem *curritem = ModulesView->currentItem(); 96 QListViewItem *curritem = ModulesView->currentItem();
97 if ( curritem ) 97 if ( curritem )
98 { 98 {
99 selectedmod = curritem->text( 0 ); 99 selectedmod = curritem->text( 0 );
100 } 100 }
101 101
102 ModulesView->clear(); 102 ModulesView->clear();
103 103
104 FILE *procfile = fopen( ( QString ) ( "/proc/modules"), "r"); 104 FILE *procfile = fopen( ( QString ) ( "/proc/modules"), "r");
105 105
106 if ( procfile ) 106 if ( procfile )
107 { 107 {
108 QListViewItem *newitem; 108 QListViewItem *newitem;
109 QListViewItem *selecteditem = 0x0; 109 QListViewItem *selecteditem = 0x0;
110 while ( true ) 110 while ( true )
111 { 111 {
112 modname[0] = '\0'; 112 modname[0] = '\0';
113 usage[0] = '\0'; 113 usage[0] = '\0';
114 int success = fscanf( procfile, "%s%d%d%[^\n]", modname, &modsize, &usecount, usage ); 114 int success = fscanf( procfile, "%s%d%d%[^\n]", modname, &modsize, &usecount, usage );
115 115
116 if ( success == EOF ) 116 if ( success == EOF )
117 break; 117 break;
118 118
119 QString qmodname = QString( modname ); 119 QString qmodname = QString( modname );
120 QString qmodsize = QString::number( modsize ).rightJustify( 6, ' ' ); 120 QString qmodsize = QString::number( modsize ).rightJustify( 6, ' ' );
121 QString qusecount = QString::number( usecount ).rightJustify( 2, ' ' ); 121 QString qusecount = QString::number( usecount ).rightJustify( 2, ' ' );
122 QString qusage = QString( usage ); 122 QString qusage = QString( usage );
123 123
124 newitem = new QListViewItem( ModulesView, qmodname, qmodsize, qusecount, qusage ); 124 newitem = new QListViewItem( ModulesView, qmodname, qmodsize, qusecount, qusage );
125 if ( qmodname == selectedmod ) 125 if ( qmodname == selectedmod )
126 { 126 {
127 selecteditem = newitem; 127 selecteditem = newitem;
128 } 128 }
129 } 129 }
130 ModulesView->setCurrentItem( selecteditem ); 130 ModulesView->setCurrentItem( selecteditem );
131 131
132 fclose( procfile ); 132 fclose( procfile );
133 } 133 }
134} 134}
135 135
136void ModulesInfo::slotSendClicked() 136void ModulesInfo::slotSendClicked()
137{ 137{
138 if ( !ModulesView->currentItem() ) 138 if ( !ModulesView->currentItem() )
139 { 139 {
140 return; 140 return;
141 } 141 }
142 142
143 QString capstr = tr( "You really want to execute %1 for this module?" ).arg( CommandCB->currentText() ); 143 QString capstr = tr( "You really want to execute %1 for this module?" ).arg( CommandCB->currentText() );
144 144
145 QString modname = ModulesView->currentItem()->text( 0 ); 145 QString modname = ModulesView->currentItem()->text( 0 );
146 146
147 if ( QMessageBox::warning( this, modname, capstr, 147 if ( QMessageBox::warning( this, modname, capstr,
148 QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::Yes ) 148 QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::Yes )
149 { 149 {
150 QString command = "/sbin/"; 150 QString command = "/sbin/";
151 command.append( CommandCB->currentText() ); 151 command.append( CommandCB->currentText() );
152 command.append( " " ); 152 command.append( " " );
153 command.append( modname ); 153 command.append( modname );
154 154
155 FILE* stream = popen( command, "r" ); 155 FILE* stream = popen( command, "r" );
156 if ( stream ) 156 if ( stream )
157 pclose( stream ); 157 pclose( stream );
158 } 158 }
159 159
160} 160}
161 161
162void ModulesInfo::viewModules( QListViewItem *modules ) 162void ModulesInfo::viewModules( QListViewItem *modules )
163{ 163{
164 QString modname = modules->text( 0 ); 164 QString modname = modules->text( 0 );
165 QString capstr = "Module: "; 165 QString capstr = "Module: ";
166 capstr.append( modname ); 166 capstr.append( modname );
167 ModulesDtl->setCaption( capstr ); 167 ModulesDtl->setCaption( capstr );
168 QString command = "/sbin/modinfo "; 168 QString command = "/sbin/modinfo ";
169 command.append( modname ); 169 command.append( modname );
170 FILE* modinfo = popen( command, "r" ); 170 FILE* modinfo = popen( command, "r" );
171 171
172 if ( modinfo ) 172 if ( modinfo )
173 { 173 {
174 char line[200]; 174 char line[200];
175 ModulesDtl->detailView->setText( " Details:\n------------\n" ); 175 ModulesDtl->detailView->setText( " Details:\n------------\n" );
176 176
177 while( true ) 177 while( true )
178 { 178 {
179 int success = fscanf( modinfo, "%[^\n]\n", line ); 179 int success = fscanf( modinfo, "%[^\n]\n", line );
180 if ( success == EOF ) 180 if ( success == EOF )
181 break; 181 break;
182 ModulesDtl->detailView->append( line ); 182 ModulesDtl->detailView->append( line );
183 } 183 }
184 184
185 pclose( modinfo ); 185 pclose( modinfo );
186 } 186 }
187 187
188 QPEApplication::showWidget( ModulesDtl ); 188 QPEApplication::showWidget( ModulesDtl );
189} 189}
190 190
diff --git a/noncore/settings/sysinfo/processinfo.cpp b/noncore/settings/sysinfo/processinfo.cpp
index 2a90b0f..69b4ab5 100644
--- a/noncore/settings/sysinfo/processinfo.cpp
+++ b/noncore/settings/sysinfo/processinfo.cpp
@@ -1,202 +1,202 @@
1/********************************************************************** 1/**********************************************************************
2** ProcessInfo 2** ProcessInfo
3** 3**
4** Display process information 4** Display process information
5** 5**
6** Copyright (C) 2002, Dan Williams 6** Copyright (C) 2002, Dan Williams
7** williamsdr@acm.org 7** williamsdr@acm.org
8** http://draknor.net 8** http://draknor.net
9** 9**
10** This file may be distributed and/or modified under the terms of the 10** This file may be distributed and/or modified under the terms of the
11** GNU General Public License version 2 as published by the Free Software 11** GNU General Public License version 2 as published by the Free Software
12** Foundation and appearing in the file LICENSE.GPL included in the 12** Foundation and appearing in the file LICENSE.GPL included in the
13** packaging of this file. 13** packaging of this file.
14** 14**
15** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 15** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 16** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
17** 17**
18**********************************************************************/ 18**********************************************************************/
19 19
20#include "processinfo.h" 20#include "processinfo.h"
21#include "detail.h" 21#include "detail.h"
22 22
23/* OPIE */ 23/* OPIE */
24#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25 25
26/* QT */ 26/* QT */
27#include <qdir.h> 27#include <qdir.h>
28#include <qlayout.h> 28#include <qlayout.h>
29#include <qmessagebox.h> 29#include <qmessagebox.h>
30#include <qtimer.h> 30#include <qtimer.h>
31#include <qwhatsthis.h> 31#include <qwhatsthis.h>
32 32
33/* STD */ 33/* STD */
34#include <sys/types.h> 34#include <sys/types.h>
35#include <signal.h> 35#include <signal.h>
36 36
37ProcessInfo::ProcessInfo( QWidget* parent, const char* name, WFlags fl ) 37ProcessInfo::ProcessInfo( QWidget* parent, const char* name, WFlags fl )
38 : QWidget( parent, name, fl ) 38 : QWidget( parent, name, fl )
39{ 39{
40 QGridLayout *layout = new QGridLayout( this ); 40 QGridLayout *layout = new QGridLayout( this );
41 layout->setSpacing( 4 ); 41 layout->setSpacing( 4 );
42 layout->setMargin( 4 ); 42 layout->setMargin( 4 );
43 43
44 44
45 ProcessView = new QListView( this, "ProcessView" ); 45 ProcessView = new QListView( this, "ProcessView" );
46 int colnum = ProcessView->addColumn( tr( "PID" ) ); 46 int colnum = ProcessView->addColumn( tr( "PID" ) );
47 ProcessView->setColumnAlignment( colnum, Qt::AlignRight ); 47 ProcessView->setColumnAlignment( colnum, Qt::AlignRight );
48 colnum = ProcessView->addColumn( tr( "Command" ),96 ); 48 colnum = ProcessView->addColumn( tr( "Command" ),96 );
49 colnum = ProcessView->addColumn( tr( "Status" ) ); 49 colnum = ProcessView->addColumn( tr( "Status" ) );
50 colnum = ProcessView->addColumn( tr( "Time" ) ); 50 colnum = ProcessView->addColumn( tr( "Time" ) );
51 ProcessView->setColumnAlignment( colnum, Qt::AlignRight ); 51 ProcessView->setColumnAlignment( colnum, Qt::AlignRight );
52 ProcessView->setAllColumnsShowFocus( TRUE ); 52 ProcessView->setAllColumnsShowFocus( TRUE );
53 QPEApplication::setStylusOperation( ProcessView->viewport(), QPEApplication::RightOnHold ); 53 QPEApplication::setStylusOperation( ProcessView->viewport(), QPEApplication::RightOnHold );
54 connect( ProcessView, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), 54 connect( ProcessView, SIGNAL( rightButtonPressed(QListViewItem*,const QPoint&,int) ),
55 this, SLOT( viewProcess( QListViewItem * ) ) ); 55 this, SLOT( viewProcess(QListViewItem*) ) );
56 layout->addMultiCellWidget( ProcessView, 0, 0, 0, 1 ); 56 layout->addMultiCellWidget( ProcessView, 0, 0, 0, 1 );
57 QWhatsThis::add( ProcessView, tr( "This is a list of all the processes on this handheld device.\n\nClick and hold on a process to see additional information about the process, or to send a signal to it." ) ); 57 QWhatsThis::add( ProcessView, tr( "This is a list of all the processes on this handheld device.\n\nClick and hold on a process to see additional information about the process, or to send a signal to it." ) );
58 58
59 SignalCB = new QComboBox( FALSE, this, "SignalCB" ); 59 SignalCB = new QComboBox( FALSE, this, "SignalCB" );
60 SignalCB->insertItem( " 1: SIGHUP" ); 60 SignalCB->insertItem( " 1: SIGHUP" );
61 SignalCB->insertItem( " 2: SIGINT" ); 61 SignalCB->insertItem( " 2: SIGINT" );
62 SignalCB->insertItem( " 3: SIGQUIT" ); 62 SignalCB->insertItem( " 3: SIGQUIT" );
63 SignalCB->insertItem( " 5: SIGTRAP" ); 63 SignalCB->insertItem( " 5: SIGTRAP" );
64 SignalCB->insertItem( " 6: SIGABRT" ); 64 SignalCB->insertItem( " 6: SIGABRT" );
65 SignalCB->insertItem( " 9: SIGKILL" ); 65 SignalCB->insertItem( " 9: SIGKILL" );
66 SignalCB->insertItem( "14: SIGALRM" ); 66 SignalCB->insertItem( "14: SIGALRM" );
67 SignalCB->insertItem( "15: SIGTERM" ); 67 SignalCB->insertItem( "15: SIGTERM" );
68 SignalCB->insertItem( "18: SIGCONT" ); 68 SignalCB->insertItem( "18: SIGCONT" );
69 SignalCB->insertItem( "19: SIGSTOP" ); 69 SignalCB->insertItem( "19: SIGSTOP" );
70 layout->addWidget( SignalCB, 1, 0 ); 70 layout->addWidget( SignalCB, 1, 0 );
71 QWhatsThis::add( SignalCB, tr( "Select a signal here and then click the Send button to the right to send to this process." ) ); 71 QWhatsThis::add( SignalCB, tr( "Select a signal here and then click the Send button to the right to send to this process." ) );
72 72
73 SendButton = new QPushButton( this, "SendButton" ); 73 SendButton = new QPushButton( this, "SendButton" );
74 SendButton->setMinimumSize( QSize( 50, 24 ) ); 74 SendButton->setMinimumSize( QSize( 50, 24 ) );
75 SendButton->setMaximumSize( QSize( 50, 24 ) ); 75 SendButton->setMaximumSize( QSize( 50, 24 ) );
76 SendButton->setText( tr( "Send" ) ); 76 SendButton->setText( tr( "Send" ) );
77 connect( SendButton, SIGNAL( clicked() ), this, SLOT( slotSendClicked() ) ); 77 connect( SendButton, SIGNAL( clicked() ), this, SLOT( slotSendClicked() ) );
78 layout->addWidget( SendButton, 1, 1 ); 78 layout->addWidget( SendButton, 1, 1 );
79 QWhatsThis::add( SendButton, tr( "Click here to send the selected signal to this process." ) ); 79 QWhatsThis::add( SendButton, tr( "Click here to send the selected signal to this process." ) );
80 80
81 QTimer *t = new QTimer( this ); 81 QTimer *t = new QTimer( this );
82 connect( t, SIGNAL( timeout() ), this, SLOT( updateData() ) ); 82 connect( t, SIGNAL( timeout() ), this, SLOT( updateData() ) );
83 t->start( 5000 ); 83 t->start( 5000 );
84 84
85 updateData(); 85 updateData();
86 86
87 ProcessDtl = new Detail(); 87 ProcessDtl = new Detail();
88 QWhatsThis::add( ProcessDtl->detailView, tr( "This area shows detailed information about this process." ) ); 88 QWhatsThis::add( ProcessDtl->detailView, tr( "This area shows detailed information about this process." ) );
89} 89}
90 90
91ProcessInfo::~ProcessInfo() 91ProcessInfo::~ProcessInfo()
92{} 92{}
93 93
94void ProcessInfo::updateData() 94void ProcessInfo::updateData()
95{ 95{
96 int pid, ppid, pgrp, session, tty, tpgid, utime, stime, cutime, cstime, counter, priority, starttime, 96 int pid, ppid, pgrp, session, tty, tpgid, utime, stime, cutime, cstime, counter, priority, starttime,
97 signal, blocked, sigignore, sigcatch; 97 signal, blocked, sigignore, sigcatch;
98 uint flags, minflt, cminflt, majflt, cmajflt, timeout, itrealvalue, vsize, rss, rlim, startcode, 98 uint flags, minflt, cminflt, majflt, cmajflt, timeout, itrealvalue, vsize, rss, rlim, startcode,
99 endcode, startstack, kstkesp, kstkeip, wchan; 99 endcode, startstack, kstkesp, kstkeip, wchan;
100 char state; 100 char state;
101 char comm[64]; 101 char comm[64];
102 102
103 QString selectedpid; 103 QString selectedpid;
104 QListViewItem *curritem = ProcessView->currentItem(); 104 QListViewItem *curritem = ProcessView->currentItem();
105 if ( curritem ) 105 if ( curritem )
106 { 106 {
107 selectedpid = curritem->text( 0 ); 107 selectedpid = curritem->text( 0 );
108 } 108 }
109 109
110 ProcessView->clear(); 110 ProcessView->clear();
111 111
112 QListViewItem *newitem; 112 QListViewItem *newitem;
113 QListViewItem *selecteditem = 0x0; 113 QListViewItem *selecteditem = 0x0;
114 QDir *procdir = new QDir("/proc", 0, QDir::Name, QDir::Dirs); 114 QDir *procdir = new QDir("/proc", 0, QDir::Name, QDir::Dirs);
115 QFileInfoList *proclist = new QFileInfoList(*(procdir->entryInfoList())); 115 QFileInfoList *proclist = new QFileInfoList(*(procdir->entryInfoList()));
116 if ( proclist ) 116 if ( proclist )
117 { 117 {
118 QFileInfoListIterator it(*proclist); 118 QFileInfoListIterator it(*proclist);
119 QFileInfo *f; 119 QFileInfo *f;
120 while ( ( f = it.current() ) != 0 ) 120 while ( ( f = it.current() ) != 0 )
121 { 121 {
122 ++it; 122 ++it;
123 QString processnum = f->fileName(); 123 QString processnum = f->fileName();
124 if ( processnum >= "1" && processnum <= "99999" ) 124 if ( processnum >= "1" && processnum <= "99999" )
125 { 125 {
126 FILE *procfile = fopen( ( QString ) ( "/proc/" + processnum + "/stat"), "r"); 126 FILE *procfile = fopen( ( QString ) ( "/proc/" + processnum + "/stat"), "r");
127 127
128 if ( procfile ) 128 if ( procfile )
129 { 129 {
130 fscanf( procfile, 130 fscanf( procfile,
131 "%d %s %c %d %d %d %d %d %u %u %u %u %u %d %d %d %d %d %d %u %u %d %u %u %u %u %u %u %u %u %d %d %d %d %u", 131 "%d %s %c %d %d %d %d %d %u %u %u %u %u %d %d %d %d %d %d %u %u %d %u %u %u %u %u %u %u %u %d %d %d %d %u",
132 &pid, comm, &state, &ppid, &pgrp, &session,&tty, &tpgid, &flags, &minflt, &cminflt, 132 &pid, comm, &state, &ppid, &pgrp, &session,&tty, &tpgid, &flags, &minflt, &cminflt,
133 &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &counter, &priority, &timeout, 133 &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &counter, &priority, &timeout,
134 &itrealvalue, &starttime, &vsize, &rss, &rlim, &startcode, &endcode, &startstack, 134 &itrealvalue, &starttime, &vsize, &rss, &rlim, &startcode, &endcode, &startstack,
135 &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan ); 135 &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan );
136 processnum = processnum.rightJustify( 5, ' ' ); 136 processnum = processnum.rightJustify( 5, ' ' );
137 QString processcmd = QString( comm ).replace( QRegExp( "[()]" ), "" ); 137 QString processcmd = QString( comm ).replace( QRegExp( "[()]" ), "" );
138 QString processstatus = QChar(state); 138 QString processstatus = QChar(state);
139 QString processtime = QString::number( ( utime + stime ) / 100 ); 139 QString processtime = QString::number( ( utime + stime ) / 100 );
140 processtime = processtime.rightJustify( 9, ' ' ); 140 processtime = processtime.rightJustify( 9, ' ' );
141 fclose( procfile ); 141 fclose( procfile );
142 142
143 newitem = new QListViewItem( ProcessView, processnum, processcmd, processstatus, processtime ); 143 newitem = new QListViewItem( ProcessView, processnum, processcmd, processstatus, processtime );
144 if ( processnum == selectedpid ) 144 if ( processnum == selectedpid )
145 { 145 {
146 selecteditem = newitem; 146 selecteditem = newitem;
147 } 147 }
148 } 148 }
149 } 149 }
150 } 150 }
151 ProcessView->setCurrentItem( selecteditem ); 151 ProcessView->setCurrentItem( selecteditem );
152 } 152 }
153 153
154 delete proclist; 154 delete proclist;
155 delete procdir; 155 delete procdir;
156} 156}
157 157
158void ProcessInfo::slotSendClicked() 158void ProcessInfo::slotSendClicked()
159{ 159{
160 QListViewItem *currprocess = ProcessView->currentItem(); 160 QListViewItem *currprocess = ProcessView->currentItem();
161 if ( !currprocess ) 161 if ( !currprocess )
162 { 162 {
163 return; 163 return;
164 } 164 }
165 165
166 QString capstr = tr( "Really want to send %1\nto this process?" ).arg( SignalCB->currentText() ); 166 QString capstr = tr( "Really want to send %1\nto this process?" ).arg( SignalCB->currentText() );
167 167
168 168
169 if ( QMessageBox::warning( this, currprocess->text( 1 ), capstr, 169 if ( QMessageBox::warning( this, currprocess->text( 1 ), capstr,
170 QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::Yes ) 170 QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::Yes )
171 { 171 {
172 currprocess = ProcessView->currentItem(); 172 currprocess = ProcessView->currentItem();
173 if ( currprocess ) 173 if ( currprocess )
174 { 174 {
175 QString sigstr = SignalCB->currentText(); 175 QString sigstr = SignalCB->currentText();
176 sigstr.truncate(2); 176 sigstr.truncate(2);
177 int sigid = sigstr.toUInt(); 177 int sigid = sigstr.toUInt();
178 kill( currprocess->text( 0 ).stripWhiteSpace().toUInt(), sigid ); 178 kill( currprocess->text( 0 ).stripWhiteSpace().toUInt(), sigid );
179 } 179 }
180 } 180 }
181 181
182} 182}
183 183
184void ProcessInfo::viewProcess( QListViewItem *process ) 184void ProcessInfo::viewProcess( QListViewItem *process )
185{ 185{
186 QString pid= process->text( 0 ).stripWhiteSpace(); 186 QString pid= process->text( 0 ).stripWhiteSpace();
187 QString command = process->text( 1 ); 187 QString command = process->text( 1 );
188 ProcessDtl->setCaption( pid + " - " + command ); 188 ProcessDtl->setCaption( pid + " - " + command );
189 FILE *statfile = fopen( ( QString ) ( "/proc/" + pid + "/status"), "r"); 189 FILE *statfile = fopen( ( QString ) ( "/proc/" + pid + "/status"), "r");
190 if ( statfile ) 190 if ( statfile )
191 { 191 {
192 char line[81]; 192 char line[81];
193 fgets( line, 81, statfile ); 193 fgets( line, 81, statfile );
194 ProcessDtl->detailView->setText( line ); 194 ProcessDtl->detailView->setText( line );
195 while ( fgets( line, 81, statfile ) ) 195 while ( fgets( line, 81, statfile ) )
196 { 196 {
197 ProcessDtl->detailView->append( line ); 197 ProcessDtl->detailView->append( line );
198 } 198 }
199 fclose( statfile ); 199 fclose( statfile );
200 } 200 }
201 QPEApplication::showWidget( ProcessDtl ); 201 QPEApplication::showWidget( ProcessDtl );
202} 202}
diff --git a/noncore/settings/tabmanager/tabmanager.cpp b/noncore/settings/tabmanager/tabmanager.cpp
index ff5957c..15aeaf5 100644
--- a/noncore/settings/tabmanager/tabmanager.cpp
+++ b/noncore/settings/tabmanager/tabmanager.cpp
@@ -1,508 +1,508 @@
1#include "tabmanager.h" 1#include "tabmanager.h"
2#include "app.h" 2#include "app.h"
3#include "wait.h" 3#include "wait.h"
4#include "tabapplnk.h" 4#include "tabapplnk.h"
5 5
6#include <qpe/applnk.h> 6#include <qpe/applnk.h>
7#include <qdir.h> 7#include <qdir.h>
8#include <qfile.h> 8#include <qfile.h>
9#include <qtextstream.h> 9#include <qtextstream.h>
10#include <qlistview.h> 10#include <qlistview.h>
11#include <qheader.h> 11#include <qheader.h>
12#include <qcombobox.h> 12#include <qcombobox.h>
13#include <qlineedit.h> 13#include <qlineedit.h>
14#include <qlabel.h> 14#include <qlabel.h>
15#include <qmessagebox.h> 15#include <qmessagebox.h>
16#include <stdlib.h> 16#include <stdlib.h>
17#include <qpe/qcopenvelope_qws.h> 17#include <qpe/qcopenvelope_qws.h>
18#include <qpe/qpeapplication.h> 18#include <qpe/qpeapplication.h>
19#include <qpe/resource.h> 19#include <qpe/resource.h>
20 20
21 21
22#define HOME_APP_DIR QPEApplication::qpeDir()+"/apps" 22#define HOME_APP_DIR QPEApplication::qpeDir()+"/apps"
23#define HOME_APP_INSTALL_DIR "/usr/lib/ipkg/info" 23#define HOME_APP_INSTALL_DIR "/usr/lib/ipkg/info"
24#define NEW_FOLDER "EmptyTab" 24#define NEW_FOLDER "EmptyTab"
25#define NEW_APPLICATION "NewApp" 25#define NEW_APPLICATION "NewApp"
26#define APPLICATION_EXTENSION ".desktop" 26#define APPLICATION_EXTENSION ".desktop"
27#define APPLICATION_EXTENSION_LENGTH 8 27#define APPLICATION_EXTENSION_LENGTH 8
28 28
29/** 29/**
30 * Constructor. Sets up signals. Performs initial scan of applications 30 * Constructor. Sets up signals. Performs initial scan of applications
31 * and tabs 31 * and tabs
32 */ 32 */
33TabManager::TabManager( QWidget* parent, const char* name):TabManagerBase(parent, name), changed(false), application(NULL){ 33TabManager::TabManager( QWidget* parent, const char* name):TabManagerBase(parent, name), changed(false), application(NULL){
34 rescanFolder(HOME_APP_DIR); 34 rescanFolder(HOME_APP_DIR);
35 35
36 // Connect the signals and slots 36 // Connect the signals and slots
37 connect(tabList, SIGNAL(doubleClicked(QListViewItem *)), this, SLOT(editItem(QListViewItem*))); 37 connect(tabList, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(editItem(QListViewItem*)));
38 (tabList->header())->hide(); 38 (tabList->header())->hide();
39 connect(tabList, SIGNAL(moveItem(QListViewItem *, QListViewItem *)), this, SLOT(moveApplication(QListViewItem *, QListViewItem *))); 39 connect(tabList, SIGNAL(moveItem(QListViewItem*,QListViewItem*)), this, SLOT(moveApplication(QListViewItem*,QListViewItem*)));
40} 40}
41 41
42/** 42/**
43 * If anything in the tab's have been changed then update the system or alert 43 * If anything in the tab's have been changed then update the system or alert
44 * the user. 44 * the user.
45 */ 45 */
46TabManager::~TabManager(){ 46TabManager::~TabManager(){
47 if(changed){ 47 if(changed){
48 // Prompt. 48 // Prompt.
49 //int answer = QMessageBox::warning(this, "Message", "Should your desktop be","Yes", "Cancel", 0, 1 ); 49 //int answer = QMessageBox::warning(this, "Message", "Should your desktop be","Yes", "Cancel", 0, 1 );
50 //if (answer) 50 //if (answer)
51 // return; 51 // return;
52 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 52 QCopEnvelope e("QPE/System", "linkChanged(QString)");
53 QString link; //we'll just send an empty string 53 QString link; //we'll just send an empty string
54 e << link; 54 e << link;
55 } 55 }
56} 56}
57 57
58/** 58/**
59 * Scans root directory for any tabs or applications. Will recursivly go down, 59 * Scans root directory for any tabs or applications. Will recursivly go down,
60 * but will not follow symlinks. 60 * but will not follow symlinks.
61 * @param directory - the directory to look in. 61 * @param directory - the directory to look in.
62 * @param parent - the parent to place any new tabs or apps into. If parent is 62 * @param parent - the parent to place any new tabs or apps into. If parent is
63 * NULL then the item is a tab and should be placed as a child of the window. 63 * NULL then the item is a tab and should be placed as a child of the window.
64 */ 64 */
65void TabManager::rescanFolder(QString directory, QListViewItem* parent){ 65void TabManager::rescanFolder(QString directory, QListViewItem* parent){
66 //qDebug(QString("rescanFolder: ") + directory.latin1()); 66 //qDebug(QString("rescanFolder: ") + directory.latin1());
67 67
68 QDir d; 68 QDir d;
69 d.setPath(directory); 69 d.setPath(directory);
70 // Show hidden files for .directories 70 // Show hidden files for .directories
71 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs); 71 d.setFilter( QDir::Files | QDir::Hidden | QDir::Dirs);
72 72
73 const QFileInfoList *list = d.entryInfoList(); 73 const QFileInfoList *list = d.entryInfoList();
74 QFileInfoListIterator it( *list ); // create list iterator 74 QFileInfoListIterator it( *list ); // create list iterator
75 QFileInfo *fi; // pointer for traversing 75 QFileInfo *fi; // pointer for traversing
76 76
77 while ( (fi=it.current()) ) { // for each file... 77 while ( (fi=it.current()) ) { // for each file...
78 // If it is a dir and not .. or . then add it as a tab and go down. 78 // If it is a dir and not .. or . then add it as a tab and go down.
79 if(fi->isDir()){ 79 if(fi->isDir()){
80 if(fi->fileName() != ".." && fi->fileName() != ".") { 80 if(fi->fileName() != ".." && fi->fileName() != ".") {
81 QListViewItem* newItem; 81 QListViewItem* newItem;
82 if(!parent) 82 if(!parent)
83 newItem = new QListViewItem(tabList, fi->fileName()); 83 newItem = new QListViewItem(tabList, fi->fileName());
84 else 84 else
85 newItem = new QListViewItem(parent, fi->fileName()); 85 newItem = new QListViewItem(parent, fi->fileName());
86 itemList.insert(newItem, directory + "/" + fi->fileName() + "/.directory" ); 86 itemList.insert(newItem, directory + "/" + fi->fileName() + "/.directory" );
87 rescanFolder(directory + "/" + fi->fileName(), newItem); 87 rescanFolder(directory + "/" + fi->fileName(), newItem);
88 } 88 }
89 } 89 }
90 else{ 90 else{
91 // it is a file, if not a .directory add to parent. 91 // it is a file, if not a .directory add to parent.
92 92
93 // Change parents name and icon to reflect icon. 93 // Change parents name and icon to reflect icon.
94 if(fi->fileName() == ".directory"){ 94 if(fi->fileName() == ".directory"){
95 AppLnk app(directory + "/" + fi->fileName()); 95 AppLnk app(directory + "/" + fi->fileName());
96 if(parent){ 96 if(parent){
97 parent->setPixmap(0,app.pixmap()); 97 parent->setPixmap(0,app.pixmap());
98 parent->setText(0, app.name()); 98 parent->setText(0, app.name());
99 } 99 }
100 } 100 }
101 else{ 101 else{
102 // Add any desktop files found. 102 // Add any desktop files found.
103 QListViewItem* newItem; 103 QListViewItem* newItem;
104 if(directory != HOME_APP_DIR){ 104 if(directory != HOME_APP_DIR){
105 if(!parent) 105 if(!parent)
106 newItem = new QListViewItem(tabList, fi->fileName()); 106 newItem = new QListViewItem(tabList, fi->fileName());
107 else 107 else
108 newItem = new QListViewItem(parent, fi->fileName()); 108 newItem = new QListViewItem(parent, fi->fileName());
109 if(fi->fileName().right(APPLICATION_EXTENSION_LENGTH) == APPLICATION_EXTENSION){ 109 if(fi->fileName().right(APPLICATION_EXTENSION_LENGTH) == APPLICATION_EXTENSION){
110 AppLnk app(directory + "/" + fi->fileName()); 110 AppLnk app(directory + "/" + fi->fileName());
111 newItem->setPixmap(0,app.pixmap()); 111 newItem->setPixmap(0,app.pixmap());
112 newItem->setText(0, app.name()); 112 newItem->setText(0, app.name());
113 itemList.insert(newItem, directory + "/" + fi->fileName()); 113 itemList.insert(newItem, directory + "/" + fi->fileName());
114 } 114 }
115 } 115 }
116 } 116 }
117 } 117 }
118 ++it; // goto next list element 118 ++it; // goto next list element
119 } 119 }
120} 120}
121 121
122/** 122/**
123 * Create a new blank Tab. 123 * Create a new blank Tab.
124 * Create a physical folder with .directory file 124 * Create a physical folder with .directory file
125 * Create a item on the list 125 * Create a item on the list
126 */ 126 */
127void TabManager::newFolder(){ 127void TabManager::newFolder(){
128 QDir r; 128 QDir r;
129 r.mkdir(QString(HOME_APP_DIR) + "/" + NEW_FOLDER); 129 r.mkdir(QString(HOME_APP_DIR) + "/" + NEW_FOLDER);
130 system((QString("echo [Desktop Entry] | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1()); 130 system((QString("echo [Desktop Entry] | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1());
131 system((QString("echo Name=" NEW_FOLDER " | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1()); 131 system((QString("echo Name=" NEW_FOLDER " | cat >> ") + HOME_APP_DIR + "/" + NEW_FOLDER "/.directory").latin1());
132 132
133 QString homeLocation = QString(HOME_APP_DIR) + "/" + NEW_FOLDER + "/.directory"; 133 QString homeLocation = QString(HOME_APP_DIR) + "/" + NEW_FOLDER + "/.directory";
134 QListViewItem *newItem = new QListViewItem(tabList, NEW_FOLDER); 134 QListViewItem *newItem = new QListViewItem(tabList, NEW_FOLDER);
135 itemList.insert(newItem, homeLocation ); 135 itemList.insert(newItem, homeLocation );
136 136
137 // We have changed something. 137 // We have changed something.
138 changed = true; 138 changed = true;
139} 139}
140 140
141/** 141/**
142 * Create a new blank application 142 * Create a new blank application
143 * Make sure a tab is selected 143 * Make sure a tab is selected
144 * create physical file 144 * create physical file
145 * fill file with default information (entry, name, type). 145 * fill file with default information (entry, name, type).
146 */ 146 */
147void TabManager::newApplication(){ 147void TabManager::newApplication(){
148 QListViewItem *item = tabList->currentItem(); 148 QListViewItem *item = tabList->currentItem();
149 if(!item || item->parent()) 149 if(!item || item->parent())
150 return; 150 return;
151 151
152 QString parentDir = itemList[item].mid(0,itemList[item].length()-11); 152 QString parentDir = itemList[item].mid(0,itemList[item].length()-11);
153 QString homeLocation = parentDir + "/" NEW_APPLICATION APPLICATION_EXTENSION; 153 QString homeLocation = parentDir + "/" NEW_APPLICATION APPLICATION_EXTENSION;
154 system((QString("echo [Desktop Entry] | cat >> ") + homeLocation).latin1()); 154 system((QString("echo [Desktop Entry] | cat >> ") + homeLocation).latin1());
155 system((QString("echo Name=" NEW_APPLICATION " | cat >> ") + homeLocation).latin1()); 155 system((QString("echo Name=" NEW_APPLICATION " | cat >> ") + homeLocation).latin1());
156 int slash = parentDir.findRev('/', -1); 156 int slash = parentDir.findRev('/', -1);
157 QString folderName = parentDir.mid(slash+1, parentDir.length()); 157 QString folderName = parentDir.mid(slash+1, parentDir.length());
158 158
159 system((QString("echo Type=") + folderName + " | cat >> " + homeLocation).latin1()); 159 system((QString("echo Type=") + folderName + " | cat >> " + homeLocation).latin1());
160 160
161 // Insert into the tree 161 // Insert into the tree
162 QListViewItem *newItem = new QListViewItem(item, NEW_APPLICATION); 162 QListViewItem *newItem = new QListViewItem(item, NEW_APPLICATION);
163 itemList.insert(newItem, homeLocation ); 163 itemList.insert(newItem, homeLocation );
164 164
165 // We have changed something. 165 // We have changed something.
166 changed = true; 166 changed = true;
167} 167}
168 168
169/** 169/**
170 * Remove the item. 170 * Remove the item.
171 * Check if we can 171 * Check if we can
172 * Prompt user 172 * Prompt user
173 * Delete physical file (Dir, remove .dir, then dir. File, remove file) 173 * Delete physical file (Dir, remove .dir, then dir. File, remove file)
174 * Remove from installer if need too. 174 * Remove from installer if need too.
175 */ 175 */
176void TabManager::removeItem(){ 176void TabManager::removeItem(){
177 // Make sure we can delete 177 // Make sure we can delete
178 QListViewItem *item = tabList->currentItem(); 178 QListViewItem *item = tabList->currentItem();
179 if(!item) 179 if(!item)
180 return; 180 return;
181 if(item->childCount() > 0){ 181 if(item->childCount() > 0){
182 QMessageBox::critical(this, tr("Message"), tr("Can't remove with applications\nstill in the group."), tr("Ok") ); 182 QMessageBox::critical(this, tr("Message"), tr("Can't remove with applications\nstill in the group."), tr("Ok") );
183 return; 183 return;
184 } 184 }
185 185
186 // Prompt. 186 // Prompt.
187 int answer = QMessageBox::warning(this, tr("Message"), tr("Are you sure you want to delete?"), tr("Yes"), tr("Cancel"), 0, 1 ); 187 int answer = QMessageBox::warning(this, tr("Message"), tr("Are you sure you want to delete?"), tr("Yes"), tr("Cancel"), 0, 1 );
188 if (answer) 188 if (answer)
189 return; 189 return;
190 190
191 bool removeSuccessful = true; 191 bool removeSuccessful = true;
192 QString location = itemList[item]; 192 QString location = itemList[item];
193 // Remove file (.directory in a Directory case) 193 // Remove file (.directory in a Directory case)
194 if(!QFile::remove(location)) 194 if(!QFile::remove(location))
195 removeSuccessful = false; 195 removeSuccessful = false;
196 196
197 // Remove directory 197 // Remove directory
198 if(item->parent() == NULL){ 198 if(item->parent() == NULL){
199 // Remove .directory file string 199 // Remove .directory file string
200 location = location.mid(0,location.length()-10); 200 location = location.mid(0,location.length()-10);
201 QDir dir; 201 QDir dir;
202 if(!dir.rmdir(location)) 202 if(!dir.rmdir(location))
203 removeSuccessful = false; 203 removeSuccessful = false;
204 else 204 else
205 removeSuccessful = true; 205 removeSuccessful = true;
206 } 206 }
207 207
208 // If removing failed. 208 // If removing failed.
209 if(!removeSuccessful){ 209 if(!removeSuccessful){
210 qDebug((QString("removeItem: ") + location).latin1()); 210 qDebug((QString("removeItem: ") + location).latin1());
211 QMessageBox::critical(this, tr("Message"), tr("Can't remove."), tr("Ok") ); 211 QMessageBox::critical(this, tr("Message"), tr("Can't remove."), tr("Ok") );
212 return; 212 return;
213 } 213 }
214 214
215 // Remove from the installer so it wont fail. 215 // Remove from the installer so it wont fail.
216 // Don't need to do this sense the current install uses rm -f so no error 216 // Don't need to do this sense the current install uses rm -f so no error
217 217
218 // Remove from the gui list. 218 // Remove from the gui list.
219 itemList.remove(item); 219 itemList.remove(item);
220 if(item->parent()) 220 if(item->parent())
221 item->parent()->takeItem(item); 221 item->parent()->takeItem(item);
222 delete item; 222 delete item;
223 223
224 // We have changed something. 224 // We have changed something.
225 changed = true; 225 changed = true;
226} 226}
227 227
228/** 228/**
229 * Helper function. Edits the current item. 229 * Helper function. Edits the current item.
230 * calls editItem with the currently selected item. 230 * calls editItem with the currently selected item.
231 */ 231 */
232void TabManager::editCurrentItem(){ 232void TabManager::editCurrentItem(){
233 editItem(tabList->currentItem()); 233 editItem(tabList->currentItem());
234} 234}
235 235
236/** 236/**
237 * Edit the item that is passed in. 237 * Edit the item that is passed in.
238 * Show application dialog and if anything changed 238 * Show application dialog and if anything changed
239 * @param item the item to edit. 239 * @param item the item to edit.
240 */ 240 */
241void TabManager::editItem( QListViewItem * item){ 241void TabManager::editItem( QListViewItem * item){
242 if(!item) 242 if(!item)
243 return; 243 return;
244 244
245 TabAppLnk app(itemList[item]); 245 TabAppLnk app(itemList[item]);
246 if(!app.isValid()){ 246 if(!app.isValid()){
247 qDebug(QString("editItem: Not a valid applnk file: ") + itemList[item].latin1()); 247 qDebug(QString("editItem: Not a valid applnk file: ") + itemList[item].latin1());
248 return; 248 return;
249 } 249 }
250 250
251 // Fill with all of the icons 251 // Fill with all of the icons
252 if(!application){ 252 if(!application){
253 Wait waitDialog(this, "Wait dialog"); 253 Wait waitDialog(this, "Wait dialog");
254 waitDialog.waitLabel->setText(tr("Gathering icons...")); 254 waitDialog.waitLabel->setText(tr("Gathering icons..."));
255 waitDialog.show(); 255 waitDialog.show();
256 qApp->processEvents(); 256 qApp->processEvents();
257 application = new AppEdit(this, "Application edit", true); 257 application = new AppEdit(this, "Application edit", true);
258 258
259 QDir d(QPEApplication::qpeDir() + "/pics/"); 259 QDir d(QPEApplication::qpeDir() + "/pics/");
260 d.setFilter( QDir::Files); 260 d.setFilter( QDir::Files);
261 261
262 const QFileInfoList *list = d.entryInfoList(); 262 const QFileInfoList *list = d.entryInfoList();
263 QFileInfoListIterator it( *list ); // create list iterator 263 QFileInfoListIterator it( *list ); // create list iterator
264 QFileInfo *fi; // pointer for traversing 264 QFileInfo *fi; // pointer for traversing
265 265
266 while ( (fi=it.current()) ) { // for each file... 266 while ( (fi=it.current()) ) { // for each file...
267 QString fileName = fi->fileName(); 267 QString fileName = fi->fileName();
268 if(fileName.right(4) == ".png"){ 268 if(fileName.right(4) == ".png"){
269 fileName = fileName.mid(0,fileName.length()-4); 269 fileName = fileName.mid(0,fileName.length()-4);
270 QPixmap imageOfFile(Resource::loadPixmap(fileName)); 270 QPixmap imageOfFile(Resource::loadPixmap(fileName));
271 QImage foo = imageOfFile.convertToImage(); 271 QImage foo = imageOfFile.convertToImage();
272 foo = foo.smoothScale(16,16); 272 foo = foo.smoothScale(16,16);
273 imageOfFile.convertFromImage(foo); 273 imageOfFile.convertFromImage(foo);
274 application->iconLineEdit->insertItem(imageOfFile,fileName); 274 application->iconLineEdit->insertItem(imageOfFile,fileName);
275 } 275 }
276 //qDebug(fi->fileName().latin1()); 276 //qDebug(fi->fileName().latin1());
277 ++it; 277 ++it;
278 } 278 }
279 waitDialog.hide(); 279 waitDialog.hide();
280 } 280 }
281 int pixmap = -1; 281 int pixmap = -1;
282 QString pixmapText = app.pixmapString(); 282 QString pixmapText = app.pixmapString();
283 QComboBox *f = application->iconLineEdit; 283 QComboBox *f = application->iconLineEdit;
284 for(int i = 0; i < application->iconLineEdit->count(); i++){ 284 for(int i = 0; i < application->iconLineEdit->count(); i++){
285 if(f->text(i) == pixmapText){ 285 if(f->text(i) == pixmapText){
286 pixmap = i; 286 pixmap = i;
287 break; 287 break;
288 } 288 }
289 } 289 }
290 if(pixmap != -1) 290 if(pixmap != -1)
291 application->iconLineEdit->setCurrentItem(pixmap); 291 application->iconLineEdit->setCurrentItem(pixmap);
292 else if(pixmapText.isEmpty()){ 292 else if(pixmapText.isEmpty()){
293 application->iconLineEdit->setCurrentItem(0); 293 application->iconLineEdit->setCurrentItem(0);
294 } 294 }
295 else{ 295 else{
296 QPixmap imageOfFile(Resource::loadPixmap(pixmapText)); 296 QPixmap imageOfFile(Resource::loadPixmap(pixmapText));
297 QImage foo = imageOfFile.convertToImage(); 297 QImage foo = imageOfFile.convertToImage();
298 foo = foo.smoothScale(16,16); 298 foo = foo.smoothScale(16,16);
299 imageOfFile.convertFromImage(foo); 299 imageOfFile.convertFromImage(foo);
300 application->iconLineEdit->insertItem(imageOfFile,pixmapText,0); 300 application->iconLineEdit->insertItem(imageOfFile,pixmapText,0);
301 application->iconLineEdit->setCurrentItem(0); 301 application->iconLineEdit->setCurrentItem(0);
302 } 302 }
303 303
304 application->nameLineEdit->setText(app.name()); 304 application->nameLineEdit->setText(app.name());
305 application->execLineEdit->setText(app.exec()); 305 application->execLineEdit->setText(app.exec());
306 application->commentLineEdit->setText(app.comment()); 306 application->commentLineEdit->setText(app.comment());
307 307
308 if(item->parent() == NULL){ 308 if(item->parent() == NULL){
309 application->execLineEdit->setEnabled(false); 309 application->execLineEdit->setEnabled(false);
310 application->TextLabel3->setEnabled(false); 310 application->TextLabel3->setEnabled(false);
311 application->setCaption(tr("Tab")); 311 application->setCaption(tr("Tab"));
312 } 312 }
313 else{ 313 else{
314 application->execLineEdit->setEnabled(true); 314 application->execLineEdit->setEnabled(true);
315 application->TextLabel3->setEnabled(true); 315 application->TextLabel3->setEnabled(true);
316 application->setCaption(tr("Application")); 316 application->setCaption(tr("Application"));
317 } 317 }
318 318
319 // Only do somthing if they hit OK 319 // Only do somthing if they hit OK
320 application->showMaximized(); 320 application->showMaximized();
321 if(application->exec() == 0) 321 if(application->exec() == 0)
322 return; 322 return;
323 323
324 // If nothing has changed exit (hmmm why did they hit ok?) 324 // If nothing has changed exit (hmmm why did they hit ok?)
325 if(app.name() == application->nameLineEdit->text() && 325 if(app.name() == application->nameLineEdit->text() &&
326 app.pixmapString() == application->iconLineEdit->currentText() && 326 app.pixmapString() == application->iconLineEdit->currentText() &&
327 app.comment() == application->commentLineEdit->text() && 327 app.comment() == application->commentLineEdit->text() &&
328 app.exec() == application->execLineEdit->text()) 328 app.exec() == application->execLineEdit->text())
329 return; 329 return;
330 330
331 // Change the applnk file 331 // Change the applnk file
332 QString oldName = app.name(); 332 QString oldName = app.name();
333 app.setName(application->nameLineEdit->text()); 333 app.setName(application->nameLineEdit->text());
334 app.setIcon(application->iconLineEdit->currentText()); 334 app.setIcon(application->iconLineEdit->currentText());
335 app.setComment(application->commentLineEdit->text()); 335 app.setComment(application->commentLineEdit->text());
336 app.setExec(application->execLineEdit->text()); 336 app.setExec(application->execLineEdit->text());
337 if(!app.writeLink()){ 337 if(!app.writeLink()){
338 QMessageBox::critical(this, tr("Message"), "Can't save.", tr("Ok") ); 338 QMessageBox::critical(this, tr("Message"), "Can't save.", tr("Ok") );
339 return; 339 return;
340 } 340 }
341 341
342 // Update the gui icon and name 342 // Update the gui icon and name
343 item->setText(0,app.name()); 343 item->setText(0,app.name());
344 item->setPixmap(0,app.pixmap()); 344 item->setPixmap(0,app.pixmap());
345 345
346 // We have changed something. 346 // We have changed something.
347 changed = true; 347 changed = true;
348 348
349 // If we were dealing with a new folder or new application change 349 // If we were dealing with a new folder or new application change
350 // the file names. Also change the item location in itemList 350 // the file names. Also change the item location in itemList
351 if(oldName == NEW_FOLDER){ 351 if(oldName == NEW_FOLDER){
352 QDir r; 352 QDir r;
353 QString oldName = itemList[item]; 353 QString oldName = itemList[item];
354 oldName = oldName.mid(0,oldName.length()-11); 354 oldName = oldName.mid(0,oldName.length()-11);
355 QString newName = oldName.mid(0,oldName.length()-9); 355 QString newName = oldName.mid(0,oldName.length()-9);
356 newName = newName + "/" + app.name(); 356 newName = newName + "/" + app.name();
357 r.rename(oldName, newName); 357 r.rename(oldName, newName);
358 itemList.remove(item); 358 itemList.remove(item);
359 itemList.insert(item, newName + "/.directory" ); 359 itemList.insert(item, newName + "/.directory" );
360 } 360 }
361 else if(oldName == NEW_APPLICATION){ 361 else if(oldName == NEW_APPLICATION){
362 if(!item->parent()) 362 if(!item->parent())
363 return; 363 return;
364 QString parentDir = itemList[item->parent()]; 364 QString parentDir = itemList[item->parent()];
365 QDir r; 365 QDir r;
366 QString oldName = itemList[item]; 366 QString oldName = itemList[item];
367 QString newName = oldName.mid(0, parentDir.length()-10); 367 QString newName = oldName.mid(0, parentDir.length()-10);
368 newName = newName + app.name() + APPLICATION_EXTENSION; 368 newName = newName + app.name() + APPLICATION_EXTENSION;
369 r.rename(oldName, newName); 369 r.rename(oldName, newName);
370 itemList.remove(item); 370 itemList.remove(item);
371 itemList.insert(item, newName); 371 itemList.insert(item, newName);
372 } 372 }
373} 373}
374 374
375/** 375/**
376 * Move an application from one directory to another. 376 * Move an application from one directory to another.
377 * Move in the gui, move in the applnk file, move in the installer. 377 * Move in the gui, move in the applnk file, move in the installer.
378 * @param item the application to move 378 * @param item the application to move
379 * @pearam newGroup the new parent of this application 379 * @pearam newGroup the new parent of this application
380 */ 380 */
381void TabManager::moveApplication(QListViewItem *item, QListViewItem *newGroup){ 381void TabManager::moveApplication(QListViewItem *item, QListViewItem *newGroup){
382 // Can we even move it? 382 // Can we even move it?
383 if(!item || !item->parent() || newGroup->parent()) 383 if(!item || !item->parent() || newGroup->parent())
384 return; 384 return;
385 if(item->parent() == newGroup) 385 if(item->parent() == newGroup)
386 return; 386 return;
387 387
388 // Get the new folder, new file name, 388 // Get the new folder, new file name,
389 QString newFolder = itemList[newGroup]; 389 QString newFolder = itemList[newGroup];
390 newFolder = newFolder.mid(0,newFolder.length()-11); 390 newFolder = newFolder.mid(0,newFolder.length()-11);
391 int slash = newFolder.findRev('/', -1); 391 int slash = newFolder.findRev('/', -1);
392 QString folderName = newFolder.mid(slash+1, newFolder.length()); 392 QString folderName = newFolder.mid(slash+1, newFolder.length());
393 393
394 QString desktopFile = itemList[item]; 394 QString desktopFile = itemList[item];
395 slash = desktopFile.findRev('/', -1); 395 slash = desktopFile.findRev('/', -1);
396 desktopFile = desktopFile.mid(slash, desktopFile.length()); 396 desktopFile = desktopFile.mid(slash, desktopFile.length());
397 newFolder = newFolder + desktopFile; 397 newFolder = newFolder + desktopFile;
398 398
399 // Move file 399 // Move file
400 QDir r; 400 QDir r;
401 if(!r.rename(itemList[item], newFolder)){ 401 if(!r.rename(itemList[item], newFolder)){
402 QMessageBox::critical(this, tr("Message"), "Can't move application.", tr("Ok") ); 402 QMessageBox::critical(this, tr("Message"), "Can't move application.", tr("Ok") );
403 return; 403 return;
404 } 404 }
405 //qDebug((QString("moveApplication: ") + itemList[item]).latin1()); 405 //qDebug((QString("moveApplication: ") + itemList[item]).latin1());
406 //qDebug((QString("moveApplication: ") + newFolder).latin1()); 406 //qDebug((QString("moveApplication: ") + newFolder).latin1());
407 407
408 // Move in the gui 408 // Move in the gui
409 item->parent()->takeItem(item); 409 item->parent()->takeItem(item);
410 newGroup->insertItem(item); 410 newGroup->insertItem(item);
411 newGroup->setOpen(true); 411 newGroup->setOpen(true);
412 412
413 // Move file in the installer 413 // Move file in the installer
414 QString installedAppFile; 414 QString installedAppFile;
415 if(findInstalledApplication(desktopFile, installedAppFile)) 415 if(findInstalledApplication(desktopFile, installedAppFile))
416 swapInstalledLocation(installedAppFile, desktopFile, newFolder); 416 swapInstalledLocation(installedAppFile, desktopFile, newFolder);
417 else 417 else
418 qDebug("moveApplication: No installed app found for dekstop file"); 418 qDebug("moveApplication: No installed app found for dekstop file");
419 419
420 // Move application type 420 // Move application type
421 AppLnk app(newFolder); 421 AppLnk app(newFolder);
422 app.setType(folderName); 422 app.setType(folderName);
423 app.writeLink(); 423 app.writeLink();
424 424
425 // Move in our internal list 425 // Move in our internal list
426 itemList.remove(item); 426 itemList.remove(item);
427 itemList.insert(item, newFolder); 427 itemList.insert(item, newFolder);
428 428
429 // We have changed something. 429 // We have changed something.
430 changed = true; 430 changed = true;
431} 431}
432 432
433/** 433/**
434 * File the installed application that has this desktop file. 434 * File the installed application that has this desktop file.
435 * Go through each file in HOME_APP_INSTALL_DIR and see if it contains desktop 435 * Go through each file in HOME_APP_INSTALL_DIR and see if it contains desktop
436 * file 436 * file
437 * @param desktopFile - the .desktop file to search for [foo.desktop] 437 * @param desktopFile - the .desktop file to search for [foo.desktop]
438 * @param installedAppFile - location of the app install list 438 * @param installedAppFile - location of the app install list
439 * @return true if successful, false if file not found. 439 * @return true if successful, false if file not found.
440 */ 440 */
441bool TabManager::findInstalledApplication(QString desktopFile, QString &installedAppFile){ 441bool TabManager::findInstalledApplication(QString desktopFile, QString &installedAppFile){
442 442
443 QDir d; 443 QDir d;
444 d.setPath(HOME_APP_INSTALL_DIR); 444 d.setPath(HOME_APP_INSTALL_DIR);
445 d.setFilter( QDir::Files ); 445 d.setFilter( QDir::Files );
446 446
447 const QFileInfoList *list = d.entryInfoList(); 447 const QFileInfoList *list = d.entryInfoList();
448 QFileInfoListIterator it( *list ); // create list iterator 448 QFileInfoListIterator it( *list ); // create list iterator
449 QFileInfo *fi; // pointer for traversing 449 QFileInfo *fi; // pointer for traversing
450 450
451 while ( (fi=it.current()) ) { // for each file... 451 while ( (fi=it.current()) ) { // for each file...
452 QFile file(QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName()); 452 QFile file(QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName());
453 if ( file.open(IO_ReadOnly) ) { // file opened successfully 453 if ( file.open(IO_ReadOnly) ) { // file opened successfully
454 QTextStream stream( &file ); // use a text stream 454 QTextStream stream( &file ); // use a text stream
455 QString line; 455 QString line;
456 while ( !stream.eof() ) { // until end of file... 456 while ( !stream.eof() ) { // until end of file...
457 line = stream.readLine(); // line of text excluding '\n' 457 line = stream.readLine(); // line of text excluding '\n'
458 if(line.contains(desktopFile)){ 458 if(line.contains(desktopFile)){
459 installedAppFile = QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName(); 459 installedAppFile = QString(HOME_APP_INSTALL_DIR) + "/" + fi->fileName();
460 file.close(); 460 file.close();
461 return true; 461 return true;
462 } 462 }
463 } 463 }
464 file.close(); 464 file.close();
465 } 465 }
466 else 466 else
467 qDebug((QString("findInstalledApplication: Can't open file") + HOME_APP_INSTALL_DIR + "/" + fi->fileName()).latin1()); 467 qDebug((QString("findInstalledApplication: Can't open file") + HOME_APP_INSTALL_DIR + "/" + fi->fileName()).latin1());
468 ++it; // goto next list element 468 ++it; // goto next list element
469 } 469 }
470 return false; 470 return false;
471} 471}
472 472
473/** 473/**
474 * Open a file and replace a file containing the old desktop file with the new. 474 * Open a file and replace a file containing the old desktop file with the new.
475 * @param installedAppFile application installed list 475 * @param installedAppFile application installed list
476 * @param desktopFile old .desktop file 476 * @param desktopFile old .desktop file
477 * @param newLocation new .desktop file 477 * @param newLocation new .desktop file
478 */ 478 */
479void TabManager::swapInstalledLocation( QString installedAppFile, QString desktopFile, QString newLocation ){ 479void TabManager::swapInstalledLocation( QString installedAppFile, QString desktopFile, QString newLocation ){
480 QFile file(installedAppFile); 480 QFile file(installedAppFile);
481 if ( !file.open(IO_ReadOnly) ){ 481 if ( !file.open(IO_ReadOnly) ){
482 qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1()); 482 qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1());
483 return; 483 return;
484 } 484 }
485 485
486 QTextStream stream( &file ); // use a text stream 486 QTextStream stream( &file ); // use a text stream
487 QString allLines; 487 QString allLines;
488 while ( !stream.eof() ) { // until end of file... 488 while ( !stream.eof() ) { // until end of file...
489 QString line = stream.readLine(); // line of text excluding '\n' 489 QString line = stream.readLine(); // line of text excluding '\n'
490 if(line.contains(desktopFile)) 490 if(line.contains(desktopFile))
491 allLines += newLocation; 491 allLines += newLocation;
492 else 492 else
493 allLines += line; 493 allLines += line;
494 allLines += '\n'; 494 allLines += '\n';
495 } 495 }
496 file.close(); 496 file.close();
497 497
498 if ( !file.open(IO_ReadWrite) ){ 498 if ( !file.open(IO_ReadWrite) ){
499 qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1()); 499 qDebug(QString("swapInstalledLocation: Can't edit file: %1").arg(installedAppFile).latin1());
500 return; 500 return;
501 } 501 }
502 QTextStream streamOut( &file ); 502 QTextStream streamOut( &file );
503 streamOut << allLines; 503 streamOut << allLines;
504 file.close(); 504 file.close();
505} 505}
506 506
507// tabmanager.cpp 507// tabmanager.cpp
508 508
diff --git a/noncore/settings/usermanager/usermanager.cpp b/noncore/settings/usermanager/usermanager.cpp
index 5411995..a1130d4 100644
--- a/noncore/settings/usermanager/usermanager.cpp
+++ b/noncore/settings/usermanager/usermanager.cpp
@@ -1,257 +1,257 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9 9
10#include "usermanager.h" 10#include "usermanager.h"
11 11
12#include <qlayout.h> 12#include <qlayout.h>
13 13
14#include <qmessagebox.h> 14#include <qmessagebox.h>
15#include <qfile.h> 15#include <qfile.h>
16#include <qpe/resource.h> 16#include <qpe/resource.h>
17 17
18#include <qregexp.h> 18#include <qregexp.h>
19 19
20/** 20/**
21 * The mainwindow constructor. 21 * The mainwindow constructor.
22 * 22 *
23 * @param QWidget *parent 23 * @param QWidget *parent
24 * @param const char *name 24 * @param const char *name
25 * @ param WFlags fl 25 * @ param WFlags fl
26 * 26 *
27 */ 27 */
28UserConfig::UserConfig(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) { 28UserConfig::UserConfig(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) {
29 setCaption(tr("Opie User Manager")); 29 setCaption(tr("Opie User Manager"));
30 30
31 // Create an instance of the global object 'accounts'. This holds all user/group info, and functions to modify them. 31 // Create an instance of the global object 'accounts'. This holds all user/group info, and functions to modify them.
32 accounts=new Passwd(); 32 accounts=new Passwd();
33 accounts->open();// This actually loads the files /etc/passwd & /etc/group into memory. 33 accounts->open();// This actually loads the files /etc/passwd & /etc/group into memory.
34 34
35 // Create the toolbar. 35 // Create the toolbar.
36 QToolBar *toolbar = new QToolBar(this,"Toolbar"); 36 QToolBar *toolbar = new QToolBar(this,"Toolbar");
37 toolbar->setHorizontalStretchable(1); // Is there any other way to get the toolbar to stretch of the full screen!? 37 toolbar->setHorizontalStretchable(1); // Is there any other way to get the toolbar to stretch of the full screen!?
38 adduserToolButton = new QToolButton(Resource::loadPixmap("usermanager/adduser"),"Add User",0,this,SLOT(addUser()),toolbar,"Add User"); 38 adduserToolButton = new QToolButton(Resource::loadPixmap("usermanager/adduser"),"Add User",0,this,SLOT(addUser()),toolbar,"Add User");
39 edituserToolButton = new QToolButton(Resource::loadPixmap("usermanager/edituser"),"Edit User",0,this,SLOT(editUser()),toolbar,"Edit User"); 39 edituserToolButton = new QToolButton(Resource::loadPixmap("usermanager/edituser"),"Edit User",0,this,SLOT(editUser()),toolbar,"Edit User");
40 deleteuserToolButton = new QToolButton(Resource::loadPixmap("usermanager/deleteuser"),"Delete User",0,this,SLOT(delUser()),toolbar,"Delete User"); 40 deleteuserToolButton = new QToolButton(Resource::loadPixmap("usermanager/deleteuser"),"Delete User",0,this,SLOT(delUser()),toolbar,"Delete User");
41 QToolButton *userstext = new QToolButton(0,"User",0,0,0,toolbar,"User"); 41 QToolButton *userstext = new QToolButton(0,"User",0,0,0,toolbar,"User");
42 userstext->setUsesTextLabel(true); 42 userstext->setUsesTextLabel(true);
43 toolbar->addSeparator(); 43 toolbar->addSeparator();
44 addgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/addgroup"),"Add Group",0,this,SLOT(addGroup()),toolbar,"Add Group"); 44 addgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/addgroup"),"Add Group",0,this,SLOT(addGroup()),toolbar,"Add Group");
45 editgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/editgroup"),"Edit Group",0,this,SLOT(editGroup()),toolbar,"Edit Group"); 45 editgroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/editgroup"),"Edit Group",0,this,SLOT(editGroup()),toolbar,"Edit Group");
46 deletegroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/deletegroup"),"Delete Group",0,this,SLOT(delGroup()),toolbar,"Delete Group"); 46 deletegroupToolButton = new QToolButton(Resource::loadPixmap("usermanager/deletegroup"),"Delete Group",0,this,SLOT(delGroup()),toolbar,"Delete Group");
47 QToolButton *groupstext = new QToolButton(0,"Group",0,0,0,toolbar,"Group"); 47 QToolButton *groupstext = new QToolButton(0,"Group",0,0,0,toolbar,"Group");
48 groupstext->setUsesTextLabel(true); 48 groupstext->setUsesTextLabel(true);
49 addToolBar(toolbar,"myToolBar"); 49 addToolBar(toolbar,"myToolBar");
50 50
51 // Add a tabwidget and all the tabs. 51 // Add a tabwidget and all the tabs.
52 myTabWidget = new QTabWidget(this,"My Tab Widget"); 52 myTabWidget = new QTabWidget(this,"My Tab Widget");
53 setupTabAccounts(); 53 setupTabAccounts();
54 setupTabAllUsers(); 54 setupTabAllUsers();
55 setupTabAllGroups(); 55 setupTabAllGroups();
56 userPopupMenu.insertItem("Copy",0); 56 userPopupMenu.insertItem("Copy",0);
57 57
58 getUsers(); // Fill out the iconview & listview with all users. 58 getUsers(); // Fill out the iconview & listview with all users.
59 getGroups(); // Fill out the group listview with all groups. 59 getGroups(); // Fill out the group listview with all groups.
60 60
61 setCentralWidget(myTabWidget); 61 setCentralWidget(myTabWidget);
62} 62}
63 63
64UserConfig::~UserConfig() { 64UserConfig::~UserConfig() {
65 accounts->close(); 65 accounts->close();
66 delete accounts; 66 delete accounts;
67} 67}
68 68
69void UserConfig::setupTabAccounts() { 69void UserConfig::setupTabAccounts() {
70 QWidget *tabpage = new QWidget(this); 70 QWidget *tabpage = new QWidget(this);
71 QVBoxLayout *layout = new QVBoxLayout(tabpage); 71 QVBoxLayout *layout = new QVBoxLayout(tabpage);
72 layout->setMargin(5); 72 layout->setMargin(5);
73 73
74 usersIconView=new QListView(tabpage,"users"); 74 usersIconView=new QListView(tabpage,"users");
75 usersIconView->addColumn("Icon"); 75 usersIconView->addColumn("Icon");
76 usersIconView->addColumn("Username"); 76 usersIconView->addColumn("Username");
77 usersIconView->setAllColumnsShowFocus(true); 77 usersIconView->setAllColumnsShowFocus(true);
78 layout->addWidget(usersIconView); 78 layout->addWidget(usersIconView);
79 79
80 connect(usersIconView,SIGNAL(returnPressed(QListViewItem *)),this,SLOT(showUserMenu(QListViewItem *))); 80 connect(usersIconView,SIGNAL(returnPressed(QListViewItem*)),this,SLOT(showUserMenu(QListViewItem*)));
81 81
82 myTabWidget->addTab(tabpage,"Users"); 82 myTabWidget->addTab(tabpage,"Users");
83} 83}
84 84
85void UserConfig::setupTabAllUsers() { 85void UserConfig::setupTabAllUsers() {
86 QWidget *tabpage = new QWidget(this); 86 QWidget *tabpage = new QWidget(this);
87 QVBoxLayout *layout = new QVBoxLayout(tabpage); 87 QVBoxLayout *layout = new QVBoxLayout(tabpage);
88 layout->setMargin(5); 88 layout->setMargin(5);
89 89
90 usersListView=new QListView(tabpage,"allusers"); 90 usersListView=new QListView(tabpage,"allusers");
91 usersListView->addColumn("UID"); 91 usersListView->addColumn("UID");
92 usersListView->addColumn("Login"); 92 usersListView->addColumn("Login");
93 usersListView->addColumn("Username"); 93 usersListView->addColumn("Username");
94 layout->addWidget(usersListView); 94 layout->addWidget(usersListView);
95 usersListView->setSorting(1,1); 95 usersListView->setSorting(1,1);
96 usersListView->setAllColumnsShowFocus(true); 96 usersListView->setAllColumnsShowFocus(true);
97 97
98 myTabWidget->addTab(tabpage,"All Users"); 98 myTabWidget->addTab(tabpage,"All Users");
99} 99}
100 100
101void UserConfig::setupTabAllGroups() { 101void UserConfig::setupTabAllGroups() {
102 QWidget *tabpage = new QWidget(this); 102 QWidget *tabpage = new QWidget(this);
103 QVBoxLayout *layout = new QVBoxLayout(tabpage); 103 QVBoxLayout *layout = new QVBoxLayout(tabpage);
104 layout->setMargin(5); 104 layout->setMargin(5);
105 105
106 groupsListView=new QListView(tabpage,"groups"); 106 groupsListView=new QListView(tabpage,"groups");
107 groupsListView->addColumn("GID"); 107 groupsListView->addColumn("GID");
108 groupsListView->addColumn("Groupname"); 108 groupsListView->addColumn("Groupname");
109 layout->addWidget(groupsListView); 109 layout->addWidget(groupsListView);
110 groupsListView->setSorting(1,1); 110 groupsListView->setSorting(1,1);
111 groupsListView->setAllColumnsShowFocus(true); 111 groupsListView->setAllColumnsShowFocus(true);
112 112
113 myTabWidget->addTab(tabpage,"All Groups"); 113 myTabWidget->addTab(tabpage,"All Groups");
114} 114}
115void UserConfig::getUsers() { 115void UserConfig::getUsers() {
116 QString mytext; 116 QString mytext;
117 QPixmap mypixmap; 117 QPixmap mypixmap;
118 QListViewItem *listviewitem; 118 QListViewItem *listviewitem;
119 119
120 // Empty the iconview & the listview. 120 // Empty the iconview & the listview.
121 usersIconView->clear(); 121 usersIconView->clear();
122 usersListView->clear(); 122 usersListView->clear();
123 123
124 // availableUID is used as a deposite for the next available UID on the system, this should start at an ID over 500. 124 // availableUID is used as a deposite for the next available UID on the system, this should start at an ID over 500.
125 availableUID=500; 125 availableUID=500;
126 for(QStringList::Iterator it=accounts->passwdStringList.begin(); it!=accounts->passwdStringList.end(); ++it) { 126 for(QStringList::Iterator it=accounts->passwdStringList.begin(); it!=accounts->passwdStringList.end(); ++it) {
127 accounts->splitPasswdEntry(*it); // Split the string into it's components and store in variables in the accounts object. ("pr_name" and so on.) 127 accounts->splitPasswdEntry(*it); // Split the string into it's components and store in variables in the accounts object. ("pr_name" and so on.)
128 if(accounts->pw_name.find(QRegExp("^#"),0)) {// Skip commented lines. 128 if(accounts->pw_name.find(QRegExp("^#"),0)) {// Skip commented lines.
129 new QListViewItem(usersListView,QString::number(accounts->pw_uid),accounts->pw_name,accounts->pw_gecos); 129 new QListViewItem(usersListView,QString::number(accounts->pw_uid),accounts->pw_name,accounts->pw_gecos);
130 if((accounts->pw_uid>=500) && (accounts->pw_uid<65000)) {// Is this user a "normal" user ? 130 if((accounts->pw_uid>=500) && (accounts->pw_uid<65000)) {// Is this user a "normal" user ?
131 mytext=QString(accounts->pw_name)+" - ("+QString(accounts->pw_gecos)+")"; // The string displayed next to the icon. 131 mytext=QString(accounts->pw_name)+" - ("+QString(accounts->pw_gecos)+")"; // The string displayed next to the icon.
132 if(!(mypixmap.load("/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png"))) { // Is there an icon for this user? Resource::loadPixmap is caching, doesn't work. 132 if(!(mypixmap.load("/opt/QtPalmtop/pics/users/"+accounts->pw_name+".png"))) { // Is there an icon for this user? Resource::loadPixmap is caching, doesn't work.
133 mypixmap=Resource::loadPixmap(QString("usermanager/usericon"));// If this user has no icon, load the default icon. 133 mypixmap=Resource::loadPixmap(QString("usermanager/usericon"));// If this user has no icon, load the default icon.
134 } 134 }
135 listviewitem=new QListViewItem(usersIconView,"",mytext);// Add the icon+text to the qiconview. 135 listviewitem=new QListViewItem(usersIconView,"",mytext);// Add the icon+text to the qiconview.
136 listviewitem->setPixmap(0,mypixmap); 136 listviewitem->setPixmap(0,mypixmap);
137 } 137 }
138 if((accounts->pw_uid>=availableUID) && (accounts->pw_uid<65000)) availableUID=accounts->pw_uid+1; // Increase 1 to the latest know UID to get a free uid. 138 if((accounts->pw_uid>=availableUID) && (accounts->pw_uid<65000)) availableUID=accounts->pw_uid+1; // Increase 1 to the latest know UID to get a free uid.
139 } 139 }
140 } 140 }
141 usersIconView->sort(); 141 usersIconView->sort();
142} 142}
143 143
144void UserConfig::addUser() { 144void UserConfig::addUser() {
145 if(UserDialog::addUser(availableUID,availableGID)) {// Add the user to the system, also send next available UID and GID. 145 if(UserDialog::addUser(availableUID,availableGID)) {// Add the user to the system, also send next available UID and GID.
146 getUsers(); // Update users views. 146 getUsers(); // Update users views.
147 getGroups(); // Update groups view. 147 getGroups(); // Update groups view.
148 } 148 }
149} 149}
150 150
151void UserConfig::editUser() { 151void UserConfig::editUser() {
152 QString username; 152 QString username;
153 if(myTabWidget->currentPageIndex()==0) {// Users 153 if(myTabWidget->currentPageIndex()==0) {// Users
154 if(usersIconView->currentItem()) {// Any icon selected? 154 if(usersIconView->currentItem()) {// Any icon selected?
155 username=usersIconView->currentItem()->text(1);// Get the text associated with the icon. 155 username=usersIconView->currentItem()->text(1);// Get the text associated with the icon.
156 username=username.left(username.find(" - (",0,true));// Strip out the username. 156 username=username.left(username.find(" - (",0,true));// Strip out the username.
157 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog. 157 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog.
158 // If there were any changed also update the views. 158 // If there were any changed also update the views.
159 getUsers(); 159 getUsers();
160 getGroups(); 160 getGroups();
161 } 161 }
162 } else { 162 } else {
163 QMessageBox::information(this,"No selection.","No user has been selected."); 163 QMessageBox::information(this,"No selection.","No user has been selected.");
164 } 164 }
165 } 165 }
166 if(myTabWidget->currentPageIndex()==1) {// All users 166 if(myTabWidget->currentPageIndex()==1) {// All users
167 if(usersListView->currentItem()) {// Anything changed!? 167 if(usersListView->currentItem()) {// Anything changed!?
168 username=usersListView->currentItem()->text(1);// Get the username. 168 username=usersListView->currentItem()->text(1);// Get the username.
169 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog. 169 if(UserDialog::editUser(username)) {// Bring up the userinfo dialog.
170 // And again update the views if there were any changes. 170 // And again update the views if there were any changes.
171 getUsers(); 171 getUsers();
172 getGroups(); 172 getGroups();
173 } 173 }
174 } else { 174 } else {
175 QMessageBox::information(this,"No selection.","No user has been selected."); 175 QMessageBox::information(this,"No selection.","No user has been selected.");
176 } 176 }
177 } 177 }
178} 178}
179 179
180void UserConfig::delUser() { 180void UserConfig::delUser() {
181 QString username; 181 QString username;
182 182
183 if(myTabWidget->currentPageIndex()==0) {// Users, Iconview. 183 if(myTabWidget->currentPageIndex()==0) {// Users, Iconview.
184 if(usersIconView->currentItem()) {// Anything selected? 184 if(usersIconView->currentItem()) {// Anything selected?
185 username=usersIconView->currentItem()->text(1);// Get string associated with icon. 185 username=usersIconView->currentItem()->text(1);// Get string associated with icon.
186 username=username.left(username.find(" - (",0,true));// Strip out the username. 186 username=username.left(username.find(" - (",0,true));// Strip out the username.
187 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) { 187 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) {
188 if(UserDialog::delUser(username)) {// Delete the user if possible. 188 if(UserDialog::delUser(username)) {// Delete the user if possible.
189 // Update views. 189 // Update views.
190 getUsers(); 190 getUsers();
191 getGroups(); 191 getGroups();
192 } 192 }
193 } 193 }
194 } else { 194 } else {
195 QMessageBox::information(this,"No selection","No user has been selected."); 195 QMessageBox::information(this,"No selection","No user has been selected.");
196 } 196 }
197 } 197 }
198 if(myTabWidget->currentPageIndex()==1) {// All users 198 if(myTabWidget->currentPageIndex()==1) {// All users
199 if(usersListView->currentItem()) {// Anything changed!? 199 if(usersListView->currentItem()) {// Anything changed!?
200 username=usersListView->currentItem()->text(1);// Get the username. 200 username=usersListView->currentItem()->text(1);// Get the username.
201 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) { 201 if(QMessageBox::warning(this,"Delete user","Are you sure you want to\ndelete this user? \""+QString(username)+"\" ?","&No","&Yes",0,0,1)) {
202 if(UserDialog::delUser(username)) {// Try to delete the user. 202 if(UserDialog::delUser(username)) {// Try to delete the user.
203 // Update views. 203 // Update views.
204 getUsers(); 204 getUsers();
205 getGroups(); 205 getGroups();
206 } 206 }
207 } 207 }
208 } else { 208 } else {
209 QMessageBox::information(this,"No selection","No user has been selected."); 209 QMessageBox::information(this,"No selection","No user has been selected.");
210 } 210 }
211 } 211 }
212 212
213} 213}
214 214
215void UserConfig::getGroups() { 215void UserConfig::getGroups() {
216 groupsListView->clear();// Empty the listview. 216 groupsListView->clear();// Empty the listview.
217 availableGID=500;// We need to find the next free GID, and are only interested in values between 500 & 65000. 217 availableGID=500;// We need to find the next free GID, and are only interested in values between 500 & 65000.
218 for(QStringList::Iterator it=accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) {// Split the list into lines. 218 for(QStringList::Iterator it=accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) {// Split the list into lines.
219 accounts->splitGroupEntry(*it);// Split the line into its components and fill the variables of 'accounts'. (gr_name, gr_uid & gr_mem). 219 accounts->splitGroupEntry(*it);// Split the line into its components and fill the variables of 'accounts'. (gr_name, gr_uid & gr_mem).
220 if(accounts->gr_name.find(QRegExp("^#"),0)) {// Skip commented lines. 220 if(accounts->gr_name.find(QRegExp("^#"),0)) {// Skip commented lines.
221 new QListViewItem(groupsListView,QString::number(accounts->gr_gid),accounts->gr_name); 221 new QListViewItem(groupsListView,QString::number(accounts->gr_gid),accounts->gr_name);
222 if((accounts->gr_gid>=availableGID) && (accounts->gr_gid<65000)) availableGID=accounts->gr_gid+1;// Maybe a new free GID. 222 if((accounts->gr_gid>=availableGID) && (accounts->gr_gid<65000)) availableGID=accounts->gr_gid+1;// Maybe a new free GID.
223 } 223 }
224 } 224 }
225} 225}
226 226
227void UserConfig::addGroup() { 227void UserConfig::addGroup() {
228 if(GroupDialog::addGroup(availableGID)) getGroups();// Bring up the add group dialog. 228 if(GroupDialog::addGroup(availableGID)) getGroups();// Bring up the add group dialog.
229} 229}
230 230
231void UserConfig::editGroup() { 231void UserConfig::editGroup() {
232 int gid; 232 int gid;
233 if(groupsListView->currentItem()) {// Any group selected? 233 if(groupsListView->currentItem()) {// Any group selected?
234 gid=groupsListView->currentItem()->text(0).toInt();// Get the GID from the listview. 234 gid=groupsListView->currentItem()->text(0).toInt();// Get the GID from the listview.
235 if(GroupDialog::editGroup(gid)) getGroups();// Bring up the edit group dialog. 235 if(GroupDialog::editGroup(gid)) getGroups();// Bring up the edit group dialog.
236 } else { 236 } else {
237 QMessageBox::information(this,"No selection","No group has been selected."); 237 QMessageBox::information(this,"No selection","No group has been selected.");
238 } 238 }
239} 239}
240 240
241void UserConfig::delGroup() { 241void UserConfig::delGroup() {
242 const char *groupname; 242 const char *groupname;
243 if(groupsListView->currentItem()) {// Any group selected? 243 if(groupsListView->currentItem()) {// Any group selected?
244 groupname=groupsListView->currentItem()->text(1);// Get the groupname from the listview. 244 groupname=groupsListView->currentItem()->text(1);// Get the groupname from the listview.
245 if(QMessageBox::warning(this,"Delete group","Are you sure you want to\ndelete the group \""+QString(groupname)+"\" ?","&No","&Yes",0,0,1)) { 245 if(QMessageBox::warning(this,"Delete group","Are you sure you want to\ndelete the group \""+QString(groupname)+"\" ?","&No","&Yes",0,0,1)) {
246 // If confirmed, try to delete the group. 246 // If confirmed, try to delete the group.
247 if(GroupDialog::delGroup(groupname)) getGroups(); // And also update the view afterwards if the user was deleted. 247 if(GroupDialog::delGroup(groupname)) getGroups(); // And also update the view afterwards if the user was deleted.
248 } 248 }
249 } else { 249 } else {
250 QMessageBox::information(this,"No selection","No group has been selected."); 250 QMessageBox::information(this,"No selection","No group has been selected.");
251 } 251 }
252} 252}
253 253
254void UserConfig::showUserMenu(QListViewItem *item) { 254void UserConfig::showUserMenu(QListViewItem *item) {
255 //userPopupMenu.exec(item->mapToGlobal(QPoint(0,0))); 255 //userPopupMenu.exec(item->mapToGlobal(QPoint(0,0)));
256 qWarning("Pressed!"); 256 qWarning("Pressed!");
257} 257}
diff --git a/noncore/styles/liquid/liquidset.cpp b/noncore/styles/liquid/liquidset.cpp
index 7747da7..a7cfccc 100644
--- a/noncore/styles/liquid/liquidset.cpp
+++ b/noncore/styles/liquid/liquidset.cpp
@@ -1,169 +1,169 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21 21
22 22
23#include "liquidset.h" 23#include "liquidset.h"
24#include "liquid.h" 24#include "liquid.h"
25 25
26#include <qpe/qpeapplication.h> 26#include <qpe/qpeapplication.h>
27#include <qpe/global.h> 27#include <qpe/global.h>
28 28
29#include <qslider.h> 29#include <qslider.h>
30#include <qcombobox.h> 30#include <qcombobox.h>
31#include <qradiobutton.h> 31#include <qradiobutton.h>
32#include <qcheckbox.h> 32#include <qcheckbox.h>
33#include <qlabel.h> 33#include <qlabel.h>
34#include <qlayout.h> 34#include <qlayout.h>
35 35
36#include <qpe/config.h> 36#include <qpe/config.h>
37 37
38#include <opie/ocolorbutton.h> 38#include <opie/ocolorbutton.h>
39 39
40 40
41LiquidSettings::LiquidSettings ( QWidget* parent, const char *name, WFlags fl ) 41LiquidSettings::LiquidSettings ( QWidget* parent, const char *name, WFlags fl )
42 : QWidget ( parent, name, fl ) 42 : QWidget ( parent, name, fl )
43{ 43{
44 setCaption ( tr( "Liquid Style" ) ); 44 setCaption ( tr( "Liquid Style" ) );
45 45
46 Config config ( "qpe" ); 46 Config config ( "qpe" );
47 config. setGroup ( "Liquid-Style" ); 47 config. setGroup ( "Liquid-Style" );
48 48
49 m_type = config. readNumEntry ( "Type", TransStippleBg ); 49 m_type = config. readNumEntry ( "Type", TransStippleBg );
50 QColor mcol = QColor ( config. readEntry ( "Color", QApplication::palette ( ). active ( ). button ( ). name ( ))); 50 QColor mcol = QColor ( config. readEntry ( "Color", QApplication::palette ( ). active ( ). button ( ). name ( )));
51 QColor tcol = QColor ( config. readEntry ( "TextColor", QApplication::palette ( ). active ( ). text ( ). name ( ))); 51 QColor tcol = QColor ( config. readEntry ( "TextColor", QApplication::palette ( ). active ( ). text ( ). name ( )));
52 int opacity = config. readNumEntry ( "Opacity", 10 ); 52 int opacity = config. readNumEntry ( "Opacity", 10 );
53 m_shadow = config. readBoolEntry ( "ShadowText", true ); 53 m_shadow = config. readBoolEntry ( "ShadowText", true );
54 int contrast = config. readNumEntry ( "StippleContrast", 5 ); 54 int contrast = config. readNumEntry ( "StippleContrast", 5 );
55 m_flat = config. readBoolEntry ( "FlatToolButtons", false ); 55 m_flat = config. readBoolEntry ( "FlatToolButtons", false );
56 56
57 QVBoxLayout *vbox = new QVBoxLayout ( this ); 57 QVBoxLayout *vbox = new QVBoxLayout ( this );
58 vbox-> setSpacing ( 3 ); 58 vbox-> setSpacing ( 3 );
59 vbox-> setMargin ( 4 ); 59 vbox-> setMargin ( 4 );
60 60
61 QComboBox *cb = new QComboBox ( this ); 61 QComboBox *cb = new QComboBox ( this );
62 cb-> insertItem ( tr( "No translucency" ), None ); 62 cb-> insertItem ( tr( "No translucency" ), None );
63 cb-> insertItem ( tr( "Stippled, background color" ), StippledBg ); 63 cb-> insertItem ( tr( "Stippled, background color" ), StippledBg );
64 cb-> insertItem ( tr( "Stippled, button color" ), StippledBtn ); 64 cb-> insertItem ( tr( "Stippled, button color" ), StippledBtn );
65 cb-> insertItem ( tr( "Translucent stippled, background color" ), TransStippleBg ); 65 cb-> insertItem ( tr( "Translucent stippled, background color" ), TransStippleBg );
66 cb-> insertItem ( tr( "Translucent stippled, button color" ), TransStippleBtn ); 66 cb-> insertItem ( tr( "Translucent stippled, button color" ), TransStippleBtn );
67 cb-> insertItem ( tr( "Custom translucency" ), Custom ); 67 cb-> insertItem ( tr( "Custom translucency" ), Custom );
68 68
69 cb-> setCurrentItem ( m_type ); 69 cb-> setCurrentItem ( m_type );
70 vbox-> addWidget ( cb ); 70 vbox-> addWidget ( cb );
71 71
72 72
73 QGridLayout *grid = new QGridLayout ( vbox ); 73 QGridLayout *grid = new QGridLayout ( vbox );
74 grid-> addColSpacing ( 0, 16 ); 74 grid-> addColSpacing ( 0, 16 );
75 grid-> addColSpacing ( 3, 8 ); 75 grid-> addColSpacing ( 3, 8 );
76 76
77 grid-> addWidget ( m_menulbl = new QLabel ( tr( "Menu color" ), this ), 0, 1 ); 77 grid-> addWidget ( m_menulbl = new QLabel ( tr( "Menu color" ), this ), 0, 1 );
78 grid-> addWidget ( m_textlbl = new QLabel ( tr( "Text color" ), this ), 0, 4 ); 78 grid-> addWidget ( m_textlbl = new QLabel ( tr( "Text color" ), this ), 0, 4 );
79 grid-> addWidget ( m_opaclbl = new QLabel ( tr( "Opacity" ), this ), 1, 1 ); 79 grid-> addWidget ( m_opaclbl = new QLabel ( tr( "Opacity" ), this ), 1, 1 );
80 80
81 m_menubtn = new OColorButton ( this, mcol ); 81 m_menubtn = new OColorButton ( this, mcol );
82 grid-> addWidget ( m_menubtn, 0, 2 ); 82 grid-> addWidget ( m_menubtn, 0, 2 );
83 83
84 m_textbtn = new OColorButton ( this, tcol ); 84 m_textbtn = new OColorButton ( this, tcol );
85 grid-> addWidget ( m_textbtn, 0, 5 ); 85 grid-> addWidget ( m_textbtn, 0, 5 );
86 86
87 m_opacsld = new QSlider ( Horizontal, this ); 87 m_opacsld = new QSlider ( Horizontal, this );
88 m_opacsld-> setRange ( -20, 20 ); 88 m_opacsld-> setRange ( -20, 20 );
89 m_opacsld-> setSteps ( 1, 1 ); 89 m_opacsld-> setSteps ( 1, 1 );
90 m_opacsld-> setValue ( opacity ); 90 m_opacsld-> setValue ( opacity );
91 m_opacsld-> setTickmarks ( QSlider::Below ); 91 m_opacsld-> setTickmarks ( QSlider::Below );
92 grid-> addMultiCellWidget ( m_opacsld, 1, 1, 2, 5 ); 92 grid-> addMultiCellWidget ( m_opacsld, 1, 1, 2, 5 );
93 93
94 vbox-> addSpacing ( 4 ); 94 vbox-> addSpacing ( 4 );
95 95
96 QCheckBox *shadow = new QCheckBox ( tr( "Use shadowed menu text" ), this ); 96 QCheckBox *shadow = new QCheckBox ( tr( "Use shadowed menu text" ), this );
97 shadow-> setChecked ( m_shadow ); 97 shadow-> setChecked ( m_shadow );
98 vbox-> addWidget ( shadow ); 98 vbox-> addWidget ( shadow );
99 99
100 vbox-> addSpacing ( 4 ); 100 vbox-> addSpacing ( 4 );
101 101
102 QCheckBox *flattb = new QCheckBox ( tr( "Make toolbar buttons appear flat" ), this ); 102 QCheckBox *flattb = new QCheckBox ( tr( "Make toolbar buttons appear flat" ), this );
103 flattb-> setChecked ( m_flat ); 103 flattb-> setChecked ( m_flat );
104 vbox-> addWidget ( flattb ); 104 vbox-> addWidget ( flattb );
105 105
106 vbox-> addSpacing ( 4 ); 106 vbox-> addSpacing ( 4 );
107 107
108 QHBoxLayout *hbox = new QHBoxLayout ( vbox ); 108 QHBoxLayout *hbox = new QHBoxLayout ( vbox );
109 109
110 hbox-> addWidget ( new QLabel ( tr( "Stipple contrast" ), this )); 110 hbox-> addWidget ( new QLabel ( tr( "Stipple contrast" ), this ));
111 111
112 m_contsld = new QSlider ( Horizontal, this ); 112 m_contsld = new QSlider ( Horizontal, this );
113 m_contsld-> setRange ( 0, 10 ); 113 m_contsld-> setRange ( 0, 10 );
114 m_contsld-> setSteps ( 1, 1 ); 114 m_contsld-> setSteps ( 1, 1 );
115 m_contsld-> setValue ( contrast ); 115 m_contsld-> setValue ( contrast );
116 m_contsld-> setTickmarks ( QSlider::Below ); 116 m_contsld-> setTickmarks ( QSlider::Below );
117 hbox-> addWidget ( m_contsld, 10 ); 117 hbox-> addWidget ( m_contsld, 10 );
118 118
119 vbox-> addStretch ( 10 ); 119 vbox-> addStretch ( 10 );
120 120
121 changeType ( m_type ); 121 changeType ( m_type );
122 122
123 connect ( cb, SIGNAL( highlighted ( int ) ), this, SLOT( changeType ( int ) ) ); 123 connect ( cb, SIGNAL( highlighted(int) ), this, SLOT( changeType(int) ) );
124 connect ( shadow, SIGNAL( toggled ( bool ) ), this, SLOT( changeShadow ( bool ) ) ); 124 connect ( shadow, SIGNAL( toggled(bool) ), this, SLOT( changeShadow(bool) ) );
125 connect ( flattb, SIGNAL( toggled ( bool ) ), this, SLOT( changeFlat ( bool ) ) ); 125 connect ( flattb, SIGNAL( toggled(bool) ), this, SLOT( changeFlat(bool) ) );
126} 126}
127 127
128void LiquidSettings::changeType ( int t ) 128void LiquidSettings::changeType ( int t )
129{ 129{
130 bool custom = ( t == Custom ); 130 bool custom = ( t == Custom );
131 131
132 m_menulbl-> setEnabled ( custom ); 132 m_menulbl-> setEnabled ( custom );
133 m_textlbl-> setEnabled ( custom ); 133 m_textlbl-> setEnabled ( custom );
134 m_opaclbl-> setEnabled ( custom ); 134 m_opaclbl-> setEnabled ( custom );
135 m_menubtn-> setEnabled ( custom ); 135 m_menubtn-> setEnabled ( custom );
136 m_textbtn-> setEnabled ( custom ); 136 m_textbtn-> setEnabled ( custom );
137 m_opacsld-> setEnabled ( custom ); 137 m_opacsld-> setEnabled ( custom );
138 138
139 m_type = t; 139 m_type = t;
140} 140}
141 141
142void LiquidSettings::changeShadow ( bool b ) 142void LiquidSettings::changeShadow ( bool b )
143{ 143{
144 m_shadow = b; 144 m_shadow = b;
145} 145}
146 146
147void LiquidSettings::changeFlat ( bool b ) 147void LiquidSettings::changeFlat ( bool b )
148{ 148{
149 m_flat = b; 149 m_flat = b;
150} 150}
151 151
152 152
153bool LiquidSettings::writeConfig ( ) 153bool LiquidSettings::writeConfig ( )
154{ 154{
155 Config config ( "qpe" ); 155 Config config ( "qpe" );
156 config. setGroup ( "Liquid-Style" ); 156 config. setGroup ( "Liquid-Style" );
157 157
158 config. writeEntry ( "Type", m_type ); 158 config. writeEntry ( "Type", m_type );
159 config. writeEntry ( "Color", m_menubtn-> color ( ). name ( )); 159 config. writeEntry ( "Color", m_menubtn-> color ( ). name ( ));
160 config. writeEntry ( "TextColor", m_textbtn-> color ( ). name ( )); 160 config. writeEntry ( "TextColor", m_textbtn-> color ( ). name ( ));
161 config. writeEntry ( "Opacity", m_opacsld-> value ( )); 161 config. writeEntry ( "Opacity", m_opacsld-> value ( ));
162 config. writeEntry ( "ShadowText", m_shadow ); 162 config. writeEntry ( "ShadowText", m_shadow );
163 config. writeEntry ( "StippleContrast", m_contsld-> value ( )); 163 config. writeEntry ( "StippleContrast", m_contsld-> value ( ));
164 config. writeEntry ( "FlatToolButtons", m_flat ); 164 config. writeEntry ( "FlatToolButtons", m_flat );
165 config. write ( ); 165 config. write ( );
166 166
167 return true; 167 return true;
168} 168}
169 169
diff --git a/noncore/todayplugins/fortune/fortunepluginwidget.cpp b/noncore/todayplugins/fortune/fortunepluginwidget.cpp
index b210fa9..e6a0d09 100644
--- a/noncore/todayplugins/fortune/fortunepluginwidget.cpp
+++ b/noncore/todayplugins/fortune/fortunepluginwidget.cpp
@@ -1,84 +1,84 @@
1/* 1/*
2 * fortunepluginwidget.cpp 2 * fortunepluginwidget.cpp
3 * 3 *
4 * copyright : (c) 2002 by Maximilian Reiß 4 * copyright : (c) 2002 by Maximilian Reiß
5 * email : harlekin@handhelds.org 5 * email : harlekin@handhelds.org
6 * 6 *
7 */ 7 */
8/*************************************************************************** 8/***************************************************************************
9 * * 9 * *
10 * This program is free software; you can redistribute it and/or modify * 10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by * 11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or * 12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. * 13 * (at your option) any later version. *
14 * * 14 * *
15 ***************************************************************************/ 15 ***************************************************************************/
16 16
17#include "fortunepluginwidget.h" 17#include "fortunepluginwidget.h"
18 18
19#include <qvaluelist.h> 19#include <qvaluelist.h>
20#include <qtl.h> 20#include <qtl.h>
21#include <qstring.h> 21#include <qstring.h>
22#include <qscrollview.h> 22#include <qscrollview.h>
23#include <qobject.h> 23#include <qobject.h>
24#include <qlayout.h> 24#include <qlayout.h>
25 25
26#include <qpe/config.h> 26#include <qpe/config.h>
27#include <qpe/qcopenvelope_qws.h> 27#include <qpe/qcopenvelope_qws.h>
28 28
29#include <opie/oprocess.h> 29#include <opie/oprocess.h>
30#include <opie/oticker.h> 30#include <opie/oticker.h>
31 31
32FortunePluginWidget::FortunePluginWidget( QWidget *parent, const char* name ) 32FortunePluginWidget::FortunePluginWidget( QWidget *parent, const char* name )
33 : QWidget( parent, name ) 33 : QWidget( parent, name )
34{ 34{
35 35
36 fortune = NULL; 36 fortune = NULL;
37 getFortune(); 37 getFortune();
38} 38}
39 39
40FortunePluginWidget::~FortunePluginWidget() { 40FortunePluginWidget::~FortunePluginWidget() {
41 if( fortuneProcess ){ 41 if( fortuneProcess ){
42 delete fortuneProcess; 42 delete fortuneProcess;
43 } 43 }
44} 44}
45 45
46/** 46/**
47 * Get the fortunes 47 * Get the fortunes
48 */ 48 */
49void FortunePluginWidget::getFortune() { 49void FortunePluginWidget::getFortune() {
50 50
51 QVBoxLayout* layoutFortune = new QVBoxLayout( this ); 51 QVBoxLayout* layoutFortune = new QVBoxLayout( this );
52 52
53 if ( fortune ) { 53 if ( fortune ) {
54 delete fortune; 54 delete fortune;
55 } 55 }
56 56
57 fortune = new OTicker( this ); 57 fortune = new OTicker( this );
58 //fortune->setReadOnly( TRUE ); 58 //fortune->setReadOnly( TRUE );
59 //fortune->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) ); 59 //fortune->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) );
60 60
61 fortune->setText( QString("Obtaining fortune...") ); 61 fortune->setText( QString("Obtaining fortune...") );
62 layoutFortune->addWidget( fortune ); 62 layoutFortune->addWidget( fortune );
63 63
64 fortuneProcess = new OProcess(); 64 fortuneProcess = new OProcess();
65 *fortuneProcess << "fortune"; 65 *fortuneProcess << "fortune";
66 66
67 connect(fortuneProcess, SIGNAL(receivedStdout(OProcess*, char*, int ) ), 67 connect(fortuneProcess, SIGNAL(receivedStdout(OProcess*,char*,int) ),
68 this, SLOT(slotStdOut(OProcess*, char*, int) ) ); 68 this, SLOT(slotStdOut(OProcess*,char*,int) ) );
69 69
70 if(!fortuneProcess->start(OProcess::NotifyOnExit, OProcess::AllOutput) ) { 70 if(!fortuneProcess->start(OProcess::NotifyOnExit, OProcess::AllOutput) ) {
71 qWarning("could not start :("); 71 qWarning("could not start :(");
72 fortune->setText( QString("Failed to obtain fortune.") ); 72 fortune->setText( QString("Failed to obtain fortune.") );
73 delete fortuneProcess; 73 delete fortuneProcess;
74 fortuneProcess = 0; 74 fortuneProcess = 0;
75 } 75 }
76 76
77} 77}
78 78
79void FortunePluginWidget::slotStdOut( OProcess* proc, char* buf, int len ) 79void FortunePluginWidget::slotStdOut( OProcess* proc, char* buf, int len )
80{ 80{
81 QCString s( buf, len ); 81 QCString s( buf, len );
82 s.replace( QRegExp("\n"), "" ); 82 s.replace( QRegExp("\n"), "" );
83 fortune->setText( s ); 83 fortune->setText( s );
84} 84}
diff --git a/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp b/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp
index 2274402..db662e8 100644
--- a/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp
+++ b/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp
@@ -1,267 +1,267 @@
1/**************************************************************************** 1/****************************************************************************
2** 2**
3** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. 3** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
4** 4**
5** This file is part of an example program for Qt. This example 5** This file is part of an example program for Qt. This example
6** program may be used, distributed and modified without limitation. 6** program may be used, distributed and modified without limitation.
7** 7**
8*****************************************************************************/ 8*****************************************************************************/
9 9
10#include "helpwindow.h" 10#include "helpwindow.h"
11#include <qstatusbar.h> 11#include <qstatusbar.h>
12 12
13#include <qmenubar.h> 13#include <qmenubar.h>
14#include <qtoolbar.h> 14#include <qtoolbar.h>
15#include <qtoolbutton.h> 15#include <qtoolbutton.h>
16#include <qcombobox.h> 16#include <qcombobox.h>
17 17
18#include <ctype.h> 18#include <ctype.h>
19 19
20HelpWindow::HelpWindow( const QString& home_, const QString& _path, QWidget* parent, const char *name ) 20HelpWindow::HelpWindow( const QString& home_, const QString& _path, QWidget* parent, const char *name )
21 : QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL() 21 : QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL()
22{ 22{
23 readHistory(); 23 readHistory();
24 readBookmarks(); 24 readBookmarks();
25 25
26 browser = new QTextBrowser( this ); 26 browser = new QTextBrowser( this );
27 QStringList Strlist; 27 QStringList Strlist;
28 Strlist.append( home_); 28 Strlist.append( home_);
29 29
30 browser->mimeSourceFactory()->setFilePath( Strlist ); 30 browser->mimeSourceFactory()->setFilePath( Strlist );
31 31
32 browser->setFrameStyle( QFrame::Panel | QFrame::Sunken ); 32 browser->setFrameStyle( QFrame::Panel | QFrame::Sunken );
33 33
34 connect( browser, SIGNAL( textChanged() ), 34 connect( browser, SIGNAL( textChanged() ),
35 35
36 this, SLOT( textChanged() ) ); 36 this, SLOT( textChanged() ) );
37 37
38 setCentralWidget( browser ); 38 setCentralWidget( browser );
39 39
40 if ( !home_.isEmpty() ) 40 if ( !home_.isEmpty() )
41 41
42//////////////////////////////// 42////////////////////////////////
43 browser->setSource( home_ ); 43 browser->setSource( home_ );
44 44
45//////////////////////////////// 45////////////////////////////////
46 connect( browser, SIGNAL( highlighted( const QString&) ), 46 connect( browser, SIGNAL( highlighted(const QString&) ),
47 statusBar(), SLOT( message( const QString&)) ); 47 statusBar(), SLOT( message(const QString&)) );
48 48
49 setGeometry( 0,0,236,280); 49 setGeometry( 0,0,236,280);
50 50
51 QPopupMenu* file = new QPopupMenu( this ); 51 QPopupMenu* file = new QPopupMenu( this );
52// file->insertItem( tr("&New Window"), this, SLOT( newWindow() ), ALT | Key_N ); 52// file->insertItem( tr("&New Window"), this, SLOT( newWindow() ), ALT | Key_N );
53 file->insertItem( tr("&Open File"), this, SLOT( openFile() ), ALT | Key_O ); 53 file->insertItem( tr("&Open File"), this, SLOT( openFile() ), ALT | Key_O );
54// file->insertItem( tr("&Print"), this, SLOT( print() ), ALT | Key_P ); 54// file->insertItem( tr("&Print"), this, SLOT( print() ), ALT | Key_P );
55 file->insertSeparator(); 55 file->insertSeparator();
56 file->insertItem( tr("&Close"), this, SLOT( close() ), ALT | Key_Q ); 56 file->insertItem( tr("&Close"), this, SLOT( close() ), ALT | Key_Q );
57// file->insertItem( tr("E&xit"), qApp, SLOT( closeAllWindows() ), ALT | Key_X ); 57// file->insertItem( tr("E&xit"), qApp, SLOT( closeAllWindows() ), ALT | Key_X );
58 58
59 // The same three icons are used twice each. 59 // The same three icons are used twice each.
60////F FIXME 60////F FIXME
61 QString pixs=(QDir::homeDirPath ()) +"/Applications/gutenbrowser/pix/"; 61 QString pixs=(QDir::homeDirPath ()) +"/Applications/gutenbrowser/pix/";
62 QIconSet icon_back( QPixmap(pixs+"back.png") ); 62 QIconSet icon_back( QPixmap(pixs+"back.png") );
63 QIconSet icon_forward( QPixmap(pixs+"forward.png") ); 63 QIconSet icon_forward( QPixmap(pixs+"forward.png") );
64 QIconSet icon_home( QPixmap(pixs+"home.png") ); 64 QIconSet icon_home( QPixmap(pixs+"home.png") );
65 65
66 QPopupMenu* go = new QPopupMenu( this ); 66 QPopupMenu* go = new QPopupMenu( this );
67 backwardId = go->insertItem( icon_back, tr("&Backward"), browser, SLOT( backward() ), ALT | Key_Left ); 67 backwardId = go->insertItem( icon_back, tr("&Backward"), browser, SLOT( backward() ), ALT | Key_Left );
68 forwardId = go->insertItem( icon_forward, tr("&Forward"), browser, SLOT( forward() ), ALT | Key_Right ); 68 forwardId = go->insertItem( icon_forward, tr("&Forward"), browser, SLOT( forward() ), ALT | Key_Right );
69 go->insertItem( icon_home, tr("&Home"), browser, SLOT( home() ) ); 69 go->insertItem( icon_home, tr("&Home"), browser, SLOT( home() ) );
70 70
71 71
72 hist = new QPopupMenu( this ); 72 hist = new QPopupMenu( this );
73 QStringList::Iterator it = history.begin(); 73 QStringList::Iterator it = history.begin();
74 for ( ; it != history.end(); ++it ) 74 for ( ; it != history.end(); ++it )
75 mHistory[ hist->insertItem( *it ) ] = *it; 75 mHistory[ hist->insertItem( *it ) ] = *it;
76 connect( hist, SIGNAL( activated( int ) ), this, SLOT( histChosen( int ) ) ); 76 connect( hist, SIGNAL( activated(int) ), this, SLOT( histChosen(int) ) );
77 77
78 bookm = new QPopupMenu( this ); 78 bookm = new QPopupMenu( this );
79 bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) ); 79 bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) );
80 bookm->insertSeparator(); 80 bookm->insertSeparator();
81 81
82 QStringList::Iterator it2 = bookmarks.begin(); 82 QStringList::Iterator it2 = bookmarks.begin();
83 for ( ; it2 != bookmarks.end(); ++it2 ) 83 for ( ; it2 != bookmarks.end(); ++it2 )
84 mBookmarks[ bookm->insertItem( *it2 ) ] = *it2; 84 mBookmarks[ bookm->insertItem( *it2 ) ] = *it2;
85 connect( bookm, SIGNAL( activated( int ) ), 85 connect( bookm, SIGNAL( activated(int) ),
86 this, SLOT( bookmChosen( int ) ) ); 86 this, SLOT( bookmChosen(int) ) );
87 87
88 menuBar()->insertItem( tr("&File"), file ); 88 menuBar()->insertItem( tr("&File"), file );
89 menuBar()->insertItem( tr("&Go"), go ); 89 menuBar()->insertItem( tr("&Go"), go );
90 menuBar()->insertItem( tr( "History" ), hist ); 90 menuBar()->insertItem( tr( "History" ), hist );
91 menuBar()->insertItem( tr( "Bookmarks" ), bookm ); 91 menuBar()->insertItem( tr( "Bookmarks" ), bookm );
92// menuBar()->insertSeparator(); 92// menuBar()->insertSeparator();
93// menuBar()->insertItem( tr("&Help"), help ); 93// menuBar()->insertItem( tr("&Help"), help );
94 94
95 menuBar()->setItemEnabled( forwardId, FALSE); 95 menuBar()->setItemEnabled( forwardId, FALSE);
96 menuBar()->setItemEnabled( backwardId, FALSE); 96 menuBar()->setItemEnabled( backwardId, FALSE);
97 connect( browser, SIGNAL( backwardAvailable( bool ) ), this, SLOT( setBackwardAvailable( bool ) ) ); 97 connect( browser, SIGNAL( backwardAvailable(bool) ), this, SLOT( setBackwardAvailable(bool) ) );
98 connect( browser, SIGNAL( forwardAvailable( bool ) ), this, SLOT( setForwardAvailable( bool ) ) ); 98 connect( browser, SIGNAL( forwardAvailable(bool) ), this, SLOT( setForwardAvailable(bool) ) );
99 99
100 100
101 QToolBar* toolbar = new QToolBar( this ); 101 QToolBar* toolbar = new QToolBar( this );
102 addToolBar( toolbar, "Toolbar"); 102 addToolBar( toolbar, "Toolbar");
103 QToolButton* button; 103 QToolButton* button;
104 104
105 button = new QToolButton( icon_back, tr("Backward"), "", browser, SLOT(backward()), toolbar ); 105 button = new QToolButton( icon_back, tr("Backward"), "", browser, SLOT(backward()), toolbar );
106 connect( browser, SIGNAL( backwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) ); 106 connect( browser, SIGNAL( backwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) );
107 button->setEnabled( FALSE ); 107 button->setEnabled( FALSE );
108 button = new QToolButton( icon_forward, tr("Forward"), "", browser, SLOT(forward()), toolbar ); 108 button = new QToolButton( icon_forward, tr("Forward"), "", browser, SLOT(forward()), toolbar );
109 connect( browser, SIGNAL( forwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) ); 109 connect( browser, SIGNAL( forwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) );
110 button->setEnabled( FALSE ); 110 button->setEnabled( FALSE );
111 button = new QToolButton( icon_home, tr("Home"), "", browser, SLOT(home()), toolbar ); 111 button = new QToolButton( icon_home, tr("Home"), "", browser, SLOT(home()), toolbar );
112 112
113 toolbar->addSeparator(); 113 toolbar->addSeparator();
114 114
115 pathCombo = new QComboBox( TRUE, toolbar ); 115 pathCombo = new QComboBox( TRUE, toolbar );
116 connect( pathCombo, SIGNAL( activated( const QString & ) ), this, SLOT( pathSelected( const QString & ) ) ); 116 connect( pathCombo, SIGNAL( activated(const QString&) ), this, SLOT( pathSelected(const QString&) ) );
117 toolbar->setStretchableWidget( pathCombo ); 117 toolbar->setStretchableWidget( pathCombo );
118 118
119// pathCombo->setMaximumWidth(190); 119// pathCombo->setMaximumWidth(190);
120// setRightJustification( TRUE ); 120// setRightJustification( TRUE );
121// setDockEnabled( Left, FALSE ); 121// setDockEnabled( Left, FALSE );
122// setDockEnabled( Right, FALSE ); 122// setDockEnabled( Right, FALSE );
123 123
124 pathCombo->insertItem( home_ ); 124 pathCombo->insertItem( home_ );
125 125
126 browser->setFocus(); 126 browser->setFocus();
127 127
128 128
129} 129}
130 130
131 131
132void HelpWindow::setBackwardAvailable( bool b) 132void HelpWindow::setBackwardAvailable( bool b)
133{ 133{
134 menuBar()->setItemEnabled( backwardId, b); 134 menuBar()->setItemEnabled( backwardId, b);
135} 135}
136 136
137void HelpWindow::setForwardAvailable( bool b) 137void HelpWindow::setForwardAvailable( bool b)
138{ 138{
139 menuBar()->setItemEnabled( forwardId, b); 139 menuBar()->setItemEnabled( forwardId, b);
140} 140}
141 141
142 142
143void HelpWindow::textChanged() 143void HelpWindow::textChanged()
144{ 144{
145 if ( browser->documentTitle().isNull() ) { 145 if ( browser->documentTitle().isNull() ) {
146 setCaption( "Stockticker Lookup - " + browser->context() ); 146 setCaption( "Stockticker Lookup - " + browser->context() );
147 selectedURL = browser->context(); 147 selectedURL = browser->context();
148 } 148 }
149 else { 149 else {
150 setCaption( "Stockticker Lookup - " + browser->documentTitle() ) ; 150 setCaption( "Stockticker Lookup - " + browser->documentTitle() ) ;
151 selectedURL = browser->documentTitle(); 151 selectedURL = browser->documentTitle();
152 } 152 }
153 153
154 if ( !selectedURL.isEmpty() && pathCombo ) { 154 if ( !selectedURL.isEmpty() && pathCombo ) {
155 bool exists = FALSE; 155 bool exists = FALSE;
156 int i; 156 int i;
157 for ( i = 0; i < pathCombo->count(); ++i ) { 157 for ( i = 0; i < pathCombo->count(); ++i ) {
158 if ( pathCombo->text( i ) == selectedURL ) { 158 if ( pathCombo->text( i ) == selectedURL ) {
159 exists = TRUE; 159 exists = TRUE;
160 break; 160 break;
161 } 161 }
162 } 162 }
163 if ( !exists ) { 163 if ( !exists ) {
164 pathCombo->insertItem( selectedURL, 0 ); 164 pathCombo->insertItem( selectedURL, 0 );
165 pathCombo->setCurrentItem( 0 ); 165 pathCombo->setCurrentItem( 0 );
166 mHistory[ hist->insertItem( selectedURL ) ] = selectedURL; 166 mHistory[ hist->insertItem( selectedURL ) ] = selectedURL;
167 } else 167 } else
168 pathCombo->setCurrentItem( i ); 168 pathCombo->setCurrentItem( i );
169 selectedURL = QString::null; 169 selectedURL = QString::null;
170 } 170 }
171} 171}
172 172
173HelpWindow::~HelpWindow() 173HelpWindow::~HelpWindow()
174{ 174{
175 history.clear(); 175 history.clear();
176 QMap<int, QString>::Iterator it = mHistory.begin(); 176 QMap<int, QString>::Iterator it = mHistory.begin();
177 for ( ; it != mHistory.end(); ++it ) 177 for ( ; it != mHistory.end(); ++it )
178 history.append( *it ); 178 history.append( *it );
179 179
180 QFile f( QDir::currentDirPath() + "/.history" ); 180 QFile f( QDir::currentDirPath() + "/.history" );
181 f.open( IO_WriteOnly ); 181 f.open( IO_WriteOnly );
182 QDataStream s( &f ); 182 QDataStream s( &f );
183 s << history; 183 s << history;
184 f.close(); 184 f.close();
185 185
186 bookmarks.clear(); 186 bookmarks.clear();
187 QMap<int, QString>::Iterator it2 = mBookmarks.begin(); 187 QMap<int, QString>::Iterator it2 = mBookmarks.begin();
188 for ( ; it2 != mBookmarks.end(); ++it2 ) 188 for ( ; it2 != mBookmarks.end(); ++it2 )
189 bookmarks.append( *it2 ); 189 bookmarks.append( *it2 );
190 190
191 QFile f2( QDir::currentDirPath() + "/.bookmarks" ); 191 QFile f2( QDir::currentDirPath() + "/.bookmarks" );
192 f2.open( IO_WriteOnly ); 192 f2.open( IO_WriteOnly );
193 QDataStream s2( &f2 ); 193 QDataStream s2( &f2 );
194 s2 << bookmarks; 194 s2 << bookmarks;
195 f2.close(); 195 f2.close();
196} 196}
197 197
198void HelpWindow::openFile() 198void HelpWindow::openFile()
199{ 199{
200#ifndef QT_NO_FILEDIALOG 200#ifndef QT_NO_FILEDIALOG
201 QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this ); 201 QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this );
202 if ( !fn.isEmpty() ) 202 if ( !fn.isEmpty() )
203 browser->setSource( fn ); 203 browser->setSource( fn );
204#endif 204#endif
205} 205}
206 206
207void HelpWindow::newWindow() 207void HelpWindow::newWindow()
208{ 208{
209 ( new HelpWindow(browser->source(), "qbrowser") )->show(); 209 ( new HelpWindow(browser->source(), "qbrowser") )->show();
210} 210}
211 211
212void HelpWindow::pathSelected( const QString &_path ) 212void HelpWindow::pathSelected( const QString &_path )
213{ 213{
214 browser->setSource( _path ); 214 browser->setSource( _path );
215 QMap<int, QString>::Iterator it = mHistory.begin(); 215 QMap<int, QString>::Iterator it = mHistory.begin();
216 bool exists = FALSE; 216 bool exists = FALSE;
217 for ( ; it != mHistory.end(); ++it ) { 217 for ( ; it != mHistory.end(); ++it ) {
218 if ( *it == _path ) { 218 if ( *it == _path ) {
219 exists = TRUE; 219 exists = TRUE;
220 break; 220 break;
221 } 221 }
222 } 222 }
223 if ( !exists ) 223 if ( !exists )
224 mHistory[ hist->insertItem( _path ) ] = _path; 224 mHistory[ hist->insertItem( _path ) ] = _path;
225} 225}
226 226
227void HelpWindow::readHistory() 227void HelpWindow::readHistory()
228{ 228{
229 if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) { 229 if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) {
230 QFile f( QDir::currentDirPath() + "/.history" ); 230 QFile f( QDir::currentDirPath() + "/.history" );
231 f.open( IO_ReadOnly ); 231 f.open( IO_ReadOnly );
232 QDataStream s( &f ); 232 QDataStream s( &f );
233 s >> history; 233 s >> history;
234 f.close(); 234 f.close();
235 while ( history.count() > 20 ) 235 while ( history.count() > 20 )
236 history.remove( history.begin() ); 236 history.remove( history.begin() );
237 } 237 }
238} 238}
239 239
240void HelpWindow::readBookmarks() 240void HelpWindow::readBookmarks()
241{ 241{
242 if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) { 242 if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) {
243 QFile f( QDir::currentDirPath() + "/.bookmarks" ); 243 QFile f( QDir::currentDirPath() + "/.bookmarks" );
244 f.open( IO_ReadOnly ); 244 f.open( IO_ReadOnly );
245 QDataStream s( &f ); 245 QDataStream s( &f );
246 s >> bookmarks; 246 s >> bookmarks;
247 f.close(); 247 f.close();
248 } 248 }
249} 249}
250 250
251void HelpWindow::histChosen( int i ) 251void HelpWindow::histChosen( int i )
252{ 252{
253 if ( mHistory.contains( i ) ) 253 if ( mHistory.contains( i ) )
254 browser->setSource( mHistory[ i ] ); 254 browser->setSource( mHistory[ i ] );
255} 255}
256 256
257void HelpWindow::bookmChosen( int i ) 257void HelpWindow::bookmChosen( int i )
258{ 258{
259 if ( mBookmarks.contains( i ) ) 259 if ( mBookmarks.contains( i ) )
260 browser->setSource( mBookmarks[ i ] ); 260 browser->setSource( mBookmarks[ i ] );
261} 261}
262 262
263void HelpWindow::addBookmark() 263void HelpWindow::addBookmark()
264{ 264{
265 mBookmarks[ bookm->insertItem( caption() ) ] = caption(); 265 mBookmarks[ bookm->insertItem( caption() ) ] = caption();
266} 266}
267 267
diff --git a/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp b/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp
index 73f8bb3..64798f4 100644
--- a/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp
+++ b/noncore/todayplugins/stockticker/stockticker/inputDialog.cpp
@@ -1,89 +1,89 @@
1#include "inputDialog.h" 1#include "inputDialog.h"
2 2
3#include <qapplication.h> 3#include <qapplication.h>
4 4
5#include <qlayout.h> 5#include <qlayout.h>
6#include <qcheckbox.h> 6#include <qcheckbox.h>
7#include <qlineedit.h> 7#include <qlineedit.h>
8#include <qvariant.h> 8#include <qvariant.h>
9#include <qpushbutton.h> 9#include <qpushbutton.h>
10#include <qwhatsthis.h> 10#include <qwhatsthis.h>
11#include <qlabel.h> 11#include <qlabel.h>
12#include <qlayout.h> 12#include <qlayout.h>
13#include <qpe/config.h> 13#include <qpe/config.h>
14#include <qstringlist.h> 14#include <qstringlist.h>
15#include <qmainwindow.h> 15#include <qmainwindow.h>
16#include "helpwindow.h" 16#include "helpwindow.h"
17 17
18#include <opie/oprocess.h> 18#include <opie/oprocess.h>
19 19
20#include <stdlib.h> 20#include <stdlib.h>
21// #include <sys/stat.h> 21// #include <sys/stat.h>
22// #include <unistd.h> 22// #include <unistd.h>
23 23
24InputDialog::InputDialog( ) 24InputDialog::InputDialog( )
25 : QMainWindow( 0x0, 0x0, WStyle_ContextHelp ) { 25 : QMainWindow( 0x0, 0x0, WStyle_ContextHelp ) {
26 setCaption( tr("Symbol Lookup")); 26 setCaption( tr("Symbol Lookup"));
27 27
28 QGridLayout *layout = new QGridLayout( this ); 28 QGridLayout *layout = new QGridLayout( this );
29 layout->setSpacing(6); 29 layout->setSpacing(6);
30 layout->setMargin( 2); 30 layout->setMargin( 2);
31 31
32 LineEdit1 = new QLineEdit( this, "LineEdit1" ); 32 LineEdit1 = new QLineEdit( this, "LineEdit1" );
33 LineEdit1->setFocus(); 33 LineEdit1->setFocus();
34 34
35 layout->addMultiCellWidget( LineEdit1, 0, 0, 0, 3); 35 layout->addMultiCellWidget( LineEdit1, 0, 0, 0, 3);
36 36
37 QLabel *label; 37 QLabel *label;
38 label = new QLabel(this); 38 label = new QLabel(this);
39 label->setText( tr("Enter something to lookup / search.")); 39 label->setText( tr("Enter something to lookup / search."));
40 label->setMaximumHeight(60); 40 label->setMaximumHeight(60);
41 layout->addMultiCellWidget( label, 1, 1, 0, 3); 41 layout->addMultiCellWidget( label, 1, 1, 0, 3);
42 42
43 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(doLookup())); 43 connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(doLookup()));
44 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding ); 44 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Expanding );
45 layout->addItem( spacer, 8, 0 ); 45 layout->addItem( spacer, 8, 0 );
46 46
47} 47}
48 48
49InputDialog::~InputDialog() { 49InputDialog::~InputDialog() {
50} 50}
51 51
52void InputDialog::doLookup() { 52void InputDialog::doLookup() {
53// http://finance.yahoo.com/l?m=&s=siemens&t= 53// http://finance.yahoo.com/l?m=&s=siemens&t=
54 54
55 QString url = "\"http://finance.yahoo.com/l?m=&s="+LineEdit1->text()+"\""; 55 QString url = "\"http://finance.yahoo.com/l?m=&s="+LineEdit1->text()+"\"";
56 QString tempHtml = "/tmp/stockticker.html"; 56 QString tempHtml = "/tmp/stockticker.html";
57 QString cmd = "wget -O "+tempHtml+" "+url; 57 QString cmd = "wget -O "+tempHtml+" "+url;
58 qDebug(cmd); 58 qDebug(cmd);
59 59
60 60
61/* 61/*
62 OProcess proc; 62 OProcess proc;
63 proc << "/usr/bin/wget"; 63 proc << "/usr/bin/wget";
64 proc<<"-O"<< tempHtml<< url; 64 proc<<"-O"<< tempHtml<< url;
65 65
66 connect( &proc, SIGNAL( processExited( OProcess *)),this, SLOT( showBrowser(OProcess *))); 66 connect( &proc, SIGNAL( processExited(OProcess*)),this, SLOT( showBrowser(OProcess*)));
67 proc.start( OProcess::NotifyOnExit); 67 proc.start( OProcess::NotifyOnExit);
68*/ 68*/
69 system(cmd.latin1()); 69 system(cmd.latin1());
70 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup"); 70 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup");
71 StockLookup->setCaption("Symbol"); 71 StockLookup->setCaption("Symbol");
72 StockLookup->showMaximized(); 72 StockLookup->showMaximized();
73 StockLookup->show(); 73 StockLookup->show();
74 LineEdit1->text(); 74 LineEdit1->text();
75 75
76 76
77} 77}
78 78
79void InputDialog::showBrowser(OProcess*) { 79void InputDialog::showBrowser(OProcess*) {
80 qDebug("BLAH"); 80 qDebug("BLAH");
81 QString tempHtml = "/tmp/stockticker.html"; 81 QString tempHtml = "/tmp/stockticker.html";
82 82
83 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup"); 83 HelpWindow *StockLookup = new HelpWindow( tempHtml,".",this, "SymbolLookup");
84 StockLookup->setCaption("Symbol"); 84 StockLookup->setCaption("Symbol");
85 StockLookup->showMaximized(); 85 StockLookup->showMaximized();
86 StockLookup->show(); 86 StockLookup->show();
87 LineEdit1->text(); 87 LineEdit1->text();
88 88
89} 89}
diff --git a/noncore/todayplugins/weather/weatherpluginwidget.cpp b/noncore/todayplugins/weather/weatherpluginwidget.cpp
index 4491b91..15d1c6e 100644
--- a/noncore/todayplugins/weather/weatherpluginwidget.cpp
+++ b/noncore/todayplugins/weather/weatherpluginwidget.cpp
@@ -1,325 +1,325 @@
1/* 1/*
2                This file is part of the OPIE Project 2                This file is part of the OPIE Project
3 =. 3 =.
4             .=l. Copyright (c) 2002 Dan Williams <williamsdr@acm.org> 4             .=l. Copyright (c) 2002 Dan Williams <williamsdr@acm.org>
5           .>+-= 5           .>+-=
6 _;:,     .>    :=|. This file is free software; you can 6 _;:,     .>    :=|. This file is free software; you can
7.> <`_,   >  .   <= redistribute it and/or modify it under 7.> <`_,   >  .   <= redistribute it and/or modify it under
8:`=1 )Y*s>-.--   : the terms of the GNU General Public 8:`=1 )Y*s>-.--   : the terms of the GNU General Public
9.="- .-=="i,     .._ License as published by the Free Software 9.="- .-=="i,     .._ License as published by the Free Software
10 - .   .-<_>     .<> Foundation; either version 2 of the License, 10 - .   .-<_>     .<> Foundation; either version 2 of the License,
11     ._= =}       : or (at your option) any later version. 11     ._= =}       : or (at your option) any later version.
12    .%`+i>       _;_. 12    .%`+i>       _;_.
13    .i_,=:_.      -<s. This file is distributed in the hope that 13    .i_,=:_.      -<s. This file is distributed in the hope that
14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY; 14     +  .  -:.       = it will be useful, but WITHOUT ANY WARRANTY;
15    : ..    .:,     . . . without even the implied warranty of 15    : ..    .:,     . . . without even the implied warranty of
16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A 16    =_        +     =;=|` MERCHANTABILITY or FITNESS FOR A
17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General 17  _.=:.       :    :=>`: PARTICULAR PURPOSE. See the GNU General
18..}^=.=       =       ; Public License for more details. 18..}^=.=       =       ; Public License for more details.
19++=   -.     .`     .: 19++=   -.     .`     .:
20 :     =  ...= . :.=- You should have received a copy of the GNU 20 :     =  ...= . :.=- You should have received a copy of the GNU
21 -.   .:....=;==+<; General Public License along with this file; 21 -.   .:....=;==+<; General Public License along with this file;
22  -_. . .   )=.  = see the file COPYING. If not, write to the 22  -_. . .   )=.  = see the file COPYING. If not, write to the
23    --        :-=` Free Software Foundation, Inc., 23    --        :-=` Free Software Foundation, Inc.,
24 59 Temple Place - Suite 330, 24 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA. 25 Boston, MA 02111-1307, USA.
26 26
27*/ 27*/
28 28
29#include <qfile.h> 29#include <qfile.h>
30#include <qimage.h> 30#include <qimage.h>
31#include <qlabel.h> 31#include <qlabel.h>
32#include <qlayout.h> 32#include <qlayout.h>
33#include <qpixmap.h> 33#include <qpixmap.h>
34#include <qtextstream.h> 34#include <qtextstream.h>
35 35
36#include <opie/oprocess.h> 36#include <opie/oprocess.h>
37 37
38#include <qpe/config.h> 38#include <qpe/config.h>
39#include <qpe/resource.h> 39#include <qpe/resource.h>
40 40
41#include "weatherpluginwidget.h" 41#include "weatherpluginwidget.h"
42 42
43WeatherPluginWidget::WeatherPluginWidget( QWidget *parent, const char* name ) 43WeatherPluginWidget::WeatherPluginWidget( QWidget *parent, const char* name )
44 : QWidget( parent, name ) 44 : QWidget( parent, name )
45{ 45{
46 QHBoxLayout *layout = new QHBoxLayout( this ); 46 QHBoxLayout *layout = new QHBoxLayout( this );
47 layout->setAutoAdd( TRUE ); 47 layout->setAutoAdd( TRUE );
48 layout->setSpacing( 2 ); 48 layout->setSpacing( 2 );
49 49
50 weatherIcon = new QLabel( this ); 50 weatherIcon = new QLabel( this );
51 weatherIcon->setMaximumWidth( 32 ); 51 weatherIcon->setMaximumWidth( 32 );
52 QImage logo1 = Resource::loadImage( "Clock" ); 52 QImage logo1 = Resource::loadImage( "Clock" );
53 QPixmap pic; 53 QPixmap pic;
54 pic.convertFromImage( logo1 ); 54 pic.convertFromImage( logo1 );
55 weatherIcon->setPixmap( pic ); 55 weatherIcon->setPixmap( pic );
56 56
57 weatherLabel = new QLabel( tr( "Retreiving current weather information." ), this ); 57 weatherLabel = new QLabel( tr( "Retreiving current weather information." ), this );
58 weatherLabel->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ) ); 58 weatherLabel->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ) );
59 59
60 startTimer(1000); 60 startTimer(1000);
61} 61}
62 62
63WeatherPluginWidget::~WeatherPluginWidget() 63WeatherPluginWidget::~WeatherPluginWidget()
64{ 64{
65 QFile file( localFile ); 65 QFile file( localFile );
66 if ( file.exists() ) 66 if ( file.exists() )
67 { 67 {
68 file.remove(); 68 file.remove();
69 } 69 }
70} 70}
71 71
72void WeatherPluginWidget::timerEvent( QTimerEvent *e ) 72void WeatherPluginWidget::timerEvent( QTimerEvent *e )
73{ 73{
74 killTimer( e->timerId() ); 74 killTimer( e->timerId() );
75 retreiveData(); 75 retreiveData();
76} 76}
77 77
78 78
79 79
80void WeatherPluginWidget::retreiveData() 80void WeatherPluginWidget::retreiveData()
81{ 81{
82 Config config( "todayweatherplugin"); 82 Config config( "todayweatherplugin");
83 config.setGroup( "Config" ); 83 config.setGroup( "Config" );
84 84
85 location = config.readEntry( "Location", "" ); 85 location = config.readEntry( "Location", "" );
86 useMetric = config.readBoolEntry( "Metric", TRUE ); 86 useMetric = config.readBoolEntry( "Metric", TRUE );
87 frequency = config.readNumEntry( "Frequency", 5 ); 87 frequency = config.readNumEntry( "Frequency", 5 );
88 88
89 startTimer( frequency * 60000 ); 89 startTimer( frequency * 60000 );
90 90
91 localFile = "/tmp/"; 91 localFile = "/tmp/";
92 localFile.append( location ); 92 localFile.append( location );
93 localFile.append( ".TXT" ); 93 localFile.append( ".TXT" );
94 94
95 remoteFile = "http://weather.noaa.gov/pub/data/observations/metar/stations/"; 95 remoteFile = "http://weather.noaa.gov/pub/data/observations/metar/stations/";
96 remoteFile.append( location ); 96 remoteFile.append( location );
97 remoteFile.append( ".TXT" ); 97 remoteFile.append( ".TXT" );
98 98
99 QFile file( localFile ); 99 QFile file( localFile );
100 if ( file.exists() ) 100 if ( file.exists() )
101 { 101 {
102 file.remove(); 102 file.remove();
103 } 103 }
104 104
105 OProcess *proc = new OProcess; 105 OProcess *proc = new OProcess;
106 106
107 *proc << "wget" << "-q" << remoteFile << "-O" << localFile; 107 *proc << "wget" << "-q" << remoteFile << "-O" << localFile;
108 connect( proc, SIGNAL( processExited( OProcess * ) ), this, SLOT( dataRetrieved( OProcess * ) ) ); 108 connect( proc, SIGNAL( processExited(OProcess*) ), this, SLOT( dataRetrieved(OProcess*) ) );
109 proc->start(); 109 proc->start();
110} 110}
111 111
112void WeatherPluginWidget::displayWeather() 112void WeatherPluginWidget::displayWeather()
113{ 113{
114 weatherData = QString::null; 114 weatherData = QString::null;
115 115
116 QFile file( localFile ); 116 QFile file( localFile );
117 117
118 if ( file.size() > 0 && file.open( IO_ReadOnly ) ) 118 if ( file.size() > 0 && file.open( IO_ReadOnly ) )
119 { 119 {
120 QTextStream data( &file ); 120 QTextStream data( &file );
121 while ( !data.eof() ) 121 while ( !data.eof() )
122 { 122 {
123 weatherData.append( data.readLine() ); 123 weatherData.append( data.readLine() );
124 } 124 }
125 file.close(); 125 file.close();
126 weatherData = weatherData.simplifyWhiteSpace(); 126 weatherData = weatherData.simplifyWhiteSpace();
127 127
128 QString tmpstr; 128 QString tmpstr;
129 129
130 tmpstr.append( tr( "Temp: " ) ); 130 tmpstr.append( tr( "Temp: " ) );
131 getTemp( weatherData ); 131 getTemp( weatherData );
132 tmpstr.append( dataStr ); 132 tmpstr.append( dataStr );
133 133
134 tmpstr.append( tr( " Wind: " ) ); 134 tmpstr.append( tr( " Wind: " ) );
135 getWind( weatherData ); 135 getWind( weatherData );
136 tmpstr.append( dataStr ); 136 tmpstr.append( dataStr );
137 137
138 tmpstr.append( tr( "\nPres: " ) ); 138 tmpstr.append( tr( "\nPres: " ) );
139 getPressure( weatherData ); 139 getPressure( weatherData );
140 tmpstr.append( dataStr ); 140 tmpstr.append( dataStr );
141 141
142 weatherLabel->setText( tmpstr ); 142 weatherLabel->setText( tmpstr );
143 143
144 tmpstr = "todayweatherplugin/"; 144 tmpstr = "todayweatherplugin/";
145 getIcon( weatherData ); 145 getIcon( weatherData );
146 tmpstr.append( dataStr ); 146 tmpstr.append( dataStr );
147 QImage logo1 = Resource::loadImage( tmpstr ); 147 QImage logo1 = Resource::loadImage( tmpstr );
148 QPixmap pic; 148 QPixmap pic;
149 pic.convertFromImage( logo1 ); 149 pic.convertFromImage( logo1 );
150 weatherIcon->setPixmap( pic ); 150 weatherIcon->setPixmap( pic );
151 } 151 }
152 else 152 else
153 { 153 {
154 weatherLabel->setText( tr( "Current weather data not available." ) ); 154 weatherLabel->setText( tr( "Current weather data not available." ) );
155 } 155 }
156} 156}
157 157
158void WeatherPluginWidget::getTemp( const QString &data ) 158void WeatherPluginWidget::getTemp( const QString &data )
159{ 159{
160 int value; 160 int value;
161 bool ok; 161 bool ok;
162 162
163 int pos = data.find( QRegExp( "M?[0-9]+/M?[0-9]+" ), 20 ); 163 int pos = data.find( QRegExp( "M?[0-9]+/M?[0-9]+" ), 20 );
164 if ( pos > -1 ) 164 if ( pos > -1 )
165 { 165 {
166 if ( data.at( pos ) == 'M' ) 166 if ( data.at( pos ) == 'M' )
167 { 167 {
168 value = -1 * data.mid( pos + 1, 2 ).toInt( &ok ); 168 value = -1 * data.mid( pos + 1, 2 ).toInt( &ok );
169 } 169 }
170 else 170 else
171 { 171 {
172 value = data.mid( pos, 2 ).toInt( &ok ); 172 value = data.mid( pos, 2 ).toInt( &ok );
173 } 173 }
174 if ( useMetric ) 174 if ( useMetric )
175 { 175 {
176 dataStr = QString::number( value ); 176 dataStr = QString::number( value );
177 dataStr.append( 'C' ); 177 dataStr.append( 'C' );
178 } 178 }
179 else 179 else
180 { 180 {
181 dataStr = QString::number( ( value * 9 / 5 ) + 32 ); 181 dataStr = QString::number( ( value * 9 / 5 ) + 32 );
182 dataStr.append( 'F' ); 182 dataStr.append( 'F' );
183 } 183 }
184 } 184 }
185 else 185 else
186 { 186 {
187 dataStr = tr( "n/a" ); 187 dataStr = tr( "n/a" );
188 } 188 }
189} 189}
190 190
191void WeatherPluginWidget::getWind( const QString &data ) 191void WeatherPluginWidget::getWind( const QString &data )
192{ 192{
193 int value; 193 int value;
194 bool ok; 194 bool ok;
195 195
196 int pos = data.find( QRegExp( "[0-9]*G*[0-9]*KT" ), 20 ); 196 int pos = data.find( QRegExp( "[0-9]*G*[0-9]*KT" ), 20 );
197 if ( pos > -1 ) 197 if ( pos > -1 )
198 { 198 {
199 if ( data.mid( pos, 3 ) != "VRB" ) 199 if ( data.mid( pos, 3 ) != "VRB" )
200 { 200 {
201 value = data.mid( pos, 3 ).toInt( &ok ); 201 value = data.mid( pos, 3 ).toInt( &ok );
202 if ( ( value >= 0 && value < 23 ) || ( value >= 239 && value <= 360 ) ) 202 if ( ( value >= 0 && value < 23 ) || ( value >= 239 && value <= 360 ) )
203 dataStr = tr("E " ); 203 dataStr = tr("E " );
204 else if ( value >= 23 && value < 69 ) 204 else if ( value >= 23 && value < 69 )
205 dataStr = tr( "NE " ); 205 dataStr = tr( "NE " );
206 else if ( value >= 69 && value < 113 ) 206 else if ( value >= 69 && value < 113 )
207 dataStr = tr( "N " ); 207 dataStr = tr( "N " );
208 else if ( value >= 113 && value < 157 ) 208 else if ( value >= 113 && value < 157 )
209 dataStr = tr( "NW " ); 209 dataStr = tr( "NW " );
210 else if ( value >= 157 && value < 203 ) 210 else if ( value >= 157 && value < 203 )
211 dataStr = tr( "W " ); 211 dataStr = tr( "W " );
212 else if ( value >= 203 && value < 248 ) 212 else if ( value >= 203 && value < 248 )
213 dataStr = tr( "SW " ); 213 dataStr = tr( "SW " );
214 else if ( value >= 248 && value < 294 ) 214 else if ( value >= 248 && value < 294 )
215 dataStr = tr( "S " ); 215 dataStr = tr( "S " );
216 else if ( value >= 294 && value < 238 ) 216 else if ( value >= 294 && value < 238 )
217 dataStr = tr( "SE " ); 217 dataStr = tr( "SE " );
218 } 218 }
219 if ( data.mid( pos + 5, 1) == "G" || 219 if ( data.mid( pos + 5, 1) == "G" ||
220 data.mid( pos + 5, 1) == "K" ) 220 data.mid( pos + 5, 1) == "K" )
221 { 221 {
222 value = data.mid( pos + 3, 2 ).toInt( &ok ); 222 value = data.mid( pos + 3, 2 ).toInt( &ok );
223 } 223 }
224 else 224 else
225 { 225 {
226 value = data.mid( pos + 3, 3 ).toInt( &ok ); 226 value = data.mid( pos + 3, 3 ).toInt( &ok );
227 } 227 }
228 if ( useMetric ) 228 if ( useMetric )
229 { 229 {
230 value = value * 3.6 / 1.94; 230 value = value * 3.6 / 1.94;
231 dataStr.append( QString::number( value ) ); 231 dataStr.append( QString::number( value ) );
232 dataStr.append( tr( " KPH" ) ); 232 dataStr.append( tr( " KPH" ) );
233 } 233 }
234 else 234 else
235 { 235 {
236 value = value * 2.24 / 1.94; 236 value = value * 2.24 / 1.94;
237 dataStr.append( QString::number( value ) ); 237 dataStr.append( QString::number( value ) );
238 dataStr.append( tr( " MPH" ) ); 238 dataStr.append( tr( " MPH" ) );
239 } 239 }
240 } 240 }
241 else 241 else
242 { 242 {
243 dataStr = tr( "n/a" ); 243 dataStr = tr( "n/a" );
244 } 244 }
245} 245}
246 246
247void WeatherPluginWidget::getPressure( const QString &data ) 247void WeatherPluginWidget::getPressure( const QString &data )
248{ 248{
249 float value; 249 float value;
250 bool ok; 250 bool ok;
251 251
252 int pos = data.find( QRegExp( "[AQ][0-9]+" ), 20 ); 252 int pos = data.find( QRegExp( "[AQ][0-9]+" ), 20 );
253 if ( pos > -1 ) 253 if ( pos > -1 )
254 { 254 {
255 value = data.mid( pos + 1, 4 ).toFloat( &ok ); 255 value = data.mid( pos + 1, 4 ).toFloat( &ok );
256 if ( useMetric ) 256 if ( useMetric )
257 { 257 {
258 if ( data.mid( pos, 1 ) == "A" ) 258 if ( data.mid( pos, 1 ) == "A" )
259 value *= 33.8639 / 100; 259 value *= 33.8639 / 100;
260 dataStr = QString::number( value, 'f', 2 ); 260 dataStr = QString::number( value, 'f', 2 );
261 dataStr.append( tr( " kPa" ) ); 261 dataStr.append( tr( " kPa" ) );
262 } 262 }
263 else 263 else
264 { 264 {
265 if ( data.mid( pos, 1 ) == "Q" ) 265 if ( data.mid( pos, 1 ) == "Q" )
266 value /= 33.8639; 266 value /= 33.8639;
267 else 267 else
268 value /= 100; 268 value /= 100;
269 dataStr = QString::number( value, 'f', 2 ); 269 dataStr = QString::number( value, 'f', 2 );
270 dataStr.append( tr( " Hg" ) ); 270 dataStr.append( tr( " Hg" ) );
271 } 271 }
272 } 272 }
273 else 273 else
274 { 274 {
275 dataStr = tr( "n/a" ); 275 dataStr = tr( "n/a" );
276 } 276 }
277} 277}
278 278
279void WeatherPluginWidget::getIcon(const QString &data ) 279void WeatherPluginWidget::getIcon(const QString &data )
280{ 280{
281 dataStr = "psunny"; 281 dataStr = "psunny";
282 if ( data.find( "CLR ", 20 ) > -1 || 282 if ( data.find( "CLR ", 20 ) > -1 ||
283 data.find( "SKC ", 20 ) > -1 || 283 data.find( "SKC ", 20 ) > -1 ||
284 data.find( "CAVOK ", 20 ) > -1 ) 284 data.find( "CAVOK ", 20 ) > -1 )
285 { 285 {
286 dataStr = "sunny"; 286 dataStr = "sunny";
287 } 287 }
288 else if ( data.find( "SH ", 20 ) > -1 || 288 else if ( data.find( "SH ", 20 ) > -1 ||
289 data.find( "DZ ", 20 ) > -1 || 289 data.find( "DZ ", 20 ) > -1 ||
290 data.find( "RA ", 20 ) > -1 || 290 data.find( "RA ", 20 ) > -1 ||
291 data.find( "UP ", 20 ) > -1 || 291 data.find( "UP ", 20 ) > -1 ||
292 data.find( "BR ", 20 ) > -1 ) 292 data.find( "BR ", 20 ) > -1 )
293 { 293 {
294 dataStr = "shower"; 294 dataStr = "shower";
295 } 295 }
296 else if ( data.find( "TS ", 20 ) > -1 ) 296 else if ( data.find( "TS ", 20 ) > -1 )
297 { 297 {
298 dataStr = "tstorm"; 298 dataStr = "tstorm";
299 } 299 }
300 else if ( data.find( "SN ", 20 ) > -1 || 300 else if ( data.find( "SN ", 20 ) > -1 ||
301 data.find( "SG ", 20 ) > -1 ) 301 data.find( "SG ", 20 ) > -1 )
302 { 302 {
303 dataStr = "snow"; 303 dataStr = "snow";
304 } 304 }
305 else if ( data.find( "FZ ", 20 ) > -1 || 305 else if ( data.find( "FZ ", 20 ) > -1 ||
306 data.find( "GR ", 20 ) > -1 || 306 data.find( "GR ", 20 ) > -1 ||
307 data.find( "GS ", 20 ) > -1 || 307 data.find( "GS ", 20 ) > -1 ||
308 data.find( "PE ", 20 ) > -1 || 308 data.find( "PE ", 20 ) > -1 ||
309 data.find( "IC ", 20 ) > -1 ) 309 data.find( "IC ", 20 ) > -1 )
310 { 310 {
311 dataStr = "sleet"; 311 dataStr = "sleet";
312 } 312 }
313} 313}
314 314
315void WeatherPluginWidget::dataRetrieved( OProcess *process ) 315void WeatherPluginWidget::dataRetrieved( OProcess *process )
316{ 316{
317 if ( process->normalExit() ) 317 if ( process->normalExit() )
318 { 318 {
319 displayWeather(); 319 displayWeather();
320 } 320 }
321 else 321 else
322 { 322 {
323 weatherLabel->setText( tr( "Current weather data not available." ) ); 323 weatherLabel->setText( tr( "Current weather data not available." ) );
324 } 324 }
325} 325}
diff --git a/noncore/tools/calc2/calc.cpp b/noncore/tools/calc2/calc.cpp
index f75eb69..3dcdf6e 100644
--- a/noncore/tools/calc2/calc.cpp
+++ b/noncore/tools/calc2/calc.cpp
@@ -1,104 +1,104 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21#include <qvaluelist.h> 21#include <qvaluelist.h>
22#include <qpe/qpeapplication.h> 22#include <qpe/qpeapplication.h>
23#include <qdir.h> 23#include <qdir.h>
24#include <qwidgetstack.h> 24#include <qwidgetstack.h>
25 25
26#include "calc.h" 26#include "calc.h"
27#include "plugininterface.h" 27#include "plugininterface.h"
28 28
29calc::calc (QWidget * p, const char *n):QWidget (p, n) 29calc::calc (QWidget * p, const char *n):QWidget (p, n)
30{ 30{
31 setCaption (tr ("Calculator")); 31 setCaption (tr ("Calculator"));
32 32
33// widgets 33// widgets
34 LCD = new QLCDNumber (this); 34 LCD = new QLCDNumber (this);
35 LCD->setMaximumSize (QSize (240, 30)); 35 LCD->setMaximumSize (QSize (240, 30));
36 LCD->setNumDigits(12); 36 LCD->setNumDigits(12);
37LCD->setSegmentStyle(QLCDNumber::Filled); 37LCD->setSegmentStyle(QLCDNumber::Filled);
38 pluginWidgetStack = new QWidgetStack (this); 38 pluginWidgetStack = new QWidgetStack (this);
39 39
40// layout widgets 40// layout widgets
41 calculatorLayout = new QVBoxLayout (this); 41 calculatorLayout = new QVBoxLayout (this);
42 calculatorLayout->addWidget (LCD); 42 calculatorLayout->addWidget (LCD);
43 calculatorLayout->addWidget (pluginWidgetStack); 43 calculatorLayout->addWidget (pluginWidgetStack);
44 44
45// no formatting of display for now 45// no formatting of display for now
46 connect (&engine, SIGNAL(display (double)), LCD, SLOT(display (double))); 46 connect (&engine, SIGNAL(display(double)), LCD, SLOT(display(double)));
47 connect (&engine, SIGNAL(display (const QString &)), LCD, SLOT(display (const QString &))); 47 connect (&engine, SIGNAL(display(const QString&)), LCD, SLOT(display(const QString&)));
48 connect (&engine, SIGNAL(setBinMode()), LCD, SLOT(setBinMode())); 48 connect (&engine, SIGNAL(setBinMode()), LCD, SLOT(setBinMode()));
49 connect (&engine, SIGNAL(setOctMode()), LCD, SLOT(setOctMode())); 49 connect (&engine, SIGNAL(setOctMode()), LCD, SLOT(setOctMode()));
50 connect (&engine, SIGNAL(setDecMode()), LCD, SLOT(setDecMode())); 50 connect (&engine, SIGNAL(setDecMode()), LCD, SLOT(setDecMode()));
51 connect (&engine, SIGNAL(setHexMode()), LCD, SLOT(setHexMode())); 51 connect (&engine, SIGNAL(setHexMode()), LCD, SLOT(setHexMode()));
52 52
53#ifndef NO_PLUGINS 53#ifndef NO_PLUGINS
54// load plugins 54// load plugins
55 QValueList < Plugin >::Iterator mit; 55 QValueList < Plugin >::Iterator mit;
56 for (mit = pluginList.begin (); mit != pluginList.end (); ++mit) { 56 for (mit = pluginList.begin (); mit != pluginList.end (); ++mit) {
57 (*mit).interface->release (); 57 (*mit).interface->release ();
58 (*mit).library->unload (); 58 (*mit).library->unload ();
59 delete (*mit).library; 59 delete (*mit).library;
60 } 60 }
61 pluginList.clear (); 61 pluginList.clear ();
62 62
63 QString path = QPEApplication::qpeDir() + "/plugins/calculator"; 63 QString path = QPEApplication::qpeDir() + "/plugins/calculator";
64 QDir dir (path, "lib*.so"); 64 QDir dir (path, "lib*.so");
65 QStringList list = dir.entryList (); 65 QStringList list = dir.entryList ();
66 66
67 QStringList::Iterator it; 67 QStringList::Iterator it;
68 for (it = list.begin (); it != list.end (); ++it) { 68 for (it = list.begin (); it != list.end (); ++it) {
69 CalcInterface *iface = 0; 69 CalcInterface *iface = 0;
70 QLibrary *lib = new QLibrary (path + "/" + *it); 70 QLibrary *lib = new QLibrary (path + "/" + *it);
71 71
72 Plugin plugin; 72 Plugin plugin;
73 plugin.pluginWidget = 0; 73 plugin.pluginWidget = 0;
74 74
75 if (lib->queryInterface (IID_Calc, (QUnknownInterface **) & iface) == 75 if (lib->queryInterface (IID_Calc, (QUnknownInterface **) & iface) ==
76 QS_OK) { 76 QS_OK) {
77 plugin.library = lib; 77 plugin.library = lib;
78 plugin.interface = iface; 78 plugin.interface = iface;
79 plugin.pluginWidget = plugin.interface->getPlugin(&engine,pluginWidgetStack); 79 plugin.pluginWidget = plugin.interface->getPlugin(&engine,pluginWidgetStack);
80 if (plugin.pluginWidget) 80 if (plugin.pluginWidget)
81 pluginWidgetStack->addWidget (plugin.pluginWidget, pluginList.count()); 81 pluginWidgetStack->addWidget (plugin.pluginWidget, pluginList.count());
82 pluginList.append (plugin); 82 pluginList.append (plugin);
83 } else { 83 } else {
84 delete lib; 84 delete lib;
85 } 85 }
86 } 86 }
87 setMode (1); 87 setMode (1);
88#else 88#else
89// load simple interface 89// load simple interface
90#endif 90#endif
91} 91}
92 92
93calc::~calc () 93calc::~calc ()
94{ 94{
95#ifndef NO_PLUGINS 95#ifndef NO_PLUGINS
96 QValueList < Plugin >::Iterator mit; 96 QValueList < Plugin >::Iterator mit;
97 for (mit = pluginList.begin (); mit != pluginList.end (); ++mit) { 97 for (mit = pluginList.begin (); mit != pluginList.end (); ++mit) {
98 (*mit).interface->release (); 98 (*mit).interface->release ();
99 (*mit).library->unload (); 99 (*mit).library->unload ();
100 delete (*mit).library; 100 delete (*mit).library;
101 } 101 }
102#endif 102#endif
103} 103}
104 104
diff --git a/noncore/tools/calculator/calculatorimpl.cpp b/noncore/tools/calculator/calculatorimpl.cpp
index 163b4da..dead03d 100644
--- a/noncore/tools/calculator/calculatorimpl.cpp
+++ b/noncore/tools/calculator/calculatorimpl.cpp
@@ -1,728 +1,728 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21/* 21/*
22 * 01/14/2002 Charles-Edouard Ruault <ce@ruault.com> 22 * 01/14/2002 Charles-Edouard Ruault <ce@ruault.com>
23 * Added support for Temperature conversions. 23 * Added support for Temperature conversions.
24 */ 24 */
25// Sat 03-09-2002 L.J. Potter added the inlined pixmaps here 25// Sat 03-09-2002 L.J. Potter added the inlined pixmaps here
26 26
27#include "calculatorimpl.h" 27#include "calculatorimpl.h"
28 28
29#include <qpe/resource.h> 29#include <qpe/resource.h>
30#include <qpe/qmath.h> 30#include <qpe/qmath.h>
31#include <qpe/qpeapplication.h> 31#include <qpe/qpeapplication.h>
32 32
33#include <qpushbutton.h> 33#include <qpushbutton.h>
34#include <qcombobox.h> 34#include <qcombobox.h>
35#include <qlabel.h> 35#include <qlabel.h>
36#include <qfont.h> 36#include <qfont.h>
37#include <qlayout.h> 37#include <qlayout.h>
38#include <qstringlist.h> 38#include <qstringlist.h>
39#include <qfile.h> 39#include <qfile.h>
40#include <qtextstream.h> 40#include <qtextstream.h>
41#include <qmessagebox.h> 41#include <qmessagebox.h>
42#include <math.h> 42#include <math.h>
43/* XPM */ 43/* XPM */
44static char *oneoverx_xpm[] = { 44static char *oneoverx_xpm[] = {
45/* width height num_colors chars_per_pixel */ 45/* width height num_colors chars_per_pixel */
46" 13 11 2 1", 46" 13 11 2 1",
47/* colors */ 47/* colors */
48". c None", 48". c None",
49"# c #000000", 49"# c #000000",
50/* pixels */ 50/* pixels */
51"......#......", 51"......#......",
52".....##......", 52".....##......",
53"......#......" 53"......#......"
54".....###.....", 54".....###.....",
55".............", 55".............",
56"..#########..", 56"..#########..",
57".............", 57".............",
58"....##.##....", 58"....##.##....",
59"......#......", 59"......#......",
60"......#......", 60"......#......",
61"....##.##....", 61"....##.##....",
62}; 62};
63/* XPM */ 63/* XPM */
64static char *ythrootofx_xpm[] = { 64static char *ythrootofx_xpm[] = {
65/* width height num_colors chars_per_pixel */ 65/* width height num_colors chars_per_pixel */
66" 13 11 2 1", 66" 13 11 2 1",
67/* colors */ 67/* colors */
68". c None", 68". c None",
69"# c #000000", 69"# c #000000",
70/* pixels */ 70/* pixels */
71"#.#..........", 71"#.#..........",
72"#.#..........", 72"#.#..........",
73"###...#######", 73"###...#######",
74"..#..#.......", 74"..#..#.......",
75"###..#.......", 75"###..#.......",
76".....#.#...#.", 76".....#.#...#.",
77".#..#...#.#..", 77".#..#...#.#..",
78"#.#.#....#...", 78"#.#.#....#...",
79"..#.#...#.#..", 79"..#.#...#.#..",
80"...#...#...#.", 80"...#...#...#.",
81"...#........." 81"...#........."
82}; 82};
83/* XPM */ 83/* XPM */
84static char *xtopowerofy_xpm[] = { 84static char *xtopowerofy_xpm[] = {
85/* width height num_colors chars_per_pixel */ 85/* width height num_colors chars_per_pixel */
86" 9 8 2 1", 86" 9 8 2 1",
87/* colors */ 87/* colors */
88". c None", 88". c None",
89"# c #000000", 89"# c #000000",
90/* pixels */ 90/* pixels */
91"......#.#", 91"......#.#",
92"......#.#", 92"......#.#",
93"......###", 93"......###",
94"#...#...#", 94"#...#...#",
95".#.#..###", 95".#.#..###",
96"..#......", 96"..#......",
97".#.#.....", 97".#.#.....",
98"#...#...." 98"#...#...."
99}; 99};
100 100
101CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name, 101CalculatorImpl::CalculatorImpl( QWidget * parent, const char * name,
102 WFlags f ) 102 WFlags f )
103 : Calculator( parent, name, f ) 103 : Calculator( parent, name, f )
104{ 104{
105// xtopowerofy = Resource::loadPixmap("xtopowerofy"); 105// xtopowerofy = Resource::loadPixmap("xtopowerofy");
106// ythrootofx = Resource::loadPixmap("ythrootofx"); 106// ythrootofx = Resource::loadPixmap("ythrootofx");
107// oneoverx = Resource::loadPixmap("oneoverx"); 107// oneoverx = Resource::loadPixmap("oneoverx");
108 108
109 memMark = new QLabel( "m", LCD ); 109 memMark = new QLabel( "m", LCD );
110 memMark->setFont( QFont( "helvetica", 12, QFont::Bold, TRUE ) ); 110 memMark->setFont( QFont( "helvetica", 12, QFont::Bold, TRUE ) );
111 memMark->resize( 12, 12 ); 111 memMark->resize( 12, 12 );
112 memMark->move( 4, 2 ); 112 memMark->move( 4, 2 );
113 memMark->hide(); 113 memMark->hide();
114 mem = 0; 114 mem = 0;
115 115
116 PushButtonMR->setEnabled( FALSE ); 116 PushButtonMR->setEnabled( FALSE );
117 117
118 current_mode = max_mode = conversion_mode_count = 0; 118 current_mode = max_mode = conversion_mode_count = 0;
119 last_conversion = -1; 119 last_conversion = -1;
120 120
121 // translation trick mode - with this stuff parsed in from a file is translatable 121 // translation trick mode - with this stuff parsed in from a file is translatable
122 QObject::tr("Standard"); 122 QObject::tr("Standard");
123 QObject::tr("Weight"); 123 QObject::tr("Weight");
124 QObject::tr("Distance"); 124 QObject::tr("Distance");
125 QObject::tr("Area"); 125 QObject::tr("Area");
126 QObject::tr("Temperatures"); 126 QObject::tr("Temperatures");
127 QObject::tr("Volume"); 127 QObject::tr("Volume");
128 QObject::tr("acres"); 128 QObject::tr("acres");
129 QObject::tr("°C"); 129 QObject::tr("°C");
130 QObject::tr("carats"); 130 QObject::tr("carats");
131 QObject::tr("cm"); 131 QObject::tr("cm");
132 QObject::tr("cu cm"); 132 QObject::tr("cu cm");
133 QObject::tr("cu ft"); 133 QObject::tr("cu ft");
134 QObject::tr("cu in"); 134 QObject::tr("cu in");
135 QObject::tr("°F"); 135 QObject::tr("°F");
136 QObject::tr("fl oz (US)"); 136 QObject::tr("fl oz (US)");
137 QObject::tr("ft"); 137 QObject::tr("ft");
138 QObject::tr("g"); 138 QObject::tr("g");
139 QObject::tr("gal (US)"); 139 QObject::tr("gal (US)");
140 QObject::tr("hectares"); 140 QObject::tr("hectares");
141 QObject::tr("in"); 141 QObject::tr("in");
142 QObject::tr("kg"); 142 QObject::tr("kg");
143 QObject::tr("km"); 143 QObject::tr("km");
144 QObject::tr("l"); 144 QObject::tr("l");
145 QObject::tr("lb"); 145 QObject::tr("lb");
146 QObject::tr("Lg tons"); 146 QObject::tr("Lg tons");
147 QObject::tr("m"); 147 QObject::tr("m");
148 QObject::tr("mg"); 148 QObject::tr("mg");
149 QObject::tr("mi"); 149 QObject::tr("mi");
150 QObject::tr("ml"); 150 QObject::tr("ml");
151 QObject::tr("mm"); 151 QObject::tr("mm");
152 QObject::tr("naut. mi"); 152 QObject::tr("naut. mi");
153 QObject::tr("oz"); 153 QObject::tr("oz");
154 QObject::tr("points"); 154 QObject::tr("points");
155 QObject::tr("pt"); 155 QObject::tr("pt");
156 QObject::tr("qt"); 156 QObject::tr("qt");
157 QObject::tr("sq cm"); 157 QObject::tr("sq cm");
158 QObject::tr("sq ft"); 158 QObject::tr("sq ft");
159 QObject::tr("sq in"); 159 QObject::tr("sq in");
160 QObject::tr("sq km"); 160 QObject::tr("sq km");
161 QObject::tr("sq m"); 161 QObject::tr("sq m");
162 QObject::tr("sq mi"); 162 QObject::tr("sq mi");
163 QObject::tr("sq mm"); 163 QObject::tr("sq mm");
164 QObject::tr("sq yd"); 164 QObject::tr("sq yd");
165 QObject::tr("st"); 165 QObject::tr("st");
166 QObject::tr("St tons"); 166 QObject::tr("St tons");
167 QObject::tr("tblspoon"); 167 QObject::tr("tblspoon");
168 QObject::tr("teaspoons"); 168 QObject::tr("teaspoons");
169 QObject::tr("tonnes"); 169 QObject::tr("tonnes");
170 QObject::tr("yd"); 170 QObject::tr("yd");
171 171
172 172
173//bgr_command.insert( PushButtonFunction); 173//bgr_command.insert( PushButtonFunction);
174 bgr_command.insert( PushButtonMPlus); 174 bgr_command.insert( PushButtonMPlus);
175 bgr_command.insert( PushButtonMR); 175 bgr_command.insert( PushButtonMR);
176 bgr_command.insert( PushButtonMC); 176 bgr_command.insert( PushButtonMC);
177 bgr_command.insert( PushButtonCE); 177 bgr_command.insert( PushButtonCE);
178 connect( &bgr_command, SIGNAL(clicked(int) ), this, SLOT(command_buttons(int))); 178 connect( &bgr_command, SIGNAL(clicked(int) ), this, SLOT(command_buttons(int)));
179 179
180 bgr_digits.insert(PushButton0); 180 bgr_digits.insert(PushButton0);
181 bgr_digits.insert(PushButton1); 181 bgr_digits.insert(PushButton1);
182 bgr_digits.insert(PushButton2); 182 bgr_digits.insert(PushButton2);
183 bgr_digits.insert(PushButton3); 183 bgr_digits.insert(PushButton3);
184 bgr_digits.insert(PushButton4); 184 bgr_digits.insert(PushButton4);
185 bgr_digits.insert(PushButton5); 185 bgr_digits.insert(PushButton5);
186 bgr_digits.insert(PushButton6); 186 bgr_digits.insert(PushButton6);
187 bgr_digits.insert(PushButton7); 187 bgr_digits.insert(PushButton7);
188 bgr_digits.insert(PushButton8); 188 bgr_digits.insert(PushButton8);
189 bgr_digits.insert(PushButton9); 189 bgr_digits.insert(PushButton9);
190 connect( &bgr_digits, SIGNAL(clicked(int) ), this, SLOT(enterNumber(int))); 190 connect( &bgr_digits, SIGNAL(clicked(int) ), this, SLOT(enterNumber(int)));
191 191
192 192
193 bgr_std.insert(PushButtonEquals); 193 bgr_std.insert(PushButtonEquals);
194 bgr_std.insert(PushButtonDecimal); 194 bgr_std.insert(PushButtonDecimal);
195 bgr_std.insert(PushButtonAdd); 195 bgr_std.insert(PushButtonAdd);
196 bgr_std.insert(PushButtonMinus); 196 bgr_std.insert(PushButtonMinus);
197 bgr_std.insert(PushButtonDivide); 197 bgr_std.insert(PushButtonDivide);
198 bgr_std.insert(PushButtonTimes); 198 bgr_std.insert(PushButtonTimes);
199 connect( &bgr_std, SIGNAL(clicked(int) ), this, SLOT(std_buttons(int))); 199 connect( &bgr_std, SIGNAL(clicked(int) ), this, SLOT(std_buttons(int)));
200 200
201// change the / to a proper division signal 201// change the / to a proper division signal
202 PushButtonDivide->setText(QChar(0xF7)); 202 PushButtonDivide->setText(QChar(0xF7));
203 203
204 func_buttons[0] = PushButtonF1; 204 func_buttons[0] = PushButtonF1;
205 func_buttons[1] = PushButtonF2; 205 func_buttons[1] = PushButtonF2;
206 func_buttons[2] = PushButtonF3; 206 func_buttons[2] = PushButtonF3;
207 func_buttons[3] = PushButtonF4; 207 func_buttons[3] = PushButtonF4;
208 func_buttons[4] = PushButtonF5; 208 func_buttons[4] = PushButtonF5;
209 func_buttons[5] = PushButtonF6; 209 func_buttons[5] = PushButtonF6;
210 func_buttons[6] = PushButtonF7; 210 func_buttons[6] = PushButtonF7;
211 func_buttons[7] = PushButtonF8; 211 func_buttons[7] = PushButtonF8;
212 func_buttons[8] = PushButtonF9; 212 func_buttons[8] = PushButtonF9;
213 func_buttons[9] = PushButtonF10; 213 func_buttons[9] = PushButtonF10;
214 func_buttons[10] = PushButtonF11; 214 func_buttons[10] = PushButtonF11;
215 func_buttons[11] = PushButtonF12; 215 func_buttons[11] = PushButtonF12;
216 216
217 for ( int x = 0 ; x < func_button_count ; x++ ) { 217 for ( int x = 0 ; x < func_button_count ; x++ ) {
218 QPushButton* tmpbutton = func_buttons[x]; 218 QPushButton* tmpbutton = func_buttons[x];
219 faces << tmpbutton->text(); 219 faces << tmpbutton->text();
220 bgr_function.insert(tmpbutton); 220 bgr_function.insert(tmpbutton);
221 } 221 }
222 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(do_convert(int) ) ); 222 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(do_convert(int) ) );
223 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(std_funcs (int) ) ); 223 connect( &bgr_function, SIGNAL(clicked(int) ) , this, SLOT(std_funcs(int) ) );
224 224
225 connect(ComboBoxFunction, SIGNAL(activated(int) ), this, SLOT(function_button(int) ) ); 225 connect(ComboBoxFunction, SIGNAL(activated(int) ), this, SLOT(function_button(int) ) );
226 226
227 captions.append(tr("Standard")); 227 captions.append(tr("Standard"));
228 ComboBoxFunction->insertItem(captions.last()); 228 ComboBoxFunction->insertItem(captions.last());
229 229
230 // now add in the conversion modes 230 // now add in the conversion modes
231 // when the menu gets done, these should be in a submenu 231 // when the menu gets done, these should be in a submenu
232 QString tmp = QPEApplication::qpeDir(); 232 QString tmp = QPEApplication::qpeDir();
233 tmp += "etc/unit_conversion.dat"; 233 tmp += "etc/unit_conversion.dat";
234 QFile myfile(tmp); 234 QFile myfile(tmp);
235 if ( !myfile.open( IO_Translate | IO_ReadOnly ) ) { 235 if ( !myfile.open( IO_Translate | IO_ReadOnly ) ) {
236 qDebug("Data file unit_conversion.dat not found\nNo conversion features will be available\n"+tmp); 236 qDebug("Data file unit_conversion.dat not found\nNo conversion features will be available\n"+tmp);
237 // disable the f button if no conv file available 237 // disable the f button if no conv file available
238 ComboBoxFunction->setEnabled(FALSE); 238 ComboBoxFunction->setEnabled(FALSE);
239 } 239 }
240 else { 240 else {
241 QString line, line2; 241 QString line, line2;
242 QTextStream ts(&myfile); 242 QTextStream ts(&myfile);
243 243
244 // first pass, see how many conversion types there are in order to allocate for them 244 // first pass, see how many conversion types there are in order to allocate for them
245 while ( ! ts.eof() ) { 245 while ( ! ts.eof() ) {
246 line = ts.readLine(); 246 line = ts.readLine();
247 if ( line.contains ("STARTTYPE" ) ) 247 if ( line.contains ("STARTTYPE" ) )
248 conversion_mode_count++; 248 conversion_mode_count++;
249 } 249 }
250 250
251 entry_list = new double[conversion_mode_count*func_button_count]; 251 entry_list = new double[conversion_mode_count*func_button_count];
252 preoffset_list = new double[conversion_mode_count*func_button_count]; 252 preoffset_list = new double[conversion_mode_count*func_button_count];
253 postoffset_list = new double[conversion_mode_count*func_button_count]; 253 postoffset_list = new double[conversion_mode_count*func_button_count];
254 myfile.close(); 254 myfile.close();
255 myfile.open( IO_Translate | IO_ReadOnly ); 255 myfile.open( IO_Translate | IO_ReadOnly );
256 QTextStream ts2(&myfile); 256 QTextStream ts2(&myfile);
257 257
258 // second pass, read in values 258 // second pass, read in values
259 int x = 0; 259 int x = 0;
260 while ( ! ts2.eof() ) { 260 while ( ! ts2.eof() ) {
261 line = ts2.readLine(); 261 line = ts2.readLine();
262 if ( line.contains("STARTTYPE") ) { 262 if ( line.contains("STARTTYPE") ) {
263 captions << tr( line.remove(0,10) ); 263 captions << tr( line.remove(0,10) );
264 ComboBoxFunction->insertItem(captions.last()); 264 ComboBoxFunction->insertItem(captions.last());
265 while ( !line.contains("ENDTYPE") ) { 265 while ( !line.contains("ENDTYPE") ) {
266 line = ts2.readLine(); 266 line = ts2.readLine();
267 if ( line.contains("NAME") ) { 267 if ( line.contains("NAME") ) {
268 faces << tr( line.remove(0,5) ); 268 faces << tr( line.remove(0,5) );
269 line2 = ts2.readLine(); 269 line2 = ts2.readLine();
270 line2.remove(0,6); 270 line2.remove(0,6);
271 entry_list[x] = line2.toDouble(); 271 entry_list[x] = line2.toDouble();
272 line2 = ts2.readLine(); 272 line2 = ts2.readLine();
273 line2.remove(0,7); 273 line2.remove(0,7);
274 preoffset_list[x] = line2.toDouble(); 274 preoffset_list[x] = line2.toDouble();
275 line2 = ts2.readLine(); 275 line2 = ts2.readLine();
276 line2.remove(0,8); 276 line2.remove(0,8);
277 postoffset_list[x] = line2.toDouble(); 277 postoffset_list[x] = line2.toDouble();
278 x++; 278 x++;
279 } 279 }
280 } 280 }
281 } 281 }
282 } 282 }
283 } 283 }
284 myfile.close(); 284 myfile.close();
285 clear(); 285 clear();
286 max_mode = pre_conv_modes_count + conversion_mode_count + post_conv_modes_count - 1; 286 max_mode = pre_conv_modes_count + conversion_mode_count + post_conv_modes_count - 1;
287 display_pixmap_faces(); 287 display_pixmap_faces();
288 288
289 qApp->installEventFilter( this ); 289 qApp->installEventFilter( this );
290} 290}
291 291
292bool CalculatorImpl::eventFilter( QObject *o, QEvent *e ) 292bool CalculatorImpl::eventFilter( QObject *o, QEvent *e )
293{ 293{
294 if ( e->type() == QEvent::KeyPress && state != sError ) { 294 if ( e->type() == QEvent::KeyPress && state != sError ) {
295 QKeyEvent *k = (QKeyEvent*)e; 295 QKeyEvent *k = (QKeyEvent*)e;
296 if ( k->key() >= Key_0 && k->key() <= Key_9 ) { 296 if ( k->key() >= Key_0 && k->key() <= Key_9 ) {
297 enterNumber( k->key() - Key_0 ); 297 enterNumber( k->key() - Key_0 );
298 return true; 298 return true;
299 } else { 299 } else {
300 switch ( k->key() ) { 300 switch ( k->key() ) {
301 case Key_Equal: 301 case Key_Equal:
302 std_buttons(0); 302 std_buttons(0);
303 return true; 303 return true;
304 case Key_Period: 304 case Key_Period:
305 std_buttons(1); 305 std_buttons(1);
306 return true; 306 return true;
307 case Key_Plus: 307 case Key_Plus:
308 std_buttons(2); 308 std_buttons(2);
309 return true; 309 return true;
310 case Key_Minus: 310 case Key_Minus:
311 std_buttons(3); 311 std_buttons(3);
312 return true; 312 return true;
313 case Key_Slash: 313 case Key_Slash:
314 std_buttons(4); 314 std_buttons(4);
315 return true; 315 return true;
316 case Key_Asterisk: 316 case Key_Asterisk:
317 std_buttons(5); 317 std_buttons(5);
318 return true; 318 return true;
319 case Key_Percent: 319 case Key_Percent:
320 execOp( oPercent ); 320 execOp( oPercent );
321 return true; 321 return true;
322 case Key_ParenLeft: 322 case Key_ParenLeft:
323 if ( current_mode < pre_conv_modes_count ) 323 if ( current_mode < pre_conv_modes_count )
324 execOp( oOpenBrace ); 324 execOp( oOpenBrace );
325 return true; 325 return true;
326 case Key_ParenRight: 326 case Key_ParenRight:
327 if ( current_mode < pre_conv_modes_count ) 327 if ( current_mode < pre_conv_modes_count )
328 execOp( oCloseBrace ); 328 execOp( oCloseBrace );
329 return true; 329 return true;
330 default: 330 default:
331 break; 331 break;
332 } 332 }
333 } 333 }
334 } 334 }
335 return Calculator::eventFilter( o, e ); 335 return Calculator::eventFilter( o, e );
336} 336}
337 337
338void CalculatorImpl::do_convert(int button) { 338void CalculatorImpl::do_convert(int button) {
339 if ( state == sError ) 339 if ( state == sError )
340 return; 340 return;
341 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) && 341 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) &&
342 button < changeable_func_button_count ) { 342 button < changeable_func_button_count ) {
343 if ( last_conversion > -1 ) { 343 if ( last_conversion > -1 ) {
344 if( state == sNewNumber ){ 344 if( state == sNewNumber ){
345 acc = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 345 acc = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
346 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 346 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
347 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button]) 347 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button])
348 +postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button]; 348 +postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button];
349 num = acc; 349 num = acc;
350 LCD->display( acc ); 350 LCD->display( acc );
351 } else { 351 } else {
352 state = sNewNumber; 352 state = sNewNumber;
353 num = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 353 num = (num+ preoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
354 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion]) 354 / (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + last_conversion])
355 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button]) 355 * (entry_list[(current_mode - pre_conv_modes_count) * func_button_count + button])
356 + postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button];; 356 + postoffset_list[(current_mode - pre_conv_modes_count) * func_button_count + button];;
357 LCD->display( num ); 357 LCD->display( num );
358 acc = num; 358 acc = num;
359 } 359 }
360 } 360 }
361 last_conversion = button; 361 last_conversion = button;
362 } 362 }
363} 363}
364 364
365 365
366void CalculatorImpl::function_button(int mode){ 366void CalculatorImpl::function_button(int mode){
367 if ( state == sError ) 367 if ( state == sError )
368 clear(); 368 clear();
369 // dont need the next line when using a popup menu 369 // dont need the next line when using a popup menu
370 current_mode = mode; 370 current_mode = mode;
371 371
372 // reset the last conv 372 // reset the last conv
373 last_conversion = -1; 373 last_conversion = -1;
374 374
375 // set the caption 375 // set the caption
376 this->setCaption( captions[current_mode] ); 376 this->setCaption( captions[current_mode] );
377 377
378 reset_conv(); 378 reset_conv();
379 379
380 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) { 380 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) {
381 QPushButton* tmpbutton = func_buttons[x]; 381 QPushButton* tmpbutton = func_buttons[x];
382 382
383 // if its a conversion , make it a toggle button 383 // if its a conversion , make it a toggle button
384 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) { 384 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) {
385 tmpbutton->setToggleButton(TRUE); 385 tmpbutton->setToggleButton(TRUE);
386 } else { 386 } else {
387 tmpbutton->setToggleButton(FALSE); 387 tmpbutton->setToggleButton(FALSE);
388 } 388 }
389 tmpbutton->setText( faces[current_mode * func_button_count + x] ); 389 tmpbutton->setText( faces[current_mode * func_button_count + x] );
390 } 390 }
391 391
392 if ( current_mode == 0 ) display_pixmap_faces(); 392 if ( current_mode == 0 ) display_pixmap_faces();
393 393
394 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) { 394 if ( current_mode >= pre_conv_modes_count && current_mode <= (max_mode - post_conv_modes_count) ) {
395 bgr_function.setExclusive(TRUE); 395 bgr_function.setExclusive(TRUE);
396 } else { 396 } else {
397 bgr_function.setExclusive(FALSE); 397 bgr_function.setExclusive(FALSE);
398 } 398 }
399} 399}
400 400
401void CalculatorImpl::display_pixmap_faces() { 401void CalculatorImpl::display_pixmap_faces() {
402 QPixmap image0( ( const char** ) xtopowerofy_xpm); 402 QPixmap image0( ( const char** ) xtopowerofy_xpm);
403 QPushButton* tmpbutton = func_buttons[5]; 403 QPushButton* tmpbutton = func_buttons[5];
404 tmpbutton->setPixmap(image0); 404 tmpbutton->setPixmap(image0);
405 405
406 QPixmap image1( ( const char** ) ythrootofx_xpm); 406 QPixmap image1( ( const char** ) ythrootofx_xpm);
407 tmpbutton = func_buttons[6]; 407 tmpbutton = func_buttons[6];
408 tmpbutton->setPixmap(image1); 408 tmpbutton->setPixmap(image1);
409 409
410 QPixmap image2( ( const char** ) oneoverx_xpm); 410 QPixmap image2( ( const char** ) oneoverx_xpm);
411 tmpbutton = func_buttons[3]; 411 tmpbutton = func_buttons[3];
412 tmpbutton->setPixmap(image2); 412 tmpbutton->setPixmap(image2);
413} 413}
414 414
415void CalculatorImpl::clear() { 415void CalculatorImpl::clear() {
416 acc = num = 0; 416 acc = num = 0;
417 operationStack.clear(); 417 operationStack.clear();
418 state = sStart; 418 state = sStart;
419 numDecimals = 0; 419 numDecimals = 0;
420 numOpenBraces = 0; 420 numOpenBraces = 0;
421 flPoint = FALSE; 421 flPoint = FALSE;
422 LCD->display( 0 ); 422 LCD->display( 0 );
423 fake = QString::null; 423 fake = QString::null;
424 424
425 reset_conv(); 425 reset_conv();
426} 426}
427 427
428void CalculatorImpl::reset_conv() { 428void CalculatorImpl::reset_conv() {
429 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) { 429 for ( int x = 0 ; x < changeable_func_button_count ; x++ ) {
430 QPushButton* tmpbutton = func_buttons[x]; 430 QPushButton* tmpbutton = func_buttons[x];
431 431
432 // dont carry any selections into the next mode 432 // dont carry any selections into the next mode
433 if ( tmpbutton->state() == QPushButton::On ) { 433 if ( tmpbutton->state() == QPushButton::On ) {
434 tmpbutton->toggle(); 434 tmpbutton->toggle();
435 } 435 }
436 } 436 }
437 437
438 last_conversion = -1; 438 last_conversion = -1;
439} 439}
440 440
441void CalculatorImpl::std_buttons(int button) 441void CalculatorImpl::std_buttons(int button)
442{ 442{
443 if ( state == sError ) 443 if ( state == sError )
444 return; 444 return;
445 execOp( (Operation)(button + oSum) ); 445 execOp( (Operation)(button + oSum) );
446} 446}
447 447
448void CalculatorImpl::std_funcs(int button) { 448void CalculatorImpl::std_funcs(int button) {
449 if ( state == sError ) 449 if ( state == sError )
450 return; 450 return;
451 if ( current_mode < pre_conv_modes_count || 451 if ( current_mode < pre_conv_modes_count ||
452 button > changeable_func_button_count-1 ) { 452 button > changeable_func_button_count-1 ) {
453 Operation op; 453 Operation op;
454 if ( button < 10 ) 454 if ( button < 10 )
455 op = (Operation)(button + oSin); 455 op = (Operation)(button + oSin);
456 else if ( button == 10 ) 456 else if ( button == 10 )
457 op = oOpenBrace; 457 op = oOpenBrace;
458 else 458 else
459 op = oCloseBrace; 459 op = oCloseBrace;
460 execOp( op ); 460 execOp( op );
461 } 461 }
462} 462}
463 463
464void CalculatorImpl::execOp( Operation i ) 464void CalculatorImpl::execOp( Operation i )
465{ 465{
466 switch (i) { 466 switch (i) {
467 // these operators only affect the current number. 467 // these operators only affect the current number.
468 case oDivX: 468 case oDivX:
469 case oLog: 469 case oLog:
470 case oLn: 470 case oLn:
471 case oSin: 471 case oSin:
472 case oCos: 472 case oCos:
473 case oTan: 473 case oTan:
474 num = evalExpr(i); 474 num = evalExpr(i);
475 break; 475 break;
476 476
477 case oAdd: 477 case oAdd:
478 case oSub: { 478 case oSub: {
479 processStack( oAdd ); 479 processStack( oAdd );
480 Op op( num, i ); 480 Op op( num, i );
481 operationStack.push( op ); 481 operationStack.push( op );
482 break; 482 break;
483 } 483 }
484 case oDiv: 484 case oDiv:
485 case oMult: 485 case oMult:
486 case oRoot: 486 case oRoot:
487 case oXsquared: { 487 case oXsquared: {
488 processStack( oDiv ); 488 processStack( oDiv );
489 Op op( num, i ); 489 Op op( num, i );
490 operationStack.push( op ); 490 operationStack.push( op );
491 break; 491 break;
492 } 492 }
493 case oChSign: 493 case oChSign:
494 num = -num; 494 num = -num;
495 LCD->display(num); 495 LCD->display(num);
496 return; 496 return;
497 497
498 case oOpenBrace: { 498 case oOpenBrace: {
499 Op op( 0, oOpenBrace ); 499 Op op( 0, oOpenBrace );
500 operationStack.push( op ); 500 operationStack.push( op );
501 numOpenBraces++; 501 numOpenBraces++;
502 state = sNewNumber; 502 state = sNewNumber;
503 return; 503 return;
504 } 504 }
505 case oCloseBrace: { 505 case oCloseBrace: {
506 if ( numOpenBraces == 0 ) 506 if ( numOpenBraces == 0 )
507 return; 507 return;
508 processStack( oAdd ); 508 processStack( oAdd );
509 if ( operationStack.top().operation != oOpenBrace ) 509 if ( operationStack.top().operation != oOpenBrace )
510 qDebug( "Calculator: internal Error" ); 510 qDebug( "Calculator: internal Error" );
511 operationStack.pop(); 511 operationStack.pop();
512 state = sNewNumber; 512 state = sNewNumber;
513 numOpenBraces--; 513 numOpenBraces--;
514 break; 514 break;
515 } 515 }
516 516
517 case oPoint: 517 case oPoint:
518 flPoint = TRUE; 518 flPoint = TRUE;
519 return; 519 return;
520 520
521 case oPercent: 521 case oPercent:
522 processStack( oPercent ); 522 processStack( oPercent );
523 break; 523 break;
524 524
525 525
526 case oSum: 526 case oSum:
527 processStack( oSum ); 527 processStack( oSum );
528 break; 528 break;
529 529
530 default: 530 default:
531 return; 531 return;
532 }; 532 };
533 533
534 if ( state == sError ) { 534 if ( state == sError ) {
535 LCD->display( "Error" ); 535 LCD->display( "Error" );
536 return; 536 return;
537 } else { 537 } else {
538 LCD->display(num); 538 LCD->display(num);
539 } 539 }
540 state = sNewNumber; 540 state = sNewNumber;
541 numDecimals = 0; 541 numDecimals = 0;
542 flPoint = FALSE; 542 flPoint = FALSE;
543} 543}
544 544
545 545
546void CalculatorImpl::processStack( int op ) 546void CalculatorImpl::processStack( int op )
547{ 547{
548 //dubious percent hack, since the changeable operator precedences are 548 //dubious percent hack, since the changeable operator precedences are
549 //pretty much hardwired to be less than the non-changeable 549 //pretty much hardwired to be less than the non-changeable
550 bool percent = FALSE; 550 bool percent = FALSE;
551 if ( op == oPercent ) { 551 if ( op == oPercent ) {
552 percent = TRUE; 552 percent = TRUE;
553 op = oSum; 553 op = oSum;
554 } 554 }
555 while( !operationStack.isEmpty() && operationStack.top().operation >= op ) { 555 while( !operationStack.isEmpty() && operationStack.top().operation >= op ) {
556 Op operation = operationStack.pop(); 556 Op operation = operationStack.pop();
557 acc = operation.number; 557 acc = operation.number;
558 if ( percent ) { 558 if ( percent ) {
559 if ( operation.operation == oAdd || operation.operation == oSub ) 559 if ( operation.operation == oAdd || operation.operation == oSub )
560 num = acc*num/100; 560 num = acc*num/100;
561 else 561 else
562 num = num / 100; 562 num = num / 100;
563 } 563 }
564 num = evalExpr( operation.operation ); 564 num = evalExpr( operation.operation );
565 percent = FALSE; 565 percent = FALSE;
566 } 566 }
567} 567}
568 568
569 569
570double CalculatorImpl::evalExpr( int op ) { 570double CalculatorImpl::evalExpr( int op ) {
571 double sum = 0; 571 double sum = 0;
572 572
573 switch( op ){ 573 switch( op ){
574 case oPercent: sum = num / 100.; break; 574 case oPercent: sum = num / 100.; break;
575 case oDivX: 575 case oDivX:
576 if (num == 0) 576 if (num == 0)
577 state = sError; 577 state = sError;
578 else 578 else
579 sum = 1 / num; 579 sum = 1 / num;
580 break; 580 break;
581 case oXsquared: 581 case oXsquared:
582 sum = pow(acc,num); 582 sum = pow(acc,num);
583 break; 583 break;
584 case oChSign: (state == sStart) ? sum = -num : sum = -acc; break; 584 case oChSign: (state == sStart) ? sum = -num : sum = -acc; break;
585 case oSub: sum = acc - num; break; 585 case oSub: sum = acc - num; break;
586 case oMult: sum = acc * num; break; 586 case oMult: sum = acc * num; break;
587 case oAdd: sum = acc + num; break; 587 case oAdd: sum = acc + num; break;
588 case oDiv: { 588 case oDiv: {
589 if (num == 0) { 589 if (num == 0) {
590 state = sError; 590 state = sError;
591 } else { 591 } else {
592 sum = acc / num; 592 sum = acc / num;
593 } 593 }
594 break; 594 break;
595 } 595 }
596 case oRoot: 596 case oRoot:
597 /* the linux library is dumb, and can't to -x to 1/n 597 /* the linux library is dumb, and can't to -x to 1/n
598 when n is odd. (even and error of course is acceptable */ 598 when n is odd. (even and error of course is acceptable */
599 if((acc < 0) && (int(num) == num) && (int(num) % 2 == 1 )) { 599 if((acc < 0) && (int(num) == num) && (int(num) % 2 == 1 )) {
600 sum = pow(-acc, 1 / num); 600 sum = pow(-acc, 1 / num);
601 sum = -sum; 601 sum = -sum;
602 } else { 602 } else {
603 sum = pow(acc, 1 / num); 603 sum = pow(acc, 1 / num);
604 } 604 }
605 break; 605 break;
606 case oLog: 606 case oLog:
607 sum = log10(num); 607 sum = log10(num);
608 break; 608 break;
609 case oLn: 609 case oLn:
610 sum = log(num); 610 sum = log(num);
611 break; 611 break;
612 case oTan: sum = qTan(num);break; 612 case oTan: sum = qTan(num);break;
613 case oSin: sum = qSin(num);break; 613 case oSin: sum = qSin(num);break;
614 case oCos: sum = qCos(num);break; 614 case oCos: sum = qCos(num);break;
615 default: sum = num; break; 615 default: sum = num; break;
616 } 616 }
617 617
618 if ( isinf( sum ) || isnan( sum ) ) 618 if ( isinf( sum ) || isnan( sum ) )
619 state = sError; 619 state = sError;
620 return sum; 620 return sum;
621} 621}
622 622
623 623
624void CalculatorImpl::enterNumber( int n ) 624void CalculatorImpl::enterNumber( int n )
625{ 625{
626 if ( state == sError ) 626 if ( state == sError )
627 return; 627 return;
628 if( state == sStart ){ 628 if( state == sStart ){
629 if( LCD->value() > 0 ){ 629 if( LCD->value() > 0 ){
630 QString s = QString::number( LCD->value(), 'g', LCD->numDigits()); 630 QString s = QString::number( LCD->value(), 'g', LCD->numDigits());
631 if( s.length() > (uint)(LCD->numDigits() - 2)) return; 631 if( s.length() > (uint)(LCD->numDigits() - 2)) return;
632 632
633 } else if( (int)fake.length() >= LCD->numDigits() || numDecimals >=12 ){ 633 } else if( (int)fake.length() >= LCD->numDigits() || numDecimals >=12 ){
634 return; 634 return;
635 } 635 }
636 } 636 }
637 637
638 if( state == sNewNumber ){ 638 if( state == sNewNumber ){
639 state = sStart; 639 state = sStart;
640 acc = 0; 640 acc = 0;
641 if( flPoint ){ 641 if( flPoint ){
642 numDecimals = 1; 642 numDecimals = 1;
643 num = n / pow(10, numDecimals); 643 num = n / pow(10, numDecimals);
644 } else 644 } else
645 num = n; 645 num = n;
646 } else if( flPoint ){ 646 } else if( flPoint ){
647 numDecimals++; 647 numDecimals++;
648 if( num < 0 ){ 648 if( num < 0 ){
649 num -= n / pow(10, numDecimals); 649 num -= n / pow(10, numDecimals);
650 } else { 650 } else {
651 num += n / pow(10, numDecimals); 651 num += n / pow(10, numDecimals);
652 } 652 }
653 } else { 653 } else {
654 num *= 10; 654 num *= 10;
655 if( num < 0 ) 655 if( num < 0 )
656 num -= n; 656 num -= n;
657 else 657 else
658 num += n; 658 num += n;
659 } 659 }
660 660
661 // We need feedback in the calc display while entering fl.point zeros. 661 // We need feedback in the calc display while entering fl.point zeros.
662 // This is a small hack to display sequences like: 0.000 and 1.100 662 // This is a small hack to display sequences like: 0.000 and 1.100
663 double integer, fraction; 663 double integer, fraction;
664 fraction = modf( num, &integer ); 664 fraction = modf( num, &integer );
665 if( flPoint ){ 665 if( flPoint ){
666 QString is, fs, zeros; 666 QString is, fs, zeros;
667 667
668 is = QString::number( integer, 'g', 13 ); 668 is = QString::number( integer, 'g', 13 );
669 fs = QString::number( fraction, 'g', numDecimals ); 669 fs = QString::number( fraction, 'g', numDecimals );
670 if( fs.contains('e') ){ 670 if( fs.contains('e') ){
671 fs = QString::number( fraction, 'f', LCD->numDigits() ); 671 fs = QString::number( fraction, 'f', LCD->numDigits() );
672 } 672 }
673 fs = fs.mid( 2, numDecimals ); 673 fs = fs.mid( 2, numDecimals );
674 674
675 if( (integer == 0) && (fraction == 0) ) 675 if( (integer == 0) && (fraction == 0) )
676 fake = "0."; 676 fake = "0.";
677 else if( (integer != 0) && (fraction == 0) ) 677 else if( (integer != 0) && (fraction == 0) )
678 fake = is + "."; 678 fake = is + ".";
679 else 679 else
680 fake = is + "." + fs; 680 fake = is + "." + fs;
681 681
682 zeros.fill( '0', (numDecimals - fs.length()) ); 682 zeros.fill( '0', (numDecimals - fs.length()) );
683 fake += zeros; 683 fake += zeros;
684 // ### This code sets LCD->value() to zero since it sets a text 684 // ### This code sets LCD->value() to zero since it sets a text
685 // ### Avoid getting the current value from LCD->value() for 685 // ### Avoid getting the current value from LCD->value() for
686 // ### calculations. 686 // ### calculations.
687 LCD->display( fake ); 687 LCD->display( fake );
688 } else 688 } else
689 LCD->display( num ); 689 LCD->display( num );
690} 690}
691 691
692void CalculatorImpl::command_buttons(int i) { 692void CalculatorImpl::command_buttons(int i) {
693 if ( state == sError && i != 3 ) 693 if ( state == sError && i != 3 )
694 return; 694 return;
695 switch (i) { 695 switch (i) {
696 case 0: // M+ 696 case 0: // M+
697 mem += num; 697 mem += num;
698 if( mem != 0 ){ 698 if( mem != 0 ){
699 memMark->show(); 699 memMark->show();
700 PushButtonMR->setEnabled( TRUE ); }; 700 PushButtonMR->setEnabled( TRUE ); };
701 state = sNewNumber; 701 state = sNewNumber;
702 break; 702 break;
703 case 1: // MR 703 case 1: // MR
704 acc = num = mem; 704 acc = num = mem;
705 state = sNewNumber; 705 state = sNewNumber;
706 LCD->display( mem ); 706 LCD->display( mem );
707 break; 707 break;
708 case 2: // MC 708 case 2: // MC
709 mem = 0; 709 mem = 0;
710 memMark->hide(); 710 memMark->hide();
711 PushButtonMR->setEnabled( FALSE ); 711 PushButtonMR->setEnabled( FALSE );
712 break; 712 break;
713 case 3: // CE 713 case 3: // CE
714 if ( state == sStart ) { 714 if ( state == sStart ) {
715 // clear the entered number on the first press 715 // clear the entered number on the first press
716 state = sNewNumber; 716 state = sNewNumber;
717 num = acc = 0; 717 num = acc = 0;
718 flPoint = FALSE; 718 flPoint = FALSE;
719 LCD->display( 0 ); 719 LCD->display( 0 );
720 fake = QString::null; 720 fake = QString::null;
721 numDecimals = 0; 721 numDecimals = 0;
722 } else { 722 } else {
723 clear(); 723 clear();
724 } 724 }
725 break; 725 break;
726 }; 726 };
727 727
728} 728}
diff --git a/noncore/tools/clock/clock.cpp b/noncore/tools/clock/clock.cpp
index 4d92683..118cf1f 100644
--- a/noncore/tools/clock/clock.cpp
+++ b/noncore/tools/clock/clock.cpp
@@ -1,663 +1,663 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20// changes added and Copyright (C) by L. J. Potter <ljp@llornkcor.com> 2002 20// changes added and Copyright (C) by L. J. Potter <ljp@llornkcor.com> 2002
21 21
22#include "clock.h" 22#include "clock.h"
23#include "setAlarm.h" 23#include "setAlarm.h"
24 24
25#include <qpe/qpeapplication.h> 25#include <qpe/qpeapplication.h>
26#include <qpe/qcopenvelope_qws.h> 26#include <qpe/qcopenvelope_qws.h>
27#include <qpe/config.h> 27#include <qpe/config.h>
28#include <qpe/timestring.h> 28#include <qpe/timestring.h>
29#include <qpe/alarmserver.h> 29#include <qpe/alarmserver.h>
30#include <qpe/sound.h> 30#include <qpe/sound.h>
31#include <qpe/resource.h> 31#include <qpe/resource.h>
32#include <qsound.h> 32#include <qsound.h>
33#include <qtimer.h> 33#include <qtimer.h>
34 34
35#include <opie/oclickablelabel.h> 35#include <opie/oclickablelabel.h>
36 36
37#include <qlcdnumber.h> 37#include <qlcdnumber.h>
38#include <qslider.h> 38#include <qslider.h>
39#include <qlabel.h> 39#include <qlabel.h>
40#include <qlayout.h> 40#include <qlayout.h>
41#include <qtimer.h> 41#include <qtimer.h>
42#include <qpushbutton.h> 42#include <qpushbutton.h>
43#include <qradiobutton.h> 43#include <qradiobutton.h>
44#include <qbuttongroup.h> 44#include <qbuttongroup.h>
45#include <qpainter.h> 45#include <qpainter.h>
46#include <qmessagebox.h> 46#include <qmessagebox.h>
47#include <qdatetime.h> 47#include <qdatetime.h>
48 48
49#include <math.h> 49#include <math.h>
50#include <unistd.h> 50#include <unistd.h>
51#include <sys/types.h> 51#include <sys/types.h>
52 52
53#include <pthread.h> 53#include <pthread.h>
54 54
55 55
56const double deg2rad = 0.017453292519943295769; // pi/180 56const double deg2rad = 0.017453292519943295769; // pi/180
57const int sw_prec = 2; 57const int sw_prec = 2;
58 58
59void startPlayer() 59void startPlayer()
60{ 60{
61 Config config( "qpe" ); 61 Config config( "qpe" );
62 config.setGroup( "Time" ); 62 config.setGroup( "Time" );
63 sleep(15); 63 sleep(15);
64 QCopEnvelope e( "QPE/Application/opieplayer", "setDocument(QString)" ); 64 QCopEnvelope e( "QPE/Application/opieplayer", "setDocument(QString)" );
65 e << config.readEntry( "mp3File", "" ); 65 e << config.readEntry( "mp3File", "" );
66} 66}
67 67
68 68
69static void toggleScreenSaver( bool on ) 69static void toggleScreenSaver( bool on )
70{ 70{
71 QCopEnvelope e( "QPE/System", "setScreenSaverMode(int)" ); 71 QCopEnvelope e( "QPE/System", "setScreenSaverMode(int)" );
72 e << ( on ? QPEApplication::Enable : QPEApplication::DisableSuspend ); 72 e << ( on ? QPEApplication::Enable : QPEApplication::DisableSuspend );
73} 73}
74 74
75Clock::Clock( QWidget * parent, const char * name, WFlags f ) 75Clock::Clock( QWidget * parent, const char * name, WFlags f )
76 : QVBox( parent, name , f ) 76 : QVBox( parent, name , f )
77{ 77{
78 setSpacing( 4 ); 78 setSpacing( 4 );
79 setMargin( 1 ); 79 setMargin( 1 );
80 80
81 81
82 snoozeBtn = new QPushButton ( this ); 82 snoozeBtn = new QPushButton ( this );
83 snoozeBtn->setText( tr( "Snooze" ) ); 83 snoozeBtn->setText( tr( "Snooze" ) );
84 84
85 aclock = new AnalogClock( this ); 85 aclock = new AnalogClock( this );
86 aclock->display( QTime::currentTime() ); 86 aclock->display( QTime::currentTime() );
87 aclock->setLineWidth( 2 ); 87 aclock->setLineWidth( 2 );
88 88
89 QHBox *hb = new QHBox( this ); 89 QHBox *hb = new QHBox( this );
90 hb->setMargin( 0 ); 90 hb->setMargin( 0 );
91 QWidget *space = new QWidget( hb ); 91 QWidget *space = new QWidget( hb );
92 lcd = new QLCDNumber( hb ); 92 lcd = new QLCDNumber( hb );
93 lcd->setSegmentStyle( QLCDNumber::Flat ); 93 lcd->setSegmentStyle( QLCDNumber::Flat );
94 lcd->setFrameStyle( QFrame::NoFrame ); 94 lcd->setFrameStyle( QFrame::NoFrame );
95 lcd->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) ); 95 lcd->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ) );
96 lcd->setFixedHeight( 23 ); 96 lcd->setFixedHeight( 23 );
97 97
98 ampmLabel = new QLabel( tr( "PM" ), hb ); 98 ampmLabel = new QLabel( tr( "PM" ), hb );
99 ampmLabel->setFont( QFont( "Helvetica", 14, QFont::Bold ) ); 99 ampmLabel->setFont( QFont( "Helvetica", 14, QFont::Bold ) );
100 ampmLabel->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Preferred ) ); 100 ampmLabel->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Preferred ) );
101 ampmLabel->setAlignment( AlignLeft | AlignBottom ); 101 ampmLabel->setAlignment( AlignLeft | AlignBottom );
102 space = new QWidget( hb ); 102 space = new QWidget( hb );
103 103
104 date = new QLabel( this ); 104 date = new QLabel( this );
105 date->setAlignment( AlignHCenter | AlignVCenter ); 105 date->setAlignment( AlignHCenter | AlignVCenter );
106 date->setFont( QFont( "Helvetica", 14, QFont::Bold ) ); 106 date->setFont( QFont( "Helvetica", 14, QFont::Bold ) );
107 date->setText( TimeString::longDateString( QDate::currentDate() ) ); 107 date->setText( TimeString::longDateString( QDate::currentDate() ) );
108 108
109 QWidget *controls = new QWidget( this ); 109 QWidget *controls = new QWidget( this );
110 QGridLayout *gl = new QGridLayout( controls, 3, 2, 6, 4 ); 110 QGridLayout *gl = new QGridLayout( controls, 3, 2, 6, 4 );
111 111
112 QButtonGroup *grp = new QButtonGroup( controls ); 112 QButtonGroup *grp = new QButtonGroup( controls );
113 grp->setRadioButtonExclusive( true ); 113 grp->setRadioButtonExclusive( true );
114 grp->hide(); 114 grp->hide();
115 115
116 clockRB = new QRadioButton ( tr( "Clock" ), controls ); 116 clockRB = new QRadioButton ( tr( "Clock" ), controls );
117 gl->addWidget( clockRB, 0, 0 ); 117 gl->addWidget( clockRB, 0, 0 );
118 grp->insert( clockRB ); 118 grp->insert( clockRB );
119 119
120 swatchRB = new QRadioButton ( tr( "Stopwatch" ), controls ); 120 swatchRB = new QRadioButton ( tr( "Stopwatch" ), controls );
121 gl->addWidget( swatchRB, 1, 0 ); 121 gl->addWidget( swatchRB, 1, 0 );
122 grp->insert( swatchRB ); 122 grp->insert( swatchRB );
123 123
124 connect( grp, SIGNAL( clicked( int ) ), this, SLOT( modeSelect( int ) ) ); 124 connect( grp, SIGNAL( clicked(int) ), this, SLOT( modeSelect(int) ) );
125 grp->setButton( 0 ); 125 grp->setButton( 0 );
126 126
127 set = new QPushButton ( controls ); 127 set = new QPushButton ( controls );
128 set->setMaximumSize( 50, 30 ); 128 set->setMaximumSize( 50, 30 );
129 gl->addWidget( set , 0, 1 ); 129 gl->addWidget( set , 0, 1 );
130 set->setText( tr( "Start" ) ); 130 set->setText( tr( "Start" ) );
131 set->setEnabled( FALSE ); 131 set->setEnabled( FALSE );
132 grp->insert( set ); 132 grp->insert( set );
133 133
134 reset = new QPushButton ( controls ); 134 reset = new QPushButton ( controls );
135 gl->addWidget( reset, 1, 1 ); 135 gl->addWidget( reset, 1, 1 );
136 reset->setText( tr( "Reset" ) ); 136 reset->setText( tr( "Reset" ) );
137 reset->setEnabled( FALSE ); 137 reset->setEnabled( FALSE );
138 grp->insert( reset ); 138 grp->insert( reset );
139 139
140 alarmOffBtn = new QPushButton ( controls ); 140 alarmOffBtn = new QPushButton ( controls );
141 gl->addWidget( alarmOffBtn, 0, 2 ); 141 gl->addWidget( alarmOffBtn, 0, 2 );
142 142
143 alarmBtn = new QPushButton ( controls ); 143 alarmBtn = new QPushButton ( controls );
144 gl->addWidget( alarmBtn, 1, 2 ); 144 gl->addWidget( alarmBtn, 1, 2 );
145 145
146 alarmBtn->setText( tr( "Set Alarm" ) ); 146 alarmBtn->setText( tr( "Set Alarm" ) );
147 147
148 OClickableLabel *click = new OClickableLabel( controls, "label" ); 148 OClickableLabel *click = new OClickableLabel( controls, "label" );
149 click->setText( tr( "Set date and time." ) ); 149 click->setText( tr( "Set date and time." ) );
150 gl->addMultiCellWidget( click, 3, 3, 0, 2, AlignHCenter ); 150 gl->addMultiCellWidget( click, 3, 3, 0, 2, AlignHCenter );
151 connect( click, SIGNAL( clicked() ), this, SLOT( slotAdjustTime() ) ); 151 connect( click, SIGNAL( clicked() ), this, SLOT( slotAdjustTime() ) );
152 152
153 connect( set , SIGNAL( pressed() ), SLOT( slotSet() ) ); 153 connect( set , SIGNAL( pressed() ), SLOT( slotSet() ) );
154 connect( reset, SIGNAL( clicked() ), SLOT( slotReset() ) ); 154 connect( reset, SIGNAL( clicked() ), SLOT( slotReset() ) );
155 155
156 connect( alarmBtn, SIGNAL( clicked() ), SLOT( slotSetAlarm() ) ); 156 connect( alarmBtn, SIGNAL( clicked() ), SLOT( slotSetAlarm() ) );
157 connect( snoozeBtn, SIGNAL( clicked() ), SLOT( slotSnooze() ) ); 157 connect( snoozeBtn, SIGNAL( clicked() ), SLOT( slotSnooze() ) );
158 connect( alarmOffBtn, SIGNAL( clicked() ), SLOT( slotToggleAlarm() ) ); 158 connect( alarmOffBtn, SIGNAL( clicked() ), SLOT( slotToggleAlarm() ) );
159 159
160 connect( qApp, SIGNAL( appMessage( const QCString&, const QByteArray& ) ), 160 connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ),
161 this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); 161 this, SLOT( appMessage(const QCString&,const QByteArray&) ) );
162 162
163 t = new QTimer( this ); 163 t = new QTimer( this );
164 connect( t, SIGNAL( timeout() ), SLOT( updateClock() ) ); 164 connect( t, SIGNAL( timeout() ), SLOT( updateClock() ) );
165 t->start( 1000 ); 165 t->start( 1000 );
166 166
167 connect( qApp, SIGNAL( timeChanged() ), SLOT( updateClock() ) ); 167 connect( qApp, SIGNAL( timeChanged() ), SLOT( updateClock() ) );
168 168
169 swatch_running = FALSE; 169 swatch_running = FALSE;
170 swatch_totalms = 0; 170 swatch_totalms = 0;
171 171
172 connect( qApp, SIGNAL( clockChanged( bool ) ), this, SLOT( changeClock( bool ) ) ); 172 connect( qApp, SIGNAL( clockChanged(bool) ), this, SLOT( changeClock(bool) ) );
173 173
174 174
175 Config config( "qpe" ); 175 Config config( "qpe" );
176 config.setGroup( "Time" ); 176 config.setGroup( "Time" );
177 ampm = config.readBoolEntry( "AMPM", TRUE ); 177 ampm = config.readBoolEntry( "AMPM", TRUE );
178 178
179 QString tmp = config.readEntry( "clockAlarmHour", "" ); 179 QString tmp = config.readEntry( "clockAlarmHour", "" );
180 bool ok; 180 bool ok;
181 hour = tmp.toInt( &ok, 10 ); 181 hour = tmp.toInt( &ok, 10 );
182 tmp = config.readEntry( "clockAlarmMinute", "" ); 182 tmp = config.readEntry( "clockAlarmMinute", "" );
183 minute = tmp.toInt( &ok, 10 ); 183 minute = tmp.toInt( &ok, 10 );
184 184
185 if ( config.readEntry( "clockAlarmSet", "FALSE" ) == "TRUE" ) 185 if ( config.readEntry( "clockAlarmSet", "FALSE" ) == "TRUE" )
186 { 186 {
187 alarmOffBtn->setText( tr( "Alarm Is On" ) ); 187 alarmOffBtn->setText( tr( "Alarm Is On" ) );
188 alarmBool = TRUE; 188 alarmBool = TRUE;
189 snoozeBtn->show(); 189 snoozeBtn->show();
190 } 190 }
191 else 191 else
192 { 192 {
193 alarmOffBtn->setText( tr( "Alarm Is Off" ) ); 193 alarmOffBtn->setText( tr( "Alarm Is Off" ) );
194 alarmBool = FALSE; 194 alarmBool = FALSE;
195 snoozeBtn->hide(); 195 snoozeBtn->hide();
196 } 196 }
197 197
198 QTimer::singleShot( 0, this, SLOT( updateClock() ) ); 198 QTimer::singleShot( 0, this, SLOT( updateClock() ) );
199 199
200 Config cfg( "Clock" ); 200 Config cfg( "Clock" );
201 cfg.setGroup( "Mode" ); 201 cfg.setGroup( "Mode" );
202 int mode = cfg.readBoolEntry( "clockMode"); 202 int mode = cfg.readBoolEntry( "clockMode");
203 setSwatchMode( mode); 203 setSwatchMode( mode);
204 modeSelect( mode); 204 modeSelect( mode);
205} 205}
206 206
207Clock::~Clock() 207Clock::~Clock()
208{ 208{
209 toggleScreenSaver( true ); 209 toggleScreenSaver( true );
210} 210}
211 211
212void Clock::updateClock() 212void Clock::updateClock()
213{ 213{
214 if ( clockRB->isChecked() ) 214 if ( clockRB->isChecked() )
215 { 215 {
216 QTime tm = QDateTime::currentDateTime().time(); 216 QTime tm = QDateTime::currentDateTime().time();
217 QString s; 217 QString s;
218 if ( ampm ) 218 if ( ampm )
219 { 219 {
220 int hour = tm.hour(); 220 int hour = tm.hour();
221 if ( hour == 0 ) 221 if ( hour == 0 )
222 hour = 12; 222 hour = 12;
223 if ( hour > 12 ) 223 if ( hour > 12 )
224 hour -= 12; 224 hour -= 12;
225 s.sprintf( "%2d%c%02d", hour, ':', tm.minute() ); 225 s.sprintf( "%2d%c%02d", hour, ':', tm.minute() );
226 ampmLabel->setText( ( tm.hour() >= 12 ) ? "PM" : "AM" ); 226 ampmLabel->setText( ( tm.hour() >= 12 ) ? "PM" : "AM" );
227 ampmLabel->show(); 227 ampmLabel->show();
228 } 228 }
229 else 229 else
230 { 230 {
231 s.sprintf( "%2d%c%02d", tm.hour(), ':', tm.minute() ); 231 s.sprintf( "%2d%c%02d", tm.hour(), ':', tm.minute() );
232 ampmLabel->hide(); 232 ampmLabel->hide();
233 } 233 }
234 lcd->display( s ); 234 lcd->display( s );
235 lcd->repaint( FALSE ); 235 lcd->repaint( FALSE );
236 aclock->display( QTime::currentTime() ); 236 aclock->display( QTime::currentTime() );
237 date->setText( TimeString::longDateString( QDate::currentDate() ) ); 237 date->setText( TimeString::longDateString( QDate::currentDate() ) );
238 } 238 }
239 else 239 else
240 { 240 {
241 QTime swatch_time; 241 QTime swatch_time;
242 QString lcdtext; 242 QString lcdtext;
243 int totalms = swatch_totalms; 243 int totalms = swatch_totalms;
244 if ( swatch_running ) 244 if ( swatch_running )
245 totalms += swatch_start.elapsed(); 245 totalms += swatch_start.elapsed();
246 swatch_time = QTime( 0, 0, 0 ).addMSecs( totalms ); 246 swatch_time = QTime( 0, 0, 0 ).addMSecs( totalms );
247 QString d = swatch_running ? QString( " " ) 247 QString d = swatch_running ? QString( " " )
248 : QString::number( totalms % 1000 + 1000 ); 248 : QString::number( totalms % 1000 + 1000 );
249 lcdtext = swatch_time.toString() + "." + d.right( 3 ).left( sw_prec ); 249 lcdtext = swatch_time.toString() + "." + d.right( 3 ).left( sw_prec );
250 lcd->display( lcdtext ); 250 lcd->display( lcdtext );
251 lcd->repaint( FALSE ); 251 lcd->repaint( FALSE );
252 aclock->display( swatch_time ); 252 aclock->display( swatch_time );
253 date->setText( TimeString::longDateString( QDate::currentDate() ) ); 253 date->setText( TimeString::longDateString( QDate::currentDate() ) );
254 } 254 }
255} 255}
256 256
257void Clock::changeClock( bool a ) 257void Clock::changeClock( bool a )
258{ 258{
259 ampm = a; 259 ampm = a;
260 updateClock(); 260 updateClock();
261} 261}
262 262
263void Clock::clearClock( void ) 263void Clock::clearClock( void )
264{ 264{
265 lcd->display( QTime( 0, 0, 0 ).toString() ); 265 lcd->display( QTime( 0, 0, 0 ).toString() );
266 aclock->display( QTime( 0, 0, 0 ) ); 266 aclock->display( QTime( 0, 0, 0 ) );
267} 267}
268 268
269void Clock::startSWatch() 269void Clock::startSWatch()
270{ 270{
271 if(swatch_running) { 271 if(swatch_running) {
272 stopSWatch(); 272 stopSWatch();
273 return; 273 return;
274 } 274 }
275 qDebug("startSWatch()"); 275 qDebug("startSWatch()");
276 swatch_start.start(); 276 swatch_start.start();
277 set->setText( tr( "Stop" ) ); 277 set->setText( tr( "Stop" ) );
278 t->start( 1000 ); 278 t->start( 1000 );
279 swatch_running = TRUE; 279 swatch_running = TRUE;
280 // disable screensaver while stop watch is running 280 // disable screensaver while stop watch is running
281 toggleScreenSaver( FALSE ); 281 toggleScreenSaver( FALSE );
282} 282}
283 283
284void Clock::stopSWatch() 284void Clock::stopSWatch()
285{ 285{
286 qDebug("stopSWatch()"); 286 qDebug("stopSWatch()");
287 swatch_totalms += swatch_start.elapsed(); 287 swatch_totalms += swatch_start.elapsed();
288 set->setText( tr( "Start" ) ); 288 set->setText( tr( "Start" ) );
289 t->stop(); 289 t->stop();
290 swatch_running = FALSE; 290 swatch_running = FALSE;
291 toggleScreenSaver( TRUE ); 291 toggleScreenSaver( TRUE );
292 updateClock(); 292 updateClock();
293} 293}
294 294
295 295
296void Clock::slotSet() 296void Clock::slotSet()
297{ 297{
298 if ( t->isActive() ) 298 if ( t->isActive() )
299 { 299 {
300 startSWatch(); 300 startSWatch();
301 } 301 }
302 else 302 else
303 { 303 {
304 stopSWatch(); 304 stopSWatch();
305 } 305 }
306} 306}
307 307
308void Clock::slotReset() 308void Clock::slotReset()
309{ 309{
310 t->stop(); 310 t->stop();
311 swatch_start.start(); 311 swatch_start.start();
312 swatch_totalms = 0; 312 swatch_totalms = 0;
313 313
314 if ( swatch_running ) 314 if ( swatch_running )
315 t->start( 1000 ); 315 t->start( 1000 );
316 316
317 updateClock(); 317 updateClock();
318} 318}
319 319
320void Clock::modeSelect( int m ) 320void Clock::modeSelect( int m )
321{ 321{
322 qDebug("Clock::modeSelect( %d) ", m); 322 qDebug("Clock::modeSelect( %d) ", m);
323 if ( m != 0 ) 323 if ( m != 0 )
324 { 324 {
325 lcd->setNumDigits( 8 + 1 + sw_prec ); 325 lcd->setNumDigits( 8 + 1 + sw_prec );
326 lcd->setMinimumWidth( lcd->sizeHint().width() ); 326 lcd->setMinimumWidth( lcd->sizeHint().width() );
327 set->setEnabled( TRUE ); 327 set->setEnabled( TRUE );
328 reset->setEnabled( TRUE ); 328 reset->setEnabled( TRUE );
329 ampmLabel->hide(); 329 ampmLabel->hide();
330 330
331// if(m == 2) { 331// if(m == 2) {
332 if ( !swatch_running ) { 332 if ( !swatch_running ) {
333 t->start( 1000 ); 333 t->start( 1000 );
334 } 334 }
335// else 335// else
336// { 336// {
337// stopSWatch(); 337// stopSWatch();
338// } 338// }
339// } 339// }
340 } 340 }
341 else //clock mode 341 else //clock mode
342 { 342 {
343 lcd->setNumDigits( 5 ); 343 lcd->setNumDigits( 5 );
344 lcd->setMinimumWidth( lcd->sizeHint().width() ); 344 lcd->setMinimumWidth( lcd->sizeHint().width() );
345 set->setEnabled( FALSE ); 345 set->setEnabled( FALSE );
346 reset->setEnabled( FALSE ); 346 reset->setEnabled( FALSE );
347 t->start( 1000 ); 347 t->start( 1000 );
348 } 348 }
349 349
350 Config config( "Clock" ); 350 Config config( "Clock" );
351 config.setGroup( "Mode" ); 351 config.setGroup( "Mode" );
352 config.writeEntry( "clockMode", m ); 352 config.writeEntry( "clockMode", m );
353 updateClock(); 353 updateClock();
354} 354}
355 355
356//this sets the alarm time 356//this sets the alarm time
357void Clock::slotSetAlarm() 357void Clock::slotSetAlarm()
358{ 358{
359 if ( !snoozeBtn->isHidden() ) 359 if ( !snoozeBtn->isHidden() )
360 slotToggleAlarm(); 360 slotToggleAlarm();
361 Set_Alarm *setAlarmDlg; 361 Set_Alarm *setAlarmDlg;
362 setAlarmDlg = new Set_Alarm( this, "SetAlarm", TRUE ); 362 setAlarmDlg = new Set_Alarm( this, "SetAlarm", TRUE );
363 int result = setAlarmDlg->exec(); 363 int result = setAlarmDlg->exec();
364 if ( result == 1 ) { 364 if ( result == 1 ) {
365 Config config( "qpe" ); 365 Config config( "qpe" );
366 config.setGroup( "Time" ); 366 config.setGroup( "Time" );
367 QString tmp; 367 QString tmp;
368 hour = setAlarmDlg->Hour_Slider->value(); 368 hour = setAlarmDlg->Hour_Slider->value();
369 minute = setAlarmDlg->Minute_Slider->value(); 369 minute = setAlarmDlg->Minute_Slider->value();
370 snoozeTime = setAlarmDlg->SnoozeSlider->value(); 370 snoozeTime = setAlarmDlg->SnoozeSlider->value();
371 if ( ampm ) { 371 if ( ampm ) {
372 if ( hour == 12 ) 372 if ( hour == 12 )
373 hour = 0; 373 hour = 0;
374 374
375 if ( setAlarmDlg->Pm_RadioButton->isChecked() && hour < 12 ) 375 if ( setAlarmDlg->Pm_RadioButton->isChecked() && hour < 12 )
376 hour += 12; 376 hour += 12;
377 } 377 }
378 config.writeEntry( "clockAlarmHour", tmp.setNum( hour ), 10 ); 378 config.writeEntry( "clockAlarmHour", tmp.setNum( hour ), 10 );
379 config.writeEntry( "clockAlarmMinute", tmp.setNum( minute ), 10 ); 379 config.writeEntry( "clockAlarmMinute", tmp.setNum( minute ), 10 );
380 config.writeEntry( "clockAlarmSnooze", tmp.setNum( snoozeTime ), 10 ); 380 config.writeEntry( "clockAlarmSnooze", tmp.setNum( snoozeTime ), 10 );
381 config.write(); 381 config.write();
382 } 382 }
383} 383}
384 384
385void Clock::slotSnooze() 385void Clock::slotSnooze()
386{ 386{
387 bSound = FALSE; 387 bSound = FALSE;
388 int warn = 0; 388 int warn = 0;
389 QTime t = QTime::currentTime(); 389 QTime t = QTime::currentTime();
390 QDateTime whenl( when.date(), t.addSecs( snoozeTime * 60 ) ); 390 QDateTime whenl( when.date(), t.addSecs( snoozeTime * 60 ) );
391 when = whenl; 391 when = whenl;
392 AlarmServer::addAlarm( when, 392 AlarmServer::addAlarm( when,
393 "QPE/Application/clock", 393 "QPE/Application/clock",
394 "alarm(QDateTime,int)", warn ); 394 "alarm(QDateTime,int)", warn );
395 395
396} 396}
397 397
398//toggles alarm on/off 398//toggles alarm on/off
399void Clock::slotToggleAlarm() 399void Clock::slotToggleAlarm()
400{ 400{
401 Config config( "qpe" ); 401 Config config( "qpe" );
402 config.setGroup( "Time" ); 402 config.setGroup( "Time" );
403 if ( alarmBool ) 403 if ( alarmBool )
404 { 404 {
405 config.writeEntry( "clockAlarmSet", "FALSE" ); 405 config.writeEntry( "clockAlarmSet", "FALSE" );
406 alarmOffBtn->setText( tr( "Alarm Is Off" ) ); 406 alarmOffBtn->setText( tr( "Alarm Is Off" ) );
407 snoozeBtn->hide(); 407 snoozeBtn->hide();
408 alarmBool = FALSE; 408 alarmBool = FALSE;
409 alarmOff(); 409 alarmOff();
410 } 410 }
411 else 411 else
412 { 412 {
413 config.writeEntry( "clockAlarmSet", "TRUE" ); 413 config.writeEntry( "clockAlarmSet", "TRUE" );
414 alarmOffBtn->setText( tr( "Alarm Is On" ) ); 414 alarmOffBtn->setText( tr( "Alarm Is On" ) );
415 snoozeBtn->show(); 415 snoozeBtn->show();
416 alarmBool = TRUE; 416 alarmBool = TRUE;
417 alarmOn(); 417 alarmOn();
418 } 418 }
419 config.write(); 419 config.write();
420} 420}
421 421
422void Clock::alarmOn() 422void Clock::alarmOn()
423{ 423{
424 QDate d = QDate::currentDate(); 424 QDate d = QDate::currentDate();
425 QTime tm( ( int ) hour, ( int ) minute, 0 ); 425 QTime tm( ( int ) hour, ( int ) minute, 0 );
426 qDebug( "Time set " + tm.toString() ); 426 qDebug( "Time set " + tm.toString() );
427 QTime t = QTime::currentTime(); 427 QTime t = QTime::currentTime();
428 if ( t > tm ) 428 if ( t > tm )
429 d = d.addDays( 1 ); 429 d = d.addDays( 1 );
430 int warn = 0; 430 int warn = 0;
431 QDateTime whenl( d, tm ); 431 QDateTime whenl( d, tm );
432 when = whenl; 432 when = whenl;
433 AlarmServer::addAlarm( when, 433 AlarmServer::addAlarm( when,
434 "QPE/Application/clock", 434 "QPE/Application/clock",
435 "alarm(QDateTime,int)", warn ); 435 "alarm(QDateTime,int)", warn );
436// setCaption( "Alarm set: " + whenl.toString() ); 436// setCaption( "Alarm set: " + whenl.toString() );
437 setCaption( tr("Alarm set: %1" ).arg(whenl.toString()) ); 437 setCaption( tr("Alarm set: %1" ).arg(whenl.toString()) );
438} 438}
439 439
440void Clock::alarmOff() 440void Clock::alarmOff()
441{ 441{
442 int warn = 0; 442 int warn = 0;
443 bSound = FALSE; 443 bSound = FALSE;
444 AlarmServer::deleteAlarm( when, 444 AlarmServer::deleteAlarm( when,
445 "QPE/Application/clock", 445 "QPE/Application/clock",
446 "alarm(QDateTime,int)", warn ); 446 "alarm(QDateTime,int)", warn );
447 qDebug( "Alarm Off " + when.toString() ); 447 qDebug( "Alarm Off " + when.toString() );
448 setCaption( tr("Clock") ); 448 setCaption( tr("Clock") );
449} 449}
450 450
451void Clock::clearTimer() 451void Clock::clearTimer()
452{ 452{
453 alarmOffBtn->setText( tr( "Alarm Is Off" ) ); 453 alarmOffBtn->setText( tr( "Alarm Is Off" ) );
454 alarmBool = FALSE; 454 alarmBool = FALSE;
455 snoozeBtn->hide(); 455 snoozeBtn->hide();
456 setCaption( tr("Clock") ); 456 setCaption( tr("Clock") );
457} 457}
458 458
459void Clock::appMessage( const QCString& msg, const QByteArray& /*data*/ ) 459void Clock::appMessage( const QCString& msg, const QByteArray& /*data*/ )
460{ 460{
461 int stopTimer = 0; 461 int stopTimer = 0;
462 int timerStay = 5000; 462 int timerStay = 5000;
463 bSound = TRUE; 463 bSound = TRUE;
464 qDebug( "Message received in clock" ); 464 qDebug( "Message received in clock" );
465 if ( msg == "alarm(QDateTime,int)" ) 465 if ( msg == "alarm(QDateTime,int)" )
466 { 466 {
467 Config config( "qpe" ); 467 Config config( "qpe" );
468 config.setGroup( "Time" ); 468 config.setGroup( "Time" );
469 if ( config.readBoolEntry( "mp3Alarm", 0 ) ) 469 if ( config.readBoolEntry( "mp3Alarm", 0 ) )
470 { 470 {
471 clearTimer(); 471 clearTimer();
472 pthread_t thread; 472 pthread_t thread;
473 pthread_create(&thread, NULL, (void * (*) (void *))startPlayer, NULL/* &*/); 473 pthread_create(&thread, NULL, (void * (*) (void *))startPlayer, NULL/* &*/);
474 474
475 } 475 }
476 else 476 else
477 { 477 {
478 478
479 Sound::soundAlarm(); 479 Sound::soundAlarm();
480 stopTimer = startTimer( timerStay ); 480 stopTimer = startTimer( timerStay );
481 } 481 }
482 } 482 }
483 483
484 if ( msg == "timerStart()" ) 484 if ( msg == "timerStart()" )
485 { 485 {
486 slotStartTimer(); 486 slotStartTimer();
487 } 487 }
488 if ( msg == "timerStop()" ) 488 if ( msg == "timerStop()" )
489 { 489 {
490 slotStopTimer(); 490 slotStopTimer();
491 } 491 }
492 if ( msg == "timerReset()" ) 492 if ( msg == "timerReset()" )
493 { 493 {
494 slotResetTimer(); 494 slotResetTimer();
495 } 495 }
496 496
497 show(); 497 show();
498 raise(); 498 raise();
499 QPEApplication::setKeepRunning(); 499 QPEApplication::setKeepRunning();
500 setActiveWindow(); 500 setActiveWindow();
501} 501}
502 502
503void Clock::timerEvent( QTimerEvent *e ) 503void Clock::timerEvent( QTimerEvent *e )
504{ 504{
505 static int stop = 0; 505 static int stop = 0;
506 if ( stop < 120 && bSound ) 506 if ( stop < 120 && bSound )
507 { 507 {
508 Sound::soundAlarm(); 508 Sound::soundAlarm();
509 stop++; 509 stop++;
510 } 510 }
511 else 511 else
512 { 512 {
513 stop = 0; 513 stop = 0;
514 killTimer( e->timerId() ); 514 killTimer( e->timerId() );
515 clearTimer(); 515 clearTimer();
516 setCaption( tr( "Clock: Alarm was missed." ) ); 516 setCaption( tr( "Clock: Alarm was missed." ) );
517 } 517 }
518} 518}
519 519
520AnalogClock::AnalogClock(QWidget * parent, const char * name) : QFrame( parent, name ), clear(true) 520AnalogClock::AnalogClock(QWidget * parent, const char * name) : QFrame( parent, name ), clear(true)
521{ 521{
522 QWidget *d = QApplication::desktop(); 522 QWidget *d = QApplication::desktop();
523 if(d->width() <= 240) 523 if(d->width() <= 240)
524 bg = Resource::loadPixmap("clock/bg"); 524 bg = Resource::loadPixmap("clock/bg");
525} 525}
526 526
527QSizePolicy AnalogClock::sizePolicy() const 527QSizePolicy AnalogClock::sizePolicy() const
528{ 528{
529 return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); 529 return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
530} 530}
531 531
532void AnalogClock::drawContents( QPainter *p ) 532void AnalogClock::drawContents( QPainter *p )
533{ 533{
534 QRect r = contentsRect(); 534 QRect r = contentsRect();
535 QRect fr; 535 QRect fr;
536 536
537 p->drawPixmap(QPoint(0, 0), bg, r); 537 p->drawPixmap(QPoint(0, 0), bg, r);
538 538
539 if ( r. width ( ) > r. height ( )) 539 if ( r. width ( ) > r. height ( ))
540 fr. setRect (( r. width ( ) - r. height ( )) / 2, r. y ( ), r. height ( ), r. height ( )); 540 fr. setRect (( r. width ( ) - r. height ( )) / 2, r. y ( ), r. height ( ), r. height ( ));
541 else 541 else
542 fr. setRect ( r. x ( ), ( r. height ( ) - r. width ( )) / 2, r. width ( ), r. width ( )); 542 fr. setRect ( r. x ( ), ( r. height ( ) - r. width ( )) / 2, r. width ( ), r. width ( ));
543 543
544 QPoint center = fr. center ( ); // ( fr.x() + fr.width() / 2, fr.y() + fr.height() / 2 ); 544 QPoint center = fr. center ( ); // ( fr.x() + fr.width() / 2, fr.y() + fr.height() / 2 );
545 QPoint l1 ( center. x ( ), fr. y ( ) + 2 ); 545 QPoint l1 ( center. x ( ), fr. y ( ) + 2 );
546 QPoint l2 ( center. x ( ), fr. y ( ) + 8 ); 546 QPoint l2 ( center. x ( ), fr. y ( ) + 8 );
547 547
548 548
549 549
550 if ( clear ) 550 if ( clear )
551 { 551 {
552 erase ( r ); 552 erase ( r );
553 p-> setPen ( NoPen ); 553 p-> setPen ( NoPen );
554 p-> setBrush ( colorGroup ( ). color ( QColorGroup::Base )); 554 p-> setBrush ( colorGroup ( ). color ( QColorGroup::Base ));
555 p-> drawEllipse ( fr ); 555 p-> drawEllipse ( fr );
556 p-> setBrush ( NoBrush ); 556 p-> setBrush ( NoBrush );
557 557
558 // draw ticks 558 // draw ticks
559 p->setPen( QPen( colorGroup ( ). color ( QColorGroup::Text ), 1 ) ); 559 p->setPen( QPen( colorGroup ( ). color ( QColorGroup::Text ), 1 ) );
560 for ( int i = 0; i < 12; i++ ) 560 for ( int i = 0; i < 12; i++ )
561 p->drawLine( rotate( center, l1, i * 30 ), rotate( center, l2, i * 30 ) ); 561 p->drawLine( rotate( center, l1, i * 30 ), rotate( center, l2, i * 30 ) );
562 } 562 }
563 else 563 else
564 { 564 {
565 drawPointers ( p, fr, colorGroup ( ). color ( QColorGroup::Base ), prevTime, &currTime ); 565 drawPointers ( p, fr, colorGroup ( ). color ( QColorGroup::Base ), prevTime, &currTime );
566 } 566 }
567 567
568 drawPointers ( p, fr, colorGroup ( ). color ( QColorGroup::Text ), currTime ); 568 drawPointers ( p, fr, colorGroup ( ). color ( QColorGroup::Text ), currTime );
569 569
570 prevTime = currTime; 570 prevTime = currTime;
571} 571}
572 572
573void AnalogClock::drawPointers ( QPainter *p, const QRect &r, const QColor &c, const QTime &t, const QTime *t2 ) 573void AnalogClock::drawPointers ( QPainter *p, const QRect &r, const QColor &c, const QTime &t, const QTime *t2 )
574{ 574{
575 QPoint center = r. center ( ); 575 QPoint center = r. center ( );
576 576
577 QPoint h1( center. x ( ), r. y ( ) + r. height ( ) / 4 ); 577 QPoint h1( center. x ( ), r. y ( ) + r. height ( ) / 4 );
578 QPoint h2( center. x ( ), center. y ( ) ); 578 QPoint h2( center. x ( ), center. y ( ) );
579 579
580 QPoint m1( center. x ( ), r.y() + r.height() / 8 ); 580 QPoint m1( center. x ( ), r.y() + r.height() / 8 );
581 QPoint m2( center. x ( ), center. y ( ) ); 581 QPoint m2( center. x ( ), center. y ( ) );
582 582
583 QPoint s1( center. x ( ), r. y ( ) + 8 ); 583 QPoint s1( center. x ( ), r. y ( ) + 8 );
584 QPoint s2( center. x ( ), center. y ( ) ); 584 QPoint s2( center. x ( ), center. y ( ) );
585 585
586 586
587 if ( !t2 || ( t. minute ( ) != t2-> minute ( ) || t. hour ( ) != t2-> hour ( ))) { 587 if ( !t2 || ( t. minute ( ) != t2-> minute ( ) || t. hour ( ) != t2-> hour ( ))) {
588 // draw hour pointer 588 // draw hour pointer
589 h1 = rotate( center, h1, 30 * ( t.hour() % 12 ) + t.minute() / 2 ); 589 h1 = rotate( center, h1, 30 * ( t.hour() % 12 ) + t.minute() / 2 );
590 h2 = rotate( center, h2, 30 * ( t.hour() % 12 ) + t.minute() / 2 ); 590 h2 = rotate( center, h2, 30 * ( t.hour() % 12 ) + t.minute() / 2 );
591 p-> setPen ( QPen ( c, 3 )); 591 p-> setPen ( QPen ( c, 3 ));
592 p-> drawLine ( h1, h2 ); 592 p-> drawLine ( h1, h2 );
593 } 593 }
594 594
595 if ( !t2 || ( t. minute ( ) != t2-> minute ( ))) { 595 if ( !t2 || ( t. minute ( ) != t2-> minute ( ))) {
596 // draw minute pointer 596 // draw minute pointer
597 m1 = rotate( center, m1, t.minute() * 6 ); 597 m1 = rotate( center, m1, t.minute() * 6 );
598 m2 = rotate( center, m2, t.minute() * 6 ); 598 m2 = rotate( center, m2, t.minute() * 6 );
599 p-> setPen ( QPen ( c, 2 )); 599 p-> setPen ( QPen ( c, 2 ));
600 p-> drawLine ( m1, m2 ); 600 p-> drawLine ( m1, m2 );
601 } 601 }
602 602
603 if ( !t2 || ( t. second ( ) != t2-> second ( ))) { 603 if ( !t2 || ( t. second ( ) != t2-> second ( ))) {
604 // draw second pointer 604 // draw second pointer
605 s1 = rotate( center, s1, t.second() * 6 ); 605 s1 = rotate( center, s1, t.second() * 6 );
606 s2 = rotate( center, s2, t.second() * 6 ); 606 s2 = rotate( center, s2, t.second() * 6 );
607 p-> setPen ( QPen ( c, 1 )); 607 p-> setPen ( QPen ( c, 1 ));
608 p-> drawLine ( s1, s2 ); 608 p-> drawLine ( s1, s2 );
609 } 609 }
610} 610}
611 611
612void AnalogClock::display( const QTime& t ) 612void AnalogClock::display( const QTime& t )
613{ 613{
614 currTime = t; 614 currTime = t;
615 clear = false; 615 clear = false;
616 repaint( false ); 616 repaint( false );
617 clear = true; 617 clear = true;
618} 618}
619 619
620QPoint AnalogClock::rotate( QPoint c, QPoint p, int a ) 620QPoint AnalogClock::rotate( QPoint c, QPoint p, int a )
621{ 621{
622 double angle = deg2rad * ( - a + 180 ); 622 double angle = deg2rad * ( - a + 180 );
623 double nx = c.x() - ( p.x() - c.x() ) * cos( angle ) - 623 double nx = c.x() - ( p.x() - c.x() ) * cos( angle ) -
624 ( p.y() - c.y() ) * sin( angle ); 624 ( p.y() - c.y() ) * sin( angle );
625 double ny = c.y() - ( p.y() - c.y() ) * cos( angle ) + 625 double ny = c.y() - ( p.y() - c.y() ) * cos( angle ) +
626 ( p.x() - c.x() ) * sin( angle ); 626 ( p.x() - c.x() ) * sin( angle );
627 return QPoint( nx, ny ); 627 return QPoint( nx, ny );
628} 628}
629 629
630void Clock::slotAdjustTime() 630void Clock::slotAdjustTime()
631{ 631{
632 QCopEnvelope e( "QPE/System", "execute(QString)" ); 632 QCopEnvelope e( "QPE/System", "execute(QString)" );
633 e << QString( "systemtime" ); 633 e << QString( "systemtime" );
634} 634}
635 635
636void Clock::slotStartTimer() 636void Clock::slotStartTimer()
637{ 637{
638 if ( clockRB->isChecked() ) 638 if ( clockRB->isChecked() )
639 setSwatchMode( 1); 639 setSwatchMode( 1);
640 startSWatch(); 640 startSWatch();
641} 641}
642 642
643void Clock::slotStopTimer() 643void Clock::slotStopTimer()
644{ 644{
645 if ( clockRB->isChecked() ) 645 if ( clockRB->isChecked() )
646 setSwatchMode( 1); 646 setSwatchMode( 1);
647 stopSWatch(); 647 stopSWatch();
648} 648}
649 649
650void Clock::slotResetTimer() 650void Clock::slotResetTimer()
651{ 651{
652 if ( clockRB->isChecked() ) 652 if ( clockRB->isChecked() )
653 setSwatchMode( 1); 653 setSwatchMode( 1);
654slotReset(); 654slotReset();
655} 655}
656 656
657void Clock::setSwatchMode(int mode) 657void Clock::setSwatchMode(int mode)
658{ 658{
659 qDebug("Clock::setSwatchMode( %d)", mode); 659 qDebug("Clock::setSwatchMode( %d)", mode);
660 swatchRB->setChecked( mode); 660 swatchRB->setChecked( mode);
661 clearClock( ); 661 clearClock( );
662 modeSelect( mode ); 662 modeSelect( mode );
663} 663}
diff --git a/noncore/tools/formatter/formatter.cpp b/noncore/tools/formatter/formatter.cpp
index e869317..77e1790 100644
--- a/noncore/tools/formatter/formatter.cpp
+++ b/noncore/tools/formatter/formatter.cpp
@@ -1,632 +1,632 @@
1/**************************************************************************** 1/****************************************************************************
2 ** formatter.cpp 2 ** formatter.cpp
3 ** 3 **
4 ** Copyright: Thu Apr 11 11:01:13 2002 4 ** Copyright: Thu Apr 11 11:01:13 2002
5 ** by: L. J. Potter 5 ** by: L. J. Potter
6 ** 6 **
7 ****************************************************************************/ 7 ****************************************************************************/
8 8
9#include "formatter.h" 9#include "formatter.h"
10#include "inputDialog.h" 10#include "inputDialog.h"
11#include "output.h" 11#include "output.h"
12 12
13/* OPIE */ 13/* OPIE */
14#include <qpe/qpetoolbar.h> 14#include <qpe/qpetoolbar.h>
15#include <qpe/qpeapplication.h> 15#include <qpe/qpeapplication.h>
16#include <qpe/resource.h> 16#include <qpe/resource.h>
17#include <qpe/config.h> 17#include <qpe/config.h>
18#include <qpe/mimetype.h> 18#include <qpe/mimetype.h>
19#include <qpe/qcopenvelope_qws.h> 19#include <qpe/qcopenvelope_qws.h>
20#include <qpe/storage.h> 20#include <qpe/storage.h>
21 21
22/* QT */ 22/* QT */
23#include <qmenubar.h> 23#include <qmenubar.h>
24#include <qmultilineedit.h> 24#include <qmultilineedit.h>
25#include <qstring.h> 25#include <qstring.h>
26#include <qlist.h> 26#include <qlist.h>
27#include <qstringlist.h> 27#include <qstringlist.h>
28#include <qdir.h> 28#include <qdir.h>
29#include <qfile.h> 29#include <qfile.h>
30#include <qtstream.h> 30#include <qtstream.h>
31#include <qcombobox.h> 31#include <qcombobox.h>
32#include <qpopupmenu.h> 32#include <qpopupmenu.h>
33#include <qmessagebox.h> 33#include <qmessagebox.h>
34#include <qregexp.h> 34#include <qregexp.h>
35#include <qlabel.h> 35#include <qlabel.h>
36#include <qlineedit.h> 36#include <qlineedit.h>
37#include <qpushbutton.h> 37#include <qpushbutton.h>
38#include <qtabwidget.h> 38#include <qtabwidget.h>
39#include <qwidget.h> 39#include <qwidget.h>
40#include <qlayout.h> 40#include <qlayout.h>
41#include <qvariant.h> 41#include <qvariant.h>
42 42
43/* STD */ 43/* STD */
44#include <unistd.h> 44#include <unistd.h>
45#include <stdio.h> 45#include <stdio.h>
46#include <stdlib.h> 46#include <stdlib.h>
47#include <sys/vfs.h> 47#include <sys/vfs.h>
48#include <mntent.h> 48#include <mntent.h>
49#include <string.h> 49#include <string.h>
50#include <errno.h> 50#include <errno.h>
51 51
52#define BLANK ' ' 52#define BLANK ' '
53#define DELIMITER '#' 53#define DELIMITER '#'
54 54
55/* 55/*
56 Blah blah blah blah */ 56 Blah blah blah blah */
57FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool modal ) 57FormatterApp::FormatterApp( QWidget* parent, const char* name, WFlags fl, bool modal )
58 : QMainWindow( parent, name, fl ) 58 : QMainWindow( parent, name, fl )
59 // : QDialog( parent, name, modal, fl ) 59 // : QDialog( parent, name, modal, fl )
60{ 60{
61 if ( !name ) 61 if ( !name )
62 setName( "FormatterApp" ); 62 setName( "FormatterApp" );
63 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 63 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
64 64
65 setCaption( tr( "Formatter" ) ); 65 setCaption( tr( "Formatter" ) );
66 FormatterAppLayout = new QGridLayout( this ); 66 FormatterAppLayout = new QGridLayout( this );
67 FormatterAppLayout->setSpacing( 2); 67 FormatterAppLayout->setSpacing( 2);
68 FormatterAppLayout->setMargin( 2 ); 68 FormatterAppLayout->setMargin( 2 );
69 69
70 TabWidget = new QTabWidget( this, "TabWidget" ); 70 TabWidget = new QTabWidget( this, "TabWidget" );
71 71
72 tab = new QWidget( TabWidget, "tab" ); 72 tab = new QWidget( TabWidget, "tab" );
73 tabLayout = new QGridLayout( tab ); 73 tabLayout = new QGridLayout( tab );
74 tabLayout->setSpacing( 3); 74 tabLayout->setSpacing( 3);
75 tabLayout->setMargin( 2); 75 tabLayout->setMargin( 2);
76 76
77 storageComboBox = new QComboBox( FALSE, tab, "storageComboBox" ); 77 storageComboBox = new QComboBox( FALSE, tab, "storageComboBox" );
78 storageComboBox->setMaximumWidth(220); 78 storageComboBox->setMaximumWidth(220);
79 79
80 tabLayout->addMultiCellWidget( storageComboBox, 0, 0, 0, 1); 80 tabLayout->addMultiCellWidget( storageComboBox, 0, 0, 0, 1);
81 81
82 TextLabel4 = new QLabel( tab, "TextLabel4" ); 82 TextLabel4 = new QLabel( tab, "TextLabel4" );
83 TextLabel4->setText( tr( "Storage Type" ) ); 83 TextLabel4->setText( tr( "Storage Type" ) );
84 84
85 tabLayout->addMultiCellWidget( TextLabel4, 1, 1, 0, 1); 85 tabLayout->addMultiCellWidget( TextLabel4, 1, 1, 0, 1);
86 86
87 TextLabel2 = new QLabel( tab, "TextLabel2" ); 87 TextLabel2 = new QLabel( tab, "TextLabel2" );
88 TextLabel2->setText( tr( "File Systems" ) ); 88 TextLabel2->setText( tr( "File Systems" ) );
89 89
90 tabLayout->addMultiCellWidget( TextLabel2, 4, 4, 0, 1); 90 tabLayout->addMultiCellWidget( TextLabel2, 4, 4, 0, 1);
91 91
92 fileSystemsCombo = new QComboBox( FALSE, tab, "fileSystemsCombo" ); 92 fileSystemsCombo = new QComboBox( FALSE, tab, "fileSystemsCombo" );
93 fileSystemsCombo->setMaximumWidth(220); 93 fileSystemsCombo->setMaximumWidth(220);
94 94
95 tabLayout->addMultiCellWidget( fileSystemsCombo, 3, 3, 0, 1); 95 tabLayout->addMultiCellWidget( fileSystemsCombo, 3, 3, 0, 1);
96 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum ); 96 QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum );
97 tabLayout->addItem( spacer, 2, 0 ); 97 tabLayout->addItem( spacer, 2, 0 );
98 98
99 formatPushButton = new QPushButton( tab, "formatPushButton" ); 99 formatPushButton = new QPushButton( tab, "formatPushButton" );
100 formatPushButton->setText( tr( "Format" ) ); 100 formatPushButton->setText( tr( "Format" ) );
101 formatPushButton->setMaximumWidth(170); 101 formatPushButton->setMaximumWidth(170);
102 102
103 tabLayout->addMultiCellWidget( formatPushButton, 6, 6, 0, 1); 103 tabLayout->addMultiCellWidget( formatPushButton, 6, 6, 0, 1);
104 QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum ); 104 QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum );
105 tabLayout->addItem( spacer_2, 5, 0 ); 105 tabLayout->addItem( spacer_2, 5, 0 );
106 106
107 TabWidget->insertTab( tab, tr( "Main" ) ); 107 TabWidget->insertTab( tab, tr( "Main" ) );
108 108
109 tab_2 = new QWidget( TabWidget, "tab_2" ); 109 tab_2 = new QWidget( TabWidget, "tab_2" );
110 tabLayout_2 = new QGridLayout( tab_2 ); 110 tabLayout_2 = new QGridLayout( tab_2 );
111 tabLayout_2->setSpacing(3); 111 tabLayout_2->setSpacing(3);
112 tabLayout_2->setMargin(2); 112 tabLayout_2->setMargin(2);
113 113
114 mountPointLineEdit = new QLineEdit( tab_2, "mountPointLineEdit" ); 114 mountPointLineEdit = new QLineEdit( tab_2, "mountPointLineEdit" );
115 115
116 tabLayout_2->addMultiCellWidget( mountPointLineEdit, 0, 0, 0, 1); 116 tabLayout_2->addMultiCellWidget( mountPointLineEdit, 0, 0, 0, 1);
117 117
118 deviceComboBox = new QComboBox( FALSE, tab_2, "deviceComboBox" ); 118 deviceComboBox = new QComboBox( FALSE, tab_2, "deviceComboBox" );
119 119
120 tabLayout_2->addMultiCellWidget( deviceComboBox, 3, 3, 0, 1); 120 tabLayout_2->addMultiCellWidget( deviceComboBox, 3, 3, 0, 1);
121 121
122 TextLabel5 = new QLabel( tab_2, "TextLabel5" ); 122 TextLabel5 = new QLabel( tab_2, "TextLabel5" );
123 TextLabel5->setText( tr( "CAUTION:\n" 123 TextLabel5->setText( tr( "CAUTION:\n"
124 "Changing parameters on this\n" 124 "Changing parameters on this\n"
125 "page may cause your system\n" 125 "page may cause your system\n"
126 "to stop functioning properly!" ) );//idiot message 126 "to stop functioning properly!" ) );//idiot message
127 127
128 tabLayout_2->addMultiCellWidget( TextLabel5, 6, 6, 0, 1); 128 tabLayout_2->addMultiCellWidget( TextLabel5, 6, 6, 0, 1);
129 129
130 editPushButton = new QPushButton( tab_2, "editPushButton" ); 130 editPushButton = new QPushButton( tab_2, "editPushButton" );
131 editPushButton->setText( tr( "Edit fstab" ) ); 131 editPushButton->setText( tr( "Edit fstab" ) );
132 editPushButton->setMaximumWidth(100); 132 editPushButton->setMaximumWidth(100);
133 133
134 tabLayout_2->addMultiCellWidget( editPushButton, 7, 7, 0, 0 ); 134 tabLayout_2->addMultiCellWidget( editPushButton, 7, 7, 0, 0 );
135 135
136 fsckButton = new QPushButton( tab_2, "fsckPushButton" ); 136 fsckButton = new QPushButton( tab_2, "fsckPushButton" );
137 fsckButton->setText( tr( "Check Disk" ) ); 137 fsckButton->setText( tr( "Check Disk" ) );
138 fsckButton->setMaximumWidth(100); 138 fsckButton->setMaximumWidth(100);
139 139
140 tabLayout_2->addMultiCellWidget( fsckButton, 7, 7, 1, 1); 140 tabLayout_2->addMultiCellWidget( fsckButton, 7, 7, 1, 1);
141 141
142 TextLabel3 = new QLabel( tab_2, "TextLabel3" ); 142 TextLabel3 = new QLabel( tab_2, "TextLabel3" );
143 TextLabel3->setText( tr( "Device" ) ); 143 TextLabel3->setText( tr( "Device" ) );
144 144
145 tabLayout_2->addMultiCellWidget( TextLabel3, 4, 4, 0, 1 ); 145 tabLayout_2->addMultiCellWidget( TextLabel3, 4, 4, 0, 1 );
146 QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); 146 QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
147 tabLayout_2->addItem( spacer_3, 5, 0 ); 147 tabLayout_2->addItem( spacer_3, 5, 0 );
148 148
149 TextLabel1 = new QLabel( tab_2, "TextLabel1" ); 149 TextLabel1 = new QLabel( tab_2, "TextLabel1" );
150 TextLabel1->setText( tr( "Mount Point" ) ); 150 TextLabel1->setText( tr( "Mount Point" ) );
151 151
152 tabLayout_2->addMultiCellWidget( TextLabel1, 1, 1, 0, 1 ); 152 tabLayout_2->addMultiCellWidget( TextLabel1, 1, 1, 0, 1 );
153 QSpacerItem* spacer_4 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); 153 QSpacerItem* spacer_4 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
154 tabLayout_2->addItem( spacer_4, 2, 1 ); 154 tabLayout_2->addItem( spacer_4, 2, 1 );
155 TabWidget->insertTab( tab_2, tr( "Advanced" ) ); 155 TabWidget->insertTab( tab_2, tr( "Advanced" ) );
156 156
157 FormatterAppLayout->addWidget( TabWidget, 0, 1 ); 157 FormatterAppLayout->addWidget( TabWidget, 0, 1 );
158 158
159 connect( formatPushButton ,SIGNAL(released()),this,SLOT( doFormat()) ); 159 connect( formatPushButton ,SIGNAL(released()),this,SLOT( doFormat()) );
160 connect( editPushButton ,SIGNAL(released()),this,SLOT( editFstab()) ); 160 connect( editPushButton ,SIGNAL(released()),this,SLOT( editFstab()) );
161 connect( fsckButton ,SIGNAL(released()),this,SLOT( doFsck()) ); 161 connect( fsckButton ,SIGNAL(released()),this,SLOT( doFsck()) );
162 162
163 connect( fileSystemsCombo,SIGNAL(activated(int)),this,SLOT( fsComboSelected(int ) )); 163 connect( fileSystemsCombo,SIGNAL(activated(int)),this,SLOT( fsComboSelected(int) ));
164 connect( storageComboBox,SIGNAL(activated(int)),this,SLOT( storageComboSelected(int ) )); 164 connect( storageComboBox,SIGNAL(activated(int)),this,SLOT( storageComboSelected(int) ));
165 connect( deviceComboBox,SIGNAL(activated(int)),this,SLOT( deviceComboSelected(int ) )); 165 connect( deviceComboBox,SIGNAL(activated(int)),this,SLOT( deviceComboSelected(int) ));
166 166
167 167
168 fillCombos(); 168 fillCombos();
169} 169}
170 170
171FormatterApp::~FormatterApp() 171FormatterApp::~FormatterApp()
172{} 172{}
173 173
174void FormatterApp::doFormat() 174void FormatterApp::doFormat()
175{ 175{
176 int err=0; 176 int err=0;
177 Output *outDlg; 177 Output *outDlg;
178 QString umountS, remountS; 178 QString umountS, remountS;
179 QString text = storageComboBox->currentText(); 179 QString text = storageComboBox->currentText();
180 QString currentText = storageComboBox->currentText(); 180 QString currentText = storageComboBox->currentText();
181 QString cmd; 181 QString cmd;
182 QString diskDevice = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4); 182 QString diskDevice = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4);
183 QString diskName = currentText.left(currentText.find(" -> ",0,TRUE)); 183 QString diskName = currentText.left(currentText.find(" -> ",0,TRUE));
184 QString fs = fileSystemsCombo->currentText(); 184 QString fs = fileSystemsCombo->currentText();
185 185
186#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) // lets test on something cheap 186#if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) // lets test on something cheap
187#else 187#else
188 currentText = diskDevice = "/dev/fd0"; 188 currentText = diskDevice = "/dev/fd0";
189 umountS = "umount -v /floppy 2>&1"; 189 umountS = "umount -v /floppy 2>&1";
190 remountS = "mount -v /floppy 2>&1"; 190 remountS = "mount -v /floppy 2>&1";
191#endif 191#endif
192 192
193 if( currentText.find("CF",0,TRUE) != -1) 193 if( currentText.find("CF",0,TRUE) != -1)
194 { 194 {
195 umountS = "umount "; 195 umountS = "umount ";
196 remountS = "mount "; 196 remountS = "mount ";
197 197
198 // umountS = "/sbin/cardctl eject"; 198 // umountS = "/sbin/cardctl eject";
199 // remountS = "/sbin/cardctl insert"; 199 // remountS = "/sbin/cardctl insert";
200 } 200 }
201 if( currentText.find("SD",0,TRUE) != -1) 201 if( currentText.find("SD",0,TRUE) != -1)
202 { 202 {
203 umountS = "umount "; 203 umountS = "umount ";
204 remountS = "mount "; 204 remountS = "mount ";
205 // umountS = "/etc/sdcontrol compeject"; 205 // umountS = "/etc/sdcontrol compeject";
206 // remountS = "/etc/sdcontrol insert"; 206 // remountS = "/etc/sdcontrol insert";
207 } 207 }
208 208
209 switch ( QMessageBox::warning(this,tr("Format?") 209 switch ( QMessageBox::warning(this,tr("Format?")
210 , tr("Really format\n") +diskName+" "+ currentText + 210 , tr("Really format\n") +diskName+" "+ currentText +
211 tr("\nwith %1 filesystem?\nYou will loose all data!!").arg( fs ) 211 tr("\nwith %1 filesystem?\nYou will loose all data!!").arg( fs )
212 ,tr("Yes") 212 ,tr("Yes")
213 ,tr("No") 213 ,tr("No")
214 ,0 214 ,0
215 ,1 215 ,1
216 ,1) ) 216 ,1) )
217 { 217 {
218 case 0: 218 case 0:
219 { 219 {
220 if(fs == "vfat") 220 if(fs == "vfat")
221 cmd = "mkdosfs -v " + diskDevice+" 2>&1"; 221 cmd = "mkdosfs -v " + diskDevice+" 2>&1";
222 else if(fs == "ext2") 222 else if(fs == "ext2")
223 cmd = "mke2fs -v " + diskDevice+" 2>&1"; 223 cmd = "mke2fs -v " + diskDevice+" 2>&1";
224 else 224 else
225 { 225 {
226 QMessageBox::warning(this, tr("Formatter"),tr("Could not format.\nUnknown type"), tr("Ok")); 226 QMessageBox::warning(this, tr("Formatter"),tr("Could not format.\nUnknown type"), tr("Ok"));
227 break; 227 break;
228 } 228 }
229 // cmd = "ls -l"; 229 // cmd = "ls -l";
230 outDlg = new Output(this, tr("Formatter Output"),FALSE); 230 outDlg = new Output(this, tr("Formatter Output"),FALSE);
231 QPEApplication::showDialog( outDlg); 231 QPEApplication::showDialog( outDlg);
232 qApp->processEvents(); 232 qApp->processEvents();
233 FILE *fp; 233 FILE *fp;
234 char line[130]; 234 char line[130];
235 235
236 236
237 outDlg->OutputEdit->append( tr("Trying to umount %1.").arg( currentText) ); 237 outDlg->OutputEdit->append( tr("Trying to umount %1.").arg( currentText) );
238 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 238 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
239 239
240 sleep(1); 240 sleep(1);
241 qDebug("Command is "+umountS); 241 qDebug("Command is "+umountS);
242 fp = popen( (const char *) umountS, "r"); 242 fp = popen( (const char *) umountS, "r");
243 // qDebug("%d", fp); 243 // qDebug("%d", fp);
244 if ( !fp ) 244 if ( !fp )
245 { 245 {
246 qDebug("Could not execute '" + umountS + "'! err=%d\n" +(QString)strerror(errno), err); 246 qDebug("Could not execute '" + umountS + "'! err=%d\n" +(QString)strerror(errno), err);
247 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") ); 247 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") );
248 pclose(fp); 248 pclose(fp);
249 return; 249 return;
250 } 250 }
251 else 251 else
252 { 252 {
253 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted.")); 253 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted."));
254 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 254 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
255 while ( fgets( line, sizeof line, fp)) 255 while ( fgets( line, sizeof line, fp))
256 { 256 {
257 if( ((QString)line).find("busy",0,TRUE) != -1) 257 if( ((QString)line).find("busy",0,TRUE) != -1)
258 { 258 {
259 qDebug("Could not find '" + umountS); 259 qDebug("Could not find '" + umountS);
260 QMessageBox::warning( this, tr("Formatter"), tr("Could not umount.\nDevice is busy!"), tr("&OK") ); 260 QMessageBox::warning( this, tr("Formatter"), tr("Could not umount.\nDevice is busy!"), tr("&OK") );
261 pclose(fp); 261 pclose(fp);
262 return; 262 return;
263 } 263 }
264 else 264 else
265 { 265 {
266 QString lineStr = line; 266 QString lineStr = line;
267 lineStr=lineStr.left(lineStr.length()-1); 267 lineStr=lineStr.left(lineStr.length()-1);
268 outDlg->OutputEdit->append(lineStr); 268 outDlg->OutputEdit->append(lineStr);
269 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 269 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
270 } 270 }
271 } 271 }
272 } 272 }
273 pclose(fp); 273 pclose(fp);
274 274
275 qDebug("Command would be: "+cmd); 275 qDebug("Command would be: "+cmd);
276 outDlg->OutputEdit->append( tr("Trying to format.") ); 276 outDlg->OutputEdit->append( tr("Trying to format.") );
277 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 277 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
278 278
279 fp = popen( (const char *) cmd, "r"); 279 fp = popen( (const char *) cmd, "r");
280 while ( fgets( line, sizeof line, fp)) 280 while ( fgets( line, sizeof line, fp))
281 { 281 {
282 if( ((QString)line).find("No such device",0,TRUE) != -1) 282 if( ((QString)line).find("No such device",0,TRUE) != -1)
283 { 283 {
284 qDebug("No such device '" + umountS); 284 qDebug("No such device '" + umountS);
285 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") ); 285 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") );
286 pclose(fp); 286 pclose(fp);
287 // outDlg->OutputEdit->append("No such device"); 287 // outDlg->OutputEdit->append("No such device");
288 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 288 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
289 return; 289 return;
290 } 290 }
291 else 291 else
292 { 292 {
293 QString lineStr = line; 293 QString lineStr = line;
294 lineStr=lineStr.left(lineStr.length()-1); 294 lineStr=lineStr.left(lineStr.length()-1);
295 outDlg->OutputEdit->append(lineStr); 295 outDlg->OutputEdit->append(lineStr);
296 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 296 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
297 } 297 }
298 } 298 }
299 outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted.")); 299 outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted."));
300 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 300 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
301 pclose(fp); 301 pclose(fp);
302 302
303 outDlg->OutputEdit->append( tr("Trying to mount %1.").arg( currentText) ); 303 outDlg->OutputEdit->append( tr("Trying to mount %1.").arg( currentText) );
304 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 304 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
305 fp = popen( (const char *) remountS, "r"); 305 fp = popen( (const char *) remountS, "r");
306 if ( !fp) 306 if ( !fp)
307 { 307 {
308 qDebug("Could not execute '" + remountS + "'! err=%d\n" +(QString)strerror(errno), err); 308 qDebug("Could not execute '" + remountS + "'! err=%d\n" +(QString)strerror(errno), err);
309 QMessageBox::warning( this, tr("Formatter"), tr("Card mount failed!"), tr("&OK") ); 309 QMessageBox::warning( this, tr("Formatter"), tr("Card mount failed!"), tr("&OK") );
310 310
311 } 311 }
312 else 312 else
313 { 313 {
314 outDlg->OutputEdit->append(tr("%1\nhas been successfully mounted.").arg( currentText )); 314 outDlg->OutputEdit->append(tr("%1\nhas been successfully mounted.").arg( currentText ));
315 while ( fgets( line, sizeof line, fp)) 315 while ( fgets( line, sizeof line, fp))
316 { 316 {
317 QString lineStr = line; 317 QString lineStr = line;
318 lineStr=lineStr.left(lineStr.length()-1); 318 lineStr=lineStr.left(lineStr.length()-1);
319 outDlg->OutputEdit->append(lineStr); 319 outDlg->OutputEdit->append(lineStr);
320 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 320 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
321 } 321 }
322 } 322 }
323 pclose(fp); 323 pclose(fp);
324 sleep(1); 324 sleep(1);
325 325
326 outDlg->OutputEdit->append(tr("You can now close the output window.")); 326 outDlg->OutputEdit->append(tr("You can now close the output window."));
327 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 327 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
328 // outDlg->close(); 328 // outDlg->close();
329 // if(outDlg) 329 // if(outDlg)
330 // delete outDlg; 330 // delete outDlg;
331 } 331 }
332 break; 332 break;
333 }; 333 };
334} 334}
335 335
336bool FormatterApp::doFdisk() 336bool FormatterApp::doFdisk()
337{ 337{
338 return FALSE; 338 return FALSE;
339 339
340} 340}
341 341
342void FormatterApp::fillCombos() 342void FormatterApp::fillCombos()
343{ 343{
344 344
345 StorageInfo storageInfo; 345 StorageInfo storageInfo;
346 const QList<FileSystem> &fs = storageInfo.fileSystems(); 346 const QList<FileSystem> &fs = storageInfo.fileSystems();
347 QListIterator<FileSystem> it ( fs ); 347 QListIterator<FileSystem> it ( fs );
348 QString storage; 348 QString storage;
349 for( ; it.current(); ++it ) 349 for( ; it.current(); ++it )
350 { 350 {
351 const QString name = (*it)->name(); 351 const QString name = (*it)->name();
352 const QString path = (*it)->path(); 352 const QString path = (*it)->path();
353 const QString disk = (*it)->disk(); 353 const QString disk = (*it)->disk();
354 const QString options = (*it)->options(); 354 const QString options = (*it)->options();
355 if( name.find( tr("Internal"),0,TRUE) == -1) 355 if( name.find( tr("Internal"),0,TRUE) == -1)
356 { 356 {
357 storageComboBox->insertItem(name +" -> "+disk); 357 storageComboBox->insertItem(name +" -> "+disk);
358 } 358 }
359 // deviceComboBox->insertItem(disk); 359 // deviceComboBox->insertItem(disk);
360 } 360 }
361 parsetab("/etc/mtab"); 361 parsetab("/etc/mtab");
362 // parsetab("/etc/fstab"); 362 // parsetab("/etc/fstab");
363 fileSystemsCombo->insertStringList( fsList,-1); 363 fileSystemsCombo->insertStringList( fsList,-1);
364 deviceComboBox->insertStringList( deviceList,-1); 364 deviceComboBox->insertStringList( deviceList,-1);
365 storageComboSelected(0); 365 storageComboSelected(0);
366 deviceComboSelected(0); 366 deviceComboSelected(0);
367} 367}
368 368
369 369
370void FormatterApp::fsComboSelected(int ) 370void FormatterApp::fsComboSelected(int )
371{} 371{}
372 372
373void FormatterApp::storageComboSelected(int index ) 373void FormatterApp::storageComboSelected(int index )
374{ 374{
375 375
376 QString currentText = storageComboBox->text(index); 376 QString currentText = storageComboBox->text(index);
377 QString nameS = currentText.left( currentText.find("->",0,TRUE)); 377 QString nameS = currentText.left( currentText.find("->",0,TRUE));
378 378
379 TextLabel4->setText( tr( "Storage Type: %1").arg( nameS) ); 379 TextLabel4->setText( tr( "Storage Type: %1").arg( nameS) );
380 currentText = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4); 380 currentText = currentText.right( currentText.length() - currentText.find(" -> ",0,TRUE) - 4);
381 381
382 QString fsType = getFileSystemType((const QString &) currentText); 382 QString fsType = getFileSystemType((const QString &) currentText);
383 // qDebug(fsType); 383 // qDebug(fsType);
384 for(int i = 0; i < fileSystemsCombo->count(); i++) 384 for(int i = 0; i < fileSystemsCombo->count(); i++)
385 { 385 {
386 if( fsType == fileSystemsCombo->text(i)) 386 if( fsType == fileSystemsCombo->text(i))
387 fileSystemsCombo->setCurrentItem(i); 387 fileSystemsCombo->setCurrentItem(i);
388 } 388 }
389 // deviceComboSelected(index); 389 // deviceComboSelected(index);
390} 390}
391 391
392void FormatterApp::deviceComboSelected(int index) 392void FormatterApp::deviceComboSelected(int index)
393{ 393{
394 394
395 StorageInfo storageInfo; 395 StorageInfo storageInfo;
396 QString totalS, usedS, avS, diskS, nameS, fsType, selectedText; 396 QString totalS, usedS, avS, diskS, nameS, fsType, selectedText;
397 397
398 selectedText = deviceComboBox->text(index); 398 selectedText = deviceComboBox->text(index);
399 399
400 const QList<FileSystem> &fs = storageInfo.fileSystems(); 400 const QList<FileSystem> &fs = storageInfo.fileSystems();
401 QListIterator<FileSystem> it ( fs ); 401 QListIterator<FileSystem> it ( fs );
402 QString storage; 402 QString storage;
403 for( ; it.current(); ++it ) 403 for( ; it.current(); ++it )
404 { 404 {
405 const QString name = (*it)->name(); 405 const QString name = (*it)->name();
406 const QString path = (*it)->path(); 406 const QString path = (*it)->path();
407 const QString disk = (*it)->disk(); 407 const QString disk = (*it)->disk();
408 // const QString options = (*it)->options(); 408 // const QString options = (*it)->options();
409 if( selectedText == disk) 409 if( selectedText == disk)
410 { 410 {
411 diskS = disk; nameS= name; 411 diskS = disk; nameS= name;
412 mountPointLineEdit->setText(path); 412 mountPointLineEdit->setText(path);
413 long mult = (*it)->blockSize() / 1024; 413 long mult = (*it)->blockSize() / 1024;
414 long div = 1024 / (*it)->blockSize(); 414 long div = 1024 / (*it)->blockSize();
415 if ( !mult ) mult = 1; 415 if ( !mult ) mult = 1;
416 if ( !div ) div = 1; 416 if ( !div ) div = 1;
417 long total = (*it)->totalBlocks() * mult / div; 417 long total = (*it)->totalBlocks() * mult / div;
418 long totalMb = total/1024; 418 long totalMb = total/1024;
419 long avail = (*it)->availBlocks() * mult / div; 419 long avail = (*it)->availBlocks() * mult / div;
420 long availMb = avail/1024; 420 long availMb = avail/1024;
421 long used = total - avail; 421 long used = total - avail;
422 long usedMb = used/1024; 422 long usedMb = used/1024;
423 totalS.sprintf(tr("Total: %1 kB ( %d mB)\n").arg( total ), totalMb ); 423 totalS.sprintf(tr("Total: %1 kB ( %d mB)\n").arg( total ), totalMb );
424 usedS.sprintf(tr("Used: %1 kB ( %d mB)\n").arg(used) ,usedMb); 424 usedS.sprintf(tr("Used: %1 kB ( %d mB)\n").arg(used) ,usedMb);
425 avS.sprintf( tr("Available: %1 kB ( %d mB)").arg(avail), availMb ); 425 avS.sprintf( tr("Available: %1 kB ( %d mB)").arg(avail), availMb );
426 } 426 }
427 } 427 }
428 fsType = getFileSystemType((const QString &)selectedText); 428 fsType = getFileSystemType((const QString &)selectedText);
429 429
430 TextLabel5->setText(tr("Type: %1\nFormatted with %2\n%3, %4, %5").arg( nameS).arg( fsType).arg(totalS).arg( usedS).arg( avS )); 430 TextLabel5->setText(tr("Type: %1\nFormatted with %2\n%3, %4, %5").arg( nameS).arg( fsType).arg(totalS).arg( usedS).arg( avS ));
431 TextLabel5->setTextFormat( Qt::RichText ); 431 TextLabel5->setTextFormat( Qt::RichText );
432 // storageComboSelected(0); 432 // storageComboSelected(0);
433} 433}
434 434
435void FormatterApp::cleanUp() 435void FormatterApp::cleanUp()
436{} 436{}
437 437
438 438
439void FormatterApp::editFstab() 439void FormatterApp::editFstab()
440{ 440{
441 QCopEnvelope e("QPE/Application/textedit","setDocument(QString)"); 441 QCopEnvelope e("QPE/Application/textedit","setDocument(QString)");
442 e << (const QString &)"/etc/fstab"; 442 e << (const QString &)"/etc/fstab";
443} 443}
444 444
445void FormatterApp::parsetab(const QString &fileName) 445void FormatterApp::parsetab(const QString &fileName)
446{ 446{
447 447
448 fileSystemTypeList.clear(); 448 fileSystemTypeList.clear();
449 fsList.clear(); 449 fsList.clear();
450 struct mntent *me; 450 struct mntent *me;
451 // if(fileName == "/etc/mtab") { 451 // if(fileName == "/etc/mtab") {
452 FILE *mntfp = setmntent( fileName.latin1(), "r" ); 452 FILE *mntfp = setmntent( fileName.latin1(), "r" );
453 if ( mntfp ) 453 if ( mntfp )
454 { 454 {
455 while ( (me = getmntent( mntfp )) != 0 ) 455 while ( (me = getmntent( mntfp )) != 0 )
456 { 456 {
457 QString deviceName = me->mnt_fsname; 457 QString deviceName = me->mnt_fsname;
458 QString filesystemType = me->mnt_type; 458 QString filesystemType = me->mnt_type;
459 if(deviceName != "none") 459 if(deviceName != "none")
460 { 460 {
461 if( fsList.contains(filesystemType) == 0 461 if( fsList.contains(filesystemType) == 0
462 & filesystemType.find("proc",0,TRUE) == -1 462 & filesystemType.find("proc",0,TRUE) == -1
463 & filesystemType.find("cramfs",0,TRUE) == -1 463 & filesystemType.find("cramfs",0,TRUE) == -1
464 & filesystemType.find("auto",0,TRUE) == -1) 464 & filesystemType.find("auto",0,TRUE) == -1)
465 fsList << filesystemType; 465 fsList << filesystemType;
466 deviceList << deviceName; 466 deviceList << deviceName;
467 qDebug(deviceName+"::"+filesystemType); 467 qDebug(deviceName+"::"+filesystemType);
468 fileSystemTypeList << deviceName+"::"+filesystemType; 468 fileSystemTypeList << deviceName+"::"+filesystemType;
469 } 469 }
470 } 470 }
471 } 471 }
472 endmntent( mntfp ); 472 endmntent( mntfp );
473 // } else if(fileName == "/etc/fstab") { 473 // } else if(fileName == "/etc/fstab") {
474 // QFile f("/etc/fstab"); 474 // QFile f("/etc/fstab");
475 // if ( f.open(IO_ReadOnly) ) { 475 // if ( f.open(IO_ReadOnly) ) {
476 // QTextStream t (&f); 476 // QTextStream t (&f);
477 // QString s; 477 // QString s;
478 // while (! t.eof()) { 478 // while (! t.eof()) {
479 // s=t.readLine(); 479 // s=t.readLine();
480 // s=s.simplifyWhiteSpace(); 480 // s=s.simplifyWhiteSpace();
481 // if ( (!s.isEmpty() ) && (s.find(" ")!=0) ) { 481 // if ( (!s.isEmpty() ) && (s.find(" ")!=0) ) {
482 // // = me->mnt_fsname; 482 // // = me->mnt_fsname;
483 // QString filesystemType = me->mnt_type; 483 // QString filesystemType = me->mnt_type;
484 // QString deviceName = s.left(0,s.find(BLANK) ); 484 // QString deviceName = s.left(0,s.find(BLANK) );
485 // s=s.remove(0,s.find(BLANK)+1 ); // devicename 485 // s=s.remove(0,s.find(BLANK)+1 ); // devicename
486 486
487 // s=s.remove(0,s.find(BLANK)+1 ); // mountpoint 487 // s=s.remove(0,s.find(BLANK)+1 ); // mountpoint
488 // QStringt mountPoint= s.left(0,s.find(BLANK) ); 488 // QStringt mountPoint= s.left(0,s.find(BLANK) );
489 // s=s.remove(0,s.find(BLANK)+1 ); // fs 489 // s=s.remove(0,s.find(BLANK)+1 ); // fs
490 // QString filesystemType= s.left(0,s.find(BLANK) ); 490 // QString filesystemType= s.left(0,s.find(BLANK) );
491 // } 491 // }
492 // } 492 // }
493 // } 493 // }
494 // f.close(); 494 // f.close();
495 // } 495 // }
496} 496}
497 497
498QString FormatterApp::getFileSystemType(const QString &currentText) 498QString FormatterApp::getFileSystemType(const QString &currentText)
499{ 499{
500 500
501 parsetab("/etc/mtab"); //why did TT forget filesystem type? 501 parsetab("/etc/mtab"); //why did TT forget filesystem type?
502 502
503 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it ) 503 for ( QStringList::Iterator it = fileSystemTypeList.begin(); it != fileSystemTypeList.end(); ++it )
504 { 504 {
505 QString temp = (*it); 505 QString temp = (*it);
506 if( temp.find( currentText,0,TRUE) != -1) 506 if( temp.find( currentText,0,TRUE) != -1)
507 { 507 {
508 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2); 508 return temp.right( temp.length() - temp.find("::",0,TRUE) - 2);
509 // qDebug(fsType); 509 // qDebug(fsType);
510 } 510 }
511 } 511 }
512 return ""; 512 return "";
513} 513}
514 514
515bool FormatterApp::doFsck() 515bool FormatterApp::doFsck()
516{ 516{
517 517
518 Output *outDlg; 518 Output *outDlg;
519 QString selectedDevice; 519 QString selectedDevice;
520 // #if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX) 520 // #if defined(QT_QWS_IPAQ) || defined(QT_QWS_SL5XXX)
521 selectedDevice = deviceComboBox->currentText(); 521 selectedDevice = deviceComboBox->currentText();
522 QString mountPoint = mountPointLineEdit->text(); 522 QString mountPoint = mountPointLineEdit->text();
523 QString umountS = "umount -v "+mountPoint+" 2>&1"; 523 QString umountS = "umount -v "+mountPoint+" 2>&1";
524 QString remountS = "mount -v "+mountPoint+" 2>&1"; 524 QString remountS = "mount -v "+mountPoint+" 2>&1";
525 // #else 525 // #else
526 // // for testing 526 // // for testing
527 // // currentText = diskDevice = "/dev/fd0"; 527 // // currentText = diskDevice = "/dev/fd0";
528 // QString umountS = "umount -v /floppy 2>&1"; 528 // QString umountS = "umount -v /floppy 2>&1";
529 // QString remountS = "mount -v /floppy 2>&1"; 529 // QString remountS = "mount -v /floppy 2>&1";
530 // selectedDevice ="/dev/fd0"; 530 // selectedDevice ="/dev/fd0";
531 531
532 // #endif 532 // #endif
533 533
534 QString fsType = getFileSystemType((const QString &)selectedDevice); 534 QString fsType = getFileSystemType((const QString &)selectedDevice);
535 QString cmd; 535 QString cmd;
536 qDebug( selectedDevice +" "+ fsType); 536 qDebug( selectedDevice +" "+ fsType);
537 if(fsType == "vfat") cmd = "dosfsck -vy "; 537 if(fsType == "vfat") cmd = "dosfsck -vy ";
538 if(fsType == "ext2") cmd = "e2fsck -cpvy "; 538 if(fsType == "ext2") cmd = "e2fsck -cpvy ";
539 cmd += selectedDevice + " 2>&1"; 539 cmd += selectedDevice + " 2>&1";
540 540
541 outDlg = new Output(this, tr("Formatter Output"),FALSE); 541 outDlg = new Output(this, tr("Formatter Output"),FALSE);
542 QPEApplication::showDialog( outDlg ); 542 QPEApplication::showDialog( outDlg );
543 qApp->processEvents(); 543 qApp->processEvents();
544 FILE *fp; 544 FILE *fp;
545 char line[130]; 545 char line[130];
546 outDlg->OutputEdit->append( tr("Trying to umount.")); 546 outDlg->OutputEdit->append( tr("Trying to umount."));
547 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 547 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
548 548
549 sleep(1); 549 sleep(1);
550 // qDebug("Command is "+umountS); 550 // qDebug("Command is "+umountS);
551 fp = popen( (const char *) umountS, "r"); 551 fp = popen( (const char *) umountS, "r");
552 // qDebug("%d", fp); 552 // qDebug("%d", fp);
553 if ( !fp ) 553 if ( !fp )
554 { 554 {
555 qDebug("Could not execute '" + umountS + "'!\n" +(QString)strerror(errno)); 555 qDebug("Could not execute '" + umountS + "'!\n" +(QString)strerror(errno));
556 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") ); 556 QMessageBox::warning( this, tr("Formatter"), tr("umount failed!"), tr("&OK") );
557 pclose(fp); 557 pclose(fp);
558 return false; 558 return false;
559 } 559 }
560 else 560 else
561 { 561 {
562 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted.")); 562 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully umounted."));
563 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 563 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
564 while ( fgets( line, sizeof line, fp)) 564 while ( fgets( line, sizeof line, fp))
565 { 565 {
566 if( ((QString)line).find("busy",0,TRUE) != -1) 566 if( ((QString)line).find("busy",0,TRUE) != -1)
567 { 567 {
568 qDebug("Could not find '" + umountS); 568 qDebug("Could not find '" + umountS);
569 QMessageBox::warning( this, tr("Formatter"), 569 QMessageBox::warning( this, tr("Formatter"),
570 tr("Could not umount.\nDevice is busy!"), tr("&OK") ); 570 tr("Could not umount.\nDevice is busy!"), tr("&OK") );
571 pclose(fp); 571 pclose(fp);
572 return false; 572 return false;
573 } 573 }
574 else 574 else
575 { 575 {
576 QString lineStr = line; 576 QString lineStr = line;
577 lineStr=lineStr.left(lineStr.length()-1); 577 lineStr=lineStr.left(lineStr.length()-1);
578 outDlg->OutputEdit->append(lineStr); 578 outDlg->OutputEdit->append(lineStr);
579 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 579 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
580 } 580 }
581 } 581 }
582 } 582 }
583 pclose(fp); 583 pclose(fp);
584 ///////////////////////////////////// 584 /////////////////////////////////////
585 fp = popen( (const char *) cmd, "r"); 585 fp = popen( (const char *) cmd, "r");
586 while ( fgets( line, sizeof line, fp)) 586 while ( fgets( line, sizeof line, fp))
587 { 587 {
588 if( ((QString)line).find("No such device",0,TRUE) != -1) 588 if( ((QString)line).find("No such device",0,TRUE) != -1)
589 { 589 {
590 qDebug("No such device '" + umountS); 590 qDebug("No such device '" + umountS);
591 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") ); 591 QMessageBox::warning( this, tr("Formatter"), tr("No such device!"), tr("&OK") );
592 pclose(fp); 592 pclose(fp);
593 // outDlg->OutputEdit->append("No such device"); 593 // outDlg->OutputEdit->append("No such device");
594 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 594 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
595 return false; 595 return false;
596 } 596 }
597 else 597 else
598 { 598 {
599 QString lineStr = line; 599 QString lineStr = line;
600 lineStr=lineStr.left(lineStr.length()-1); 600 lineStr=lineStr.left(lineStr.length()-1);
601 outDlg->OutputEdit->append(lineStr); 601 outDlg->OutputEdit->append(lineStr);
602 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 602 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
603 } 603 }
604 } 604 }
605 outDlg->OutputEdit->append(tr("You can now close the output window.")); 605 outDlg->OutputEdit->append(tr("You can now close the output window."));
606 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 606 outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
607 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted.")); 607 // outDlg->OutputEdit->append( currentText + tr("\nhas been successfully formatted."));
608 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); 608 // outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE);
609 pclose(fp); 609 pclose(fp);
610 610
611 ///////////////////////////////////////// 611 /////////////////////////////////////////
612 612
613 return true; 613 return true;
614} 614}
615 615
616bool FormatterApp::doFsckCheck() 616bool FormatterApp::doFsckCheck()
617{ 617{
618 618
619 return FALSE; 619 return FALSE;
620} 620}
621 621
622int FormatterApp::formatCheck(const QString &) 622int FormatterApp::formatCheck(const QString &)
623{ 623{
624 624
625 return -1; 625 return -1;
626} 626}
627 627
628int FormatterApp::runCommand(const QString &) 628int FormatterApp::runCommand(const QString &)
629{ 629{
630 630
631 return -1; 631 return -1;
632} 632}
diff --git a/noncore/tools/remote/buttondialog.cpp b/noncore/tools/remote/buttondialog.cpp
index 6ea4801..580f101 100644
--- a/noncore/tools/remote/buttondialog.cpp
+++ b/noncore/tools/remote/buttondialog.cpp
@@ -1,293 +1,293 @@
1/* 1/*
2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie. 2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie.
3Copyright (C) 2002 Thomas Stephens 3Copyright (C) 2002 Thomas Stephens
4 4
5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public 5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later 6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
7version. 7version.
8 8
9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the 9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11Public License for more details. 11Public License for more details.
12 12
13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free 13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15*/ 15*/
16 16
17#include "buttondialog.h" 17#include "buttondialog.h"
18 18
19ButtonDialog::ButtonDialog(QString buttonName, QWidget *parent, const char*name, bool modal, WFlags f):QDialog(parent, name, modal, f) 19ButtonDialog::ButtonDialog(QString buttonName, QWidget *parent, const char*name, bool modal, WFlags f):QDialog(parent, name, modal, f)
20{ 20{
21 setCaption(tr(buttonName)); 21 setCaption(tr(buttonName));
22 22
23 QVBoxLayout *layout = new QVBoxLayout(this); 23 QVBoxLayout *layout = new QVBoxLayout(this);
24 24
25 QHBoxLayout *hlayout1 = new QHBoxLayout(this); 25 QHBoxLayout *hlayout1 = new QHBoxLayout(this);
26 QHBoxLayout *hlayout2 = new QHBoxLayout(this); 26 QHBoxLayout *hlayout2 = new QHBoxLayout(this);
27 QHBoxLayout *hlayout3 = new QHBoxLayout(this); 27 QHBoxLayout *hlayout3 = new QHBoxLayout(this);
28 28
29 layout->addSpacing(5); 29 layout->addSpacing(5);
30 layout->addLayout(hlayout1); 30 layout->addLayout(hlayout1);
31 layout->addSpacing(5); 31 layout->addSpacing(5);
32 layout->addLayout(hlayout2); 32 layout->addLayout(hlayout2);
33 layout->addSpacing(5); 33 layout->addSpacing(5);
34 layout->addLayout(hlayout3); 34 layout->addLayout(hlayout3);
35 layout->addSpacing(5); 35 layout->addSpacing(5);
36 36
37 remote = new QComboBox(false, this, "remote"); 37 remote = new QComboBox(false, this, "remote");
38 QLabel *remoteLabel = new QLabel(remote, "Remote: ", this, "remoteLabel"); 38 QLabel *remoteLabel = new QLabel(remote, "Remote: ", this, "remoteLabel");
39 hlayout1->addSpacing(5); 39 hlayout1->addSpacing(5);
40 hlayout1->addWidget(remoteLabel); 40 hlayout1->addWidget(remoteLabel);
41 hlayout1->addSpacing(5); 41 hlayout1->addSpacing(5);
42 hlayout1->addWidget(remote); 42 hlayout1->addWidget(remote);
43 hlayout1->addSpacing(5); 43 hlayout1->addSpacing(5);
44 remote->insertItem("Remote "); 44 remote->insertItem("Remote ");
45 remote->insertStringList(getRemotes()); 45 remote->insertStringList(getRemotes());
46 connect(remote, SIGNAL(activated(const QString &)), this, SLOT(remoteSelected(const QString&)) ); 46 connect(remote, SIGNAL(activated(const QString&)), this, SLOT(remoteSelected(const QString&)) );
47 47
48 button = new QComboBox(false, this, "button"); 48 button = new QComboBox(false, this, "button");
49 QLabel *buttonLabel = new QLabel(remote, "Button: ", this, "buttonLabel"); 49 QLabel *buttonLabel = new QLabel(remote, "Button: ", this, "buttonLabel");
50 hlayout2->addSpacing(5); 50 hlayout2->addSpacing(5);
51 hlayout2->addWidget(buttonLabel); 51 hlayout2->addWidget(buttonLabel);
52 hlayout2->addSpacing(5); 52 hlayout2->addSpacing(5);
53 hlayout2->addWidget(button); 53 hlayout2->addWidget(button);
54 hlayout2->addSpacing(5); 54 hlayout2->addSpacing(5);
55 button->insertItem("Button "); 55 button->insertItem("Button ");
56 connect(button, SIGNAL(activated(const QString &)), this, SLOT(buttonSelected(const QString&)) ); 56 connect(button, SIGNAL(activated(const QString&)), this, SLOT(buttonSelected(const QString&)) );
57 57
58 label = new QLineEdit(this, "label"); 58 label = new QLineEdit(this, "label");
59 label->setText(buttonName); 59 label->setText(buttonName);
60 QLabel *labelLabel = new QLabel(label, "Label: ", this, "labelLabel"); 60 QLabel *labelLabel = new QLabel(label, "Label: ", this, "labelLabel");
61 hlayout3->addSpacing(5); 61 hlayout3->addSpacing(5);
62 hlayout3->addWidget(labelLabel); 62 hlayout3->addWidget(labelLabel);
63 hlayout3->addSpacing(5); 63 hlayout3->addSpacing(5);
64 hlayout3->addWidget(label); 64 hlayout3->addWidget(label);
65 hlayout3->addSpacing(5); 65 hlayout3->addSpacing(5);
66} 66}
67 67
68void ButtonDialog::remoteSelected(const QString &string) 68void ButtonDialog::remoteSelected(const QString &string)
69{ 69{
70 button->insertStringList(getButtons(string.latin1()) ); 70 button->insertStringList(getButtons(string.latin1()) );
71 list="SEND_ONCE"; 71 list="SEND_ONCE";
72 list+=string; 72 list+=string;
73} 73}
74 74
75void ButtonDialog::buttonSelected(const QString &string) 75void ButtonDialog::buttonSelected(const QString &string)
76{ 76{
77 list+=string; 77 list+=string;
78} 78}
79 79
80QStringList ButtonDialog::getList() 80QStringList ButtonDialog::getList()
81{ 81{
82 return list; 82 return list;
83} 83}
84 84
85QString ButtonDialog::getLabel() 85QString ButtonDialog::getLabel()
86{ 86{
87 return label->text(); 87 return label->text();
88} 88}
89 89
90QStringList ButtonDialog::getRemotes() 90QStringList ButtonDialog::getRemotes()
91{ 91{
92 const char write_buffer[] = "LIST\n"; 92 const char write_buffer[] = "LIST\n";
93 const char *readbuffer; 93 const char *readbuffer;
94 int i, numlines; 94 int i, numlines;
95 QStringList list; 95 QStringList list;
96 96
97 addr.sun_family=AF_UNIX; 97 addr.sun_family=AF_UNIX;
98 strcpy(addr.sun_path,"/dev/lircd"); 98 strcpy(addr.sun_path,"/dev/lircd");
99 99
100 fd = socket(AF_UNIX, SOCK_STREAM, 0); 100 fd = socket(AF_UNIX, SOCK_STREAM, 0);
101 if(fd == -1) 101 if(fd == -1)
102 { 102 {
103 QMessageBox *mb = new QMessageBox("Error!", 103 QMessageBox *mb = new QMessageBox("Error!",
104 "couldnt connect to socket", 104 "couldnt connect to socket",
105 QMessageBox::NoIcon, 105 QMessageBox::NoIcon,
106 QMessageBox::Ok, 106 QMessageBox::Ok,
107 QMessageBox::NoButton, 107 QMessageBox::NoButton,
108 QMessageBox::NoButton); 108 QMessageBox::NoButton);
109 mb->exec(); 109 mb->exec();
110 perror("ButtonDialog::GetRemotes"); 110 perror("ButtonDialog::GetRemotes");
111 return NULL; 111 return NULL;
112 } 112 }
113 113
114 if(::connect(fd,(struct sockaddr *) &addr, sizeof(addr) ) == -1) 114 if(::connect(fd,(struct sockaddr *) &addr, sizeof(addr) ) == -1)
115 { 115 {
116 QMessageBox *mb = new QMessageBox("Error!", 116 QMessageBox *mb = new QMessageBox("Error!",
117 "couldnt connect to socket", 117 "couldnt connect to socket",
118 QMessageBox::NoIcon, 118 QMessageBox::NoIcon,
119 QMessageBox::Ok, 119 QMessageBox::Ok,
120 QMessageBox::NoButton, 120 QMessageBox::NoButton,
121 QMessageBox::NoButton); 121 QMessageBox::NoButton);
122 mb->exec(); 122 mb->exec();
123 perror("ButtonDialog::GetRemotes"); 123 perror("ButtonDialog::GetRemotes");
124 return NULL; 124 return NULL;
125 } 125 }
126 126
127 write(fd, write_buffer, strlen(write_buffer)); 127 write(fd, write_buffer, strlen(write_buffer));
128 128
129 for(i=0; i<5; i++) 129 for(i=0; i<5; i++)
130 { 130 {
131 printf("%d\n", i); 131 printf("%d\n", i);
132 readbuffer = readPacket(); 132 readbuffer = readPacket();
133 printf("%s", readbuffer); 133 printf("%s", readbuffer);
134 printf("%d\n", i); 134 printf("%d\n", i);
135 } 135 }
136 136
137 numlines = atoi(readbuffer); 137 numlines = atoi(readbuffer);
138 138
139 for(i=0; i<numlines; i++) 139 for(i=0; i<numlines; i++)
140 { 140 {
141 list+=readPacket(); 141 list+=readPacket();
142 } 142 }
143 143
144 if(strcasecmp(readPacket(), "END") != 0) 144 if(strcasecmp(readPacket(), "END") != 0)
145 { 145 {
146 QMessageBox *mb = new QMessageBox("Error!", 146 QMessageBox *mb = new QMessageBox("Error!",
147 "bad packet", 147 "bad packet",
148 QMessageBox::NoIcon, 148 QMessageBox::NoIcon,
149 QMessageBox::Ok, 149 QMessageBox::Ok,
150 QMessageBox::NoButton, 150 QMessageBox::NoButton,
151 QMessageBox::NoButton); 151 QMessageBox::NoButton);
152 mb->exec(); 152 mb->exec();
153 perror("ButtonDialog::GetRemotes"); 153 perror("ButtonDialog::GetRemotes");
154 return NULL; 154 return NULL;
155 } 155 }
156 156
157 ::close(fd); 157 ::close(fd);
158 return list; 158 return list;
159} 159}
160 160
161QStringList ButtonDialog::getButtons(const char *remoteName) 161QStringList ButtonDialog::getButtons(const char *remoteName)
162{ 162{
163 QString write_buffer = "LIST "; 163 QString write_buffer = "LIST ";
164 const char *readbuffer; 164 const char *readbuffer;
165 int i, j, numlines; 165 int i, j, numlines;
166 QStringList list; 166 QStringList list;
167 QString string; 167 QString string;
168 168
169 write_buffer += remoteName; 169 write_buffer += remoteName;
170 write_buffer += '\n'; 170 write_buffer += '\n';
171 171
172 fd = socket(AF_UNIX, SOCK_STREAM, 0); 172 fd = socket(AF_UNIX, SOCK_STREAM, 0);
173 if(fd == -1) 173 if(fd == -1)
174 { 174 {
175 QMessageBox *mb = new QMessageBox("Error!", 175 QMessageBox *mb = new QMessageBox("Error!",
176 "couldnt connect to socket", 176 "couldnt connect to socket",
177 QMessageBox::NoIcon, 177 QMessageBox::NoIcon,
178 QMessageBox::Ok, 178 QMessageBox::Ok,
179 QMessageBox::NoButton, 179 QMessageBox::NoButton,
180 QMessageBox::NoButton); 180 QMessageBox::NoButton);
181 mb->exec(); 181 mb->exec();
182 perror("ButtonDialog::GetButtons"); 182 perror("ButtonDialog::GetButtons");
183 return NULL; 183 return NULL;
184 } 184 }
185 185
186 186
187 if(::connect(fd,(struct sockaddr *) &addr, sizeof(addr) ) == -1) 187 if(::connect(fd,(struct sockaddr *) &addr, sizeof(addr) ) == -1)
188 { 188 {
189 QMessageBox *mb = new QMessageBox("Error!", 189 QMessageBox *mb = new QMessageBox("Error!",
190 "couldnt connect to socket", 190 "couldnt connect to socket",
191 QMessageBox::NoIcon, 191 QMessageBox::NoIcon,
192 QMessageBox::Ok, 192 QMessageBox::Ok,
193 QMessageBox::NoButton, 193 QMessageBox::NoButton,
194 QMessageBox::NoButton); 194 QMessageBox::NoButton);
195 mb->exec(); 195 mb->exec();
196 perror("ButtonDialog::GetButtons"); 196 perror("ButtonDialog::GetButtons");
197 return NULL; 197 return NULL;
198 } 198 }
199 199
200 write(fd, write_buffer.latin1(), strlen(write_buffer) ); 200 write(fd, write_buffer.latin1(), strlen(write_buffer) );
201 201
202 for(i=0; i<5; i++) 202 for(i=0; i<5; i++)
203 { 203 {
204 readbuffer = readPacket(); 204 readbuffer = readPacket();
205 } 205 }
206 206
207 numlines = atoi(readbuffer); 207 numlines = atoi(readbuffer);
208 208
209 for(i=0; i<numlines; i++) 209 for(i=0; i<numlines; i++)
210 { 210 {
211 list+=readPacket(); 211 list+=readPacket();
212 for(j=0; j<list[i].length(); j++) 212 for(j=0; j<list[i].length(); j++)
213 { 213 {
214 if(list[i][j] == ' ') 214 if(list[i][j] == ' ')
215 break; 215 break;
216 } 216 }
217 list[i].remove(0, j+1); 217 list[i].remove(0, j+1);
218 } 218 }
219 219
220 if(strcasecmp(readPacket(), "END") != 0) 220 if(strcasecmp(readPacket(), "END") != 0)
221 { 221 {
222 QMessageBox *mb = new QMessageBox("Error!", 222 QMessageBox *mb = new QMessageBox("Error!",
223 "bad packet", 223 "bad packet",
224 QMessageBox::NoIcon, 224 QMessageBox::NoIcon,
225 QMessageBox::Ok, 225 QMessageBox::Ok,
226 QMessageBox::NoButton, 226 QMessageBox::NoButton,
227 QMessageBox::NoButton); 227 QMessageBox::NoButton);
228 mb->exec(); 228 mb->exec();
229 perror("ButtonDialog::GetButtons"); 229 perror("ButtonDialog::GetButtons");
230 return NULL; 230 return NULL;
231 } 231 }
232 232
233 ::close(fd); 233 ::close(fd);
234 return list; 234 return list;
235} 235}
236 236
237 237
238//this function was ripped for rc.c in xrc, it is available here: http://www.lirc.org/software.html 238//this function was ripped for rc.c in xrc, it is available here: http://www.lirc.org/software.html
239const char *ButtonDialog::readPacket() 239const char *ButtonDialog::readPacket()
240{ 240{
241 static char buffer[PACKET_SIZE+1]=""; 241 static char buffer[PACKET_SIZE+1]="";
242 char *end; 242 char *end;
243 static int ptr=0,end_len=0; 243 static int ptr=0,end_len=0;
244 ssize_t ret; 244 ssize_t ret;
245 timeout = 0; 245 timeout = 0;
246 246
247 if(ptr>0) 247 if(ptr>0)
248 { 248 {
249 memmove(buffer,buffer+ptr,strlen(buffer+ptr)+1); 249 memmove(buffer,buffer+ptr,strlen(buffer+ptr)+1);
250 ptr=strlen(buffer); 250 ptr=strlen(buffer);
251 end=strchr(buffer,'\n'); 251 end=strchr(buffer,'\n');
252 } 252 }
253 else 253 else
254 { 254 {
255 end=NULL; 255 end=NULL;
256 } 256 }
257 alarm(TIMEOUT); 257 alarm(TIMEOUT);
258 while(end==NULL) 258 while(end==NULL)
259 { 259 {
260 if(PACKET_SIZE<=ptr) 260 if(PACKET_SIZE<=ptr)
261 { 261 {
262 fprintf(stderr,"bad packet\n"); 262 fprintf(stderr,"bad packet\n");
263 ptr=0; 263 ptr=0;
264 return(NULL); 264 return(NULL);
265 } 265 }
266 ret=read(fd,buffer+ptr,PACKET_SIZE-ptr); 266 ret=read(fd,buffer+ptr,PACKET_SIZE-ptr);
267 267
268 if(ret<=0 || timeout) 268 if(ret<=0 || timeout)
269 { 269 {
270 if(timeout) 270 if(timeout)
271 { 271 {
272 fprintf(stderr,"timeout\n"); 272 fprintf(stderr,"timeout\n");
273 } 273 }
274 else 274 else
275 { 275 {
276 alarm(0); 276 alarm(0);
277 } 277 }
278 ptr=0; 278 ptr=0;
279 return(NULL); 279 return(NULL);
280 } 280 }
281 buffer[ptr+ret]=0; 281 buffer[ptr+ret]=0;
282 ptr=strlen(buffer); 282 ptr=strlen(buffer);
283 end=strchr(buffer,'\n'); 283 end=strchr(buffer,'\n');
284 } 284 }
285 alarm(0);timeout=0; 285 alarm(0);timeout=0;
286 286
287 end[0]=0; 287 end[0]=0;
288 ptr=strlen(buffer)+1; 288 ptr=strlen(buffer)+1;
289//# ifdef DEBUG 289//# ifdef DEBUG
290 //printf("buffer: -%s-\n",buffer); 290 //printf("buffer: -%s-\n",buffer);
291//# endif 291//# endif
292 return(buffer); 292 return(buffer);
293} 293}
diff --git a/noncore/tools/remote/recorddialog.cpp b/noncore/tools/remote/recorddialog.cpp
index cfab730..1ce5472 100644
--- a/noncore/tools/remote/recorddialog.cpp
+++ b/noncore/tools/remote/recorddialog.cpp
@@ -1,82 +1,82 @@
1/* 1/*
2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie. 2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie.
3Copyright (C) 2002 Thomas Stephens 3Copyright (C) 2002 Thomas Stephens
4 4
5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public 5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later 6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
7version. 7version.
8 8
9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the 9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11Public License for more details. 11Public License for more details.
12 12
13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free 13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15*/ 15*/
16 16
17#include "recorddialog.h" 17#include "recorddialog.h"
18 18
19RecordDialog::RecordDialog(QWidget *parent, const char *name) 19RecordDialog::RecordDialog(QWidget *parent, const char *name)
20 :QDialog(parent, name) 20 :QDialog(parent, name)
21{ 21{
22 QVBoxLayout *layout = new QVBoxLayout(this); 22 QVBoxLayout *layout = new QVBoxLayout(this);
23 QHBoxLayout *hlayout = new QHBoxLayout(this); 23 QHBoxLayout *hlayout = new QHBoxLayout(this);
24 24
25 layout->insertSpacing(0,5); 25 layout->insertSpacing(0,5);
26 output = new QTextView("Please enter the name of the new remote, and press Return\n", 0, this, "output"); 26 output = new QTextView("Please enter the name of the new remote, and press Return\n", 0, this, "output");
27 layout->insertWidget(-1, output); 27 layout->insertWidget(-1, output);
28 layout->insertSpacing(-1, 5); 28 layout->insertSpacing(-1, 5);
29 layout->insertLayout(-1, hlayout); 29 layout->insertLayout(-1, hlayout);
30 layout->insertSpacing(-1, 5); 30 layout->insertSpacing(-1, 5);
31 31
32 hlayout->insertSpacing(0, 5); 32 hlayout->insertSpacing(0, 5);
33 input = new QLineEdit(this, "input"); 33 input = new QLineEdit(this, "input");
34 hlayout->insertWidget(-1, input, 1); 34 hlayout->insertWidget(-1, input, 1);
35 hlayout->insertSpacing(-1, 5); 35 hlayout->insertSpacing(-1, 5);
36 36
37 QPushButton *ret = new QPushButton("Return", this, "return"); 37 QPushButton *ret = new QPushButton("Return", this, "return");
38 hlayout->insertWidget(-1, ret); 38 hlayout->insertWidget(-1, ret);
39 hlayout->insertSpacing(-1, 5); 39 hlayout->insertSpacing(-1, 5);
40 connect(ret, SIGNAL(clicked()), this, SLOT(retPressed()) ); 40 connect(ret, SIGNAL(clicked()), this, SLOT(retPressed()) );
41 where = 0; 41 where = 0;
42 42
43 record = new OProcess; 43 record = new OProcess;
44} 44}
45 45
46void RecordDialog::retPressed() 46void RecordDialog::retPressed()
47{ 47{
48 printf("RecordDialog::retPressed: ret pressed\n"); 48 printf("RecordDialog::retPressed: ret pressed\n");
49 49
50 if(where == 0) 50 if(where == 0)
51 { 51 {
52 connect(record, SIGNAL(receivedStdout(OProcess *, char *, int)), this, SLOT(incoming(OProcess *, char *, int)) ); 52 connect(record, SIGNAL(receivedStdout(OProcess*,char*,int)), this, SLOT(incoming(OProcess*,char*,int)) );
53 connect(record, SIGNAL(receivedStderr(OProcess *, char *, int)), this, SLOT(incoming(OProcess *, char *, int)) ); 53 connect(record, SIGNAL(receivedStderr(OProcess*,char*,int)), this, SLOT(incoming(OProcess*,char*,int)) );
54 connect(record, SIGNAL(processExited(OProcess *)), this, SLOT(done(OProcess *)) ); 54 connect(record, SIGNAL(processExited(OProcess*)), this, SLOT(done(OProcess*)) );
55 printf("RecordDialog::retPressed: starting irrecord\n"); 55 printf("RecordDialog::retPressed: starting irrecord\n");
56 QString file = "/tmp/" + input->text(); 56 QString file = "/tmp/" + input->text();
57 *record<<"irrecord"<<file.latin1(); 57 *record<<"irrecord"<<file.latin1();
58 if(!record->start(OProcess::NotifyOnExit, OProcess::AllOutput)) 58 if(!record->start(OProcess::NotifyOnExit, OProcess::AllOutput))
59 { 59 {
60 QMessageBox *mb = new QMessageBox("Error!", 60 QMessageBox *mb = new QMessageBox("Error!",
61 "Could not start irrecord. You must<br>use an lirc ipkg that includes<br>irrecord", 61 "Could not start irrecord. You must<br>use an lirc ipkg that includes<br>irrecord",
62 QMessageBox::NoIcon, 62 QMessageBox::NoIcon,
63 QMessageBox::Ok, 63 QMessageBox::Ok,
64 QMessageBox::NoButton, 64 QMessageBox::NoButton,
65 QMessageBox::NoButton); 65 QMessageBox::NoButton);
66 mb->exec(); 66 mb->exec();
67 return; 67 return;
68 } 68 }
69 // record->resume(); 69 // record->resume();
70 where = 1; 70 where = 1;
71 } 71 }
72} 72}
73 73
74void RecordDialog::incoming(OProcess *proc, char *buffer, int len) 74void RecordDialog::incoming(OProcess *proc, char *buffer, int len)
75{ 75{
76 //output->setText(output->text() + QString(buffer).truncate(len-1)); 76 //output->setText(output->text() + QString(buffer).truncate(len-1));
77 printf("RecordDialog::incoming: got text from irrecord\n"); 77 printf("RecordDialog::incoming: got text from irrecord\n");
78} 78}
79 79
80void RecordDialog::done(OProcess *proc) 80void RecordDialog::done(OProcess *proc)
81{ 81{
82} 82}
diff --git a/noncore/tools/remote/topgroup.cpp b/noncore/tools/remote/topgroup.cpp
index 93cffbb..427cb8f 100644
--- a/noncore/tools/remote/topgroup.cpp
+++ b/noncore/tools/remote/topgroup.cpp
@@ -1,54 +1,54 @@
1/* 1/*
2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie. 2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie.
3Copyright (C) 2002 Thomas Stephens 3Copyright (C) 2002 Thomas Stephens
4 4
5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public 5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later 6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
7version. 7version.
8 8
9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the 9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11Public License for more details. 11Public License for more details.
12 12
13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free 13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15*/ 15*/
16 16
17#include "topgroup.h" 17#include "topgroup.h"
18 18
19TopGroup::TopGroup(QWidget *parent, const char *name):QWidget(parent,name) 19TopGroup::TopGroup(QWidget *parent, const char *name):QWidget(parent,name)
20{ 20{
21 QHBoxLayout *layout = new QHBoxLayout(this, 0, -1, 0); 21 QHBoxLayout *layout = new QHBoxLayout(this, 0, -1, 0);
22 22
23 QPushButton *power = new QPushButton("Power",this,"power"); 23 QPushButton *power = new QPushButton("Power",this,"power");
24 layout->addWidget(power); 24 layout->addWidget(power);
25 connect(power, SIGNAL(pressed()), this->parentWidget(), SLOT(sendIR()) ); 25 connect(power, SIGNAL(pressed()), this->parentWidget(), SLOT(sendIR()) );
26 //power->setGeometry(5, 5,40, 20); 26 //power->setGeometry(5, 5,40, 20);
27 27
28 layout->addSpacing(5); 28 layout->addSpacing(5);
29 29
30 QPushButton *source = new QPushButton("Source",this,"source"); 30 QPushButton *source = new QPushButton("Source",this,"source");
31 layout->addWidget(source); 31 layout->addWidget(source);
32 connect(source, SIGNAL(pressed()), this->parentWidget(), SLOT(sendIR()) ); 32 connect(source, SIGNAL(pressed()), this->parentWidget(), SLOT(sendIR()) );
33 //source->setGeometry(50,5,40,20); 33 //source->setGeometry(50,5,40,20);
34 34
35 remotes = new QComboBox(false, this, "remotes"); 35 remotes = new QComboBox(false, this, "remotes");
36 connect(remotes, SIGNAL(activated(const QString &)), this->parentWidget(), SLOT(remoteSelected(const QString &)) ); 36 connect(remotes, SIGNAL(activated(const QString&)), this->parentWidget(), SLOT(remoteSelected(const QString&)) );
37 remotes->insertItem("Select Remote"); 37 remotes->insertItem("Select Remote");
38 //remotes->setGeometry(135,5,95,20); 38 //remotes->setGeometry(135,5,95,20);
39 39
40 QLabel *remoteLabel = new QLabel(remotes, "Remote: ",this,"remoteLabel"); 40 QLabel *remoteLabel = new QLabel(remotes, "Remote: ",this,"remoteLabel");
41 //remoteLabel->setGeometry(90,5,40,20); 41 //remoteLabel->setGeometry(90,5,40,20);
42 remoteLabel->setAlignment(AlignRight | AlignVCenter); 42 remoteLabel->setAlignment(AlignRight | AlignVCenter);
43 43
44 layout->addWidget(remoteLabel); 44 layout->addWidget(remoteLabel);
45 layout->addWidget(remotes); 45 layout->addWidget(remotes);
46} 46}
47 47
48void TopGroup::updateRemotes(Config *cfg) 48void TopGroup::updateRemotes(Config *cfg)
49{ 49{
50 remotes->clear(); 50 remotes->clear();
51 remotes->insertItem(QString("SelectRemote")); 51 remotes->insertItem(QString("SelectRemote"));
52 cfg->setGroup("Remotes"); 52 cfg->setGroup("Remotes");
53 remotes->insertStringList(cfg->readListEntry("remoteList", ',') ); 53 remotes->insertStringList(cfg->readListEntry("remoteList", ',') );
54} 54}
diff --git a/noncore/tools/remote/topgroupconf.cpp b/noncore/tools/remote/topgroupconf.cpp
index d763a3a..0419a65 100644
--- a/noncore/tools/remote/topgroupconf.cpp
+++ b/noncore/tools/remote/topgroupconf.cpp
@@ -1,70 +1,70 @@
1/* 1/*
2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie. 2Opie-Remote. emulates remote controlls on an iPaq (and maybe a Zaurus) in Opie.
3Copyright (C) 2002 Thomas Stephens 3Copyright (C) 2002 Thomas Stephens
4 4
5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public 5This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later 6License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
7version. 7version.
8 8
9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the 9This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 10implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11Public License for more details. 11Public License for more details.
12 12
13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free 13You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 14Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15*/ 15*/
16 16
17#include "topgroupconf.h" 17#include "topgroupconf.h"
18 18
19TopGroupConf::TopGroupConf(QWidget *parent, const char *name):QWidget(parent,name) 19TopGroupConf::TopGroupConf(QWidget *parent, const char *name):QWidget(parent,name)
20{ 20{
21 QHBoxLayout *layout = new QHBoxLayout(this); 21 QHBoxLayout *layout = new QHBoxLayout(this);
22 22
23 QPushButton *power = new QPushButton("Power",this,"power"); 23 QPushButton *power = new QPushButton("Power",this,"power");
24 layout->addWidget(power); 24 layout->addWidget(power);
25 connect(power, SIGNAL(pressed()), this->parentWidget(), SLOT(buttonPressed()) ); 25 connect(power, SIGNAL(pressed()), this->parentWidget(), SLOT(buttonPressed()) );
26 //power->setGeometry(5, 5,40, 20); 26 //power->setGeometry(5, 5,40, 20);
27 27
28 layout->addSpacing(5); 28 layout->addSpacing(5);
29 29
30 QPushButton *source = new QPushButton("Source",this,"source"); 30 QPushButton *source = new QPushButton("Source",this,"source");
31 layout->addWidget(source); 31 layout->addWidget(source);
32 connect(source, SIGNAL(pressed()), this->parentWidget(), SLOT(buttonPressed()) ); 32 connect(source, SIGNAL(pressed()), this->parentWidget(), SLOT(buttonPressed()) );
33 //source->setGeometry(50,5,40,20); 33 //source->setGeometry(50,5,40,20);
34 34
35 remotes = new QComboBox(true, this, "remotes"); 35 remotes = new QComboBox(true, this, "remotes");
36 remotes->insertItem(QString("Remotes")); 36 remotes->insertItem(QString("Remotes"));
37 layout->addWidget(remotes); 37 layout->addWidget(remotes);
38 layout->setStretchFactor(remotes, 1); 38 layout->setStretchFactor(remotes, 1);
39 connect(remotes, SIGNAL(activated(const QString &)), this->parentWidget(), SLOT(remoteSelected(const QString &)) ); 39 connect(remotes, SIGNAL(activated(const QString&)), this->parentWidget(), SLOT(remoteSelected(const QString&)) );
40 40
41 41
42 QPushButton *newrem = new QPushButton("New", this, "new"); 42 QPushButton *newrem = new QPushButton("New", this, "new");
43 layout->addWidget(newrem); 43 layout->addWidget(newrem);
44 connect(newrem, SIGNAL(pressed()), this->parentWidget(), SLOT(newPressed()) ); 44 connect(newrem, SIGNAL(pressed()), this->parentWidget(), SLOT(newPressed()) );
45 45
46 46
47 /*remotes = new QComboBox(false, this, "remotes"); 47 /*remotes = new QComboBox(false, this, "remotes");
48 connect(remotes, SIGNAL(activated(const QString &)), this->parentWidget(), SLOT(remoteSelected(const QString &)) ); 48 connect(remotes, SIGNAL(activated(const QString&)), this->parentWidget(), SLOT(remoteSelected(const QString&)) );
49 remotes->insertItem("Select Remote"); 49 remotes->insertItem("Select Remote");
50 //remotes->setGeometry(135,5,95,20); 50 //remotes->setGeometry(135,5,95,20);
51 51
52 QLabel *remoteLabel = new QLabel(remotes, "Remote: ",this,"remoteLabel"); 52 QLabel *remoteLabel = new QLabel(remotes, "Remote: ",this,"remoteLabel");
53 //remoteLabel->setGeometry(90,5,40,20); 53 //remoteLabel->setGeometry(90,5,40,20);
54 remoteLabel->setAlignment(AlignRight | AlignVCenter); 54 remoteLabel->setAlignment(AlignRight | AlignVCenter);
55 55
56 layout->addWidget(remoteLabel); 56 layout->addWidget(remoteLabel);
57 layout->addWidget(remotes); 57 layout->addWidget(remotes);
58*/ 58*/
59} 59}
60 60
61void TopGroupConf::updateRemotes(QStringList list) 61void TopGroupConf::updateRemotes(QStringList list)
62{ 62{
63 remotes->insertStringList(list); 63 remotes->insertStringList(list);
64} 64}
65 65
66QString TopGroupConf::getRemotesText() 66QString TopGroupConf::getRemotesText()
67{ 67{
68 return remotes->currentText(); 68 return remotes->currentText();
69} 69}
70 70
diff --git a/noncore/unsupported/filebrowser/filebrowser.cpp b/noncore/unsupported/filebrowser/filebrowser.cpp
index 8cf8a60..92a688a 100644
--- a/noncore/unsupported/filebrowser/filebrowser.cpp
+++ b/noncore/unsupported/filebrowser/filebrowser.cpp
@@ -1,1091 +1,1091 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000 Trolltech AS. All rights reserved. 2** Copyright (C) 2000 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qtopia Environment. 4** This file is part of Qtopia Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20 20
21 21
22#include "inlineedit.h" 22#include "inlineedit.h"
23#include "filebrowser.h" 23#include "filebrowser.h"
24#include "filePermissions.h" 24#include "filePermissions.h"
25#include <qpe/resource.h> 25#include <qpe/resource.h>
26#include <qpe/global.h> 26#include <qpe/global.h>
27#include <qpe/mimetype.h> 27#include <qpe/mimetype.h>
28#include <qpe/applnk.h> 28#include <qpe/applnk.h>
29#include <qpe/config.h> 29#include <qpe/config.h>
30 30
31#include <qcopchannel_qws.h> 31#include <qcopchannel_qws.h>
32#include <qpe/qcopenvelope_qws.h> 32#include <qpe/qcopenvelope_qws.h>
33 33
34#include <qmessagebox.h> 34#include <qmessagebox.h>
35#include <qdir.h> 35#include <qdir.h>
36#include <qregexp.h> 36#include <qregexp.h>
37#include <qheader.h> 37#include <qheader.h>
38#include <qtoolbar.h> 38#include <qtoolbar.h>
39#include <qpopupmenu.h> 39#include <qpopupmenu.h>
40#include <qmenubar.h> 40#include <qmenubar.h>
41#include <qaction.h> 41#include <qaction.h>
42#include <qstringlist.h> 42#include <qstringlist.h>
43#include <qcursor.h> 43#include <qcursor.h>
44#include <qmultilineedit.h> 44#include <qmultilineedit.h>
45#include <qfont.h> 45#include <qfont.h>
46#include <qpainter.h> 46#include <qpainter.h>
47#include <qprogressbar.h> 47#include <qprogressbar.h>
48 48
49#include <unistd.h> 49#include <unistd.h>
50#include <stdlib.h> 50#include <stdlib.h>
51#include <sys/stat.h> 51#include <sys/stat.h>
52#include <qpe/qpeapplication.h> 52#include <qpe/qpeapplication.h>
53 53
54// 54//
55// FileItem 55// FileItem
56// 56//
57FileItem::FileItem( QListView * parent, const QFileInfo & fi ) 57FileItem::FileItem( QListView * parent, const QFileInfo & fi )
58 : QListViewItem( parent ), 58 : QListViewItem( parent ),
59 fileInfo( fi ) 59 fileInfo( fi )
60{ 60{
61 QDate d = fi.lastModified().date(); 61 QDate d = fi.lastModified().date();
62 62
63 setText( 0, fi.fileName() ); 63 setText( 0, fi.fileName() );
64 setText( 1, sizeString( fi.size() ) + " " ); 64 setText( 1, sizeString( fi.size() ) + " " );
65 setText( 2, QString().sprintf("%4d-%02d-%02d",d.year(), d.month(), d.day() ) ); 65 setText( 2, QString().sprintf("%4d-%02d-%02d",d.year(), d.month(), d.day() ) );
66 66
67 MimeType mt(fi.filePath()); 67 MimeType mt(fi.filePath());
68 68
69 if ( fi.isSymLink() ) 69 if ( fi.isSymLink() )
70 setText( 3, "symlink" ); 70 setText( 3, "symlink" );
71 else if( fi.isDir() ) 71 else if( fi.isDir() )
72 setText( 3, "directory" ); 72 setText( 3, "directory" );
73 else if( isLib() ) 73 else if( isLib() )
74 setText( 3, "library" ); 74 setText( 3, "library" );
75 else 75 else
76 setText( 3, mt.description() ); 76 setText( 3, mt.description() );
77 77
78 QPixmap pm; 78 QPixmap pm;
79 if( fi.isDir() ){ 79 if( fi.isDir() ){
80 if( !QDir( fi.filePath() ).isReadable() ) 80 if( !QDir( fi.filePath() ).isReadable() )
81 pm = Resource::loadPixmap( "lockedfolder" ); 81 pm = Resource::loadPixmap( "lockedfolder" );
82 else 82 else
83 pm = Resource::loadPixmap( "folder" ); 83 pm = Resource::loadPixmap( "folder" );
84 } 84 }
85 else if( !fi.isReadable() ) 85 else if( !fi.isReadable() )
86 pm = Resource::loadPixmap( "locked" ); 86 pm = Resource::loadPixmap( "locked" );
87 else if( isLib() ) 87 else if( isLib() )
88 pm = Resource::loadPixmap( "library" ); 88 pm = Resource::loadPixmap( "library" );
89 else if( ((FileView* )parent)->getShowThumbnails() && mt.id().contains(QRegExp("^image/", FALSE, FALSE)) ) 89 else if( ((FileView* )parent)->getShowThumbnails() && mt.id().contains(QRegExp("^image/", FALSE, FALSE)) )
90 pm = drawThumbnail(fi); 90 pm = drawThumbnail(fi);
91 else 91 else
92 pm = mt.pixmap(); 92 pm = mt.pixmap();
93 if ( pm.isNull() ) 93 if ( pm.isNull() )
94 pm = Resource::loadPixmap("UnknownDocument-14"); 94 pm = Resource::loadPixmap("UnknownDocument-14");
95 95
96 if( fi.isSymLink() ){ 96 if( fi.isSymLink() ){
97 // overlay link image 97 // overlay link image
98 QPixmap lnk = Resource::loadPixmap( "filebrowser/symlink" ); 98 QPixmap lnk = Resource::loadPixmap( "filebrowser/symlink" );
99 QPainter painter( &pm ); 99 QPainter painter( &pm );
100 painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); 100 painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk );
101 pm.setMask( pm.createHeuristicMask( FALSE ) ); 101 pm.setMask( pm.createHeuristicMask( FALSE ) );
102 } 102 }
103 setPixmap(0,pm); 103 setPixmap(0,pm);
104} 104}
105 105
106QString FileItem::sizeString( unsigned int s ) 106QString FileItem::sizeString( unsigned int s )
107{ 107{
108 double size = s; 108 double size = s;
109 109
110 if ( size > 1024 * 1024 * 1024 ) 110 if ( size > 1024 * 1024 * 1024 )
111 return QString().sprintf( "%.1f", size / ( 1024 * 1024 * 1024 ) ) + "G"; 111 return QString().sprintf( "%.1f", size / ( 1024 * 1024 * 1024 ) ) + "G";
112 else if ( size > 1024 * 1024 ) 112 else if ( size > 1024 * 1024 )
113 return QString().sprintf( "%.1f", size / ( 1024 * 1024 ) ) + "M"; 113 return QString().sprintf( "%.1f", size / ( 1024 * 1024 ) ) + "M";
114 else if ( size > 1024 ) 114 else if ( size > 1024 )
115 return QString().sprintf( "%.1f", size / ( 1024 ) ) + "K"; 115 return QString().sprintf( "%.1f", size / ( 1024 ) ) + "K";
116 else 116 else
117 return QString::number( size ) + "B"; 117 return QString::number( size ) + "B";
118} 118}
119 119
120QString FileItem::key( int column, bool ascending ) const 120QString FileItem::key( int column, bool ascending ) const
121{ 121{
122 QString tmp; 122 QString tmp;
123 123
124 ascending = ascending; 124 ascending = ascending;
125 125
126 if( (column == 0) && fileInfo.isDir() ){ // Sort by name 126 if( (column == 0) && fileInfo.isDir() ){ // Sort by name
127 // We want the directories to appear at the top of the list 127 // We want the directories to appear at the top of the list
128 tmp = (char) 0; 128 tmp = (char) 0;
129 return (tmp + text( column ).lower()); 129 return (tmp + text( column ).lower());
130 } 130 }
131 else if( column == 2 ) { // Sort by date 131 else if( column == 2 ) { // Sort by date
132 QDateTime epoch( QDate( 1980, 1, 1 ) ); 132 QDateTime epoch( QDate( 1980, 1, 1 ) );
133 tmp.sprintf( "%08d", epoch.secsTo( fileInfo.lastModified() ) ); 133 tmp.sprintf( "%08d", epoch.secsTo( fileInfo.lastModified() ) );
134 return tmp; 134 return tmp;
135 } 135 }
136 else if( column == 1 ) { // Sort by size 136 else if( column == 1 ) { // Sort by size
137 return tmp.sprintf( "%08d", fileInfo.size() ); 137 return tmp.sprintf( "%08d", fileInfo.size() );
138 } 138 }
139 139
140 return text( column ).lower(); 140 return text( column ).lower();
141} 141}
142 142
143bool FileItem::isLib() 143bool FileItem::isLib()
144{ 144{
145 // This is of course not foolproof 145 // This is of course not foolproof
146 if( !qstrncmp("lib", fileInfo.baseName(), 3) && 146 if( !qstrncmp("lib", fileInfo.baseName(), 3) &&
147 ( fileInfo.extension().contains( "so" ) || 147 ( fileInfo.extension().contains( "so" ) ||
148 fileInfo.extension().contains( "a" ) ) ) 148 fileInfo.extension().contains( "a" ) ) )
149 return TRUE; 149 return TRUE;
150 else 150 else
151 return FALSE; 151 return FALSE;
152} 152}
153 153
154int FileItem::launch() 154int FileItem::launch()
155{ 155{
156 DocLnk doc( fileInfo.filePath(), FALSE ); 156 DocLnk doc( fileInfo.filePath(), FALSE );
157 doc.execute(); 157 doc.execute();
158 listView()->clearSelection(); 158 listView()->clearSelection();
159 return 1; 159 return 1;
160} 160}
161 161
162bool FileItem::rename( const QString & name ) 162bool FileItem::rename( const QString & name )
163{ 163{
164 QString oldpath, newpath; 164 QString oldpath, newpath;
165 165
166 if ( name.isEmpty() ) 166 if ( name.isEmpty() )
167 return FALSE; 167 return FALSE;
168 168
169 if ( name.contains( QRegExp("[/\\$\"\'\\*\\?]") ) ) 169 if ( name.contains( QRegExp("[/\\$\"\'\\*\\?]") ) )
170 return FALSE; 170 return FALSE;
171 171
172 oldpath = fileInfo.filePath(); 172 oldpath = fileInfo.filePath();
173 newpath = fileInfo.dirPath() + "/" + name; 173 newpath = fileInfo.dirPath() + "/" + name;
174 174
175 if ( ::rename( (const char *) oldpath, (const char *) newpath ) != 0 ) 175 if ( ::rename( (const char *) oldpath, (const char *) newpath ) != 0 )
176 return FALSE; 176 return FALSE;
177 else 177 else
178 return TRUE; 178 return TRUE;
179} 179}
180 180
181QPixmap FileItem::drawThumbnail(const QFileInfo &file) { 181QPixmap FileItem::drawThumbnail(const QFileInfo &file) {
182 182
183 /* 183 /*
184 * this thing is sloooooow, and it also doesn't load 184 * this thing is sloooooow, and it also doesn't load
185 * dynamicly (like a web browser). if anyone knows how to 185 * dynamicly (like a web browser). if anyone knows how to
186 * do that, please do! 186 * do that, please do!
187 */ 187 */
188 QString cacheDir = "/tmp/filebrowserThumbnailCache"; 188 QString cacheDir = "/tmp/filebrowserThumbnailCache";
189 QFileInfo cachedFile (cacheDir + file.filePath()); 189 QFileInfo cachedFile (cacheDir + file.filePath());
190 190
191 if (cachedFile.exists() && cachedFile.lastModified() == file.lastModified()) { 191 if (cachedFile.exists() && cachedFile.lastModified() == file.lastModified()) {
192 192
193 QPixmap cachedImage (cachedFile.filePath()); 193 QPixmap cachedImage (cachedFile.filePath());
194 return cachedImage; 194 return cachedImage;
195 } 195 }
196 else { 196 else {
197 197
198 QImage image (file.filePath()); 198 QImage image (file.filePath());
199 199
200 // if inside of cache dir, don't render thumbnails! recursive error! 200 // if inside of cache dir, don't render thumbnails! recursive error!
201 if (image.isNull() || file.filePath().contains(QRegExp("^" + cacheDir))) { 201 if (image.isNull() || file.filePath().contains(QRegExp("^" + cacheDir))) {
202 DocLnk doc (file.filePath()); 202 DocLnk doc (file.filePath());
203 return doc.pixmap(); 203 return doc.pixmap();
204 } 204 }
205 Config cfg("Filebrowser"); 205 Config cfg("Filebrowser");
206 cfg.setGroup("View"); 206 cfg.setGroup("View");
207 int size; 207 int size;
208 size =cfg.readNumEntry("ThumbSize", 72); 208 size =cfg.readNumEntry("ThumbSize", 72);
209 QPixmap thumb (size, size); 209 QPixmap thumb (size, size);
210 210
211 double scale = (double)image.height() / (double)image.width(); 211 double scale = (double)image.height() / (double)image.width();
212 int newHeight = int(size * scale); 212 int newHeight = int(size * scale);
213 thumb.convertFromImage (image.smoothScale(size, newHeight)); 213 thumb.convertFromImage (image.smoothScale(size, newHeight));
214 214
215 if (!cachedFile.dir().exists()) { 215 if (!cachedFile.dir().exists()) {
216 QString cmd = "/bin/mkdir -p \"" + cachedFile.dirPath() +"\""; 216 QString cmd = "/bin/mkdir -p \"" + cachedFile.dirPath() +"\"";
217 system( (const char *) cmd ); 217 system( (const char *) cmd );
218 } 218 }
219 219
220 if (thumb.save(cachedFile.filePath(), QPixmap::imageFormat(file.filePath()), 70)) { 220 if (thumb.save(cachedFile.filePath(), QPixmap::imageFormat(file.filePath()), 70)) {
221 // make thumbnail modify time the same as the image 221 // make thumbnail modify time the same as the image
222 QString cmd = "/bin/touch -r \"" + file.filePath() +"\" " + 222 QString cmd = "/bin/touch -r \"" + file.filePath() +"\" " +
223 "\"" + cachedFile.filePath() + "\""; 223 "\"" + cachedFile.filePath() + "\"";
224 system( (const char *) cmd ); 224 system( (const char *) cmd );
225 225
226 } 226 }
227 227
228 return thumb; 228 return thumb;
229 } 229 }
230} 230}
231 231
232// 232//
233// FileView 233// FileView
234// 234//
235FileView::FileView( const QString & dir, QWidget * parent, 235FileView::FileView( const QString & dir, QWidget * parent,
236 const char * name, 236 const char * name,
237 bool hidden, bool symlinks, bool thumbnails ) 237 bool hidden, bool symlinks, bool thumbnails )
238 : QListView( parent, name ), 238 : QListView( parent, name ),
239 menuTimer( this ), 239 menuTimer( this ),
240 le( NULL ), 240 le( NULL ),
241 itemToRename( NULL ), 241 itemToRename( NULL ),
242 showHidden( hidden ), 242 showHidden( hidden ),
243 showSymlinks( symlinks ), 243 showSymlinks( symlinks ),
244 showThumbnails( thumbnails ), 244 showThumbnails( thumbnails ),
245 menuKeepsOpen( FALSE ) 245 menuKeepsOpen( FALSE )
246{ 246{
247 addColumn( "Name" ); 247 addColumn( "Name" );
248 addColumn( "Size" ); 248 addColumn( "Size" );
249 addColumn( "Date" ); 249 addColumn( "Date" );
250 addColumn( "Type" ); 250 addColumn( "Type" );
251 251
252 setMultiSelection( TRUE ); 252 setMultiSelection( TRUE );
253 //header()->hide(); 253 //header()->hide();
254 254
255 setColumnWidthMode( 0, Manual ); 255 setColumnWidthMode( 0, Manual );
256 setColumnWidthMode( 3, Manual ); 256 setColumnWidthMode( 3, Manual );
257 257
258 // right align yize column 258 // right align yize column
259 setColumnAlignment( 1, AlignRight ); 259 setColumnAlignment( 1, AlignRight );
260 260
261 generateDir( dir ); 261 generateDir( dir );
262 262
263 connect( this, SIGNAL( clicked( QListViewItem * )), 263 connect( this, SIGNAL( clicked(QListViewItem*)),
264 SLOT( itemClicked( QListViewItem * )) ); 264 SLOT( itemClicked(QListViewItem*)) );
265 connect( this, SIGNAL( doubleClicked( QListViewItem * )), 265 connect( this, SIGNAL( doubleClicked(QListViewItem*)),
266 SLOT( itemDblClicked( QListViewItem * )) ); 266 SLOT( itemDblClicked(QListViewItem*)) );
267 connect( this, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) ); 267 connect( this, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) );
268 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) ); 268 connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) );
269} 269}
270 270
271void FileView::resizeEvent( QResizeEvent *e ) 271void FileView::resizeEvent( QResizeEvent *e )
272{ 272{
273 setColumnWidth( 0, width() - 2 * lineWidth() - 20 - columnWidth( 1 ) - columnWidth( 2 ) ); 273 setColumnWidth( 0, width() - 2 * lineWidth() - 20 - columnWidth( 1 ) - columnWidth( 2 ) );
274 274
275 // hide type column, we use it for "sort by type" only 275 // hide type column, we use it for "sort by type" only
276 //setColumnWidth( 3, 0 ); 276 //setColumnWidth( 3, 0 );
277 QListView::resizeEvent( e ); 277 QListView::resizeEvent( e );
278} 278}
279 279
280void FileView::updateDir() 280void FileView::updateDir()
281{ 281{
282 generateDir( currentDir ); 282 generateDir( currentDir );
283} 283}
284 284
285void FileView::setDir( const QString & dir ) 285void FileView::setDir( const QString & dir )
286{ 286{
287 if ( dir.startsWith( "/dev" ) ) { 287 if ( dir.startsWith( "/dev" ) ) {
288 QMessageBox::warning( this, tr( "File Manager" ), 288 QMessageBox::warning( this, tr( "File Manager" ),
289 tr( "Can't show /dev/ directory." ), tr( "&Ok" ) ); 289 tr( "Can't show /dev/ directory." ), tr( "&Ok" ) );
290 return; 290 return;
291 } 291 }
292 dirHistory += currentDir; 292 dirHistory += currentDir;
293 generateDir( dir ); 293 generateDir( dir );
294} 294}
295 295
296void FileView::generateDir( const QString & dir ) 296void FileView::generateDir( const QString & dir )
297{ 297{
298 if(menuKeepsOpen){ 298 if(menuKeepsOpen){
299 cancelMenuTimer(); 299 cancelMenuTimer();
300 } 300 }
301 QDir d( dir ); 301 QDir d( dir );
302 302
303 if( d.exists() && !d.isReadable() ) return; 303 if( d.exists() && !d.isReadable() ) return;
304 304
305 currentDir = d.canonicalPath(); 305 currentDir = d.canonicalPath();
306 306
307 if( !showHidden) 307 if( !showHidden)
308 d.setFilter( QDir::Dirs | QDir::Files ); 308 d.setFilter( QDir::Dirs | QDir::Files );
309 else 309 else
310 d.setFilter( QDir::Dirs | QDir::Files |QDir::Hidden | QDir::All); 310 d.setFilter( QDir::Dirs | QDir::Files |QDir::Hidden | QDir::All);
311 311
312 d.setSorting( QDir::Name | QDir::DirsFirst | QDir::IgnoreCase | QDir::Reversed ); 312 d.setSorting( QDir::Name | QDir::DirsFirst | QDir::IgnoreCase | QDir::Reversed );
313 313
314 const QFileInfoList * list = d.entryInfoList(); 314 const QFileInfoList * list = d.entryInfoList();
315 QFileInfoListIterator it( *list ); 315 QFileInfoListIterator it( *list );
316 QFileInfo *fi; 316 QFileInfo *fi;
317 317
318 QProgressBar *thumbProgress = 0; 318 QProgressBar *thumbProgress = 0;
319 if (showThumbnails) { 319 if (showThumbnails) {
320 320
321 thumbProgress = new QProgressBar(it.count(), this); 321 thumbProgress = new QProgressBar(it.count(), this);
322 thumbProgress->show(); 322 thumbProgress->show();
323 } 323 }
324 324
325 clear(); 325 clear();
326 326
327 int fileCount = 1; // used in the thumbnail progress meter 327 int fileCount = 1; // used in the thumbnail progress meter
328 while( (fi = it.current()) ){ 328 while( (fi = it.current()) ){
329 if( (fi->fileName() == ".") || (fi->fileName() == "..") ){ 329 if( (fi->fileName() == ".") || (fi->fileName() == "..") ){
330 ++it; 330 ++it;
331 continue; 331 continue;
332 } 332 }
333 if(!showSymlinks && fi->isSymLink()){ 333 if(!showSymlinks && fi->isSymLink()){
334 ++it; 334 ++it;
335 continue; 335 continue;
336 } 336 }
337 // thumbnail progress 337 // thumbnail progress
338 if (showThumbnails) { 338 if (showThumbnails) {
339 339
340 thumbProgress->setProgress(fileCount); 340 thumbProgress->setProgress(fileCount);
341 } 341 }
342 (void) new FileItem( (QListView *) this, *fi ); 342 (void) new FileItem( (QListView *) this, *fi );
343 343
344 ++it; 344 ++it;
345 ++fileCount; 345 ++fileCount;
346 } 346 }
347 347
348 if (showThumbnails) { 348 if (showThumbnails) {
349 thumbProgress->close(); 349 thumbProgress->close();
350 } 350 }
351 emit dirChanged(); 351 emit dirChanged();
352 352
353} 353}
354 354
355void FileView::rename() 355void FileView::rename()
356{ 356{
357 itemToRename = (FileItem *) currentItem(); 357 itemToRename = (FileItem *) currentItem();
358 const QPixmap * pm; 358 const QPixmap * pm;
359 int pmw; 359 int pmw;
360 360
361 if( itemToRename == NULL ) return; 361 if( itemToRename == NULL ) return;
362 362
363 if( ( pm = itemToRename->pixmap( 0 ) ) == NULL ) 363 if( ( pm = itemToRename->pixmap( 0 ) ) == NULL )
364 pmw = 0; 364 pmw = 0;
365 else 365 else
366 pmw = pm->width(); 366 pmw = pm->width();
367 367
368 ensureItemVisible( itemToRename ); 368 ensureItemVisible( itemToRename );
369 horizontalScrollBar()->setValue( 0 ); 369 horizontalScrollBar()->setValue( 0 );
370 horizontalScrollBar()->setEnabled( FALSE ); 370 horizontalScrollBar()->setEnabled( FALSE );
371 verticalScrollBar()->setEnabled( FALSE ); 371 verticalScrollBar()->setEnabled( FALSE );
372 372
373 selected = isSelected( itemToRename ); 373 selected = isSelected( itemToRename );
374 setSelected( itemToRename, FALSE ); 374 setSelected( itemToRename, FALSE );
375 375
376 if( le == NULL ){ 376 if( le == NULL ){
377 le = new InlineEdit( this ); 377 le = new InlineEdit( this );
378 le->setFrame( FALSE ); 378 le->setFrame( FALSE );
379 connect( le, SIGNAL( lostFocus() ), SLOT( endRenaming() ) ); 379 connect( le, SIGNAL( lostFocus() ), SLOT( endRenaming() ) );
380 } 380 }
381 381
382 QRect r = itemRect( itemToRename ); 382 QRect r = itemRect( itemToRename );
383 r.setTop( r.top() + frameWidth() + 1 ); 383 r.setTop( r.top() + frameWidth() + 1 );
384 r.setLeft( r.left() + frameWidth() + pmw ); 384 r.setLeft( r.left() + frameWidth() + pmw );
385 r.setBottom( r.bottom() + frameWidth() ); 385 r.setBottom( r.bottom() + frameWidth() );
386 r.setWidth( columnWidth( 0 ) - pmw ); 386 r.setWidth( columnWidth( 0 ) - pmw );
387 387
388 le->setGeometry( r ); 388 le->setGeometry( r );
389 le->setText( itemToRename->text( 0 ) ); 389 le->setText( itemToRename->text( 0 ) );
390 le->selectAll(); 390 le->selectAll();
391 le->show(); 391 le->show();
392 le->setFocus(); 392 le->setFocus();
393} 393}
394 394
395void FileView::endRenaming() 395void FileView::endRenaming()
396{ 396{
397 if( le && itemToRename ){ 397 if( le && itemToRename ){
398 le->hide(); 398 le->hide();
399 setSelected( itemToRename, selected ); 399 setSelected( itemToRename, selected );
400 400
401 if( !itemToRename->rename( le->text() ) ){ 401 if( !itemToRename->rename( le->text() ) ){
402 QMessageBox::warning( this, tr( "Rename file" ), 402 QMessageBox::warning( this, tr( "Rename file" ),
403 tr( "Rename failed!" ), tr( "&Ok" ) ); 403 tr( "Rename failed!" ), tr( "&Ok" ) );
404 } else { 404 } else {
405 updateDir(); 405 updateDir();
406 } 406 }
407 itemToRename = NULL; 407 itemToRename = NULL;
408 horizontalScrollBar()->setEnabled( TRUE ); 408 horizontalScrollBar()->setEnabled( TRUE );
409 verticalScrollBar()->setEnabled( TRUE ); 409 verticalScrollBar()->setEnabled( TRUE );
410 } 410 }
411} 411}
412 412
413void FileView::copy() 413void FileView::copy()
414{ 414{
415 // dont keep cut files any longer than necessary 415 // dont keep cut files any longer than necessary
416 // ##### a better inmplementation might be to rename the CUT file 416 // ##### a better inmplementation might be to rename the CUT file
417 // ##### to ".QPE-FILEBROWSER-MOVING" rather than copying it. 417 // ##### to ".QPE-FILEBROWSER-MOVING" rather than copying it.
418 system ( "rm -rf /tmp/qpemoving" ); 418 system ( "rm -rf /tmp/qpemoving" );
419 419
420 FileItem * i; 420 FileItem * i;
421 421
422 if((i = (FileItem *) firstChild()) == 0) return; 422 if((i = (FileItem *) firstChild()) == 0) return;
423 423
424 flist.clear(); 424 flist.clear();
425 while( i ){ 425 while( i ){
426 if( i->isSelected() /*&& !i->isDir()*/ ){ 426 if( i->isSelected() /*&& !i->isDir()*/ ){
427 flist += i->getFilePath(); 427 flist += i->getFilePath();
428 } 428 }
429 i = (FileItem *) i->nextSibling(); 429 i = (FileItem *) i->nextSibling();
430 } 430 }
431} 431}
432 432
433void FileView::paste() 433void FileView::paste()
434{ 434{
435 int i, err; 435 int i, err;
436 QString cmd, dest, basename, cd = currentDir; 436 QString cmd, dest, basename, cd = currentDir;
437 437
438 if(cd == "/") cd = ""; 438 if(cd == "/") cd = "";
439 439
440 for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) { 440 for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) {
441 basename = (*it).mid((*it).findRev("/") + 1, (*it).length()); 441 basename = (*it).mid((*it).findRev("/") + 1, (*it).length());
442 442
443 dest = cd + "/" + basename; 443 dest = cd + "/" + basename;
444 if( QFile( dest ).exists() ){ 444 if( QFile( dest ).exists() ){
445 i = 1; 445 i = 1;
446 dest = cd + "/Copy of " + basename; 446 dest = cd + "/Copy of " + basename;
447 while( QFile( dest ).exists() ){ 447 while( QFile( dest ).exists() ){
448 dest.sprintf( "%s/Copy (%d) of %s", (const char *) cd, i++, 448 dest.sprintf( "%s/Copy (%d) of %s", (const char *) cd, i++,
449 (const char *) basename ); 449 (const char *) basename );
450 } 450 }
451 } 451 }
452 452
453 // 453 //
454 // Copy a directory recursively using the "cp" command - 454 // Copy a directory recursively using the "cp" command -
455 // may have to be changed 455 // may have to be changed
456 // 456 //
457 if( QFileInfo( (*it) ).isDir() ){ 457 if( QFileInfo( (*it) ).isDir() ){
458 cmd = "/bin/cp -fpR \"" + (*it) +"\" " + "\"" + dest + "\""; 458 cmd = "/bin/cp -fpR \"" + (*it) +"\" " + "\"" + dest + "\"";
459 err = system( (const char *) cmd ); 459 err = system( (const char *) cmd );
460 } else if( !copyFile( dest, (*it) ) ){ 460 } else if( !copyFile( dest, (*it) ) ){
461 err = -1; 461 err = -1;
462 } else { 462 } else {
463 err = 0; 463 err = 0;
464 } 464 }
465 465
466 if ( err != 0 ) { 466 if ( err != 0 ) {
467 QMessageBox::warning( this, tr("Paste file"), tr("Paste failed!"), 467 QMessageBox::warning( this, tr("Paste file"), tr("Paste failed!"),
468 tr("Ok") ); 468 tr("Ok") );
469 break; 469 break;
470 } else { 470 } else {
471 updateDir(); 471 updateDir();
472 QListViewItem * i = firstChild(); 472 QListViewItem * i = firstChild();
473 basename = dest.mid( dest.findRev("/") + 1, dest.length() ); 473 basename = dest.mid( dest.findRev("/") + 1, dest.length() );
474 474
475 while( i ){ 475 while( i ){
476 if( i->text(0) == basename ){ 476 if( i->text(0) == basename ){
477 setCurrentItem( i ); 477 setCurrentItem( i );
478 ensureItemVisible( i ); 478 ensureItemVisible( i );
479 break; 479 break;
480 } 480 }
481 i = i->nextSibling(); 481 i = i->nextSibling();
482 } 482 }
483 } 483 }
484 } 484 }
485} 485}
486 486
487bool FileView::copyFile( const QString & dest, const QString & src ) 487bool FileView::copyFile( const QString & dest, const QString & src )
488{ 488{
489 char bf[ 50000 ]; 489 char bf[ 50000 ];
490 int bytesRead; 490 int bytesRead;
491 bool success = TRUE; 491 bool success = TRUE;
492 struct stat status; 492 struct stat status;
493 493
494 QFile s( src ); 494 QFile s( src );
495 QFile d( dest ); 495 QFile d( dest );
496 496
497 if( s.open( IO_ReadOnly | IO_Raw ) && 497 if( s.open( IO_ReadOnly | IO_Raw ) &&
498 d.open( IO_WriteOnly | IO_Raw ) ) 498 d.open( IO_WriteOnly | IO_Raw ) )
499 { 499 {
500 while( (bytesRead = s.readBlock( bf, sizeof( bf ) )) == 500 while( (bytesRead = s.readBlock( bf, sizeof( bf ) )) ==
501 sizeof( bf ) ) 501 sizeof( bf ) )
502 { 502 {
503 if( d.writeBlock( bf, sizeof( bf ) ) != sizeof( bf ) ){ 503 if( d.writeBlock( bf, sizeof( bf ) ) != sizeof( bf ) ){
504 success = FALSE; 504 success = FALSE;
505 break; 505 break;
506 } 506 }
507 } 507 }
508 if( success && (bytesRead > 0) ){ 508 if( success && (bytesRead > 0) ){
509 d.writeBlock( bf, bytesRead ); 509 d.writeBlock( bf, bytesRead );
510 } 510 }
511 } else { 511 } else {
512 success = FALSE; 512 success = FALSE;
513 } 513 }
514 514
515 // Set file permissions 515 // Set file permissions
516 if( stat( (const char *) src, &status ) == 0 ){ 516 if( stat( (const char *) src, &status ) == 0 ){
517 chmod( (const char *) dest, status.st_mode ); 517 chmod( (const char *) dest, status.st_mode );
518 } 518 }
519 519
520 return success; 520 return success;
521} 521}
522 522
523void FileView::cut() 523void FileView::cut()
524{ 524{
525 int err; 525 int err;
526 // ##### a better inmplementation might be to rename the CUT file 526 // ##### a better inmplementation might be to rename the CUT file
527 // ##### to ".QPE-FILEBROWSER-MOVING" rather than copying it. 527 // ##### to ".QPE-FILEBROWSER-MOVING" rather than copying it.
528 QString cmd, dest, basename, cd = "/tmp/qpemoving"; 528 QString cmd, dest, basename, cd = "/tmp/qpemoving";
529 QStringList newflist; 529 QStringList newflist;
530 newflist.clear(); 530 newflist.clear();
531 531
532 cmd = "rm -rf " + cd; 532 cmd = "rm -rf " + cd;
533 system ( (const char *) cmd ); 533 system ( (const char *) cmd );
534 cmd = "mkdir " + cd; 534 cmd = "mkdir " + cd;
535 system( (const char *) cmd ); 535 system( (const char *) cmd );
536 536
537// get the names of the files to cut 537// get the names of the files to cut
538 FileItem * item; 538 FileItem * item;
539 539
540 if((item = (FileItem *) firstChild()) == 0) return; 540 if((item = (FileItem *) firstChild()) == 0) return;
541 541
542 flist.clear(); 542 flist.clear();
543 while( item ){ 543 while( item ){
544 if( item->isSelected() /*&& !item->isDir()*/ ){ 544 if( item->isSelected() /*&& !item->isDir()*/ ){
545 flist += item->getFilePath(); 545 flist += item->getFilePath();
546 } 546 }
547 item = (FileItem *) item->nextSibling(); 547 item = (FileItem *) item->nextSibling();
548 } 548 }
549 549
550// move these files into a tmp dir 550// move these files into a tmp dir
551 for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) { 551 for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) {
552 basename = (*it).mid((*it).findRev("/") + 1, (*it).length()); 552 basename = (*it).mid((*it).findRev("/") + 1, (*it).length());
553 553
554 dest = cd + "/" + basename; 554 dest = cd + "/" + basename;
555 555
556 newflist += dest; 556 newflist += dest;
557 557
558 cmd = "/bin/mv -f \"" + (*it) +"\" " + "\"" + dest + "\""; 558 cmd = "/bin/mv -f \"" + (*it) +"\" " + "\"" + dest + "\"";
559 err = system( (const char *) cmd ); 559 err = system( (const char *) cmd );
560 560
561 if ( err != 0 ) { 561 if ( err != 0 ) {
562 QMessageBox::warning( this, tr("Cut file"), tr("Cut failed!"), 562 QMessageBox::warning( this, tr("Cut file"), tr("Cut failed!"),
563 tr("Ok") ); 563 tr("Ok") );
564 break; 564 break;
565 } else { 565 } else {
566 updateDir(); 566 updateDir();
567 QListViewItem * im = firstChild(); 567 QListViewItem * im = firstChild();
568 basename = dest.mid( dest.findRev("/") + 1, dest.length() ); 568 basename = dest.mid( dest.findRev("/") + 1, dest.length() );
569 569
570 while( im ){ 570 while( im ){
571 if( im->text(0) == basename ){ 571 if( im->text(0) == basename ){
572 setCurrentItem( im ); 572 setCurrentItem( im );
573 ensureItemVisible( im ); 573 ensureItemVisible( im );
574 break; 574 break;
575 } 575 }
576 im = im->nextSibling(); 576 im = im->nextSibling();
577 } 577 }
578 } 578 }
579 } 579 }
580 580
581 // update the filelist to point to tmp dir so paste works nicely 581 // update the filelist to point to tmp dir so paste works nicely
582 flist = newflist; 582 flist = newflist;
583} 583}
584 584
585void FileView::del() 585void FileView::del()
586{ 586{
587 FileItem * i; 587 FileItem * i;
588 QStringList fl; 588 QStringList fl;
589 QString cmd; 589 QString cmd;
590 int err; 590 int err;
591 591
592 if((i = (FileItem *) firstChild()) == 0) return; 592 if((i = (FileItem *) firstChild()) == 0) return;
593 593
594 while( i ){ 594 while( i ){
595 if( i->isSelected() ){ 595 if( i->isSelected() ){
596 fl += i->getFilePath(); 596 fl += i->getFilePath();
597 } 597 }
598 i = (FileItem *) i->nextSibling(); 598 i = (FileItem *) i->nextSibling();
599 } 599 }
600 if( fl.count() < 1 ) return; 600 if( fl.count() < 1 ) return;
601 601
602 if( QMessageBox::warning( this, tr("Delete"), tr("Are you sure?"), 602 if( QMessageBox::warning( this, tr("Delete"), tr("Are you sure?"),
603 tr("Yes"), tr("No") ) == 0) 603 tr("Yes"), tr("No") ) == 0)
604 { 604 {
605 // 605 //
606 // Dependant upon the "rm" command - will probably have to be replaced 606 // Dependant upon the "rm" command - will probably have to be replaced
607 // 607 //
608 for ( QStringList::Iterator it = fl.begin(); it != fl.end(); ++it ) { 608 for ( QStringList::Iterator it = fl.begin(); it != fl.end(); ++it ) {
609 cmd = "/bin/rm -rf \"" + (*it) + "\""; 609 cmd = "/bin/rm -rf \"" + (*it) + "\"";
610 err = system( (const char *) cmd ); 610 err = system( (const char *) cmd );
611 if ( err != 0 ) { 611 if ( err != 0 ) {
612 QMessageBox::warning( this, tr("Delete"), tr("Delete failed!"), 612 QMessageBox::warning( this, tr("Delete"), tr("Delete failed!"),
613 tr("Ok") ); 613 tr("Ok") );
614 break; 614 break;
615 } 615 }
616 } 616 }
617 updateDir(); 617 updateDir();
618 } 618 }
619} 619}
620 620
621void FileView::newFolder() 621void FileView::newFolder()
622{ 622{
623 int t = 1; 623 int t = 1;
624 FileItem * i; 624 FileItem * i;
625 QString nd = currentDir + "/NewFolder"; 625 QString nd = currentDir + "/NewFolder";
626 626
627 while( QFile( nd ).exists() ){ 627 while( QFile( nd ).exists() ){
628 nd.sprintf( "%s/NewFolder (%d)", (const char *) currentDir, t++ ); 628 nd.sprintf( "%s/NewFolder (%d)", (const char *) currentDir, t++ );
629 } 629 }
630 630
631 if( mkdir( (const char *) nd, 0777 ) != 0){ 631 if( mkdir( (const char *) nd, 0777 ) != 0){
632 QMessageBox::warning( this, tr( "New folder" ), 632 QMessageBox::warning( this, tr( "New folder" ),
633 tr( "Folder creation failed!" ), 633 tr( "Folder creation failed!" ),
634 tr( "Ok" ) ); 634 tr( "Ok" ) );
635 return; 635 return;
636 } 636 }
637 updateDir(); 637 updateDir();
638 638
639 if((i = (FileItem *) firstChild()) == 0) return; 639 if((i = (FileItem *) firstChild()) == 0) return;
640 640
641 while( i ){ 641 while( i ){
642 if( i->isDir() && ( i->getFilePath() == nd ) ){ 642 if( i->isDir() && ( i->getFilePath() == nd ) ){
643 setCurrentItem( i ); 643 setCurrentItem( i );
644 rename(); 644 rename();
645 break; 645 break;
646 } 646 }
647 i = (FileItem *) i->nextSibling(); 647 i = (FileItem *) i->nextSibling();
648 } 648 }
649} 649}
650 650
651void FileView::viewAsText() 651void FileView::viewAsText()
652{ 652{
653 FileItem * i = (FileItem *) currentItem(); 653 FileItem * i = (FileItem *) currentItem();
654 QCopEnvelope e("QPE/Application/textedit","setDocument(QString)"); 654 QCopEnvelope e("QPE/Application/textedit","setDocument(QString)");
655 e << i->getFilePath(); 655 e << i->getFilePath();
656// Global::execute( "textedit -f ", i->getFilePath() ); 656// Global::execute( "textedit -f ", i->getFilePath() );
657} 657}
658 658
659void FileView::itemClicked( QListViewItem * i) 659void FileView::itemClicked( QListViewItem * i)
660{ 660{
661 FileItem * t = (FileItem *) i; 661 FileItem * t = (FileItem *) i;
662 662
663 if( t == NULL ) return; 663 if( t == NULL ) return;
664 if( t->isDir() ){ 664 if( t->isDir() ){
665 setDir( t->getFilePath() ); 665 setDir( t->getFilePath() );
666 } 666 }
667} 667}
668 668
669void FileView::itemDblClicked( QListViewItem * i) 669void FileView::itemDblClicked( QListViewItem * i)
670{ 670{
671 if(menuKeepsOpen){ 671 if(menuKeepsOpen){
672 cancelMenuTimer(); 672 cancelMenuTimer();
673 } 673 }
674 674
675 FileItem * t = (FileItem *) i; 675 FileItem * t = (FileItem *) i;
676 676
677 if(t == NULL) return; 677 if(t == NULL) return;
678 if(t->launch() == -1){ 678 if(t->launch() == -1){
679 QMessageBox::warning( this, tr( "Launch Application" ), 679 QMessageBox::warning( this, tr( "Launch Application" ),
680 tr( "Launch failed!" ), tr( "Ok" ) ); 680 tr( "Launch failed!" ), tr( "Ok" ) );
681 } 681 }
682} 682}
683 683
684void FileView::parentDir() 684void FileView::parentDir()
685{ 685{
686 setDir( currentDir + "./.." ); 686 setDir( currentDir + "./.." );
687} 687}
688 688
689void FileView::lastDir() 689void FileView::lastDir()
690{ 690{
691 if( dirHistory.count() == 0 ) return; 691 if( dirHistory.count() == 0 ) return;
692 692
693 QString newDir = dirHistory.last(); 693 QString newDir = dirHistory.last();
694 dirHistory.remove( dirHistory.last() ); 694 dirHistory.remove( dirHistory.last() );
695 generateDir( newDir ); 695 generateDir( newDir );
696} 696}
697 697
698void FileView::contentsMousePressEvent( QMouseEvent * e ) 698void FileView::contentsMousePressEvent( QMouseEvent * e )
699{ 699{
700 QListView::contentsMousePressEvent( e ); 700 QListView::contentsMousePressEvent( e );
701 menuTimer.start( 750, TRUE ); 701 menuTimer.start( 750, TRUE );
702} 702}
703 703
704void FileView::contentsMouseReleaseEvent( QMouseEvent * e ) 704void FileView::contentsMouseReleaseEvent( QMouseEvent * e )
705{ 705{
706 QListView::contentsMouseReleaseEvent( e ); 706 QListView::contentsMouseReleaseEvent( e );
707 if(!menuKeepsOpen){ 707 if(!menuKeepsOpen){
708 menuTimer.stop(); 708 menuTimer.stop();
709 } 709 }
710 710
711} 711}
712 712
713void FileView::cancelMenuTimer() 713void FileView::cancelMenuTimer()
714{ 714{
715 if( menuTimer.isActive() ) 715 if( menuTimer.isActive() )
716 menuTimer.stop(); 716 menuTimer.stop();
717} 717}
718 718
719void FileView::addToDocuments() 719void FileView::addToDocuments()
720{ 720{
721 FileItem * i = (FileItem *) currentItem(); 721 FileItem * i = (FileItem *) currentItem();
722 DocLnk f; 722 DocLnk f;
723 QString n = i->text(0); 723 QString n = i->text(0);
724 n.replace(QRegExp("\\..*"),""); 724 n.replace(QRegExp("\\..*"),"");
725 f.setName( n ); 725 f.setName( n );
726 f.setFile( i->getFilePath() ); 726 f.setFile( i->getFilePath() );
727 f.writeLink(); 727 f.writeLink();
728} 728}
729 729
730void FileView::run() 730void FileView::run()
731{ 731{
732 FileItem * i = (FileItem *) currentItem(); 732 FileItem * i = (FileItem *) currentItem();
733 i->launch(); 733 i->launch();
734} 734}
735 735
736void FileView::showFileMenu() 736void FileView::showFileMenu()
737{ 737{
738 FileItem * i = (FileItem *) currentItem(); 738 FileItem * i = (FileItem *) currentItem();
739 if ( !i ) 739 if ( !i )
740 return; 740 return;
741 741
742 QPopupMenu * m = new QPopupMenu( this ); 742 QPopupMenu * m = new QPopupMenu( this );
743 743
744 if ( !i->isDir() ) { 744 if ( !i->isDir() ) {
745 m->insertItem( tr( "Add to Documents" ), this, SLOT( addToDocuments() ) ); 745 m->insertItem( tr( "Add to Documents" ), this, SLOT( addToDocuments() ) );
746 m->insertSeparator(); 746 m->insertSeparator();
747 } 747 }
748 748
749 MimeType mt(i->getFilePath()); 749 MimeType mt(i->getFilePath());
750 const AppLnk* app = mt.application(); 750 const AppLnk* app = mt.application();
751 751
752 if ( !i->isDir() ) { 752 if ( !i->isDir() ) {
753 if ( app ) 753 if ( app )
754 m->insertItem( app->pixmap(), tr( "Open in " + app->name() ), this, SLOT( run() ) ); 754 m->insertItem( app->pixmap(), tr( "Open in " + app->name() ), this, SLOT( run() ) );
755 else if( i->isExecutable() ) 755 else if( i->isExecutable() )
756 m->insertItem( Resource::loadPixmap( i->text( 0 ) ), tr( "Run" ), this, SLOT( run() ) ); 756 m->insertItem( Resource::loadPixmap( i->text( 0 ) ), tr( "Run" ), this, SLOT( run() ) );
757 757
758 m->insertItem( Resource::loadPixmap( "txt" ), tr( "View as text" ), 758 m->insertItem( Resource::loadPixmap( "txt" ), tr( "View as text" ),
759 this, SLOT( viewAsText() ) ); 759 this, SLOT( viewAsText() ) );
760 760
761 m->insertSeparator(); 761 m->insertSeparator();
762 } 762 }
763 763
764 m->insertItem( tr( "Rename" ), this, SLOT( rename() ) ); 764 m->insertItem( tr( "Rename" ), this, SLOT( rename() ) );
765 m->insertItem( Resource::loadPixmap("cut"), 765 m->insertItem( Resource::loadPixmap("cut"),
766 tr( "Cut" ), this, SLOT( cut() ) ); 766 tr( "Cut" ), this, SLOT( cut() ) );
767 m->insertItem( Resource::loadPixmap("copy"), 767 m->insertItem( Resource::loadPixmap("copy"),
768 768
769 tr( "Copy" ), this, SLOT( copy() ) ); 769 tr( "Copy" ), this, SLOT( copy() ) );
770 m->insertItem( Resource::loadPixmap("paste"), 770 m->insertItem( Resource::loadPixmap("paste"),
771 tr( "Paste" ), this, SLOT( paste() ) ); 771 tr( "Paste" ), this, SLOT( paste() ) );
772 m->insertItem( tr( "Change Permissions" ), this, SLOT( chPerm() ) ); 772 m->insertItem( tr( "Change Permissions" ), this, SLOT( chPerm() ) );
773 m->insertItem(Resource::loadPixmap( "close" ), tr( "Delete" ), this, SLOT( del() ) ); 773 m->insertItem(Resource::loadPixmap( "close" ), tr( "Delete" ), this, SLOT( del() ) );
774 m->insertSeparator(); 774 m->insertSeparator();
775 m->insertItem( tr( "Select all" ), this, SLOT( selectAll() ) ); 775 m->insertItem( tr( "Select all" ), this, SLOT( selectAll() ) );
776 m->insertItem( tr( "Deselect all" ), this, SLOT( deselectAll() ) ); 776 m->insertItem( tr( "Deselect all" ), this, SLOT( deselectAll() ) );
777 m->popup( QCursor::pos() ); 777 m->popup( QCursor::pos() );
778} 778}
779 779
780// 780//
781// FileBrowser 781// FileBrowser
782// 782//
783 783
784void FileView::setShowHidden(bool hidden) 784void FileView::setShowHidden(bool hidden)
785{ 785{
786 showHidden=hidden; 786 showHidden=hidden;
787} 787}
788 788
789void FileView::setShowSymlinks(bool symlinks) 789void FileView::setShowSymlinks(bool symlinks)
790{ 790{
791 showSymlinks=symlinks; 791 showSymlinks=symlinks;
792} 792}
793 793
794void FileView::setShowThumbnails(bool thumbnails) 794void FileView::setShowThumbnails(bool thumbnails)
795{ 795{
796 showThumbnails=thumbnails; 796 showThumbnails=thumbnails;
797} 797}
798 798
799void FileView::setMenuKeepsOpen(bool keepOpen) 799void FileView::setMenuKeepsOpen(bool keepOpen)
800{ 800{
801 menuKeepsOpen=keepOpen; 801 menuKeepsOpen=keepOpen;
802} 802}
803 803
804FileBrowser::FileBrowser( QWidget * parent, 804FileBrowser::FileBrowser( QWidget * parent,
805 const char * name, WFlags f ) : 805 const char * name, WFlags f ) :
806 QMainWindow( parent, name, f ) 806 QMainWindow( parent, name, f )
807{ 807{
808 init( QDir::current().canonicalPath() ); 808 init( QDir::current().canonicalPath() );
809} 809}
810 810
811FileBrowser::FileBrowser( const QString & dir, QWidget * parent, 811FileBrowser::FileBrowser( const QString & dir, QWidget * parent,
812 const char * name, WFlags f ) : 812 const char * name, WFlags f ) :
813 QMainWindow( parent, name, f ) 813 QMainWindow( parent, name, f )
814{ 814{
815 init( dir ); 815 init( dir );
816} 816}
817 817
818void FileBrowser::init(const QString & dir) 818void FileBrowser::init(const QString & dir)
819{ 819{
820 setCaption( tr("File Manager") ); 820 setCaption( tr("File Manager") );
821 setIcon( Resource::loadPixmap( "filebrowser_icon" ) ); 821 setIcon( Resource::loadPixmap( "filebrowser_icon" ) );
822 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); 822 connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) );
823 823
824 824
825 Config cfg("Filebrowser"); 825 Config cfg("Filebrowser");
826 cfg.setGroup("View"); 826 cfg.setGroup("View");
827 bool showHidden=(cfg.readEntry("Hidden","FALSE") == "TRUE"); 827 bool showHidden=(cfg.readEntry("Hidden","FALSE") == "TRUE");
828 bool showSymlinks=(cfg.readEntry("Symlinks","FALSE") == "TRUE"); 828 bool showSymlinks=(cfg.readEntry("Symlinks","FALSE") == "TRUE");
829 bool showThumbnails=(cfg.readEntry("Thumbnails","FALSE") == "TRUE"); 829 bool showThumbnails=(cfg.readEntry("Thumbnails","FALSE") == "TRUE");
830 830
831 cfg.setGroup("Menu"); 831 cfg.setGroup("Menu");
832 bool menuKeepsOpen=(cfg.readEntry("KeepOpen", "FALSE") == "TRUE"); 832 bool menuKeepsOpen=(cfg.readEntry("KeepOpen", "FALSE") == "TRUE");
833 833
834 834
835 fileView = new FileView( dir, this, 0, showHidden, showSymlinks, showThumbnails ); 835 fileView = new FileView( dir, this, 0, showHidden, showSymlinks, showThumbnails );
836 fileView->setAllColumnsShowFocus( TRUE ); 836 fileView->setAllColumnsShowFocus( TRUE );
837 fileView->setMenuKeepsOpen(menuKeepsOpen); 837 fileView->setMenuKeepsOpen(menuKeepsOpen);
838 838
839 setCentralWidget( fileView ); 839 setCentralWidget( fileView );
840 setToolBarsMovable( FALSE ); 840 setToolBarsMovable( FALSE );
841 841
842 QToolBar* toolBar = new QToolBar( this ); 842 QToolBar* toolBar = new QToolBar( this );
843 toolBar->setHorizontalStretchable( TRUE ); 843 toolBar->setHorizontalStretchable( TRUE );
844 844
845 QMenuBar* menuBar = new QMenuBar( toolBar ); 845 QMenuBar* menuBar = new QMenuBar( toolBar );
846 846
847 dirMenu = new QPopupMenu( this ); 847 dirMenu = new QPopupMenu( this );
848 menuBar->insertItem( tr( "Dir" ), dirMenu ); 848 menuBar->insertItem( tr( "Dir" ), dirMenu );
849 849
850 sortMenu = new QPopupMenu( this ); 850 sortMenu = new QPopupMenu( this );
851 menuBar->insertItem( tr( "Sort" ), sortMenu ); 851 menuBar->insertItem( tr( "Sort" ), sortMenu );
852 sortMenu->insertItem( tr( "by Name "), this, SLOT( sortName() ) ); 852 sortMenu->insertItem( tr( "by Name "), this, SLOT( sortName() ) );
853 sortMenu->insertItem( tr( "by Size "), this, SLOT( sortSize() ) ); 853 sortMenu->insertItem( tr( "by Size "), this, SLOT( sortSize() ) );
854 sortMenu->insertItem( tr( "by Date "), this, SLOT( sortDate() ) ); 854 sortMenu->insertItem( tr( "by Date "), this, SLOT( sortDate() ) );
855 sortMenu->insertItem( tr( "by Type "), this, SLOT( sortType() ) ); 855 sortMenu->insertItem( tr( "by Type "), this, SLOT( sortType() ) );
856 sortMenu->insertSeparator(); 856 sortMenu->insertSeparator();
857 sortMenu->insertItem( tr( "Ascending" ), this, SLOT( updateSorting() ) ); 857 sortMenu->insertItem( tr( "Ascending" ), this, SLOT( updateSorting() ) );
858 858
859 sortMenu->setItemChecked( sortMenu->idAt( 5 ), TRUE ); 859 sortMenu->setItemChecked( sortMenu->idAt( 5 ), TRUE );
860 sortMenu->setItemChecked( sortMenu->idAt( 0 ), TRUE ); 860 sortMenu->setItemChecked( sortMenu->idAt( 0 ), TRUE );
861 861
862 viewMenu = new QPopupMenu( this); 862 viewMenu = new QPopupMenu( this);
863 viewMenu->insertItem( tr( "Hidden"), this, SLOT( updateShowHidden() ) ); 863 viewMenu->insertItem( tr( "Hidden"), this, SLOT( updateShowHidden() ) );
864 viewMenu->insertItem( tr( "Symlinks"), this, SLOT( updateShowSymlinks() ) ); 864 viewMenu->insertItem( tr( "Symlinks"), this, SLOT( updateShowSymlinks() ) );
865 viewMenu->insertItem( tr( "Thumbnails"), this, SLOT( updateShowThumbnails() ) ); 865 viewMenu->insertItem( tr( "Thumbnails"), this, SLOT( updateShowThumbnails() ) );
866 viewMenu->setItemChecked( viewMenu->idAt( 0 ), showHidden ); 866 viewMenu->setItemChecked( viewMenu->idAt( 0 ), showHidden );
867 viewMenu->setItemChecked( viewMenu->idAt( 1 ), showSymlinks ); 867 viewMenu->setItemChecked( viewMenu->idAt( 1 ), showSymlinks );
868 viewMenu->setItemChecked( viewMenu->idAt( 2 ), showThumbnails ); 868 viewMenu->setItemChecked( viewMenu->idAt( 2 ), showThumbnails );
869 869
870 menuBar->insertItem( tr("View"), viewMenu ); 870 menuBar->insertItem( tr("View"), viewMenu );
871 871
872 toolBar = new QToolBar( this ); 872 toolBar = new QToolBar( this );
873 873
874 lastAction = new QAction( tr("Previous dir"), Resource::loadIconSet( "back" ), 874 lastAction = new QAction( tr("Previous dir"), Resource::loadIconSet( "back" ),
875 QString::null, 0, this, 0 ); 875 QString::null, 0, this, 0 );
876 connect( lastAction, SIGNAL( activated() ), fileView, SLOT( lastDir() ) ); 876 connect( lastAction, SIGNAL( activated() ), fileView, SLOT( lastDir() ) );
877 lastAction->addTo( toolBar ); 877 lastAction->addTo( toolBar );
878 lastAction->setEnabled( FALSE ); 878 lastAction->setEnabled( FALSE );
879 879
880 upAction = new QAction( tr("Parent dir"), Resource::loadIconSet( "up" ), 880 upAction = new QAction( tr("Parent dir"), Resource::loadIconSet( "up" ),
881 QString::null, 0, this, 0 ); 881 QString::null, 0, this, 0 );
882 connect( upAction, SIGNAL( activated() ), fileView, SLOT( parentDir() ) ); 882 connect( upAction, SIGNAL( activated() ), fileView, SLOT( parentDir() ) );
883 upAction->addTo( toolBar ); 883 upAction->addTo( toolBar );
884 884
885 QAction *a = new QAction( tr("New folder"), Resource::loadPixmap( "newfolder" ), 885 QAction *a = new QAction( tr("New folder"), Resource::loadPixmap( "newfolder" ),
886 QString::null, 0, this, 0 ); 886 QString::null, 0, this, 0 );
887 connect( a, SIGNAL( activated() ), fileView, SLOT( newFolder() ) ); 887 connect( a, SIGNAL( activated() ), fileView, SLOT( newFolder() ) );
888 a->addTo( toolBar ); 888 a->addTo( toolBar );
889 889
890 a = new QAction( tr("Cut"), Resource::loadPixmap( "cut" ), 890 a = new QAction( tr("Cut"), Resource::loadPixmap( "cut" ),
891 QString::null, 0, this, 0 ); 891 QString::null, 0, this, 0 );
892 connect( a, SIGNAL( activated() ), fileView, SLOT( cut() ) ); 892 connect( a, SIGNAL( activated() ), fileView, SLOT( cut() ) );
893 a->addTo( toolBar ); 893 a->addTo( toolBar );
894 894
895 a = new QAction( tr("Copy"), Resource::loadPixmap( "copy" ), 895 a = new QAction( tr("Copy"), Resource::loadPixmap( "copy" ),
896 QString::null, 0, this, 0 ); 896 QString::null, 0, this, 0 );
897 connect( a, SIGNAL( activated() ), fileView, SLOT( copy() ) ); 897 connect( a, SIGNAL( activated() ), fileView, SLOT( copy() ) );
898 a->addTo( toolBar ); 898 a->addTo( toolBar );
899 899
900 pasteAction = new QAction( tr("Paste"), Resource::loadPixmap( "paste" ), 900 pasteAction = new QAction( tr("Paste"), Resource::loadPixmap( "paste" ),
901 QString::null, 0, this, 0 ); 901 QString::null, 0, this, 0 );
902 connect( pasteAction, SIGNAL( activated() ), fileView, SLOT( paste() ) ); 902 connect( pasteAction, SIGNAL( activated() ), fileView, SLOT( paste() ) );
903 pasteAction->addTo( toolBar ); 903 pasteAction->addTo( toolBar );
904 904
905// dirLabel = new QLabel(this, "DirLabel"); 905// dirLabel = new QLabel(this, "DirLabel");
906 906
907 connect( fileView, SIGNAL( dirChanged() ), SLOT( updateDirMenu() ) ); 907 connect( fileView, SIGNAL( dirChanged() ), SLOT( updateDirMenu() ) );
908 updateDirMenu(); 908 updateDirMenu();
909 909
910 QCopChannel* pcmciaChannel = new QCopChannel( "QPE/Card", this ); 910 QCopChannel* pcmciaChannel = new QCopChannel( "QPE/Card", this );
911 connect( pcmciaChannel, SIGNAL(received(const QCString &, const QByteArray &)), 911 connect( pcmciaChannel, SIGNAL(received(const QCString&,const QByteArray&)),
912 this, SLOT(pcmciaMessage( const QCString &, const QByteArray &)) ); 912 this, SLOT(pcmciaMessage(const QCString&,const QByteArray&)) );
913} 913}
914 914
915void FileBrowser::pcmciaMessage( const QCString &msg, const QByteArray &) 915void FileBrowser::pcmciaMessage( const QCString &msg, const QByteArray &)
916{ 916{
917 if ( msg == "mtabChanged()" ) { 917 if ( msg == "mtabChanged()" ) {
918 // ## Only really needed if current dir is on a card 918 // ## Only really needed if current dir is on a card
919 fileView->updateDir(); 919 fileView->updateDir();
920 } 920 }
921} 921}
922 922
923void FileBrowser::changeCaption(const QString & dir) { 923void FileBrowser::changeCaption(const QString & dir) {
924 setCaption( dir); 924 setCaption( dir);
925} 925}
926 926
927void FileBrowser::dirSelected( int id ) 927void FileBrowser::dirSelected( int id )
928{ 928{
929 int i = 0, j; 929 int i = 0, j;
930 QString dir; 930 QString dir;
931 931
932 // Bulid target dir from menu 932 // Bulid target dir from menu
933 while( (j = dirMenu->idAt( i )) != id ){ 933 while( (j = dirMenu->idAt( i )) != id ){
934 dir += dirMenu->text( j ).stripWhiteSpace(); 934 dir += dirMenu->text( j ).stripWhiteSpace();
935 if( dirMenu->text( j ) != "/" ) dir += "/"; 935 if( dirMenu->text( j ) != "/" ) dir += "/";
936 i++; 936 i++;
937 } 937 }
938 dir += dirMenu->text( dirMenu->idAt( i ) ).stripWhiteSpace(); 938 dir += dirMenu->text( dirMenu->idAt( i ) ).stripWhiteSpace();
939 939
940 fileView->setDir( dir ); 940 fileView->setDir( dir );
941} 941}
942 942
943void FileBrowser::updateDirMenu() 943void FileBrowser::updateDirMenu()
944{ 944{
945 QString spc, cd = fileView->cd(); 945 QString spc, cd = fileView->cd();
946 QStringList l = QStringList::split( "/", cd ); 946 QStringList l = QStringList::split( "/", cd );
947 int i = 0; 947 int i = 0;
948 948
949 dirMenu->clear(); 949 dirMenu->clear();
950 dirMenu->insertItem( tr( "/" ), this, SLOT( dirSelected(int) ) ); 950 dirMenu->insertItem( tr( "/" ), this, SLOT( dirSelected(int) ) );
951 951
952 for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) { 952 for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) {
953 spc.fill( ' ', i++); 953 spc.fill( ' ', i++);
954 dirMenu->insertItem( spc + (*it), this, 954 dirMenu->insertItem( spc + (*it), this,
955 SLOT( dirSelected(int) ) ); 955 SLOT( dirSelected(int) ) );
956 } 956 }
957 dirMenu->setItemChecked( dirMenu->idAt( l.count() ), TRUE ); 957 dirMenu->setItemChecked( dirMenu->idAt( l.count() ), TRUE );
958 958
959 lastAction->setEnabled( fileView->history().count() != 0 ); 959 lastAction->setEnabled( fileView->history().count() != 0 );
960 upAction->setEnabled( cd != "/" ); 960 upAction->setEnabled( cd != "/" );
961} 961}
962 962
963void FileBrowser::sortName() 963void FileBrowser::sortName()
964{ 964{
965 fileView->setSorting( 0, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); 965 fileView->setSorting( 0, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) );
966 fileView->sort(); 966 fileView->sort();
967 sortMenu->setItemChecked( sortMenu->idAt( 0 ), TRUE ); 967 sortMenu->setItemChecked( sortMenu->idAt( 0 ), TRUE );
968 sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE ); 968 sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE );
969 sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE ); 969 sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE );
970 sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE ); 970 sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE );
971} 971}
972 972
973void FileBrowser::sortSize() 973void FileBrowser::sortSize()
974{ 974{
975 fileView->setSorting( 1, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); 975 fileView->setSorting( 1, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) );
976 fileView->sort(); 976 fileView->sort();
977 sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE ); 977 sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE );
978 sortMenu->setItemChecked( sortMenu->idAt( 1 ), TRUE ); 978 sortMenu->setItemChecked( sortMenu->idAt( 1 ), TRUE );
979 sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE ); 979 sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE );
980 sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE ); 980 sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE );
981} 981}
982 982
983void FileBrowser::sortDate() 983void FileBrowser::sortDate()
984{ 984{
985 fileView->setSorting( 2, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); 985 fileView->setSorting( 2, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) );
986 fileView->sort(); 986 fileView->sort();
987 sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE ); 987 sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE );
988 sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE ); 988 sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE );
989 sortMenu->setItemChecked( sortMenu->idAt( 2 ), TRUE ); 989 sortMenu->setItemChecked( sortMenu->idAt( 2 ), TRUE );
990 sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE ); 990 sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE );
991} 991}
992 992
993void FileBrowser::sortType() 993void FileBrowser::sortType()
994{ 994{
995 fileView->setSorting( 3, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); 995 fileView->setSorting( 3, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) );
996 fileView->sort(); 996 fileView->sort();
997 sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE ); 997 sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE );
998 sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE ); 998 sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE );
999 sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE ); 999 sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE );
1000 sortMenu->setItemChecked( sortMenu->idAt( 3 ), TRUE ); 1000 sortMenu->setItemChecked( sortMenu->idAt( 3 ), TRUE );
1001} 1001}
1002 1002
1003void FileBrowser::updateSorting() 1003void FileBrowser::updateSorting()
1004{ 1004{
1005 sortMenu->setItemChecked( sortMenu->idAt( 5 ), !sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); 1005 sortMenu->setItemChecked( sortMenu->idAt( 5 ), !sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) );
1006 1006
1007 if ( sortMenu->isItemChecked( sortMenu->idAt( 0 ) ) ) 1007 if ( sortMenu->isItemChecked( sortMenu->idAt( 0 ) ) )
1008 sortName(); 1008 sortName();
1009 else if ( sortMenu->isItemChecked( sortMenu->idAt( 1 ) ) ) 1009 else if ( sortMenu->isItemChecked( sortMenu->idAt( 1 ) ) )
1010 sortSize(); 1010 sortSize();
1011 else if ( sortMenu->isItemChecked( sortMenu->idAt( 2 ) ) ) 1011 else if ( sortMenu->isItemChecked( sortMenu->idAt( 2 ) ) )
1012 sortDate(); 1012 sortDate();
1013 else 1013 else
1014 sortType(); 1014 sortType();
1015} 1015}
1016 1016
1017void FileView::chPerm() { 1017void FileView::chPerm() {
1018 FileItem * i; 1018 FileItem * i;
1019 QStringList fl; 1019 QStringList fl;
1020 QString cmd; 1020 QString cmd;
1021 1021
1022 if((i = (FileItem *) firstChild()) == 0) return; 1022 if((i = (FileItem *) firstChild()) == 0) return;
1023 1023
1024 while( i ){ 1024 while( i ){
1025 if( i->isSelected() ){ 1025 if( i->isSelected() ){
1026 fl += i->getFilePath(); 1026 fl += i->getFilePath();
1027 } 1027 }
1028 i = (FileItem *) i->nextSibling(); 1028 i = (FileItem *) i->nextSibling();
1029 } 1029 }
1030 if( fl.count() < 1 ) return; 1030 if( fl.count() < 1 ) return;
1031 if( QMessageBox::warning( this, tr("Change permissions"), tr("Are you sure?"), 1031 if( QMessageBox::warning( this, tr("Change permissions"), tr("Are you sure?"),
1032 tr("Yes"), tr("No") ) == 0) { 1032 tr("Yes"), tr("No") ) == 0) {
1033 for ( QStringList::Iterator it = fl.begin(); it != fl.end(); ++it ) { 1033 for ( QStringList::Iterator it = fl.begin(); it != fl.end(); ++it ) {
1034 filePermissions *filePerm; 1034 filePermissions *filePerm;
1035 filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(*it)); 1035 filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(*it));
1036 filePerm->exec(); 1036 filePerm->exec();
1037 if( filePerm) 1037 if( filePerm)
1038 delete filePerm; 1038 delete filePerm;
1039 break; 1039 break;
1040 } 1040 }
1041 updateDir(); 1041 updateDir();
1042 } 1042 }
1043} 1043}
1044 1044
1045void FileBrowser::updateShowHidden() 1045void FileBrowser::updateShowHidden()
1046{ 1046{
1047 bool valShowHidden=viewMenu->isItemChecked( viewMenu->idAt( 0 ) ); 1047 bool valShowHidden=viewMenu->isItemChecked( viewMenu->idAt( 0 ) );
1048 valShowHidden=!valShowHidden; 1048 valShowHidden=!valShowHidden;
1049 viewMenu->setItemChecked( viewMenu->idAt( 0 ), valShowHidden ); 1049 viewMenu->setItemChecked( viewMenu->idAt( 0 ), valShowHidden );
1050 fileView->setShowHidden(valShowHidden); 1050 fileView->setShowHidden(valShowHidden);
1051 1051
1052 Config cfg("Filebrowser"); 1052 Config cfg("Filebrowser");
1053 cfg.setGroup("View"); 1053 cfg.setGroup("View");
1054 cfg.writeEntry("Hidden",valShowHidden?"TRUE":"FALSE"); 1054 cfg.writeEntry("Hidden",valShowHidden?"TRUE":"FALSE");
1055 1055
1056 fileView->updateDir(); 1056 fileView->updateDir();
1057} 1057}
1058 1058
1059void FileBrowser::updateShowSymlinks() 1059void FileBrowser::updateShowSymlinks()
1060{ 1060{
1061 bool valShowSymlinks=viewMenu->isItemChecked( viewMenu->idAt( 1 ) ); 1061 bool valShowSymlinks=viewMenu->isItemChecked( viewMenu->idAt( 1 ) );
1062 valShowSymlinks=!valShowSymlinks; 1062 valShowSymlinks=!valShowSymlinks;
1063 viewMenu->setItemChecked( viewMenu->idAt( 1 ), valShowSymlinks ); 1063 viewMenu->setItemChecked( viewMenu->idAt( 1 ), valShowSymlinks );
1064 fileView->setShowSymlinks(valShowSymlinks); 1064 fileView->setShowSymlinks(valShowSymlinks);
1065 1065
1066 Config cfg("Filebrowser"); 1066 Config cfg("Filebrowser");
1067 cfg.setGroup("View"); 1067 cfg.setGroup("View");
1068 cfg.writeEntry("Symlinks",valShowSymlinks?"TRUE":"FALSE"); 1068 cfg.writeEntry("Symlinks",valShowSymlinks?"TRUE":"FALSE");
1069 1069
1070 fileView->updateDir(); 1070 fileView->updateDir();
1071} 1071}
1072 1072
1073void FileBrowser::updateShowThumbnails() 1073void FileBrowser::updateShowThumbnails()
1074{ 1074{
1075 bool valShowThumbnails=viewMenu->isItemChecked( viewMenu->idAt( 2 ) ); 1075 bool valShowThumbnails=viewMenu->isItemChecked( viewMenu->idAt( 2 ) );
1076 valShowThumbnails=!valShowThumbnails; 1076 valShowThumbnails=!valShowThumbnails;
1077 viewMenu->setItemChecked( viewMenu->idAt( 2 ), valShowThumbnails ); 1077 viewMenu->setItemChecked( viewMenu->idAt( 2 ), valShowThumbnails );
1078 fileView->setShowThumbnails(valShowThumbnails); 1078 fileView->setShowThumbnails(valShowThumbnails);
1079 1079
1080 Config cfg("Filebrowser"); 1080 Config cfg("Filebrowser");
1081 cfg.setGroup("View"); 1081 cfg.setGroup("View");
1082 cfg.writeEntry("Thumbnails",valShowThumbnails?"TRUE":"FALSE"); 1082 cfg.writeEntry("Thumbnails",valShowThumbnails?"TRUE":"FALSE");
1083 1083
1084 fileView->updateDir(); 1084 fileView->updateDir();
1085} 1085}
1086 1086
1087void FileBrowser::cleanUp() { 1087void FileBrowser::cleanUp() {
1088 QString cmdr = "rm -rf /tmp/filebrowserThumbnailCache"; 1088 QString cmdr = "rm -rf /tmp/filebrowserThumbnailCache";
1089// qDebug("exit"); 1089// qDebug("exit");
1090 system(cmdr.latin1()); 1090 system(cmdr.latin1());
1091} 1091}
diff --git a/noncore/unsupported/gsmtool/gsmtool.cpp b/noncore/unsupported/gsmtool/gsmtool.cpp
index 5940b0e..47920e5 100644
--- a/noncore/unsupported/gsmtool/gsmtool.cpp
+++ b/noncore/unsupported/gsmtool/gsmtool.cpp
@@ -1,457 +1,457 @@
1#include "gsmtool.h" 1#include "gsmtool.h"
2#include <qpushbutton.h> 2#include <qpushbutton.h>
3#include <qcombobox.h> 3#include <qcombobox.h>
4#include <qlineedit.h> 4#include <qlineedit.h>
5#include <qlabel.h> 5#include <qlabel.h>
6#include <qtabwidget.h> 6#include <qtabwidget.h>
7#include <qlistview.h> 7#include <qlistview.h>
8#include <qtextbrowser.h> 8#include <qtextbrowser.h>
9#include <qmultilineedit.h> 9#include <qmultilineedit.h>
10 10
11#include <termios.h> 11#include <termios.h>
12 12
13#include <gsmlib/gsm_me_ta.h> 13#include <gsmlib/gsm_me_ta.h>
14#include <gsmlib/gsm_unix_serial.h> 14#include <gsmlib/gsm_unix_serial.h>
15#include <gsmlib/gsm_sms.h> 15#include <gsmlib/gsm_sms.h>
16#include <gsmlib/gsm_sorted_sms_store.h> 16#include <gsmlib/gsm_sorted_sms_store.h>
17 17
18using namespace gsmlib; 18using namespace gsmlib;
19 19
20 20
21/* 21/*
22 * Constructs a GSMTool which is a child of 'parent', with the 22 * Constructs a GSMTool which is a child of 'parent', with the
23 * name 'name' and widget flags set to 'f' 23 * name 'name' and widget flags set to 'f'
24 */ 24 */
25GSMTool::GSMTool( QWidget* parent, const char* name, WFlags fl ) 25GSMTool::GSMTool( QWidget* parent, const char* name, WFlags fl )
26 : GSMToolBase( parent, name, fl ) 26 : GSMToolBase( parent, name, fl )
27{ 27{
28 devicelocked = 0; 28 devicelocked = 0;
29 me = NULL; 29 me = NULL;
30 sms_store = NULL; 30 sms_store = NULL;
31 setConnected(FALSE); 31 setConnected(FALSE);
32 /* FIXME: Persistent settings for device/baudrate */ 32 /* FIXME: Persistent settings for device/baudrate */
33 connect(ConnectButton, SIGNAL(clicked()), this, SLOT(doConnectButton())); 33 connect(ConnectButton, SIGNAL(clicked()), this, SLOT(doConnectButton()));
34 connect(SMSDeleteButton, SIGNAL(clicked()), this, SLOT(doSMSDeleteButton())); 34 connect(SMSDeleteButton, SIGNAL(clicked()), this, SLOT(doSMSDeleteButton()));
35 connect(SMSSendButton, SIGNAL(clicked()), this, SLOT(doSMSSendButton())); 35 connect(SMSSendButton, SIGNAL(clicked()), this, SLOT(doSMSSendButton()));
36 connect(NewSMSClearButton, SIGNAL(clicked()), this, SLOT(doNewSMSClearButton())); 36 connect(NewSMSClearButton, SIGNAL(clicked()), this, SLOT(doNewSMSClearButton()));
37 connect(NewSMSSaveButton, SIGNAL(clicked()), this, SLOT(doNewSMSSaveButton())); 37 connect(NewSMSSaveButton, SIGNAL(clicked()), this, SLOT(doNewSMSSaveButton()));
38 connect(NewSMSSendButton, SIGNAL(clicked()), this, SLOT(doNewSMSSendButton())); 38 connect(NewSMSSendButton, SIGNAL(clicked()), this, SLOT(doNewSMSSendButton()));
39 connect(ScanButton, SIGNAL(clicked()), this, SLOT(doScanButton())); 39 connect(ScanButton, SIGNAL(clicked()), this, SLOT(doScanButton()));
40 connect(TabWidget2, SIGNAL(currentChanged(QWidget *)), this, SLOT(doTabChanged())); 40 connect(TabWidget2, SIGNAL(currentChanged(QWidget*)), this, SLOT(doTabChanged()));
41 connect(SMSStoreList, SIGNAL(activated(int)), this, SLOT(doSMSStoreChanged())); 41 connect(SMSStoreList, SIGNAL(activated(int)), this, SLOT(doSMSStoreChanged()));
42 connect(SMSViewType, SIGNAL(activated(int)), this, SLOT(doSMSTypeChanged())); 42 connect(SMSViewType, SIGNAL(activated(int)), this, SLOT(doSMSTypeChanged()));
43 connect(SMSList, SIGNAL(selectionChanged(QListViewItem *)), this, SLOT(doSelectedSMSChanged(QListViewItem *))); 43 connect(SMSList, SIGNAL(selectionChanged(QListViewItem*)), this, SLOT(doSelectedSMSChanged(QListViewItem*)));
44 timerid = -1; // Is this not possible normally? 44 timerid = -1; // Is this not possible normally?
45} 45}
46 46
47/* 47/*
48 * Destroys the object and frees any allocated resources 48 * Destroys the object and frees any allocated resources
49 */ 49 */
50GSMTool::~GSMTool() 50GSMTool::~GSMTool()
51{ 51{
52 // no need to delete child widgets, Qt does it all for us 52 // no need to delete child widgets, Qt does it all for us
53 if (devicelocked) 53 if (devicelocked)
54 unlockDevice(); 54 unlockDevice();
55} 55}
56const speed_t GSMTool::baudrates[12] = { 56const speed_t GSMTool::baudrates[12] = {
57 B300, B600, B1200, B2400, B4800, B9600, B19200, 57 B300, B600, B1200, B2400, B4800, B9600, B19200,
58 B38400, B57600, B115200, B230400, B460800 58 B38400, B57600, B115200, B230400, B460800
59}; 59};
60 60
61int GSMTool::lockDevice( ) 61int GSMTool::lockDevice( )
62{ 62{
63 devicelocked = 1; 63 devicelocked = 1;
64 /* FIXME */ 64 /* FIXME */
65 return 0; 65 return 0;
66} 66}
67 67
68void GSMTool::unlockDevice( ) 68void GSMTool::unlockDevice( )
69{ 69{
70 devicelocked = 0; 70 devicelocked = 0;
71} 71}
72 72
73void GSMTool::setConnected( bool conn ) 73void GSMTool::setConnected( bool conn )
74{ 74{
75 TabWidget2->setTabEnabled(tab_2, conn); 75 TabWidget2->setTabEnabled(tab_2, conn);
76 TabWidget2->setTabEnabled(tab_3, conn); 76 TabWidget2->setTabEnabled(tab_3, conn);
77 //TabWidget2->setTabEnabled(tab_4, conn); 77 //TabWidget2->setTabEnabled(tab_4, conn);
78 NewSMSSendButton->setEnabled(conn); 78 NewSMSSendButton->setEnabled(conn);
79 MfrLabel->setEnabled(conn); 79 MfrLabel->setEnabled(conn);
80 MfrText->setEnabled(conn); 80 MfrText->setEnabled(conn);
81 ModelLabel->setEnabled(conn); 81 ModelLabel->setEnabled(conn);
82 ModelText->setEnabled(conn); 82 ModelText->setEnabled(conn);
83 RevisionLabel->setEnabled(conn); 83 RevisionLabel->setEnabled(conn);
84 RevisionText->setEnabled(conn); 84 RevisionText->setEnabled(conn);
85 SerialLabel->setEnabled(conn); 85 SerialLabel->setEnabled(conn);
86 SerialText->setEnabled(conn); 86 SerialText->setEnabled(conn);
87 87
88} 88}
89void GSMTool::doTabChanged() 89void GSMTool::doTabChanged()
90{ 90{
91 int index = TabWidget2->currentPageIndex(); 91 int index = TabWidget2->currentPageIndex();
92 qDebug("tab changed to %d", index); 92 qDebug("tab changed to %d", index);
93 93
94 if (index == 1) { 94 if (index == 1) {
95 timerid = startTimer(5000); 95 timerid = startTimer(5000);
96 timerEvent(NULL); 96 timerEvent(NULL);
97 } else if (timerid != -1) { 97 } else if (timerid != -1) {
98 killTimer(timerid); 98 killTimer(timerid);
99 timerid = -1; 99 timerid = -1;
100 } 100 }
101} 101}
102 102
103void GSMTool::timerEvent( QTimerEvent * ) 103void GSMTool::timerEvent( QTimerEvent * )
104{ 104{
105 OPInfo opi; 105 OPInfo opi;
106 106
107 opi = me->getCurrentOPInfo(); 107 opi = me->getCurrentOPInfo();
108 108
109 if (opi._numericName == NOT_SET) { 109 if (opi._numericName == NOT_SET) {
110 NetStatText->setText("No network"); 110 NetStatText->setText("No network");
111 NetworkLabel->setEnabled(FALSE); 111 NetworkLabel->setEnabled(FALSE);
112 NetworkText->setEnabled(FALSE); 112 NetworkText->setEnabled(FALSE);
113 NetworkText->setText(""); 113 NetworkText->setText("");
114 SigStrText->setEnabled(FALSE); 114 SigStrText->setEnabled(FALSE);
115 SigStrText->setText(""); 115 SigStrText->setText("");
116 dB->setEnabled(FALSE); 116 dB->setEnabled(FALSE);
117 SigStrLabel->setEnabled(FALSE); 117 SigStrLabel->setEnabled(FALSE);
118 } else { 118 } else {
119 // FIXME: Add 'roaming' info from AT+CFUN 119 // FIXME: Add 'roaming' info from AT+CFUN
120 qDebug("network"); 120 qDebug("network");
121 NetStatText->setText("Registered"); 121 NetStatText->setText("Registered");
122 NetworkLabel->setEnabled(TRUE); 122 NetworkLabel->setEnabled(TRUE);
123 NetworkText->setEnabled(TRUE); 123 NetworkText->setEnabled(TRUE);
124 NetworkText->setText(opi._longName.c_str()); 124 NetworkText->setText(opi._longName.c_str());
125 SigStrText->setEnabled(TRUE); 125 SigStrText->setEnabled(TRUE);
126 126
127 qDebug("get sig str"); 127 qDebug("get sig str");
128 int csq = me->getSignalStrength(); 128 int csq = me->getSignalStrength();
129 if (csq == 0) { 129 if (csq == 0) {
130 SigStrText->setText("<= -113"); 130 SigStrText->setText("<= -113");
131 dB->setEnabled(TRUE); 131 dB->setEnabled(TRUE);
132 SigStrLabel->setEnabled(TRUE); 132 SigStrLabel->setEnabled(TRUE);
133 } else if (csq == 99) { 133 } else if (csq == 99) {
134 SigStrText->setText("Unknown"); 134 SigStrText->setText("Unknown");
135 dB->setEnabled(FALSE); 135 dB->setEnabled(FALSE);
136 SigStrLabel->setEnabled(FALSE); 136 SigStrLabel->setEnabled(FALSE);
137 } else { 137 } else {
138 char buf[6]; 138 char buf[6];
139 sprintf(buf, "%d", -113 + (2*csq)); 139 sprintf(buf, "%d", -113 + (2*csq));
140 SigStrText->setText(buf); 140 SigStrText->setText(buf);
141 dB->setEnabled(TRUE); 141 dB->setEnabled(TRUE);
142 SigStrLabel->setEnabled(TRUE); 142 SigStrLabel->setEnabled(TRUE);
143 } 143 }
144 } 144 }
145} 145}
146 146
147void GSMTool::doSMSStoreChanged() 147void GSMTool::doSMSStoreChanged()
148{ 148{
149 const char *storename = SMSStoreList->currentText().ascii(); 149 const char *storename = SMSStoreList->currentText().ascii();
150 qDebug("Store Changed to '%s'", storename); 150 qDebug("Store Changed to '%s'", storename);
151 if (!strcmp(storename, "None")) { 151 if (!strcmp(storename, "None")) {
152 sms_store = NULL; 152 sms_store = NULL;
153 } else try { 153 } else try {
154 sms_store = new SortedSMSStore(me->getSMSStore(storename)); 154 sms_store = new SortedSMSStore(me->getSMSStore(storename));
155 sms_store->setSortOrder(ByIndex); 155 sms_store->setSortOrder(ByIndex);
156 156
157 qDebug("got store of size %d", sms_store->size()); 157 qDebug("got store of size %d", sms_store->size());
158 } catch (GsmException) { 158 } catch (GsmException) {
159 sms_store = NULL; 159 sms_store = NULL;
160 qDebug("get store failed"); 160 qDebug("get store failed");
161 } 161 }
162 162
163 SMSList->setEnabled(!(sms_store == NULL)); 163 SMSList->setEnabled(!(sms_store == NULL));
164 NewSMSSaveButton->setEnabled(!(sms_store == NULL)); 164 NewSMSSaveButton->setEnabled(!(sms_store == NULL));
165 doSMSTypeChanged(); 165 doSMSTypeChanged();
166} 166}
167 167
168void GSMTool::doSMSTypeChanged() 168void GSMTool::doSMSTypeChanged()
169{ 169{
170 int direction = SMSViewType->currentItem(); 170 int direction = SMSViewType->currentItem();
171 qDebug("direction %s\n", direction?"outgoing":"incoming"); 171 qDebug("direction %s\n", direction?"outgoing":"incoming");
172 if (direction) 172 if (direction)
173 SMSSendButton->setText("Send"); 173 SMSSendButton->setText("Send");
174 else 174 else
175 SMSSendButton->setText("Reply"); 175 SMSSendButton->setText("Reply");
176 176
177 SMSList->clear(); 177 SMSList->clear();
178 doSelectedSMSChanged(NULL); 178 doSelectedSMSChanged(NULL);
179 179
180 if (sms_store == NULL) 180 if (sms_store == NULL)
181 return; 181 return;
182 for (SortedSMSStore::iterator e = sms_store->begin(); 182 for (SortedSMSStore::iterator e = sms_store->begin();
183 e != sms_store->end(); e++) { 183 e != sms_store->end(); e++) {
184 // qDebug("Message %d", i); 184 // qDebug("Message %d", i);
185 qDebug("Is%sempty", e->empty()?" ":" not "); 185 qDebug("Is%sempty", e->empty()?" ":" not ");
186 if (e->empty()) 186 if (e->empty())
187 continue; 187 continue;
188 188
189 qDebug("Status %d", e->status()); 189 qDebug("Status %d", e->status());
190 SMSMessageRef message = e->message(); 190 SMSMessageRef message = e->message();
191 qDebug("Got message."); 191 qDebug("Got message.");
192 192
193 // qDebug(message->toString().c_str()); 193 // qDebug(message->toString().c_str());
194 if (direction == message->messageType()) { 194 if (direction == message->messageType()) {
195 qDebug("yes\n"); 195 qDebug("yes\n");
196 char buf[3]; 196 char buf[3];
197 snprintf(buf, 3, "%d", e->index()); 197 snprintf(buf, 3, "%d", e->index());
198 new QListViewItem(SMSList, message->address()._number.c_str(), message->serviceCentreTimestamp().toString().c_str(), buf); 198 new QListViewItem(SMSList, message->address()._number.c_str(), message->serviceCentreTimestamp().toString().c_str(), buf);
199 } 199 }
200 } 200 }
201} 201}
202 202
203void GSMTool::doSelectedSMSChanged(QListViewItem *item) 203void GSMTool::doSelectedSMSChanged(QListViewItem *item)
204{ 204{
205 qDebug("message changed\n"); 205 qDebug("message changed\n");
206 206
207 if (!item || sms_store == NULL) { 207 if (!item || sms_store == NULL) {
208 SMSText->setText(""); 208 SMSText->setText("");
209 SMSText->setEnabled(FALSE); 209 SMSText->setEnabled(FALSE);
210 SMSDeleteButton->setEnabled(FALSE); 210 SMSDeleteButton->setEnabled(FALSE);
211 SMSSendButton->setEnabled(FALSE); 211 SMSSendButton->setEnabled(FALSE);
212 return; 212 return;
213 } 213 }
214 /* ARGH. This sucks. Surely there's an app-private pointer in the 214 /* ARGH. This sucks. Surely there's an app-private pointer in the
215 QListViewItem that I've failed to notice? 215 QListViewItem that I've failed to notice?
216 216
217 SMSMessageRef message = *(SMSMessageRef*)item->private; 217 SMSMessageRef message = *(SMSMessageRef*)item->private;
218 */ 218 */
219 qDebug("item %p\n", item); 219 qDebug("item %p\n", item);
220 220
221 qDebug("text(2) is %s\n", item->text(2).ascii()); 221 qDebug("text(2) is %s\n", item->text(2).ascii());
222 int index = atoi(item->text(2).ascii()); 222 int index = atoi(item->text(2).ascii());
223 qDebug("index %d\n", index); 223 qDebug("index %d\n", index);
224 SMSMessageRef message = sms_store->find(index)->message(); 224 SMSMessageRef message = sms_store->find(index)->message();
225 225
226 SMSText->setText(message->userData().c_str()); 226 SMSText->setText(message->userData().c_str());
227 SMSText->setEnabled(TRUE); 227 SMSText->setEnabled(TRUE);
228 SMSDeleteButton->setEnabled(TRUE); 228 SMSDeleteButton->setEnabled(TRUE);
229 SMSSendButton->setEnabled(TRUE); 229 SMSSendButton->setEnabled(TRUE);
230 230
231} 231}
232 232
233void GSMTool::doSMSSendButton() 233void GSMTool::doSMSSendButton()
234{ 234{
235 qDebug("SMSSendButton"); 235 qDebug("SMSSendButton");
236 236
237 QListViewItem *item = SMSList->currentItem(); 237 QListViewItem *item = SMSList->currentItem();
238 if (!item) 238 if (!item)
239 return; 239 return;
240 240
241 int index = atoi(item->text(2).ascii()); 241 int index = atoi(item->text(2).ascii());
242 qDebug("index %d\n", index); 242 qDebug("index %d\n", index);
243 243
244 int direction = SMSViewType->currentItem(); 244 int direction = SMSViewType->currentItem();
245 qDebug("direction %s\n", direction?"outgoing":"incoming"); 245 qDebug("direction %s\n", direction?"outgoing":"incoming");
246 246
247 SMSMessageRef message = sms_store->find(index)->message(); 247 SMSMessageRef message = sms_store->find(index)->message();
248 248
249 if (direction) 249 if (direction)
250 NewSMSText->setText(message->userData().c_str()); 250 NewSMSText->setText(message->userData().c_str());
251 else 251 else
252 NewSMSText->setText(""); 252 NewSMSText->setText("");
253 NewSMSToBox->insertItem(message->address()._number.c_str(), 0); 253 NewSMSToBox->insertItem(message->address()._number.c_str(), 0);
254 TabWidget2->setCurrentPage(3); 254 TabWidget2->setCurrentPage(3);
255 255
256} 256}
257 257
258void GSMTool::doNewSMSClearButton() 258void GSMTool::doNewSMSClearButton()
259{ 259{
260 NewSMSText->setText(""); 260 NewSMSText->setText("");
261} 261}
262 262
263void GSMTool::doNewSMSSaveButton() 263void GSMTool::doNewSMSSaveButton()
264{ 264{
265 qDebug("NewSMSSaveButton"); 265 qDebug("NewSMSSaveButton");
266 const char *msgtext = strdup(NewSMSText->text().local8Bit()); 266 const char *msgtext = strdup(NewSMSText->text().local8Bit());
267 const char *dest = NewSMSToBox->currentText().ascii(); 267 const char *dest = NewSMSToBox->currentText().ascii();
268 268
269 NewSMSStatusLabel->setText("Sending..."); 269 NewSMSStatusLabel->setText("Sending...");
270 me->setMessageService(1); 270 me->setMessageService(1);
271 271
272 qDebug("NewSMSSendButton: '%s' to '%s'", msgtext, dest); 272 qDebug("NewSMSSendButton: '%s' to '%s'", msgtext, dest);
273 273
274 SMSMessageRef m = new SMSSubmitMessage (msgtext, dest); 274 SMSMessageRef m = new SMSSubmitMessage (msgtext, dest);
275 sms_store->insert(m); 275 sms_store->insert(m);
276 free((void *)msgtext); 276 free((void *)msgtext);
277 277
278} 278}
279void GSMTool::doNewSMSSendButton() 279void GSMTool::doNewSMSSendButton()
280{ 280{
281 const char *msgtext = strdup(NewSMSText->text().local8Bit()); 281 const char *msgtext = strdup(NewSMSText->text().local8Bit());
282 const char *dest = NewSMSToBox->currentText().ascii(); 282 const char *dest = NewSMSToBox->currentText().ascii();
283 283
284 NewSMSStatusLabel->setText("Sending..."); 284 NewSMSStatusLabel->setText("Sending...");
285 me->setMessageService(1); 285 me->setMessageService(1);
286 286
287 qDebug("NewSMSSendButton: '%s' to '%s'", msgtext, dest); 287 qDebug("NewSMSSendButton: '%s' to '%s'", msgtext, dest);
288 288
289 SMSSubmitMessage m(msgtext, dest); 289 SMSSubmitMessage m(msgtext, dest);
290 try { 290 try {
291 m.setAt(new GsmAt(*me)); 291 m.setAt(new GsmAt(*me));
292 m.send(); 292 m.send();
293 293
294 NewSMSStatusLabel->setText("Message sent."); 294 NewSMSStatusLabel->setText("Message sent.");
295 } catch (GsmException &ge) { 295 } catch (GsmException &ge) {
296 NewSMSStatusLabel->setText("Failed."); 296 NewSMSStatusLabel->setText("Failed.");
297 qDebug(ge.what()); 297 qDebug(ge.what());
298 } 298 }
299 free((void *)msgtext); 299 free((void *)msgtext);
300 300
301 301
302} 302}
303 303
304 304
305void GSMTool::doSMSDeleteButton() 305void GSMTool::doSMSDeleteButton()
306{ 306{
307 QListViewItem *item = SMSList->currentItem(); 307 QListViewItem *item = SMSList->currentItem();
308 if (!item) 308 if (!item)
309 return; 309 return;
310 310
311 int index = atoi(item->text(2).ascii()); 311 int index = atoi(item->text(2).ascii());
312 qDebug("delete SMS with index %d\n", index); 312 qDebug("delete SMS with index %d\n", index);
313 313
314 314
315 315
316 SortedSMSStore::iterator e = sms_store->find(index); 316 SortedSMSStore::iterator e = sms_store->find(index);
317 317
318 if (e != sms_store->end()) { 318 if (e != sms_store->end()) {
319 qDebug("message is %s\n", e->message()->userData().c_str()); 319 qDebug("message is %s\n", e->message()->userData().c_str());
320 sms_store->erase(e); 320 sms_store->erase(e);
321 321
322 } 322 }
323 doSMSTypeChanged(); 323 doSMSTypeChanged();
324} 324}
325 325
326void GSMTool::doScanButton() 326void GSMTool::doScanButton()
327{ 327{
328 qDebug("ScanButton"); 328 qDebug("ScanButton");
329 329
330 NetworkList->setEnabled(FALSE); 330 NetworkList->setEnabled(FALSE);
331 AvailNetsLabel->setEnabled(FALSE); 331 AvailNetsLabel->setEnabled(FALSE);
332 NetworkList->clear(); 332 NetworkList->clear();
333 new QListViewItem(NetworkList, "Scanning..."); 333 new QListViewItem(NetworkList, "Scanning...");
334 334
335 vector<OPInfo> opis; 335 vector<OPInfo> opis;
336 336
337 try { 337 try {
338 opis = me->getAvailableOPInfo(); 338 opis = me->getAvailableOPInfo();
339 } catch (GsmException) { 339 } catch (GsmException) {
340 NetworkList->clear(); 340 NetworkList->clear();
341 new QListViewItem(NetworkList, "Scan failed..."); 341 new QListViewItem(NetworkList, "Scan failed...");
342 return; 342 return;
343 } 343 }
344 344
345 NetworkList->clear(); 345 NetworkList->clear();
346 for (vector<OPInfo>::iterator i = opis.begin(); i != opis.end(); ++i) { 346 for (vector<OPInfo>::iterator i = opis.begin(); i != opis.end(); ++i) {
347 char *statustext; 347 char *statustext;
348 switch (i->_status) { 348 switch (i->_status) {
349 349
350 case UnknownOPStatus: 350 case UnknownOPStatus:
351 statustext = "unknown"; 351 statustext = "unknown";
352 break; 352 break;
353 353
354 case CurrentOPStatus: 354 case CurrentOPStatus:
355 statustext = "current"; 355 statustext = "current";
356 break; 356 break;
357 357
358 case AvailableOPStatus: 358 case AvailableOPStatus:
359 statustext = "available"; 359 statustext = "available";
360 break; 360 break;
361 361
362 case ForbiddenOPStatus: 362 case ForbiddenOPStatus:
363 statustext = "forbidden"; 363 statustext = "forbidden";
364 break; 364 break;
365 365
366 default: 366 default:
367 statustext = "(ERROR)"; 367 statustext = "(ERROR)";
368 } 368 }
369 char num[7]; 369 char num[7];
370 snprintf(num, 6, "%d", i->_numericName); 370 snprintf(num, 6, "%d", i->_numericName);
371 new QListViewItem(NetworkList, i->_longName.c_str(), statustext, num, i->_shortName.c_str()); 371 new QListViewItem(NetworkList, i->_longName.c_str(), statustext, num, i->_shortName.c_str());
372 } 372 }
373 NetworkList->setEnabled(TRUE); 373 NetworkList->setEnabled(TRUE);
374 AvailNetsLabel->setEnabled(TRUE); 374 AvailNetsLabel->setEnabled(TRUE);
375} 375}
376/* 376/*
377 * A simple slot... not very interesting. 377 * A simple slot... not very interesting.
378 */ 378 */
379void GSMTool::doConnectButton() 379void GSMTool::doConnectButton()
380{ 380{
381 gsmlib::Port *port; 381 gsmlib::Port *port;
382 382
383 speed_t rate; 383 speed_t rate;
384 devicename = strdup(DeviceName->currentText().local8Bit().data()); 384 devicename = strdup(DeviceName->currentText().local8Bit().data());
385 rate = baudrates[BaudRate->currentItem()]; 385 rate = baudrates[BaudRate->currentItem()];
386 386
387 qDebug("Connect Button Pressed"); 387 qDebug("Connect Button Pressed");
388 MfrText->setText("Opening..."); 388 MfrText->setText("Opening...");
389 ModelText->setText(""); 389 ModelText->setText("");
390 RevisionText->setText(""); 390 RevisionText->setText("");
391 SerialText->setText(""); 391 SerialText->setText("");
392 392
393 setConnected(FALSE); 393 setConnected(FALSE);
394 if (me) { 394 if (me) {
395 me = NULL; 395 me = NULL;
396 } 396 }
397 397
398 if (lockDevice()) { 398 if (lockDevice()) {
399 qDebug("lockDevice() failed\n"); 399 qDebug("lockDevice() failed\n");
400 MfrText->setText("Lock port failed"); 400 MfrText->setText("Lock port failed");
401 }; 401 };
402 402
403 qDebug("Device name is %s\n", devicename); 403 qDebug("Device name is %s\n", devicename);
404 404
405 try { 405 try {
406 port = new UnixSerialPort(devicename, rate, DEFAULT_INIT_STRING, 0); 406 port = new UnixSerialPort(devicename, rate, DEFAULT_INIT_STRING, 0);
407 } catch (GsmException) { 407 } catch (GsmException) {
408 qDebug("port failed"); 408 qDebug("port failed");
409 MfrText->setText("Open port failed"); 409 MfrText->setText("Open port failed");
410 return; 410 return;
411 } 411 }
412 MfrText->setText("Initialising..."); 412 MfrText->setText("Initialising...");
413 qDebug("got port"); 413 qDebug("got port");
414 try { 414 try {
415 me = new MeTa(port); 415 me = new MeTa(port);
416 } catch (GsmException) { 416 } catch (GsmException) {
417 qDebug("meta failed"); 417 qDebug("meta failed");
418 MfrText->setText("Initialise GSM unit failed"); 418 MfrText->setText("Initialise GSM unit failed");
419 me = NULL; 419 me = NULL;
420 unlockDevice(); 420 unlockDevice();
421 return; 421 return;
422 } 422 }
423 423
424 qDebug("Opened"); 424 qDebug("Opened");
425 425
426 MEInfo ifo; 426 MEInfo ifo;
427 427
428 MfrText->setText("Querying..."); 428 MfrText->setText("Querying...");
429 429
430 try { 430 try {
431 ifo = me->getMEInfo(); 431 ifo = me->getMEInfo();
432 } catch (GsmException) { 432 } catch (GsmException) {
433 qDebug("getMEInfo failed"); 433 qDebug("getMEInfo failed");
434 MfrText->setText("Query GSM unit failed"); 434 MfrText->setText("Query GSM unit failed");
435 me = NULL; 435 me = NULL;
436 unlockDevice(); 436 unlockDevice();
437 return; 437 return;
438 } 438 }
439 439
440 MfrText->setText(ifo._manufacturer.c_str()); 440 MfrText->setText(ifo._manufacturer.c_str());
441 ModelText->setText(ifo._model.c_str()); 441 ModelText->setText(ifo._model.c_str());
442 RevisionText->setText(ifo._revision.c_str()); 442 RevisionText->setText(ifo._revision.c_str());
443 SerialText->setText(ifo._serialNumber.c_str()); 443 SerialText->setText(ifo._serialNumber.c_str());
444 setConnected(TRUE); 444 setConnected(TRUE);
445 445
446 SMSStoreList->clear(); 446 SMSStoreList->clear();
447 SMSStoreList->insertItem("None"); 447 SMSStoreList->insertItem("None");
448 448
449 vector<string> storenames = me->getSMSStoreNames(); 449 vector<string> storenames = me->getSMSStoreNames();
450 450
451 for (vector<string>::iterator i = storenames.begin(); i != storenames.end(); ++i) { 451 for (vector<string>::iterator i = storenames.begin(); i != storenames.end(); ++i) {
452 SMSStoreList->insertItem(i->c_str()); 452 SMSStoreList->insertItem(i->c_str());
453 } 453 }
454 SMSList->clear(); 454 SMSList->clear();
455 SMSText->setText(""); 455 SMSText->setText("");
456 sms_store = NULL; 456 sms_store = NULL;
457} 457}
diff --git a/noncore/unsupported/mail2/bend/bend.cpp b/noncore/unsupported/mail2/bend/bend.cpp
index e2ece2a..ab6eb45 100644
--- a/noncore/unsupported/mail2/bend/bend.cpp
+++ b/noncore/unsupported/mail2/bend/bend.cpp
@@ -1,124 +1,124 @@
1#include <qlayout.h> 1#include <qlayout.h>
2#include <qpixmap.h> 2#include <qpixmap.h>
3#include <qlabel.h> 3#include <qlabel.h>
4#include <qsound.h> 4#include <qsound.h>
5#include <qtimer.h> 5#include <qtimer.h>
6#include <qdir.h> 6#include <qdir.h>
7 7
8#include <qpe/qcopenvelope_qws.h> 8#include <qpe/qcopenvelope_qws.h>
9#include <qpe/resource.h> 9#include <qpe/resource.h>
10#include <qpe/config.h> 10#include <qpe/config.h>
11 11
12#include <opie/odevice.h> 12#include <opie/odevice.h>
13 13
14#include "imapresponse.h" 14#include "imapresponse.h"
15#include "imaphandler.h" 15#include "imaphandler.h"
16#include "configfile.h" 16#include "configfile.h"
17#include "bend.h" 17#include "bend.h"
18 18
19using namespace Opie; 19using namespace Opie;
20 20
21BenD::BenD(QWidget *parent, const char *name, WFlags fl) 21BenD::BenD(QWidget *parent, const char *name, WFlags fl)
22 : QButton(parent, name, fl) 22 : QButton(parent, name, fl)
23{ 23{
24 _config = new Config("mail"); 24 _config = new Config("mail");
25 _config->setGroup("Settings"); 25 _config->setGroup("Settings");
26 26
27 QVBoxLayout *layout = new QVBoxLayout(this); 27 QVBoxLayout *layout = new QVBoxLayout(this);
28 layout->addItem(new QSpacerItem(0,0)); 28 layout->addItem(new QSpacerItem(0,0));
29 29
30 QLabel *pixmap = new QLabel(this); 30 QLabel *pixmap = new QLabel(this);
31 pixmap->setPixmap(Resource::loadPixmap("mail/mailchecker")); 31 pixmap->setPixmap(Resource::loadPixmap("mail/mailchecker"));
32 layout->addWidget(pixmap); 32 layout->addWidget(pixmap);
33 33
34 layout->addItem(new QSpacerItem(0,0)); 34 layout->addItem(new QSpacerItem(0,0));
35 35
36 hide(); 36 hide();
37 37
38 connect(this, SIGNAL(clicked()), SLOT(slotClicked())); 38 connect(this, SIGNAL(clicked()), SLOT(slotClicked()));
39 39
40 if (!_config->readBoolEntry("Disabled", false)) { 40 if (!_config->readBoolEntry("Disabled", false)) {
41 _intervalMs = _config->readNumEntry("CheckEvery", 5) * 60000; 41 _intervalMs = _config->readNumEntry("CheckEvery", 5) * 60000;
42 _intervalTimer = new QTimer(); 42 _intervalTimer = new QTimer();
43 _intervalTimer->start(_intervalMs); 43 _intervalTimer->start(_intervalMs);
44 connect(_intervalTimer, SIGNAL(timeout()), SLOT(slotCheck())); 44 connect(_intervalTimer, SIGNAL(timeout()), SLOT(slotCheck()));
45 45
46 QTimer::singleShot(0, this, SLOT(slotCheck())); 46 QTimer::singleShot(0, this, SLOT(slotCheck()));
47 } 47 }
48} 48}
49 49
50void BenD::drawButton(QPainter *) { } 50void BenD::drawButton(QPainter *) { }
51void BenD::drawButtonText(QPainter *) { } 51void BenD::drawButtonText(QPainter *) { }
52 52
53void BenD::slotClicked() 53void BenD::slotClicked()
54{ 54{
55 QCopEnvelope e("QPE/System", "execute(QString)"); 55 QCopEnvelope e("QPE/System", "execute(QString)");
56 e << QString("mail"); 56 e << QString("mail");
57 57
58 ODevice *device = ODevice::inst(); 58 ODevice *device = ODevice::inst();
59 if ( !device-> ledList ( ). isEmpty ( )) { 59 if ( !device-> ledList ( ). isEmpty ( )) {
60 OLed led = ( device-> ledList ( ). contains ( Led_Mail )) ? Led_Mail : device-> ledList ( ) [0]; 60 OLed led = ( device-> ledList ( ). contains ( Led_Mail )) ? Led_Mail : device-> ledList ( ) [0];
61 61
62 device->setLedState(led, Led_Off); 62 device->setLedState(led, Led_Off);
63 } 63 }
64} 64}
65 65
66void BenD::slotCheck() 66void BenD::slotCheck()
67{ 67{
68 // Check wether the check interval has been changed. 68 // Check wether the check interval has been changed.
69 int newIntervalMs = _config->readNumEntry("CheckEvery", 5) * 60000; 69 int newIntervalMs = _config->readNumEntry("CheckEvery", 5) * 60000;
70 if (newIntervalMs != _intervalMs) { 70 if (newIntervalMs != _intervalMs) {
71 _intervalTimer->changeInterval(newIntervalMs); 71 _intervalTimer->changeInterval(newIntervalMs);
72 _intervalMs = newIntervalMs; 72 _intervalMs = newIntervalMs;
73#ifndef QT_NO_DEBUG 73#ifndef QT_NO_DEBUG
74 qWarning("BenD: Detected interval change"); 74 qWarning("BenD: Detected interval change");
75#endif 75#endif
76 } 76 }
77 77
78 QValueList<Account> acList = ConfigFile::getAccounts(); 78 QValueList<Account> acList = ConfigFile::getAccounts();
79 QValueList<Account>::Iterator ot; 79 QValueList<Account>::Iterator ot;
80 for (ot = acList.begin(); ot != acList.end(); ot++) { 80 for (ot = acList.begin(); ot != acList.end(); ot++) {
81 if (!((*ot).imapServer().isEmpty() || 81 if (!((*ot).imapServer().isEmpty() ||
82 (*ot).imapPort().isEmpty() || 82 (*ot).imapPort().isEmpty() ||
83 (*ot).user().isEmpty() || 83 (*ot).user().isEmpty() ||
84 (*ot).pass().isEmpty())) { 84 (*ot).pass().isEmpty())) {
85 if (!((*ot).imapSsl() && 85 if (!((*ot).imapSsl() &&
86 (*ot).imapSslPort().isEmpty())) { 86 (*ot).imapSslPort().isEmpty())) {
87 IMAPHandler *handler = new IMAPHandler(*ot); 87 IMAPHandler *handler = new IMAPHandler(*ot);
88 handler->iStatus("INBOX", "RECENT"); 88 handler->iStatus("INBOX", "RECENT");
89 connect(handler, SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPStatus(IMAPResponse &))); 89 connect(handler, SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPStatus(IMAPResponse&)));
90 } 90 }
91 } 91 }
92 } 92 }
93} 93}
94 94
95void BenD::slotIMAPStatus(IMAPResponse &response) 95void BenD::slotIMAPStatus(IMAPResponse &response)
96{ 96{
97 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPStatus(IMAPResponse &))); 97 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPStatus(IMAPResponse&)));
98 98
99 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 99 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
100 if (response.STATUS()[0].recent().toInt() > 0) { 100 if (response.STATUS()[0].recent().toInt() > 0) {
101 ODevice *device = ODevice::inst(); 101 ODevice *device = ODevice::inst();
102 if (isHidden()) show(); 102 if (isHidden()) show();
103 if (_config->readBoolEntry("BlinkLed", true)) { 103 if (_config->readBoolEntry("BlinkLed", true)) {
104 if ( !device-> ledList ( ). isEmpty ( )) { 104 if ( !device-> ledList ( ). isEmpty ( )) {
105 OLed led = ( device-> ledList ( ). contains ( Led_Mail )) ? Led_Mail : device-> ledList ( ) [0]; 105 OLed led = ( device-> ledList ( ). contains ( Led_Mail )) ? Led_Mail : device-> ledList ( ) [0];
106 106
107 device->setLedState(led, device-> ledStateList ( led ). contains ( Led_BlinkSlow ) ? Led_BlinkSlow : Led_On ); 107 device->setLedState(led, device-> ledStateList ( led ). contains ( Led_BlinkSlow ) ? Led_BlinkSlow : Led_On );
108 } 108 }
109 } 109 }
110 if (_config->readBoolEntry("PlaySound", false)) 110 if (_config->readBoolEntry("PlaySound", false))
111 device->alarmSound(); 111 device->alarmSound();
112 } else { 112 } else {
113 ODevice *device = ODevice::inst(); 113 ODevice *device = ODevice::inst();
114 if (!isHidden()) hide(); 114 if (!isHidden()) hide();
115 if ( !device-> ledList ( ). isEmpty ( )) { 115 if ( !device-> ledList ( ). isEmpty ( )) {
116 OLed led = ( device-> ledList ( ). contains ( Led_Mail )) ? Led_Mail : device-> ledList ( ) [0]; 116 OLed led = ( device-> ledList ( ). contains ( Led_Mail )) ? Led_Mail : device-> ledList ( ) [0];
117 117
118 device->setLedState(led, Led_Off); 118 device->setLedState(led, Led_Off);
119 } 119 }
120 } 120 }
121 response.imapHandler()->iLogout(); 121 response.imapHandler()->iLogout();
122 } else qWarning("BenD: WARNING: Couldn't retrieve INBOX status."); 122 } else qWarning("BenD: WARNING: Couldn't retrieve INBOX status.");
123} 123}
124 124
diff --git a/noncore/unsupported/mail2/composer.cpp b/noncore/unsupported/mail2/composer.cpp
index cb80299..da1aee9 100644
--- a/noncore/unsupported/mail2/composer.cpp
+++ b/noncore/unsupported/mail2/composer.cpp
@@ -1,420 +1,420 @@
1#include <qmultilineedit.h> 1#include <qmultilineedit.h>
2#include <qmessagebox.h> 2#include <qmessagebox.h>
3#include <qpopupmenu.h> 3#include <qpopupmenu.h>
4#include <qcombobox.h> 4#include <qcombobox.h>
5#include <qlineedit.h> 5#include <qlineedit.h>
6#include <qaction.h> 6#include <qaction.h>
7#include <qtimer.h> 7#include <qtimer.h>
8#include <qlabel.h> 8#include <qlabel.h>
9#include <qapplication.h> 9#include <qapplication.h>
10 10
11#include <qpe/resource.h> 11#include <qpe/resource.h>
12#include <qpe/config.h> 12#include <qpe/config.h>
13 13
14#include <opie/ofiledialog.h> 14#include <opie/ofiledialog.h>
15 15
16#include "mailstatusbar.h" 16#include "mailstatusbar.h"
17#include "addresspicker.h" 17#include "addresspicker.h"
18#include "listviewplus.h" 18#include "listviewplus.h"
19#include "smtphandler.h" 19#include "smtphandler.h"
20#include "composer.h" 20#include "composer.h"
21#include "rename.h" 21#include "rename.h"
22 22
23AttachViewItem::AttachViewItem(QListView *parent, Attachment &attachment) 23AttachViewItem::AttachViewItem(QListView *parent, Attachment &attachment)
24 : QListViewItem(parent), _attachment(attachment) 24 : QListViewItem(parent), _attachment(attachment)
25{ 25{
26 setPixmap(0, _attachment.docLnk().pixmap().isNull() ? Resource::loadPixmap("UnknownDocument-14") : _attachment.docLnk().pixmap()); 26 setPixmap(0, _attachment.docLnk().pixmap().isNull() ? Resource::loadPixmap("UnknownDocument-14") : _attachment.docLnk().pixmap());
27 setText(0, _attachment.newName().isEmpty() ? _attachment.fileName() : _attachment.newName()); 27 setText(0, _attachment.newName().isEmpty() ? _attachment.fileName() : _attachment.newName());
28 setText(1, _attachment.description()); 28 setText(1, _attachment.description());
29} 29}
30 30
31Composer::Composer(QWidget *parent, const char *name, WFlags fl, bool sendQueue) 31Composer::Composer(QWidget *parent, const char *name, WFlags fl, bool sendQueue)
32 : ComposerBase(parent, name, fl), _inLoop(false) 32 : ComposerBase(parent, name, fl), _inLoop(false)
33{ 33{
34 _sendQueued = sendQueue; 34 _sendQueued = sendQueue;
35 status->setStopEnabled(false); 35 status->setStopEnabled(false);
36 to->setFocus(); 36 to->setFocus();
37 37
38 connect(sendmail, SIGNAL(activated()), SLOT(slotSendMail())); 38 connect(sendmail, SIGNAL(activated()), SLOT(slotSendMail()));
39 connect(queuemail, SIGNAL(activated()), SLOT(slotQueueMail())); 39 connect(queuemail, SIGNAL(activated()), SLOT(slotQueueMail()));
40 connect(addressbook, SIGNAL(activated()), SLOT(slotOpenAddressPicker())); 40 connect(addressbook, SIGNAL(activated()), SLOT(slotOpenAddressPicker()));
41 connect(addattach, SIGNAL(activated()), SLOT(slotAddAttach())); 41 connect(addattach, SIGNAL(activated()), SLOT(slotAddAttach()));
42 connect(delattach, SIGNAL(activated()), SLOT(slotDelAttach())); 42 connect(delattach, SIGNAL(activated()), SLOT(slotDelAttach()));
43 43
44 connect(from, SIGNAL(activated(int)), SLOT(slotFromChanged(int))); 44 connect(from, SIGNAL(activated(int)), SLOT(slotFromChanged(int)));
45 45
46 connect(attachPopup, SIGNAL(activated(int)), SLOT(slotPopupHandler(int))); 46 connect(attachPopup, SIGNAL(activated(int)), SLOT(slotPopupHandler(int)));
47 47
48 QTimer::singleShot(0, this, SLOT(slotFillStuff())); 48 QTimer::singleShot(0, this, SLOT(slotFillStuff()));
49 QTimer::singleShot(0, this, SLOT(slotResizing())); 49 QTimer::singleShot(0, this, SLOT(slotResizing()));
50 50
51} 51}
52 52
53Composer::~Composer() 53Composer::~Composer()
54{ 54{
55 hide(); 55 hide();
56} 56}
57 57
58void Composer::hide() 58void Composer::hide()
59{ 59{
60 QWidget::hide(); 60 QWidget::hide();
61 61
62 if (_inLoop) { 62 if (_inLoop) {
63 _inLoop = false; 63 _inLoop = false;
64 qApp->exit_loop(); 64 qApp->exit_loop();
65 } 65 }
66} 66}
67 67
68void Composer::exec() 68void Composer::exec()
69{ 69{
70 show(); 70 show();
71 if (!_inLoop) { 71 if (!_inLoop) {
72 _inLoop = true; 72 _inLoop = true;
73 qApp->enter_loop(); 73 qApp->enter_loop();
74 } 74 }
75} 75}
76 76
77void Composer::setSendMail(SendMail &sendMail) 77void Composer::setSendMail(SendMail &sendMail)
78{ 78{
79 to->setText(sendMail.to()); 79 to->setText(sendMail.to());
80 cc->setText(sendMail.cc()); 80 cc->setText(sendMail.cc());
81 bcc->setText(sendMail.bcc()); 81 bcc->setText(sendMail.bcc());
82 subject->setText(sendMail.subject()); 82 subject->setText(sendMail.subject());
83 message->setText(sendMail.message()); 83 message->setText(sendMail.message());
84 _inReplyTo = sendMail.inReplyTo(); 84 _inReplyTo = sendMail.inReplyTo();
85 85
86 QValueList<Attachment> attachments = sendMail.attachments(); 86 QValueList<Attachment> attachments = sendMail.attachments();
87 QValueList<Attachment>::Iterator it; 87 QValueList<Attachment>::Iterator it;
88 for (it = attachments.begin(); it != attachments.end(); it++) { 88 for (it = attachments.begin(); it != attachments.end(); it++) {
89 (void) new AttachViewItem(attachView, *it); 89 (void) new AttachViewItem(attachView, *it);
90 if (attachView->isHidden()) attachView->show(); 90 if (attachView->isHidden()) attachView->show();
91 } 91 }
92} 92}
93 93
94void Composer::slotResizing() 94void Composer::slotResizing()
95{ 95{
96 from->setMaximumWidth(width() - fromBox->width()); 96 from->setMaximumWidth(width() - fromBox->width());
97 from->resize(width() - fromBox->width(), y()); 97 from->resize(width() - fromBox->width(), y());
98 if (_sendQueued) slotSendQueued(); 98 if (_sendQueued) slotSendQueued();
99} 99}
100 100
101void Composer::slotPopupHandler(int itemid) 101void Composer::slotPopupHandler(int itemid)
102{ 102{
103 if (attachView->currentItem() == NULL) { 103 if (attachView->currentItem() == NULL) {
104 QMessageBox::information(this, tr("Error"), tr("Please select an entry first."), tr("Ok")); 104 QMessageBox::information(this, tr("Error"), tr("Please select an entry first."), tr("Ok"));
105 return; 105 return;
106 } 106 }
107 107
108 if (itemid == POPUP_ATTACH_RENAME) { 108 if (itemid == POPUP_ATTACH_RENAME) {
109 QString tmp = Rename::rename(attachView->currentItem()->text(0), this); 109 QString tmp = Rename::rename(attachView->currentItem()->text(0), this);
110 if (tmp != QString(0)) attachView->currentItem()->setText(0, tmp); 110 if (tmp != QString(0)) attachView->currentItem()->setText(0, tmp);
111 } else if (itemid == POPUP_ATTACH_DESC) { 111 } else if (itemid == POPUP_ATTACH_DESC) {
112 QString tmp = Rename::getText(tr("Set Description"), tr("<div align=center>Description"), this); 112 QString tmp = Rename::getText(tr("Set Description"), tr("<div align=center>Description"), this);
113 if (tmp != QString(0)) attachView->currentItem()->setText(1, tmp); 113 if (tmp != QString(0)) attachView->currentItem()->setText(1, tmp);
114 } else if (itemid == POPUP_ATTACH_REMOVE) { 114 } else if (itemid == POPUP_ATTACH_REMOVE) {
115 attachView->takeItem(attachView->currentItem()); 115 attachView->takeItem(attachView->currentItem());
116 } 116 }
117} 117}
118 118
119void Composer::slotSendMail() 119void Composer::slotSendMail()
120{ 120{
121 if (to->text().find(QRegExp(".*\\@.*\\..*")) == -1) { 121 if (to->text().find(QRegExp(".*\\@.*\\..*")) == -1) {
122 QMessageBox::information(this, tr("Error"), tr("<p>You have to specify a recipient.<br>(eg: foo@bar.org)</p>"), tr("Ok")); 122 QMessageBox::information(this, tr("Error"), tr("<p>You have to specify a recipient.<br>(eg: foo@bar.org)</p>"), tr("Ok"));
123 return; 123 return;
124 } 124 }
125 125
126 SendMail smail; 126 SendMail smail;
127 smail.setFrom(from->currentText()); 127 smail.setFrom(from->currentText());
128 smail.setReplyTo(replyto->text()); 128 smail.setReplyTo(replyto->text());
129 smail.setTo(to->text()); 129 smail.setTo(to->text());
130 smail.setCc(cc->text()); 130 smail.setCc(cc->text());
131 smail.setBcc(bcc->text()); 131 smail.setBcc(bcc->text());
132 smail.setSubject(subject->text()); 132 smail.setSubject(subject->text());
133 smail.setMessage(message->text()); 133 smail.setMessage(message->text());
134 smail.setNeedsMime(attachView->childCount() == 0 ? false : true); 134 smail.setNeedsMime(attachView->childCount() == 0 ? false : true);
135 smail.setAccount(accountsLoaded[from->currentItem()]); 135 smail.setAccount(accountsLoaded[from->currentItem()]);
136 136
137 if (priority->currentItem() == POPUP_PRIO_LOW) { 137 if (priority->currentItem() == POPUP_PRIO_LOW) {
138 smail.setPriority("Low");// No i18n on purpose 138 smail.setPriority("Low");// No i18n on purpose
139 } else if (priority->currentItem() == POPUP_PRIO_NORMAL) { 139 } else if (priority->currentItem() == POPUP_PRIO_NORMAL) {
140 smail.setPriority("Normal");// No i18n on purpose 140 smail.setPriority("Normal");// No i18n on purpose
141 } else if (priority->currentItem() == POPUP_PRIO_HIGH) { 141 } else if (priority->currentItem() == POPUP_PRIO_HIGH) {
142 smail.setPriority("High");// No i18n on purpose 142 smail.setPriority("High");// No i18n on purpose
143 } 143 }
144 144
145 QValueList<Attachment> attachments; 145 QValueList<Attachment> attachments;
146 QListViewItem *item; 146 QListViewItem *item;
147 for (item = attachView->firstChild(); item != 0; item = item->itemBelow()) { 147 for (item = attachView->firstChild(); item != 0; item = item->itemBelow()) {
148 attachments.append(((AttachViewItem *)item)->attachment()); 148 attachments.append(((AttachViewItem *)item)->attachment());
149 } 149 }
150 150
151 smail.setAttachments(attachments); 151 smail.setAttachments(attachments);
152 152
153 QString header, message; 153 QString header, message;
154 MailFactory::genMail(header, message, smail, this); 154 MailFactory::genMail(header, message, smail, this);
155 if (header.isNull() || message.isNull()) return;// Aborted. 155 if (header.isNull() || message.isNull()) return;// Aborted.
156 156
157 status->setStopEnabled(true); 157 status->setStopEnabled(true);
158 158
159 SmtpHandler *handler = new SmtpHandler(header, message, accountsLoaded[from->currentItem()], to->text()); 159 SmtpHandler *handler = new SmtpHandler(header, message, accountsLoaded[from->currentItem()], to->text());
160 connect(handler, SIGNAL(finished()), SLOT(slotSendFinished())); 160 connect(handler, SIGNAL(finished()), SLOT(slotSendFinished()));
161 connect(handler, SIGNAL(error(const QString &)), SLOT(slotSendError(const QString &))); 161 connect(handler, SIGNAL(error(const QString&)), SLOT(slotSendError(const QString&)));
162 connect(handler, SIGNAL(status(const QString &)), status, SLOT(setStatusText(const QString &))); 162 connect(handler, SIGNAL(status(const QString&)), status, SLOT(setStatusText(const QString&)));
163} 163}
164 164
165void Composer::slotSendQueued() 165void Composer::slotSendQueued()
166{ 166{
167 int effSendCount = 0; 167 int effSendCount = 0;
168 qDebug("Sending queued messages"); 168 qDebug("Sending queued messages");
169 Config cfg( "mailqueue", Config::User ); 169 Config cfg( "mailqueue", Config::User );
170 cfg.setGroup( "Settings" ); 170 cfg.setGroup( "Settings" );
171 _sendCount = 0; 171 _sendCount = 0;
172 _sendError = 0; 172 _sendError = 0;
173 _toSend = cfg.readNumEntry( "count", 0 ); 173 _toSend = cfg.readNumEntry( "count", 0 );
174 174
175 if (_toSend == 0) close(); 175 if (_toSend == 0) close();
176 176
177 qDebug("%i messages to send", _toSend); 177 qDebug("%i messages to send", _toSend);
178 QString str; 178 QString str;
179 for (int i=1;i<=_toSend;i++) 179 for (int i=1;i<=_toSend;i++)
180 { 180 {
181 qDebug("sending message %i",i); 181 qDebug("sending message %i",i);
182 cfg.setGroup( "Mail_" + QString::number(i) ); 182 cfg.setGroup( "Mail_" + QString::number(i) );
183 SendMail smail; 183 SendMail smail;
184 str = cfg.readEntry("from"); 184 str = cfg.readEntry("from");
185 qDebug("setFrom %s",str.latin1()); 185 qDebug("setFrom %s",str.latin1());
186 smail.setFrom( str ); 186 smail.setFrom( str );
187 str = cfg.readEntry("reply"); 187 str = cfg.readEntry("reply");
188 qDebug("setReplyTo %s",str.latin1()); 188 qDebug("setReplyTo %s",str.latin1());
189 smail.setReplyTo( str ); 189 smail.setReplyTo( str );
190 QString toAdr = cfg.readEntry("to"); 190 QString toAdr = cfg.readEntry("to");
191 qDebug("to %s",toAdr.latin1()); 191 qDebug("to %s",toAdr.latin1());
192 smail.setTo( toAdr ); //to->text()); 192 smail.setTo( toAdr ); //to->text());
193 str = cfg.readEntry("cc"); 193 str = cfg.readEntry("cc");
194 qDebug("setCc %s",str.latin1()); 194 qDebug("setCc %s",str.latin1());
195 smail.setCc( str ); //cc->text()); 195 smail.setCc( str ); //cc->text());
196 smail.setBcc( cfg.readEntry("bcc") ); //bcc->text()); 196 smail.setBcc( cfg.readEntry("bcc") ); //bcc->text());
197 str = cfg.readEntry("subject"); 197 str = cfg.readEntry("subject");
198 qDebug("setSubject %s",str.latin1()); 198 qDebug("setSubject %s",str.latin1());
199 smail.setSubject( str ); //subject->text()); 199 smail.setSubject( str ); //subject->text());
200 str = cfg.readEntryCrypt("message"); 200 str = cfg.readEntryCrypt("message");
201 qDebug("setMessage %s",str.latin1()); 201 qDebug("setMessage %s",str.latin1());
202 smail.setMessage( str ); //message->text()); 202 smail.setMessage( str ); //message->text());
203 smail.setNeedsMime( cfg.readBoolEntry("mime") ); //attachView->childCount() == 0 ? false : true); 203 smail.setNeedsMime( cfg.readBoolEntry("mime") ); //attachView->childCount() == 0 ? false : true);
204 204
205 qDebug("setting account [%i]",cfg.readNumEntry("account")); 205 qDebug("setting account [%i]",cfg.readNumEntry("account"));
206 Account accnt = accountsLoaded[ cfg.readNumEntry("account") ]; 206 Account accnt = accountsLoaded[ cfg.readNumEntry("account") ];
207 smail.setAccount( accnt ); //accountsLoaded[from->currentItem()]); 207 smail.setAccount( accnt ); //accountsLoaded[from->currentItem()]);
208 208
209 209
210 int prio = cfg.readNumEntry( "priority" ); 210 int prio = cfg.readNumEntry( "priority" );
211 qDebug("setting priority %i",prio); 211 qDebug("setting priority %i",prio);
212 if (prio == POPUP_PRIO_LOW) { 212 if (prio == POPUP_PRIO_LOW) {
213 smail.setPriority("Low");// No i18n on purpose 213 smail.setPriority("Low");// No i18n on purpose
214 } else if (prio == POPUP_PRIO_NORMAL) { 214 } else if (prio == POPUP_PRIO_NORMAL) {
215 smail.setPriority("Normal");// No i18n on purpose 215 smail.setPriority("Normal");// No i18n on purpose
216 } else if (prio == POPUP_PRIO_HIGH) { 216 } else if (prio == POPUP_PRIO_HIGH) {
217 smail.setPriority("High");// No i18n on purpose 217 smail.setPriority("High");// No i18n on purpose
218 } 218 }
219 219
220 QValueList<Attachment> attachments; 220 QValueList<Attachment> attachments;
221 Attachment a; 221 Attachment a;
222 QString an; 222 QString an;
223 223
224 int ac = cfg.readNumEntry( "attachments", 0 ); 224 int ac = cfg.readNumEntry( "attachments", 0 );
225 qDebug("%i Attachments",ac); 225 qDebug("%i Attachments",ac);
226 for (int j = 0; i < ac; ac++) { 226 for (int j = 0; i < ac; ac++) {
227 an = "Attachment_" + QString::number( j ); 227 an = "Attachment_" + QString::number( j );
228 qDebug(an.latin1()); 228 qDebug(an.latin1());
229 a.setFileName(cfg.readEntry( an + "fileName" )); 229 a.setFileName(cfg.readEntry( an + "fileName" ));
230 a.setNewName(cfg.readEntry( an + "newName" )); 230 a.setNewName(cfg.readEntry( an + "newName" ));
231 a.setDescription(cfg.readEntry( an + "description" )); 231 a.setDescription(cfg.readEntry( an + "description" ));
232 a.setDocLnk( DocLnk( cfg.readEntry( an + "docLnk" )) ); 232 a.setDocLnk( DocLnk( cfg.readEntry( an + "docLnk" )) );
233 attachments.append( a ); 233 attachments.append( a );
234 } 234 }
235 235
236 smail.setAttachments(attachments); 236 smail.setAttachments(attachments);
237 237
238 qDebug("putting mail together"); 238 qDebug("putting mail together");
239 239
240 QString header, message; 240 QString header, message;
241 MailFactory::genMail(header, message, smail, this); 241 MailFactory::genMail(header, message, smail, this);
242 if (header.isNull() || message.isNull()) continue;//return;// Aborted. 242 if (header.isNull() || message.isNull()) continue;//return;// Aborted.
243 243
244 // abort->setEnabled(true); 244 // abort->setEnabled(true);
245 245
246 qDebug("Sending to %s",toAdr.latin1()); 246 qDebug("Sending to %s",toAdr.latin1());
247 SmtpHandler *handler = new SmtpHandler(header, message, accnt ,toAdr); 247 SmtpHandler *handler = new SmtpHandler(header, message, accnt ,toAdr);
248 effSendCount++; 248 effSendCount++;
249 connect(handler, SIGNAL(finished()), SLOT(slotSendQueuedFinished())); 249 connect(handler, SIGNAL(finished()), SLOT(slotSendQueuedFinished()));
250 connect(handler, SIGNAL(error(const QString &)), SLOT(slotSendQueuedError(const QString &))); 250 connect(handler, SIGNAL(error(const QString&)), SLOT(slotSendQueuedError(const QString&)));
251 connect(handler, SIGNAL(status(const QString &)), status, SLOT(setStatusText(const QString &))); 251 connect(handler, SIGNAL(status(const QString&)), status, SLOT(setStatusText(const QString&)));
252 252
253 } 253 }
254 if (effSendCount < _toSend) 254 if (effSendCount < _toSend)
255 { 255 {
256 _toSend = effSendCount; 256 _toSend = effSendCount;
257 QMessageBox::information(this, tr("Error"), tr("<p>There was a problem sending some of the queued mails.</p>"), tr("Ok")); 257 QMessageBox::information(this, tr("Error"), tr("<p>There was a problem sending some of the queued mails.</p>"), tr("Ok"));
258 } 258 }
259} 259}
260 260
261void Composer::slotQueueMail() 261void Composer::slotQueueMail()
262{ 262{
263 if (to->text().find(QRegExp(".*\\@.*\\..*")) == -1) { 263 if (to->text().find(QRegExp(".*\\@.*\\..*")) == -1) {
264 QMessageBox::information(this, tr("Error"), tr("<p>You have to specify a recipient.<br>(eg: foo@bar.org)</p>"), tr("Ok")); 264 QMessageBox::information(this, tr("Error"), tr("<p>You have to specify a recipient.<br>(eg: foo@bar.org)</p>"), tr("Ok"));
265 return; 265 return;
266 } 266 }
267 267
268 Config cfg( "mailqueue", Config::User ); 268 Config cfg( "mailqueue", Config::User );
269 269
270 cfg.setGroup( "Settings" ); 270 cfg.setGroup( "Settings" );
271 int count = cfg.readNumEntry( "count", 0 ); 271 int count = cfg.readNumEntry( "count", 0 );
272 count++; 272 count++;
273 cfg.writeEntry( "count", count ); 273 cfg.writeEntry( "count", count );
274 qDebug("queueing mail %i",count); 274 qDebug("queueing mail %i",count);
275 275
276 cfg.setGroup( "Mail_" + QString::number( count )); 276 cfg.setGroup( "Mail_" + QString::number( count ));
277 cfg.writeEntry( "from", from->currentText() ); 277 cfg.writeEntry( "from", from->currentText() );
278 cfg.writeEntry( "reply", replyto->text()); 278 cfg.writeEntry( "reply", replyto->text());
279 cfg.writeEntry( "to", to->text()); 279 cfg.writeEntry( "to", to->text());
280 cfg.writeEntry( "cc", cc->text()); 280 cfg.writeEntry( "cc", cc->text());
281 cfg.writeEntry( "bcc", bcc->text()); 281 cfg.writeEntry( "bcc", bcc->text());
282 cfg.writeEntry( "subject", subject->text()); 282 cfg.writeEntry( "subject", subject->text());
283 cfg.writeEntryCrypt( "message", message->text()); 283 cfg.writeEntryCrypt( "message", message->text());
284 cfg.writeEntry( "mime", attachView->childCount() == 0 ); 284 cfg.writeEntry( "mime", attachView->childCount() == 0 );
285 cfg.writeEntry( "account", from->currentItem()); 285 cfg.writeEntry( "account", from->currentItem());
286 cfg.writeEntry( "priority", priority->currentItem() ); 286 cfg.writeEntry( "priority", priority->currentItem() );
287 cfg.writeEntry( "attachments", attachView->childCount() ); 287 cfg.writeEntry( "attachments", attachView->childCount() );
288 288
289 Attachment a; 289 Attachment a;
290 QListViewItem *item; 290 QListViewItem *item;
291 QString an; 291 QString an;
292 int i = 0; 292 int i = 0;
293 for (item = attachView->firstChild(); item != 0; item = item->itemBelow()) { 293 for (item = attachView->firstChild(); item != 0; item = item->itemBelow()) {
294 a = ((AttachViewItem *)item)->attachment(); 294 a = ((AttachViewItem *)item)->attachment();
295 an = "Attachment_" + QString::number( i++ ); 295 an = "Attachment_" + QString::number( i++ );
296 cfg.writeEntry( an + "fileName", a.fileName() ); 296 cfg.writeEntry( an + "fileName", a.fileName() );
297 cfg.writeEntry( an + "newName", a.newName() ); 297 cfg.writeEntry( an + "newName", a.newName() );
298 cfg.writeEntry( an + "description", a.description() ); 298 cfg.writeEntry( an + "description", a.description() );
299 cfg.writeEntry( an + "docLnk", a.docLnk().file() ); 299 cfg.writeEntry( an + "docLnk", a.docLnk().file() );
300 } 300 }
301 301
302 QMessageBox::information(this, tr("Success"), tr("<p>The mail was queued successfully.</p><p>The queue contains ")+QString::number(count)+tr(" mails.</p>"), tr("Ok")); 302 QMessageBox::information(this, tr("Success"), tr("<p>The mail was queued successfully.</p><p>The queue contains ")+QString::number(count)+tr(" mails.</p>"), tr("Ok"));
303 303
304} 304}
305 305
306void Composer::slotSendError(const QString &error) 306void Composer::slotSendError(const QString &error)
307{ 307{
308 status->setStatusText(tr("<font color=#ff0000>Error occoured during sending.</font>")); 308 status->setStatusText(tr("<font color=#ff0000>Error occoured during sending.</font>"));
309 QMessageBox::warning(this, tr("Error"), tr("<p>%1</p").arg(error), tr("Ok")); 309 QMessageBox::warning(this, tr("Error"), tr("<p>%1</p").arg(error), tr("Ok"));
310} 310}
311 311
312void Composer::slotSendQueuedError(const QString &error) 312void Composer::slotSendQueuedError(const QString &error)
313{ 313{
314 _sendError++; 314 _sendError++;
315 qDebug("error send mail %i",_sendCount); 315 qDebug("error send mail %i",_sendCount);
316 status->setStatusText(tr("<font color=#ff0000>Error occoured during sending.</font>")); 316 status->setStatusText(tr("<font color=#ff0000>Error occoured during sending.</font>"));
317 QMessageBox::warning(this, tr("Error"), tr("<p>%1</p").arg(error), tr("Ok")); 317 QMessageBox::warning(this, tr("Error"), tr("<p>%1</p").arg(error), tr("Ok"));
318} 318}
319 319
320void Composer::slotSendFinished() 320void Composer::slotSendFinished()
321{ 321{
322 QMessageBox::information(this, tr("Success"), tr("<p>The mail was sent successfully.</p>"), tr("Ok")); 322 QMessageBox::information(this, tr("Success"), tr("<p>The mail was sent successfully.</p>"), tr("Ok"));
323 323
324 status->setStatusText(QString(0)); 324 status->setStatusText(QString(0));
325 status->setStopEnabled(false); 325 status->setStopEnabled(false);
326} 326}
327 327
328void Composer::slotSendQueuedFinished() 328void Composer::slotSendQueuedFinished()
329{ 329{
330 330
331 _sendCount++; 331 _sendCount++;
332 qDebug("finished send mail %i of %i (error %i)",_sendCount,_toSend,_sendError); 332 qDebug("finished send mail %i of %i (error %i)",_sendCount,_toSend,_sendError);
333 if (_sendCount < _toSend) return; 333 if (_sendCount < _toSend) return;
334 if (_sendError == _toSend) close(); 334 if (_sendError == _toSend) close();
335 QMessageBox::information(this, tr("Success"), tr("<p>The queued mails ")+QString::number(_toSend-_sendError)+tr(" of ")+QString::number(_toSend)+(" were sent successfully.</p>"), tr("Ok")); 335 QMessageBox::information(this, tr("Success"), tr("<p>The queued mails ")+QString::number(_toSend-_sendError)+tr(" of ")+QString::number(_toSend)+(" were sent successfully.</p>"), tr("Ok"));
336 Config cfg( "mailqueue", Config::User ); 336 Config cfg( "mailqueue", Config::User );
337 cfg.setGroup( "Settings" ); 337 cfg.setGroup( "Settings" );
338 cfg.writeEntry( "count", 0 ); 338 cfg.writeEntry( "count", 0 );
339 for (int i=1;i<=_sendCount;i++) 339 for (int i=1;i<=_sendCount;i++)
340 { 340 {
341 cfg.setGroup( "Mail_" + QString::number(i) ); 341 cfg.setGroup( "Mail_" + QString::number(i) );
342 qDebug("remove mail %i", i); 342 qDebug("remove mail %i", i);
343 cfg.clearGroup(); 343 cfg.clearGroup();
344 cfg.removeEntry( "Mail_" + QString::number(i) ); 344 cfg.removeEntry( "Mail_" + QString::number(i) );
345 } 345 }
346 close(); 346 close();
347} 347}
348 348
349void Composer::slotFillStuff() 349void Composer::slotFillStuff()
350{ 350{
351 QValueList<Account> accounts = ConfigFile::getAccounts(); 351 QValueList<Account> accounts = ConfigFile::getAccounts();
352 int i = 0; 352 int i = 0;
353 353
354 QValueList<Account>::Iterator it; 354 QValueList<Account>::Iterator it;
355 for (it = accounts.begin(); it != accounts.end(); it++) { 355 for (it = accounts.begin(); it != accounts.end(); it++) {
356 if (!(*it).email().isEmpty() && !(*it).smtpServer().isEmpty() && !(*it).smtpPort().isEmpty()) { 356 if (!(*it).email().isEmpty() && !(*it).smtpServer().isEmpty() && !(*it).smtpPort().isEmpty()) {
357 if (!(*it).realName().isEmpty()) 357 if (!(*it).realName().isEmpty())
358 from->insertItem((*it).realName() + " <" + (*it).email() + ">", i); 358 from->insertItem((*it).realName() + " <" + (*it).email() + ">", i);
359 else 359 else
360 from->insertItem((*it).email()); 360 from->insertItem((*it).email());
361 361
362 accountsLoaded.append(*it); 362 accountsLoaded.append(*it);
363 i++; 363 i++;
364 } 364 }
365 } 365 }
366} 366}
367 367
368void Composer::slotFromChanged(int id) 368void Composer::slotFromChanged(int id)
369{ 369{
370 Account account = accountsLoaded[id]; 370 Account account = accountsLoaded[id];
371 371
372 if (account.defaultCc()) cc->setText(account.cc()); 372 if (account.defaultCc()) cc->setText(account.cc());
373 if (account.defaultBcc()) bcc->setText(account.bcc()); 373 if (account.defaultBcc()) bcc->setText(account.bcc());
374 if (account.defaultReplyTo()) replyto->setText(account.replyTo()); 374 if (account.defaultReplyTo()) replyto->setText(account.replyTo());
375 if (!account.signature().isEmpty()) 375 if (!account.signature().isEmpty())
376 message->setText(message->text() + "\n\n-- \n" + account.signature()); 376 message->setText(message->text() + "\n\n-- \n" + account.signature());
377} 377}
378 378
379void Composer::slotOpenAddressPicker() 379void Composer::slotOpenAddressPicker()
380{ 380{
381 if (!to->isHidden() && cc->isHidden() && bcc->isHidden()) { 381 if (!to->isHidden() && cc->isHidden() && bcc->isHidden()) {
382 if (to->text().isEmpty()) { 382 if (to->text().isEmpty()) {
383 to->setText(AddressPicker::getNames()); 383 to->setText(AddressPicker::getNames());
384 } else { 384 } else {
385 to->setText(to->text() + ", " + AddressPicker::getNames()); 385 to->setText(to->text() + ", " + AddressPicker::getNames());
386 } 386 }
387 } else if (to->isHidden() && !cc->isHidden() && bcc->isHidden()) { 387 } else if (to->isHidden() && !cc->isHidden() && bcc->isHidden()) {
388 if (cc->text().isEmpty()) { 388 if (cc->text().isEmpty()) {
389 cc->setText(AddressPicker::getNames()); 389 cc->setText(AddressPicker::getNames());
390 } else { 390 } else {
391 cc->setText(cc->text() + ", " + AddressPicker::getNames()); 391 cc->setText(cc->text() + ", " + AddressPicker::getNames());
392 } 392 }
393 } else if (to->isHidden() && cc->isHidden() && !bcc->isHidden()) { 393 } else if (to->isHidden() && cc->isHidden() && !bcc->isHidden()) {
394 if (bcc->text().isEmpty()) { 394 if (bcc->text().isEmpty()) {
395 bcc->setText(AddressPicker::getNames()); 395 bcc->setText(AddressPicker::getNames());
396 } else { 396 } else {
397 bcc->setText(bcc->text() + ", " + AddressPicker::getNames()); 397 bcc->setText(bcc->text() + ", " + AddressPicker::getNames());
398 } 398 }
399 } 399 }
400} 400}
401 401
402void Composer::slotAddAttach() 402void Composer::slotAddAttach()
403{ 403{
404 DocLnk lnk = OFileDialog::getOpenFileName( 1,"/"); 404 DocLnk lnk = OFileDialog::getOpenFileName( 1,"/");
405 //DocLnk lnk = AttachDiag::getFile(this); 405 //DocLnk lnk = AttachDiag::getFile(this);
406 if (lnk.name().isEmpty()) return; 406 if (lnk.name().isEmpty()) return;
407 407
408 Attachment attachment; 408 Attachment attachment;
409 attachment.setFileName(lnk.file()); 409 attachment.setFileName(lnk.file());
410 attachment.setNewName(lnk.name()); 410 attachment.setNewName(lnk.name());
411 attachment.setDocLnk(lnk); 411 attachment.setDocLnk(lnk);
412 412
413 (void) new AttachViewItem(attachView, attachment); 413 (void) new AttachViewItem(attachView, attachment);
414} 414}
415 415
416void Composer::slotDelAttach() 416void Composer::slotDelAttach()
417{ 417{
418 if (attachView->currentItem() == NULL) return; 418 if (attachView->currentItem() == NULL) return;
419 attachView->takeItem(attachView->currentItem()); 419 attachView->takeItem(attachView->currentItem());
420} 420}
diff --git a/noncore/unsupported/mail2/folderwidget.cpp b/noncore/unsupported/mail2/folderwidget.cpp
index d27968b..a0520b1 100644
--- a/noncore/unsupported/mail2/folderwidget.cpp
+++ b/noncore/unsupported/mail2/folderwidget.cpp
@@ -1,314 +1,314 @@
1#include <qmessagebox.h> 1#include <qmessagebox.h>
2#include <qtextstream.h> 2#include <qtextstream.h>
3#include <qpopupmenu.h> 3#include <qpopupmenu.h>
4#include <qheader.h> 4#include <qheader.h>
5#include <qfile.h> 5#include <qfile.h>
6#include <qdir.h> 6#include <qdir.h>
7 7
8#include <qpe/resource.h> 8#include <qpe/resource.h>
9 9
10#include <stdlib.h> 10#include <stdlib.h>
11 11
12#include "folderwidget.h" 12#include "folderwidget.h"
13#include "imaphandler.h" 13#include "imaphandler.h"
14#include "imapbase.h" 14#include "imapbase.h"
15#include "rename.h" 15#include "rename.h"
16 16
17FolderWidgetItem::FolderWidgetItem(Folder &folder, QListView *parent) 17FolderWidgetItem::FolderWidgetItem(Folder &folder, QListView *parent)
18 : QListViewItem(parent), _folder(folder) 18 : QListViewItem(parent), _folder(folder)
19{ 19{
20 setPixmap(0, QPixmap(Resource::loadPixmap("mail/inbox"))); 20 setPixmap(0, QPixmap(Resource::loadPixmap("mail/inbox")));
21 setText(0, _folder.topFolder().account().user() + " (" + _folder.topFolder().account().imapServer() + ")"); 21 setText(0, _folder.topFolder().account().user() + " (" + _folder.topFolder().account().imapServer() + ")");
22 setOpen(true); 22 setOpen(true);
23} 23}
24 24
25FolderWidgetItem::FolderWidgetItem(Folder &folder, FolderWidgetItem *parent) 25FolderWidgetItem::FolderWidgetItem(Folder &folder, FolderWidgetItem *parent)
26 : QListViewItem(parent), _folder(folder) 26 : QListViewItem(parent), _folder(folder)
27{ 27{
28 if (_folder.noCache()) { 28 if (_folder.noCache()) {
29 setText(0, QObject::tr("<Foldertree not known.>")); 29 setText(0, QObject::tr("<Foldertree not known.>"));
30 } else { 30 } else {
31 if (folder.fullName().upper() == "INBOX") { 31 if (folder.fullName().upper() == "INBOX") {
32 setPixmap(0, QPixmap(Resource::loadPixmap("mail/inbox"))); 32 setPixmap(0, QPixmap(Resource::loadPixmap("mail/inbox")));
33 setText(0, QObject::tr("Inbox")); 33 setText(0, QObject::tr("Inbox"));
34 } else { 34 } else {
35 setPixmap(0, QPixmap(Resource::loadPixmap("mail/folder"))); 35 setPixmap(0, QPixmap(Resource::loadPixmap("mail/folder")));
36 setText(0, folder.fullName()); 36 setText(0, folder.fullName());
37 } 37 }
38 setOpen(true); 38 setOpen(true);
39 } 39 }
40} 40}
41 41
42FolderWidget::FolderWidget(QWidget *parent, const char *name, WFlags fl) 42FolderWidget::FolderWidget(QWidget *parent, const char *name, WFlags fl)
43 : ListViewPlus(parent, name, fl) 43 : ListViewPlus(parent, name, fl)
44{ 44{
45 header()->hide(); 45 header()->hide();
46 addColumn(""); 46 addColumn("");
47 setSorting(-1); 47 setSorting(-1);
48 48
49 QPopupMenu *menu = new QPopupMenu(); 49 QPopupMenu *menu = new QPopupMenu();
50 menu->insertItem(tr("Rename"), MENU_RENAME); 50 menu->insertItem(tr("Rename"), MENU_RENAME);
51 menu->insertItem(tr("Delete"), MENU_DELETE); 51 menu->insertItem(tr("Delete"), MENU_DELETE);
52 menu->insertItem(tr("Move"), MENU_MOVE); 52 menu->insertItem(tr("Move"), MENU_MOVE);
53 menu->insertItem(tr("Copy"), MENU_COPY); 53 menu->insertItem(tr("Copy"), MENU_COPY);
54 menu->insertSeparator(); 54 menu->insertSeparator();
55 menu->insertItem(tr("Create folder"), MENU_CREATE); 55 menu->insertItem(tr("Create folder"), MENU_CREATE);
56 menu->insertSeparator(); 56 menu->insertSeparator();
57 menu->insertItem(tr("Rescan folder list"), MENU_RESCAN); 57 menu->insertItem(tr("Rescan folder list"), MENU_RESCAN);
58 setPopup(menu); 58 setPopup(menu);
59 59
60 getAccounts(); 60 getAccounts();
61 61
62 connect(menu, SIGNAL(activated(int)), SLOT(slotMenuActivated(int))); 62 connect(menu, SIGNAL(activated(int)), SLOT(slotMenuActivated(int)));
63 connect(this, SIGNAL(clicked(QListViewItem *)), SLOT(slotItemClicked(QListViewItem *))); 63 connect(this, SIGNAL(clicked(QListViewItem*)), SLOT(slotItemClicked(QListViewItem*)));
64} 64}
65 65
66FolderWidget::~FolderWidget() 66FolderWidget::~FolderWidget()
67{ 67{
68 // TODO: Save folder tree. 68 // TODO: Save folder tree.
69} 69}
70 70
71void FolderWidget::update() 71void FolderWidget::update()
72{ 72{
73 getAccounts(); 73 getAccounts();
74} 74}
75 75
76void FolderWidget::getAccounts() 76void FolderWidget::getAccounts()
77{ 77{
78 clear(); 78 clear();
79 79
80 QValueList<Account> accounts = ConfigFile::getAccounts(); 80 QValueList<Account> accounts = ConfigFile::getAccounts();
81 QValueList<Account>::Iterator it; 81 QValueList<Account>::Iterator it;
82 for (it = accounts.begin(); it != accounts.end(); it++) { 82 for (it = accounts.begin(); it != accounts.end(); it++) {
83 FolderWidgetItem *item = addAccount(*it); 83 FolderWidgetItem *item = addAccount(*it);
84 QFile f((QString) getenv("HOME") + "/Applications/mail/foldercache/foldercache-" + (*it).accountName()); 84 QFile f((QString) getenv("HOME") + "/Applications/mail/foldercache/foldercache-" + (*it).accountName());
85 if (!f.open(IO_ReadOnly)) { 85 if (!f.open(IO_ReadOnly)) {
86 Folder folder; 86 Folder folder;
87 folder.setNoCache(true); 87 folder.setNoCache(true);
88 addFolder(folder, item); 88 addFolder(folder, item);
89 } else { 89 } else {
90 QTextStream t(&f); 90 QTextStream t(&f);
91 while (!t.atEnd()) { 91 while (!t.atEnd()) {
92 QString separator = t.readLine(); 92 QString separator = t.readLine();
93 QString fullname = t.readLine(); 93 QString fullname = t.readLine();
94 Folder folder; 94 Folder folder;
95 folder.setSeparator(separator); 95 folder.setSeparator(separator);
96 folder.setFullName(fullname); 96 folder.setFullName(fullname);
97 folder.setTopFolder(item->folder().topFolder()); 97 folder.setTopFolder(item->folder().topFolder());
98 addFolder(folder, item); 98 addFolder(folder, item);
99 } 99 }
100 f.close(); 100 f.close();
101 } 101 }
102 } 102 }
103} 103}
104 104
105FolderWidgetItem *FolderWidget::addAccount(Account &account) 105FolderWidgetItem *FolderWidget::addAccount(Account &account)
106{ 106{
107 TopFolder tf; 107 TopFolder tf;
108 tf.setAccount(account); 108 tf.setAccount(account);
109 109
110 // XXX This has to change!!! The folderwidget may not create an 110 // XXX This has to change!!! The folderwidget may not create an
111 // XXX IMAPHandler!!!! Do this in IMAPHandler! 111 // XXX IMAPHandler!!!! Do this in IMAPHandler!
112 tf.setIMAPHandler(new IMAPHandler(account)); 112 tf.setIMAPHandler(new IMAPHandler(account));
113 113
114 Folder folder; 114 Folder folder;
115 folder.setTopFolder(tf); 115 folder.setTopFolder(tf);
116 116
117 connect(tf.handler(), SIGNAL(IMAPLookingUpHost()), SLOT(slotIMAPLookingUpHost())); 117 connect(tf.handler(), SIGNAL(IMAPLookingUpHost()), SLOT(slotIMAPLookingUpHost()));
118 connect(tf.handler(), SIGNAL(IMAPHostFound()), SLOT(slotIMAPHostFound())); 118 connect(tf.handler(), SIGNAL(IMAPHostFound()), SLOT(slotIMAPHostFound()));
119 connect(tf.handler(), SIGNAL(IMAPConnected()), SLOT(slotIMAPConnected())); 119 connect(tf.handler(), SIGNAL(IMAPConnected()), SLOT(slotIMAPConnected()));
120 connect(tf.handler(), SIGNAL(IMAPDisconnected()), SLOT(slotIMAPDisconnected())); 120 connect(tf.handler(), SIGNAL(IMAPDisconnected()), SLOT(slotIMAPDisconnected()));
121 connect(tf.handler(), SIGNAL(IMAPError(int)), SLOT(slotIMAPError(int))); 121 connect(tf.handler(), SIGNAL(IMAPError(int)), SLOT(slotIMAPError(int)));
122 122
123 return new FolderWidgetItem(folder, this); 123 return new FolderWidgetItem(folder, this);
124} 124}
125 125
126FolderWidgetItem *FolderWidget::addFolder(Folder &folder, FolderWidgetItem *folderWidgetItem) 126FolderWidgetItem *FolderWidget::addFolder(Folder &folder, FolderWidgetItem *folderWidgetItem)
127{ 127{
128 return new FolderWidgetItem(folder, folderWidgetItem); 128 return new FolderWidgetItem(folder, folderWidgetItem);
129} 129}
130 130
131void FolderWidget::slotMenuActivated(int itemid) 131void FolderWidget::slotMenuActivated(int itemid)
132{ 132{
133 if (currentItem() == NULL) { 133 if (currentItem() == NULL) {
134 QMessageBox::information(this, tr("Error"), tr("<p>Please select an item first.</p>"), tr("Ok")); 134 QMessageBox::information(this, tr("Error"), tr("<p>Please select an item first.</p>"), tr("Ok"));
135 return; 135 return;
136 } 136 }
137 137
138 if (itemid == MENU_RENAME) { 138 if (itemid == MENU_RENAME) {
139 if (((FolderWidgetItem *)currentItem())->folder().fullName().isEmpty()) return; 139 if (((FolderWidgetItem *)currentItem())->folder().fullName().isEmpty()) return;
140 140
141 Folder folder = ((FolderWidgetItem *)currentItem())->folder(); 141 Folder folder = ((FolderWidgetItem *)currentItem())->folder();
142 QString newName = Rename::rename(folder.fullName(), this); 142 QString newName = Rename::rename(folder.fullName(), this);
143 if (newName.isNull()) return; 143 if (newName.isNull()) return;
144 144
145 folder.topFolder().handler()->iRename(folder.fullName(), newName); 145 folder.topFolder().handler()->iRename(folder.fullName(), newName);
146 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPRename(IMAPResponse &))); 146 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPRename(IMAPResponse&)));
147 } else if (itemid == MENU_DELETE) { 147 } else if (itemid == MENU_DELETE) {
148 if (((FolderWidgetItem *)currentItem())->folder().fullName().isEmpty()) return; 148 if (((FolderWidgetItem *)currentItem())->folder().fullName().isEmpty()) return;
149 149
150 Folder folder = ((FolderWidgetItem *)currentItem())->folder(); 150 Folder folder = ((FolderWidgetItem *)currentItem())->folder();
151 151
152 int ret = QMessageBox::information(this, tr("Question"), tr("<p>Do you really want to delete <pre>%1</pre>?").arg(folder.fullName()), tr("Yes"), tr("No")); 152 int ret = QMessageBox::information(this, tr("Question"), tr("<p>Do you really want to delete <pre>%1</pre>?").arg(folder.fullName()), tr("Yes"), tr("No"));
153 if (ret == 1) return; 153 if (ret == 1) return;
154 154
155 _createFolder = folder; 155 _createFolder = folder;
156 156
157 folder.topFolder().handler()->iDelete(folder.fullName()); 157 folder.topFolder().handler()->iDelete(folder.fullName());
158 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPDelete(IMAPResponse &))); 158 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPDelete(IMAPResponse&)));
159 } else if (itemid == MENU_MOVE) { 159 } else if (itemid == MENU_MOVE) {
160 160
161 } else if (itemid == MENU_COPY) { 161 } else if (itemid == MENU_COPY) {
162 162
163 } else if (itemid == MENU_CREATE) { 163 } else if (itemid == MENU_CREATE) {
164 Folder folder = (((FolderWidgetItem *)currentItem())->folder()); 164 Folder folder = (((FolderWidgetItem *)currentItem())->folder());
165 _createFolder = folder; 165 _createFolder = folder;
166 166
167 QString folderName = Rename::getText(tr("Foldername"), tr("<p>Please enter the name of the new folder.</p>"), this); 167 QString folderName = Rename::getText(tr("Foldername"), tr("<p>Please enter the name of the new folder.</p>"), this);
168 if (folderName.isNull()) return; 168 if (folderName.isNull()) return;
169 169
170 folder.topFolder().handler()->iCreate(folder.fullName() + folder.separator() + folderName); 170 folder.topFolder().handler()->iCreate(folder.fullName() + folder.separator() + folderName);
171 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPCreate(IMAPResponse &))); 171 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPCreate(IMAPResponse&)));
172 } else if (itemid == MENU_RESCAN) { 172 } else if (itemid == MENU_RESCAN) {
173 Folder folder = (((FolderWidgetItem *)currentItem())->folder()); 173 Folder folder = (((FolderWidgetItem *)currentItem())->folder());
174 _rescanAccount = folder.topFolder().account(); 174 _rescanAccount = folder.topFolder().account();
175 175
176 folder.topFolder().handler()->iList("", "*"); 176 folder.topFolder().handler()->iList("", "*");
177 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPList(IMAPResponse &))); 177 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPList(IMAPResponse&)));
178 } 178 }
179} 179}
180 180
181void FolderWidget::slotItemClicked(QListViewItem *item) 181void FolderWidget::slotItemClicked(QListViewItem *item)
182{ 182{
183 if (item == NULL) return; 183 if (item == NULL) return;
184 Folder folder = ((FolderWidgetItem *)item)->folder(); 184 Folder folder = ((FolderWidgetItem *)item)->folder();
185 if (folder.fullName().isEmpty()) return; 185 if (folder.fullName().isEmpty()) return;
186 186
187 emit folderSelected(folder); 187 emit folderSelected(folder);
188} 188}
189 189
190void FolderWidget::slotIMAPLookingUpHost() 190void FolderWidget::slotIMAPLookingUpHost()
191{ 191{
192 emit status(tr("Looking up host...")); 192 emit status(tr("Looking up host..."));
193 emit connecting(); 193 emit connecting();
194} 194}
195 195
196void FolderWidget::slotIMAPHostFound() 196void FolderWidget::slotIMAPHostFound()
197{ 197{
198 emit status(tr("Host found.")); 198 emit status(tr("Host found."));
199} 199}
200 200
201void FolderWidget::slotIMAPConnected() 201void FolderWidget::slotIMAPConnected()
202{ 202{
203 emit status(tr("Connected to host.")); 203 emit status(tr("Connected to host."));
204 emit connected(); 204 emit connected();
205} 205}
206 206
207void FolderWidget::slotIMAPError(int error) 207void FolderWidget::slotIMAPError(int error)
208{ 208{
209 if (error == IMAPBase::IMAPErrConnectionRefused) { 209 if (error == IMAPBase::IMAPErrConnectionRefused) {
210 QMessageBox::warning(this, tr("Error"), tr("<p>The IMAP connection was refused.</p>"), tr("Ok")); 210 QMessageBox::warning(this, tr("Error"), tr("<p>The IMAP connection was refused.</p>"), tr("Ok"));
211 } else if (error == IMAPBase::IMAPErrHostNotFound) { 211 } else if (error == IMAPBase::IMAPErrHostNotFound) {
212 QMessageBox::warning(this, tr("Error"), tr("<p>The host was not found.</p>"), tr("Ok")); 212 QMessageBox::warning(this, tr("Error"), tr("<p>The host was not found.</p>"), tr("Ok"));
213 } else if (error == IMAPBase::IMAPErrSocketRead) { 213 } else if (error == IMAPBase::IMAPErrSocketRead) {
214 QMessageBox::warning(this, tr("Error"), tr("<p>There was an error while reading from the socket.</p>"), tr("Ok")); 214 QMessageBox::warning(this, tr("Error"), tr("<p>There was an error while reading from the socket.</p>"), tr("Ok"));
215 } else if (error == IMAPBase::IMAPErrLoginFailed) { 215 } else if (error == IMAPBase::IMAPErrLoginFailed) {
216 QMessageBox::warning(this, tr("Error"), tr("<p>Login failed. Check your password/username.</p>"), tr("Ok")); 216 QMessageBox::warning(this, tr("Error"), tr("<p>Login failed. Check your password/username.</p>"), tr("Ok"));
217 } else { 217 } else {
218 QMessageBox::warning(this, tr("Error"), tr("<p>An unknown error was encountered.</p>"), tr("Ok")); 218 QMessageBox::warning(this, tr("Error"), tr("<p>An unknown error was encountered.</p>"), tr("Ok"));
219 } 219 }
220} 220}
221 221
222void FolderWidget::slotIMAPDisconnected() 222void FolderWidget::slotIMAPDisconnected()
223{ 223{
224 emit status(tr("Disconnected.")); 224 emit status(tr("Disconnected."));
225 emit disconnected(); 225 emit disconnected();
226} 226}
227 227
228void FolderWidget::slotIMAPLogin(IMAPResponse &response) 228void FolderWidget::slotIMAPLogin(IMAPResponse &response)
229{ 229{
230 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPLogin(IMAPResponse &))); 230 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPLogin(IMAPResponse&)));
231 231
232 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 232 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
233 emit status(tr("Login successful!")); 233 emit status(tr("Login successful!"));
234 } else { 234 } else {
235 QMessageBox::warning(this, tr("Error"), tr("<p>Login failed. Go away.</p>"), tr("Ok")); 235 QMessageBox::warning(this, tr("Error"), tr("<p>Login failed. Go away.</p>"), tr("Ok"));
236 } 236 }
237} 237}
238 238
239void FolderWidget::slotIMAPRename(IMAPResponse &response) 239void FolderWidget::slotIMAPRename(IMAPResponse &response)
240{ 240{
241 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPRename(IMAPResponse &))); 241 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPRename(IMAPResponse&)));
242 242
243 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 243 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
244 emit status(tr("Renaming successful!")); 244 emit status(tr("Renaming successful!"));
245 } else { 245 } else {
246 QMessageBox::warning(this, tr("Error"), tr("<p>Renaming failed. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok")); 246 QMessageBox::warning(this, tr("Error"), tr("<p>Renaming failed. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok"));
247 } 247 }
248} 248}
249 249
250void FolderWidget::slotIMAPDelete(IMAPResponse &response) 250void FolderWidget::slotIMAPDelete(IMAPResponse &response)
251{ 251{
252 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPDelete(IMAPResponse &))); 252 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPDelete(IMAPResponse&)));
253 253
254 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 254 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
255 emit status(tr("Deletion successful!")); 255 emit status(tr("Deletion successful!"));
256 256
257 _rescanAccount = _createFolder.topFolder().account(); 257 _rescanAccount = _createFolder.topFolder().account();
258 258
259 _createFolder.topFolder().handler()->iList(".", "*"); 259 _createFolder.topFolder().handler()->iList(".", "*");
260 connect(_createFolder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPList(IMAPResponse &))); 260 connect(_createFolder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPList(IMAPResponse&)));
261 } else { 261 } else {
262 QMessageBox::warning(this, tr("Error"), tr("<p>Delete failed. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok")); 262 QMessageBox::warning(this, tr("Error"), tr("<p>Delete failed. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok"));
263 } 263 }
264} 264}
265 265
266void FolderWidget::slotIMAPCreate(IMAPResponse &response) 266void FolderWidget::slotIMAPCreate(IMAPResponse &response)
267{ 267{
268 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPCreate(IMAPResponse &))); 268 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPCreate(IMAPResponse&)));
269 269
270 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 270 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
271 emit status(tr("Folder created. Rescanning...")); 271 emit status(tr("Folder created. Rescanning..."));
272 272
273 _rescanAccount = _createFolder.topFolder().account(); 273 _rescanAccount = _createFolder.topFolder().account();
274 274
275 _createFolder.topFolder().handler()->iList(".", "*"); 275 _createFolder.topFolder().handler()->iList(".", "*");
276 connect(_createFolder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPList(IMAPResponse &))); 276 connect(_createFolder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPList(IMAPResponse&)));
277 } else { 277 } else {
278 QMessageBox::warning(this, tr("Error"), tr("<p>The folder could not be created. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok")); 278 QMessageBox::warning(this, tr("Error"), tr("<p>The folder could not be created. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok"));
279 } 279 }
280} 280}
281 281
282void FolderWidget::slotIMAPList(IMAPResponse &response) 282void FolderWidget::slotIMAPList(IMAPResponse &response)
283{ 283{
284 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPList(IMAPResponse &))); 284 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPList(IMAPResponse&)));
285 285
286 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 286 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
287 QDir d((QString) getenv("HOME") + "/Applications/mail/foldercache"); 287 QDir d((QString) getenv("HOME") + "/Applications/mail/foldercache");
288 if (!d.exists()) { 288 if (!d.exists()) {
289 system("mkdir -p $HOME/Applications/mail/foldercache"); 289 system("mkdir -p $HOME/Applications/mail/foldercache");
290 qWarning("Created $HOME/Applications/mail/foldercache."); 290 qWarning("Created $HOME/Applications/mail/foldercache.");
291 } 291 }
292 QFile f((QString) getenv("HOME") + "/Applications/mail/foldercache/foldercache-" + _rescanAccount.accountName()); 292 QFile f((QString) getenv("HOME") + "/Applications/mail/foldercache/foldercache-" + _rescanAccount.accountName());
293 if (!f.open(IO_WriteOnly)) { 293 if (!f.open(IO_WriteOnly)) {
294 QMessageBox::critical(this, tr("Error"), tr("<p>Couldn't open folder cache file for writing!</p>"), tr("Ok")); 294 QMessageBox::critical(this, tr("Error"), tr("<p>Couldn't open folder cache file for writing!</p>"), tr("Ok"));
295 return; 295 return;
296 } 296 }
297 QTextStream t(&f); 297 QTextStream t(&f);
298 298
299 QValueList<IMAPResponseLIST>::Iterator it; 299 QValueList<IMAPResponseLIST>::Iterator it;
300 QValueList<IMAPResponseLIST> lists = response.LIST(); 300 QValueList<IMAPResponseLIST> lists = response.LIST();
301 for (it = lists.begin(); it != lists.end(); it++) { 301 for (it = lists.begin(); it != lists.end(); it++) {
302 t << (*it).folderSeparator() << "\n"; 302 t << (*it).folderSeparator() << "\n";
303 t << (*it).folder() << "\n"; 303 t << (*it).folder() << "\n";
304 } 304 }
305 305
306 f.close(); 306 f.close();
307 307
308 emit status(tr("Got folder list.")); 308 emit status(tr("Got folder list."));
309 getAccounts(); 309 getAccounts();
310 } else { 310 } else {
311 QMessageBox::warning(this, tr("Error"), tr("<p>Couldn't retrieve the folder list. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok")); 311 QMessageBox::warning(this, tr("Error"), tr("<p>Couldn't retrieve the folder list. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok"));
312 } 312 }
313} 313}
314 314
diff --git a/noncore/unsupported/mail2/libmail/imaphandler.cpp b/noncore/unsupported/mail2/libmail/imaphandler.cpp
index dc97b28..8da0acd 100644
--- a/noncore/unsupported/mail2/libmail/imaphandler.cpp
+++ b/noncore/unsupported/mail2/libmail/imaphandler.cpp
@@ -1,346 +1,346 @@
1#include "imapresponse.h" 1#include "imapresponse.h"
2#include "imaphandler.h" 2#include "imaphandler.h"
3#include "imapbase.h" 3#include "imapbase.h"
4 4
5IMAPHandler::IMAPHandler(const Account &account) 5IMAPHandler::IMAPHandler(const Account &account)
6 : QObject(), _account(account) 6 : QObject(), _account(account)
7{ 7{
8 _ready = false; 8 _ready = false;
9 _loggingin = false; 9 _loggingin = false;
10 _loggedin = false; 10 _loggedin = false;
11 _tag = 0; 11 _tag = 0;
12 _ibase = new IMAPBase(account); 12 _ibase = new IMAPBase(account);
13 13
14 connect(_ibase, SIGNAL(dataReceived(const QString &)), SLOT(slotDataReceived(const QString &))); 14 connect(_ibase, SIGNAL(dataReceived(const QString&)), SLOT(slotDataReceived(const QString&)));
15 connect(_ibase, SIGNAL(lookingUpHost()), SLOT(slotLookingUpHost())); 15 connect(_ibase, SIGNAL(lookingUpHost()), SLOT(slotLookingUpHost()));
16 connect(_ibase, SIGNAL(hostFound()), SLOT(slotHostFound())); 16 connect(_ibase, SIGNAL(hostFound()), SLOT(slotHostFound()));
17 connect(_ibase, SIGNAL(connected()), SLOT(slotConnected())); 17 connect(_ibase, SIGNAL(connected()), SLOT(slotConnected()));
18 connect(_ibase, SIGNAL(disconnected()), SLOT(slotDisconnected())); 18 connect(_ibase, SIGNAL(disconnected()), SLOT(slotDisconnected()));
19 connect(_ibase, SIGNAL(error(int)), SLOT(slotError(int))); 19 connect(_ibase, SIGNAL(error(int)), SLOT(slotError(int)));
20} 20}
21 21
22void IMAPHandler::doLogin() 22void IMAPHandler::doLogin()
23{ 23{
24 if (_loggedin) return; 24 if (_loggedin) return;
25 if (_loggingin) return; 25 if (_loggingin) return;
26 26
27 _loggingin = true; 27 _loggingin = true;
28 iLogin(_account.user(), _account.pass()); 28 iLogin(_account.user(), _account.pass());
29} 29}
30 30
31QString IMAPHandler::iCapability() 31QString IMAPHandler::iCapability()
32{ 32{
33 _ibase->sendCommand(QString("%1 CAPABILITY\r\n") 33 _ibase->sendCommand(QString("%1 CAPABILITY\r\n")
34 .arg(tag())); 34 .arg(tag()));
35 return tag(false); 35 return tag(false);
36} 36}
37 37
38QString IMAPHandler::iNoop() 38QString IMAPHandler::iNoop()
39{ 39{
40 _ibase->sendCommand(QString("%1 NOOP\r\n") 40 _ibase->sendCommand(QString("%1 NOOP\r\n")
41 .arg(tag())); 41 .arg(tag()));
42 return tag(false); 42 return tag(false);
43} 43}
44 44
45QString IMAPHandler::iLogout() 45QString IMAPHandler::iLogout()
46{ 46{
47 _ibase->sendCommand(QString("%1 LOGOUT\r\n") 47 _ibase->sendCommand(QString("%1 LOGOUT\r\n")
48 .arg(tag())); 48 .arg(tag()));
49 return tag(false); 49 return tag(false);
50} 50}
51 51
52QString IMAPHandler::iAuthenticate(const QString &mechanism) 52QString IMAPHandler::iAuthenticate(const QString &mechanism)
53{ 53{
54 _ibase->sendCommand(QString("%1 AUTHENTICATE \"%2\"\r\n") 54 _ibase->sendCommand(QString("%1 AUTHENTICATE \"%2\"\r\n")
55 .arg(tag()) 55 .arg(tag())
56 .arg(escape(mechanism))); 56 .arg(escape(mechanism)));
57 return tag(false); 57 return tag(false);
58} 58}
59 59
60QString IMAPHandler::iLogin(const QString &user, const QString &pass) 60QString IMAPHandler::iLogin(const QString &user, const QString &pass)
61{ 61{
62 _ibase->sendCommand(QString("%1 LOGIN \"%2\" \"%3\"\r\n") 62 _ibase->sendCommand(QString("%1 LOGIN \"%2\" \"%3\"\r\n")
63 .arg(tag()) 63 .arg(tag())
64 .arg(escape(user)) 64 .arg(escape(user))
65 .arg(escape(pass))); 65 .arg(escape(pass)));
66 return tag(false); 66 return tag(false);
67} 67}
68 68
69QString IMAPHandler::iSelect(const QString &mailbox) 69QString IMAPHandler::iSelect(const QString &mailbox)
70{ 70{
71 doLogin(); 71 doLogin();
72 72
73 _ibase->sendCommand(QString("%1 SELECT \"%2\"\r\n") 73 _ibase->sendCommand(QString("%1 SELECT \"%2\"\r\n")
74 .arg(tag()) 74 .arg(tag())
75 .arg(escape(mailbox))); 75 .arg(escape(mailbox)));
76 return tag(false); 76 return tag(false);
77} 77}
78 78
79QString IMAPHandler::iExamine(const QString &mailbox) 79QString IMAPHandler::iExamine(const QString &mailbox)
80{ 80{
81 doLogin(); 81 doLogin();
82 82
83 _ibase->sendCommand(QString("%1 EXAMINE \"%2\"\r\n") 83 _ibase->sendCommand(QString("%1 EXAMINE \"%2\"\r\n")
84 .arg(tag()) 84 .arg(tag())
85 .arg(escape(mailbox))); 85 .arg(escape(mailbox)));
86 return tag(false); 86 return tag(false);
87} 87}
88 88
89QString IMAPHandler::iCreate(const QString &mailbox) 89QString IMAPHandler::iCreate(const QString &mailbox)
90{ 90{
91 doLogin(); 91 doLogin();
92 92
93 _ibase->sendCommand(QString("%1 CREATE \"%2\"\r\n") 93 _ibase->sendCommand(QString("%1 CREATE \"%2\"\r\n")
94 .arg(tag()) 94 .arg(tag())
95 .arg(escape(mailbox))); 95 .arg(escape(mailbox)));
96 return tag(false); 96 return tag(false);
97} 97}
98 98
99QString IMAPHandler::iDelete(const QString &mailbox) 99QString IMAPHandler::iDelete(const QString &mailbox)
100{ 100{
101 doLogin(); 101 doLogin();
102 102
103 _ibase->sendCommand(QString("%1 DELETE \"%2\"\r\n") 103 _ibase->sendCommand(QString("%1 DELETE \"%2\"\r\n")
104 .arg(tag()) 104 .arg(tag())
105 .arg(escape(mailbox))); 105 .arg(escape(mailbox)));
106 return tag(false); 106 return tag(false);
107} 107}
108 108
109QString IMAPHandler::iRename(const QString &mailbox, const QString &newMailbox) 109QString IMAPHandler::iRename(const QString &mailbox, const QString &newMailbox)
110{ 110{
111 doLogin(); 111 doLogin();
112 112
113 _ibase->sendCommand(QString("%1 RENAME \"%2\" \"%3\"\r\n") 113 _ibase->sendCommand(QString("%1 RENAME \"%2\" \"%3\"\r\n")
114 .arg(tag()) 114 .arg(tag())
115 .arg(escape(mailbox)) 115 .arg(escape(mailbox))
116 .arg(escape(newMailbox))); 116 .arg(escape(newMailbox)));
117 return tag(false); 117 return tag(false);
118} 118}
119 119
120QString IMAPHandler::iSubscribe(const QString &mailbox) 120QString IMAPHandler::iSubscribe(const QString &mailbox)
121{ 121{
122 doLogin(); 122 doLogin();
123 123
124 _ibase->sendCommand(QString("%1 SUBSCRIBE \"%2\"\r\n") 124 _ibase->sendCommand(QString("%1 SUBSCRIBE \"%2\"\r\n")
125 .arg(tag()) 125 .arg(tag())
126 .arg(escape(mailbox))); 126 .arg(escape(mailbox)));
127 return tag(false); 127 return tag(false);
128} 128}
129 129
130QString IMAPHandler::iUnsubscribe(const QString &mailbox) 130QString IMAPHandler::iUnsubscribe(const QString &mailbox)
131{ 131{
132 doLogin(); 132 doLogin();
133 133
134 _ibase->sendCommand(QString("%1 UNSUBSCRIBE \"%2\"\r\n") 134 _ibase->sendCommand(QString("%1 UNSUBSCRIBE \"%2\"\r\n")
135 .arg(tag()) 135 .arg(tag())
136 .arg(escape(mailbox))); 136 .arg(escape(mailbox)));
137 return tag(false); 137 return tag(false);
138} 138}
139 139
140QString IMAPHandler::iList(const QString &reference, const QString &mailbox) 140QString IMAPHandler::iList(const QString &reference, const QString &mailbox)
141{ 141{
142 doLogin(); 142 doLogin();
143 143
144 _ibase->sendCommand(QString("%1 LIST \"%2\" \"%3\"\r\n") 144 _ibase->sendCommand(QString("%1 LIST \"%2\" \"%3\"\r\n")
145 .arg(tag()) 145 .arg(tag())
146 .arg(escape(reference)) 146 .arg(escape(reference))
147 .arg(escape(mailbox))); 147 .arg(escape(mailbox)));
148 return tag(false); 148 return tag(false);
149} 149}
150 150
151QString IMAPHandler::iLsub(const QString &reference, const QString &mailbox) 151QString IMAPHandler::iLsub(const QString &reference, const QString &mailbox)
152{ 152{
153 doLogin(); 153 doLogin();
154 154
155 _ibase->sendCommand(QString("%1 LSUB \"%2\" \"%3\"\r\n") 155 _ibase->sendCommand(QString("%1 LSUB \"%2\" \"%3\"\r\n")
156 .arg(tag()) 156 .arg(tag())
157 .arg(escape(reference)) 157 .arg(escape(reference))
158 .arg(escape(mailbox))); 158 .arg(escape(mailbox)));
159 return tag(false); 159 return tag(false);
160} 160}
161 161
162QString IMAPHandler::iStatus(const QString &mailbox, const QString &items) 162QString IMAPHandler::iStatus(const QString &mailbox, const QString &items)
163{ 163{
164 doLogin(); 164 doLogin();
165 165
166 _ibase->sendCommand(QString("%1 STATUS \"%2\" (%3)\r\n") 166 _ibase->sendCommand(QString("%1 STATUS \"%2\" (%3)\r\n")
167 .arg(tag()) 167 .arg(tag())
168 .arg(escape(mailbox)) 168 .arg(escape(mailbox))
169 .arg(escape(items))); 169 .arg(escape(items)));
170 return tag(false); 170 return tag(false);
171} 171}
172 172
173QString IMAPHandler::iAppend(const QString &mailbox, const QString &literal, const QString &flags, const QString &datetime) 173QString IMAPHandler::iAppend(const QString &mailbox, const QString &literal, const QString &flags, const QString &datetime)
174{ 174{
175 doLogin(); 175 doLogin();
176 176
177 _ibase->sendCommand(QString("%1 APPEND \"%2\" (%3) \"%4\" {%5}\r\n%6\r\n") 177 _ibase->sendCommand(QString("%1 APPEND \"%2\" (%3) \"%4\" {%5}\r\n%6\r\n")
178 .arg(tag()) 178 .arg(tag())
179 .arg(escape(mailbox)) 179 .arg(escape(mailbox))
180 .arg(flags) 180 .arg(flags)
181 .arg(escape(datetime)) 181 .arg(escape(datetime))
182 .arg(literal.length()) 182 .arg(literal.length())
183 .arg(literal)); 183 .arg(literal));
184 return tag(false); 184 return tag(false);
185} 185}
186 186
187QString IMAPHandler::iCheck() 187QString IMAPHandler::iCheck()
188{ 188{
189 doLogin(); 189 doLogin();
190 190
191 _ibase->sendCommand(QString("%1 CHECK\r\n") 191 _ibase->sendCommand(QString("%1 CHECK\r\n")
192 .arg(tag())); 192 .arg(tag()));
193 return tag(false); 193 return tag(false);
194} 194}
195 195
196QString IMAPHandler::iClose() 196QString IMAPHandler::iClose()
197{ 197{
198 doLogin(); 198 doLogin();
199 199
200 _ibase->sendCommand(QString("%1 CLOSE\r\n") 200 _ibase->sendCommand(QString("%1 CLOSE\r\n")
201 .arg(tag())); 201 .arg(tag()));
202 return tag(false); 202 return tag(false);
203} 203}
204 204
205QString IMAPHandler::iExpunge() 205QString IMAPHandler::iExpunge()
206{ 206{
207 doLogin(); 207 doLogin();
208 208
209 _ibase->sendCommand(QString("%1 EXPUNGE\r\n") 209 _ibase->sendCommand(QString("%1 EXPUNGE\r\n")
210 .arg(tag())); 210 .arg(tag()));
211 return tag(false); 211 return tag(false);
212} 212}
213 213
214QString IMAPHandler::iSearch(const QString &search, const QString &charset) 214QString IMAPHandler::iSearch(const QString &search, const QString &charset)
215{ 215{
216 doLogin(); 216 doLogin();
217 217
218 _ibase->sendCommand(QString("%1 SEARCH %2 %3\r\n") 218 _ibase->sendCommand(QString("%1 SEARCH %2 %3\r\n")
219 .arg(tag()) 219 .arg(tag())
220 .arg(charset.isEmpty() ? QString(0) : escape(charset)) 220 .arg(charset.isEmpty() ? QString(0) : escape(charset))
221 .arg(search)); 221 .arg(search));
222 return tag(false); 222 return tag(false);
223} 223}
224 224
225QString IMAPHandler::iFetch(const QString &message, const QString &items) 225QString IMAPHandler::iFetch(const QString &message, const QString &items)
226{ 226{
227 doLogin(); 227 doLogin();
228 228
229 _ibase->sendCommand(QString("%1 FETCH %2 (%3)\r\n") 229 _ibase->sendCommand(QString("%1 FETCH %2 (%3)\r\n")
230 .arg(tag()) 230 .arg(tag())
231 .arg(message) 231 .arg(message)
232 .arg(items)); 232 .arg(items));
233 return tag(false); 233 return tag(false);
234} 234}
235 235
236QString IMAPHandler::iStore(const QString &message, const QString &items) 236QString IMAPHandler::iStore(const QString &message, const QString &items)
237{ 237{
238 doLogin(); 238 doLogin();
239 239
240 _ibase->sendCommand(QString("%1 STORE %2 %3\r\n") 240 _ibase->sendCommand(QString("%1 STORE %2 %3\r\n")
241 .arg(tag()) 241 .arg(tag())
242 .arg(message) 242 .arg(message)
243 .arg(items)); 243 .arg(items));
244 return tag(false); 244 return tag(false);
245} 245}
246 246
247QString IMAPHandler::iCopy(const QString &message, const QString &mailbox) 247QString IMAPHandler::iCopy(const QString &message, const QString &mailbox)
248{ 248{
249 doLogin(); 249 doLogin();
250 250
251 _ibase->sendCommand(QString("%1 COPY %2 \"%3\"\r\n") 251 _ibase->sendCommand(QString("%1 COPY %2 \"%3\"\r\n")
252 .arg(tag()) 252 .arg(tag())
253 .arg(message) 253 .arg(message)
254 .arg(escape(mailbox))); 254 .arg(escape(mailbox)));
255 return tag(false); 255 return tag(false);
256} 256}
257 257
258QString IMAPHandler::iUid(const QString &command, const QString &arguments) 258QString IMAPHandler::iUid(const QString &command, const QString &arguments)
259{ 259{
260 doLogin(); 260 doLogin();
261 261
262 _ibase->sendCommand(QString("%1 UID %2 %3\r\n") 262 _ibase->sendCommand(QString("%1 UID %2 %3\r\n")
263 .arg(tag()) 263 .arg(tag())
264 .arg(command) 264 .arg(command)
265 .arg(arguments)); 265 .arg(arguments));
266 return tag(false); 266 return tag(false);
267} 267}
268 268
269QString IMAPHandler::iX(const QString &commandAtom, const QString &arguments) 269QString IMAPHandler::iX(const QString &commandAtom, const QString &arguments)
270{ 270{
271 doLogin(); 271 doLogin();
272 272
273 _ibase->sendCommand(QString("%1 X%2 %3\r\n") 273 _ibase->sendCommand(QString("%1 X%2 %3\r\n")
274 .arg(tag()) 274 .arg(tag())
275 .arg(commandAtom) 275 .arg(commandAtom)
276 .arg(arguments)); 276 .arg(arguments));
277 return tag(false); 277 return tag(false);
278} 278}
279 279
280QString IMAPHandler::escape(const QString &in) 280QString IMAPHandler::escape(const QString &in)
281{ 281{
282 QString in_ = in; 282 QString in_ = in;
283 return in_.replace(QRegExp("\""), "\\\""); 283 return in_.replace(QRegExp("\""), "\\\"");
284} 284}
285 285
286QString IMAPHandler::tag(bool count) 286QString IMAPHandler::tag(bool count)
287{ 287{
288 return QString("a%1").arg(count ? _tag++ : _tag); 288 return QString("a%1").arg(count ? _tag++ : _tag);
289} 289}
290 290
291void IMAPHandler::slotDataReceived(const QString &data) 291void IMAPHandler::slotDataReceived(const QString &data)
292{ 292{
293 if (!_ready) { 293 if (!_ready) {
294 // The first data is always the greeting string. 294 // The first data is always the greeting string.
295 // We can ignore it. 295 // We can ignore it.
296 _ready = true; 296 _ready = true;
297 return; 297 return;
298 } 298 }
299 299
300 300
301 IMAPResponseParser parser; 301 IMAPResponseParser parser;
302 //connect ( &parser, SIGNAL( needMoreData ( QString & )), _ibase, SLOT( tryRead ( QString & ))); 302 //connect ( &parser, SIGNAL( needMoreData(QString&)), _ibase, SLOT( tryRead(QString&)));
303 parser. parse ( data ); 303 parser. parse ( data );
304 IMAPResponse response = parser.response(); 304 IMAPResponse response = parser.response();
305 //disconnect ( &parser, SIGNAL( needMoreData ( QString & )), _ibase, SLOT( tryRead ( QString & ))); 305 //disconnect ( &parser, SIGNAL( needMoreData(QString&)), _ibase, SLOT( tryRead(QString&)));
306 response.setImapHandler(this); 306 response.setImapHandler(this);
307 307
308 if (!_loggingin) { qDebug("Emitting gotResponse!\n" ); emit gotResponse(response); } 308 if (!_loggingin) { qDebug("Emitting gotResponse!\n" ); emit gotResponse(response); }
309 else { 309 else {
310 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 310 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
311 _loggingin = false; 311 _loggingin = false;
312 _loggedin = true; 312 _loggedin = true;
313 qWarning("OK. Logged in. Leaving loggingin state."); 313 qWarning("OK. Logged in. Leaving loggingin state.");
314 } else { 314 } else {
315 _loggingin = false; 315 _loggingin = false;
316 emit IMAPError(IMAPBase::IMAPErrLoginFailed); 316 emit IMAPError(IMAPBase::IMAPErrLoginFailed);
317 } 317 }
318 } 318 }
319} 319}
320 320
321void IMAPHandler::slotLookingUpHost() 321void IMAPHandler::slotLookingUpHost()
322{ 322{
323 emit IMAPLookingUpHost(); 323 emit IMAPLookingUpHost();
324} 324}
325 325
326void IMAPHandler::slotHostFound() 326void IMAPHandler::slotHostFound()
327{ 327{
328 emit IMAPHostFound(); 328 emit IMAPHostFound();
329} 329}
330 330
331void IMAPHandler::slotConnected() 331void IMAPHandler::slotConnected()
332{ 332{
333 emit IMAPConnected(); 333 emit IMAPConnected();
334} 334}
335 335
336void IMAPHandler::slotDisconnected() 336void IMAPHandler::slotDisconnected()
337{ 337{
338 _loggedin = false; 338 _loggedin = false;
339 emit IMAPDisconnected(); 339 emit IMAPDisconnected();
340} 340}
341 341
342void IMAPHandler::slotError(int err) 342void IMAPHandler::slotError(int err)
343{ 343{
344 emit IMAPError(err); 344 emit IMAPError(err);
345} 345}
346 346
diff --git a/noncore/unsupported/mail2/listviewplus.cpp b/noncore/unsupported/mail2/listviewplus.cpp
index ce5f35f..722b347 100644
--- a/noncore/unsupported/mail2/listviewplus.cpp
+++ b/noncore/unsupported/mail2/listviewplus.cpp
@@ -1,54 +1,54 @@
1#include <qpopupmenu.h> 1#include <qpopupmenu.h>
2#include <qtimer.h> 2#include <qtimer.h>
3 3
4#include "listviewplus.h" 4#include "listviewplus.h"
5 5
6ListViewPlus::ListViewPlus(QWidget *parent, const char *name, WFlags fl) 6ListViewPlus::ListViewPlus(QWidget *parent, const char *name, WFlags fl)
7 : QListView(parent, name, fl) 7 : QListView(parent, name, fl)
8{ 8{
9 9
10} 10}
11 11
12void ListViewPlus::keyPressEvent(QKeyEvent *event) 12void ListViewPlus::keyPressEvent(QKeyEvent *event)
13{ 13{
14 switch(event->key()) { 14 switch(event->key()) {
15 case Qt::Key_Space: // FALLTHROUGH 15 case Qt::Key_Space: // FALLTHROUGH
16 case Qt::Key_Enter: 16 case Qt::Key_Enter:
17 if (currentItem() != 0) 17 if (currentItem() != 0)
18 emit clicked(currentItem()); 18 emit clicked(currentItem());
19 break; 19 break;
20 default: break; 20 default: break;
21 } 21 }
22 22
23 QListView::keyPressEvent(event); 23 QListView::keyPressEvent(event);
24} 24}
25 25
26void ListViewPlus::setPopup(QPopupMenu *popup, int delay) 26void ListViewPlus::setPopup(QPopupMenu *popup, int delay)
27{ 27{
28 _popup = popup; 28 _popup = popup;
29 _delay = delay; 29 _delay = delay;
30 30
31 connect(this, SIGNAL(pressed(QListViewItem *, const QPoint &, int)), SLOT(_initPopup(QListViewItem *, const QPoint &, int))); 31 connect(this, SIGNAL(pressed(QListViewItem*,const QPoint&,int)), SLOT(_initPopup(QListViewItem*,const QPoint&,int)));
32 connect(this, SIGNAL(clicked(QListViewItem *, const QPoint &, int)), SLOT(_cancelPopup(QListViewItem *, const QPoint &, int))); 32 connect(this, SIGNAL(clicked(QListViewItem*,const QPoint&,int)), SLOT(_cancelPopup(QListViewItem*,const QPoint&,int)));
33} 33}
34 34
35void ListViewPlus::_initPopup(QListViewItem *, const QPoint &point, int) 35void ListViewPlus::_initPopup(QListViewItem *, const QPoint &point, int)
36{ 36{
37 _point = point; 37 _point = point;
38 38
39 _timer = new QTimer(); 39 _timer = new QTimer();
40 _timer->start(_delay, true); 40 _timer->start(_delay, true);
41 41
42 connect(_timer, SIGNAL(timeout()), this, SLOT(_showPopup())); 42 connect(_timer, SIGNAL(timeout()), this, SLOT(_showPopup()));
43} 43}
44 44
45void ListViewPlus::_cancelPopup(QListViewItem *, const QPoint &, int) 45void ListViewPlus::_cancelPopup(QListViewItem *, const QPoint &, int)
46{ 46{
47 delete _timer; 47 delete _timer;
48} 48}
49 49
50void ListViewPlus::_showPopup() 50void ListViewPlus::_showPopup()
51{ 51{
52 _popup->popup(_point); 52 _popup->popup(_point);
53} 53}
54 54
diff --git a/noncore/unsupported/mail2/mailtable.cpp b/noncore/unsupported/mail2/mailtable.cpp
index fd179f0..56feab0 100644
--- a/noncore/unsupported/mail2/mailtable.cpp
+++ b/noncore/unsupported/mail2/mailtable.cpp
@@ -1,171 +1,171 @@
1#include <qmessagebox.h> 1#include <qmessagebox.h>
2#include <qpopupmenu.h> 2#include <qpopupmenu.h>
3#include <qheader.h> 3#include <qheader.h>
4#include <qtimer.h> 4#include <qtimer.h>
5 5
6#include "folderwidget.h" 6#include "folderwidget.h"
7#include "imaphandler.h" 7#include "imaphandler.h"
8#include "mailtable.h" 8#include "mailtable.h"
9 9
10MailTableItem::MailTableItem(QListView *parent, IMAPResponseFETCH fetch) 10MailTableItem::MailTableItem(QListView *parent, IMAPResponseFETCH fetch)
11 : QListViewItem(parent), _fetch(fetch) 11 : QListViewItem(parent), _fetch(fetch)
12{ 12{
13 _draft = false; 13 _draft = false;
14 _new = false; 14 _new = false;
15 _unseen = true; 15 _unseen = true;
16 16
17 QValueList<IMAPResponseEnums::IMAPResponseFlags>::Iterator it; 17 QValueList<IMAPResponseEnums::IMAPResponseFlags>::Iterator it;
18 QValueList<IMAPResponseEnums::IMAPResponseFlags> flags = fetch.flags(); 18 QValueList<IMAPResponseEnums::IMAPResponseFlags> flags = fetch.flags();
19 for (it = flags.begin(); it != flags.end(); it++) { 19 for (it = flags.begin(); it != flags.end(); it++) {
20 if (*it == IMAPResponseEnums::Draft) _draft = true; 20 if (*it == IMAPResponseEnums::Draft) _draft = true;
21 else if (*it == IMAPResponseEnums::Recent) _new = true; 21 else if (*it == IMAPResponseEnums::Recent) _new = true;
22 else if (*it == IMAPResponseEnums::Seen) _unseen = false; 22 else if (*it == IMAPResponseEnums::Seen) _unseen = false;
23 } 23 }
24 24
25 setText(0, fetch.envelope().from()[0].name().isEmpty() ? QObject::tr("(no from)") : fetch.envelope().from()[0].name()); 25 setText(0, fetch.envelope().from()[0].name().isEmpty() ? QObject::tr("(no from)") : fetch.envelope().from()[0].name());
26 setText(1, fetch.envelope().subject().isEmpty() ? QObject::tr("(no subject)") : fetch.envelope().subject()); 26 setText(1, fetch.envelope().subject().isEmpty() ? QObject::tr("(no subject)") : fetch.envelope().subject());
27 setText(2, fetch.envelope().mailDate().isEmpty() ? QObject::tr("(no date)") : fetch.envelope().mailDate()); 27 setText(2, fetch.envelope().mailDate().isEmpty() ? QObject::tr("(no date)") : fetch.envelope().mailDate());
28} 28}
29 29
30void MailTableItem::paintCell(QPainter *painter, const QColorGroup &cg, int col, int width, int align) 30void MailTableItem::paintCell(QPainter *painter, const QColorGroup &cg, int col, int width, int align)
31{ 31{
32 QColor color = cg.color(QColorGroup::Text); 32 QColor color = cg.color(QColorGroup::Text);
33 QFont font = painter->font(); 33 QFont font = painter->font();
34 if (_draft) { 34 if (_draft) {
35 color = QColor("#707070"); 35 color = QColor("#707070");
36 } else if (_new) { 36 } else if (_new) {
37 color = QColor("#ff0000"); 37 color = QColor("#ff0000");
38 font.setBold(true); 38 font.setBold(true);
39 } else if (_unseen) { 39 } else if (_unseen) {
40 font.setBold(true); 40 font.setBold(true);
41 } 41 }
42 42
43 painter->setFont(font); 43 painter->setFont(font);
44 QColorGroup cg_(cg); 44 QColorGroup cg_(cg);
45 cg_.setColor(QColorGroup::Text, color); 45 cg_.setColor(QColorGroup::Text, color);
46 46
47 QListViewItem::paintCell(painter, cg_, col, width, align); 47 QListViewItem::paintCell(painter, cg_, col, width, align);
48} 48}
49 49
50MailTable::MailTable(QWidget *parent, const char *name, WFlags fl) 50MailTable::MailTable(QWidget *parent, const char *name, WFlags fl)
51 : ListViewPlus(parent, name, fl), _parent(parent) 51 : ListViewPlus(parent, name, fl), _parent(parent)
52{ 52{
53 _stopped = false; 53 _stopped = false;
54 54
55 setSorting(-1); 55 setSorting(-1);
56 56
57 setAllColumnsShowFocus(true); 57 setAllColumnsShowFocus(true);
58 addColumn(tr("From"), 100); 58 addColumn(tr("From"), 100);
59 addColumn(tr("Subject"), 100); 59 addColumn(tr("Subject"), 100);
60 addColumn(tr("Date"), 100); 60 addColumn(tr("Date"), 100);
61 61
62 QPopupMenu *menu = new QPopupMenu(this); 62 QPopupMenu *menu = new QPopupMenu(this);
63 menu->insertItem(tr("Copy"), MENU_COPY); 63 menu->insertItem(tr("Copy"), MENU_COPY);
64 64
65 QPopupMenu *markMenu = new QPopupMenu(this); 65 QPopupMenu *markMenu = new QPopupMenu(this);
66 markMenu->insertItem(tr("Seen"), MENU_MARK_READ); 66 markMenu->insertItem(tr("Seen"), MENU_MARK_READ);
67 markMenu->insertItem(tr("Unseen"), MENU_MARK_UNREAD); 67 markMenu->insertItem(tr("Unseen"), MENU_MARK_UNREAD);
68 markMenu->insertSeparator(); 68 markMenu->insertSeparator();
69 markMenu->insertItem(tr("Marked"), MENU_MARK_MARKED); 69 markMenu->insertItem(tr("Marked"), MENU_MARK_MARKED);
70 markMenu->insertItem(tr("Unmarked"), MENU_MARK_UNMARKED); 70 markMenu->insertItem(tr("Unmarked"), MENU_MARK_UNMARKED);
71 71
72 menu->insertItem(tr("Mark as..."), markMenu, MENU_MARK); 72 menu->insertItem(tr("Mark as..."), markMenu, MENU_MARK);
73 menu->insertSeparator(); 73 menu->insertSeparator();
74 menu->insertItem(tr("Delete Mail"), MENU_DELETE); 74 menu->insertItem(tr("Delete Mail"), MENU_DELETE);
75 setPopup(menu); 75 setPopup(menu);
76 76
77 connect(this, SIGNAL(clicked(QListViewItem *)), SLOT(itemClicked(QListViewItem *))); 77 connect(this, SIGNAL(clicked(QListViewItem*)), SLOT(itemClicked(QListViewItem*)));
78} 78}
79 79
80void MailTable::setFolder(Folder folder) 80void MailTable::setFolder(Folder folder)
81{ 81{
82 folder.topFolder().handler()->iSelect(folder.fullName()); 82 folder.topFolder().handler()->iSelect(folder.fullName());
83 _handler = folder.topFolder().handler(); 83 _handler = folder.topFolder().handler();
84 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPSelect(IMAPResponse &))); 84 connect(folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPSelect(IMAPResponse&)));
85} 85}
86 86
87void MailTable::setHeaders(QValueList<IMAPResponseFETCH> response) 87void MailTable::setHeaders(QValueList<IMAPResponseFETCH> response)
88{ 88{
89 clear(); 89 clear();
90 QValueList<IMAPResponseFETCH>::Iterator it; 90 QValueList<IMAPResponseFETCH>::Iterator it;
91 for (it = response.begin(); it != response.end(); it++) { 91 for (it = response.begin(); it != response.end(); it++) {
92 (void) new MailTableItem(this, *it); 92 (void) new MailTableItem(this, *it);
93 } 93 }
94} 94}
95 95
96void MailTable::slotIMAPSelect(IMAPResponse &response) 96void MailTable::slotIMAPSelect(IMAPResponse &response)
97{ 97{
98 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPSelect(IMAPResponse &))); 98 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPSelect(IMAPResponse&)));
99 99
100 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 100 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
101 clear(); 101 clear();
102 QString mails = response.EXISTS()[0].mails(); 102 QString mails = response.EXISTS()[0].mails();
103 if (mails.toInt() == 0) { 103 if (mails.toInt() == 0) {
104 emit status(tr("Mailbox contained no mails.")); 104 emit status(tr("Mailbox contained no mails."));
105 return; 105 return;
106 } 106 }
107 int a = mails.toInt() / 5; 107 int a = mails.toInt() / 5;
108 int b = mails.toInt() % 5; 108 int b = mails.toInt() % 5;
109 109
110 _downloadSteps = a; 110 _downloadSteps = a;
111 if (b > 0) _downloadSteps++; 111 if (b > 0) _downloadSteps++;
112 _lastStep = b; 112 _lastStep = b;
113 _currentProgress = 0; 113 _currentProgress = 0;
114 114
115 emit totalSteps(_downloadSteps); 115 emit totalSteps(_downloadSteps);
116 emit progress(_currentProgress); 116 emit progress(_currentProgress);
117 emit stopEnabled(true); 117 emit stopEnabled(true);
118 118
119 response.imapHandler()->iFetch(QString("1:%1").arg((a == 0) ? b : 5), "ENVELOPE FLAGS UID"); 119 response.imapHandler()->iFetch(QString("1:%1").arg((a == 0) ? b : 5), "ENVELOPE FLAGS UID");
120 emit status(tr("Getting mail headers...")); 120 emit status(tr("Getting mail headers..."));
121 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPFetch(IMAPResponse &))); 121 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPFetch(IMAPResponse&)));
122 } else { 122 } else {
123 QMessageBox::warning(this, tr("Error"), tr("<p>An error occoured during the selection of the mailbox. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok")); 123 QMessageBox::warning(this, tr("Error"), tr("<p>An error occoured during the selection of the mailbox. (Server said: %1)</p>").arg(response.statusResponse().comment()), tr("Ok"));
124 } 124 }
125} 125}
126 126
127void MailTable::slotIMAPFetch(IMAPResponse &response) 127void MailTable::slotIMAPFetch(IMAPResponse &response)
128{ 128{
129 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPFetch(IMAPResponse &))); 129 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPFetch(IMAPResponse&)));
130 130
131 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 131 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
132 QValueList<IMAPResponseFETCH>::Iterator it; 132 QValueList<IMAPResponseFETCH>::Iterator it;
133 QValueList<IMAPResponseFETCH> fetch = response.FETCH(); 133 QValueList<IMAPResponseFETCH> fetch = response.FETCH();
134 for (it = fetch.begin(); it != fetch.end(); it++) { 134 for (it = fetch.begin(); it != fetch.end(); it++) {
135 (void) new MailTableItem(this, *it); 135 (void) new MailTableItem(this, *it);
136 } 136 }
137 emit progress(++_currentProgress); 137 emit progress(++_currentProgress);
138 138
139 if (_currentProgress != _downloadSteps) { 139 if (_currentProgress != _downloadSteps) {
140 if (_stopped) { 140 if (_stopped) {
141 _currentProgress = 0; 141 _currentProgress = 0;
142 _downloadSteps = 0; 142 _downloadSteps = 0;
143 _lastStep = 0; 143 _lastStep = 0;
144 _stopped = false; 144 _stopped = false;
145 emit status(tr("Stopped")); 145 emit status(tr("Stopped"));
146 emit resetProgress(); 146 emit resetProgress();
147 emit stopEnabled(false); 147 emit stopEnabled(false);
148 } else { 148 } else {
149 response.imapHandler()->iFetch(QString("%1:%2").arg(_currentProgress * 5 + 1).arg((_currentProgress + 1 == _downloadSteps) ? _currentProgress * 5 + _lastStep : _currentProgress * 5 + 5), "ENVELOPE FLAGS UID"); 149 response.imapHandler()->iFetch(QString("%1:%2").arg(_currentProgress * 5 + 1).arg((_currentProgress + 1 == _downloadSteps) ? _currentProgress * 5 + _lastStep : _currentProgress * 5 + 5), "ENVELOPE FLAGS UID");
150 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPFetch(IMAPResponse &))); 150 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPFetch(IMAPResponse&)));
151 } 151 }
152 } else { 152 } else {
153 _currentProgress = 0; 153 _currentProgress = 0;
154 _downloadSteps = 0; 154 _downloadSteps = 0;
155 _lastStep = 0; 155 _lastStep = 0;
156 emit status(tr("Got all mail headers.")); 156 emit status(tr("Got all mail headers."));
157 emit resetProgress(); 157 emit resetProgress();
158 emit stopEnabled(false); 158 emit stopEnabled(false);
159 } 159 }
160 } else { 160 } else {
161 emit status(tr("<font color=#ff0000>Couldn't fetch mail.")); 161 emit status(tr("<font color=#ff0000>Couldn't fetch mail."));
162 } 162 }
163} 163}
164 164
165void MailTable::itemClicked(QListViewItem *item) 165void MailTable::itemClicked(QListViewItem *item)
166{ 166{
167 if (item == NULL) return; 167 if (item == NULL) return;
168 emit mailClicked(((MailTableItem *)item)->fetch(), _handler); 168 emit mailClicked(((MailTableItem *)item)->fetch(), _handler);
169} 169}
170 170
171 171
diff --git a/noncore/unsupported/mail2/mainwindow.cpp b/noncore/unsupported/mail2/mainwindow.cpp
index 0d09ec8..ce80391 100644
--- a/noncore/unsupported/mail2/mainwindow.cpp
+++ b/noncore/unsupported/mail2/mainwindow.cpp
@@ -1,118 +1,118 @@
1#include <qmessagebox.h> 1#include <qmessagebox.h>
2#include <qaction.h> 2#include <qaction.h>
3#include <qapplication.h> 3#include <qapplication.h>
4 4
5#include <qpe/qcopenvelope_qws.h> 5#include <qpe/qcopenvelope_qws.h>
6 6
7#include "mailstatusbar.h" 7#include "mailstatusbar.h"
8#include "folderwidget.h" 8#include "folderwidget.h"
9#include "mainwindow.h" 9#include "mainwindow.h"
10#include "configdiag.h" 10#include "configdiag.h"
11#include "configfile.h" 11#include "configfile.h"
12#include "searchdiag.h" 12#include "searchdiag.h"
13#include "mailtable.h" 13#include "mailtable.h"
14#include "composer.h" 14#include "composer.h"
15#include "viewmail.h" 15#include "viewmail.h"
16#include "mailfactory.h" 16#include "mailfactory.h"
17 17
18MainWindow::MainWindow(QWidget *parent, const char *name, WFlags fl) 18MainWindow::MainWindow(QWidget *parent, const char *name, WFlags fl)
19 : MainWindowBase(parent, name, fl) 19 : MainWindowBase(parent, name, fl)
20{ 20{
21 status->setStopEnabled(false); 21 status->setStopEnabled(false);
22 22
23 connect(folderView, SIGNAL(status(const QString &)), status, SLOT(setStatusText(const QString &))); 23 connect(folderView, SIGNAL(status(const QString&)), status, SLOT(setStatusText(const QString&)));
24 connect(folderView, SIGNAL(folderSelected(Folder)), mailView, SLOT(setFolder(Folder))); 24 connect(folderView, SIGNAL(folderSelected(Folder)), mailView, SLOT(setFolder(Folder)));
25 25
26 connect(mailView, SIGNAL(mailClicked(IMAPResponseFETCH, IMAPHandler *)), SLOT(mailClicked(IMAPResponseFETCH, IMAPHandler *))); 26 connect(mailView, SIGNAL(mailClicked(IMAPResponseFETCH,IMAPHandler*)), SLOT(mailClicked(IMAPResponseFETCH,IMAPHandler*)));
27 connect(mailView, SIGNAL(status(const QString &)), status, SLOT(setStatusText(const QString &))); 27 connect(mailView, SIGNAL(status(const QString&)), status, SLOT(setStatusText(const QString&)));
28 connect(mailView, SIGNAL(totalSteps(int)), status, SLOT(setProgressTotalSteps(int))); 28 connect(mailView, SIGNAL(totalSteps(int)), status, SLOT(setProgressTotalSteps(int)));
29 connect(mailView, SIGNAL(progress(int)), status, SLOT(setProgress(int))); 29 connect(mailView, SIGNAL(progress(int)), status, SLOT(setProgress(int)));
30 connect(mailView, SIGNAL(resetProgress()), status, SLOT(resetProgress())); 30 connect(mailView, SIGNAL(resetProgress()), status, SLOT(resetProgress()));
31 connect(mailView, SIGNAL(stopEnabled(bool)), status, SLOT(setStopEnabled(bool))); 31 connect(mailView, SIGNAL(stopEnabled(bool)), status, SLOT(setStopEnabled(bool)));
32 32
33 connect(status, SIGNAL(stop()), mailView, SLOT(stop())); 33 connect(status, SIGNAL(stop()), mailView, SLOT(stop()));
34 34
35 connect(compose, SIGNAL(activated()), SLOT(slotComposeNoParams())); 35 connect(compose, SIGNAL(activated()), SLOT(slotComposeNoParams()));
36 connect(sendQueue, SIGNAL(activated()), SLOT(slotSendQueued())); 36 connect(sendQueue, SIGNAL(activated()), SLOT(slotSendQueued()));
37 connect(findmails, SIGNAL(activated()), SLOT(slotSearch())); 37 connect(findmails, SIGNAL(activated()), SLOT(slotSearch()));
38 connect(configure, SIGNAL(activated()), SLOT(slotConfigure())); 38 connect(configure, SIGNAL(activated()), SLOT(slotConfigure()));
39 39
40 // Added by Stefan Eilers to allow starting by addressbook.. 40 // Added by Stefan Eilers to allow starting by addressbook..
41#if !defined(QT_NO_COP) 41#if !defined(QT_NO_COP)
42 // QCopChannel *addressChannel = new QCopChannel("QPE/Application/mail" , this ); 42 // QCopChannel *addressChannel = new QCopChannel("QPE/Application/mail" , this );
43 // connect (addressChannel, SIGNAL( received(const QCString &, const QByteArray &)), 43 // connect (addressChannel, SIGNAL( received(const QCString&,const QByteArray&)),
44 // this, SLOT ( appMessage(const QCString &, const QByteArray &) ) ); 44 // this, SLOT ( appMessage(const QCString&,const QByteArray&) ) );
45 connect( qApp, SIGNAL( appMessage( const QCString&, const QByteArray& ) ), 45 connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ),
46 this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); 46 this, SLOT( appMessage(const QCString&,const QByteArray&) ) );
47#endif 47#endif
48} 48}
49 49
50// Added by Stefan Eilers to allow starting by addressbook.. 50// Added by Stefan Eilers to allow starting by addressbook..
51void MainWindow::appMessage(const QCString &msg, const QByteArray &data) 51void MainWindow::appMessage(const QCString &msg, const QByteArray &data)
52{ 52{
53 if (msg == "writeMail(QString,QString)") { 53 if (msg == "writeMail(QString,QString)") {
54 QDataStream stream(data,IO_ReadOnly); 54 QDataStream stream(data,IO_ReadOnly);
55 QString name, email; 55 QString name, email;
56 stream >> name >> email; 56 stream >> name >> email;
57 57
58 qWarning("opie-mail:: Should send mail to %s with address %s", name.latin1(), email.latin1() ); 58 qWarning("opie-mail:: Should send mail to %s with address %s", name.latin1(), email.latin1() );
59 59
60 slotCompose( name, email ); 60 slotCompose( name, email );
61 61
62 }else{ 62 }else{
63 QString str_message = msg; 63 QString str_message = msg;
64 qWarning("opie-mail:: Received unknown QCop-Message: %s", str_message.latin1() ); 64 qWarning("opie-mail:: Received unknown QCop-Message: %s", str_message.latin1() );
65 } 65 }
66} 66}
67 67
68void MainWindow::slotCompose( const QString& name, const QString& email ) 68void MainWindow::slotCompose( const QString& name, const QString& email )
69{ 69{
70 Composer composer(this, 0, true); 70 Composer composer(this, 0, true);
71 71
72 // If there is a mailaddress given, create message.. 72 // If there is a mailaddress given, create message..
73 if ( ! name.isEmpty() ){ 73 if ( ! name.isEmpty() ){
74 qWarning("opie-mail:: Compose mail for %s with address %s", name.latin1(), email.latin1() ); 74 qWarning("opie-mail:: Compose mail for %s with address %s", name.latin1(), email.latin1() );
75 SendMail compMail; 75 SendMail compMail;
76 compMail.setTo( "\"" + name + "\"" + " " + "<"+ email + ">"); 76 compMail.setTo( "\"" + name + "\"" + " " + "<"+ email + ">");
77 composer.setSendMail( compMail ); 77 composer.setSendMail( compMail );
78 } 78 }
79 composer.showMaximized(); 79 composer.showMaximized();
80 composer.exec(); 80 composer.exec();
81} 81}
82 82
83void MainWindow::slotComposeNoParams() 83void MainWindow::slotComposeNoParams()
84{ 84{
85 slotCompose( 0l, 0l); 85 slotCompose( 0l, 0l);
86} 86}
87 87
88void MainWindow::slotSendQueued() 88void MainWindow::slotSendQueued()
89{ 89{
90 Composer composer(this, 0, true, true); 90 Composer composer(this, 0, true, true);
91 // composer.sendQueue(); 91 // composer.sendQueue();
92 composer.showMaximized(); 92 composer.showMaximized();
93 composer.exec(); 93 composer.exec();
94 //composer.close(); 94 //composer.close();
95} 95}
96 96
97void MainWindow::slotSearch() 97void MainWindow::slotSearch()
98{ 98{
99 SearchDiag searchDiag(this, 0, true); 99 SearchDiag searchDiag(this, 0, true);
100 searchDiag.showMaximized(); 100 searchDiag.showMaximized();
101 searchDiag.exec(); 101 searchDiag.exec();
102} 102}
103 103
104void MainWindow::slotConfigure() 104void MainWindow::slotConfigure()
105{ 105{
106 ConfigDiag configDiag(this, 0, true); 106 ConfigDiag configDiag(this, 0, true);
107 configDiag.showMaximized(); 107 configDiag.showMaximized();
108 configDiag.exec(); 108 configDiag.exec();
109 109
110 connect(&configDiag, SIGNAL(changed()), folderView, SLOT(update())); 110 connect(&configDiag, SIGNAL(changed()), folderView, SLOT(update()));
111} 111}
112 112
113void MainWindow::mailClicked(IMAPResponseFETCH mail, IMAPHandler *handler) 113void MainWindow::mailClicked(IMAPResponseFETCH mail, IMAPHandler *handler)
114{ 114{
115 ViewMail viewMail(mail, handler, this, 0, true); 115 ViewMail viewMail(mail, handler, this, 0, true);
116 viewMail.showMaximized(); 116 viewMail.showMaximized();
117 viewMail.exec(); 117 viewMail.exec();
118} 118}
diff --git a/noncore/unsupported/mail2/searchdiag.cpp b/noncore/unsupported/mail2/searchdiag.cpp
index 907f6ff..6fb4e4d 100644
--- a/noncore/unsupported/mail2/searchdiag.cpp
+++ b/noncore/unsupported/mail2/searchdiag.cpp
@@ -1,128 +1,128 @@
1#include <qmessagebox.h> 1#include <qmessagebox.h>
2#include <qpushbutton.h> 2#include <qpushbutton.h>
3#include <qcombobox.h> 3#include <qcombobox.h>
4#include <qlineedit.h> 4#include <qlineedit.h>
5 5
6#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7 7
8#include "imaphandler.h" 8#include "imaphandler.h"
9#include "searchdiag.h" 9#include "searchdiag.h"
10#include "viewmail.h" 10#include "viewmail.h"
11 11
12 #define INMENU_BODY0 12 #define INMENU_BODY0
13 #define INMENU_HEADERF1 13 #define INMENU_HEADERF1
14 #define INMENU_SUBJECT2 14 #define INMENU_SUBJECT2
15 #define INMENU_FROM3 15 #define INMENU_FROM3
16 #define INMENU_TO4 16 #define INMENU_TO4
17 17
18SearchDiag::SearchDiag(QWidget *parent, const char *name, WFlags fl) 18SearchDiag::SearchDiag(QWidget *parent, const char *name, WFlags fl)
19 : SearchDiagBase(parent, name, fl) 19 : SearchDiagBase(parent, name, fl)
20 { 20 {
21 _selected = false; 21 _selected = false;
22 22
23 in->insertItem(tr("Body"), INMENU_BODY); 23 in->insertItem(tr("Body"), INMENU_BODY);
24 in->insertItem(tr("Header Field"), INMENU_HEADERF); 24 in->insertItem(tr("Header Field"), INMENU_HEADERF);
25 in->insertItem(tr("Subject"), INMENU_SUBJECT); 25 in->insertItem(tr("Subject"), INMENU_SUBJECT);
26 in->insertItem(tr("From"), INMENU_FROM); 26 in->insertItem(tr("From"), INMENU_FROM);
27 in->insertItem(tr("To"), INMENU_TO); 27 in->insertItem(tr("To"), INMENU_TO);
28 28
29 connect(folderView, SIGNAL(folderSelected(Folder)), SLOT(folderSelected(Folder))); 29 connect(folderView, SIGNAL(folderSelected(Folder)), SLOT(folderSelected(Folder)));
30 connect(in, SIGNAL(activated(int)), SLOT(slotInItemActivated(int))); 30 connect(in, SIGNAL(activated(int)), SLOT(slotInItemActivated(int)));
31 connect(mailTable, SIGNAL(mailClicked(IMAPResponseFETCH, IMAPHandler *)), SLOT(slotMailClicked(IMAPResponseFETCH, IMAPHandler *))); 31 connect(mailTable, SIGNAL(mailClicked(IMAPResponseFETCH,IMAPHandler*)), SLOT(slotMailClicked(IMAPResponseFETCH,IMAPHandler*)));
32} 32}
33 33
34void SearchDiag::accept() 34void SearchDiag::accept()
35{ 35{
36 if (searchFor->text().isEmpty()) { 36 if (searchFor->text().isEmpty()) {
37 QMessageBox::information(this, tr("Error"), tr("<p>Please enter what to search for.</p>"), tr("Ok")); 37 QMessageBox::information(this, tr("Error"), tr("<p>Please enter what to search for.</p>"), tr("Ok"));
38 return; 38 return;
39 } 39 }
40 40
41 if (!_selected) { 41 if (!_selected) {
42 QMessageBox::information(this, tr("Error"), tr("<p>Please select a folder.</p>"), tr("Ok")); 42 QMessageBox::information(this, tr("Error"), tr("<p>Please select a folder.</p>"), tr("Ok"));
43 return; 43 return;
44 } 44 }
45 45
46 if (in->currentItem() == INMENU_HEADERF && other->currentText().isEmpty()) { 46 if (in->currentItem() == INMENU_HEADERF && other->currentText().isEmpty()) {
47 QMessageBox::information(this, tr("Error"), tr("<p>Please enter a header field to search in.</p>"), tr("Ok")); 47 QMessageBox::information(this, tr("Error"), tr("<p>Please enter a header field to search in.</p>"), tr("Ok"));
48 return; 48 return;
49 } 49 }
50 50
51 _folder.topFolder().handler()->iSelect(_folder.fullName()); 51 _folder.topFolder().handler()->iSelect(_folder.fullName());
52 connect(_folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPSelect(IMAPResponse &))); 52 connect(_folder.topFolder().handler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPSelect(IMAPResponse&)));
53} 53}
54 54
55void SearchDiag::folderSelected(Folder folder) 55void SearchDiag::folderSelected(Folder folder)
56{ 56{
57 _selected = true; 57 _selected = true;
58 _folder = folder; 58 _folder = folder;
59} 59}
60 60
61void SearchDiag::slotIMAPSelect(IMAPResponse &response) 61void SearchDiag::slotIMAPSelect(IMAPResponse &response)
62{ 62{
63 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPSelect(IMAPResponse &))); 63 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPSelect(IMAPResponse&)));
64 64
65 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 65 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
66 if (in->currentItem() == INMENU_BODY) { 66 if (in->currentItem() == INMENU_BODY) {
67 response.imapHandler()->iSearch("BODY \"" + searchFor->text() + "\""); 67 response.imapHandler()->iSearch("BODY \"" + searchFor->text() + "\"");
68 } else if (in->currentItem() == INMENU_HEADERF) { 68 } else if (in->currentItem() == INMENU_HEADERF) {
69 response.imapHandler()->iSearch("HEADER \""+ other->currentText() + "\" \"" + searchFor->text() + "\""); 69 response.imapHandler()->iSearch("HEADER \""+ other->currentText() + "\" \"" + searchFor->text() + "\"");
70 } else if (in->currentItem() == INMENU_SUBJECT) { 70 } else if (in->currentItem() == INMENU_SUBJECT) {
71 response.imapHandler()->iSearch("SUBJECT \"" + searchFor->text() + "\""); 71 response.imapHandler()->iSearch("SUBJECT \"" + searchFor->text() + "\"");
72 } else if (in->currentItem() == INMENU_FROM) { 72 } else if (in->currentItem() == INMENU_FROM) {
73 response.imapHandler()->iSearch("FROM \"" + searchFor->text() + "\""); 73 response.imapHandler()->iSearch("FROM \"" + searchFor->text() + "\"");
74 } else if (in->currentItem() == INMENU_TO) { 74 } else if (in->currentItem() == INMENU_TO) {
75 response.imapHandler()->iSearch("TO \"" + searchFor->text() + "\""); 75 response.imapHandler()->iSearch("TO \"" + searchFor->text() + "\"");
76 } else return; 76 } else return;
77 77
78 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPSearch(IMAPResponse &))); 78 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPSearch(IMAPResponse&)));
79 } else { 79 } else {
80 QMessageBox::warning(this, tr("Error"), tr("<p>Could not select the folder. Aborting. (Server said: %1)").arg(response.statusResponse().comment()), tr("Ok")); 80 QMessageBox::warning(this, tr("Error"), tr("<p>Could not select the folder. Aborting. (Server said: %1)").arg(response.statusResponse().comment()), tr("Ok"));
81 } 81 }
82} 82}
83 83
84void SearchDiag::slotIMAPSearch(IMAPResponse &response) 84void SearchDiag::slotIMAPSearch(IMAPResponse &response)
85{ 85{
86 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPSearch(IMAPResponse &))); 86 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPSearch(IMAPResponse&)));
87 87
88 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 88 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
89 IMAPResponseSEARCH results = response.SEARCH()[0]; 89 IMAPResponseSEARCH results = response.SEARCH()[0];
90 if (results.mails().count() == 0) { 90 if (results.mails().count() == 0) {
91 QMessageBox::information(this, tr("Results"), tr("<p>No mails match your criteria.</p>"), tr("Ok")); 91 QMessageBox::information(this, tr("Results"), tr("<p>No mails match your criteria.</p>"), tr("Ok"));
92 return; 92 return;
93 } 93 }
94 94
95 response.imapHandler()->iFetch(results.mails().join(","), "ENVELOPE FLAGS UID"); 95 response.imapHandler()->iFetch(results.mails().join(","), "ENVELOPE FLAGS UID");
96 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPFetch(IMAPResponse &))); 96 connect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPFetch(IMAPResponse&)));
97 } else { 97 } else {
98 QMessageBox::warning(this, tr("Error"), tr("<p>Search failed. (Server said: %1)").arg(response.statusResponse().comment()), tr("Ok")); 98 QMessageBox::warning(this, tr("Error"), tr("<p>Search failed. (Server said: %1)").arg(response.statusResponse().comment()), tr("Ok"));
99 } 99 }
100} 100}
101 101
102void SearchDiag::slotIMAPFetch(IMAPResponse &response) 102void SearchDiag::slotIMAPFetch(IMAPResponse &response)
103{ 103{
104 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPSearch(IMAPResponse &))); 104 disconnect(response.imapHandler(), SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPSearch(IMAPResponse&)));
105 105
106 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 106 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
107 mailTable->setHeaders(response.FETCH()); 107 mailTable->setHeaders(response.FETCH());
108 } else { 108 } else {
109 QMessageBox::warning(this, tr("Error"), tr("<p>Couldn't fetch the mail headers. (Server said: %1)").arg(response.statusResponse().comment())); 109 QMessageBox::warning(this, tr("Error"), tr("<p>Couldn't fetch the mail headers. (Server said: %1)").arg(response.statusResponse().comment()));
110 } 110 }
111} 111}
112 112
113void SearchDiag::slotMailClicked(IMAPResponseFETCH fetch, IMAPHandler *) 113void SearchDiag::slotMailClicked(IMAPResponseFETCH fetch, IMAPHandler *)
114{ 114{
115 ViewMail viewMail(fetch, _folder.topFolder().handler(), this, 0, true); 115 ViewMail viewMail(fetch, _folder.topFolder().handler(), this, 0, true);
116 viewMail.showMaximized(); 116 viewMail.showMaximized();
117 viewMail.exec(); 117 viewMail.exec();
118} 118}
119 119
120void SearchDiag::slotInItemActivated(int index) 120void SearchDiag::slotInItemActivated(int index)
121{ 121{
122 if (index == INMENU_HEADERF) { 122 if (index == INMENU_HEADERF) {
123 other->setEnabled(true); 123 other->setEnabled(true);
124 } else { 124 } else {
125 other->setEnabled(false); 125 other->setEnabled(false);
126 } 126 }
127} 127}
128 128
diff --git a/noncore/unsupported/mail2/viewmail.cpp b/noncore/unsupported/mail2/viewmail.cpp
index da6924d..0cfb6e5 100644
--- a/noncore/unsupported/mail2/viewmail.cpp
+++ b/noncore/unsupported/mail2/viewmail.cpp
@@ -1,198 +1,198 @@
1#include <qtextbrowser.h> 1#include <qtextbrowser.h>
2#include <qmessagebox.h> 2#include <qmessagebox.h>
3#include <qaction.h> 3#include <qaction.h>
4#include <qapplication.h> 4#include <qapplication.h>
5 5
6#include "mailfactory.h" 6#include "mailfactory.h"
7#include "composer.h" 7#include "composer.h"
8#include "viewmail.h" 8#include "viewmail.h"
9 9
10AttachItem::AttachItem(QListView *parent, AttachItemStore &attachItemStore) 10AttachItem::AttachItem(QListView *parent, AttachItemStore &attachItemStore)
11 : QListViewItem(parent), _attachItemStore(attachItemStore) 11 : QListViewItem(parent), _attachItemStore(attachItemStore)
12{ 12{
13 setText(0, _attachItemStore.mimeType()); 13 setText(0, _attachItemStore.mimeType());
14 setText(1, _attachItemStore.fileName()); 14 setText(1, _attachItemStore.fileName());
15 setText(2, _attachItemStore.description()); 15 setText(2, _attachItemStore.description());
16} 16}
17 17
18AttachItem::AttachItem(QListViewItem *parent, AttachItemStore &attachItemStore) 18AttachItem::AttachItem(QListViewItem *parent, AttachItemStore &attachItemStore)
19 : QListViewItem(parent), _attachItemStore(attachItemStore) 19 : QListViewItem(parent), _attachItemStore(attachItemStore)
20{ 20{
21 setText(0, _attachItemStore.mimeType()); 21 setText(0, _attachItemStore.mimeType());
22 setText(1, _attachItemStore.fileName()); 22 setText(1, _attachItemStore.fileName());
23 setText(2, _attachItemStore.description()); 23 setText(2, _attachItemStore.description());
24} 24}
25 25
26ViewMail::ViewMail(IMAPResponseFETCH &mail, IMAPHandler *handler, QWidget *parent, const char *name, WFlags fl) 26ViewMail::ViewMail(IMAPResponseFETCH &mail, IMAPHandler *handler, QWidget *parent, const char *name, WFlags fl)
27 : ViewMailBase(parent, name, fl), _inLoop(false), _mail(mail), _handler(handler) 27 : ViewMailBase(parent, name, fl), _inLoop(false), _mail(mail), _handler(handler)
28{ 28{
29 setCaption(caption().arg(mail.envelope().from()[0].name())); 29 setCaption(caption().arg(mail.envelope().from()[0].name()));
30 30
31 _gotBody = false; 31 _gotBody = false;
32 _mailHtml = tr( 32 _mailHtml = tr(
33 "<html><body>" 33 "<html><body>"
34 "<div align=center><b>%1</b></div>" 34 "<div align=center><b>%1</b></div>"
35 "<b>From:</b> %2<br>" 35 "<b>From:</b> %2<br>"
36 "<b>To:</b> %3<br>" 36 "<b>To:</b> %3<br>"
37 "%4" 37 "%4"
38 "%5" 38 "%5"
39 "<b>Date:</b> %6<hr>" 39 "<b>Date:</b> %6<hr>"
40 "<font face=fixed>%7</font>") 40 "<font face=fixed>%7</font>")
41 .arg(deHtml(mail.envelope().subject().isNull() ? tr("(no subject)") 41 .arg(deHtml(mail.envelope().subject().isNull() ? tr("(no subject)")
42 : deHtml(mail.envelope().subject()))) 42 : deHtml(mail.envelope().subject())))
43 .arg(deHtml(mail.envelope().from().toString().isNull() ? tr("(no from)") 43 .arg(deHtml(mail.envelope().from().toString().isNull() ? tr("(no from)")
44 : mail.envelope().from().toString())) 44 : mail.envelope().from().toString()))
45 .arg(deHtml(mail.envelope().to().toString().isNull() ? tr("(no recipient)") 45 .arg(deHtml(mail.envelope().to().toString().isNull() ? tr("(no recipient)")
46 : mail.envelope().to().toString())) 46 : mail.envelope().to().toString()))
47 .arg(mail.envelope().cc().toString().isNull() ? QString(0) 47 .arg(mail.envelope().cc().toString().isNull() ? QString(0)
48 : tr("<b>Cc:</b> %1<br>").arg(deHtml(mail.envelope().cc().toString()))) 48 : tr("<b>Cc:</b> %1<br>").arg(deHtml(mail.envelope().cc().toString())))
49 .arg(mail.envelope().bcc().toString().isNull() ? QString(0) 49 .arg(mail.envelope().bcc().toString().isNull() ? QString(0)
50 : tr("<b>Bcc:</b> %1<br>").arg(deHtml(mail.envelope().bcc().toString()))) 50 : tr("<b>Bcc:</b> %1<br>").arg(deHtml(mail.envelope().bcc().toString())))
51 .arg(mail.envelope().mailDate().isNull() ? tr("(no date)") 51 .arg(mail.envelope().mailDate().isNull() ? tr("(no date)")
52 : mail.envelope().mailDate()) 52 : mail.envelope().mailDate())
53 .arg("%1"); 53 .arg("%1");
54 54
55 connect(reply, SIGNAL(activated()), SLOT(slotReply())); 55 connect(reply, SIGNAL(activated()), SLOT(slotReply()));
56 connect(forward, SIGNAL(activated()), SLOT(slotForward())); 56 connect(forward, SIGNAL(activated()), SLOT(slotForward()));
57 57
58 attachments->setEnabled(_gotBody); 58 attachments->setEnabled(_gotBody);
59 browser->setText(QString(_mailHtml).arg(tr("Getting mail body from server. Please wait..."))); 59 browser->setText(QString(_mailHtml).arg(tr("Getting mail body from server. Please wait...")));
60 60
61 _handler->iUid("FETCH", QString("%1 (BODY[1])").arg(mail.uid())); 61 _handler->iUid("FETCH", QString("%1 (BODY[1])").arg(mail.uid()));
62 connect(_handler, SIGNAL(gotResponse(IMAPResponse &)), SLOT(slotIMAPUid(IMAPResponse &))); 62 connect(_handler, SIGNAL(gotResponse(IMAPResponse&)), SLOT(slotIMAPUid(IMAPResponse&)));
63} 63}
64 64
65ViewMail::~ViewMail() 65ViewMail::~ViewMail()
66{ 66{
67 hide(); 67 hide();
68} 68}
69 69
70void ViewMail::hide() 70void ViewMail::hide()
71{ 71{
72 QWidget::hide(); 72 QWidget::hide();
73 73
74 if (_inLoop) { 74 if (_inLoop) {
75 _inLoop = false; 75 _inLoop = false;
76 qApp->exit_loop(); 76 qApp->exit_loop();
77 } 77 }
78} 78}
79 79
80void ViewMail::exec() 80void ViewMail::exec()
81{ 81{
82 show(); 82 show();
83 83
84 if (!_inLoop) { 84 if (!_inLoop) {
85 _inLoop = true; 85 _inLoop = true;
86 qApp->enter_loop(); 86 qApp->enter_loop();
87 } 87 }
88} 88}
89 89
90QString ViewMail::deHtml(const QString &string) 90QString ViewMail::deHtml(const QString &string)
91{ 91{
92 QString string_ = string; 92 QString string_ = string;
93 string_.replace(QRegExp("&"), "&amp;"); 93 string_.replace(QRegExp("&"), "&amp;");
94 string_.replace(QRegExp("<"), "&lt;"); 94 string_.replace(QRegExp("<"), "&lt;");
95 string_.replace(QRegExp(">"), "&gt;"); 95 string_.replace(QRegExp(">"), "&gt;");
96 string_.replace(QRegExp("\\n"), "<br>"); 96 string_.replace(QRegExp("\\n"), "<br>");
97 return string_; 97 return string_;
98} 98}
99 99
100void ViewMail::slotReply() 100void ViewMail::slotReply()
101{ 101{
102 if (!_gotBody) { 102 if (!_gotBody) {
103 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot reply yet."), tr("Ok")); 103 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot reply yet."), tr("Ok"));
104 return; 104 return;
105 } 105 }
106 106
107 QString rtext; 107 QString rtext;
108 rtext += QString("* %1 wrote on %2:\n") // no i18n on purpose 108 rtext += QString("* %1 wrote on %2:\n") // no i18n on purpose
109 .arg(_mail.envelope().from()[0].toString()) 109 .arg(_mail.envelope().from()[0].toString())
110 .arg(_mail.envelope().mailDate()); 110 .arg(_mail.envelope().mailDate());
111 111
112 QString text = _mail.bodyPart(1).data(); 112 QString text = _mail.bodyPart(1).data();
113 QStringList lines = QStringList::split(QRegExp("\\n"), text); 113 QStringList lines = QStringList::split(QRegExp("\\n"), text);
114 QStringList::Iterator it; 114 QStringList::Iterator it;
115 for (it = lines.begin(); it != lines.end(); it++) { 115 for (it = lines.begin(); it != lines.end(); it++) {
116 rtext += "> " + *it + "\n"; 116 rtext += "> " + *it + "\n";
117 } 117 }
118 rtext += "\n"; 118 rtext += "\n";
119 119
120 QString prefix; 120 QString prefix;
121 if (_mail.envelope().subject().find(QRegExp("^Re: *$")) != -1) prefix = ""; 121 if (_mail.envelope().subject().find(QRegExp("^Re: *$")) != -1) prefix = "";
122 else prefix = "Re: "; // no i18n on purpose 122 else prefix = "Re: "; // no i18n on purpose
123 123
124 SendMail sendMail; 124 SendMail sendMail;
125 sendMail.setTo(_mail.envelope().from()[0].toString()); 125 sendMail.setTo(_mail.envelope().from()[0].toString());
126 sendMail.setSubject(prefix + _mail.envelope().subject()); 126 sendMail.setSubject(prefix + _mail.envelope().subject());
127 sendMail.setInReplyTo(_mail.envelope().messageId()); 127 sendMail.setInReplyTo(_mail.envelope().messageId());
128 sendMail.setMessage(rtext); 128 sendMail.setMessage(rtext);
129 129
130 Composer composer(this, 0, true); 130 Composer composer(this, 0, true);
131 composer.setSendMail(sendMail); 131 composer.setSendMail(sendMail);
132 composer.showMaximized(); 132 composer.showMaximized();
133 composer.exec(); 133 composer.exec();
134} 134}
135 135
136void ViewMail::slotForward() 136void ViewMail::slotForward()
137{ 137{
138 if (!_gotBody) { 138 if (!_gotBody) {
139 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot forward yet."), tr("Ok")); 139 QMessageBox::information(this, tr("Error"), tr("<p>The mail body is not yet downloaded, so you cannot forward yet."), tr("Ok"));
140 return; 140 return;
141 } 141 }
142 142
143 QString ftext; 143 QString ftext;
144 ftext += QString("\n----- Forwarded message from %1 -----\n\n") 144 ftext += QString("\n----- Forwarded message from %1 -----\n\n")
145 .arg(_mail.envelope().from()[0].toString()); 145 .arg(_mail.envelope().from()[0].toString());
146 if (!_mail.envelope().mailDate().isNull()) 146 if (!_mail.envelope().mailDate().isNull())
147 ftext += QString("Date: %1\n") 147 ftext += QString("Date: %1\n")
148 .arg(_mail.envelope().mailDate()); 148 .arg(_mail.envelope().mailDate());
149 if (!_mail.envelope().from()[0].toString().isNull()) 149 if (!_mail.envelope().from()[0].toString().isNull())
150 ftext += QString("From: %1\n") 150 ftext += QString("From: %1\n")
151 .arg(_mail.envelope().from()[0].toString()); 151 .arg(_mail.envelope().from()[0].toString());
152 if (!_mail.envelope().to().toString().isNull()) 152 if (!_mail.envelope().to().toString().isNull())
153 ftext += QString("To: %1\n") 153 ftext += QString("To: %1\n")
154 .arg(_mail.envelope().to().toString()); 154 .arg(_mail.envelope().to().toString());
155 if (!_mail.envelope().cc().toString().isNull()) 155 if (!_mail.envelope().cc().toString().isNull())
156 ftext += QString("Cc: %1\n") 156 ftext += QString("Cc: %1\n")
157 .arg(_mail.envelope().cc().toString()); 157 .arg(_mail.envelope().cc().toString());
158 if (!_mail.envelope().bcc().toString().isNull()) 158 if (!_mail.envelope().bcc().toString().isNull())
159 ftext += QString("Bcc: %1\n") 159 ftext += QString("Bcc: %1\n")
160 .arg(_mail.envelope().bcc().toString()); 160 .arg(_mail.envelope().bcc().toString());
161 if (!_mail.envelope().subject().isNull()) 161 if (!_mail.envelope().subject().isNull())
162 ftext += QString("Subject: %1\n") 162 ftext += QString("Subject: %1\n")
163 .arg(_mail.envelope().subject()); 163 .arg(_mail.envelope().subject());
164 164
165 ftext += QString("\n%1\n") 165 ftext += QString("\n%1\n")
166 .arg(_mail.bodyPart(1).data()); 166 .arg(_mail.bodyPart(1).data());
167 167
168 ftext += QString("----- End forwarded message -----\n"); 168 ftext += QString("----- End forwarded message -----\n");
169 169
170 SendMail sendMail; 170 SendMail sendMail;
171 sendMail.setSubject("Fwd: " + _mail.envelope().subject()); 171 sendMail.setSubject("Fwd: " + _mail.envelope().subject());
172 sendMail.setMessage(ftext); 172 sendMail.setMessage(ftext);
173 173
174 Composer composer(this, 0, true); 174 Composer composer(this, 0, true);
175 composer.setSendMail(sendMail); 175 composer.setSendMail(sendMail);
176 composer.showMaximized(); 176 composer.showMaximized();
177 composer.exec(); 177 composer.exec();
178} 178}
179 179
180void ViewMail::slotIMAPUid(IMAPResponse &response) 180void ViewMail::slotIMAPUid(IMAPResponse &response)
181{ 181{
182 disconnect(_handler, SIGNAL(gotResponse(IMAPResponse &)), this, SLOT(slotIMAPUid(IMAPResponse &))); 182 disconnect(_handler, SIGNAL(gotResponse(IMAPResponse&)), this, SLOT(slotIMAPUid(IMAPResponse&)));
183 183
184 if (response.statusResponse().status() == IMAPResponseEnums::OK) { 184 if (response.statusResponse().status() == IMAPResponseEnums::OK) {
185 QValueList<IMAPResponseBodyPart> bodyParts; 185 QValueList<IMAPResponseBodyPart> bodyParts;
186 bodyParts.append(response.FETCH()[0].bodyPart(0)); 186 bodyParts.append(response.FETCH()[0].bodyPart(0));
187 _mail.setBodyParts(bodyParts); 187 _mail.setBodyParts(bodyParts);
188 188
189 browser->setText(QString(_mailHtml).arg(deHtml(response.FETCH()[0].bodyPart(0).data()))); 189 browser->setText(QString(_mailHtml).arg(deHtml(response.FETCH()[0].bodyPart(0).data())));
190 190
191 // fillList(response.FETCH()[0].bodyStructure()); 191 // fillList(response.FETCH()[0].bodyStructure());
192 192
193 _gotBody = true; 193 _gotBody = true;
194 } else { 194 } else {
195 QMessageBox::warning(this, tr("Error"), tr("<p>I was unable to retrieve the mail from the server. You can try again later or give up.</p>"), tr("Ok")); 195 QMessageBox::warning(this, tr("Error"), tr("<p>I was unable to retrieve the mail from the server. You can try again later or give up.</p>"), tr("Ok"));
196 } 196 }
197} 197}
198 198
diff --git a/noncore/unsupported/mailit/addatt.cpp b/noncore/unsupported/mailit/addatt.cpp
index 19ac58f..420f84c 100644
--- a/noncore/unsupported/mailit/addatt.cpp
+++ b/noncore/unsupported/mailit/addatt.cpp
@@ -1,224 +1,224 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2001 Trolltech AS. All rights reserved. 2** Copyright (C) 2001 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qt Palmtop Environment. 4** This file is part of Qt Palmtop Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include <qlayout.h> 20#include <qlayout.h>
21#include <qhbox.h> 21#include <qhbox.h>
22#include <qdir.h> 22#include <qdir.h>
23#include <qstringlist.h> 23#include <qstringlist.h>
24#include <qpe/resource.h> 24#include <qpe/resource.h>
25#include "addatt.h" 25#include "addatt.h"
26 26
27FileItem::FileItem(QListView *parent, DocLnk* dl) 27FileItem::FileItem(QListView *parent, DocLnk* dl)
28 : QListViewItem(parent) 28 : QListViewItem(parent)
29{ 29{
30 /*file = fileInfo; 30 /*file = fileInfo;
31 type = fileType;*/ 31 type = fileType;*/
32 32
33 doclnk=dl; 33 doclnk=dl;
34 34
35 setText(0, doclnk->name()); 35 setText(0, doclnk->name());
36 36
37 /*if (fileType == "Picture") { 37 /*if (fileType == "Picture") {
38 setPixmap(0, Resource::loadPixmap("pixmap")); 38 setPixmap(0, Resource::loadPixmap("pixmap"));
39 } else if (fileType == "Document") { 39 } else if (fileType == "Document") {
40 setPixmap(0, Resource::loadPixmap("txt")); 40 setPixmap(0, Resource::loadPixmap("txt"));
41 } else if (fileType == "Sound") { 41 } else if (fileType == "Sound") {
42 setPixmap(0, Resource::loadPixmap("play")); 42 setPixmap(0, Resource::loadPixmap("play"));
43 } else if (fileType == "Movie") { 43 } else if (fileType == "Movie") {
44 setPixmap(0, Resource::loadPixmap("MPEGPlayer")); 44 setPixmap(0, Resource::loadPixmap("MPEGPlayer"));
45 } else if (fileType == "File") { 45 } else if (fileType == "File") {
46 setPixmap(0, Resource::loadPixmap("exec")); 46 setPixmap(0, Resource::loadPixmap("exec"));
47 }*/ 47 }*/
48} 48}
49 49
50FileItem::~FileItem() 50FileItem::~FileItem()
51{ 51{
52 if (doclnk!=NULL) delete doclnk; 52 if (doclnk!=NULL) delete doclnk;
53 doclnk=NULL; 53 doclnk=NULL;
54} 54}
55 55
56AddAtt::AddAtt(QWidget *parent, const char *name, WFlags f) 56AddAtt::AddAtt(QWidget *parent, const char *name, WFlags f)
57 : QDialog(parent, name, f) 57 : QDialog(parent, name, f)
58{ 58{
59 setCaption(tr("Adding attachments") ); 59 setCaption(tr("Adding attachments") );
60 60
61 QGridLayout *top = new QGridLayout(this, 1,1 ); 61 QGridLayout *top = new QGridLayout(this, 1,1 );
62 62
63 QHBox *buttons=new QHBox(this); 63 QHBox *buttons=new QHBox(this);
64 /*fileCategoryButton = new QPushButton(this);*/ 64 /*fileCategoryButton = new QPushButton(this);*/
65 attachButton = new QPushButton(tr("attach..."), buttons); 65 attachButton = new QPushButton(tr("attach..."), buttons);
66 removeButton = new QPushButton(tr("Remove"), buttons); 66 removeButton = new QPushButton(tr("Remove"), buttons);
67 67
68 /*fileCategories = new QPopupMenu(fileCategoryButton); 68 /*fileCategories = new QPopupMenu(fileCategoryButton);
69 fileCategoryButton->setPopup(fileCategories); 69 fileCategoryButton->setPopup(fileCategories);
70 fileCategories->insertItem("Document"); 70 fileCategories->insertItem("Document");
71 fileCategories->insertItem("Picture"); 71 fileCategories->insertItem("Picture");
72 fileCategories->insertItem("Sound"); 72 fileCategories->insertItem("Sound");
73 fileCategories->insertItem("Movie"); 73 fileCategories->insertItem("Movie");
74 fileCategories->insertItem("File"); 74 fileCategories->insertItem("File");
75 75
76 fileCategoryButton->setText("Document"); 76 fileCategoryButton->setText("Document");
77 top->addWidget(fileCategoryButton, 0, 0);*/ 77 top->addWidget(fileCategoryButton, 0, 0);*/
78 78
79 79
80 top->addWidget(buttons,1,0); 80 top->addWidget(buttons,1,0);
81 //buttons->addWidget(attachButton,0,0); 81 //buttons->addWidget(attachButton,0,0);
82 //buttons->addWidget(removeButton,0,1); 82 //buttons->addWidget(removeButton,0,1);
83 83
84 //connect(fileCategories, SIGNAL(activated(int)), this, 84 //connect(fileCategories, SIGNAL(activated(int)), this,
85 //SLOT(fileCategorySelected(int)) );*/ 85 //SLOT(fileCategorySelected(int)) );*/
86 connect(attachButton, SIGNAL(clicked()), this, 86 connect(attachButton, SIGNAL(clicked()), this,
87 SLOT(addattachment()) ); 87 SLOT(addattachment()) );
88 connect(removeButton, SIGNAL(clicked()), this, 88 connect(removeButton, SIGNAL(clicked()), this,
89 SLOT(removeattachment()) ); 89 SLOT(removeattachment()) );
90 90
91 /*listView = new QListView(this, "AttView"); 91 /*listView = new QListView(this, "AttView");
92 listView->addColumn("Documents");* 92 listView->addColumn("Documents");*
93 connect(listView, SIGNAL(doubleClicked(QListViewItem *)), this, 93 connect(listView, SIGNAL(doubleClicked(QListViewItem*)), this,
94 SLOT(addattachment()) );*/ 94 SLOT(addattachment()) );*/
95 95
96 96
97 attView = new QListView(this, "Selected"); 97 attView = new QListView(this, "Selected");
98 attView->addColumn(tr("Attached")); 98 attView->addColumn(tr("Attached"));
99 attView->addColumn(tr("File type")); 99 attView->addColumn(tr("File type"));
100 connect(attView, SIGNAL(doubleClicked(QListViewItem *)), this, 100 connect(attView, SIGNAL(doubleClicked(QListViewItem*)), this,
101 SLOT(removeattachment()) ); 101 SLOT(removeattachment()) );
102 102
103 //top->addWidget(ofs, 0,0); 103 //top->addWidget(ofs, 0,0);
104 top->addWidget(attView, 0,0); 104 top->addWidget(attView, 0,0);
105 105
106 clear(); 106 clear();
107 107
108 108
109} 109}
110 110
111void AddAtt::clear() 111void AddAtt::clear()
112{ 112{
113 attView->clear(); 113 attView->clear();
114 //getFiles(); 114 //getFiles();
115 modified = FALSE; 115 modified = FALSE;
116} 116}
117 117
118/*void AddAtt::fileCategorySelected(int id) 118/*void AddAtt::fileCategorySelected(int id)
119{ 119{
120 fileCategoryButton->setText(fileCategories->text(id)); 120 fileCategoryButton->setText(fileCategories->text(id));
121 getFiles(); 121 getFiles();
122}*/ 122}*/
123 123
124void AddAtt::addattachment() 124void AddAtt::addattachment()
125 {// ### FIXME wrong use -zecke 125 {// ### FIXME wrong use -zecke
126 OFileDialog ofs("Attachments",this,0,0,"/root/Documents"); 126 OFileDialog ofs("Attachments",this,0,0,"/root/Documents");
127 127
128 ofs.showMaximized(); 128 ofs.showMaximized();
129 129
130 if (ofs.exec()==QDialog::Accepted) 130 if (ofs.exec()==QDialog::Accepted)
131 { 131 {
132 DocLnk* dl=new DocLnk(ofs.selectedDocument()); 132 DocLnk* dl=new DocLnk(ofs.selectedDocument());
133 FileItem* fi=new FileItem(attView,dl); 133 FileItem* fi=new FileItem(attView,dl);
134 fi->setPixmap(0,dl->pixmap()); 134 fi->setPixmap(0,dl->pixmap());
135 fi->setText(1,dl->type()); 135 fi->setText(1,dl->type());
136 attView->insertItem(fi); 136 attView->insertItem(fi);
137 modified = TRUE; 137 modified = TRUE;
138 } 138 }
139} 139}
140 140
141void AddAtt::removeattachment() 141void AddAtt::removeattachment()
142{ 142{
143 if (attView->selectedItem() != NULL) 143 if (attView->selectedItem() != NULL)
144 { 144 {
145 attView->takeItem(attView->selectedItem()); 145 attView->takeItem(attView->selectedItem());
146 } 146 }
147 modified = TRUE; 147 modified = TRUE;
148} 148}
149 149
150void AddAtt::reject() 150void AddAtt::reject()
151{ 151{
152 if (modified) { 152 if (modified) {
153 attView->clear(); 153 attView->clear();
154 modified = FALSE; 154 modified = FALSE;
155 } 155 }
156} 156}
157 157
158void AddAtt::accept() 158void AddAtt::accept()
159{ 159{
160 modified = FALSE; 160 modified = FALSE;
161 hide(); 161 hide();
162} 162}
163 163
164void AddAtt::getFiles() 164void AddAtt::getFiles()
165{ 165{
166 QString path, selected; 166 QString path, selected;
167 167
168 /*listView->clear(); 168 /*listView->clear();
169 169
170 selected = fileCategoryButton->text(); 170 selected = fileCategoryButton->text();
171 if (selected == "Picture") { 171 if (selected == "Picture") {
172 path = "../pics/"; 172 path = "../pics/";
173 } else if (selected == "Document") { 173 } else if (selected == "Document") {
174 path = "" ; //sub-dirs not decided 174 path = "" ; //sub-dirs not decided
175 } else if (selected == "Sound") { 175 } else if (selected == "Sound") {
176 path = "../sounds/"; //sub-dirs not decided 176 path = "../sounds/"; //sub-dirs not decided
177 } else if (selected == "Movie") { 177 } else if (selected == "Movie") {
178 path = ""; //sub-dirs not decided 178 path = ""; //sub-dirs not decided
179 } else if (selected == "File") { 179 } else if (selected == "File") {
180 path = ""; //sub-dirs not decided 180 path = ""; //sub-dirs not decided
181 } 181 }
182 182
183 dir = new QDir(path); 183 dir = new QDir(path);
184 dir->setFilter(QDir::Files); 184 dir->setFilter(QDir::Files);
185 const QFileInfoList *dirInfoList = dir->entryInfoList(); 185 const QFileInfoList *dirInfoList = dir->entryInfoList();
186 186
187 QFileInfoListIterator it(*dirInfoList); // create list iterator 187 QFileInfoListIterator it(*dirInfoList); // create list iterator
188 188
189 while ( (fi=it.current()) ) { // for each file... 189 while ( (fi=it.current()) ) { // for each file...
190 item = new FileItem(lis+ütView, *fi, selected); 190 item = new FileItem(lis+ütView, *fi, selected);
191 ++it; // goto next list element 191 ++it; // goto next list element
192 }*/ 192 }*/
193} 193}
194 194
195QStringList AddAtt::returnattachedFiles() 195QStringList AddAtt::returnattachedFiles()
196{ 196{
197 QFileInfo info; 197 QFileInfo info;
198 QStringList list; 198 QStringList list;
199 199
200 item = (FileItem *) attView->firstChild(); 200 item = (FileItem *) attView->firstChild();
201 201
202 202
203 while (item != NULL) { 203 while (item != NULL) {
204 DocLnk* dl=item->getDocLnk(); 204 DocLnk* dl=item->getDocLnk();
205 list+=dl->file(); 205 list+=dl->file();
206 /*info = item->getFileInfo(); 206 /*info = item->getFileInfo();
207 list += info.filePath();*/ 207 list += info.filePath();*/
208 item = (FileItem *) item->nextSibling(); 208 item = (FileItem *) item->nextSibling();
209 } 209 }
210 return list; 210 return list;
211} 211}
212 212
213QStringList AddAtt::returnFileTypes() 213QStringList AddAtt::returnFileTypes()
214{ 214{
215 QStringList list; 215 QStringList list;
216 216
217 item = (FileItem *) attView->firstChild(); 217 item = (FileItem *) attView->firstChild();
218 218
219 while (item != NULL) { 219 while (item != NULL) {
220 list += item->getDocLnk()->type(); 220 list += item->getDocLnk()->type();
221 item = (FileItem *) item->nextSibling(); 221 item = (FileItem *) item->nextSibling();
222 } 222 }
223 return list; 223 return list;
224} 224}
diff --git a/noncore/unsupported/mailit/emailclient.cpp b/noncore/unsupported/mailit/emailclient.cpp
index 8359acf..86c7987 100644
--- a/noncore/unsupported/mailit/emailclient.cpp
+++ b/noncore/unsupported/mailit/emailclient.cpp
@@ -1,1042 +1,1042 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2001 Trolltech AS. All rights reserved. 2** Copyright (C) 2001 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qt Palmtop Environment. 4** This file is part of Qt Palmtop Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include <qapplication.h> 20#include <qapplication.h>
21#include <qmessagebox.h> 21#include <qmessagebox.h>
22#include <qvbox.h> 22#include <qvbox.h>
23#include <qfile.h> 23#include <qfile.h>
24#include <qcheckbox.h> 24#include <qcheckbox.h>
25#include <qmenubar.h> 25#include <qmenubar.h>
26#include <qaction.h> 26#include <qaction.h>
27#include <qwhatsthis.h> 27#include <qwhatsthis.h>
28#include <qpe/resource.h> 28#include <qpe/resource.h>
29#include "emailclient.h" 29#include "emailclient.h"
30#include "writemail.h" 30#include "writemail.h"
31 31
32QCollection::Item AccountList::newItem(QCollection::Item d) 32QCollection::Item AccountList::newItem(QCollection::Item d)
33{ 33{
34 return dupl( (MailAccount *) d); 34 return dupl( (MailAccount *) d);
35} 35}
36 36
37MailAccount* AccountList::dupl(MailAccount *in) 37MailAccount* AccountList::dupl(MailAccount *in)
38{ 38{
39 ac = new MailAccount(*in); 39 ac = new MailAccount(*in);
40 return ac; 40 return ac;
41} 41}
42 42
43EmailClient::EmailClient( QWidget* parent, const char* name, WFlags fl ) 43EmailClient::EmailClient( QWidget* parent, const char* name, WFlags fl )
44 : QMainWindow( parent, name, fl ) 44 : QMainWindow( parent, name, fl )
45{ 45{
46 emailHandler = new EmailHandler(); 46 emailHandler = new EmailHandler();
47 addressList = new AddressList(); 47 addressList = new AddressList();
48 48
49 sending = FALSE; 49 sending = FALSE;
50 receiving = FALSE; 50 receiving = FALSE;
51 previewingMail = FALSE; 51 previewingMail = FALSE;
52 mailIdCount = 1; 52 mailIdCount = 1;
53 accountIdCount = 1; 53 accountIdCount = 1;
54 allAccounts = FALSE; 54 allAccounts = FALSE;
55 55
56 init(); 56 init();
57 57
58 58
59 59
60 connect(emailHandler, SIGNAL(mailSent()), this, SLOT(mailSent()) ); 60 connect(emailHandler, SIGNAL(mailSent()), this, SLOT(mailSent()) );
61 61
62 connect(emailHandler, SIGNAL(smtpError(int,const QString &)), this, 62 connect(emailHandler, SIGNAL(smtpError(int,const QString&)), this,
63 SLOT(smtpError(int,const QString &)) ); 63 SLOT(smtpError(int,const QString&)) );
64 connect(emailHandler, SIGNAL(popError(int,const QString &)), this, 64 connect(emailHandler, SIGNAL(popError(int,const QString&)), this,
65 SLOT(popError(int,const QString &)) ); 65 SLOT(popError(int,const QString&)) );
66 66
67 connect(inboxView, SIGNAL(doubleClicked(QListViewItem *)), this, SLOT(inboxItemSelected()) ); 67 connect(inboxView, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(inboxItemSelected()) );
68 connect(outboxView, SIGNAL(doubleClicked(QListViewItem *)), this, SLOT(outboxItemSelected()) ); 68 connect(outboxView, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(outboxItemSelected()) );
69 69
70 connect(inboxView, SIGNAL(pressed(QListViewItem *)), this, SLOT(inboxItemPressed()) ); 70 connect(inboxView, SIGNAL(pressed(QListViewItem*)), this, SLOT(inboxItemPressed()) );
71 connect(inboxView, SIGNAL(clicked(QListViewItem *)), this, SLOT(inboxItemReleased()) ); 71 connect(inboxView, SIGNAL(clicked(QListViewItem*)), this, SLOT(inboxItemReleased()) );
72 72
73 connect(emailHandler, SIGNAL(mailArrived(const Email &, bool)), this, 73 connect(emailHandler, SIGNAL(mailArrived(const Email&,bool)), this,
74 SLOT(mailArrived(const Email &, bool)) ); 74 SLOT(mailArrived(const Email&,bool)) );
75 connect(emailHandler, SIGNAL(mailTransfered(int)), this, 75 connect(emailHandler, SIGNAL(mailTransfered(int)), this,
76 SLOT(allMailArrived(int)) ); 76 SLOT(allMailArrived(int)) );
77 77
78 mailconf = new Config("mailit"); 78 mailconf = new Config("mailit");
79 //In case Synchronize is not defined in settings.txt 79 //In case Synchronize is not defined in settings.txt
80 80
81 readSettings(); 81 readSettings();
82 82
83 updateAccounts(); 83 updateAccounts();
84 84
85 lineShift = "\n"; 85 lineShift = "\n";
86 readMail(); 86 readMail();
87 lineShift = "\r\n"; 87 lineShift = "\r\n";
88 88
89 mailboxView->setCurrentTab(0); //ensure that inbox has focus 89 mailboxView->setCurrentTab(0); //ensure that inbox has focus
90 90
91 /*channel = new QCopChannel( "QPE/Application/mailit", this ); 91 /*channel = new QCopChannel( "QPE/Application/mailit", this );
92 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 92 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
93 this, SLOT(receive(const QCString&, const QByteArray&)) );*/ 93 this, SLOT(receive(const QCString&,const QByteArray&)) );*/
94 94
95} 95}
96 96
97 97
98EmailClient::~EmailClient() 98EmailClient::~EmailClient()
99{ 99{
100 //needs to be moved from destructor to closewindow event 100 //needs to be moved from destructor to closewindow event
101 saveMail(getPath(FALSE) + "inbox.txt", inboxView); 101 saveMail(getPath(FALSE) + "inbox.txt", inboxView);
102 //does not currently work. Defining outbox in the same 102 //does not currently work. Defining outbox in the same
103 //format as inbox is not a good solution as they have 103 //format as inbox is not a good solution as they have
104 //different properties 104 //different properties
105 saveMail(getPath(FALSE) + "outbox.txt", outboxView); 105 saveMail(getPath(FALSE) + "outbox.txt", outboxView);
106 saveSettings(); 106 saveSettings();
107 107
108 mailconf->write(); 108 mailconf->write();
109 delete mailconf; 109 delete mailconf;
110 110
111} 111}
112 112
113void EmailClient::init() 113void EmailClient::init()
114{ 114{
115 initStatusBar(this); 115 initStatusBar(this);
116 116
117 setToolBarsMovable(FALSE); 117 setToolBarsMovable(FALSE);
118 118
119 bar = new QToolBar(this); 119 bar = new QToolBar(this);
120 QWhatsThis::add(bar,tr("Main operation toolbar")); 120 QWhatsThis::add(bar,tr("Main operation toolbar"));
121 bar->setHorizontalStretchable( TRUE ); 121 bar->setHorizontalStretchable( TRUE );
122 122
123 mb = new QMenuBar( bar ); 123 mb = new QMenuBar( bar );
124 124
125 QPopupMenu *mail = new QPopupMenu(mb); 125 QPopupMenu *mail = new QPopupMenu(mb);
126 mb->insertItem( tr( "&Mail" ), mail); 126 mb->insertItem( tr( "&Mail" ), mail);
127 127
128 QPopupMenu *configure = new QPopupMenu(mb); 128 QPopupMenu *configure = new QPopupMenu(mb);
129 mb->insertItem( tr( "Accounts" ), configure); 129 mb->insertItem( tr( "Accounts" ), configure);
130 130
131 selectAccountMenu = new QPopupMenu(mb); 131 selectAccountMenu = new QPopupMenu(mb);
132 editAccountMenu = new QPopupMenu(mb); 132 editAccountMenu = new QPopupMenu(mb);
133 deleteAccountMenu = new QPopupMenu(mb); 133 deleteAccountMenu = new QPopupMenu(mb);
134 134
135 mail->insertItem(tr("Get Mail in"), selectAccountMenu); 135 mail->insertItem(tr("Get Mail in"), selectAccountMenu);
136 configure->insertItem(tr("Edit account"), editAccountMenu); 136 configure->insertItem(tr("Edit account"), editAccountMenu);
137 configure->insertItem(tr("Delete account"), deleteAccountMenu); 137 configure->insertItem(tr("Delete account"), deleteAccountMenu);
138 138
139 bar = new QToolBar(this); 139 bar = new QToolBar(this);
140 140
141 getMailButton = new QToolButton(Resource::loadPixmap("mailit/getmail"),tr("getMail"),tr("select account"), this,SLOT(getAllNewMail()),bar); 141 getMailButton = new QToolButton(Resource::loadPixmap("mailit/getmail"),tr("getMail"),tr("select account"), this,SLOT(getAllNewMail()),bar);
142 QWhatsThis::add(getMailButton,tr("Click to download mail via all available accounts.\n Press and hold to select the desired account.")); 142 QWhatsThis::add(getMailButton,tr("Click to download mail via all available accounts.\n Press and hold to select the desired account."));
143 143
144 getMailButton->setPopup(selectAccountMenu); 144 getMailButton->setPopup(selectAccountMenu);
145 145
146 sendMailButton = new QAction(tr("Send mail"), Resource::loadPixmap("mailit/sendqueue"), QString::null, 0, this, 0); 146 sendMailButton = new QAction(tr("Send mail"), Resource::loadPixmap("mailit/sendqueue"), QString::null, 0, this, 0);
147 connect(sendMailButton, SIGNAL(activated()), this, SLOT(sendQuedMail()) ); 147 connect(sendMailButton, SIGNAL(activated()), this, SLOT(sendQuedMail()) );
148 sendMailButton->addTo(bar); 148 sendMailButton->addTo(bar);
149 sendMailButton->addTo(mail); 149 sendMailButton->addTo(mail);
150 sendMailButton->setWhatsThis("Send mail queued in the outbox"); 150 sendMailButton->setWhatsThis("Send mail queued in the outbox");
151 151
152 composeButton = new QAction(tr("Compose"), Resource::loadPixmap("new"), QString::null, 0, this, 0); 152 composeButton = new QAction(tr("Compose"), Resource::loadPixmap("new"), QString::null, 0, this, 0);
153 connect(composeButton, SIGNAL(activated()), this, SLOT(compose()) ); 153 connect(composeButton, SIGNAL(activated()), this, SLOT(compose()) );
154 composeButton->addTo(bar); 154 composeButton->addTo(bar);
155 composeButton->addTo(mail); 155 composeButton->addTo(mail);
156 composeButton->setWhatsThis("Compose a new mail"); 156 composeButton->setWhatsThis("Compose a new mail");
157 157
158 cancelButton = new QAction(tr("Cancel transfer"), Resource::loadPixmap("close"), QString::null, 0, this, 0); 158 cancelButton = new QAction(tr("Cancel transfer"), Resource::loadPixmap("close"), QString::null, 0, this, 0);
159 connect(cancelButton, SIGNAL(activated()), this, SLOT(cancel()) ); 159 connect(cancelButton, SIGNAL(activated()), this, SLOT(cancel()) );
160 cancelButton->addTo(mail); 160 cancelButton->addTo(mail);
161 cancelButton->addTo(bar); 161 cancelButton->addTo(bar);
162 cancelButton->setEnabled(FALSE); 162 cancelButton->setEnabled(FALSE);
163 cancelButton->setWhatsThis("Stop the currently active mail transfer"); 163 cancelButton->setWhatsThis("Stop the currently active mail transfer");
164 164
165 165
166 deleteButton = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 ); 166 deleteButton = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 );
167 connect( deleteButton, SIGNAL( activated() ), this, SLOT( deleteItem() ) ); 167 connect( deleteButton, SIGNAL( activated() ), this, SLOT( deleteItem() ) );
168 deleteButton->addTo(bar); 168 deleteButton->addTo(bar);
169 deleteButton->setWhatsThis("Remove the currently selected eMail(s)"); 169 deleteButton->setWhatsThis("Remove the currently selected eMail(s)");
170 170
171 mailboxView = new OTabWidget( this, "mailboxView" ); 171 mailboxView = new OTabWidget( this, "mailboxView" );
172 172
173 QWidget* widget = new QWidget( mailboxView, "widget" ); 173 QWidget* widget = new QWidget( mailboxView, "widget" );
174 grid_2 = new QGridLayout( widget ); 174 grid_2 = new QGridLayout( widget );
175// grid_2->setSpacing(6); 175// grid_2->setSpacing(6);
176// grid_2->setMargin( 11 ); 176// grid_2->setMargin( 11 );
177 177
178 inboxView = new QListView( widget, "inboxView" ); 178 inboxView = new QListView( widget, "inboxView" );
179 inboxView->addColumn( tr( "From" ) ); 179 inboxView->addColumn( tr( "From" ) );
180 inboxView->addColumn( tr( "Subject" ) ); 180 inboxView->addColumn( tr( "Subject" ) );
181 inboxView->addColumn( tr( "Date" ) ); 181 inboxView->addColumn( tr( "Date" ) );
182 inboxView->setMinimumSize( QSize( 0, 0 ) ); 182 inboxView->setMinimumSize( QSize( 0, 0 ) );
183 inboxView->setAllColumnsShowFocus(TRUE); 183 inboxView->setAllColumnsShowFocus(TRUE);
184 QWhatsThis::add(inboxView,QWidget::tr("This is the inbox view.\n" 184 QWhatsThis::add(inboxView,QWidget::tr("This is the inbox view.\n"
185 "It keeps the fetched mail which can be \n" 185 "It keeps the fetched mail which can be \n"
186 "viewed by double clicking the entry.\n" 186 "viewed by double clicking the entry.\n"
187 "blue attachment icon shows whether this \n" 187 "blue attachment icon shows whether this \n"
188 "mailhas attachments.\n")); 188 "mailhas attachments.\n"));
189 189
190 grid_2->addWidget( inboxView, 2, 0 ); 190 grid_2->addWidget( inboxView, 2, 0 );
191 mailboxView->addTab( widget, "mailit/inbox", tr( "Inbox" ) ); 191 mailboxView->addTab( widget, "mailit/inbox", tr( "Inbox" ) );
192 192
193 QWidget* widget_2 = new QWidget( mailboxView, "widget_2" ); 193 QWidget* widget_2 = new QWidget( mailboxView, "widget_2" );
194 grid_3 = new QGridLayout( widget_2 ); 194 grid_3 = new QGridLayout( widget_2 );
195// grid_3->setSpacing(6); 195// grid_3->setSpacing(6);
196// grid_3->setMargin( 11 ); 196// grid_3->setMargin( 11 );
197 197
198 outboxView = new QListView( widget_2, "outboxView" ); 198 outboxView = new QListView( widget_2, "outboxView" );
199 outboxView->addColumn( tr( "To" ) ); 199 outboxView->addColumn( tr( "To" ) );
200 outboxView->addColumn( tr( "Subject" ) ); 200 outboxView->addColumn( tr( "Subject" ) );
201 outboxView->setAllColumnsShowFocus(TRUE); 201 outboxView->setAllColumnsShowFocus(TRUE);
202 202
203 QWhatsThis::add(outboxView,QWidget::tr("This is the outbox view.\n" 203 QWhatsThis::add(outboxView,QWidget::tr("This is the outbox view.\n"
204 "It keeps the queued mails to send which can be \n" 204 "It keeps the queued mails to send which can be \n"
205 "reviewed by double clicking the entry.")); 205 "reviewed by double clicking the entry."));
206 grid_3->addWidget( outboxView, 0, 0 ); 206 grid_3->addWidget( outboxView, 0, 0 );
207 mailboxView->addTab( widget_2,"mailit/outbox", tr( "Outbox" ) ); 207 mailboxView->addTab( widget_2,"mailit/outbox", tr( "Outbox" ) );
208 208
209 setCentralWidget(mailboxView); 209 setCentralWidget(mailboxView);
210 210
211} 211}
212 212
213void EmailClient::initStatusBar(QWidget* parent) 213void EmailClient::initStatusBar(QWidget* parent)
214{ 214{
215 statusBar = new QStatusBar(parent); 215 statusBar = new QStatusBar(parent);
216 statusBar->setSizeGripEnabled(FALSE); 216 statusBar->setSizeGripEnabled(FALSE);
217 217
218 status1Label = new QLabel( tr("Idle"), statusBar); 218 status1Label = new QLabel( tr("Idle"), statusBar);
219 status2Label = new QLabel("", statusBar); 219 status2Label = new QLabel("", statusBar);
220 connect(emailHandler, SIGNAL(updatePopStatus(const QString &)), 220 connect(emailHandler, SIGNAL(updatePopStatus(const QString&)),
221 status2Label, SLOT(setText(const QString &)) ); 221 status2Label, SLOT(setText(const QString&)) );
222 connect(emailHandler, SIGNAL(updateSmtpStatus(const QString &)), 222 connect(emailHandler, SIGNAL(updateSmtpStatus(const QString&)),
223 status2Label, SLOT(setText(const QString &)) ); 223 status2Label, SLOT(setText(const QString&)) );
224 224
225 progressBar = new QProgressBar(statusBar); 225 progressBar = new QProgressBar(statusBar);
226 226
227 connect(emailHandler, SIGNAL(mailboxSize(int)), 227 connect(emailHandler, SIGNAL(mailboxSize(int)),
228 this, SLOT(setTotalSize(int)) ); 228 this, SLOT(setTotalSize(int)) );
229 connect(emailHandler, SIGNAL(currentMailSize(int)), 229 connect(emailHandler, SIGNAL(currentMailSize(int)),
230 this, SLOT(setMailSize(int)) ); 230 this, SLOT(setMailSize(int)) );
231 connect(emailHandler, SIGNAL(downloadedSize(int)), 231 connect(emailHandler, SIGNAL(downloadedSize(int)),
232 this, SLOT(setDownloadedSize(int)) ); 232 this, SLOT(setDownloadedSize(int)) );
233 233
234 statusBar->addWidget(status1Label); 234 statusBar->addWidget(status1Label);
235 statusBar->addWidget(progressBar); 235 statusBar->addWidget(progressBar);
236 statusBar->addWidget(status2Label); 236 statusBar->addWidget(status2Label);
237 237
238} 238}
239 239
240void EmailClient::compose() 240void EmailClient::compose()
241{ 241{
242 emit composeRequested(); 242 emit composeRequested();
243} 243}
244 244
245void EmailClient::cancel() 245void EmailClient::cancel()
246{ 246{
247 emailHandler->cancel(); 247 emailHandler->cancel();
248} 248}
249 249
250AddressList* EmailClient::getAdrListRef() 250AddressList* EmailClient::getAdrListRef()
251{ 251{
252 return addressList; 252 return addressList;
253} 253}
254 254
255//this needs to be rewritten to syncronize with outboxView 255//this needs to be rewritten to syncronize with outboxView
256void EmailClient::enqueMail(const Email &mail) 256void EmailClient::enqueMail(const Email &mail)
257{ 257{
258 if (accountList.count() == 0) { 258 if (accountList.count() == 0) {
259 QMessageBox::warning(qApp->activeWindow(), 259 QMessageBox::warning(qApp->activeWindow(),
260 tr("No account selected"), tr("You must create an account"), "OK\n"); 260 tr("No account selected"), tr("You must create an account"), "OK\n");
261 return; 261 return;
262 } 262 }
263 263
264 if (accountList.count() > 0) { 264 if (accountList.count() > 0) {
265 currentAccount = accountList.first(); 265 currentAccount = accountList.first();
266 qWarning("using account " + currentAccount->name); 266 qWarning("using account " + currentAccount->name);
267 } 267 }
268 268
269 Email addMail = mail; 269 Email addMail = mail;
270 addMail.from = currentAccount->name; 270 addMail.from = currentAccount->name;
271 addMail.fromMail = currentAccount->emailAddress; 271 addMail.fromMail = currentAccount->emailAddress;
272 addMail.rawMail.prepend("From: \"" + addMail.from + "\" <" + addMail.fromMail + ">\n"); 272 addMail.rawMail.prepend("From: \"" + addMail.from + "\" <" + addMail.fromMail + ">\n");
273 item = new EmailListItem(outboxView, addMail, false); 273 item = new EmailListItem(outboxView, addMail, false);
274 274
275 mailboxView->setCurrentTab(1); 275 mailboxView->setCurrentTab(1);
276 276
277} 277}
278 278
279void EmailClient::sendQuedMail() 279void EmailClient::sendQuedMail()
280{ 280{
281 int count = 0; 281 int count = 0;
282 282
283 if (accountList.count() == 0) { 283 if (accountList.count() == 0) {
284 QMessageBox::warning(qApp->activeWindow(), tr("No account selected"), tr("You must create an account"), "OK\n"); 284 QMessageBox::warning(qApp->activeWindow(), tr("No account selected"), tr("You must create an account"), "OK\n");
285 return; 285 return;
286 } 286 }
287 //traverse listview, find messages to send 287 //traverse listview, find messages to send
288 if (! sending) { 288 if (! sending) {
289 item = (EmailListItem *) outboxView->firstChild(); 289 item = (EmailListItem *) outboxView->firstChild();
290 if (item != NULL) { 290 if (item != NULL) {
291 while (item != NULL) { 291 while (item != NULL) {
292 quedMessages.append(item->getMail()); 292 quedMessages.append(item->getMail());
293 item = (EmailListItem *) item->nextSibling(); 293 item = (EmailListItem *) item->nextSibling();
294 count++; 294 count++;
295 } 295 }
296 setMailAccount(); 296 setMailAccount();
297 emailHandler->sendMail(&quedMessages); 297 emailHandler->sendMail(&quedMessages);
298 sending = TRUE; 298 sending = TRUE;
299 sendMailButton->setEnabled(FALSE); 299 sendMailButton->setEnabled(FALSE);
300 cancelButton->setEnabled(TRUE); 300 cancelButton->setEnabled(TRUE);
301 } else { 301 } else {
302 qWarning("sendQuedMail(): no messages to send"); 302 qWarning("sendQuedMail(): no messages to send");
303 } 303 }
304 } 304 }
305} 305}
306 306
307void EmailClient::setMailAccount() 307void EmailClient::setMailAccount()
308{ 308{
309 emailHandler->setAccount(*currentAccount); 309 emailHandler->setAccount(*currentAccount);
310} 310}
311 311
312void EmailClient::mailSent() 312void EmailClient::mailSent()
313{ 313{
314 sending = FALSE; 314 sending = FALSE;
315 sendMailButton->setEnabled(TRUE); 315 sendMailButton->setEnabled(TRUE);
316 316
317 quedMessages.clear(); 317 quedMessages.clear();
318 outboxView->clear(); //should be moved to an sentBox 318 outboxView->clear(); //should be moved to an sentBox
319} 319}
320 320
321void EmailClient::getNewMail() { 321void EmailClient::getNewMail() {
322 322
323 if (accountList.count() == 0) { 323 if (accountList.count() == 0) {
324 QMessageBox::warning(qApp->activeWindow(),tr("No account selected"), 324 QMessageBox::warning(qApp->activeWindow(),tr("No account selected"),
325 tr("You must create an account"), "OK\n"); 325 tr("You must create an account"), "OK\n");
326 return; 326 return;
327 } 327 }
328 328
329 setMailAccount(); 329 setMailAccount();
330 330
331 receiving = TRUE; 331 receiving = TRUE;
332 previewingMail = TRUE; 332 previewingMail = TRUE;
333 getMailButton->setEnabled(FALSE); 333 getMailButton->setEnabled(FALSE);
334 cancelButton->setEnabled(TRUE); 334 cancelButton->setEnabled(TRUE);
335 selectAccountMenu->setEnabled(FALSE); 335 selectAccountMenu->setEnabled(FALSE);
336 336
337 status1Label->setText(currentAccount->accountName + " headers"); 337 status1Label->setText(currentAccount->accountName + " headers");
338 progressBar->reset(); 338 progressBar->reset();
339 339
340 //get any previous mails not downloaded and add to queue 340 //get any previous mails not downloaded and add to queue
341 /*mailDownloadList.clear(); 341 /*mailDownloadList.clear();
342 Email *mailPtr; 342 Email *mailPtr;
343 item = (EmailListItem *) inboxView->firstChild(); 343 item = (EmailListItem *) inboxView->firstChild();
344 while (item != NULL) { 344 while (item != NULL) {
345 mailPtr = item->getMail(); 345 mailPtr = item->getMail();
346 if ( (!mailPtr->downloaded) && (mailPtr->fromAccountId == currentAccount->id) ) { 346 if ( (!mailPtr->downloaded) && (mailPtr->fromAccountId == currentAccount->id) ) {
347 mailDownloadList.sizeInsert(mailPtr->serverId, mailPtr->size); 347 mailDownloadList.sizeInsert(mailPtr->serverId, mailPtr->size);
348 } 348 }
349 item = (EmailListItem *) item->nextSibling(); 349 item = (EmailListItem *) item->nextSibling();
350 }*/ 350 }*/
351 351
352 emailHandler->getMailHeaders(); 352 emailHandler->getMailHeaders();
353 353
354} 354}
355 355
356void EmailClient::getAllNewMail() 356void EmailClient::getAllNewMail()
357{ 357{
358 allAccounts = TRUE; 358 allAccounts = TRUE;
359 currentAccount = accountList.first(); 359 currentAccount = accountList.first();
360 getNewMail(); 360 getNewMail();
361} 361}
362 362
363void EmailClient::mailArrived(const Email &mail, bool fromDisk) 363void EmailClient::mailArrived(const Email &mail, bool fromDisk)
364{ 364{
365 Enclosure *ePtr; 365 Enclosure *ePtr;
366 Email newMail; 366 Email newMail;
367 int thisMailId; 367 int thisMailId;
368 emailHandler->parse( mail.rawMail, lineShift, &newMail); 368 emailHandler->parse( mail.rawMail, lineShift, &newMail);
369 mailconf->setGroup(newMail.id); 369 mailconf->setGroup(newMail.id);
370 370
371 if (fromDisk) 371 if (fromDisk)
372 { 372 {
373 373
374 newMail.downloaded = mailconf->readBoolEntry("downloaded"); 374 newMail.downloaded = mailconf->readBoolEntry("downloaded");
375 newMail.size = mailconf->readNumEntry("size"); 375 newMail.size = mailconf->readNumEntry("size");
376 newMail.serverId = mailconf->readNumEntry("serverid"); 376 newMail.serverId = mailconf->readNumEntry("serverid");
377 newMail.fromAccountId = mailconf->readNumEntry("fromaccountid"); 377 newMail.fromAccountId = mailconf->readNumEntry("fromaccountid");
378 } 378 }
379 else 379 else
380 { //mail arrived from server 380 { //mail arrived from server
381 381
382 newMail.serverId = mail.serverId; 382 newMail.serverId = mail.serverId;
383 newMail.size = mail.size; 383 newMail.size = mail.size;
384 newMail.downloaded = mail.downloaded; 384 newMail.downloaded = mail.downloaded;
385 385
386 newMail.fromAccountId = emailHandler->getAccount()->id; 386 newMail.fromAccountId = emailHandler->getAccount()->id;
387 mailconf->writeEntry("fromaccountid", newMail.fromAccountId); 387 mailconf->writeEntry("fromaccountid", newMail.fromAccountId);
388 } 388 }
389 389
390 //add if read or not 390 //add if read or not
391 newMail.read = mailconf->readBoolEntry("mailread"); 391 newMail.read = mailconf->readBoolEntry("mailread");
392 392
393 //check if new mail 393 //check if new mail
394 if ( (thisMailId = mailconf->readNumEntry("internalmailid", -1)) == -1) { 394 if ( (thisMailId = mailconf->readNumEntry("internalmailid", -1)) == -1) {
395 thisMailId = mailIdCount; 395 thisMailId = mailIdCount;
396 mailIdCount++; 396 mailIdCount++;
397 397
398 //set server count, so that if the user aborts, the new 398 //set server count, so that if the user aborts, the new
399 //header is not reloaded 399 //header is not reloaded
400 if ((currentAccount)&&(currentAccount->synchronize)) 400 if ((currentAccount)&&(currentAccount->synchronize))
401 currentAccount->lastServerMailCount++; 401 currentAccount->lastServerMailCount++;
402 402
403 mailconf->writeEntry("internalmailid", thisMailId); 403 mailconf->writeEntry("internalmailid", thisMailId);
404 mailconf->writeEntry("downloaded", newMail.downloaded); 404 mailconf->writeEntry("downloaded", newMail.downloaded);
405 mailconf->writeEntry("size", (int) newMail.size); 405 mailconf->writeEntry("size", (int) newMail.size);
406 mailconf->writeEntry("serverid", newMail.serverId); 406 mailconf->writeEntry("serverid", newMail.serverId);
407 407
408 //addressList->addContact(newMail.fromMail, newMail.from); 408 //addressList->addContact(newMail.fromMail, newMail.from);
409 } 409 }
410 410
411 mailconf->writeEntry("downloaded", newMail.downloaded); 411 mailconf->writeEntry("downloaded", newMail.downloaded);
412 412
413 QString stringMailId; 413 QString stringMailId;
414 stringMailId.setNum(thisMailId); 414 stringMailId.setNum(thisMailId);
415 //see if any attatchments needs to be stored 415 //see if any attatchments needs to be stored
416 416
417 for ( ePtr=newMail.files.first(); ePtr != 0; ePtr=newMail.files.next() ) { 417 for ( ePtr=newMail.files.first(); ePtr != 0; ePtr=newMail.files.next() ) {
418 QString stringId; 418 QString stringId;
419 stringId.setNum(ePtr->id); 419 stringId.setNum(ePtr->id);
420 420
421 int id = mailconf->readNumEntry("enclosureid_" + stringId); 421 int id = mailconf->readNumEntry("enclosureid_" + stringId);
422 if (id != ePtr->id) { //new entry 422 if (id != ePtr->id) { //new entry
423 mailconf->writeEntry("enclosureid_" + stringId, ePtr->id); 423 mailconf->writeEntry("enclosureid_" + stringId, ePtr->id);
424 mailconf->writeEntry("name_" + stringId, ePtr->originalName); 424 mailconf->writeEntry("name_" + stringId, ePtr->originalName);
425 mailconf->writeEntry("contenttype_" + stringId, ePtr->contentType); 425 mailconf->writeEntry("contenttype_" + stringId, ePtr->contentType);
426 mailconf->writeEntry("contentattribute_" + stringId, ePtr->contentAttribute); 426 mailconf->writeEntry("contentattribute_" + stringId, ePtr->contentAttribute);
427 mailconf->writeEntry("saved_" + stringId, ePtr->saved); 427 mailconf->writeEntry("saved_" + stringId, ePtr->saved);
428 mailconf->writeEntry("installed_" + stringId, FALSE); 428 mailconf->writeEntry("installed_" + stringId, FALSE);
429 429
430 ePtr->name = stringMailId + "_" + stringId; 430 ePtr->name = stringMailId + "_" + stringId;
431 ePtr->path = getPath(TRUE); 431 ePtr->path = getPath(TRUE);
432 if (emailHandler->getEnclosure(ePtr)) { //file saved 432 if (emailHandler->getEnclosure(ePtr)) { //file saved
433 ePtr->saved = TRUE; 433 ePtr->saved = TRUE;
434 mailconf->writeEntry("saved_" + stringId, ePtr->saved); 434 mailconf->writeEntry("saved_" + stringId, ePtr->saved);
435 mailconf->writeEntry("filename_" + stringId, ePtr->name); 435 mailconf->writeEntry("filename_" + stringId, ePtr->name);
436 mailconf->writeEntry("path_" + stringId, ePtr->path); 436 mailconf->writeEntry("path_" + stringId, ePtr->path);
437 } else { 437 } else {
438 ePtr->saved = FALSE; 438 ePtr->saved = FALSE;
439 mailconf->writeEntry("saved_" + stringId, ePtr->saved); 439 mailconf->writeEntry("saved_" + stringId, ePtr->saved);
440 } 440 }
441 } else { 441 } else {
442 ePtr->saved = mailconf->readBoolEntry("saved_" + stringId); 442 ePtr->saved = mailconf->readBoolEntry("saved_" + stringId);
443 ePtr->installed = mailconf->readBoolEntry("installed_" + stringId); 443 ePtr->installed = mailconf->readBoolEntry("installed_" + stringId);
444 if (ePtr->saved) { 444 if (ePtr->saved) {
445 ePtr->name = mailconf->readEntry("filename_" + stringId); 445 ePtr->name = mailconf->readEntry("filename_" + stringId);
446 ePtr->path = mailconf->readEntry("path_" + stringId); 446 ePtr->path = mailconf->readEntry("path_" + stringId);
447 } 447 }
448 } 448 }
449 } 449 }
450 450
451 bool found=false; 451 bool found=false;
452 452
453 if (!fromDisk) 453 if (!fromDisk)
454 { 454 {
455 455
456 Email *mailPtr; 456 Email *mailPtr;
457 item = (EmailListItem *) inboxView->firstChild(); 457 item = (EmailListItem *) inboxView->firstChild();
458 while ((item != NULL)&&(!found)) 458 while ((item != NULL)&&(!found))
459 { 459 {
460 mailPtr = item->getMail(); 460 mailPtr = item->getMail();
461 if (mailPtr->id == newMail.id) { 461 if (mailPtr->id == newMail.id) {
462 item->setMail(newMail); 462 item->setMail(newMail);
463 emit mailUpdated(item->getMail()); 463 emit mailUpdated(item->getMail());
464 found = true; 464 found = true;
465 } 465 }
466 item = (EmailListItem *) item->nextSibling(); 466 item = (EmailListItem *) item->nextSibling();
467 } 467 }
468 } 468 }
469 if ((!found)||(fromDisk)) { 469 if ((!found)||(fromDisk)) {
470 item = new EmailListItem(inboxView, newMail, TRUE); 470 item = new EmailListItem(inboxView, newMail, TRUE);
471 } 471 }
472// if (item->getMail()->files.count()>0) 472// if (item->getMail()->files.count()>0)
473// { 473// {
474// item->setPixmap(0, Resource::loadPixmap("mailit/attach")); 474// item->setPixmap(0, Resource::loadPixmap("mailit/attach"));
475// } 475// }
476 /*if (!newMail.downloaded) 476 /*if (!newMail.downloaded)
477 mailDownloadList.sizeInsert(newMail.serverId, newMail.size);*/ 477 mailDownloadList.sizeInsert(newMail.serverId, newMail.size);*/
478 478
479 mailboxView->setCurrentTab(0); 479 mailboxView->setCurrentTab(0);
480 480
481} 481}
482 482
483void EmailClient::allMailArrived(int /*count*/) 483void EmailClient::allMailArrived(int /*count*/)
484{ 484{
485 // not previewing means all mailtransfer has been done 485 // not previewing means all mailtransfer has been done
486 /*if (!previewingMail) {*/ 486 /*if (!previewingMail) {*/
487 if ( (allAccounts) && ( (currentAccount = accountList.next()) !=0 ) ) { 487 if ( (allAccounts) && ( (currentAccount = accountList.next()) !=0 ) ) {
488 emit newCaption("Mailit - " + currentAccount->accountName); 488 emit newCaption("Mailit - " + currentAccount->accountName);
489 getNewMail(); 489 getNewMail();
490 return; 490 return;
491 } else { 491 } else {
492 allAccounts = FALSE; 492 allAccounts = FALSE;
493 receiving = FALSE; 493 receiving = FALSE;
494 getMailButton->setEnabled(TRUE); 494 getMailButton->setEnabled(TRUE);
495 cancelButton->setEnabled(FALSE); 495 cancelButton->setEnabled(FALSE);
496 selectAccountMenu->setEnabled(TRUE); 496 selectAccountMenu->setEnabled(TRUE);
497 status1Label->setText("Idle"); 497 status1Label->setText("Idle");
498 498
499 progressBar->reset(); 499 progressBar->reset();
500 return; 500 return;
501 } 501 }
502 //} 502 //}
503 503
504 // all headers downloaded from server, start downloading remaining mails 504 // all headers downloaded from server, start downloading remaining mails
505 previewingMail = FALSE; 505 previewingMail = FALSE;
506 status1Label->setText(currentAccount->accountName); 506 status1Label->setText(currentAccount->accountName);
507 progressBar->reset(); 507 progressBar->reset();
508 508
509 509
510 mailboxView->setCurrentTab(0); 510 mailboxView->setCurrentTab(0);
511} 511}
512 512
513 513
514void EmailClient::moveMailFront(Email *mailPtr) 514void EmailClient::moveMailFront(Email *mailPtr)
515{ 515{
516 if ( (receiving) && (mailPtr->fromAccountId == currentAccount->id) ) { 516 if ( (receiving) && (mailPtr->fromAccountId == currentAccount->id) ) {
517 mailDownloadList.moveFront(mailPtr->serverId, mailPtr->size); 517 mailDownloadList.moveFront(mailPtr->serverId, mailPtr->size);
518 } 518 }
519} 519}
520 520
521void EmailClient::smtpError(int code, const QString & Msg) 521void EmailClient::smtpError(int code, const QString & Msg)
522{ 522{
523 QString temp; 523 QString temp;
524 524
525 if (code == ErrUnknownResponse) { 525 if (code == ErrUnknownResponse) {
526 temp = tr("<qt>Unknown response from server</qt>"); 526 temp = tr("<qt>Unknown response from server</qt>");
527 if( ! Msg.isEmpty() ) 527 if( ! Msg.isEmpty() )
528 temp += Msg; 528 temp += Msg;
529 } else if (code == QSocket::ErrHostNotFound) { 529 } else if (code == QSocket::ErrHostNotFound) {
530 temp = tr("<qt>host not found</qt>"); 530 temp = tr("<qt>host not found</qt>");
531 } else if (code == QSocket::ErrConnectionRefused) { 531 } else if (code == QSocket::ErrConnectionRefused) {
532 temp = tr("<qt>connection refused</qt>"); 532 temp = tr("<qt>connection refused</qt>");
533 } else if (code == QSocket::ErrSocketRead) { 533 } else if (code == QSocket::ErrSocketRead) {
534 temp = tr("<qt>socket packet error</qt>"); 534 temp = tr("<qt>socket packet error</qt>");
535 } 535 }
536 536
537 if (code != ErrCancel) { 537 if (code != ErrCancel) {
538 QMessageBox::warning(qApp->activeWindow(), "Sending error", temp, "OK\n"); 538 QMessageBox::warning(qApp->activeWindow(), "Sending error", temp, "OK\n");
539 } else { 539 } else {
540 status2Label->setText("Aborted by user"); 540 status2Label->setText("Aborted by user");
541 } 541 }
542 542
543 sending = FALSE; 543 sending = FALSE;
544 sendMailButton->setEnabled(TRUE); 544 sendMailButton->setEnabled(TRUE);
545 cancelButton->setEnabled(FALSE); 545 cancelButton->setEnabled(FALSE);
546 quedMessages.clear(); 546 quedMessages.clear();
547} 547}
548 548
549void EmailClient::popError(int code, const QString & Msg) 549void EmailClient::popError(int code, const QString & Msg)
550{ 550{
551 QString temp; 551 QString temp;
552 552
553 if (code == ErrUnknownResponse) { 553 if (code == ErrUnknownResponse) {
554 temp = tr("<qt>Unknown response from server</qt>"); 554 temp = tr("<qt>Unknown response from server</qt>");
555 if( ! Msg.isEmpty() ) 555 if( ! Msg.isEmpty() )
556 temp += Msg; 556 temp += Msg;
557 } else if (code == ErrLoginFailed) { 557 } else if (code == ErrLoginFailed) {
558 temp = tr("<qt>Login failed\nCheck user name and password</qt>"); 558 temp = tr("<qt>Login failed\nCheck user name and password</qt>");
559 } else if (code == QSocket::ErrHostNotFound) { 559 } else if (code == QSocket::ErrHostNotFound) {
560 temp = tr("<qt>host not found</qt>"); 560 temp = tr("<qt>host not found</qt>");
561 } else if (code == QSocket::ErrConnectionRefused) { 561 } else if (code == QSocket::ErrConnectionRefused) {
562 temp = tr("<qt>connection refused</qt>"); 562 temp = tr("<qt>connection refused</qt>");
563 } else if (code == QSocket::ErrSocketRead) { 563 } else if (code == QSocket::ErrSocketRead) {
564 temp = tr("<qt>socket packet error</qt>"); 564 temp = tr("<qt>socket packet error</qt>");
565 } 565 }
566 566
567 if (code != ErrCancel) { 567 if (code != ErrCancel) {
568 QMessageBox::warning(qApp->activeWindow(), tr("Receiving error"), temp, tr("OK\n")); 568 QMessageBox::warning(qApp->activeWindow(), tr("Receiving error"), temp, tr("OK\n"));
569 569
570 } else { 570 } else {
571 status2Label->setText("Aborted by user"); 571 status2Label->setText("Aborted by user");
572 } 572 }
573 573
574 receiving = FALSE; 574 receiving = FALSE;
575 getMailButton->setEnabled(TRUE); 575 getMailButton->setEnabled(TRUE);
576 cancelButton->setEnabled(FALSE); 576 cancelButton->setEnabled(FALSE);
577 selectAccountMenu->setEnabled(TRUE); 577 selectAccountMenu->setEnabled(TRUE);
578} 578}
579 579
580void EmailClient::inboxItemSelected() 580void EmailClient::inboxItemSelected()
581{ 581{
582 //killTimer(timerID); 582 //killTimer(timerID);
583 583
584 item = (EmailListItem*) inboxView->selectedItem(); 584 item = (EmailListItem*) inboxView->selectedItem();
585 if (item != NULL) { 585 if (item != NULL) {
586 emit viewEmail(inboxView, item->getMail()); 586 emit viewEmail(inboxView, item->getMail());
587 } 587 }
588} 588}
589 589
590void EmailClient::outboxItemSelected() 590void EmailClient::outboxItemSelected()
591{ 591{
592 //killTimer(timerID); 592 //killTimer(timerID);
593 593
594 item = (EmailListItem*) outboxView->selectedItem(); 594 item = (EmailListItem*) outboxView->selectedItem();
595 if (item != NULL) { 595 if (item != NULL) {
596 emit viewEmail(outboxView, item->getMail()); 596 emit viewEmail(outboxView, item->getMail());
597 } 597 }
598 598
599} 599}
600 600
601void EmailClient::readMail() 601void EmailClient::readMail()
602{ 602{
603 Email mail; 603 Email mail;
604 int start, stop; 604 int start, stop;
605 QString s, del; 605 QString s, del;
606 606
607 QFile f(getPath(FALSE) + "inbox.txt"); 607 QFile f(getPath(FALSE) + "inbox.txt");
608 608
609 if ( f.open(IO_ReadOnly) ) { // file opened successfully 609 if ( f.open(IO_ReadOnly) ) { // file opened successfully
610 QTextStream t( &f ); // use a text stream 610 QTextStream t( &f ); // use a text stream
611 s = t.read(); 611 s = t.read();
612 f.close(); 612 f.close();
613 613
614 start = 0; 614 start = 0;
615 del = "\n.\n"; 615 del = "\n.\n";
616 while ((uint) start < s.length()) { 616 while ((uint) start < s.length()) {
617 stop = s.find(del, start); 617 stop = s.find(del, start);
618 if (stop == -1) 618 if (stop == -1)
619 stop = s.length() - del.length(); 619 stop = s.length() - del.length();
620 620
621 mail.rawMail = s.mid(start, stop + del.length() - start ); 621 mail.rawMail = s.mid(start, stop + del.length() - start );
622 start = stop + del.length(); 622 start = stop + del.length();
623 mailArrived(mail, TRUE); 623 mailArrived(mail, TRUE);
624 } 624 }
625 } 625 }
626 626
627 QFile fo(getPath(FALSE) + "outbox.txt"); 627 QFile fo(getPath(FALSE) + "outbox.txt");
628 if ( fo.open(IO_ReadOnly) ) { // file opened successfully 628 if ( fo.open(IO_ReadOnly) ) { // file opened successfully
629 QTextStream t( &fo ); // use a text stream 629 QTextStream t( &fo ); // use a text stream
630 s = t.read(); 630 s = t.read();
631 fo.close(); 631 fo.close();
632 632
633 start = 0; 633 start = 0;
634 del = "\n.\n"; 634 del = "\n.\n";
635 while ((uint) start < s.length()) { 635 while ((uint) start < s.length()) {
636 stop = s.find(del, start); 636 stop = s.find(del, start);
637 if (stop == -1) 637 if (stop == -1)
638 stop = s.length() - del.length(); 638 stop = s.length() - del.length();
639 639
640 mail.rawMail = s.mid(start, stop + del.length() - start ); 640 mail.rawMail = s.mid(start, stop + del.length() - start );
641 start = stop + del.length(); 641 start = stop + del.length();
642 emailHandler->parse(mail.rawMail, lineShift, &mail); 642 emailHandler->parse(mail.rawMail, lineShift, &mail);
643 mail.sent = false; 643 mail.sent = false;
644 mail.received = false; 644 mail.received = false;
645 enqueMail(mail); 645 enqueMail(mail);
646 646
647 } 647 }
648 } 648 }
649} 649}
650 650
651void EmailClient::saveMail(const QString &fileName, QListView *view) 651void EmailClient::saveMail(const QString &fileName, QListView *view)
652{ 652{
653 QFile f(fileName); 653 QFile f(fileName);
654 Email *mail; 654 Email *mail;
655 655
656 if (! f.open(IO_WriteOnly) ) { 656 if (! f.open(IO_WriteOnly) ) {
657 qWarning("could not open file"); 657 qWarning("could not open file");
658 return; 658 return;
659 } 659 }
660 item = (EmailListItem *) view->firstChild(); 660 item = (EmailListItem *) view->firstChild();
661 QTextStream t(&f); 661 QTextStream t(&f);
662 while (item != NULL) { 662 while (item != NULL) {
663 mail = item->getMail(); 663 mail = item->getMail();
664 t << mail->rawMail; 664 t << mail->rawMail;
665 665
666 mailconf->setGroup(mail->id); 666 mailconf->setGroup(mail->id);
667 mailconf->writeEntry("mailread", mail->read); 667 mailconf->writeEntry("mailread", mail->read);
668 668
669 item = (EmailListItem *) item->nextSibling(); 669 item = (EmailListItem *) item->nextSibling();
670 } 670 }
671 f.close(); 671 f.close();
672} 672}
673 673
674//paths for mailit, is settings, inbox, enclosures 674//paths for mailit, is settings, inbox, enclosures
675QString EmailClient::getPath(bool enclosurePath) 675QString EmailClient::getPath(bool enclosurePath)
676{ 676{
677 QString basePath = "qtmail"; 677 QString basePath = "qtmail";
678 QString enclosures = "enclosures"; 678 QString enclosures = "enclosures";
679 679
680 QDir dir = (QString(getenv("HOME")) + "/Applications/" + basePath); 680 QDir dir = (QString(getenv("HOME")) + "/Applications/" + basePath);
681 if ( !dir.exists() ) 681 if ( !dir.exists() )
682 dir.mkdir( dir.path() ); 682 dir.mkdir( dir.path() );
683 683
684 if (enclosurePath) { 684 if (enclosurePath) {
685 dir = (QString(getenv("HOME")) + "/Applications/" + basePath + "/" + enclosures); 685 dir = (QString(getenv("HOME")) + "/Applications/" + basePath + "/" + enclosures);
686 686
687 if ( !dir.exists() ) 687 if ( !dir.exists() )
688 dir.mkdir( dir.path() ); 688 dir.mkdir( dir.path() );
689 689
690 return (dir.path() + "/"); 690 return (dir.path() + "/");
691 691
692 } 692 }
693 return (dir.path() + "/"); 693 return (dir.path() + "/");
694} 694}
695 695
696void EmailClient::readSettings() 696void EmailClient::readSettings()
697{ 697{
698 int y,acc_count; 698 int y,acc_count;
699 699
700 mailconf->setGroup("mailitglobal"); 700 mailconf->setGroup("mailitglobal");
701 acc_count=mailconf->readNumEntry("Accounts",0); 701 acc_count=mailconf->readNumEntry("Accounts",0);
702 702
703 for (int accountPos = 0;accountPos<acc_count ; accountPos++) 703 for (int accountPos = 0;accountPos<acc_count ; accountPos++)
704 { 704 {
705 mailconf->setGroup("Account_"+QString::number(accountPos+1)); //Account numbers start at 1 ... 705 mailconf->setGroup("Account_"+QString::number(accountPos+1)); //Account numbers start at 1 ...
706 account.accountName = mailconf->readEntry("AccName",""); 706 account.accountName = mailconf->readEntry("AccName","");
707 account.name = mailconf->readEntry("UserName",""); 707 account.name = mailconf->readEntry("UserName","");
708 account.emailAddress = mailconf->readEntry("Email",""); 708 account.emailAddress = mailconf->readEntry("Email","");
709 account.popUserName = mailconf->readEntry("POPUser",""); 709 account.popUserName = mailconf->readEntry("POPUser","");
710 account.popPasswd = mailconf->readEntryCrypt("POPPassword",""); 710 account.popPasswd = mailconf->readEntryCrypt("POPPassword","");
711 account.popServer = mailconf->readEntry("POPServer",""); 711 account.popServer = mailconf->readEntry("POPServer","");
712 account.smtpServer = mailconf->readEntry("SMTPServer",""); 712 account.smtpServer = mailconf->readEntry("SMTPServer","");
713 account.id = mailconf->readNumEntry("AccountId",0); 713 account.id = mailconf->readNumEntry("AccountId",0);
714 account.syncLimit = mailconf->readNumEntry("HeaderLimit",0); 714 account.syncLimit = mailconf->readNumEntry("HeaderLimit",0);
715 account.lastServerMailCount = 0; 715 account.lastServerMailCount = 0;
716 account.synchronize = FALSE; 716 account.synchronize = FALSE;
717 717
718 account.synchronize = (mailconf->readEntry("Synchronize","No")=="Yes"); 718 account.synchronize = (mailconf->readEntry("Synchronize","No")=="Yes");
719 if (account.synchronize) 719 if (account.synchronize)
720 { 720 {
721 mailconf->readNumEntry("LASTSERVERMAILCOUNT",0); 721 mailconf->readNumEntry("LASTSERVERMAILCOUNT",0);
722 } 722 }
723 723
724 accountList.append(&account); 724 accountList.append(&account);
725 } 725 }
726 726
727 mailconf->setGroup("mailitglobal"); 727 mailconf->setGroup("mailitglobal");
728 728
729 if ( (y = mailconf->readNumEntry("mailidcount", -1)) != -1) 729 if ( (y = mailconf->readNumEntry("mailidcount", -1)) != -1)
730 { 730 {
731 mailIdCount = y; 731 mailIdCount = y;
732 } 732 }
733 if ( (y = mailconf->readNumEntry("accountidcount", -1)) != -1) 733 if ( (y = mailconf->readNumEntry("accountidcount", -1)) != -1)
734 { 734 {
735 accountIdCount = y; 735 accountIdCount = y;
736 } 736 }
737} 737}
738 738
739void EmailClient::saveSettings() 739void EmailClient::saveSettings()
740{ 740{
741 int acc_count=0; 741 int acc_count=0;
742 MailAccount *accountPtr; 742 MailAccount *accountPtr;
743 743
744 744
745 if (!mailconf) 745 if (!mailconf)
746 { 746 {
747 qWarning("could not save settings"); 747 qWarning("could not save settings");
748 return; 748 return;
749 } 749 }
750 750
751 for (accountPtr = accountList.first(); accountPtr != 0; 751 for (accountPtr = accountList.first(); accountPtr != 0;
752 accountPtr = accountList.next()) 752 accountPtr = accountList.next())
753 { 753 {
754 mailconf->setGroup("Account_"+QString::number(++acc_count)); 754 mailconf->setGroup("Account_"+QString::number(++acc_count));
755 mailconf->writeEntry("AccName",accountPtr->accountName ); 755 mailconf->writeEntry("AccName",accountPtr->accountName );
756 mailconf->writeEntry("UserName",accountPtr->name); 756 mailconf->writeEntry("UserName",accountPtr->name);
757 mailconf->writeEntry("Email",accountPtr->emailAddress); 757 mailconf->writeEntry("Email",accountPtr->emailAddress);
758 mailconf->writeEntry("POPUser",accountPtr->popUserName); 758 mailconf->writeEntry("POPUser",accountPtr->popUserName);
759 mailconf->writeEntryCrypt("POPPassword",accountPtr->popPasswd); 759 mailconf->writeEntryCrypt("POPPassword",accountPtr->popPasswd);
760 mailconf->writeEntry("POPServer",accountPtr->popServer); 760 mailconf->writeEntry("POPServer",accountPtr->popServer);
761 mailconf->writeEntry("SMTPServer",accountPtr->smtpServer); 761 mailconf->writeEntry("SMTPServer",accountPtr->smtpServer);
762 mailconf->writeEntry("AccountId",accountPtr->id); 762 mailconf->writeEntry("AccountId",accountPtr->id);
763 if (accountPtr->synchronize) 763 if (accountPtr->synchronize)
764 { 764 {
765 mailconf->writeEntry("Synchronize","Yes"); 765 mailconf->writeEntry("Synchronize","Yes");
766 mailconf->writeEntry("HeaderLimit",accountPtr->syncLimit); 766 mailconf->writeEntry("HeaderLimit",accountPtr->syncLimit);
767 mailconf->writeEntry("LastServerMailCount",accountPtr->lastServerMailCount); 767 mailconf->writeEntry("LastServerMailCount",accountPtr->lastServerMailCount);
768 } 768 }
769 else 769 else
770 { 770 {
771 mailconf->writeEntry("Synchronize", "No"); 771 mailconf->writeEntry("Synchronize", "No");
772 } 772 }
773 } 773 }
774 774
775 mailconf->setGroup("mailitglobal"); 775 mailconf->setGroup("mailitglobal");
776 mailconf->writeEntry("Accounts",acc_count); 776 mailconf->writeEntry("Accounts",acc_count);
777 mailconf->writeEntry("mailidcount", mailIdCount); 777 mailconf->writeEntry("mailidcount", mailIdCount);
778 mailconf->writeEntry("accountidcount", accountIdCount); 778 mailconf->writeEntry("accountidcount", accountIdCount);
779} 779}
780 780
781void EmailClient::selectAccount(int id) 781void EmailClient::selectAccount(int id)
782{ 782{
783 if (accountList.count() > 0) { 783 if (accountList.count() > 0) {
784 currentAccount = accountList.at(id); 784 currentAccount = accountList.at(id);
785 emit newCaption("Mailit - " + currentAccount->accountName); 785 emit newCaption("Mailit - " + currentAccount->accountName);
786 getNewMail(); 786 getNewMail();
787 } else { 787 } else {
788 emit newCaption( tr("Mailit ! No account defined") ); 788 emit newCaption( tr("Mailit ! No account defined") );
789 } 789 }
790} 790}
791 791
792void EmailClient::editAccount(int id) 792void EmailClient::editAccount(int id)
793{ 793{
794 MailAccount *newAccount; 794 MailAccount *newAccount;
795 795
796 editAccountView = new EditAccount(this, "account", TRUE); 796 editAccountView = new EditAccount(this, "account", TRUE);
797 if (id == newAccountId) { //new account 797 if (id == newAccountId) { //new account
798 newAccount = new MailAccount; 798 newAccount = new MailAccount;
799 editAccountView->setAccount(newAccount); 799 editAccountView->setAccount(newAccount);
800 } else { 800 } else {
801 newAccount = accountList.at(id); 801 newAccount = accountList.at(id);
802 editAccountView->setAccount(newAccount, FALSE); 802 editAccountView->setAccount(newAccount, FALSE);
803 } 803 }
804 804
805 editAccountView->showMaximized(); 805 editAccountView->showMaximized();
806 editAccountView->exec(); 806 editAccountView->exec();
807 807
808 if (editAccountView->result() == QDialog::Accepted) { 808 if (editAccountView->result() == QDialog::Accepted) {
809 if (id == newAccountId) { 809 if (id == newAccountId) {
810 newAccount->id = accountIdCount; 810 newAccount->id = accountIdCount;
811 accountIdCount++; 811 accountIdCount++;
812 accountList.append(newAccount); 812 accountList.append(newAccount);
813 updateAccounts(); 813 updateAccounts();
814 } else { 814 } else {
815 updateAccounts(); 815 updateAccounts();
816 } 816 }
817 } 817 }
818 818
819 delete editAccountView; 819 delete editAccountView;
820} 820}
821 821
822void EmailClient::deleteAccount(int id) 822void EmailClient::deleteAccount(int id)
823{ 823{
824 MailAccount *newAccount; 824 MailAccount *newAccount;
825 QString message; 825 QString message;
826 826
827 newAccount = accountList.at(id); 827 newAccount = accountList.at(id);
828 message = tr("Delete account:\n") + newAccount->accountName; 828 message = tr("Delete account:\n") + newAccount->accountName;
829 switch( QMessageBox::warning( this, "Mailit", message, 829 switch( QMessageBox::warning( this, "Mailit", message,
830 "Yes", "No", 0, 0, 1 ) ) { 830 "Yes", "No", 0, 0, 1 ) ) {
831 831
832 case 0: accountList.remove(id); 832 case 0: accountList.remove(id);
833 updateAccounts(); 833 updateAccounts();
834 break; 834 break;
835 case 1: 835 case 1:
836 break; 836 break;
837 } 837 }
838} 838}
839 839
840void EmailClient::updateAccounts() 840void EmailClient::updateAccounts()
841{ 841{
842 MailAccount *accountPtr; 842 MailAccount *accountPtr;
843 843
844 //rebuild menus, clear all first 844 //rebuild menus, clear all first
845 editAccountMenu->clear(); 845 editAccountMenu->clear();
846 selectAccountMenu->clear(); 846 selectAccountMenu->clear();
847 deleteAccountMenu->clear(); 847 deleteAccountMenu->clear();
848 848
849 newAccountId = editAccountMenu->insertItem( tr("New"), this, 849 newAccountId = editAccountMenu->insertItem( tr("New"), this,
850 SLOT(editAccount(int)) ); 850 SLOT(editAccount(int)) );
851 editAccountMenu->insertSeparator(); 851 editAccountMenu->insertSeparator();
852 852
853 idCount = 0; 853 idCount = 0;
854 for (accountPtr = accountList.first(); accountPtr != 0; 854 for (accountPtr = accountList.first(); accountPtr != 0;
855 accountPtr = accountList.next()) { 855 accountPtr = accountList.next()) {
856 856
857 editAccountMenu->insertItem(accountPtr->accountName, 857 editAccountMenu->insertItem(accountPtr->accountName,
858 this, SLOT(editAccount(int)), 0, idCount); 858 this, SLOT(editAccount(int)), 0, idCount);
859 selectAccountMenu->insertItem(accountPtr->accountName, 859 selectAccountMenu->insertItem(accountPtr->accountName,
860 this, SLOT(selectAccount(int)), 0, idCount); 860 this, SLOT(selectAccount(int)), 0, idCount);
861 deleteAccountMenu->insertItem(accountPtr->accountName, 861 deleteAccountMenu->insertItem(accountPtr->accountName,
862 this, SLOT(deleteAccount(int)), 0, idCount); 862 this, SLOT(deleteAccount(int)), 0, idCount);
863 idCount++; 863 idCount++;
864 } 864 }
865} 865}
866 866
867void EmailClient::deleteMail(EmailListItem *mailItem, bool &inbox) 867void EmailClient::deleteMail(EmailListItem *mailItem, bool &inbox)
868{ 868{
869 Email *mPtr; 869 Email *mPtr;
870 Enclosure *ePtr; 870 Enclosure *ePtr;
871 871
872 if (inbox) 872 if (inbox)
873 { 873 {
874 mPtr = mailItem->getMail(); 874 mPtr = mailItem->getMail();
875 875
876 //if mail is in queue for download, remove it from 876 //if mail is in queue for download, remove it from
877 //queue if possible 877 //queue if possible
878 if ( (receiving) && (mPtr->fromAccountId == currentAccount->id) ) { 878 if ( (receiving) && (mPtr->fromAccountId == currentAccount->id) ) {
879 if ( !mPtr->downloaded ) 879 if ( !mPtr->downloaded )
880 mailDownloadList.remove(mPtr->serverId, mPtr->size); 880 mailDownloadList.remove(mPtr->serverId, mPtr->size);
881 } 881 }
882 882
883 mailconf->setGroup(mPtr->id); 883 mailconf->setGroup(mPtr->id);
884 mailconf->clearGroup(); 884 mailconf->clearGroup();
885 885
886 //delete any temporary attatchemnts storing 886 //delete any temporary attatchemnts storing
887 for ( ePtr=mPtr->files.first(); ePtr != 0; ePtr=mPtr->files.next() ) { 887 for ( ePtr=mPtr->files.first(); ePtr != 0; ePtr=mPtr->files.next() ) {
888 if (ePtr->saved) { 888 if (ePtr->saved) {
889 QFile::remove( (ePtr->path + ePtr->name) ); 889 QFile::remove( (ePtr->path + ePtr->name) );
890 } 890 }
891 } 891 }
892 inboxView->takeItem(mailItem); 892 inboxView->takeItem(mailItem);
893 } 893 }
894 else 894 else
895 { 895 {
896 outboxView->takeItem(mailItem); 896 outboxView->takeItem(mailItem);
897 } 897 }
898} 898}
899 899
900void EmailClient::setMailSize(int size) 900void EmailClient::setMailSize(int size)
901{ 901{
902 progressBar->reset(); 902 progressBar->reset();
903 progressBar->setTotalSteps(size); 903 progressBar->setTotalSteps(size);
904} 904}
905 905
906void EmailClient::setTotalSize(int /*size*/) 906void EmailClient::setTotalSize(int /*size*/)
907{ 907{
908 908
909} 909}
910 910
911void EmailClient::setDownloadedSize(int size) 911void EmailClient::setDownloadedSize(int size)
912{ 912{
913 int total = progressBar->totalSteps(); 913 int total = progressBar->totalSteps();
914 914
915 if (size < total) { 915 if (size < total) {
916 progressBar->setProgress(size); 916 progressBar->setProgress(size);
917 } else { 917 } else {
918 progressBar->setProgress(total); 918 progressBar->setProgress(total);
919 } 919 }
920} 920}
921 921
922void EmailClient::deleteItem() 922void EmailClient::deleteItem()
923{ 923{
924 bool inbox=mailboxView->currentTab()==0; 924 bool inbox=mailboxView->currentTab()==0;
925 QListView* box; 925 QListView* box;
926 926
927 EmailListItem* eli; 927 EmailListItem* eli;
928 // int pos; 928 // int pos;
929 929
930 inbox ? box=inboxView : box=outboxView; 930 inbox ? box=inboxView : box=outboxView;
931 931
932 eli=(EmailListItem*)box->selectedItem(); 932 eli=(EmailListItem*)box->selectedItem();
933 933
934 if (eli) 934 if (eli)
935 { 935 {
936 box->setSelected(eli->itemBelow(),true); //select the previous item 936 box->setSelected(eli->itemBelow(),true); //select the previous item
937 937
938 deleteMail(eli,(bool&)inbox); //remove mail entry 938 deleteMail(eli,(bool&)inbox); //remove mail entry
939 } 939 }
940} 940}
941 941
942void EmailClient::inboxItemPressed() 942void EmailClient::inboxItemPressed()
943{ 943{
944// timerID=startTimer(500); 944// timerID=startTimer(500);
945} 945}
946 946
947void EmailClient::inboxItemReleased() 947void EmailClient::inboxItemReleased()
948{ 948{
949 // killTimer(timerID); 949 // killTimer(timerID);
950} 950}
951 951
952/*void EmailClient::timerEvent(QTimerEvent *e) 952/*void EmailClient::timerEvent(QTimerEvent *e)
953{ 953{
954 //killTimer(timerID); 954 //killTimer(timerID);
955 955
956 956
957 QPopupMenu *action = new QPopupMenu(this); 957 QPopupMenu *action = new QPopupMenu(this);
958 958
959 int reply=0; 959 int reply=0;
960 960
961 action->insertItem(tr( "Reply To" ),this,SLOT(reply())); 961 action->insertItem(tr( "Reply To" ),this,SLOT(reply()));
962 action->insertItem( tr( "Reply All" ),this,SLOT(replyAll())); 962 action->insertItem( tr( "Reply All" ),this,SLOT(replyAll()));
963 action->insertItem( tr( "Forward" ), this,SLOT(forward())); 963 action->insertItem( tr( "Forward" ), this,SLOT(forward()));
964 action->insertItem( tr( "Remove Mail" ), this,SLOT(remove())); 964 action->insertItem( tr( "Remove Mail" ), this,SLOT(remove()));
965 965
966 action->exec(QCursor::pos()); 966 action->exec(QCursor::pos());
967 967
968 if (action) delete action; 968 if (action) delete action;
969 969
970}*/ 970}*/
971 971
972Email* EmailClient::getCurrentMail() 972Email* EmailClient::getCurrentMail()
973{ 973{
974 EmailListItem *eli=(EmailListItem* ) (inboxView->selectedItem()); 974 EmailListItem *eli=(EmailListItem* ) (inboxView->selectedItem());
975 if (eli!=NULL) 975 if (eli!=NULL)
976 return eli->getMail(); 976 return eli->getMail();
977 else 977 else
978 return NULL; 978 return NULL;
979} 979}
980 980
981void EmailClient::download(Email* mail) 981void EmailClient::download(Email* mail)
982{ 982{
983 MailAccount* acc=0; 983 MailAccount* acc=0;
984 984
985 tempMailDownloadList.clear(); 985 tempMailDownloadList.clear();
986 tempMailDownloadList.sizeInsert(mail->serverId, mail->size); 986 tempMailDownloadList.sizeInsert(mail->serverId, mail->size);
987 987
988 acc=accountList.at(mail->fromAccountId-1); 988 acc=accountList.at(mail->fromAccountId-1);
989 if (acc) 989 if (acc)
990 { 990 {
991 emailHandler->setAccount(*acc); 991 emailHandler->setAccount(*acc);
992 emailHandler->getMailByList(&tempMailDownloadList); 992 emailHandler->getMailByList(&tempMailDownloadList);
993 } 993 }
994 else 994 else
995 QMessageBox::warning(qApp->activeWindow(), 995 QMessageBox::warning(qApp->activeWindow(),
996 tr("No account associated"), tr("There is no active account \nassociated to this mail\n it can not be downloaded"), "Abort\n"); 996 tr("No account associated"), tr("There is no active account \nassociated to this mail\n it can not be downloaded"), "Abort\n");
997} 997}
998 998
999void EmailClient::receive(const QCString& /*msg*/, const QByteArray& /*data*/) 999void EmailClient::receive(const QCString& /*msg*/, const QByteArray& /*data*/)
1000{ 1000{
1001 /*if (msg=="getMail()") 1001 /*if (msg=="getMail()")
1002 { 1002 {
1003 //QDialog qd(qApp->activeWindow(),"Getting mail",true); 1003 //QDialog qd(qApp->activeWindow(),"Getting mail",true);
1004 QVBoxLayout *vbProg = new QVBoxLayout( &qd ); 1004 QVBoxLayout *vbProg = new QVBoxLayout( &qd );
1005 1005
1006 initStatusBar(&qd); 1006 initStatusBar(&qd);
1007 1007
1008 if (statusBar==0) 1008 if (statusBar==0)
1009 { 1009 {
1010 qDebug("No Bar ..."); 1010 qDebug("No Bar ...");
1011 //statusBar=new ProgressBar(&qd); 1011 //statusBar=new ProgressBar(&qd);
1012 } 1012 }
1013 statusBar->show(); 1013 statusBar->show();
1014 vbProg->addWidget(statusBar); 1014 vbProg->addWidget(statusBar);
1015 qd.showMaximized(); 1015 qd.showMaximized();
1016 qd.show(); 1016 qd.show();
1017 emit getAllNewMail(); 1017 emit getAllNewMail();
1018 //qd.exec(); 1018 //qd.exec();
1019 } 1019 }
1020 else if (msg=="compose()") 1020 else if (msg=="compose()")
1021 { 1021 {
1022 QDialog qd(qApp->activeWindow(),"Getting mail",true); 1022 QDialog qd(qApp->activeWindow(),"Getting mail",true);
1023 1023
1024 WriteMail wm(&qd,"write new mail"); 1024 WriteMail wm(&qd,"write new mail");
1025 QVBoxLayout vbProg( &qd ); 1025 QVBoxLayout vbProg( &qd );
1026 1026
1027 wm.showMaximized(); 1027 wm.showMaximized();
1028 vbProg.addWidget(&wm); 1028 vbProg.addWidget(&wm);
1029 1029
1030 qd.showMaximized(); 1030 qd.showMaximized();
1031 1031
1032 emit composeRequested(); 1032 emit composeRequested();
1033 qd.exec(); 1033 qd.exec();
1034 1034
1035 QMessageBox::warning(qApp->activeWindow(),tr("Info"), tr("Info"), "OK\n"); 1035 QMessageBox::warning(qApp->activeWindow(),tr("Info"), tr("Info"), "OK\n");
1036 } 1036 }
1037 1037
1038 else if (msg=="dialog()") 1038 else if (msg=="dialog()")
1039 { 1039 {
1040 QMessageBox::warning(qApp->activeWindow(),tr("Info"), tr("Info"), "OK\n"); 1040 QMessageBox::warning(qApp->activeWindow(),tr("Info"), tr("Info"), "OK\n");
1041 }*/ 1041 }*/
1042} 1042}
diff --git a/noncore/unsupported/mailit/emailhandler.cpp b/noncore/unsupported/mailit/emailhandler.cpp
index 06e978d..02b3e9a 100644
--- a/noncore/unsupported/mailit/emailhandler.cpp
+++ b/noncore/unsupported/mailit/emailhandler.cpp
@@ -1,630 +1,630 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2001 Trolltech AS. All rights reserved. 2** Copyright (C) 2001 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qt Palmtop Environment. 4** This file is part of Qt Palmtop Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include <qfileinfo.h> 20#include <qfileinfo.h>
21#include <stdlib.h> 21#include <stdlib.h>
22#include <qapplication.h> 22#include <qapplication.h>
23#include <qmessagebox.h> 23#include <qmessagebox.h>
24#include <qcstring.h> 24#include <qcstring.h>
25#include "emailhandler.h" 25#include "emailhandler.h"
26#include <qpe/applnk.h> 26#include <qpe/applnk.h>
27#include <qpe/filemanager.h> 27#include <qpe/filemanager.h>
28 28
29QCollection::Item EnclosureList::newItem(QCollection::Item d) 29QCollection::Item EnclosureList::newItem(QCollection::Item d)
30{ 30{
31 return dupl( (Enclosure *) d); 31 return dupl( (Enclosure *) d);
32} 32}
33 33
34Enclosure* EnclosureList::dupl(Enclosure *in) 34Enclosure* EnclosureList::dupl(Enclosure *in)
35{ 35{
36 ac = new Enclosure(*in); 36 ac = new Enclosure(*in);
37 return ac; 37 return ac;
38} 38}
39 39
40EmailHandler::EmailHandler() 40EmailHandler::EmailHandler()
41{ 41{
42 qDebug("EMailHandler::EmailHandler"); 42 qDebug("EMailHandler::EmailHandler");
43 43
44 smtpClient = new SmtpClient(); 44 smtpClient = new SmtpClient();
45 popClient = new PopClient(); 45 popClient = new PopClient();
46 46
47 connect(smtpClient, SIGNAL(errorOccurred(int, const QString &)), this, 47 connect(smtpClient, SIGNAL(errorOccurred(int,const QString&)), this,
48 SIGNAL(smtpError(int, const QString &)) ); 48 SIGNAL(smtpError(int,const QString&)) );
49 connect(smtpClient, SIGNAL(mailSent()), this, SIGNAL(mailSent()) ); 49 connect(smtpClient, SIGNAL(mailSent()), this, SIGNAL(mailSent()) );
50 connect(smtpClient, SIGNAL(updateStatus(const QString &)), this, 50 connect(smtpClient, SIGNAL(updateStatus(const QString&)), this,
51 SIGNAL(updateSmtpStatus(const QString &)) ); 51 SIGNAL(updateSmtpStatus(const QString&)) );
52 52
53 connect(popClient, SIGNAL(errorOccurred(int, const QString &)), this, 53 connect(popClient, SIGNAL(errorOccurred(int,const QString&)), this,
54 SIGNAL(popError(int, const QString &)) ); 54 SIGNAL(popError(int,const QString&)) );
55 connect(popClient, SIGNAL(newMessage(const QString &, int, uint, bool)), 55 connect(popClient, SIGNAL(newMessage(const QString&,int,uint,bool)),
56 this, SLOT(messageArrived(const QString &, int, uint, bool)) ); 56 this, SLOT(messageArrived(const QString&,int,uint,bool)) );
57 connect(popClient, SIGNAL(updateStatus(const QString &)), this, 57 connect(popClient, SIGNAL(updateStatus(const QString&)), this,
58 SIGNAL(updatePopStatus(const QString &)) ); 58 SIGNAL(updatePopStatus(const QString&)) );
59 connect(popClient, SIGNAL(mailTransfered(int)), this, 59 connect(popClient, SIGNAL(mailTransfered(int)), this,
60 SIGNAL(mailTransfered(int)) ); 60 SIGNAL(mailTransfered(int)) );
61 61
62 62
63 //relaying size information 63 //relaying size information
64 connect(popClient, SIGNAL(currentMailSize(int)), 64 connect(popClient, SIGNAL(currentMailSize(int)),
65 this, SIGNAL(currentMailSize(int)) ); 65 this, SIGNAL(currentMailSize(int)) );
66 connect(popClient, SIGNAL(downloadedSize(int)), 66 connect(popClient, SIGNAL(downloadedSize(int)),
67 this, SIGNAL(downloadedSize(int)) ); 67 this, SIGNAL(downloadedSize(int)) );
68} 68}
69 69
70void EmailHandler::sendMail(QList<Email> *mailList) 70void EmailHandler::sendMail(QList<Email> *mailList)
71{ 71{
72 Email *currentMail; 72 Email *currentMail;
73 QString temp; 73 QString temp;
74 QString userName = QString::null; 74 QString userName = QString::null;
75 // not supported by ALL SMTP servers in the MAIL From field 75 // not supported by ALL SMTP servers in the MAIL From field
76 // userName = "\""+mailAccount.name+"\""; 76 // userName = "\""+mailAccount.name+"\"";
77 userName += "<" + mailAccount.emailAddress + ">"; 77 userName += "<" + mailAccount.emailAddress + ">";
78 78
79 for (currentMail = mailList->first(); currentMail != 0; 79 for (currentMail = mailList->first(); currentMail != 0;
80 currentMail = mailList->next()) { 80 currentMail = mailList->next()) {
81 81
82 if (encodeMime(currentMail) == 0) { 82 if (encodeMime(currentMail) == 0) {
83 smtpClient->addMail(userName, currentMail->subject, 83 smtpClient->addMail(userName, currentMail->subject,
84 currentMail->recipients, currentMail->rawMail); 84 currentMail->recipients, currentMail->rawMail);
85 } else { //error 85 } else { //error
86 temp = tr("Could not locate all files in \nmail with subject: ") + 86 temp = tr("Could not locate all files in \nmail with subject: ") +
87 currentMail->subject; 87 currentMail->subject;
88 temp += tr("\nMail has NOT been sent"); 88 temp += tr("\nMail has NOT been sent");
89 QMessageBox::warning(qApp->activeWindow(), tr("Attachment error"), temp, tr("OK\n")); 89 QMessageBox::warning(qApp->activeWindow(), tr("Attachment error"), temp, tr("OK\n"));
90 90
91 } 91 }
92 } 92 }
93 smtpClient->newConnection(mailAccount.smtpServer, 25); 93 smtpClient->newConnection(mailAccount.smtpServer, 25);
94} 94}
95 95
96void EmailHandler::setAccount(MailAccount account) 96void EmailHandler::setAccount(MailAccount account)
97{ 97{
98 mailAccount = account; 98 mailAccount = account;
99} 99}
100 100
101void EmailHandler::getMail() 101void EmailHandler::getMail()
102{ 102{
103 popClient->setAccount(mailAccount.popUserName, mailAccount.popPasswd); 103 popClient->setAccount(mailAccount.popUserName, mailAccount.popPasswd);
104 if (mailAccount.synchronize) { 104 if (mailAccount.synchronize) {
105 popClient->setSynchronize(mailAccount.lastServerMailCount); 105 popClient->setSynchronize(mailAccount.lastServerMailCount);
106 } else { 106 } else {
107 popClient->removeSynchronize(); 107 popClient->removeSynchronize();
108 } 108 }
109 109
110 headers = FALSE; 110 headers = FALSE;
111 //popClient->headersOnly(headers, 0); 111 //popClient->headersOnly(headers, 0);
112 popClient->newConnection(mailAccount.popServer, 110); 112 popClient->newConnection(mailAccount.popServer, 110);
113} 113}
114 114
115void EmailHandler::getMailHeaders() 115void EmailHandler::getMailHeaders()
116{ 116{
117 popClient->setAccount(mailAccount.popUserName, mailAccount.popPasswd); 117 popClient->setAccount(mailAccount.popUserName, mailAccount.popPasswd);
118 mailAccount.synchronize ? popClient->setSynchronize(mailAccount.lastServerMailCount): popClient->removeSynchronize(); 118 mailAccount.synchronize ? popClient->setSynchronize(mailAccount.lastServerMailCount): popClient->removeSynchronize();
119 119
120 headers = TRUE; 120 headers = TRUE;
121 popClient->headersOnly(headers, mailAccount.syncLimit); //less than requested syncLimit, download all 121 popClient->headersOnly(headers, mailAccount.syncLimit); //less than requested syncLimit, download all
122 qDebug("Initiating connection"); 122 qDebug("Initiating connection");
123 popClient->newConnection(mailAccount.popServer, 110); 123 popClient->newConnection(mailAccount.popServer, 110);
124} 124}
125 125
126void EmailHandler::getMailByList(MailList *mailList) 126void EmailHandler::getMailByList(MailList *mailList)
127{ 127{
128 if (mailList->count() == 0) { //should not occur though 128 if (mailList->count() == 0) { //should not occur though
129 emit mailTransfered(0); 129 emit mailTransfered(0);
130 return; 130 return;
131 } 131 }
132 132
133 headers = FALSE; 133 headers = FALSE;
134 popClient->headersOnly(FALSE, 0); 134 popClient->headersOnly(FALSE, 0);
135 135
136 popClient->setAccount(mailAccount.popUserName,mailAccount.popPasswd); 136 popClient->setAccount(mailAccount.popUserName,mailAccount.popPasswd);
137 popClient->setSelectedMails(mailList); 137 popClient->setSelectedMails(mailList);
138 popClient->newConnection(mailAccount.popServer, 110); 138 popClient->newConnection(mailAccount.popServer, 110);
139 } 139 }
140 140
141void EmailHandler::messageArrived(const QString &message, int id, uint size, bool complete) 141void EmailHandler::messageArrived(const QString &message, int id, uint size, bool complete)
142{ 142{
143 Email mail; 143 Email mail;
144 144
145 mail.rawMail = message; 145 mail.rawMail = message;
146 mail.serverId = id; 146 mail.serverId = id;
147 mail.size = size; 147 mail.size = size;
148 mail.downloaded = complete; 148 mail.downloaded = complete;
149 149
150 emit mailArrived(mail, FALSE); 150 emit mailArrived(mail, FALSE);
151} 151}
152 152
153bool EmailHandler::parse(const QString &in, const QString &lineShift, Email *mail) 153bool EmailHandler::parse(const QString &in, const QString &lineShift, Email *mail)
154{ 154{
155 QString temp, boundary; 155 QString temp, boundary;
156 int pos; 156 int pos;
157 QString delimiter, header, body, mimeHeader, mimeBody; 157 QString delimiter, header, body, mimeHeader, mimeBody;
158 QString content, contentType, contentAttribute, id, encoding; 158 QString content, contentType, contentAttribute, id, encoding;
159 QString fileName, storedName; 159 QString fileName, storedName;
160 int enclosureId = 0; 160 int enclosureId = 0;
161 161
162 mail->rawMail = in; 162 mail->rawMail = in;
163 mail->received = TRUE; 163 mail->received = TRUE;
164 mail->files.setAutoDelete(TRUE); 164 mail->files.setAutoDelete(TRUE);
165 165
166 temp = lineShift + "." + lineShift; 166 temp = lineShift + "." + lineShift;
167 167
168 if (in.right(temp.length()) != temp) { 168 if (in.right(temp.length()) != temp) {
169 mail->rawMail += temp; 169 mail->rawMail += temp;
170 } 170 }
171 171
172 172
173 delimiter = lineShift + lineShift; // "\n\n" or "\r\n\r\n" 173 delimiter = lineShift + lineShift; // "\n\n" or "\r\n\r\n"
174 pos = in.find(delimiter, 0, FALSE); 174 pos = in.find(delimiter, 0, FALSE);
175 header = in.left(pos); 175 header = in.left(pos);
176 body = in.right(in.length() - pos - delimiter.length()); 176 body = in.right(in.length() - pos - delimiter.length());
177 if ((body.at(body.length()-2) == '.') && (body.at(body.length()-3) == '\n')) 177 if ((body.at(body.length()-2) == '.') && (body.at(body.length()-3) == '\n'))
178 body.truncate(body.length()-2); 178 body.truncate(body.length()-2);
179 179
180 // TextParser p(header, lineShift); 180 // TextParser p(header, lineShift);
181 TextParser * lp = new TextParser(header, lineShift); 181 TextParser * lp = new TextParser(header, lineShift);
182#define p (*lp) 182#define p (*lp)
183 183
184 if ((pos = p.find("FROM",':', 0, TRUE)) != -1) { 184 if ((pos = p.find("FROM",':', 0, TRUE)) != -1) {
185 pos++; 185 pos++;
186 if (p.separatorAt(pos) == ' ') { 186 if (p.separatorAt(pos) == ' ') {
187 mail->from = p.getString(&pos, '<', false); 187 mail->from = p.getString(&pos, '<', false);
188 mail->from = mail->from.stripWhiteSpace(); 188 mail->from = mail->from.stripWhiteSpace();
189 if ( (mail->from.length() > 2) && (mail->from[0] == '"') ) { 189 if ( (mail->from.length() > 2) && (mail->from[0] == '"') ) {
190 mail->from = mail->from.left(mail->from.length() - 1); 190 mail->from = mail->from.left(mail->from.length() - 1);
191 mail->from = mail->from.right(mail->from.length() - 1); 191 mail->from = mail->from.right(mail->from.length() - 1);
192 } 192 }
193 pos++; 193 pos++;
194 mail->fromMail = p.getString(&pos, '>', false); 194 mail->fromMail = p.getString(&pos, '>', false);
195 } else { 195 } else {
196 if (p.separatorAt(pos) == '<') //No name.. nasty 196 if (p.separatorAt(pos) == '<') //No name.. nasty
197 pos++; 197 pos++;
198 //pos++; 198 //pos++;
199 mail->fromMail = p.getString(&pos, 'z', TRUE); 199 mail->fromMail = p.getString(&pos, 'z', TRUE);
200 if (mail->fromMail.at(mail->fromMail.length()-1) == '>') 200 if (mail->fromMail.at(mail->fromMail.length()-1) == '>')
201 mail->fromMail.truncate(mail->fromMail.length() - 1); 201 mail->fromMail.truncate(mail->fromMail.length() - 1);
202 mail->from=mail->fromMail; 202 mail->from=mail->fromMail;
203 } 203 }
204 } 204 }
205 205
206 pos=0; 206 pos=0;
207 207
208 //Search for To: after the FROM: attribute to prevent hitting the Delivered-To: 208 //Search for To: after the FROM: attribute to prevent hitting the Delivered-To:
209 while((pos = p.find("TO",':', pos+1, TRUE))!=-1) 209 while((pos = p.find("TO",':', pos+1, TRUE))!=-1)
210 { 210 {
211 QString rec; 211 QString rec;
212 212
213 if (p.separatorAt(pos-1)!='-') //The - separator means that this is a Delivered-To: or Reply-To: 213 if (p.separatorAt(pos-1)!='-') //The - separator means that this is a Delivered-To: or Reply-To:
214 { 214 {
215 pos++; 215 pos++;
216 mail->recipients.append(p.getString(&pos, '\r', TRUE)); 216 mail->recipients.append(p.getString(&pos, '\r', TRUE));
217 } 217 }
218 } 218 }
219 // 219 //
220 //if (pos==-1) mail->recipients.append (tr("undisclosed recipients") ); 220 //if (pos==-1) mail->recipients.append (tr("undisclosed recipients") );
221 221
222 if ((pos = p.find("CC",':', 0, TRUE)) != -1) 222 if ((pos = p.find("CC",':', 0, TRUE)) != -1)
223 { 223 {
224 pos++; 224 pos++;
225 mail->carbonCopies.append (p.getString(&pos, 'z', TRUE) ); 225 mail->carbonCopies.append (p.getString(&pos, 'z', TRUE) );
226 } 226 }
227 227
228 if ((pos = p.find("SUBJECT",':', 0, TRUE)) != -1) { 228 if ((pos = p.find("SUBJECT",':', 0, TRUE)) != -1) {
229 pos++; 229 pos++;
230 mail->subject = p.getString(&pos, 'z', TRUE); 230 mail->subject = p.getString(&pos, 'z', TRUE);
231 } 231 }
232 232
233 if ((pos = p.find("DATE",':', 0, TRUE)) != -1) { 233 if ((pos = p.find("DATE",':', 0, TRUE)) != -1) {
234 pos++; 234 pos++;
235 mail->date = p.getString(&pos, 'z', TRUE); 235 mail->date = p.getString(&pos, 'z', TRUE);
236 } 236 }
237 237
238 238
239 239
240 if ((pos = p.find("MESSAGE",'-', 0, TRUE)) != -1) { 240 if ((pos = p.find("MESSAGE",'-', 0, TRUE)) != -1) {
241 pos++; 241 pos++;
242 if ( (p.wordAt(pos).upper() == "ID") && 242 if ( (p.wordAt(pos).upper() == "ID") &&
243 (p.separatorAt(pos) == ':') ) { 243 (p.separatorAt(pos) == ':') ) {
244 244
245 id = p.getString(&pos, 'z', TRUE); 245 id = p.getString(&pos, 'z', TRUE);
246 mail->id = id; 246 mail->id = id;
247 } 247 }
248 } 248 }
249 249
250 pos = 0; 250 pos = 0;
251 while ( ((pos = p.find("MIME",'-', pos, TRUE)) != -1) ) { 251 while ( ((pos = p.find("MIME",'-', pos, TRUE)) != -1) ) {
252 pos++; 252 pos++;
253 if ( (p.wordAt(pos).upper() == "VERSION") && 253 if ( (p.wordAt(pos).upper() == "VERSION") &&
254 (p.separatorAt(pos) == ':') ) { 254 (p.separatorAt(pos) == ':') ) {
255 pos++; 255 pos++;
256 if (p.getString(&pos, 'z', true) == "1.0") { 256 if (p.getString(&pos, 'z', true) == "1.0") {
257 mail->mimeType = 1; 257 mail->mimeType = 1;
258 } 258 }
259 } 259 }
260 } 260 }
261 261
262 if (mail->mimeType == 1) { 262 if (mail->mimeType == 1) {
263 boundary = ""; 263 boundary = "";
264 if ((pos = p.find("BOUNDARY", '=', 0, TRUE)) != -1) { 264 if ((pos = p.find("BOUNDARY", '=', 0, TRUE)) != -1) {
265 pos++; 265 pos++;
266 boundary = p.getString(&pos, 'z', true); 266 boundary = p.getString(&pos, 'z', true);
267 if (boundary[0] == '"') { 267 if (boundary[0] == '"') {
268 boundary = boundary.left(boundary.length() - 1); //strip " 268 boundary = boundary.left(boundary.length() - 1); //strip "
269 boundary = boundary.right(boundary.length() - 1); //strip " 269 boundary = boundary.right(boundary.length() - 1); //strip "
270 } 270 }
271 boundary = "--" + boundary; //create boundary field 271 boundary = "--" + boundary; //create boundary field
272 } 272 }
273 273
274 if (boundary == "") { //fooled by Mime-Version 274 if (boundary == "") { //fooled by Mime-Version
275 mail->body = body; 275 mail->body = body;
276 mail->bodyPlain = body; 276 mail->bodyPlain = body;
277 delete lp; 277 delete lp;
278 return mail; 278 return mail;
279 } 279 }
280 280
281 while (body.length() > 0) { 281 while (body.length() > 0) {
282 pos = body.find(boundary, 0, FALSE); 282 pos = body.find(boundary, 0, FALSE);
283 pos = body.find(delimiter, pos, FALSE); 283 pos = body.find(delimiter, pos, FALSE);
284 mimeHeader = body.left(pos); 284 mimeHeader = body.left(pos);
285 mimeBody = body.right(body.length() - pos - delimiter.length()); 285 mimeBody = body.right(body.length() - pos - delimiter.length());
286 TextParser bp(mimeHeader, lineShift); 286 TextParser bp(mimeHeader, lineShift);
287 287
288 contentType = ""; 288 contentType = "";
289 contentAttribute = ""; 289 contentAttribute = "";
290 fileName = ""; 290 fileName = "";
291 if ((pos = bp.find("CONTENT",'-', 0, TRUE)) != -1) { 291 if ((pos = bp.find("CONTENT",'-', 0, TRUE)) != -1) {
292 pos++; 292 pos++;
293 if ( (bp.wordAt(pos).upper() == "TYPE") && 293 if ( (bp.wordAt(pos).upper() == "TYPE") &&
294 (bp.separatorAt(pos) == ':') ) { 294 (bp.separatorAt(pos) == ':') ) {
295 contentType = bp.nextWord().upper(); 295 contentType = bp.nextWord().upper();
296 if (bp.nextSeparator() == '/') 296 if (bp.nextSeparator() == '/')
297 contentAttribute = bp.nextWord().upper(); 297 contentAttribute = bp.nextWord().upper();
298 content = contentType + "/" + contentAttribute; 298 content = contentType + "/" + contentAttribute;
299 } 299 }
300 if ((pos = bp.find("ENCODING",':', 0, TRUE)) != -1) { 300 if ((pos = bp.find("ENCODING",':', 0, TRUE)) != -1) {
301 pos++; 301 pos++;
302 encoding = bp.getString(&pos, 'z', TRUE); 302 encoding = bp.getString(&pos, 'z', TRUE);
303 } 303 }
304 304
305 if ( (pos = bp.find("FILENAME",'=', 0, TRUE)) != -1) { 305 if ( (pos = bp.find("FILENAME",'=', 0, TRUE)) != -1) {
306 pos++; 306 pos++;
307 fileName = bp.getString(&pos, 'z', TRUE); 307 fileName = bp.getString(&pos, 'z', TRUE);
308 fileName = fileName.right(fileName.length() - 1); 308 fileName = fileName.right(fileName.length() - 1);
309 fileName = fileName.left(fileName.length() - 1); 309 fileName = fileName.left(fileName.length() - 1);
310 } 310 }
311 311
312 } 312 }
313 pos = mimeBody.find(boundary, 0, FALSE); 313 pos = mimeBody.find(boundary, 0, FALSE);
314 if (pos == -1) //should not occur, malformed mail 314 if (pos == -1) //should not occur, malformed mail
315 pos = mimeBody.length(); 315 pos = mimeBody.length();
316 body = mimeBody.right(mimeBody.length() - pos); 316 body = mimeBody.right(mimeBody.length() - pos);
317 mimeBody = mimeBody.left(pos); 317 mimeBody = mimeBody.left(pos);
318 318
319 if (fileName != "") { //attatchments of some type, audio, image etc. 319 if (fileName != "") { //attatchments of some type, audio, image etc.
320 320
321 Enclosure e; 321 Enclosure e;
322 e.id = enclosureId; 322 e.id = enclosureId;
323 e.originalName = fileName; 323 e.originalName = fileName;
324 e.contentType = contentType; 324 e.contentType = contentType;
325 e.contentAttribute = contentAttribute; 325 e.contentAttribute = contentAttribute;
326 e.encoding = encoding; 326 e.encoding = encoding;
327 e.body = mimeBody; 327 e.body = mimeBody;
328 e.saved = FALSE; 328 e.saved = FALSE;
329 mail->addEnclosure(&e); 329 mail->addEnclosure(&e);
330 enclosureId++; 330 enclosureId++;
331 331
332 } else if (contentType == "TEXT") { 332 } else if (contentType == "TEXT") {
333 if (contentAttribute == "PLAIN") { 333 if (contentAttribute == "PLAIN") {
334 mail->body = mimeBody; 334 mail->body = mimeBody;
335 mail->bodyPlain = mimeBody; 335 mail->bodyPlain = mimeBody;
336 } 336 }
337 if (contentAttribute == "HTML") { 337 if (contentAttribute == "HTML") {
338 mail->body = mimeBody; 338 mail->body = mimeBody;
339 } 339 }
340 } 340 }
341 } 341 }
342 } else { 342 } else {
343 mail->bodyPlain = body; 343 mail->bodyPlain = body;
344 mail->body = body; 344 mail->body = body;
345 } 345 }
346 delete lp; 346 delete lp;
347 return TRUE; 347 return TRUE;
348} 348}
349 349
350bool EmailHandler::getEnclosure(Enclosure *ePtr) 350bool EmailHandler::getEnclosure(Enclosure *ePtr)
351{ 351{
352 QFile f(ePtr->path + ePtr->name); 352 QFile f(ePtr->path + ePtr->name);
353 char src[4]; 353 char src[4];
354 char *destPtr; 354 char *destPtr;
355 QByteArray buffer; 355 QByteArray buffer;
356 uint bufCount, pos, decodedCount, size, x; 356 uint bufCount, pos, decodedCount, size, x;
357 357
358 if (! f.open(IO_WriteOnly) ) { 358 if (! f.open(IO_WriteOnly) ) {
359 qWarning("could not save: " + ePtr->path + ePtr->name); 359 qWarning("could not save: " + ePtr->path + ePtr->name);
360 return FALSE; 360 return FALSE;
361 } 361 }
362 362
363 if (ePtr->encoding.upper() == "BASE64") { 363 if (ePtr->encoding.upper() == "BASE64") {
364 size = (ePtr->body.length() * 3 / 4); //approximate size (always above) 364 size = (ePtr->body.length() * 3 / 4); //approximate size (always above)
365 buffer.resize(size); 365 buffer.resize(size);
366 bufCount = 0; 366 bufCount = 0;
367 pos = 0; 367 pos = 0;
368 destPtr = buffer.data(); 368 destPtr = buffer.data();
369 369
370 while (pos < ePtr->body.length()) { 370 while (pos < ePtr->body.length()) {
371 decodedCount = 4; 371 decodedCount = 4;
372 x = 0; 372 x = 0;
373 while ( (x < 4) && (pos < ePtr->body.length()) ) { 373 while ( (x < 4) && (pos < ePtr->body.length()) ) {
374 src[x] = ePtr->body[pos].latin1(); 374 src[x] = ePtr->body[pos].latin1();
375 pos++; 375 pos++;
376 if (src[x] == '\r' || src[x] == '\n' || src[x] == ' ') 376 if (src[x] == '\r' || src[x] == '\n' || src[x] == ' ')
377 x--; 377 x--;
378 x++; 378 x++;
379 } 379 }
380 if (x > 1) { 380 if (x > 1) {
381 decodedCount = parse64base(src, destPtr); 381 decodedCount = parse64base(src, destPtr);
382 destPtr += decodedCount; 382 destPtr += decodedCount;
383 bufCount += decodedCount; 383 bufCount += decodedCount;
384 } 384 }
385 } 385 }
386 386
387 buffer.resize(bufCount); //set correct length of file 387 buffer.resize(bufCount); //set correct length of file
388 f.writeBlock(buffer); 388 f.writeBlock(buffer);
389 } else { 389 } else {
390 QTextStream t(&f); 390 QTextStream t(&f);
391 t << ePtr->body; 391 t << ePtr->body;
392 } 392 }
393 return TRUE; 393 return TRUE;
394} 394}
395 395
396int EmailHandler::parse64base(char *src, char *bufOut) { 396int EmailHandler::parse64base(char *src, char *bufOut) {
397 397
398 char c, z; 398 char c, z;
399 char li[4]; 399 char li[4];
400 int processed; 400 int processed;
401 401
402 //conversion table withouth table... 402 //conversion table withouth table...
403 for (int x = 0; x < 4; x++) { 403 for (int x = 0; x < 4; x++) {
404 c = src[x]; 404 c = src[x];
405 405
406 if ( (int) c >= 'A' && (int) c <= 'Z') 406 if ( (int) c >= 'A' && (int) c <= 'Z')
407 li[x] = (int) c - (int) 'A'; 407 li[x] = (int) c - (int) 'A';
408 if ( (int) c >= 'a' && (int) c <= 'z') 408 if ( (int) c >= 'a' && (int) c <= 'z')
409 li[x] = (int) c - (int) 'a' + 26; 409 li[x] = (int) c - (int) 'a' + 26;
410 if ( (int) c >= '0' && (int) c <= '9') 410 if ( (int) c >= '0' && (int) c <= '9')
411 li[x] = (int) c - (int) '0' + 52; 411 li[x] = (int) c - (int) '0' + 52;
412 if (c == '+') 412 if (c == '+')
413 li[x] = 62; 413 li[x] = 62;
414 if (c == '/') 414 if (c == '/')
415 li[x] = 63; 415 li[x] = 63;
416 } 416 }
417 417
418 processed = 1; 418 processed = 1;
419 bufOut[0] = (char) li[0] & (32+16+8+4+2+1); //mask out top 2 bits 419 bufOut[0] = (char) li[0] & (32+16+8+4+2+1); //mask out top 2 bits
420 bufOut[0] <<= 2; 420 bufOut[0] <<= 2;
421 z = li[1] >> 4; 421 z = li[1] >> 4;
422 bufOut[0] = bufOut[0] | z; //first byte retrived 422 bufOut[0] = bufOut[0] | z; //first byte retrived
423 423
424 if (src[2] != '=') { 424 if (src[2] != '=') {
425 bufOut[1] = (char) li[1] & (8+4+2+1); //mask out top 4 bits 425 bufOut[1] = (char) li[1] & (8+4+2+1); //mask out top 4 bits
426 bufOut[1] <<= 4; 426 bufOut[1] <<= 4;
427 z = li[2] >> 2; 427 z = li[2] >> 2;
428 bufOut[1] = bufOut[1] | z; //second byte retrived 428 bufOut[1] = bufOut[1] | z; //second byte retrived
429 processed++; 429 processed++;
430 430
431 if (src[3] != '=') { 431 if (src[3] != '=') {
432 bufOut[2] = (char) li[2] & (2+1); //mask out top 6 bits 432 bufOut[2] = (char) li[2] & (2+1); //mask out top 6 bits
433 bufOut[2] <<= 6; 433 bufOut[2] <<= 6;
434 z = li[3]; 434 z = li[3];
435 bufOut[2] = bufOut[2] | z; //third byte retrieved 435 bufOut[2] = bufOut[2] | z; //third byte retrieved
436 processed++; 436 processed++;
437 } 437 }
438 } 438 }
439 return processed; 439 return processed;
440} 440}
441 441
442int EmailHandler::encodeMime(Email *mail) 442int EmailHandler::encodeMime(Email *mail)
443{ 443{
444 444
445 QString fileName, fileType, contentType, newBody, boundary; 445 QString fileName, fileType, contentType, newBody, boundary;
446 Enclosure *ePtr; 446 Enclosure *ePtr;
447 QString userName; 447 QString userName;
448 448
449 if ( ! mailAccount.name.isEmpty() ) { 449 if ( ! mailAccount.name.isEmpty() ) {
450 userName = "\"" + mailAccount.name + "\" <" + mailAccount.emailAddress + ">"; 450 userName = "\"" + mailAccount.name + "\" <" + mailAccount.emailAddress + ">";
451 } else { 451 } else {
452 userName = "<" + mailAccount.emailAddress + ">"; 452 userName = "<" + mailAccount.emailAddress + ">";
453 } 453 }
454 454
455 //add standard headers 455 //add standard headers
456 newBody = "From: " + userName + "\r\nTo: "; 456 newBody = "From: " + userName + "\r\nTo: ";
457 for (QStringList::Iterator it = mail->recipients.begin(); it != mail->recipients.end(); ++it ) { 457 for (QStringList::Iterator it = mail->recipients.begin(); it != mail->recipients.end(); ++it ) {
458 newBody += *it + " "; 458 newBody += *it + " ";
459 } 459 }
460 460
461 newBody += "\r\nCC: "; 461 newBody += "\r\nCC: ";
462 462
463 for (QStringList::Iterator it = mail->carbonCopies.begin(); it != mail->carbonCopies.end(); ++it ) { 463 for (QStringList::Iterator it = mail->carbonCopies.begin(); it != mail->carbonCopies.end(); ++it ) {
464 newBody += *it + " "; 464 newBody += *it + " ";
465 } 465 }
466 466
467 newBody += "\r\nSubject: " + mail->subject + "\r\n"; 467 newBody += "\r\nSubject: " + mail->subject + "\r\n";
468 468
469 if (mail->files.count() == 0) { //just a simple mail 469 if (mail->files.count() == 0) { //just a simple mail
470 newBody += "\r\n" + mail->body; 470 newBody += "\r\n" + mail->body;
471 mail->rawMail = newBody; 471 mail->rawMail = newBody;
472 return 0; 472 return 0;
473 } 473 }
474 474
475 //Build mime encoded mail 475 //Build mime encoded mail
476 boundary = "-----4345=next_bound=0495----"; 476 boundary = "-----4345=next_bound=0495----";
477 477
478 newBody += "Mime-Version: 1.0\r\n"; 478 newBody += "Mime-Version: 1.0\r\n";
479 newBody += "Content-Type: multipart/mixed; boundary=\"" + 479 newBody += "Content-Type: multipart/mixed; boundary=\"" +
480 boundary + "\"\r\n\r\n"; 480 boundary + "\"\r\n\r\n";
481 481
482 newBody += "This is a multipart message in Mime 1.0 format\r\n\r\n"; 482 newBody += "This is a multipart message in Mime 1.0 format\r\n\r\n";
483 newBody += "--" + boundary + "\r\nContent-Type: text/plain\r\n\r\n"; 483 newBody += "--" + boundary + "\r\nContent-Type: text/plain\r\n\r\n";
484 newBody += mail->body; 484 newBody += mail->body;
485 485
486 for ( ePtr=mail->files.first(); ePtr != 0; ePtr=mail->files.next() ) { 486 for ( ePtr=mail->files.first(); ePtr != 0; ePtr=mail->files.next() ) {
487 fileName = ePtr->originalName; 487 fileName = ePtr->originalName;
488 fileType = ePtr->contentType; 488 fileType = ePtr->contentType;
489 QFileInfo fi(fileName); 489 QFileInfo fi(fileName);
490 490
491 // This specification of contentType is temporary 491 // This specification of contentType is temporary
492 contentType = ""; 492 contentType = "";
493 if (fileType == "Picture") { 493 if (fileType == "Picture") {
494 contentType = "image/x-image"; 494 contentType = "image/x-image";
495 } else if (fileType == "Document") { 495 } else if (fileType == "Document") {
496 contentType = "text/plain"; 496 contentType = "text/plain";
497 } else if (fileType == "Sound") { 497 } else if (fileType == "Sound") {
498 contentType = "audio/x-wav"; 498 contentType = "audio/x-wav";
499 } else if (fileType == "Movie") { 499 } else if (fileType == "Movie") {
500 contentType = "video/mpeg"; 500 contentType = "video/mpeg";
501 } else { 501 } else {
502 contentType = "application/octet-stream"; 502 contentType = "application/octet-stream";
503 } 503 }
504 504
505 newBody += "\r\n\r\n--" + boundary + "\r\n"; 505 newBody += "\r\n\r\n--" + boundary + "\r\n";
506 newBody += "Content-Type: " + contentType + "; name=\"" + 506 newBody += "Content-Type: " + contentType + "; name=\"" +
507 fi.fileName() + "\"\r\n"; 507 fi.fileName() + "\"\r\n";
508 newBody += "Content-Transfer-Encoding: base64\r\n"; 508 newBody += "Content-Transfer-Encoding: base64\r\n";
509 newBody += "Content-Disposition: inline; filename=\"" + 509 newBody += "Content-Disposition: inline; filename=\"" +
510 fi.fileName() + "\"\r\n\r\n"; 510 fi.fileName() + "\"\r\n\r\n";
511 511
512 if (encodeFile(fileName, &newBody) == -1) //file not found? 512 if (encodeFile(fileName, &newBody) == -1) //file not found?
513 return -1; 513 return -1;
514 } 514 }
515 515
516 newBody += "\r\n\r\n--" + boundary + "--"; 516 newBody += "\r\n\r\n--" + boundary + "--";
517 mail->rawMail = newBody; 517 mail->rawMail = newBody;
518 518
519 return 0; 519 return 0;
520} 520}
521 521
522int EmailHandler::encodeFile(const QString &fileName, QString *toBody) 522int EmailHandler::encodeFile(const QString &fileName, QString *toBody)
523{ 523{
524 char *fileData; 524 char *fileData;
525 char *dataPtr; 525 char *dataPtr;
526 QString temp; 526 QString temp;
527 uint dataSize, count; 527 uint dataSize, count;
528 QFile f(fileName); 528 QFile f(fileName);
529 529
530 if (! f.open(IO_ReadOnly) ) { 530 if (! f.open(IO_ReadOnly) ) {
531 qWarning("could not open file: " + fileName); 531 qWarning("could not open file: " + fileName);
532 return -1; 532 return -1;
533 } 533 }
534 QTextStream s(&f); 534 QTextStream s(&f);
535 dataSize = f.size(); 535 dataSize = f.size();
536 fileData = (char *) malloc(dataSize + 3); 536 fileData = (char *) malloc(dataSize + 3);
537 s.readRawBytes(fileData, dataSize); 537 s.readRawBytes(fileData, dataSize);
538 538
539 temp = ""; 539 temp = "";
540 dataPtr = fileData; 540 dataPtr = fileData;
541 count = 0; 541 count = 0;
542 while (dataSize > 0) { 542 while (dataSize > 0) {
543 if (dataSize < 3) { 543 if (dataSize < 3) {
544 encode64base(dataPtr, &temp, dataSize); 544 encode64base(dataPtr, &temp, dataSize);
545 dataSize = 0; 545 dataSize = 0;
546 } else { 546 } else {
547 encode64base(dataPtr, &temp, 3); 547 encode64base(dataPtr, &temp, 3);
548 dataSize -= 3; 548 dataSize -= 3;
549 dataPtr += 3; 549 dataPtr += 3;
550 count += 4; 550 count += 4;
551 } 551 }
552 if (count > 72) { 552 if (count > 72) {
553 count = 0; 553 count = 0;
554 temp += "\r\n"; 554 temp += "\r\n";
555 } 555 }
556 } 556 }
557 toBody->append(temp); 557 toBody->append(temp);
558 558
559 delete(fileData); 559 delete(fileData);
560 f.close(); 560 f.close();
561 return 0; 561 return 0;
562} 562}
563 563
564void EmailHandler::encode64base(char *src, QString *dest, int len) 564void EmailHandler::encode64base(char *src, QString *dest, int len)
565{ 565{
566 QString temp; 566 QString temp;
567 uchar c; 567 uchar c;
568 uchar bufOut[4]; 568 uchar bufOut[4];
569 569
570 bufOut[0] = src[0]; 570 bufOut[0] = src[0];
571 bufOut[0] >>= 2; //Done byte 0 571 bufOut[0] >>= 2; //Done byte 0
572 572
573 bufOut[1] = src[0]; 573 bufOut[1] = src[0];
574 bufOut[1] = bufOut[1] & (1 + 2); //mask out top 6 bits 574 bufOut[1] = bufOut[1] & (1 + 2); //mask out top 6 bits
575 bufOut[1] <<= 4; //copy up 4 places 575 bufOut[1] <<= 4; //copy up 4 places
576 if (len > 1) { 576 if (len > 1) {
577 c = src[1]; 577 c = src[1];
578 } else { 578 } else {
579 c = 0; 579 c = 0;
580 } 580 }
581 581
582 c = c & (16 + 32 + 64 + 128); 582 c = c & (16 + 32 + 64 + 128);
583 c >>= 4; 583 c >>= 4;
584 bufOut[1] = bufOut[1] | c; //Done byte 1 584 bufOut[1] = bufOut[1] | c; //Done byte 1
585 585
586 bufOut[2] = src[1]; 586 bufOut[2] = src[1];
587 bufOut[2] = bufOut[2] & (1 + 2 + 4 + 8); 587 bufOut[2] = bufOut[2] & (1 + 2 + 4 + 8);
588 bufOut[2] <<= 2; 588 bufOut[2] <<= 2;
589 if (len > 2) { 589 if (len > 2) {
590 c = src[2]; 590 c = src[2];
591 } else { 591 } else {
592 c = 0; 592 c = 0;
593 } 593 }
594 c >>= 6; 594 c >>= 6;
595 bufOut[2] = bufOut[2] | c; 595 bufOut[2] = bufOut[2] | c;
596 596
597 bufOut[3] = src[2]; 597 bufOut[3] = src[2];
598 bufOut[3] = bufOut[3] & (1 + 2 + 4 + 8 + 16 + 32); 598 bufOut[3] = bufOut[3] & (1 + 2 + 4 + 8 + 16 + 32);
599 599
600 if (len == 1) { 600 if (len == 1) {
601 bufOut[2] = 64; 601 bufOut[2] = 64;
602 bufOut[3] = 64; 602 bufOut[3] = 64;
603 } 603 }
604 if (len == 2) { 604 if (len == 2) {
605 bufOut[3] = 64; 605 bufOut[3] = 64;
606 } 606 }
607 for (int x = 0; x < 4; x++) { 607 for (int x = 0; x < 4; x++) {
608 if (bufOut[x] <= 25) 608 if (bufOut[x] <= 25)
609 bufOut[x] += (uint) 'A'; 609 bufOut[x] += (uint) 'A';
610 else if (bufOut[x] >= 26 && bufOut[x] <= 51) 610 else if (bufOut[x] >= 26 && bufOut[x] <= 51)
611 bufOut[x] += (uint) 'a' - 26; 611 bufOut[x] += (uint) 'a' - 26;
612 else if (bufOut[x] >= 52 && bufOut[x] <= 61) 612 else if (bufOut[x] >= 52 && bufOut[x] <= 61)
613 bufOut[x] += (uint) '0' - 52; 613 bufOut[x] += (uint) '0' - 52;
614 else if (bufOut[x] == 62) 614 else if (bufOut[x] == 62)
615 bufOut[x] = '+'; 615 bufOut[x] = '+';
616 else if (bufOut[x] == 63) 616 else if (bufOut[x] == 63)
617 bufOut[x] = '/'; 617 bufOut[x] = '/';
618 else if (bufOut[x] == 64) 618 else if (bufOut[x] == 64)
619 bufOut[x] = '='; 619 bufOut[x] = '=';
620 620
621 dest->append(bufOut[x]); 621 dest->append(bufOut[x]);
622 } 622 }
623} 623}
624 624
625void EmailHandler::cancel() 625void EmailHandler::cancel()
626{ 626{
627 popClient->errorHandling(ErrCancel); 627 popClient->errorHandling(ErrCancel);
628 smtpClient->errorHandling(ErrCancel); 628 smtpClient->errorHandling(ErrCancel);
629} 629}
630 630
diff --git a/noncore/unsupported/mailit/mailitwindow.cpp b/noncore/unsupported/mailit/mailitwindow.cpp
index 6e298c7..fec4d78 100644
--- a/noncore/unsupported/mailit/mailitwindow.cpp
+++ b/noncore/unsupported/mailit/mailitwindow.cpp
@@ -1,168 +1,168 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2001 Trolltech AS. All rights reserved. 2** Copyright (C) 2001 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of Qt Palmtop Environment. 4** This file is part of Qt Palmtop Environment.
5** 5**
6** This file may be distributed and/or modified under the terms of the 6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software 7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the 8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file. 9** packaging of this file.
10** 10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13** 13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information. 14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15** 15**
16** Contact info@trolltech.com if any conditions of this licensing are 16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you. 17** not clear to you.
18** 18**
19**********************************************************************/ 19**********************************************************************/
20#include <qwhatsthis.h> 20#include <qwhatsthis.h>
21#include <qmessagebox.h> 21#include <qmessagebox.h>
22#include "mailitwindow.h" 22#include "mailitwindow.h"
23 23
24MailItWindow::MailItWindow(QWidget *parent, const char *name, WFlags /*fl*/) 24MailItWindow::MailItWindow(QWidget *parent, const char *name, WFlags /*fl*/)
25 : QMainWindow(parent, name, WStyle_ContextHelp) 25 : QMainWindow(parent, name, WStyle_ContextHelp)
26{ 26{
27 currentCaption = tr("Mailit"); 27 currentCaption = tr("Mailit");
28 setCaption(tr(currentCaption)); 28 setCaption(tr(currentCaption));
29 views = new QWidgetStack(this); 29 views = new QWidgetStack(this);
30 setCentralWidget(views); 30 setCentralWidget(views);
31 QWhatsThis::add(views,tr("Central view area")); 31 QWhatsThis::add(views,tr("Central view area"));
32 emailClient = new EmailClient(views, "client"); 32 emailClient = new EmailClient(views, "client");
33 writeMail = new WriteMail(views, "writing"); 33 writeMail = new WriteMail(views, "writing");
34 readMail = new ReadMail(views, "reading"); 34 readMail = new ReadMail(views, "reading");
35 35
36 views->raiseWidget(emailClient); 36 views->raiseWidget(emailClient);
37 37
38 connect(emailClient, SIGNAL(composeRequested()), 38 connect(emailClient, SIGNAL(composeRequested()),
39 this, SLOT(compose()) ); 39 this, SLOT(compose()) );
40 connect(emailClient, SIGNAL(viewEmail(QListView *, Email *)), this, 40 connect(emailClient, SIGNAL(viewEmail(QListView*,Email*)), this,
41 SLOT(viewMail(QListView *, Email *)) ); 41 SLOT(viewMail(QListView*,Email*)) );
42 connect(emailClient, SIGNAL(mailUpdated(Email *)), this, 42 connect(emailClient, SIGNAL(mailUpdated(Email*)), this,
43 SLOT(updateMailView(Email *)) ); 43 SLOT(updateMailView(Email*)) );
44 44
45 connect(writeMail, SIGNAL(cancelMail()), this, SLOT(showEmailClient()) ); 45 connect(writeMail, SIGNAL(cancelMail()), this, SLOT(showEmailClient()) );
46 connect(writeMail, SIGNAL(sendMailRequested(const Email &)), this, 46 connect(writeMail, SIGNAL(sendMailRequested(const Email&)), this,
47 SLOT(showEmailClient()) ); 47 SLOT(showEmailClient()) );
48 connect(writeMail, SIGNAL(sendMailRequested(const Email &)), emailClient, 48 connect(writeMail, SIGNAL(sendMailRequested(const Email&)), emailClient,
49 SLOT(enqueMail(const Email &)) ); 49 SLOT(enqueMail(const Email&)) );
50 50
51 connect(readMail, SIGNAL(cancelView()), this, SLOT(showEmailClient()) ); 51 connect(readMail, SIGNAL(cancelView()), this, SLOT(showEmailClient()) );
52 connect(readMail, SIGNAL(replyRequested(Email &, bool&)), this, 52 connect(readMail, SIGNAL(replyRequested(Email&,bool&)), this,
53 SLOT(composeReply(Email &, bool&)) ); 53 SLOT(composeReply(Email&,bool&)) );
54 connect(readMail, SIGNAL(forwardRequested(Email &)), this, 54 connect(readMail, SIGNAL(forwardRequested(Email&)), this,
55 SLOT(composeForward(Email &)) ); 55 SLOT(composeForward(Email&)) );
56 56
57 connect(readMail, SIGNAL(removeItem(EmailListItem *, bool &)), emailClient, 57 connect(readMail, SIGNAL(removeItem(EmailListItem*,bool&)), emailClient,
58 SLOT(deleteMail(EmailListItem *, bool &)) ); 58 SLOT(deleteMail(EmailListItem*,bool&)) );
59 connect(readMail, SIGNAL(viewingMail(Email *)), emailClient, 59 connect(readMail, SIGNAL(viewingMail(Email*)), emailClient,
60 SLOT(moveMailFront(Email *)) ); 60 SLOT(moveMailFront(Email*)) );
61 61
62 connect(emailClient, SIGNAL(newCaption(const QString &)), 62 connect(emailClient, SIGNAL(newCaption(const QString&)),
63 this, SLOT(updateCaption(const QString &)) ); 63 this, SLOT(updateCaption(const QString&)) );
64 64
65 connect(readMail, SIGNAL(download(Email *)), emailClient, SLOT(download(Email*)) ); 65 connect(readMail, SIGNAL(download(Email*)), emailClient, SLOT(download(Email*)) );
66 66
67 viewingMail = FALSE; 67 viewingMail = FALSE;
68} 68}
69 69
70MailItWindow::~MailItWindow() 70MailItWindow::~MailItWindow()
71{ 71{
72} 72}
73 73
74void MailItWindow::closeEvent(QCloseEvent *e) 74void MailItWindow::closeEvent(QCloseEvent *e)
75{ 75{
76 if (views->visibleWidget() == emailClient) { 76 if (views->visibleWidget() == emailClient) {
77 e->accept(); 77 e->accept();
78 } else { 78 } else {
79 showEmailClient(); 79 showEmailClient();
80 } 80 }
81} 81}
82 82
83void MailItWindow::compose() 83void MailItWindow::compose()
84{ 84{
85 viewingMail = FALSE; 85 viewingMail = FALSE;
86 emailClient->hide(); 86 emailClient->hide();
87 readMail->hide(); 87 readMail->hide();
88 views->raiseWidget(writeMail); 88 views->raiseWidget(writeMail);
89 writeMail->setAddressList(emailClient->getAdrListRef()); 89 writeMail->setAddressList(emailClient->getAdrListRef());
90 writeMail->newMail(); 90 writeMail->newMail();
91 setCaption( tr( "Write mail" ) ); 91 setCaption( tr( "Write mail" ) );
92} 92}
93 93
94void MailItWindow::composeReply(Email &mail, bool& replyAll) 94void MailItWindow::composeReply(Email &mail, bool& replyAll)
95{ 95{
96 compose(); 96 compose();
97 writeMail->reply(mail,replyAll) ; 97 writeMail->reply(mail,replyAll) ;
98} 98}
99 99
100void MailItWindow::composeForward(Email &mail) 100void MailItWindow::composeForward(Email &mail)
101{ 101{
102 compose(); 102 compose();
103 writeMail->forward(mail) ; 103 writeMail->forward(mail) ;
104} 104}
105 105
106 106
107void MailItWindow::showEmailClient() 107void MailItWindow::showEmailClient()
108{ 108{
109 viewingMail = FALSE; 109 viewingMail = FALSE;
110 writeMail->hide(); 110 writeMail->hide();
111 readMail->hide(); 111 readMail->hide();
112 views->raiseWidget(emailClient); 112 views->raiseWidget(emailClient);
113 setCaption( tr(currentCaption) ); 113 setCaption( tr(currentCaption) );
114} 114}
115 115
116void MailItWindow::viewMail(QListView *view, Email *mail) 116void MailItWindow::viewMail(QListView *view, Email *mail)
117{ 117{
118 viewingMail = TRUE; 118 viewingMail = TRUE;
119 emailClient->hide(); 119 emailClient->hide();
120 120
121 int result=0; 121 int result=0;
122 122
123 if ((mail->received)&&(!mail->downloaded)) 123 if ((mail->received)&&(!mail->downloaded))
124 { 124 {
125 QMessageBox mb( tr("Mail not downloaded"), 125 QMessageBox mb( tr("Mail not downloaded"),
126 tr("The mail you have clicked \n" 126 tr("The mail you have clicked \n"
127 "has not been downloaded yet.\n " 127 "has not been downloaded yet.\n "
128 "Would you like to do it now ?"), 128 "Would you like to do it now ?"),
129 QMessageBox::Information, 129 QMessageBox::Information,
130 QMessageBox::Yes | QMessageBox::Default, 130 QMessageBox::Yes | QMessageBox::Default,
131 QMessageBox::No | QMessageBox::Escape,0 ); 131 QMessageBox::No | QMessageBox::Escape,0 );
132 132
133 result=mb.exec(); 133 result=mb.exec();
134 134
135 if (result==QMessageBox::Yes) 135 if (result==QMessageBox::Yes)
136 { 136 {
137 emailClient->download(mail); 137 emailClient->download(mail);
138 } 138 }
139 } 139 }
140 140
141 readMail->update(view, mail); 141 readMail->update(view, mail);
142 views->raiseWidget(readMail); 142 views->raiseWidget(readMail);
143 setCaption( tr( "Read Mail" ) ); 143 setCaption( tr( "Read Mail" ) );
144} 144}
145 145
146void MailItWindow::updateMailView(Email *mail) 146void MailItWindow::updateMailView(Email *mail)
147{ 147{
148 if (viewingMail) { 148 if (viewingMail) {
149 readMail->mailUpdated(mail); 149 readMail->mailUpdated(mail);
150 } 150 }
151} 151}
152 152
153void MailItWindow::updateCaption(const QString &newCaption) 153void MailItWindow::updateCaption(const QString &newCaption)
154{ 154{
155 currentCaption = newCaption; 155 currentCaption = newCaption;
156 setCaption(tr(currentCaption)); 156 setCaption(tr(currentCaption));
157} 157}
158 158
159void MailItWindow::setDocument(const QString &_address) 159void MailItWindow::setDocument(const QString &_address)
160{ 160{
161 // strip leading 'mailto:' 161 // strip leading 'mailto:'
162 QString address = _address; 162 QString address = _address;
163 if (address.startsWith("mailto:")) 163 if (address.startsWith("mailto:"))
164 address = address.mid(6); 164 address = address.mid(6);
165 165
166 compose(); 166 compose();
167 writeMail->setRecipient(address); 167 writeMail->setRecipient(address);
168} 168}
diff --git a/noncore/unsupported/oipkg/mainwindow.cpp b/noncore/unsupported/oipkg/mainwindow.cpp
index a09bc30..7f1c0b8 100644
--- a/noncore/unsupported/oipkg/mainwindow.cpp
+++ b/noncore/unsupported/oipkg/mainwindow.cpp
@@ -1,515 +1,515 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9// Copyright (C) 2000 Trolltech AS. 9// Copyright (C) 2000 Trolltech AS.
10// adadpted form qpe/qipkg 10// adadpted form qpe/qipkg
11// (c) 2002 Patrick S. Vogt <tille@handhelds.org> 11// (c) 2002 Patrick S. Vogt <tille@handhelds.org>
12 12
13 13
14#include "mainwindow.h" 14#include "mainwindow.h"
15 15
16#include <qmenubar.h> 16#include <qmenubar.h>
17#include <qpe/qpemessagebox.h> 17#include <qpe/qpemessagebox.h>
18#include <qpe/resource.h> 18#include <qpe/resource.h>
19#include <qpe/config.h> 19#include <qpe/config.h>
20#include <qtoolbar.h> 20#include <qtoolbar.h>
21#include <qpe/qcopenvelope_qws.h> 21#include <qpe/qcopenvelope_qws.h>
22#include <qaction.h> 22#include <qaction.h>
23#include <qmessagebox.h> 23#include <qmessagebox.h>
24#include <qpopupmenu.h> 24#include <qpopupmenu.h>
25#include <qtoolbutton.h> 25#include <qtoolbutton.h>
26#include <qstring.h> 26#include <qstring.h>
27#include <qlabel.h> 27#include <qlabel.h>
28#include <qfile.h> 28#include <qfile.h>
29#include <qlistview.h> 29#include <qlistview.h>
30#include <qtextview.h> 30#include <qtextview.h>
31#include <qcheckbox.h> 31#include <qcheckbox.h>
32#include <qlineedit.h> 32#include <qlineedit.h>
33#include <qtabwidget.h> 33#include <qtabwidget.h>
34#include <qcombobox.h> 34#include <qcombobox.h>
35#include <qmessagebox.h> 35#include <qmessagebox.h>
36#include <qpushbutton.h> 36#include <qpushbutton.h>
37#include <qlayout.h> 37#include <qlayout.h>
38 38
39#include "pksettingsbase.h" 39#include "pksettingsbase.h"
40#include "utils.h" 40#include "utils.h"
41#include "packagelistitem.h" 41#include "packagelistitem.h"
42 42
43 43
44MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : 44MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) :
45 QMainWindow( parent, name, f ) 45 QMainWindow( parent, name, f )
46// packageListServers( QObject(parent), name ), 46// packageListServers( QObject(parent), name ),
47// packageListSearch( parent, name ), 47// packageListSearch( parent, name ),
48// packageListDocLnk( parent, name ) 48// packageListDocLnk( parent, name )
49 { 49 {
50 setCaption( tr("Package Manager") ); 50 setCaption( tr("Package Manager") );
51 settings = new PackageManagerSettings(this,0,TRUE); 51 settings = new PackageManagerSettings(this,0,TRUE);
52 listViewPackages = new PackageListView( this,"listViewPackages",settings ); 52 listViewPackages = new PackageListView( this,"listViewPackages",settings );
53 setCentralWidget( listViewPackages ); 53 setCentralWidget( listViewPackages );
54 listViewPackages->addList( tr("feeds"), &packageListServers ); 54 listViewPackages->addList( tr("feeds"), &packageListServers );
55 listViewPackages->addList( tr("ipkgfind&killefiz"), &packageListSearch ); 55 listViewPackages->addList( tr("ipkgfind&killefiz"), &packageListSearch );
56 listViewPackages->addList( tr("documents"), &packageListDocLnk ); 56 listViewPackages->addList( tr("documents"), &packageListDocLnk );
57 ipkg = new PmIpkg( settings, this ); 57 ipkg = new PmIpkg( settings, this );
58 packageListServers.setSettings( settings ); 58 packageListServers.setSettings( settings );
59 packageListSearch.setSettings( settings ); 59 packageListSearch.setSettings( settings );
60 packageListDocLnk.setSettings( settings ); 60 packageListDocLnk.setSettings( settings );
61 pvDebug(9,"packageListServers.update"); 61 pvDebug(9,"packageListServers.update");
62 packageListServers.update(); 62 packageListServers.update();
63 pvDebug(9,"packageListDocLnk.update"); 63 pvDebug(9,"packageListDocLnk.update");
64 packageListDocLnk.update(); 64 packageListDocLnk.update();
65 pvDebug(9,"makeMenu"); 65 pvDebug(9,"makeMenu");
66 makeMenu(); 66 makeMenu();
67 makeChannel(); 67 makeChannel();
68 68
69 69
70 connect( section, SIGNAL(activated(int)), SLOT(sectionChanged()) ); 70 connect( section, SIGNAL(activated(int)), SLOT(sectionChanged()) );
71 connect( subsection, SIGNAL(activated(int)), SLOT(subSectionChanged()) ); 71 connect( subsection, SIGNAL(activated(int)), SLOT(subSectionChanged()) );
72 72
73 connect( settings->removeLinksButton, SIGNAL( clicked()), 73 connect( settings->removeLinksButton, SIGNAL( clicked()),
74 SLOT(removeLinks()) ); 74 SLOT(removeLinks()) );
75 connect( settings->createLinksButton, SIGNAL( clicked()), 75 connect( settings->createLinksButton, SIGNAL( clicked()),
76 SLOT(createLinks()) ); 76 SLOT(createLinks()) );
77 77
78 pvDebug(9,"displayList"); 78 pvDebug(9,"displayList");
79 displayList(); 79 displayList();
80} 80}
81 81
82void MainWindow::makeMenu() 82void MainWindow::makeMenu()
83{ 83{
84 84
85 QToolBar *toolBar = new QToolBar( this ); 85 QToolBar *toolBar = new QToolBar( this );
86 QMenuBar *menuBar = new QMenuBar( toolBar ); 86 QMenuBar *menuBar = new QMenuBar( toolBar );
87 QPopupMenu *srvMenu = new QPopupMenu( menuBar ); 87 QPopupMenu *srvMenu = new QPopupMenu( menuBar );
88 QPopupMenu *viewMenu = new QPopupMenu( menuBar ); 88 QPopupMenu *viewMenu = new QPopupMenu( menuBar );
89 QPopupMenu *cfgMenu = new QPopupMenu( menuBar ); 89 QPopupMenu *cfgMenu = new QPopupMenu( menuBar );
90 QPopupMenu *helpMenu = new QPopupMenu( menuBar ); 90 QPopupMenu *helpMenu = new QPopupMenu( menuBar );
91 91
92 setToolBarsMovable( false ); 92 setToolBarsMovable( false );
93 toolBar->setHorizontalStretchable( true ); 93 toolBar->setHorizontalStretchable( true );
94 menuBar->insertItem( tr( "Package" ), srvMenu ); 94 menuBar->insertItem( tr( "Package" ), srvMenu );
95 menuBar->insertItem( tr( "View" ), viewMenu ); 95 menuBar->insertItem( tr( "View" ), viewMenu );
96 menuBar->insertItem( tr( "Settings" ), cfgMenu ); 96 menuBar->insertItem( tr( "Settings" ), cfgMenu );
97 menuBar->insertItem( tr( "Help" ), helpMenu ); 97 menuBar->insertItem( tr( "Help" ), helpMenu );
98 98
99// QLabel *spacer; 99// QLabel *spacer;
100// spacer = new QLabel( "", toolBar ); 100// spacer = new QLabel( "", toolBar );
101// spacer->setBackgroundColor( toolBar->backgroundColor() ); 101// spacer->setBackgroundColor( toolBar->backgroundColor() );
102// toolBar->setStretchableWidget( spacer ); 102// toolBar->setStretchableWidget( spacer );
103 103
104 104
105 runAction = new QAction( tr( "Apply" ), 105 runAction = new QAction( tr( "Apply" ),
106 Resource::loadPixmap( "oipkg/install" ), 106 Resource::loadPixmap( "oipkg/install" ),
107 QString::null, 0, this, 0 ); 107 QString::null, 0, this, 0 );
108 connect( runAction, SIGNAL( activated() ), 108 connect( runAction, SIGNAL( activated() ),
109 this, SLOT( runIpkg() ) ); 109 this, SLOT( runIpkg() ) );
110 runAction->addTo( toolBar ); 110 runAction->addTo( toolBar );
111 runAction->addTo( srvMenu ); 111 runAction->addTo( srvMenu );
112 112
113 srvMenu->insertSeparator(); 113 srvMenu->insertSeparator();
114 114
115 updateAction = new QAction( tr( "Update" ), 115 updateAction = new QAction( tr( "Update" ),
116 Resource::loadIconSet( "oipkg/update" ), 116 Resource::loadIconSet( "oipkg/update" ),
117 QString::null, 0, this, 0 ); 117 QString::null, 0, this, 0 );
118 connect( updateAction, SIGNAL( activated() ), 118 connect( updateAction, SIGNAL( activated() ),
119 this , SLOT( updateList() ) ); 119 this , SLOT( updateList() ) );
120 updateAction->addTo( toolBar ); 120 updateAction->addTo( toolBar );
121 updateAction->addTo( srvMenu ); 121 updateAction->addTo( srvMenu );
122 122
123 QAction *cfgact; 123 QAction *cfgact;
124 124
125 cfgact = new QAction( tr( "Setups" ), 125 cfgact = new QAction( tr( "Setups" ),
126 QString::null, 0, this, 0 ); 126 QString::null, 0, this, 0 );
127 connect( cfgact, SIGNAL( activated() ), 127 connect( cfgact, SIGNAL( activated() ),
128 SLOT( showSettingsSetup() ) ); 128 SLOT( showSettingsSetup() ) );
129 cfgact->addTo( cfgMenu ); 129 cfgact->addTo( cfgMenu );
130 130
131 cfgact = new QAction( tr( "Servers" ), 131 cfgact = new QAction( tr( "Servers" ),
132 QString::null, 0, this, 0 ); 132 QString::null, 0, this, 0 );
133 connect( cfgact, SIGNAL( activated() ), 133 connect( cfgact, SIGNAL( activated() ),
134 SLOT( showSettingsSrv() ) ); 134 SLOT( showSettingsSrv() ) );
135 cfgact->addTo( cfgMenu ); 135 cfgact->addTo( cfgMenu );
136 cfgact = new QAction( tr( "Destinations" ), 136 cfgact = new QAction( tr( "Destinations" ),
137 QString::null, 0, this, 0 ); 137 QString::null, 0, this, 0 );
138 connect( cfgact, SIGNAL( activated() ), 138 connect( cfgact, SIGNAL( activated() ),
139 SLOT( showSettingsDst() ) ); 139 SLOT( showSettingsDst() ) );
140 cfgact->addTo( cfgMenu ); 140 cfgact->addTo( cfgMenu );
141 141
142 QAction *a; 142 QAction *a;
143 143
144 // SECTIONS 144 // SECTIONS
145 sectionBar = new QToolBar( this ); 145 sectionBar = new QToolBar( this );
146 addToolBar( sectionBar, "Section", QMainWindow::Top, TRUE ); 146 addToolBar( sectionBar, "Section", QMainWindow::Top, TRUE );
147 sectionBar->setHorizontalStretchable( true ); 147 sectionBar->setHorizontalStretchable( true );
148 QLabel *label = new QLabel( sectionBar, "section" ); 148 QLabel *label = new QLabel( sectionBar, "section" );
149// label->setBackgroundMode( NoBackground ); 149// label->setBackgroundMode( NoBackground );
150 label->font().setPointSize( 8 ); 150 label->font().setPointSize( 8 );
151 label->setText( tr( "Section:" ) ); 151 label->setText( tr( "Section:" ) );
152 sectionBar->setStretchableWidget( label ); 152 sectionBar->setStretchableWidget( label );
153 section = new QComboBox( false, sectionBar ); 153 section = new QComboBox( false, sectionBar );
154 section->font().setPointSize( 8 ); 154 section->font().setPointSize( 8 );
155 label = new QLabel( " / ", sectionBar ); 155 label = new QLabel( " / ", sectionBar );
156 label->font().setPointSize( 8 ); 156 label->font().setPointSize( 8 );
157// label->setBackgroundMode( PaletteForeground ); 157// label->setBackgroundMode( PaletteForeground );
158 subsection = new QComboBox( false, sectionBar ); 158 subsection = new QComboBox( false, sectionBar );
159 subsection->font().setPointSize( 8 ); 159 subsection->font().setPointSize( 8 );
160 a = new QAction( tr( "Close Section" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); 160 a = new QAction( tr( "Close Section" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 );
161 connect( a, SIGNAL( activated() ), this, SLOT( sectionClose() ) ); 161 connect( a, SIGNAL( activated() ), this, SLOT( sectionClose() ) );
162 a->addTo( sectionBar ); 162 a->addTo( sectionBar );
163 setSections(); 163 setSections();
164 setSubSections(); 164 setSubSections();
165 sectionAction = new QAction( tr( "Sections" ), QString::null, 0, this, 0 ); 165 sectionAction = new QAction( tr( "Sections" ), QString::null, 0, this, 0 );
166 connect( sectionAction, SIGNAL( toggled(bool) ), this, SLOT( sectionShow(bool) ) ); 166 connect( sectionAction, SIGNAL( toggled(bool) ), this, SLOT( sectionShow(bool) ) );
167 sectionAction->setToggleAction( true ); 167 sectionAction->setToggleAction( true );
168 sectionAction->addTo( viewMenu ); 168 sectionAction->addTo( viewMenu );
169 // sectionBar->setStretchableWidget( section ); 169 // sectionBar->setStretchableWidget( section );
170 170
171 //FIND 171 //FIND
172 findBar = new QToolBar(this); 172 findBar = new QToolBar(this);
173 addToolBar( findBar, "Filter", QMainWindow::Top, TRUE ); 173 addToolBar( findBar, "Filter", QMainWindow::Top, TRUE );
174 label = new QLabel( tr("Filter: "), findBar ); 174 label = new QLabel( tr("Filter: "), findBar );
175// label->setBackgroundMode( PaletteForeground ); 175// label->setBackgroundMode( PaletteForeground );
176 findBar->setHorizontalStretchable( TRUE ); 176 findBar->setHorizontalStretchable( TRUE );
177 findEdit = new QLineEdit( findBar, "findEdit" ); 177 findEdit = new QLineEdit( findBar, "findEdit" );
178 findBar->setStretchableWidget( findEdit ); 178 findBar->setStretchableWidget( findEdit );
179 connect( findEdit, SIGNAL( textChanged( const QString & ) ), 179 connect( findEdit, SIGNAL( textChanged(const QString&) ),
180 this, SLOT( displayList() ) ); 180 this, SLOT( displayList() ) );
181 a = new QAction( tr( "Clear Find" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 ); 181 a = new QAction( tr( "Clear Find" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 );
182 connect( a, SIGNAL( activated() ), findEdit, SLOT( clear() ) ); 182 connect( a, SIGNAL( activated() ), findEdit, SLOT( clear() ) );
183 a->addTo( findBar ); 183 a->addTo( findBar );
184 a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); 184 a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 );
185 connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); 185 connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) );
186 a->addTo( findBar ); 186 a->addTo( findBar );
187 findAction = new QAction( tr( "Filter" ), QString::null, 0, this, 0 ); 187 findAction = new QAction( tr( "Filter" ), QString::null, 0, this, 0 );
188 connect( findAction, SIGNAL( toggled(bool) ), this, SLOT( findShow(bool) ) ); 188 connect( findAction, SIGNAL( toggled(bool) ), this, SLOT( findShow(bool) ) );
189 findAction->setToggleAction( true ); 189 findAction->setToggleAction( true );
190 findAction->addTo( viewMenu ); 190 findAction->addTo( viewMenu );
191 191
192 //SEARCH 192 //SEARCH
193 searchBar = new QToolBar(this); 193 searchBar = new QToolBar(this);
194 addToolBar( searchBar, "Search", QMainWindow::Top, TRUE ); 194 addToolBar( searchBar, "Search", QMainWindow::Top, TRUE );
195 label = new QLabel( tr("Search: "), searchBar ); 195 label = new QLabel( tr("Search: "), searchBar );
196// label->setBackgroundMode( PaletteForeground ); 196// label->setBackgroundMode( PaletteForeground );
197 searchBar->setHorizontalStretchable( TRUE ); 197 searchBar->setHorizontalStretchable( TRUE );
198 searchEdit = new QLineEdit( searchBar, "seachEdit" ); 198 searchEdit = new QLineEdit( searchBar, "seachEdit" );
199 searchBar->setStretchableWidget( searchEdit ); 199 searchBar->setStretchableWidget( searchEdit );
200// connect( searchEdit, SIGNAL( textChanged( const QString & ) ), 200// connect( searchEdit, SIGNAL( textChanged(const QString&) ),
201// this, SLOT( displayList() ) ); 201// this, SLOT( displayList() ) );
202 a = new QAction( tr( "Clear Search" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 ); 202 a = new QAction( tr( "Clear Search" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 );
203 connect( a, SIGNAL( activated() ), searchEdit, SLOT( clear() ) ); 203 connect( a, SIGNAL( activated() ), searchEdit, SLOT( clear() ) );
204 a->addTo( searchBar ); 204 a->addTo( searchBar );
205 searchCommit = new QAction( tr( "Do Search" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); 205 searchCommit = new QAction( tr( "Do Search" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 );
206 connect( searchCommit, SIGNAL( activated() ), SLOT( remotePackageQuery() ) ); 206 connect( searchCommit, SIGNAL( activated() ), SLOT( remotePackageQuery() ) );
207 searchCommit->addTo( searchBar ); 207 searchCommit->addTo( searchBar );
208 a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); 208 a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 );
209 connect( a, SIGNAL( activated() ), this, SLOT( searchClose() ) ); 209 connect( a, SIGNAL( activated() ), this, SLOT( searchClose() ) );
210 a->addTo( searchBar ); 210 a->addTo( searchBar );
211 searchAction = new QAction( tr( "Search" ), QString::null, 0, this, 0 ); 211 searchAction = new QAction( tr( "Search" ), QString::null, 0, this, 0 );
212 connect( searchAction, SIGNAL( toggled(bool) ), this, SLOT( searchShow(bool) ) ); 212 connect( searchAction, SIGNAL( toggled(bool) ), this, SLOT( searchShow(bool) ) );
213 searchAction->setToggleAction( true ); 213 searchAction->setToggleAction( true );
214 searchAction->addTo( viewMenu ); 214 searchAction->addTo( viewMenu );
215 215
216 //DEST 216 //DEST
217 destBar = new QToolBar(this); 217 destBar = new QToolBar(this);
218 addToolBar( destBar, "Destination", QMainWindow::Top, TRUE ); 218 addToolBar( destBar, "Destination", QMainWindow::Top, TRUE );
219 label = new QLabel( tr("Destination: "), destBar ); 219 label = new QLabel( tr("Destination: "), destBar );
220// label->setBackgroundMode( PaletteForeground ); 220// label->setBackgroundMode( PaletteForeground );
221 destBar->setHorizontalStretchable( TRUE ); 221 destBar->setHorizontalStretchable( TRUE );
222 destination = new QComboBox( false, destBar ); 222 destination = new QComboBox( false, destBar );
223 destination->insertStringList( settings->getDestinationNames() ); 223 destination->insertStringList( settings->getDestinationNames() );
224 setComboName(destination,settings->getDestinationName()); 224 setComboName(destination,settings->getDestinationName());
225 connect( destination, SIGNAL(activated(int)), 225 connect( destination, SIGNAL(activated(int)),
226 settings, SLOT(activeDestinationChange(int)) ); 226 settings, SLOT(activeDestinationChange(int)) );
227// space->setBackgroundMode( PaletteForeground ); 227// space->setBackgroundMode( PaletteForeground );
228 CheckBoxLink = new QCheckBox( tr("Link"), destBar); 228 CheckBoxLink = new QCheckBox( tr("Link"), destBar);
229// CheckBoxLink->setBackgroundMode( PaletteForeground ); 229// CheckBoxLink->setBackgroundMode( PaletteForeground );
230 CheckBoxLink->setChecked( settings->createLinks() ); 230 CheckBoxLink->setChecked( settings->createLinks() );
231 connect( CheckBoxLink, SIGNAL(toggled(bool)), 231 connect( CheckBoxLink, SIGNAL(toggled(bool)),
232 settings, SLOT(linkEnabled(bool)) ); 232 settings, SLOT(linkEnabled(bool)) );
233 destAction = new QAction( tr( "Destinations" ), QString::null, 0, this, 0 ); 233 destAction = new QAction( tr( "Destinations" ), QString::null, 0, this, 0 );
234 connect( destAction, SIGNAL( toggled(bool) ), SLOT( destShow(bool) ) ); 234 connect( destAction, SIGNAL( toggled(bool) ), SLOT( destShow(bool) ) );
235 a = new QAction( tr( "Close Destinations" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); 235 a = new QAction( tr( "Close Destinations" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 );
236 connect( a, SIGNAL( activated() ), SLOT( destClose() ) ); 236 connect( a, SIGNAL( activated() ), SLOT( destClose() ) );
237 a->addTo( destBar ); 237 a->addTo( destBar );
238 destBar->setStretchableWidget( CheckBoxLink ); 238 destBar->setStretchableWidget( CheckBoxLink );
239 destAction->setToggleAction( true ); 239 destAction->setToggleAction( true );
240 destAction->addTo( viewMenu ); 240 destAction->addTo( viewMenu );
241 241
242// helpMenu 242// helpMenu
243 helpMenu->insertSeparator(); 243 helpMenu->insertSeparator();
244 a = new QAction( tr( "Package Actions" ), QString::null, 0, this, 0 ); 244 a = new QAction( tr( "Package Actions" ), QString::null, 0, this, 0 );
245 a->addTo( helpMenu ); 245 a->addTo( helpMenu );
246 helpMenu->insertSeparator(); 246 helpMenu->insertSeparator();
247 a = new QAction( tr( "Install" ), 247 a = new QAction( tr( "Install" ),
248 Resource::loadPixmap( "oipkg/install" ), QString::null, 0, this, 0 ); 248 Resource::loadPixmap( "oipkg/install" ), QString::null, 0, this, 0 );
249 a->addTo( helpMenu ); 249 a->addTo( helpMenu );
250 a = new QAction( tr( "Remove" ), 250 a = new QAction( tr( "Remove" ),
251 Resource::loadPixmap( "oipkg/uninstall" ), QString::null, 0, this, 0 ); 251 Resource::loadPixmap( "oipkg/uninstall" ), QString::null, 0, this, 0 );
252 a->addTo( helpMenu ); 252 a->addTo( helpMenu );
253 helpMenu->insertSeparator(); 253 helpMenu->insertSeparator();
254 a = new QAction( tr( "Package Status" ), QString::null, 0, this, 0 ); 254 a = new QAction( tr( "Package Status" ), QString::null, 0, this, 0 );
255 a->addTo( helpMenu ); 255 a->addTo( helpMenu );
256 helpMenu->insertSeparator(); 256 helpMenu->insertSeparator();
257 a = new QAction( tr( "New version, installed" ), 257 a = new QAction( tr( "New version, installed" ),
258 Resource::loadPixmap( "oipkg/installed" ), QString::null, 0, this, 0 ); 258 Resource::loadPixmap( "oipkg/installed" ), QString::null, 0, this, 0 );
259 a->addTo( helpMenu ); 259 a->addTo( helpMenu );
260 a = new QAction( tr( "New version, not installed" ), 260 a = new QAction( tr( "New version, not installed" ),
261 Resource::loadPixmap( "oipkg/uninstalled" ), QString::null, 0, this, 0 ); 261 Resource::loadPixmap( "oipkg/uninstalled" ), QString::null, 0, this, 0 );
262 a->addTo( helpMenu ); 262 a->addTo( helpMenu );
263 a = new QAction( tr( "Old version, installed" ), 263 a = new QAction( tr( "Old version, installed" ),
264 Resource::loadPixmap( "oipkg/installedOld" ), QString::null, 0, this, 0 ); 264 Resource::loadPixmap( "oipkg/installedOld" ), QString::null, 0, this, 0 );
265 a->addTo( helpMenu ); 265 a->addTo( helpMenu );
266 a = new QAction( tr( "Old version, not installed" ), 266 a = new QAction( tr( "Old version, not installed" ),
267 Resource::loadPixmap( "oipkg/uninstalledOld" ), QString::null, 0, this, 0 ); 267 Resource::loadPixmap( "oipkg/uninstalledOld" ), QString::null, 0, this, 0 );
268 a->addTo( helpMenu ); 268 a->addTo( helpMenu );
269 a = new QAction( tr( "Old version, new version installed" ), 269 a = new QAction( tr( "Old version, new version installed" ),
270 Resource::loadPixmap( "oipkg/uninstalledOldinstalledNew" ), QString::null, 0, this, 0 ); 270 Resource::loadPixmap( "oipkg/uninstalledOldinstalledNew" ), QString::null, 0, this, 0 );
271 a->addTo( helpMenu ); 271 a->addTo( helpMenu );
272 a = new QAction( tr( "New version, old version installed" ), 272 a = new QAction( tr( "New version, old version installed" ),
273 Resource::loadPixmap( "oipkg/uninstalledInstalledOld" ), QString::null, 0, this, 0 ); 273 Resource::loadPixmap( "oipkg/uninstalledInstalledOld" ), QString::null, 0, this, 0 );
274 a->addTo( helpMenu ); 274 a->addTo( helpMenu );
275 //a = new QAction( tr( "" ), 275 //a = new QAction( tr( "" ),
276 // Resource::loadPixmap( "oipkg/" ), QString::null, 0, this, 0 ); 276 // Resource::loadPixmap( "oipkg/" ), QString::null, 0, this, 0 );
277 // a->addTo( helpMenu ); 277 // a->addTo( helpMenu );
278 278
279 // configure the menus 279 // configure the menus
280 Config cfg( "oipkg", Config::User ); 280 Config cfg( "oipkg", Config::User );
281 cfg.setGroup( "gui" ); 281 cfg.setGroup( "gui" );
282 282
283 findShow( cfg.readBoolEntry( "findBar", true ) ); 283 findShow( cfg.readBoolEntry( "findBar", true ) );
284 searchShow( cfg.readBoolEntry( "searchBar", true ) ); 284 searchShow( cfg.readBoolEntry( "searchBar", true ) );
285 sectionShow( cfg.readBoolEntry( "sectionBar", true ) ); 285 sectionShow( cfg.readBoolEntry( "sectionBar", true ) );
286 destShow( cfg.readBoolEntry( "destBar", false ) ); 286 destShow( cfg.readBoolEntry( "destBar", false ) );
287 setComboName(section,cfg.readEntry("default_section")); 287 setComboName(section,cfg.readEntry("default_section"));
288 sectionChanged(); 288 sectionChanged();
289} 289}
290 290
291MainWindow::~MainWindow() 291MainWindow::~MainWindow()
292{ 292{
293 Config cfg( "oipkg", Config::User ); 293 Config cfg( "oipkg", Config::User );
294 cfg.setGroup( "gui" ); 294 cfg.setGroup( "gui" );
295 cfg.writeEntry( "findBar", !findBar->isHidden() ); 295 cfg.writeEntry( "findBar", !findBar->isHidden() );
296 cfg.writeEntry( "searchBar", !searchBar->isHidden() ); 296 cfg.writeEntry( "searchBar", !searchBar->isHidden() );
297 cfg.writeEntry( "sectionBar", !sectionBar->isHidden() ); 297 cfg.writeEntry( "sectionBar", !sectionBar->isHidden() );
298 cfg.writeEntry( "destBar", !destBar->isHidden() ); 298 cfg.writeEntry( "destBar", !destBar->isHidden() );
299 cfg.writeEntry( "default_section", section->currentText() ); 299 cfg.writeEntry( "default_section", section->currentText() );
300 300
301} 301}
302 302
303void MainWindow::runIpkg() 303void MainWindow::runIpkg()
304{ 304{
305 packageListServers.allPackages(); 305 packageListServers.allPackages();
306 ipkg->loadList( &packageListSearch ); 306 ipkg->loadList( &packageListSearch );
307 ipkg->loadList( &packageListDocLnk ); 307 ipkg->loadList( &packageListDocLnk );
308 ipkg->loadList( &packageListServers ); 308 ipkg->loadList( &packageListServers );
309 ipkg->commit(); 309 ipkg->commit();
310 ipkg->clearLists(); 310 ipkg->clearLists();
311 // ##### If we looked in the list of files, we could send out accurate 311 // ##### If we looked in the list of files, we could send out accurate
312 // ##### messages. But we don't bother yet, and just do an "all". 312 // ##### messages. But we don't bother yet, and just do an "all".
313 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 313 QCopEnvelope e("QPE/System", "linkChanged(QString)");
314 QString lf = QString::null; 314 QString lf = QString::null;
315 e << lf; 315 e << lf;
316 displayList(); 316 displayList();
317} 317}
318 318
319void MainWindow::updateList() 319void MainWindow::updateList()
320{ 320{
321 packageListServers.clear(); 321 packageListServers.clear();
322 packageListSearch.clear(); 322 packageListSearch.clear();
323 323
324 packageListDocLnk.clear(); 324 packageListDocLnk.clear();
325 ipkg->update(); 325 ipkg->update();
326 packageListServers.update(); 326 packageListServers.update();
327 packageListSearch.update(); 327 packageListSearch.update();
328 packageListDocLnk.update(); 328 packageListDocLnk.update();
329} 329}
330 330
331void MainWindow::filterList() 331void MainWindow::filterList()
332{ 332{
333 QString f = ""; 333 QString f = "";
334 if ( findAction->isOn() ) f = findEdit->text(); 334 if ( findAction->isOn() ) f = findEdit->text();
335 packageListServers.filterPackages( f ); 335 packageListServers.filterPackages( f );
336} 336}
337 337
338void MainWindow::displayList() 338void MainWindow::displayList()
339{ 339{
340 filterList(); 340 filterList();
341 listViewPackages->display(); 341 listViewPackages->display();
342} 342}
343 343
344void MainWindow::sectionChanged() 344void MainWindow::sectionChanged()
345{ 345{
346 disconnect( section, SIGNAL( activated(int) ), 346 disconnect( section, SIGNAL( activated(int) ),
347 this, SLOT( sectionChanged() ) ); 347 this, SLOT( sectionChanged() ) );
348 disconnect( subsection, SIGNAL(activated(int) ), 348 disconnect( subsection, SIGNAL(activated(int) ),
349 this, SLOT( subSectionChanged() ) ); 349 this, SLOT( subSectionChanged() ) );
350 subsection->clear(); 350 subsection->clear();
351 packageListServers.setSection( section->currentText() ); 351 packageListServers.setSection( section->currentText() );
352 setSubSections(); 352 setSubSections();
353 connect( section, SIGNAL( activated(int) ), 353 connect( section, SIGNAL( activated(int) ),
354 this, SLOT( sectionChanged() ) ); 354 this, SLOT( sectionChanged() ) );
355 connect( subsection, SIGNAL(activated(int) ), 355 connect( subsection, SIGNAL(activated(int) ),
356 this, SLOT( subSectionChanged() ) ); 356 this, SLOT( subSectionChanged() ) );
357 displayList(); 357 displayList();
358} 358}
359 359
360void MainWindow::subSectionChanged() 360void MainWindow::subSectionChanged()
361{ 361{
362 disconnect( section, SIGNAL( activated(int) ), 362 disconnect( section, SIGNAL( activated(int) ),
363 this, SLOT( sectionChanged() ) ); 363 this, SLOT( sectionChanged() ) );
364 disconnect( subsection, SIGNAL(activated(int) ), 364 disconnect( subsection, SIGNAL(activated(int) ),
365 this, SLOT( subSectionChanged() ) ); 365 this, SLOT( subSectionChanged() ) );
366 packageListServers.setSubSection( subsection->currentText() ); 366 packageListServers.setSubSection( subsection->currentText() );
367 connect( section, SIGNAL( activated(int) ), 367 connect( section, SIGNAL( activated(int) ),
368 this, SLOT( sectionChanged() ) ); 368 this, SLOT( sectionChanged() ) );
369 connect( subsection, SIGNAL(activated(int) ), 369 connect( subsection, SIGNAL(activated(int) ),
370 this, SLOT( subSectionChanged() ) ); 370 this, SLOT( subSectionChanged() ) );
371 displayList(); 371 displayList();
372} 372}
373 373
374void MainWindow::setSections() 374void MainWindow::setSections()
375{ 375{
376 section->clear(); 376 section->clear();
377 section->insertStringList( packageListServers.getSections() ); 377 section->insertStringList( packageListServers.getSections() );
378} 378}
379 379
380void MainWindow::setSubSections() 380void MainWindow::setSubSections()
381{ 381{
382 subsection->clear(); 382 subsection->clear();
383 subsection->insertStringList( packageListServers.getSubSections() ); 383 subsection->insertStringList( packageListServers.getSubSections() );
384} 384}
385 385
386 386
387void MainWindow::showSettings(int i) 387void MainWindow::showSettings(int i)
388{ 388{
389 if ( settings->showDialog( i ) ) 389 if ( settings->showDialog( i ) )
390 { 390 {
391 updateList(); 391 updateList();
392 } 392 }
393 setComboName(destination,settings->getDestinationName()); 393 setComboName(destination,settings->getDestinationName());
394 CheckBoxLink->setChecked( settings->createLinks() ); 394 CheckBoxLink->setChecked( settings->createLinks() );
395} 395}
396void MainWindow::showSettingsSetup() 396void MainWindow::showSettingsSetup()
397{ 397{
398 showSettings(0); 398 showSettings(0);
399} 399}
400void MainWindow::showSettingsSrv() 400void MainWindow::showSettingsSrv()
401{ 401{
402 showSettings(1); 402 showSettings(1);
403} 403}
404void MainWindow::showSettingsDst() 404void MainWindow::showSettingsDst()
405{ 405{
406 showSettings(2); 406 showSettings(2);
407} 407}
408 408
409void MainWindow::sectionShow(bool b) 409void MainWindow::sectionShow(bool b)
410{ 410{
411 if (b) sectionBar->show(); 411 if (b) sectionBar->show();
412 else sectionBar->hide(); 412 else sectionBar->hide();
413 sectionAction->setOn( b ); 413 sectionAction->setOn( b );
414} 414}
415 415
416void MainWindow::sectionClose() 416void MainWindow::sectionClose()
417{ 417{
418 sectionAction->setOn( false ); 418 sectionAction->setOn( false );
419} 419}
420 420
421void MainWindow::findShow(bool b) 421void MainWindow::findShow(bool b)
422{ 422{
423 if (b) findBar->show(); 423 if (b) findBar->show();
424 else findBar->hide(); 424 else findBar->hide();
425 findAction->setOn( b ); 425 findAction->setOn( b );
426} 426}
427 427
428void MainWindow::findClose() 428void MainWindow::findClose()
429{ 429{
430 findAction->setOn( false ); 430 findAction->setOn( false );
431} 431}
432 432
433void MainWindow::searchShow(bool b) 433void MainWindow::searchShow(bool b)
434{ 434{
435 if (b) searchBar->show(); 435 if (b) searchBar->show();
436 else searchBar->hide(); 436 else searchBar->hide();
437 searchAction->setOn( b ); 437 searchAction->setOn( b );
438} 438}
439 439
440void MainWindow::searchClose() 440void MainWindow::searchClose()
441{ 441{
442 searchAction->setOn( false ); 442 searchAction->setOn( false );
443} 443}
444 444
445 445
446void MainWindow::destShow(bool b) 446void MainWindow::destShow(bool b)
447{ 447{
448 if (b) destBar->show(); 448 if (b) destBar->show();
449 else destBar->hide(); 449 else destBar->hide();
450 destAction->setOn( b ); 450 destAction->setOn( b );
451} 451}
452 452
453void MainWindow::destClose() 453void MainWindow::destClose()
454{ 454{
455 destAction->setOn( false ); 455 destAction->setOn( false );
456} 456}
457 457
458void MainWindow::setDocument(const QString &fileName) 458void MainWindow::setDocument(const QString &fileName)
459{ 459{
460 if ( !QFile::exists( fileName ) ) return; 460 if ( !QFile::exists( fileName ) ) return;
461 ipkg->installFile( fileName ); 461 ipkg->installFile( fileName );
462 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 462 QCopEnvelope e("QPE/System", "linkChanged(QString)");
463 QString lf = QString::null; 463 QString lf = QString::null;
464 e << lf; 464 e << lf;
465} 465}
466 466
467 467
468void MainWindow::makeChannel() 468void MainWindow::makeChannel()
469 { 469 {
470 channel = new QCopChannel( "QPE/Application/oipkg", this ); 470 channel = new QCopChannel( "QPE/Application/oipkg", this );
471 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 471 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
472 this, SLOT(receive(const QCString&, const QByteArray&)) ); 472 this, SLOT(receive(const QCString&,const QByteArray&)) );
473} 473}
474 474
475 475
476 476
477void MainWindow::receive(const QCString &msg, const QByteArray &arg) 477void MainWindow::receive(const QCString &msg, const QByteArray &arg)
478{ 478{
479 pvDebug(3, "QCop "+msg+" "+QCString(arg)); 479 pvDebug(3, "QCop "+msg+" "+QCString(arg));
480 if ( msg == "installFile(QString)" ) 480 if ( msg == "installFile(QString)" )
481 { 481 {
482 ipkg->installFile( QString(arg) ); 482 ipkg->installFile( QString(arg) );
483 }else if( msg == "removeFile(QString)" ) 483 }else if( msg == "removeFile(QString)" )
484 { 484 {
485 ipkg->removeFile( QString(arg) ); 485 ipkg->removeFile( QString(arg) );
486 }else if( msg == "createLinks(QString)" ) 486 }else if( msg == "createLinks(QString)" )
487 { 487 {
488 ipkg->createLinks( QString(arg) ); 488 ipkg->createLinks( QString(arg) );
489 }else if( msg == "removeLinks(QString)" ) 489 }else if( msg == "removeLinks(QString)" )
490 { 490 {
491 ipkg->removeLinks( QString(arg) ); 491 ipkg->removeLinks( QString(arg) );
492 }else{ 492 }else{
493 pvDebug(2,"Huh what do ya want") 493 pvDebug(2,"Huh what do ya want")
494 } 494 }
495} 495}
496 496
497 497
498void MainWindow::createLinks() 498void MainWindow::createLinks()
499{ 499{
500 pvDebug(2,"creating links..."); 500 pvDebug(2,"creating links...");
501 ipkg->createLinks( settings->destinationurl->text() ); 501 ipkg->createLinks( settings->destinationurl->text() );
502} 502}
503 503
504void MainWindow::removeLinks() 504void MainWindow::removeLinks()
505{ 505{
506 pvDebug(2,"removing links..."); 506 pvDebug(2,"removing links...");
507 ipkg->removeLinks( settings->destinationurl->text() ); 507 ipkg->removeLinks( settings->destinationurl->text() );
508} 508}
509 509
510void MainWindow::remotePackageQuery() 510void MainWindow::remotePackageQuery()
511{ 511{
512 packageListSearch.query( searchEdit->text() ); 512 packageListSearch.query( searchEdit->text() );
513 packageListSearch.update(); 513 packageListSearch.update();
514 displayList(); 514 displayList();
515} 515}
diff --git a/noncore/unsupported/oipkg/packagelistitem.cpp b/noncore/unsupported/oipkg/packagelistitem.cpp
index 1610a37..1b4812d 100644
--- a/noncore/unsupported/oipkg/packagelistitem.cpp
+++ b/noncore/unsupported/oipkg/packagelistitem.cpp
@@ -1,240 +1,240 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9// (c) 2002 Patrick S. Vogt <tille@handhelds.org> 9// (c) 2002 Patrick S. Vogt <tille@handhelds.org>
10#include "packagelistitem.h" 10#include "packagelistitem.h"
11 11
12#include <qpe/resource.h> 12#include <qpe/resource.h>
13#include <qobject.h> 13#include <qobject.h>
14#include <qpopupmenu.h> 14#include <qpopupmenu.h>
15#include <qaction.h> 15#include <qaction.h>
16 16
17#include "debug.h" 17#include "debug.h"
18 18
19static QPixmap *pm_uninstalled=0; 19static QPixmap *pm_uninstalled=0;
20static QPixmap *pm_uninstalled_old=0; 20static QPixmap *pm_uninstalled_old=0;
21static QPixmap *pm_installed=0; 21static QPixmap *pm_installed=0;
22static QPixmap *pm_installed_old=0; 22static QPixmap *pm_installed_old=0;
23static QPixmap *pm_uninstall=0; 23static QPixmap *pm_uninstall=0;
24static QPixmap *pm_install=0; 24static QPixmap *pm_install=0;
25static QPixmap *pm_uninstalled_old_installed_new=0; 25static QPixmap *pm_uninstalled_old_installed_new=0;
26static QPixmap *pm_uninstalled_installed_old=0; 26static QPixmap *pm_uninstalled_installed_old=0;
27 27
28PackageListItem::PackageListItem(ListViewItemOipkg *parent, QString name, Type ittype) 28PackageListItem::PackageListItem(ListViewItemOipkg *parent, QString name, Type ittype)
29 : ListViewItemOipkg(parent,name,ittype) 29 : ListViewItemOipkg(parent,name,ittype)
30{ 30{
31 31
32} 32}
33 33
34PackageListItem::PackageListItem(QListView* lv, OipkgPackage *pi, PackageManagerSettings *s) 34PackageListItem::PackageListItem(QListView* lv, OipkgPackage *pi, PackageManagerSettings *s)
35 :ListViewItemOipkg(lv,pi->name(),ListViewItemOipkg::Package) 35 :ListViewItemOipkg(lv,pi->name(),ListViewItemOipkg::Package)
36{ 36{
37 init(pi,s); 37 init(pi,s);
38} 38}
39 39
40PackageListItem::PackageListItem(ListViewItemOipkg *lvi, OipkgPackage *pi, PackageManagerSettings *s) 40PackageListItem::PackageListItem(ListViewItemOipkg *lvi, OipkgPackage *pi, PackageManagerSettings *s)
41 :ListViewItemOipkg(lvi,pi->name(),ListViewItemOipkg::Package) 41 :ListViewItemOipkg(lvi,pi->name(),ListViewItemOipkg::Package)
42{ 42{
43 init(pi,s); 43 init(pi,s);
44} 44}
45PackageListItem::~PackageListItem() 45PackageListItem::~PackageListItem()
46{ 46{
47 delete popupMenu; 47 delete popupMenu;
48 delete destsMenu; 48 delete destsMenu;
49} 49}
50 50
51void PackageListItem::init( OipkgPackage *pi, PackageManagerSettings *s) 51void PackageListItem::init( OipkgPackage *pi, PackageManagerSettings *s)
52{ 52{
53 //waring pass something different than 0 53 //waring pass something different than 0
54 popupMenu = new QPopupMenu( 0 ); 54 popupMenu = new QPopupMenu( 0 );
55 destsMenu = new QPopupMenu( 0 ); 55 destsMenu = new QPopupMenu( 0 );
56 package = pi; 56 package = pi;
57 settings = s; 57 settings = s;
58 setExpandable( true ); 58 setExpandable( true );
59 ListViewItemOipkg *item; 59 ListViewItemOipkg *item;
60 nameItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute,"name" ); 60 nameItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute,"name" );
61 item = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, QObject::tr("Description: ")+pi->desc() ); 61 item = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, QObject::tr("Description: ")+pi->desc() );
62 item = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, QObject::tr("Size: ")+pi->size() ); 62 item = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, QObject::tr("Size: ")+pi->size() );
63 destItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, "dest" ); 63 destItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, "dest" );
64 linkItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, "link" ); 64 linkItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, "link" );
65 statusItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, "status" ); 65 statusItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, "status" );
66 ListViewItemOipkg *otherItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, QObject::tr("other") ); 66 ListViewItemOipkg *otherItem = new ListViewItemOipkg( this, ListViewItemOipkg::Attribute, QObject::tr("other") );
67 item = new ListViewItemOipkg( otherItem, ListViewItemOipkg::Attribute, QObject::tr("Install Name: ")+pi->installName() ); 67 item = new ListViewItemOipkg( otherItem, ListViewItemOipkg::Attribute, QObject::tr("Install Name: ")+pi->installName() );
68 QDict<QString> *fields = pi->getFields(); 68 QDict<QString> *fields = pi->getFields();
69 QDictIterator<QString> it( *fields ); 69 QDictIterator<QString> it( *fields );
70 while ( it.current() ) { 70 while ( it.current() ) {
71 item = new ListViewItemOipkg( otherItem, ListViewItemOipkg::Attribute, QString(it.currentKey()+": "+*it.current()) ); 71 item = new ListViewItemOipkg( otherItem, ListViewItemOipkg::Attribute, QString(it.currentKey()+": "+*it.current()) );
72 ++it; 72 ++it;
73 } 73 }
74 displayDetails(); 74 displayDetails();
75 75
76 if (!pm_uninstalled) 76 if (!pm_uninstalled)
77 { 77 {
78 pm_uninstalled = new QPixmap(Resource::loadPixmap("oipkg/uninstalled")); 78 pm_uninstalled = new QPixmap(Resource::loadPixmap("oipkg/uninstalled"));
79 pm_uninstalled_old = new QPixmap(Resource::loadPixmap("oipkg/uninstalledOld")); 79 pm_uninstalled_old = new QPixmap(Resource::loadPixmap("oipkg/uninstalledOld"));
80 pm_uninstalled_old_installed_new = new QPixmap(Resource::loadPixmap("oipkg/uninstalledOldinstalledNew")); 80 pm_uninstalled_old_installed_new = new QPixmap(Resource::loadPixmap("oipkg/uninstalledOldinstalledNew"));
81 pm_uninstalled_installed_old = new QPixmap(Resource::loadPixmap("oipkg/uninstalledInstalledOld")); 81 pm_uninstalled_installed_old = new QPixmap(Resource::loadPixmap("oipkg/uninstalledInstalledOld"));
82 pm_installed = new QPixmap(Resource::loadPixmap("oipkg/installed")); 82 pm_installed = new QPixmap(Resource::loadPixmap("oipkg/installed"));
83 pm_installed_old = new QPixmap(Resource::loadPixmap("oipkg/installedOld")); 83 pm_installed_old = new QPixmap(Resource::loadPixmap("oipkg/installedOld"));
84 pm_install = new QPixmap(Resource::loadPixmap("oipkg/install")); 84 pm_install = new QPixmap(Resource::loadPixmap("oipkg/install"));
85 pm_uninstall = new QPixmap(Resource::loadPixmap("oipkg/uninstall")); 85 pm_uninstall = new QPixmap(Resource::loadPixmap("oipkg/uninstall"));
86 } 86 }
87} 87}
88 88
89void PackageListItem::paintCell( QPainter *p, const QColorGroup & cg, 89void PackageListItem::paintCell( QPainter *p, const QColorGroup & cg,
90 int column, int width, int alignment ) 90 int column, int width, int alignment )
91{ 91{
92 if ( !p ) 92 if ( !p )
93 return; 93 return;
94 94
95 p->fillRect( 0, 0, width, height(), 95 p->fillRect( 0, 0, width, height(),
96 isSelected()? cg.highlight() : cg.base() ); 96 isSelected()? cg.highlight() : cg.base() );
97 97
98 if ( column != 0 ) { 98 if ( column != 0 ) {
99 // The rest is text 99 // The rest is text
100 QListViewItem::paintCell( p, cg, column, width, alignment ); 100 QListViewItem::paintCell( p, cg, column, width, alignment );
101 return; 101 return;
102 } 102 }
103 103
104 QListView *lv = listView(); 104 QListView *lv = listView();
105 if ( !lv ) 105 if ( !lv )
106 return; 106 return;
107 int marg = lv->itemMargin(); 107 int marg = lv->itemMargin();
108 int r = marg; 108 int r = marg;
109 109
110 QPixmap pm = statePixmap(); 110 QPixmap pm = statePixmap();
111 p->drawPixmap(marg,(height()-pm.height())/2,pm); 111 p->drawPixmap(marg,(height()-pm.height())/2,pm);
112 r += pm.width()+1; 112 r += pm.width()+1;
113 113
114 p->translate( r, 0 ); 114 p->translate( r, 0 );
115 QListViewItem::paintCell( p, cg, column, width - r, alignment ); 115 QListViewItem::paintCell( p, cg, column, width - r, alignment );
116} 116}
117 117
118 118
119void PackageListItem::paintFocus( QPainter *p, const QColorGroup & cg, 119void PackageListItem::paintFocus( QPainter *p, const QColorGroup & cg,
120 const QRect & r ) 120 const QRect & r )
121{ 121{
122 // Skip QCheckListItem 122 // Skip QCheckListItem
123 // (makes you wonder what we're getting from QCheckListItem) 123 // (makes you wonder what we're getting from QCheckListItem)
124 QListViewItem::paintFocus(p,cg,r); 124 QListViewItem::paintFocus(p,cg,r);
125} 125}
126 126
127QPixmap PackageListItem::statePixmap() const 127QPixmap PackageListItem::statePixmap() const
128{ 128{
129 bool installed = package->installed(); 129 bool installed = package->installed();
130 bool old = package->isOld(); 130 bool old = package->isOld();
131 bool verinstalled = package->otherInstalled(); 131 bool verinstalled = package->otherInstalled();
132 if ( !package->toProcess() ) { 132 if ( !package->toProcess() ) {
133 if ( !installed ) 133 if ( !installed )
134 if (old) 134 if (old)
135 { 135 {
136 if (verinstalled) return *pm_uninstalled_old_installed_new; 136 if (verinstalled) return *pm_uninstalled_old_installed_new;
137 else return *pm_uninstalled_old; 137 else return *pm_uninstalled_old;
138 } 138 }
139 else 139 else
140 { 140 {
141 if (verinstalled) return *pm_uninstalled_installed_old; 141 if (verinstalled) return *pm_uninstalled_installed_old;
142 else return *pm_uninstalled; 142 else return *pm_uninstalled;
143 } 143 }
144 else 144 else
145 if (old) return *pm_installed_old; 145 if (old) return *pm_installed_old;
146 else return *pm_installed; 146 else return *pm_installed;
147 } else { //toProcess() == true 147 } else { //toProcess() == true
148 if ( !installed ) 148 if ( !installed )
149 return *pm_install; 149 return *pm_install;
150 else 150 else
151 return *pm_uninstall; 151 return *pm_uninstall;
152 } 152 }
153} 153}
154 154
155QString PackageListItem::key( int column, bool ascending ) const 155QString PackageListItem::key( int column, bool ascending ) const
156{ 156{
157 if ( column == 2 ) { 157 if ( column == 2 ) {
158 QString t = text(2); 158 QString t = text(2);
159 double bytes=t.toDouble(); 159 double bytes=t.toDouble();
160 if ( t.contains('M') ) bytes*=1024*1024; 160 if ( t.contains('M') ) bytes*=1024*1024;
161 else if ( t.contains('K') || t.contains('k') ) bytes*=1024; 161 else if ( t.contains('K') || t.contains('k') ) bytes*=1024;
162 if ( !ascending ) bytes=999999999-bytes; 162 if ( !ascending ) bytes=999999999-bytes;
163 return QString().sprintf("%09d",(int)bytes); 163 return QString().sprintf("%09d",(int)bytes);
164 } else { 164 } else {
165 return QListViewItem::key(column,ascending); 165 return QListViewItem::key(column,ascending);
166 } 166 }
167} 167}
168 168
169void PackageListItem::setOn( bool b ) 169void PackageListItem::setOn( bool b )
170{ 170{
171 QCheckListItem::setOn( b ); 171 QCheckListItem::setOn( b );
172 package->toggleProcess(); 172 package->toggleProcess();
173 package->setLink( settings->createLinks() ); 173 package->setLink( settings->createLinks() );
174 displayDetails(); 174 displayDetails();
175} 175}
176 176
177void PackageListItem::displayDetails() 177void PackageListItem::displayDetails()
178{ 178{
179 QString sod; 179 QString sod;
180 sod += package->sizeUnits().isEmpty()?QString(""):QString(package->sizeUnits()); 180 sod += package->sizeUnits().isEmpty()?QString(""):QString(package->sizeUnits());
181 //sod += QString(package->dest().isEmpty()?"":QObject::tr(" on ")+package->dest()); 181 //sod += QString(package->dest().isEmpty()?"":QObject::tr(" on ")+package->dest());
182 sod += package->dest().isEmpty()?QString(""):QString(QObject::tr(" on ")+package->dest()); 182 sod += package->dest().isEmpty()?QString(""):QString(QObject::tr(" on ")+package->dest());
183 sod = sod.isEmpty()?QString(""):QString(" ("+sod+")"); 183 sod = sod.isEmpty()?QString(""):QString(" ("+sod+")");
184 setText(0, package->name()+sod ); 184 setText(0, package->name()+sod );
185 nameItem->setText( 0, QObject::tr("Name: ")+package->name()); 185 nameItem->setText( 0, QObject::tr("Name: ")+package->name());
186 linkItem->setText( 0, QObject::tr("Link: ")+(package->link()?QObject::tr("Yes"):QObject::tr("No"))); 186 linkItem->setText( 0, QObject::tr("Link: ")+(package->link()?QObject::tr("Yes"):QObject::tr("No")));
187 destItem->setText( 0, QObject::tr("Destination: ")+package->dest() ); 187 destItem->setText( 0, QObject::tr("Destination: ")+package->dest() );
188 statusItem->setText( 0, QObject::tr("Status: ")+package->status() ); 188 statusItem->setText( 0, QObject::tr("Status: ")+package->status() );
189 repaint(); 189 repaint();
190} 190}
191 191
192QPopupMenu* PackageListItem::getPopupMenu() 192QPopupMenu* PackageListItem::getPopupMenu()
193{ 193{
194 popupMenu->clear(); 194 popupMenu->clear();
195 destsMenu->clear(); 195 destsMenu->clear();
196 196
197 QAction *popupAction; 197 QAction *popupAction;
198 qDebug("PackageListItem::showPopup "); 198 qDebug("PackageListItem::showPopup ");
199 199
200 if (!package->installed()){ 200 if (!package->installed()){
201 popupMenu->insertItem( QObject::tr("Install to"), destsMenu ); 201 popupMenu->insertItem( QObject::tr("Install to"), destsMenu );
202 QStringList dests = settings->getDestinationNames(); 202 QStringList dests = settings->getDestinationNames();
203 QString ad = settings->getDestinationName(); 203 QString ad = settings->getDestinationName();
204 for (uint i = 0; i < dests.count(); i++ ) 204 for (uint i = 0; i < dests.count(); i++ )
205 { 205 {
206 popupAction = new QAction( dests[i], QString::null, 0, popupMenu, 0 ); 206 popupAction = new QAction( dests[i], QString::null, 0, popupMenu, 0 );
207 popupAction->addTo( destsMenu ); 207 popupAction->addTo( destsMenu );
208 if ( dests[i] == ad && getPackage()->toInstall() ) 208 if ( dests[i] == ad && getPackage()->toInstall() )
209 { 209 {
210 popupAction->setToggleAction( true ); 210 popupAction->setToggleAction( true );
211 popupAction->setOn(true); 211 popupAction->setOn(true);
212 } 212 }
213 } 213 }
214 connect( destsMenu, SIGNAL( activated( int ) ), 214 connect( destsMenu, SIGNAL( activated(int) ),
215 this, SLOT( menuAction( int ) ) ); 215 this, SLOT( menuAction(int) ) );
216 popupMenu->popup( QCursor::pos() ); 216 popupMenu->popup( QCursor::pos() );
217 }else{ 217 }else{
218 popupMenu->insertItem( QObject::tr("Remove")); 218 popupMenu->insertItem( QObject::tr("Remove"));
219 connect( popupMenu, SIGNAL( activated( int ) ), 219 connect( popupMenu, SIGNAL( activated(int) ),
220 this, SLOT( menuAction( int ) ) ); 220 this, SLOT( menuAction(int) ) );
221 popupMenu->popup( QCursor::pos() ); 221 popupMenu->popup( QCursor::pos() );
222 } 222 }
223 return popupMenu; 223 return popupMenu;
224} 224}
225 225
226void PackageListItem::menuAction( int i ) 226void PackageListItem::menuAction( int i )
227{ 227{
228 if (!package->installed()){ 228 if (!package->installed()){
229 package->setDest( destsMenu->text(i) ); 229 package->setDest( destsMenu->text(i) );
230 package->setLink( settings->createLinks() ); 230 package->setLink( settings->createLinks() );
231 } 231 }
232 package->setOn(); 232 package->setOn();
233 displayDetails(); 233 displayDetails();
234} 234}
235 235
236//void PackageListItem::toggleProcess() 236//void PackageListItem::toggleProcess()
237//{ 237//{
238// package->toggleProcess() ; 238// package->toggleProcess() ;
239// displayDetails(); 239// displayDetails();
240//} 240//}
diff --git a/noncore/unsupported/oipkg/packagelistview.cpp b/noncore/unsupported/oipkg/packagelistview.cpp
index 3c7435d..98ebf88 100644
--- a/noncore/unsupported/oipkg/packagelistview.cpp
+++ b/noncore/unsupported/oipkg/packagelistview.cpp
@@ -1,118 +1,118 @@
1/*************************************************************************** 1/***************************************************************************
2 * * 2 * *
3 * This program is free software; you can redistribute it and/or modify * 3 * This program is free software; you can redistribute it and/or modify *
4 * it under the terms of the GNU General Public License as published by * 4 * it under the terms of the GNU General Public License as published by *
5 * the Free Software Foundation; either version 2 of the License, or * 5 * the Free Software Foundation; either version 2 of the License, or *
6 * (at your option) any later version. * 6 * (at your option) any later version. *
7 * * 7 * *
8 ***************************************************************************/ 8 ***************************************************************************/
9// (c) 2002 Patrick S. Vogt <tille@handhelds.org> 9// (c) 2002 Patrick S. Vogt <tille@handhelds.org>
10#include "packagelistview.h" 10#include "packagelistview.h"
11 11
12#include <qpopupmenu.h> 12#include <qpopupmenu.h>
13#include <qaction.h> 13#include <qaction.h>
14 14
15#include "listviewitemoipkg.h" 15#include "listviewitemoipkg.h"
16#include "packagelistitem.h" 16#include "packagelistitem.h"
17#include "pksettings.h" 17#include "pksettings.h"
18 18
19PackageListView::PackageListView(QWidget *p, const char* n, PackageManagerSettings *s) 19PackageListView::PackageListView(QWidget *p, const char* n, PackageManagerSettings *s)
20 : QListView(p,n) 20 : QListView(p,n)
21{ 21{
22 settings = s; 22 settings = s;
23 popupTimer = new QTimer( this ); 23 popupTimer = new QTimer( this );
24 setSelectionMode(QListView::NoSelection); 24 setSelectionMode(QListView::NoSelection);
25 addColumn( tr("Package") ); 25 addColumn( tr("Package") );
26 setRootIsDecorated( true ); 26 setRootIsDecorated( true );
27 27
28 connect( popupTimer, SIGNAL(timeout()), 28 connect( popupTimer, SIGNAL(timeout()),
29 this, SLOT(showPopup()) ); 29 this, SLOT(showPopup()) );
30 connect( this, SIGNAL( pressed( QListViewItem* ) ), 30 connect( this, SIGNAL( pressed(QListViewItem*) ),
31 this, SLOT( setCurrent( QListViewItem* ) ) ); 31 this, SLOT( setCurrent(QListViewItem*) ) );
32 connect( this, SIGNAL( clicked( QListViewItem* ) ), 32 connect( this, SIGNAL( clicked(QListViewItem*) ),
33 this, SLOT( stopTimer( QListViewItem* ) ) ); 33 this, SLOT( stopTimer(QListViewItem*) ) );
34 34
35} 35}
36 36
37//PackageListView::~PackageListView() 37//PackageListView::~PackageListView()
38//{ 38//{
39//} 39//}
40 40
41void PackageListView::setCurrent( QListViewItem* p ) 41void PackageListView::setCurrent( QListViewItem* p )
42{ 42{
43 qDebug("PackageListView::setCurrent "); 43 qDebug("PackageListView::setCurrent ");
44 activeItem = (ListViewItemOipkg*)p; 44 activeItem = (ListViewItemOipkg*)p;
45 45
46 if ( activeItem != 0 ) popupTimer->start( 750, true ); 46 if ( activeItem != 0 ) popupTimer->start( 750, true );
47 47
48// if ( activeItem->getType() != ListViewItemOipkg::Package ){ 48// if ( activeItem->getType() != ListViewItemOipkg::Package ){
49// qDebug("PackageListView::setCurrent !p "); 49// qDebug("PackageListView::setCurrent !p ");
50// activePackage = 0; 50// activePackage = 0;
51 // activePackageListItem = 0; 51 // activePackageListItem = 0;
52// qDebug("PackageListView::setCurrent returning "); 52// qDebug("PackageListView::setCurrent returning ");
53// return; 53// return;
54// }; 54// };
55// activePackageListItem = (PackageListItem*)p; 55// activePackageListItem = (PackageListItem*)p;
56// activePackage = activePackageListItem->getPackage(); 56// activePackage = activePackageListItem->getPackage();
57// if (activePackage == 0 ) 57// if (activePackage == 0 )
58// { 58// {
59// qDebug("PackageListView::setCurrent if (!activePackage)"); 59// qDebug("PackageListView::setCurrent if (!activePackage)");
60// return; 60// return;
61// } 61// }
62 62
63 63
64 qDebug("PackageListView::setCurrent popupTimer->start"); 64 qDebug("PackageListView::setCurrent popupTimer->start");
65} 65}
66 66
67 67
68void PackageListView::showPopup() 68void PackageListView::showPopup()
69{ 69{
70 qDebug("PackageListView::showPopup"); 70 qDebug("PackageListView::showPopup");
71 QPopupMenu *popup = activeItem->getPopupMenu(); 71 QPopupMenu *popup = activeItem->getPopupMenu();
72 if (popup == 0) return; 72 if (popup == 0) return;
73 popup->popup( QCursor::pos() ); 73 popup->popup( QCursor::pos() );
74 qDebug("PackageListView::showPopup"); 74 qDebug("PackageListView::showPopup");
75} 75}
76 76
77void PackageListView::stopTimer( QListViewItem* ) 77void PackageListView::stopTimer( QListViewItem* )
78{ 78{
79 popupTimer->stop(); 79 popupTimer->stop();
80} 80}
81 81
82 82
83void PackageListView::display() 83void PackageListView::display()
84{ 84{
85 QDictIterator<PackageList> list( PackageLists ); 85 QDictIterator<PackageList> list( PackageLists );
86 PackageList *packlist; 86 PackageList *packlist;
87 OipkgPackage *pack; 87 OipkgPackage *pack;
88 PackageListItem *item; 88 PackageListItem *item;
89 ListViewItemOipkg *rootItem; 89 ListViewItemOipkg *rootItem;
90 QListViewItem* it; 90 QListViewItem* it;
91 QListViewItem* itdel; 91 QListViewItem* itdel;
92 while ( list.current() ) { 92 while ( list.current() ) {
93 packlist = list.current(); 93 packlist = list.current();
94 rootItem = rootItems.find( list.currentKey() ); 94 rootItem = rootItems.find( list.currentKey() );
95 //rootItem->clear(); 95 //rootItem->clear();
96 it=rootItem->firstChild(); 96 it=rootItem->firstChild();
97 while ( it ) 97 while ( it )
98 { 98 {
99 itdel = it; 99 itdel = it;
100 it = it->nextSibling(); 100 it = it->nextSibling();
101 delete itdel; 101 delete itdel;
102 } 102 }
103 pack = packlist->first(); 103 pack = packlist->first();
104 while( pack ) 104 while( pack )
105 { 105 {
106 item = new PackageListItem( rootItem, pack, settings ); 106 item = new PackageListItem( rootItem, pack, settings );
107 pack = packlist->next(); 107 pack = packlist->next();
108 } 108 }
109 ++list; 109 ++list;
110 } 110 }
111} 111}
112 112
113void PackageListView::addList( QString n, PackageList* pl) 113void PackageListView::addList( QString n, PackageList* pl)
114{ 114{
115 PackageLists.insert(n, pl); 115 PackageLists.insert(n, pl);
116 ListViewItemOipkg *item = new ListViewItemOipkg(this,n,ListViewItemOipkg::Feed); 116 ListViewItemOipkg *item = new ListViewItemOipkg(this,n,ListViewItemOipkg::Feed);
117 rootItems.insert(n, item); 117 rootItems.insert(n, item);
118} 118}
diff --git a/noncore/unsupported/oipkg/pksettings.cpp b/noncore/unsupported/oipkg/pksettings.cpp
index 063b018..aac011e 100644
--- a/noncore/unsupported/oipkg/pksettings.cpp
+++ b/noncore/unsupported/oipkg/pksettings.cpp
@@ -1,575 +1,575 @@
1#include "pksettings.h" 1#include "pksettings.h"
2 2
3#include <qpe/process.h> 3#include <qpe/process.h>
4#include <qpe/resource.h> 4#include <qpe/resource.h>
5#include <qpe/stringutil.h> 5#include <qpe/stringutil.h>
6#include <qpe/qpeapplication.h> 6#include <qpe/qpeapplication.h>
7#include <qpe/qcopenvelope_qws.h> 7#include <qpe/qcopenvelope_qws.h>
8#include <qpe/applnk.h> 8#include <qpe/applnk.h>
9#include <qpe/config.h> 9#include <qpe/config.h>
10 10
11#include <qprogressbar.h> 11#include <qprogressbar.h>
12#include <qcombobox.h> 12#include <qcombobox.h>
13#include <qdict.h> 13#include <qdict.h>
14#include <qfile.h> 14#include <qfile.h>
15#include <qlineedit.h> 15#include <qlineedit.h>
16#include <qpushbutton.h> 16#include <qpushbutton.h>
17#include <qlistview.h> 17#include <qlistview.h>
18#include <qlistbox.h> 18#include <qlistbox.h>
19#include <qcheckbox.h> 19#include <qcheckbox.h>
20#include <qmessagebox.h> 20#include <qmessagebox.h>
21#include <qpainter.h> 21#include <qpainter.h>
22#include <qpixmap.h> 22#include <qpixmap.h>
23#include <qregexp.h> 23#include <qregexp.h>
24#include <qstring.h> 24#include <qstring.h>
25#include <qobject.h> 25#include <qobject.h>
26#include <qtextstream.h> 26#include <qtextstream.h>
27#include <qtextview.h> 27#include <qtextview.h>
28#include <qtoolbutton.h> 28#include <qtoolbutton.h>
29#include <qtabwidget.h> 29#include <qtabwidget.h>
30 30
31#include <stdlib.h> 31#include <stdlib.h>
32#include <unistd.h> 32#include <unistd.h>
33#include "debug.h" 33#include "debug.h"
34//#include "utils.h" 34//#include "utils.h"
35 35
36PackageManagerSettings::PackageManagerSettings( QWidget* parent, const char* name, WFlags fl ) 36PackageManagerSettings::PackageManagerSettings( QWidget* parent, const char* name, WFlags fl )
37 : PackageManagerSettingsBase( parent, name, fl ) 37 : PackageManagerSettingsBase( parent, name, fl )
38{ 38{
39 connect( newserver, SIGNAL(clicked()), this, SLOT(newServer()) ); 39 connect( newserver, SIGNAL(clicked()), this, SLOT(newServer()) );
40 connect( removeserver, SIGNAL(clicked()), this, SLOT(removeServer()) ); 40 connect( removeserver, SIGNAL(clicked()), this, SLOT(removeServer()) );
41 connect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) ); 41 connect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) );
42 connect( newdestination, SIGNAL(clicked()), this, SLOT(newDestination()) ); 42 connect( newdestination, SIGNAL(clicked()), this, SLOT(newDestination()) );
43 connect( removedestination, SIGNAL(clicked()), this, SLOT(removeDestination()) ); 43 connect( removedestination, SIGNAL(clicked()), this, SLOT(removeDestination()) );
44 connect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) ); 44 connect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) );
45 // connect( CheckBoxLink, SIGNAL(toggled(bool)), 45 // connect( CheckBoxLink, SIGNAL(toggled(bool)),
46 // activeLinkDestination, SLOT(setEnabled(bool)) ); 46 // activeLinkDestination, SLOT(setEnabled(bool)) );
47 47
48// connect( settingName, SIGNAL(activated(int)), this, SLOT(installationSettingChange(int)) ); 48// connect( settingName, SIGNAL(activated(int)), this, SLOT(installationSettingChange(int)) );
49// connect( settingName, SIGNAL(textChanged(const QString &)), this, SLOT(installationSettingSetName(const QString &)) ); 49// connect( settingName, SIGNAL(textChanged(const QString&)), this, SLOT(installationSettingSetName(const QString&)) );
50// connect( newsetting, SIGNAL(clicked()), this, SLOT(newInstallationSetting()) ); 50// connect( newsetting, SIGNAL(clicked()), this, SLOT(newInstallationSetting()) );
51// connect( renamesetting, SIGNAL(clicked()), this, SLOT(renameInstallationSetting()) ); 51// connect( renamesetting, SIGNAL(clicked()), this, SLOT(renameInstallationSetting()) );
52 // connect( removesetting, SIGNAL(clicked()), this, SLOT(removeInstallationSetting()) ); 52 // connect( removesetting, SIGNAL(clicked()), this, SLOT(removeInstallationSetting()) );
53 servername->setEnabled(FALSE); 53 servername->setEnabled(FALSE);
54 serverurl->setEnabled(FALSE); 54 serverurl->setEnabled(FALSE);
55 serverurlDic.setAutoDelete(TRUE); 55 serverurlDic.setAutoDelete(TRUE);
56 destinationname->setEnabled(FALSE); 56 destinationname->setEnabled(FALSE);
57 destinationurl->setEnabled(FALSE); 57 destinationurl->setEnabled(FALSE);
58 destinationurlDic.setAutoDelete(TRUE); 58 destinationurlDic.setAutoDelete(TRUE);
59 readSettings(); 59 readSettings();
60 activeLinkDestination->hide(); 60 activeLinkDestination->hide();
61 serverChanged = false; 61 serverChanged = false;
62 62
63 // get rid of setups 63 // get rid of setups
64// Settings->hide(); 64// Settings->hide();
65// settingName->hide(); 65// settingName->hide();
66// newsetting->hide(); 66// newsetting->hide();
67// renamesetting->hide(); 67// renamesetting->hide();
68// removesetting->hide(); 68// removesetting->hide();
69} 69}
70 70
71PackageManagerSettings::~PackageManagerSettings() 71PackageManagerSettings::~PackageManagerSettings()
72{ 72{
73} 73}
74 74
75 75
76void PackageManagerSettings::newServer() 76void PackageManagerSettings::newServer()
77{ 77{
78 int i = servers->count(); 78 int i = servers->count();
79 if ( servername->isEnabled() || serverurl->text().isEmpty() ) { 79 if ( servername->isEnabled() || serverurl->text().isEmpty() ) {
80 serverurlDic.insert(i,new QString("http://")); 80 serverurlDic.insert(i,new QString("http://"));
81 servers->insertItem(tr("New")); 81 servers->insertItem(tr("New"));
82 activeServers->insertItem(tr("New")); 82 activeServers->insertItem(tr("New"));
83 } else { 83 } else {
84 // allows one-level undo 84 // allows one-level undo
85 serverurlDic.insert(i,new QString(serverurl->text())); 85 serverurlDic.insert(i,new QString(serverurl->text()));
86 servers->insertItem(servername->text()); 86 servers->insertItem(servername->text());
87 activeServers->insertItem(servername->text()); 87 activeServers->insertItem(servername->text());
88 } 88 }
89 changed = true; 89 changed = true;
90 servers->setSelected(i,TRUE); 90 servers->setSelected(i,TRUE);
91 editServer(i); 91 editServer(i);
92 changed = true; 92 changed = true;
93} 93}
94 94
95void PackageManagerSettings::newDestination() 95void PackageManagerSettings::newDestination()
96{ 96{
97 int i = destinations->count(); 97 int i = destinations->count();
98 if ( destinationname->isEnabled() || destinationurl->text().isEmpty() ) { 98 if ( destinationname->isEnabled() || destinationurl->text().isEmpty() ) {
99 destinationurlDic.insert(i,new QString("/")); 99 destinationurlDic.insert(i,new QString("/"));
100 destinations->insertItem(tr("New")); 100 destinations->insertItem(tr("New"));
101 activeDestination->insertItem(tr("New")); 101 activeDestination->insertItem(tr("New"));
102 activeLinkDestination->insertItem(tr("New")); 102 activeLinkDestination->insertItem(tr("New"));
103 } else { 103 } else {
104 // allows one-level undo 104 // allows one-level undo
105 destinationurlDic.insert(i,new QString(destinationurl->text())); 105 destinationurlDic.insert(i,new QString(destinationurl->text()));
106 destinations->insertItem(destinationname->text()); 106 destinations->insertItem(destinationname->text());
107 activeDestination->insertItem(destinationname->text()); 107 activeDestination->insertItem(destinationname->text());
108 activeLinkDestination->insertItem(destinationname->text()); 108 activeLinkDestination->insertItem(destinationname->text());
109 } 109 }
110 destinations->setSelected(i,TRUE); 110 destinations->setSelected(i,TRUE);
111 editDestination(i); 111 editDestination(i);
112 changed = true; 112 changed = true;
113} 113}
114 114
115 115
116void PackageManagerSettings::editServer(int i) 116void PackageManagerSettings::editServer(int i)
117{ 117{
118 if ( servername->isEnabled() ) { 118 if ( servername->isEnabled() ) {
119 disconnect( servername, SIGNAL(textChanged(const QString&)), this, SLOT(serverNameChanged(const QString&)) ); 119 disconnect( servername, SIGNAL(textChanged(const QString&)), this, SLOT(serverNameChanged(const QString&)) );
120 disconnect( serverurl, SIGNAL(textChanged(const QString&)), this, SLOT(serverUrlChanged(const QString&)) ); 120 disconnect( serverurl, SIGNAL(textChanged(const QString&)), this, SLOT(serverUrlChanged(const QString&)) );
121 } else { 121 } else {
122 servername->setEnabled(TRUE); 122 servername->setEnabled(TRUE);
123 serverurl->setEnabled(TRUE); 123 serverurl->setEnabled(TRUE);
124 } 124 }
125 125
126 servername->setText( servers->text(i) ); 126 servername->setText( servers->text(i) );
127 serverurl->setText( *serverurlDic[i] ); 127 serverurl->setText( *serverurlDic[i] );
128 128
129 editedserver = i; 129 editedserver = i;
130 serverChanged = true; 130 serverChanged = true;
131 connect( servername, SIGNAL(textChanged(const QString&)), this, SLOT(serverNameChanged(const QString&)) ); 131 connect( servername, SIGNAL(textChanged(const QString&)), this, SLOT(serverNameChanged(const QString&)) );
132 connect( serverurl, SIGNAL(textChanged(const QString&)), this, SLOT(serverUrlChanged(const QString&)) ); 132 connect( serverurl, SIGNAL(textChanged(const QString&)), this, SLOT(serverUrlChanged(const QString&)) );
133 changed = true; 133 changed = true;
134} 134}
135 135
136 136
137void PackageManagerSettings::editDestination(int i) 137void PackageManagerSettings::editDestination(int i)
138{ 138{
139 if ( destinationname->isEnabled() ) { 139 if ( destinationname->isEnabled() ) {
140 disconnect( destinationname, SIGNAL(textChanged(const QString&)), this, SLOT(destNameChanged(const QString&)) ); 140 disconnect( destinationname, SIGNAL(textChanged(const QString&)), this, SLOT(destNameChanged(const QString&)) );
141 disconnect( destinationurl, SIGNAL(textChanged(const QString&)), this, SLOT(destUrlChanged(const QString&)) ); 141 disconnect( destinationurl, SIGNAL(textChanged(const QString&)), this, SLOT(destUrlChanged(const QString&)) );
142 } else { 142 } else {
143 destinationname->setEnabled(TRUE); 143 destinationname->setEnabled(TRUE);
144 destinationurl->setEnabled(TRUE); 144 destinationurl->setEnabled(TRUE);
145 //since it does not work anyway 145 //since it does not work anyway
146// createLinksButton->setEnabled(TRUE); 146// createLinksButton->setEnabled(TRUE);
147// removeLinksButton->setEnabled(TRUE); 147// removeLinksButton->setEnabled(TRUE);
148 } 148 }
149 149
150 destinationname->setText( destinations->text(i) ); 150 destinationname->setText( destinations->text(i) );
151 destinationurl->setText( *destinationurlDic[i] ); 151 destinationurl->setText( *destinationurlDic[i] );
152 152
153 editeddestination = i; 153 editeddestination = i;
154 154
155 connect( destinationname, SIGNAL(textChanged(const QString&)), this, SLOT(destNameChanged(const QString&)) ); 155 connect( destinationname, SIGNAL(textChanged(const QString&)), this, SLOT(destNameChanged(const QString&)) );
156 connect( destinationurl, SIGNAL(textChanged(const QString&)), this, SLOT(destUrlChanged(const QString&)) ); 156 connect( destinationurl, SIGNAL(textChanged(const QString&)), this, SLOT(destUrlChanged(const QString&)) );
157 changed = true; 157 changed = true;
158} 158}
159 159
160void PackageManagerSettings::removeServer() 160void PackageManagerSettings::removeServer()
161{ 161{
162 disconnect( servername, SIGNAL(textChanged(const QString&)), this, SLOT(serverNameChanged(const QString&)) ); 162 disconnect( servername, SIGNAL(textChanged(const QString&)), this, SLOT(serverNameChanged(const QString&)) );
163 disconnect( serverurl, SIGNAL(textChanged(const QString&)), this, SLOT(serverUrlChanged(const QString&)) ); 163 disconnect( serverurl, SIGNAL(textChanged(const QString&)), this, SLOT(serverUrlChanged(const QString&)) );
164 servername->setText(servers->text(editedserver)); 164 servername->setText(servers->text(editedserver));
165 serverurl->setText(*serverurlDic[editedserver]); 165 serverurl->setText(*serverurlDic[editedserver]);
166 disconnect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) ); 166 disconnect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) );
167 servers->removeItem(editedserver); 167 servers->removeItem(editedserver);
168 activeServers->removeItem(editedserver); 168 activeServers->removeItem(editedserver);
169 connect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) ); 169 connect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) );
170 servername->setEnabled(FALSE); 170 servername->setEnabled(FALSE);
171 serverurl->setEnabled(FALSE); 171 serverurl->setEnabled(FALSE);
172 changed = true; 172 changed = true;
173} 173}
174 174
175void PackageManagerSettings::removeDestination() 175void PackageManagerSettings::removeDestination()
176{ 176{
177 disconnect( destinationname, SIGNAL(textChanged(const QString&)), this, SLOT(destNameChanged(const QString&)) ); 177 disconnect( destinationname, SIGNAL(textChanged(const QString&)), this, SLOT(destNameChanged(const QString&)) );
178 disconnect( destinationurl, SIGNAL(textChanged(const QString&)), this, SLOT(destUrlChanged(const QString&)) ); 178 disconnect( destinationurl, SIGNAL(textChanged(const QString&)), this, SLOT(destUrlChanged(const QString&)) );
179 destinationname->setText(""); 179 destinationname->setText("");
180 destinationurl->setText(""); 180 destinationurl->setText("");
181 disconnect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) ); 181 disconnect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) );
182 destinations->removeItem(editeddestination); 182 destinations->removeItem(editeddestination);
183 activeDestination->removeItem(editeddestination); 183 activeDestination->removeItem(editeddestination);
184 activeLinkDestination->removeItem(editeddestination); 184 activeLinkDestination->removeItem(editeddestination);
185 editeddestination=0; 185 editeddestination=0;
186 connect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) ); 186 connect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) );
187 destinationname->setEnabled(FALSE); 187 destinationname->setEnabled(FALSE);
188 destinationurl->setEnabled(FALSE); 188 destinationurl->setEnabled(FALSE);
189 changed = true; 189 changed = true;
190} 190}
191 191
192void PackageManagerSettings::serverNameChanged(const QString& t) 192void PackageManagerSettings::serverNameChanged(const QString& t)
193{ 193{
194 disconnect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) ); 194 disconnect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) );
195 servers->changeItem( t, editedserver ); 195 servers->changeItem( t, editedserver );
196 activeServers->changeItem( t, editedserver ); 196 activeServers->changeItem( t, editedserver );
197 connect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) ); 197 connect( servers, SIGNAL(highlighted(int)), this, SLOT(editServer(int)) );
198 changed = true; 198 changed = true;
199 serverChanged = true; 199 serverChanged = true;
200} 200}
201 201
202void PackageManagerSettings::destNameChanged(const QString& t) 202void PackageManagerSettings::destNameChanged(const QString& t)
203{ 203{
204 disconnect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) ); 204 disconnect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) );
205 destinations->changeItem( t, editeddestination ); 205 destinations->changeItem( t, editeddestination );
206 activeDestination->changeItem( t, editeddestination ); 206 activeDestination->changeItem( t, editeddestination );
207 activeLinkDestination->changeItem( t, editeddestination ); 207 activeLinkDestination->changeItem( t, editeddestination );
208 connect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) ); 208 connect( destinations, SIGNAL(highlighted(int)), this, SLOT(editDestination(int)) );
209 changed = true; 209 changed = true;
210} 210}
211 211
212void PackageManagerSettings::serverUrlChanged(const QString& t) 212void PackageManagerSettings::serverUrlChanged(const QString& t)
213{ 213{
214 serverurlDic.replace(editedserver, new QString(t)); 214 serverurlDic.replace(editedserver, new QString(t));
215 changed = true; 215 changed = true;
216 serverChanged = true; 216 serverChanged = true;
217} 217}
218 218
219void PackageManagerSettings::destUrlChanged(const QString& t) 219void PackageManagerSettings::destUrlChanged(const QString& t)
220{ 220{
221 destinationurlDic.replace(editeddestination, new QString(t)); 221 destinationurlDic.replace(editeddestination, new QString(t));
222 changed = true; 222 changed = true;
223} 223}
224 224
225void PackageManagerSettings::writeIpkgConfig(const QString& conffile) 225void PackageManagerSettings::writeIpkgConfig(const QString& conffile)
226{ 226{
227 QFile conf(conffile); 227 QFile conf(conffile);
228 if ( ! conf.open(IO_WriteOnly) ) return; 228 if ( ! conf.open(IO_WriteOnly) ) return;
229 QTextStream s(&conf); 229 QTextStream s(&conf);
230 s << "# Written by oipkg -- the opie package manager\n"; 230 s << "# Written by oipkg -- the opie package manager\n";
231 for (int i=0; i<(int)activeServers->count(); i++) 231 for (int i=0; i<(int)activeServers->count(); i++)
232 { 232 {
233 QString url = serverurlDic[i] ? *serverurlDic[i] : QString("???"); 233 QString url = serverurlDic[i] ? *serverurlDic[i] : QString("???");
234 if ( !activeServers->isSelected(i) ) s << "#"; 234 if ( !activeServers->isSelected(i) ) s << "#";
235 s << "src " << activeServers->text(i) << " " << url << "\n"; 235 s << "src " << activeServers->text(i) << " " << url << "\n";
236 } 236 }
237 for (int i=0; i<(int)destinations->count(); i++) 237 for (int i=0; i<(int)destinations->count(); i++)
238 { 238 {
239 QString url = destinationurlDic[i] ? *destinationurlDic[i] : QString("???"); 239 QString url = destinationurlDic[i] ? *destinationurlDic[i] : QString("???");
240 s << "dest " << destinations->text(i) << " " << url << "\n"; 240 s << "dest " << destinations->text(i) << " " << url << "\n";
241 } 241 }
242 conf.close(); 242 conf.close();
243} 243}
244 244
245 245
246void PackageManagerSettings::readInstallationSettings() 246void PackageManagerSettings::readInstallationSettings()
247{ 247{
248 Config cfg( "oipkg", Config::User ); 248 Config cfg( "oipkg", Config::User );
249 cfg.setGroup( "Settings" ); 249 cfg.setGroup( "Settings" );
250 250
251 installationSettingsCount = cfg.readNumEntry( "count", -1 ); 251 installationSettingsCount = cfg.readNumEntry( "count", -1 );
252 currentSetting = cfg.readNumEntry( "current", 0 );// o should be -1 252 currentSetting = cfg.readNumEntry( "current", 0 );// o should be -1
253 253
254// for (int i = 0; i < installationSettingsCount; i++) 254// for (int i = 0; i < installationSettingsCount; i++)
255// { 255// {
256// cfg.setGroup( "Setting_" + QString::number(i) ); 256// cfg.setGroup( "Setting_" + QString::number(i) );
257// settingName->insertItem( cfg.readEntry( "name", "???" ), i ); 257// settingName->insertItem( cfg.readEntry( "name", "???" ), i );
258// }; 258// };
259 readInstallationSetting( currentSetting ); 259 readInstallationSetting( currentSetting );
260} 260}
261 261
262 262
263 263
264///** 264///**
265// * remove from conf file 265// * remove from conf file
266// */ 266// */
267//void PackageManagerSettings::removeInstallationSetting() 267//void PackageManagerSettings::removeInstallationSetting()
268//{ 268//{
269// settingName->removeItem( settingName->currentItem() ); 269// settingName->removeItem( settingName->currentItem() );
270// Config cfg( "oipkg", Config::User ); 270// Config cfg( "oipkg", Config::User );
271// cfg.setGroup( "Setting_" + QString::number( installationSettingsCount ) ); 271// cfg.setGroup( "Setting_" + QString::number( installationSettingsCount ) );
272// cfg.clearGroup(); 272// cfg.clearGroup();
273// installationSettingsCount--; 273// installationSettingsCount--;
274// changed = true; 274// changed = true;
275// settingName->setEditable( false ); 275// settingName->setEditable( false );
276//} 276//}
277 277
278///** 278///**
279// * write to confgile 279// * write to confgile
280// */ 280// */
281//void PackageManagerSettings::newInstallationSetting() 281//void PackageManagerSettings::newInstallationSetting()
282//{ 282//{
283// installationSettingsCount++; 283// installationSettingsCount++;
284// settingName->insertItem( "New", installationSettingsCount ); 284// settingName->insertItem( "New", installationSettingsCount );
285// settingName->setCurrentItem( installationSettingsCount ); 285// settingName->setCurrentItem( installationSettingsCount );
286// settingName->setEditable( true ); 286// settingName->setEditable( true );
287// changed = true; 287// changed = true;
288//} 288//}
289 289
290//void PackageManagerSettings::installationSettingChange(int cs) 290//void PackageManagerSettings::installationSettingChange(int cs)
291//{ 291//{
292// writeCurrentInstallationSetting(); 292// writeCurrentInstallationSetting();
293// currentSetting = cs; 293// currentSetting = cs;
294// readInstallationSetting( cs ); 294// readInstallationSetting( cs );
295// changed = true; 295// changed = true;
296//} 296//}
297 297
298void PackageManagerSettings::writeInstallationSettings() 298void PackageManagerSettings::writeInstallationSettings()
299{ 299{
300 { 300 {
301 Config cfg( "oipkg", Config::User ); 301 Config cfg( "oipkg", Config::User );
302 cfg.setGroup( "Settings" ); 302 cfg.setGroup( "Settings" );
303 cfg.writeEntry( "count", installationSettingsCount ); 303 cfg.writeEntry( "count", installationSettingsCount );
304 cfg.writeEntry( "current", currentSetting ); 304 cfg.writeEntry( "current", currentSetting );
305 } 305 }
306 writeCurrentInstallationSetting(); 306 writeCurrentInstallationSetting();
307} 307}
308 308
309 309
310void PackageManagerSettings::readInstallationSetting(int setting) 310void PackageManagerSettings::readInstallationSetting(int setting)
311{ 311{
312 if ( setting < 0 ) return; 312 if ( setting < 0 ) return;
313 Config cfg( "oipkg", Config::User ); 313 Config cfg( "oipkg", Config::User );
314 cfg.setGroup( "Setting_" + QString::number( setting ) ); 314 cfg.setGroup( "Setting_" + QString::number( setting ) );
315 CheckBoxLink->setChecked( cfg.readBoolEntry( "link", true ) ); 315 CheckBoxLink->setChecked( cfg.readBoolEntry( "link", true ) );
316 QString dest = cfg.readEntry( "dest" ); 316 QString dest = cfg.readEntry( "dest" );
317 QString linkdest = cfg.readEntry( "linkdest" ); 317 QString linkdest = cfg.readEntry( "linkdest" );
318 pvDebug(3, "dest="+dest); 318 pvDebug(3, "dest="+dest);
319 pvDebug(3, "linkdest="+linkdest); 319 pvDebug(3, "linkdest="+linkdest);
320 for ( int i = 0; i < activeDestination->count(); i++) 320 for ( int i = 0; i < activeDestination->count(); i++)
321 { 321 {
322 if ( activeDestination->text( i ) == dest ) 322 if ( activeDestination->text( i ) == dest )
323 activeDestination->setCurrentItem( i ); 323 activeDestination->setCurrentItem( i );
324 if ( activeLinkDestination->text( i ) == linkdest ) 324 if ( activeLinkDestination->text( i ) == linkdest )
325 activeLinkDestination->setCurrentItem( i ); 325 activeLinkDestination->setCurrentItem( i );
326 } 326 }
327} 327}
328 328
329void PackageManagerSettings::writeCurrentInstallationSetting() 329void PackageManagerSettings::writeCurrentInstallationSetting()
330{ 330{
331 Config cfg( "oipkg", Config::User ); 331 Config cfg( "oipkg", Config::User );
332 cfg.setGroup( "Setting_" + QString::number(currentSetting) ); 332 cfg.setGroup( "Setting_" + QString::number(currentSetting) );
333 cfg.writeEntry( "link", CheckBoxLink->isChecked() ); 333 cfg.writeEntry( "link", CheckBoxLink->isChecked() );
334 cfg.writeEntry( "dest", getDestinationName() ); 334 cfg.writeEntry( "dest", getDestinationName() );
335 cfg.writeEntry( "linkdest" , getLinkDestinationName() ); 335 cfg.writeEntry( "linkdest" , getLinkDestinationName() );
336 QStringList sers = getActiveServers(); 336 QStringList sers = getActiveServers();
337 int srvc = 0; 337 int srvc = 0;
338 for ( QStringList::Iterator it = sers.begin(); it != sers.end(); ++it ) { 338 for ( QStringList::Iterator it = sers.begin(); it != sers.end(); ++it ) {
339 cfg.writeEntry( "server_" + QString::number(srvc++), *it ); 339 cfg.writeEntry( "server_" + QString::number(srvc++), *it );
340 } 340 }
341 cfg.writeEntry( "server_count", srvc ); 341 cfg.writeEntry( "server_count", srvc );
342} 342}
343 343
344//void PackageManagerSettings::renameInstallationSetting() 344//void PackageManagerSettings::renameInstallationSetting()
345//{ 345//{
346// settingName->setEditable( true ); 346// settingName->setEditable( true );
347// changed = true; 347// changed = true;
348//} 348//}
349 349
350//void PackageManagerSettings::installationSettingSetName(const QString &name) 350//void PackageManagerSettings::installationSettingSetName(const QString &name)
351//{ 351//{
352// settingName->changeItem( name, settingName->currentItem() ); 352// settingName->changeItem( name, settingName->currentItem() );
353// changed = true; 353// changed = true;
354//} 354//}
355 355
356 356
357bool PackageManagerSettings::readIpkgConfig(const QString& conffile) 357bool PackageManagerSettings::readIpkgConfig(const QString& conffile)
358{ 358{
359 QFile conf(conffile); 359 QFile conf(conffile);
360 changed = false; 360 changed = false;
361 if ( conf.open(IO_ReadOnly) ) { 361 if ( conf.open(IO_ReadOnly) ) {
362 QTextStream s(&conf); 362 QTextStream s(&conf);
363 servers->clear(); 363 servers->clear();
364 activeServers->clear(); 364 activeServers->clear();
365 destinations->clear(); 365 destinations->clear();
366 activeDestination->clear(); 366 activeDestination->clear();
367 activeLinkDestination->clear(); 367 activeLinkDestination->clear();
368 serverurlDic.clear(); 368 serverurlDic.clear();
369 destinationurlDic.clear(); 369 destinationurlDic.clear();
370 ipkg_old=0; 370 ipkg_old=0;
371 int currentserver=0; 371 int currentserver=0;
372 while ( !s.atEnd() ) { 372 while ( !s.atEnd() ) {
373 QString l = s.readLine(); 373 QString l = s.readLine();
374 QStringList token = QStringList::split(' ', l); 374 QStringList token = QStringList::split(' ', l);
375 if ( token[0] == "src" || token[0] == "#src" ) { 375 if ( token[0] == "src" || token[0] == "#src" ) {
376 currentserver=servers->count(); 376 currentserver=servers->count();
377 serverurlDic.insert(servers->count(),new QString(token[2])); 377 serverurlDic.insert(servers->count(),new QString(token[2]));
378 int a = token[0] == "src" ? 1 : 0; 378 int a = token[0] == "src" ? 1 : 0;
379 int i = servers->count(); 379 int i = servers->count();
380 servers->insertItem(token[1]); 380 servers->insertItem(token[1]);
381 activeServers->insertItem( token[1] ); 381 activeServers->insertItem( token[1] );
382 activeServers->setSelected(i,a); 382 activeServers->setSelected(i,a);
383 } else if ( token[0] == "dest" ) { 383 } else if ( token[0] == "dest" ) {
384 currentserver=destinations->count(); 384 currentserver=destinations->count();
385 destinationurlDic.insert(destinations->count(),new QString(token[2])); 385 destinationurlDic.insert(destinations->count(),new QString(token[2]));
386 destinations->insertItem(token[1]); 386 destinations->insertItem(token[1]);
387 activeDestination->insertItem( token[1] ); 387 activeDestination->insertItem( token[1] );
388 activeLinkDestination->insertItem( token[1] ); 388 activeLinkDestination->insertItem( token[1] );
389 389
390 } else if ( token[0] == "option" ) { 390 } else if ( token[0] == "option" ) {
391 // ### somehow need to use the settings from netsetup 391 // ### somehow need to use the settings from netsetup
392 // if ( token[1] == "http_proxy" ) 392 // if ( token[1] == "http_proxy" )
393 // http->setText(token[2]); 393 // http->setText(token[2]);
394 // else if ( token[1] == "ftp_proxy" ) 394 // else if ( token[1] == "ftp_proxy" )
395 // ftp->setText(token[2]); 395 // ftp->setText(token[2]);
396 // else if ( token[1] == "proxy_username" ) 396 // else if ( token[1] == "proxy_username" )
397 // username->setText(token[2]); 397 // username->setText(token[2]);
398 // else if ( token[1] == "proxy_password" ) 398 // else if ( token[1] == "proxy_password" )
399 // password->setText(token[2]); 399 // password->setText(token[2]);
400 } else { 400 } else {
401 // Old style? 401 // Old style?
402 int eq = l.find('='); 402 int eq = l.find('=');
403 if ( eq >= 0 ) { 403 if ( eq >= 0 ) {
404 QString v = l.mid(eq+1).stripWhiteSpace(); 404 QString v = l.mid(eq+1).stripWhiteSpace();
405 if ( v[0] == '"' || v[0] == '\'' ) { 405 if ( v[0] == '"' || v[0] == '\'' ) {
406 int cl=v.find(v[0],1); 406 int cl=v.find(v[0],1);
407 if ( cl >= 0 ) 407 if ( cl >= 0 )
408 v = v.mid(1,cl-1); 408 v = v.mid(1,cl-1);
409 } 409 }
410 if ( l.left(12) == "IPKG_SOURCE=" ) { 410 if ( l.left(12) == "IPKG_SOURCE=" ) {
411 ipkg_old=1; 411 ipkg_old=1;
412 currentserver=servers->count(); 412 currentserver=servers->count();
413 serverurlDic.insert(servers->count(),new QString(v)); 413 serverurlDic.insert(servers->count(),new QString(v));
414 servers->insertItem(v); 414 servers->insertItem(v);
415 } else if ( l.left(13) == "#IPKG_SOURCE=" ) { 415 } else if ( l.left(13) == "#IPKG_SOURCE=" ) {
416 serverurlDic.insert(servers->count(),new QString(v)); 416 serverurlDic.insert(servers->count(),new QString(v));
417 servers->insertItem(v); 417 servers->insertItem(v);
418 } else if ( l.left(10) == "IPKG_ROOT=" ) { 418 } else if ( l.left(10) == "IPKG_ROOT=" ) {
419 // ### no UI 419 // ### no UI
420 // } else if ( l.left(20) == "IPKG_PROXY_USERNAME=" ) { 420 // } else if ( l.left(20) == "IPKG_PROXY_USERNAME=" ) {
421 // username->setText(v); 421 // username->setText(v);
422 // } else if ( l.left(20) == "IPKG_PROXY_PASSWORD=" ) { 422 // } else if ( l.left(20) == "IPKG_PROXY_PASSWORD=" ) {
423 // password->setText(v); 423 // password->setText(v);
424 // } else if ( l.left(16) == "IPKG_PROXY_HTTP=" ) { 424 // } else if ( l.left(16) == "IPKG_PROXY_HTTP=" ) {
425 // http->setText(v); 425 // http->setText(v);
426 // } else if ( l.left(16) == "IPKG_PROXY_FTP=" ) { 426 // } else if ( l.left(16) == "IPKG_PROXY_FTP=" ) {
427 // ftp->setText(v); 427 // ftp->setText(v);
428 } 428 }
429 } 429 }
430 } 430 }
431 } 431 }
432 if ( ipkg_old ) { 432 if ( ipkg_old ) {
433 servers->setSelectionMode(QListBox::Single); 433 servers->setSelectionMode(QListBox::Single);
434 servers->setSelected(currentserver,TRUE); 434 servers->setSelected(currentserver,TRUE);
435 } 435 }
436 return TRUE; 436 return TRUE;
437 } else { 437 } else {
438 return FALSE; 438 return FALSE;
439 } 439 }
440} 440}
441 441
442 442
443/** 443/**
444 * read from config file(s) 444 * read from config file(s)
445 */ 445 */
446void PackageManagerSettings::readSettings() 446void PackageManagerSettings::readSettings()
447{ 447{
448 readIpkgConfig("/etc/ipkg.conf"); 448 readIpkgConfig("/etc/ipkg.conf");
449 readInstallationSettings(); 449 readInstallationSettings();
450} 450}
451 451
452void PackageManagerSettings::writeSettings() 452void PackageManagerSettings::writeSettings()
453{ 453{
454 if ( changed ) writeIpkgConfig("/etc/ipkg.conf"); 454 if ( changed ) writeIpkgConfig("/etc/ipkg.conf");
455 writeInstallationSettings(); 455 writeInstallationSettings();
456} 456}
457/** shows the setting dialog */ 457/** shows the setting dialog */
458bool PackageManagerSettings::showDialog( int i ) 458bool PackageManagerSettings::showDialog( int i )
459{ 459{
460 TabWidget->setCurrentPage( i ); 460 TabWidget->setCurrentPage( i );
461 showMaximized(); 461 showMaximized();
462 bool ret = exec(); 462 bool ret = exec();
463 if ( ret ) writeSettings(); 463 if ( ret ) writeSettings();
464 else readSettings(); 464 else readSettings();
465 return (changed && ret); 465 return (changed && ret);
466} 466}
467/** Returns the installation destination */ 467/** Returns the installation destination */
468QString PackageManagerSettings::getDestinationName() 468QString PackageManagerSettings::getDestinationName()
469{ 469{
470 return activeDestination->currentText(); 470 return activeDestination->currentText();
471} 471}
472/** Returns the link destination */ 472/** Returns the link destination */
473QString PackageManagerSettings::getLinkDestinationName() 473QString PackageManagerSettings::getLinkDestinationName()
474{ 474{
475 return activeLinkDestination->currentText(); 475 return activeLinkDestination->currentText();
476} 476}
477/** Returns the URL of the active destination */ 477/** Returns the URL of the active destination */
478QString PackageManagerSettings::getDestinationUrl() 478QString PackageManagerSettings::getDestinationUrl()
479{ 479{
480 int dnr = activeDestination->currentItem(); 480 int dnr = activeDestination->currentItem();
481 return *destinationurlDic.find(dnr); 481 return *destinationurlDic.find(dnr);
482} 482}
483/** Should oipkg create links form install destination to link destination */ 483/** Should oipkg create links form install destination to link destination */
484bool PackageManagerSettings::createLinks() 484bool PackageManagerSettings::createLinks()
485{ 485{
486 return CheckBoxLink->isChecked(); 486 return CheckBoxLink->isChecked();
487} 487}
488/** get the servers that are active */ 488/** get the servers that are active */
489QStringList PackageManagerSettings::getActiveServers() 489QStringList PackageManagerSettings::getActiveServers()
490{ 490{
491 QStringList sl; 491 QStringList sl;
492 for (int i=0; i<(int)activeServers->count(); i++) 492 for (int i=0; i<(int)activeServers->count(); i++)
493 { 493 {
494 if ( activeServers->isSelected(i) ) 494 if ( activeServers->isSelected(i) )
495 sl += activeServers->text(i); 495 sl += activeServers->text(i);
496 } 496 }
497 return sl; 497 return sl;
498} 498}
499 QStringList PackageManagerSettings::getServers() 499 QStringList PackageManagerSettings::getServers()
500{ 500{
501 QStringList sl; 501 QStringList sl;
502 for (int i=0; i<(int)activeServers->count(); i++) 502 for (int i=0; i<(int)activeServers->count(); i++)
503 { 503 {
504 sl += activeServers->text(i); 504 sl += activeServers->text(i);
505 } 505 }
506 return sl; 506 return sl;
507} 507}
508 508
509/** returns the destination listed in ipkg.conf */ 509/** returns the destination listed in ipkg.conf */
510QStringList PackageManagerSettings::getDestinationUrls() 510QStringList PackageManagerSettings::getDestinationUrls()
511{ 511{
512 QStringList sl; 512 QStringList sl;
513 for (int i=0; i<(int)destinations->count(); i++) 513 for (int i=0; i<(int)destinations->count(); i++)
514 { 514 {
515 sl += *destinationurlDic[i]; 515 sl += *destinationurlDic[i];
516 } 516 }
517 return sl; 517 return sl;
518} 518}
519 519
520/** returns the destination listed in ipkg.conf */ 520/** returns the destination listed in ipkg.conf */
521QString PackageManagerSettings::getDestinationUrlByName(QString n) 521QString PackageManagerSettings::getDestinationUrlByName(QString n)
522{ 522{
523 QStringList sl; 523 QStringList sl;
524 for (int i=0; i<(int)destinations->count(); i++) 524 for (int i=0; i<(int)destinations->count(); i++)
525 { 525 {
526 if ( n == destinations->text(i)) return*destinationurlDic[i]; 526 if ( n == destinations->text(i)) return*destinationurlDic[i];
527 } 527 }
528 return ""; 528 return "";
529} 529}
530 530
531/** returns the destination listed in ipkg.conf */ 531/** returns the destination listed in ipkg.conf */
532QStringList PackageManagerSettings::getDestinationNames() 532QStringList PackageManagerSettings::getDestinationNames()
533{ 533{
534 QStringList sl; 534 QStringList sl;
535 for (int i=0; i<(int)destinations->count(); i++) 535 for (int i=0; i<(int)destinations->count(); i++)
536 { 536 {
537 sl += destinations->text(i); 537 sl += destinations->text(i);
538 } 538 }
539 return sl; 539 return sl;
540} 540}
541 541
542 542
543void PackageManagerSettings::linkEnabled( bool b ) 543void PackageManagerSettings::linkEnabled( bool b )
544{ 544{
545 pvDebug(2,"PackageManagerSettings::linkEnabled "+QString(b?"yes":"no")); 545 pvDebug(2,"PackageManagerSettings::linkEnabled "+QString(b?"yes":"no"));
546 activeLinkDestination->setEnabled( b ); 546 activeLinkDestination->setEnabled( b );
547 CheckBoxLink->setChecked( b ); 547 CheckBoxLink->setChecked( b );
548} 548}
549 549
550void PackageManagerSettings::activeServerChanged() 550void PackageManagerSettings::activeServerChanged()
551{ 551{
552 changed = true; 552 changed = true;
553} 553}
554 554
555void PackageManagerSettings::createLinksToDest() 555void PackageManagerSettings::createLinksToDest()
556{ 556{
557 pvDebug(2,"creating links..."); 557 pvDebug(2,"creating links...");
558 // emit doCreateLinks( destinationurl->text() ); 558 // emit doCreateLinks( destinationurl->text() );
559 //ipkg->createLinks( destinationurl ); 559 //ipkg->createLinks( destinationurl );
560} 560}
561 561
562void PackageManagerSettings::removeLinksToDest() 562void PackageManagerSettings::removeLinksToDest()
563{ 563{
564 pvDebug(2,"removing links..."); 564 pvDebug(2,"removing links...");
565 // emit doRemoveLinks( destinationurl->text() ); 565 // emit doRemoveLinks( destinationurl->text() );
566 //ipkg->removeLinks( destinationurl ); 566 //ipkg->removeLinks( destinationurl );
567} 567}
568 568
569void PackageManagerSettings::activeDestinationChange(int i) 569void PackageManagerSettings::activeDestinationChange(int i)
570{ 570{
571 pvDebug(5,"activeDestinationChange "+QString::number(i)); 571 pvDebug(5,"activeDestinationChange "+QString::number(i));
572 if (i > activeDestination->count()) return; 572 if (i > activeDestination->count()) return;
573 activeDestination->setCurrentItem(i); 573 activeDestination->setCurrentItem(i);
574 pvDebug(5,"dest name "+ activeDestination->currentText()); 574 pvDebug(5,"dest name "+ activeDestination->currentText());
575} 575}
diff --git a/noncore/unsupported/qpdf/qbusybar.cpp b/noncore/unsupported/qpdf/qbusybar.cpp
index ce7ab8e..e942f06 100644
--- a/noncore/unsupported/qpdf/qbusybar.cpp
+++ b/noncore/unsupported/qpdf/qbusybar.cpp
@@ -1,133 +1,133 @@
1#include <qapplication.h> 1#include <qapplication.h>
2#include <qtimer.h> 2#include <qtimer.h>
3#include <qpainter.h> 3#include <qpainter.h>
4 4
5#include "qbusybar.h" 5#include "qbusybar.h"
6 6
7 7
8 8
9QBusyBar::QBusyBar ( QWidget *parent, const char *name, int flags ) : QWidget ( parent, name, flags | WRepaintNoErase ) 9QBusyBar::QBusyBar ( QWidget *parent, const char *name, int flags ) : QWidget ( parent, name, flags | WRepaintNoErase )
10{ 10{
11 m_busy = 0; 11 m_busy = 0;
12 12
13 m_div = 0; 13 m_div = 0;
14 m_pos = 0; 14 m_pos = 0;
15 m_fade = 0; 15 m_fade = 0;
16 m_fadecols = 0; 16 m_fadecols = 0;
17 m_speed = 500; 17 m_speed = 500;
18 18
19 m_timer = new QTimer ( this ); 19 m_timer = new QTimer ( this );
20 connect ( m_timer, SIGNAL( timeout ( )), this, SLOT( slotTimeout ( ))); 20 connect ( m_timer, SIGNAL( timeout()), this, SLOT( slotTimeout()));
21 21
22 setParameters ( 12, 8, 200 ); 22 setParameters ( 12, 8, 200 );
23} 23}
24 24
25 void QBusyBar::setParameters ( int d, int s, int v ) 25 void QBusyBar::setParameters ( int d, int s, int v )
26 { 26 {
27 bool running = m_timer-> isActive ( ); 27 bool running = m_timer-> isActive ( );
28 28
29 if ( running ) 29 if ( running )
30 m_timer-> stop ( ); 30 m_timer-> stop ( );
31 31
32 m_div = d; 32 m_div = d;
33 m_speed = v; 33 m_speed = v;
34 34
35 delete [] m_fadecols; 35 delete [] m_fadecols;
36 m_fade = s; 36 m_fade = s;
37 m_fadecols = new QColor [m_fade]; 37 m_fadecols = new QColor [m_fade];
38 38
39 int rt, gt, bt; 39 int rt, gt, bt;
40 int rf, gf, bf; 40 int rf, gf, bf;
41 41
42 colorGroup ( ). color ( QColorGroup::Highlight ). rgb ( &rf, &gf, &bf ); 42 colorGroup ( ). color ( QColorGroup::Highlight ). rgb ( &rf, &gf, &bf );
43 colorGroup ( ). color ( QColorGroup::Background ). rgb ( &rt, &gt, &bt ); 43 colorGroup ( ). color ( QColorGroup::Background ). rgb ( &rt, &gt, &bt );
44 44
45 for ( int i = 0; i < s; i++ ) 45 for ( int i = 0; i < s; i++ )
46 m_fadecols [i]. setRgb ( rf + ( rt - rf ) * i / s, gf + ( gt - gf ) * i / s, bf + ( bt - bf ) * i / s ); 46 m_fadecols [i]. setRgb ( rf + ( rt - rf ) * i / s, gf + ( gt - gf ) * i / s, bf + ( bt - bf ) * i / s );
47 47
48 if ( running ) { 48 if ( running ) {
49 m_pos = 0; 49 m_pos = 0;
50 m_timer-> start ( m_speed ); 50 m_timer-> start ( m_speed );
51 } 51 }
52} 52}
53 53
54QBusyBar::~QBusyBar ( ) 54QBusyBar::~QBusyBar ( )
55{ 55{
56 delete [] m_fadecols; 56 delete [] m_fadecols;
57} 57}
58 58
59bool QBusyBar::isBusy ( ) const 59bool QBusyBar::isBusy ( ) const
60{ 60{
61 return m_busy; 61 return m_busy;
62} 62}
63 63
64void QBusyBar::beginBusy ( ) 64void QBusyBar::beginBusy ( )
65{ 65{
66 setBusy ( true ); 66 setBusy ( true );
67} 67}
68 68
69void QBusyBar::endBusy ( ) 69void QBusyBar::endBusy ( )
70{ 70{
71 setBusy ( false ); 71 setBusy ( false );
72} 72}
73 73
74void QBusyBar::setBusy ( bool b ) 74void QBusyBar::setBusy ( bool b )
75{ 75{
76 int busy = m_busy + ( b ? 1 : -1 ); 76 int busy = m_busy + ( b ? 1 : -1 );
77 77
78 if ( busy < 0 ) 78 if ( busy < 0 )
79 busy = 0; 79 busy = 0;
80 80
81 if (( m_busy == 0 ) && ( busy > 0 )) { // Changed stateto on 81 if (( m_busy == 0 ) && ( busy > 0 )) { // Changed stateto on
82 m_pos = 0; 82 m_pos = 0;
83 m_timer-> start ( m_speed ); 83 m_timer-> start ( m_speed );
84 update ( ); 84 update ( );
85 } 85 }
86 else if (( m_busy > 0 ) && ( busy == 0 )) { // Changed state to off 86 else if (( m_busy > 0 ) && ( busy == 0 )) { // Changed state to off
87 m_timer-> stop ( ); 87 m_timer-> stop ( );
88 update ( ); 88 update ( );
89 } 89 }
90 90
91 m_busy = busy; 91 m_busy = busy;
92} 92}
93 93
94void QBusyBar::slotTimeout ( ) 94void QBusyBar::slotTimeout ( )
95{ 95{
96 m_pos++; 96 m_pos++;
97 m_pos %= ( 2 * ( m_fade + m_div )); 97 m_pos %= ( 2 * ( m_fade + m_div ));
98 98
99 update ( ); 99 update ( );
100} 100}
101 101
102void QBusyBar::paintEvent ( QPaintEvent *e ) 102void QBusyBar::paintEvent ( QPaintEvent *e )
103{ 103{
104 QPainter p ( this ); 104 QPainter p ( this );
105 105
106 QRect clip = e-> rect ( ); 106 QRect clip = e-> rect ( );
107 107
108 int x = 0; 108 int x = 0;
109 int dx = width ( ) / m_div; 109 int dx = width ( ) / m_div;
110 int y = clip. top ( ); 110 int y = clip. top ( );
111 int dy = clip. height ( ); 111 int dy = clip. height ( );
112 112
113 if ( m_busy ) { 113 if ( m_busy ) {
114 int dir = ( m_pos < ( m_fade + m_div )) ? 1 : -1; 114 int dir = ( m_pos < ( m_fade + m_div )) ? 1 : -1;
115 int pos = ( dir > 0 ) ? m_pos : ( 2 * ( m_div + m_fade )) - m_pos - m_fade - 1; 115 int pos = ( dir > 0 ) ? m_pos : ( 2 * ( m_div + m_fade )) - m_pos - m_fade - 1;
116 116
117 for ( int i = 0; i < m_div; i++ ) { 117 for ( int i = 0; i < m_div; i++ ) {
118 int ind = ( pos - i ) * dir; 118 int ind = ( pos - i ) * dir;
119 if (( ind < 0 ) || ( ind >= m_fade )) 119 if (( ind < 0 ) || ( ind >= m_fade ))
120 ind = m_fade - 1; 120 ind = m_fade - 1;
121 121
122 if ((( x + dx ) > clip. left ( )) || ( x < clip. right ( ))) 122 if ((( x + dx ) > clip. left ( )) || ( x < clip. right ( )))
123 p. fillRect ( x, y, ( i < ( m_div - 1 )) ? dx : width ( ) - x, dy, m_fadecols [ind] ); 123 p. fillRect ( x, y, ( i < ( m_div - 1 )) ? dx : width ( ) - x, dy, m_fadecols [ind] );
124 x += dx; 124 x += dx;
125 } 125 }
126 } 126 }
127 else { 127 else {
128 p. fillRect ( e-> rect ( ), m_fadecols [m_fade - 1] ); 128 p. fillRect ( e-> rect ( ), m_fadecols [m_fade - 1] );
129 } 129 }
130} 130}
131 131
132 132
133 133
diff --git a/noncore/unsupported/qpdf/qpdf.cpp b/noncore/unsupported/qpdf/qpdf.cpp
index 5cdcccf..75e86d0 100644
--- a/noncore/unsupported/qpdf/qpdf.cpp
+++ b/noncore/unsupported/qpdf/qpdf.cpp
@@ -1,540 +1,540 @@
1//======================================================================== 1//========================================================================
2// 2//
3// qpdf.cc 3// qpdf.cc
4// 4//
5// Copyright 2001 Robert Griebl 5// Copyright 2001 Robert Griebl
6// 6//
7//======================================================================== 7//========================================================================
8 8
9#include "aconf.h" 9#include "aconf.h"
10#include "GString.h" 10#include "GString.h"
11#include "PDFDoc.h" 11#include "PDFDoc.h"
12#include "TextOutputDev.h" 12#include "TextOutputDev.h"
13 13
14#include "QPEOutputDev.h" 14#include "QPEOutputDev.h"
15 15
16#include <qpe/qpeapplication.h> 16#include <qpe/qpeapplication.h>
17#include <qpe/resource.h> 17#include <qpe/resource.h>
18#include <qpe/applnk.h> 18#include <qpe/applnk.h>
19#include <qpe/qcopenvelope_qws.h> 19#include <qpe/qcopenvelope_qws.h>
20 20
21 21
22#include <qclipboard.h> 22#include <qclipboard.h>
23#include <qpe/qpetoolbar.h> 23#include <qpe/qpetoolbar.h>
24#include <qtoolbutton.h> 24#include <qtoolbutton.h>
25#include <qmenubar.h> 25#include <qmenubar.h>
26#include <qpopupmenu.h> 26#include <qpopupmenu.h>
27#include <qwidgetstack.h> 27#include <qwidgetstack.h>
28#include <qtimer.h> 28#include <qtimer.h>
29#include <qfileinfo.h> 29#include <qfileinfo.h>
30#include <qstring.h> 30#include <qstring.h>
31#include <qlineedit.h> 31#include <qlineedit.h>
32#include <qspinbox.h> 32#include <qspinbox.h>
33#include <qlayout.h> 33#include <qlayout.h>
34#include <qdialog.h> 34#include <qdialog.h>
35#include <qlabel.h> 35#include <qlabel.h>
36#include <qmessagebox.h> 36#include <qmessagebox.h>
37 37
38#include "qpdf.h" 38#include "qpdf.h"
39 39
40#ifdef QPDF_QPE_ONLY 40#ifdef QPDF_QPE_ONLY
41#include <qpe/fileselector.h> 41#include <qpe/fileselector.h>
42#else 42#else
43#include <opie/ofileselector.h> 43#include <opie/ofileselector.h>
44#endif 44#endif
45 45
46 46
47int main ( int argc, char **argv ) 47int main ( int argc, char **argv )
48{ 48{
49 QPEApplication app ( argc, argv ); 49 QPEApplication app ( argc, argv );
50 50
51 // read config file 51 // read config file
52 globalParams = new GlobalParams ( "" ); 52 globalParams = new GlobalParams ( "" );
53 globalParams-> setErrQuiet ( true ); 53 globalParams-> setErrQuiet ( true );
54 54
55 QPdfDlg *dlg = new QPdfDlg ( ); 55 QPdfDlg *dlg = new QPdfDlg ( );
56 app. showMainDocumentWidget ( dlg ); 56 app. showMainDocumentWidget ( dlg );
57 57
58 if (( app. argc ( ) == 3 ) && ( app. argv ( ) [1] == QCString ( "-f" ))) 58 if (( app. argc ( ) == 3 ) && ( app. argv ( ) [1] == QCString ( "-f" )))
59 dlg-> openFile ( app. argv ( ) [2] ); 59 dlg-> openFile ( app. argv ( ) [2] );
60 60
61 return app. exec ( ); 61 return app. exec ( );
62} 62}
63 63
64 64
65QPdfDlg::QPdfDlg ( ) : QMainWindow ( ) 65QPdfDlg::QPdfDlg ( ) : QMainWindow ( )
66{ 66{
67 setCaption ( tr( "QPdf" )); 67 setCaption ( tr( "QPdf" ));
68 setIcon ( Resource::loadPixmap ( "qpdf_icon" )); 68 setIcon ( Resource::loadPixmap ( "qpdf_icon" ));
69 69
70 m_busy = false; 70 m_busy = false;
71 71
72 m_doc = 0; 72 m_doc = 0;
73 m_pages = 0; 73 m_pages = 0;
74 m_zoom = 72; 74 m_zoom = 72;
75 m_currentpage = 0; 75 m_currentpage = 0;
76 76
77 m_fullscreen = false; 77 m_fullscreen = false;
78 m_renderok = false; 78 m_renderok = false;
79 79
80 80
81 setToolBarsMovable ( false ); 81 setToolBarsMovable ( false );
82 82
83 m_stack = new QWidgetStack ( this ); 83 m_stack = new QWidgetStack ( this );
84 m_stack-> setSizePolicy ( QSizePolicy ( QSizePolicy::Expanding, QSizePolicy::Expanding )); 84 m_stack-> setSizePolicy ( QSizePolicy ( QSizePolicy::Expanding, QSizePolicy::Expanding ));
85 setCentralWidget ( m_stack ); 85 setCentralWidget ( m_stack );
86 86
87 m_outdev = new QPEOutputDev ( m_stack ); 87 m_outdev = new QPEOutputDev ( m_stack );
88 connect ( m_outdev, SIGNAL( selectionChanged ( const QRect & )), this, SLOT( copyToClipboard ( const QRect & ))); 88 connect ( m_outdev, SIGNAL( selectionChanged(const QRect&)), this, SLOT( copyToClipboard(const QRect&)));
89 89
90#ifdef QPDF_QPE_ONLY 90#ifdef QPDF_QPE_ONLY
91 m_filesel = new FileSelector ( "application/pdf", m_stack, "fs", false, true ); 91 m_filesel = new FileSelector ( "application/pdf", m_stack, "fs", false, true );
92#else 92#else
93 m_filesel = new OFileSelector ( "application/pdf", m_stack, "fs", false, true ); 93 m_filesel = new OFileSelector ( "application/pdf", m_stack, "fs", false, true );
94#endif 94#endif
95 95
96 connect ( m_filesel, SIGNAL( closeMe ( )), this, SLOT( closeFileSelector ( ))); 96 connect ( m_filesel, SIGNAL( closeMe()), this, SLOT( closeFileSelector()));
97 connect ( m_filesel, SIGNAL( fileSelected ( const DocLnk & )), this, SLOT( openFile ( const DocLnk & ))); 97 connect ( m_filesel, SIGNAL( fileSelected(const DocLnk&)), this, SLOT( openFile(const DocLnk&)));
98 98
99 m_tb_menu = new QToolBar ( this ); 99 m_tb_menu = new QToolBar ( this );
100 m_tb_menu-> setHorizontalStretchable ( true ); 100 m_tb_menu-> setHorizontalStretchable ( true );
101 101
102 QMenuBar *mb = new QMenuBar ( m_tb_menu ); 102 QMenuBar *mb = new QMenuBar ( m_tb_menu );
103 103
104 m_pm_zoom = new QPopupMenu ( mb ); 104 m_pm_zoom = new QPopupMenu ( mb );
105 m_pm_zoom-> setCheckable ( true ); 105 m_pm_zoom-> setCheckable ( true );
106 106
107 mb-> insertItem ( tr( "Zoom" ), m_pm_zoom ); 107 mb-> insertItem ( tr( "Zoom" ), m_pm_zoom );
108 108
109 m_pm_zoom-> insertItem ( tr( "Fit to width" ), 1 ); 109 m_pm_zoom-> insertItem ( tr( "Fit to width" ), 1 );
110 m_pm_zoom-> insertItem ( tr( "Fit to page" ), 2 ); 110 m_pm_zoom-> insertItem ( tr( "Fit to page" ), 2 );
111 m_pm_zoom-> insertSeparator ( ); 111 m_pm_zoom-> insertSeparator ( );
112 m_pm_zoom-> insertItem ( tr( "50%" ), 50 ); 112 m_pm_zoom-> insertItem ( tr( "50%" ), 50 );
113 m_pm_zoom-> insertItem ( tr( "75%" ), 75 ); 113 m_pm_zoom-> insertItem ( tr( "75%" ), 75 );
114 m_pm_zoom-> insertItem ( tr( "100%" ), 100 ); 114 m_pm_zoom-> insertItem ( tr( "100%" ), 100 );
115 m_pm_zoom-> insertItem ( tr( "125%" ), 125 ); 115 m_pm_zoom-> insertItem ( tr( "125%" ), 125 );
116 m_pm_zoom-> insertItem ( tr( "150%" ), 150 ); 116 m_pm_zoom-> insertItem ( tr( "150%" ), 150 );
117 m_pm_zoom-> insertItem ( tr( "200%" ), 200 ); 117 m_pm_zoom-> insertItem ( tr( "200%" ), 200 );
118 118
119 connect ( m_pm_zoom, SIGNAL( activated ( int )), this, SLOT( setZoom ( int ))); 119 connect ( m_pm_zoom, SIGNAL( activated(int)), this, SLOT( setZoom(int)));
120 120
121 m_tb_tool = new QToolBar ( this ); 121 m_tb_tool = new QToolBar ( this );
122 122
123 new QToolButton ( Resource::loadIconSet ( "fileopen" ), tr( "Open..." ), QString::null, this, SLOT( openFile ( )), m_tb_tool, "open" ); 123 new QToolButton ( Resource::loadIconSet ( "fileopen" ), tr( "Open..." ), QString::null, this, SLOT( openFile()), m_tb_tool, "open" );
124 m_tb_tool-> addSeparator ( ); 124 m_tb_tool-> addSeparator ( );
125 m_to_find = new QToolButton ( Resource::loadIconSet ( "find" ), tr( "Find..." ), QString::null, this, SLOT( toggleFindBar ( )), m_tb_tool, "find" ); 125 m_to_find = new QToolButton ( Resource::loadIconSet ( "find" ), tr( "Find..." ), QString::null, this, SLOT( toggleFindBar()), m_tb_tool, "find" );
126 m_to_find-> setToggleButton ( true ); 126 m_to_find-> setToggleButton ( true );
127 m_tb_tool-> addSeparator ( ); 127 m_tb_tool-> addSeparator ( );
128 m_to_full = new QToolButton ( Resource::loadIconSet ( "fullscreen" ), tr( "Fullscreen" ), QString::null, this, SLOT( toggleFullscreen ( )), m_tb_tool, "fullscreen" ); 128 m_to_full = new QToolButton ( Resource::loadIconSet ( "fullscreen" ), tr( "Fullscreen" ), QString::null, this, SLOT( toggleFullscreen()), m_tb_tool, "fullscreen" );
129 m_to_full-> setToggleButton ( true ); 129 m_to_full-> setToggleButton ( true );
130 m_tb_tool-> addSeparator ( ); 130 m_tb_tool-> addSeparator ( );
131 new QToolButton ( Resource::loadIconSet ( "fastback" ), tr( "First page" ), QString::null, this, SLOT( firstPage ( )), m_tb_tool, "first" ); 131 new QToolButton ( Resource::loadIconSet ( "fastback" ), tr( "First page" ), QString::null, this, SLOT( firstPage()), m_tb_tool, "first" );
132 new QToolButton ( Resource::loadIconSet ( "back" ), tr( "Previous page" ), QString::null, this, SLOT( prevPage ( )), m_tb_tool, "prev" ); 132 new QToolButton ( Resource::loadIconSet ( "back" ), tr( "Previous page" ), QString::null, this, SLOT( prevPage()), m_tb_tool, "prev" );
133 new QToolButton ( Resource::loadIconSet ( "down" ), tr( "Goto page..." ), QString::null, this, SLOT( gotoPageDialog ( )), m_tb_tool, "goto" ); 133 new QToolButton ( Resource::loadIconSet ( "down" ), tr( "Goto page..." ), QString::null, this, SLOT( gotoPageDialog()), m_tb_tool, "goto" );
134 new QToolButton ( Resource::loadIconSet ( "forward" ), tr( "Next page" ), QString::null, this, SLOT( nextPage ( )), m_tb_tool, "next" ); 134 new QToolButton ( Resource::loadIconSet ( "forward" ), tr( "Next page" ), QString::null, this, SLOT( nextPage()), m_tb_tool, "next" );
135 new QToolButton ( Resource::loadIconSet ( "fastforward" ), tr( "Last page" ), QString::null, this, SLOT( lastPage ( )), m_tb_tool, "last" ); 135 new QToolButton ( Resource::loadIconSet ( "fastforward" ), tr( "Last page" ), QString::null, this, SLOT( lastPage()), m_tb_tool, "last" );
136 136
137 m_tb_find = new QToolBar ( this ); 137 m_tb_find = new QToolBar ( this );
138 addToolBar ( m_tb_find, "Search", QMainWindow::Top, true ); 138 addToolBar ( m_tb_find, "Search", QMainWindow::Top, true );
139 m_tb_find-> setHorizontalStretchable ( true ); 139 m_tb_find-> setHorizontalStretchable ( true );
140 m_tb_find-> hide ( ); 140 m_tb_find-> hide ( );
141 141
142 m_findedit = new QLineEdit ( m_tb_find, "findedit" ); 142 m_findedit = new QLineEdit ( m_tb_find, "findedit" );
143 m_tb_find-> setStretchableWidget ( m_findedit ); 143 m_tb_find-> setStretchableWidget ( m_findedit );
144 connect ( m_findedit, SIGNAL( textChanged ( const QString & )), this, SLOT( findText ( const QString & ))); 144 connect ( m_findedit, SIGNAL( textChanged(const QString&)), this, SLOT( findText(const QString&)));
145 145
146 new QToolButton ( Resource::loadIconSet ( "next" ), tr( "Next" ), QString::null, this, SLOT( findText ( )), m_tb_find, "findnext" ); 146 new QToolButton ( Resource::loadIconSet ( "next" ), tr( "Next" ), QString::null, this, SLOT( findText()), m_tb_find, "findnext" );
147 147
148 openFile ( ); 148 openFile ( );
149} 149}
150 150
151QPdfDlg::~QPdfDlg ( ) 151QPdfDlg::~QPdfDlg ( )
152{ 152{
153 delete m_doc; 153 delete m_doc;
154} 154}
155 155
156// vv Fullscreen handling (for broken QT-lib) [David Hedbor, www.eongames.com] 156// vv Fullscreen handling (for broken QT-lib) [David Hedbor, www.eongames.com]
157 157
158void QPdfDlg::resizeEvent ( QResizeEvent * ) 158void QPdfDlg::resizeEvent ( QResizeEvent * )
159{ 159{
160 if ( m_fullscreen && ( size ( ) != qApp-> desktop ( )-> size ( ))) 160 if ( m_fullscreen && ( size ( ) != qApp-> desktop ( )-> size ( )))
161 setFullscreen ( true ); 161 setFullscreen ( true );
162} 162}
163 163
164void QPdfDlg::focusInEvent ( QFocusEvent * ) 164void QPdfDlg::focusInEvent ( QFocusEvent * )
165{ 165{
166 if ( m_fullscreen ) 166 if ( m_fullscreen )
167 setFullscreen ( true ); 167 setFullscreen ( true );
168} 168}
169 169
170void QPdfDlg::toggleFullscreen ( ) 170void QPdfDlg::toggleFullscreen ( )
171{ 171{
172 if ( m_to_full-> isOn ( ) == m_fullscreen ) 172 if ( m_to_full-> isOn ( ) == m_fullscreen )
173 m_to_full-> setOn ( !m_fullscreen ); 173 m_to_full-> setOn ( !m_fullscreen );
174 174
175 m_fullscreen = !m_fullscreen; 175 m_fullscreen = !m_fullscreen;
176 setFullscreen ( m_fullscreen ); 176 setFullscreen ( m_fullscreen );
177} 177}
178 178
179void QPdfDlg::setFullscreen ( bool b ) 179void QPdfDlg::setFullscreen ( bool b )
180{ 180{
181 static QSize normalsize; 181 static QSize normalsize;
182 182
183 if ( b ) { 183 if ( b ) {
184 if ( !normalsize. isValid ( )) 184 if ( !normalsize. isValid ( ))
185 normalsize = size ( ); 185 normalsize = size ( );
186 186
187 setFixedSize ( qApp-> desktop ( )-> size ( )); 187 setFixedSize ( qApp-> desktop ( )-> size ( ));
188 showNormal ( ); 188 showNormal ( );
189 reparent ( 0, WStyle_Customize | WStyle_NoBorder, QPoint ( 0, 0 )); 189 reparent ( 0, WStyle_Customize | WStyle_NoBorder, QPoint ( 0, 0 ));
190 showFullScreen ( ); 190 showFullScreen ( );
191 } 191 }
192 else { 192 else {
193 showNormal ( ); 193 showNormal ( );
194 reparent ( 0, 0, QPoint ( 0, 0 )); 194 reparent ( 0, 0, QPoint ( 0, 0 ));
195 resize ( normalsize ); 195 resize ( normalsize );
196 showMaximized ( ); 196 showMaximized ( );
197 normalsize = QSize ( ); 197 normalsize = QSize ( );
198 } 198 }
199} 199}
200 200
201// ^^ Fullscreen handling (for broken QT-lib) 201// ^^ Fullscreen handling (for broken QT-lib)
202 202
203void QPdfDlg::setBusy ( bool b ) 203void QPdfDlg::setBusy ( bool b )
204{ 204{
205 if ( b != m_busy ) { 205 if ( b != m_busy ) {
206 m_busy = b; 206 m_busy = b;
207 207
208 m_outdev-> setBusy ( m_busy ); 208 m_outdev-> setBusy ( m_busy );
209 setEnabled ( !m_busy ); 209 setEnabled ( !m_busy );
210 } 210 }
211} 211}
212 212
213bool QPdfDlg::busy ( ) const 213bool QPdfDlg::busy ( ) const
214{ 214{
215 return m_busy; 215 return m_busy;
216} 216}
217 217
218 218
219void QPdfDlg::updateCaption ( ) 219void QPdfDlg::updateCaption ( )
220{ 220{
221 QString cap = ""; 221 QString cap = "";
222 222
223 if ( !m_currentdoc. isEmpty ( )) 223 if ( !m_currentdoc. isEmpty ( ))
224 cap = QString ( "%1 - " ). arg ( m_currentdoc ); 224 cap = QString ( "%1 - " ). arg ( m_currentdoc );
225 cap += "QPdf"; 225 cap += "QPdf";
226 226
227 setCaption ( cap ); 227 setCaption ( cap );
228} 228}
229 229
230 230
231void QPdfDlg::setZoom ( int id ) 231void QPdfDlg::setZoom ( int id )
232{ 232{
233 int dpi = 0; 233 int dpi = 0;
234 234
235 switch ( id ) { 235 switch ( id ) {
236 case 1: 236 case 1:
237 if ( m_doc && m_doc-> isOk ( )) 237 if ( m_doc && m_doc-> isOk ( ))
238 dpi = m_outdev-> visibleWidth ( ) * 72 / m_doc-> getPageWidth ( m_currentpage ); 238 dpi = m_outdev-> visibleWidth ( ) * 72 / m_doc-> getPageWidth ( m_currentpage );
239 break; 239 break;
240 240
241 case 2: 241 case 2:
242 if ( m_doc && m_doc-> isOk ( )) 242 if ( m_doc && m_doc-> isOk ( ))
243 dpi = QMIN( m_outdev-> visibleWidth ( ) * 72 / m_doc-> getPageWidth ( m_currentpage ), \ 243 dpi = QMIN( m_outdev-> visibleWidth ( ) * 72 / m_doc-> getPageWidth ( m_currentpage ), \
244 m_outdev-> visibleHeight ( ) * 72 / m_doc-> getPageHeight ( m_currentpage )); 244 m_outdev-> visibleHeight ( ) * 72 / m_doc-> getPageHeight ( m_currentpage ));
245 break; 245 break;
246 246
247 default: 247 default:
248 dpi = id * 72 / 100; 248 dpi = id * 72 / 100;
249 break; 249 break;
250 } 250 }
251 251
252 if ( dpi < 18 ) 252 if ( dpi < 18 )
253 dpi = 18; 253 dpi = 18;
254 if ( dpi > 216 ) 254 if ( dpi > 216 )
255 dpi = 216; 255 dpi = 216;
256 256
257 for ( uint i = 0; i < m_pm_zoom-> count ( ); i++ ) { 257 for ( uint i = 0; i < m_pm_zoom-> count ( ); i++ ) {
258 int xid = m_pm_zoom-> idAt ( i ); 258 int xid = m_pm_zoom-> idAt ( i );
259 m_pm_zoom-> setItemChecked ( xid, xid == id ); 259 m_pm_zoom-> setItemChecked ( xid, xid == id );
260 } 260 }
261 261
262 if ( dpi != m_zoom ) { 262 if ( dpi != m_zoom ) {
263 m_zoom = dpi; 263 m_zoom = dpi;
264 264
265 renderPage ( ); 265 renderPage ( );
266 } 266 }
267} 267}
268 268
269 269
270void QPdfDlg::gotoPageDialog ( ) 270void QPdfDlg::gotoPageDialog ( )
271{ 271{
272 QDialog *d = new QDialog ( this, "gotodlg", true ); 272 QDialog *d = new QDialog ( this, "gotodlg", true );
273 d-> setCaption ( tr( "Goto page" )); 273 d-> setCaption ( tr( "Goto page" ));
274 274
275 QBoxLayout *lay = new QVBoxLayout ( d, 4, 4 ); 275 QBoxLayout *lay = new QVBoxLayout ( d, 4, 4 );
276 276
277 QLabel *l = new QLabel ( tr( "Select from 1 .. %1:" ). arg ( m_pages ), d ); 277 QLabel *l = new QLabel ( tr( "Select from 1 .. %1:" ). arg ( m_pages ), d );
278 lay-> addWidget ( l ); 278 lay-> addWidget ( l );
279 279
280 QSpinBox *spin = new QSpinBox ( 1, m_pages, 1, d ); 280 QSpinBox *spin = new QSpinBox ( 1, m_pages, 1, d );
281 spin-> setValue ( m_currentpage ); 281 spin-> setValue ( m_currentpage );
282 spin-> setWrapping ( true ); 282 spin-> setWrapping ( true );
283 spin-> setButtonSymbols ( QSpinBox::PlusMinus ); 283 spin-> setButtonSymbols ( QSpinBox::PlusMinus );
284 lay-> addWidget ( spin ); 284 lay-> addWidget ( spin );
285 285
286 if ( d-> exec ( ) == QDialog::Accepted ) { 286 if ( d-> exec ( ) == QDialog::Accepted ) {
287 gotoPage ( spin-> value ( )); 287 gotoPage ( spin-> value ( ));
288 } 288 }
289 289
290 delete d; 290 delete d;
291} 291}
292 292
293void QPdfDlg::toggleFindBar ( ) 293void QPdfDlg::toggleFindBar ( )
294{ 294{
295 if ( m_to_find-> isOn ( ) == m_tb_find-> isVisible ( )) 295 if ( m_to_find-> isOn ( ) == m_tb_find-> isVisible ( ))
296 m_to_find-> setOn ( !m_tb_find-> isVisible ( )); 296 m_to_find-> setOn ( !m_tb_find-> isVisible ( ));
297 297
298 if ( m_tb_find-> isVisible ( )) { 298 if ( m_tb_find-> isVisible ( )) {
299 m_tb_find-> hide ( ); 299 m_tb_find-> hide ( );
300 m_outdev-> setFocus ( ); 300 m_outdev-> setFocus ( );
301 } 301 }
302 else { 302 else {
303 m_tb_find-> show ( ); 303 m_tb_find-> show ( );
304 m_findedit-> setFocus ( ); 304 m_findedit-> setFocus ( );
305 } 305 }
306} 306}
307 307
308void QPdfDlg::findText ( const QString &str ) 308void QPdfDlg::findText ( const QString &str )
309{ 309{
310 if ( !m_doc || !m_doc-> isOk ( ) || str. isEmpty ( )) 310 if ( !m_doc || !m_doc-> isOk ( ) || str. isEmpty ( ))
311 return; 311 return;
312 312
313 TextOutputDev *textOut = 0; 313 TextOutputDev *textOut = 0;
314 int pg = 0; 314 int pg = 0;
315 315
316 setBusy ( true ); 316 setBusy ( true );
317 317
318 int len = str. length ( ); 318 int len = str. length ( );
319 Unicode *u = new Unicode [len]; 319 Unicode *u = new Unicode [len];
320 for ( int i = 0; i < len; i++ ) 320 for ( int i = 0; i < len; i++ )
321 u [i] = str [i]. unicode ( ); 321 u [i] = str [i]. unicode ( );
322 322
323 int xMin = 0, yMin = 0, xMax = 0, yMax = 0; 323 int xMin = 0, yMin = 0, xMax = 0, yMax = 0;
324 QRect selr = m_outdev-> selection ( ); 324 QRect selr = m_outdev-> selection ( );
325 bool fromtop = true; 325 bool fromtop = true;
326 326
327 if ( selr. isValid ( )) { 327 if ( selr. isValid ( )) {
328 xMin = selr. right ( ); 328 xMin = selr. right ( );
329 yMin = selr. top ( ) + selr. height ( ) / 2; 329 yMin = selr. top ( ) + selr. height ( ) / 2;
330 fromtop = false; 330 fromtop = false;
331 } 331 }
332 332
333 if ( m_outdev-> findText ( u, len, fromtop, true, &xMin, &yMin, &xMax, &yMax )) 333 if ( m_outdev-> findText ( u, len, fromtop, true, &xMin, &yMin, &xMax, &yMax ))
334 goto found; 334 goto found;
335 335
336 qApp-> processEvents ( ); 336 qApp-> processEvents ( );
337 337
338 // search following pages 338 // search following pages
339 textOut = new TextOutputDev ( 0, gFalse, gFalse ); 339 textOut = new TextOutputDev ( 0, gFalse, gFalse );
340 if ( !textOut-> isOk ( )) 340 if ( !textOut-> isOk ( ))
341 goto done; 341 goto done;
342 342
343 qApp-> processEvents ( ); 343 qApp-> processEvents ( );
344 344
345 for ( pg = ( m_currentpage % m_pages ) + 1; pg != m_currentpage; pg = ( pg % m_pages ) + 1 ) { 345 for ( pg = ( m_currentpage % m_pages ) + 1; pg != m_currentpage; pg = ( pg % m_pages ) + 1 ) {
346 m_doc-> displayPage ( textOut, pg, 72, 0, gFalse ); 346 m_doc-> displayPage ( textOut, pg, 72, 0, gFalse );
347 347
348 fp_t xMin1, yMin1, xMax1, yMax1; 348 fp_t xMin1, yMin1, xMax1, yMax1;
349 349
350 qApp-> processEvents ( ); 350 qApp-> processEvents ( );
351 351
352 if ( textOut-> findText ( u, len, gTrue, gTrue, &xMin1, &yMin1, &xMax1, &yMax1 )) 352 if ( textOut-> findText ( u, len, gTrue, gTrue, &xMin1, &yMin1, &xMax1, &yMax1 ))
353 goto foundPage; 353 goto foundPage;
354 354
355 qApp-> processEvents ( ); 355 qApp-> processEvents ( );
356 } 356 }
357 357
358 // search current page ending at current selection 358 // search current page ending at current selection
359 if ( selr. isValid ( )) { 359 if ( selr. isValid ( )) {
360 xMax = selr. left ( ); 360 xMax = selr. left ( );
361 yMax = selr. top ( ) + selr. height ( ) / 2; 361 yMax = selr. top ( ) + selr. height ( ) / 2;
362 362
363 if ( m_outdev-> findText ( u, len, gTrue, gFalse, &xMin, &yMin, &xMax, &yMax )) 363 if ( m_outdev-> findText ( u, len, gTrue, gFalse, &xMin, &yMin, &xMax, &yMax ))
364 goto found; 364 goto found;
365 } 365 }
366 366
367 // not found 367 // not found
368 QMessageBox::information ( this, tr( "Find..." ), tr( "'%1' could not be found." ). arg ( str )); 368 QMessageBox::information ( this, tr( "Find..." ), tr( "'%1' could not be found." ). arg ( str ));
369 goto done; 369 goto done;
370 370
371foundPage: 371foundPage:
372 qApp-> processEvents ( ); 372 qApp-> processEvents ( );
373 373
374 gotoPage ( pg ); 374 gotoPage ( pg );
375 375
376 if ( !m_outdev-> findText ( u, len, gTrue, gTrue, &xMin, &yMin, &xMax, &yMax )) { 376 if ( !m_outdev-> findText ( u, len, gTrue, gTrue, &xMin, &yMin, &xMax, &yMax )) {
377 // this can happen if coalescing is bad 377 // this can happen if coalescing is bad
378 goto done; 378 goto done;
379 } 379 }
380 380
381found: 381found:
382 selr. setCoords ( xMin, yMin, xMax, yMax ); 382 selr. setCoords ( xMin, yMin, xMax, yMax );
383 m_outdev-> setSelection ( selr, true ); // this will emit QPEOutputDev::selectionChanged ( ) -> copyToClipboard ( ) 383 m_outdev-> setSelection ( selr, true ); // this will emit QPEOutputDev::selectionChanged ( ) -> copyToClipboard ( )
384 384
385 done: 385 done:
386 386
387 delete [] u; 387 delete [] u;
388 delete textOut; 388 delete textOut;
389 389
390 setBusy ( false ); 390 setBusy ( false );
391} 391}
392 392
393 393
394void QPdfDlg::findText ( ) 394void QPdfDlg::findText ( )
395{ 395{
396 findText ( m_findedit-> text ( )); 396 findText ( m_findedit-> text ( ));
397} 397}
398 398
399void QPdfDlg::copyToClipboard ( const QRect &r ) 399void QPdfDlg::copyToClipboard ( const QRect &r )
400{ 400{
401 if ( m_doc && m_doc-> isOk ( ) && m_doc-> okToCopy ( )) 401 if ( m_doc && m_doc-> isOk ( ) && m_doc-> okToCopy ( ))
402 qApp-> clipboard ( )-> setText ( m_outdev-> getText ( r )); 402 qApp-> clipboard ( )-> setText ( m_outdev-> getText ( r ));
403} 403}
404 404
405void QPdfDlg::firstPage ( ) 405void QPdfDlg::firstPage ( )
406{ 406{
407 gotoPage ( 1 ); 407 gotoPage ( 1 );
408} 408}
409 409
410void QPdfDlg::prevPage ( ) 410void QPdfDlg::prevPage ( )
411{ 411{
412 gotoPage ( m_currentpage - 1 ); 412 gotoPage ( m_currentpage - 1 );
413} 413}
414 414
415void QPdfDlg::nextPage ( ) 415void QPdfDlg::nextPage ( )
416{ 416{
417 gotoPage ( m_currentpage + 1 ); 417 gotoPage ( m_currentpage + 1 );
418} 418}
419 419
420void QPdfDlg::lastPage ( ) 420void QPdfDlg::lastPage ( )
421{ 421{
422 gotoPage ( m_pages ); 422 gotoPage ( m_pages );
423} 423}
424 424
425void QPdfDlg::gotoPage ( int n ) 425void QPdfDlg::gotoPage ( int n )
426{ 426{
427 if ( n < 1 ) 427 if ( n < 1 )
428 n = 1; 428 n = 1;
429 if ( n > m_pages ) 429 if ( n > m_pages )
430 n = m_pages; 430 n = m_pages;
431 431
432 if ( n != m_currentpage ) { 432 if ( n != m_currentpage ) {
433 m_currentpage = n; 433 m_currentpage = n;
434 434
435 renderPage ( ); 435 renderPage ( );
436 } 436 }
437} 437}
438 438
439void QPdfDlg::renderPage ( ) 439void QPdfDlg::renderPage ( )
440{ 440{
441 if ( m_renderok && m_doc && m_doc-> isOk ( )) { 441 if ( m_renderok && m_doc && m_doc-> isOk ( )) {
442 m_renderok = false; 442 m_renderok = false;
443 443
444 setBusy ( true ); 444 setBusy ( true );
445 m_doc-> displayPage ( m_outdev, m_currentpage, m_zoom, 0, true ); 445 m_doc-> displayPage ( m_outdev, m_currentpage, m_zoom, 0, true );
446 setBusy ( false ); 446 setBusy ( false );
447 447
448 m_outdev-> setPageCount ( m_currentpage, m_pages ); 448 m_outdev-> setPageCount ( m_currentpage, m_pages );
449 449
450 m_renderok = true; 450 m_renderok = true;
451 } 451 }
452} 452}
453 453
454void QPdfDlg::closeFileSelector ( ) 454void QPdfDlg::closeFileSelector ( )
455{ 455{
456 m_tb_menu-> show ( ); 456 m_tb_menu-> show ( );
457 m_tb_tool-> show ( ); 457 m_tb_tool-> show ( );
458 m_stack-> raiseWidget ( m_outdev ); 458 m_stack-> raiseWidget ( m_outdev );
459} 459}
460 460
461void QPdfDlg::openFile ( ) 461void QPdfDlg::openFile ( )
462{ 462{
463 m_tb_menu-> hide ( ); 463 m_tb_menu-> hide ( );
464 m_tb_tool-> hide ( ); 464 m_tb_tool-> hide ( );
465 m_tb_find-> hide ( ); 465 m_tb_find-> hide ( );
466 m_stack-> raiseWidget ( m_filesel ); 466 m_stack-> raiseWidget ( m_filesel );
467} 467}
468 468
469void QPdfDlg::openFile ( const QString &f ) 469void QPdfDlg::openFile ( const QString &f )
470{ 470{
471 DocLnk nf; 471 DocLnk nf;
472 nf. setType ( "application/pdf" ); 472 nf. setType ( "application/pdf" );
473 nf. setFile ( f ); 473 nf. setFile ( f );
474 QFileInfo fi ( f ); 474 QFileInfo fi ( f );
475 nf. setName ( fi. baseName ( )); 475 nf. setName ( fi. baseName ( ));
476 openFile ( nf ); 476 openFile ( nf );
477} 477}
478 478
479void QPdfDlg::openFile ( const DocLnk &f ) 479void QPdfDlg::openFile ( const DocLnk &f )
480{ 480{
481 QString fn = f. file ( ); 481 QString fn = f. file ( );
482 QFileInfo fi ( fn ); 482 QFileInfo fi ( fn );
483 483
484 if ( fi. exists ( )) { 484 if ( fi. exists ( )) {
485 delete m_doc; 485 delete m_doc;
486 486
487 m_doc = new PDFDoc ( new GString ( fn. local8Bit ( )), 0, 0 ); 487 m_doc = new PDFDoc ( new GString ( fn. local8Bit ( )), 0, 0 );
488 488
489 if ( m_doc-> isOk ( )) { 489 if ( m_doc-> isOk ( )) {
490 m_currentdoc = f. name ( ); 490 m_currentdoc = f. name ( );
491 int sep = m_currentdoc. findRev ( '/' ); 491 int sep = m_currentdoc. findRev ( '/' );
492 if ( sep > 0 ) 492 if ( sep > 0 )
493 m_currentdoc = m_currentdoc. mid ( sep + 1 ); 493 m_currentdoc = m_currentdoc. mid ( sep + 1 );
494 494
495 m_pages = m_doc-> getNumPages ( ); 495 m_pages = m_doc-> getNumPages ( );
496 m_currentpage = 0; 496 m_currentpage = 0;
497 497
498 QTimer::singleShot ( 0, this, SLOT( delayedInit ( ))); 498 QTimer::singleShot ( 0, this, SLOT( delayedInit()));
499 } 499 }
500 else { 500 else {
501 delete m_doc; 501 delete m_doc;
502 m_doc = 0; 502 m_doc = 0;
503 503
504 m_currentdoc = QString::null; 504 m_currentdoc = QString::null;
505 } 505 }
506 506
507 updateCaption ( ); 507 updateCaption ( );
508 } 508 }
509 else 509 else
510 QMessageBox::warning ( this, tr( "Error" ), tr( "File does not exist!" )); 510 QMessageBox::warning ( this, tr( "Error" ), tr( "File does not exist!" ));
511} 511}
512 512
513void QPdfDlg::setDocument ( const QString &f ) 513void QPdfDlg::setDocument ( const QString &f )
514{ 514{
515 if ( f. find ( ".desktop", 0, true ) == -1 ) 515 if ( f. find ( ".desktop", 0, true ) == -1 )
516 openFile ( f ); 516 openFile ( f );
517 else 517 else
518 openFile ( DocLnk ( f )); 518 openFile ( DocLnk ( f ));
519 519
520 closeFileSelector ( ); 520 closeFileSelector ( );
521} 521}
522 522
523void QPdfDlg::delayedInit ( ) 523void QPdfDlg::delayedInit ( )
524 { 524 {
525 closeFileSelector ( ); 525 closeFileSelector ( );
526 526
527 m_currentpage = 0; 527 m_currentpage = 0;
528 m_zoom = 0; 528 m_zoom = 0;
529 m_renderok = false; 529 m_renderok = false;
530 530
531 setZoom ( 100 ); 531 setZoom ( 100 );
532 gotoPage ( 1 ); 532 gotoPage ( 1 );
533 533
534 m_renderok = true; 534 m_renderok = true;
535 535
536 renderPage ( ); 536 renderPage ( );
537 537
538 m_outdev-> setFocus ( ); 538 m_outdev-> setFocus ( );
539} 539}
540 540
diff --git a/x11/libqpe-x11/qpe/qpeapplication.cpp b/x11/libqpe-x11/qpe/qpeapplication.cpp
index 0fce355..3cb8faf 100644
--- a/x11/libqpe-x11/qpe/qpeapplication.cpp
+++ b/x11/libqpe-x11/qpe/qpeapplication.cpp
@@ -1,796 +1,796 @@
1#define QTOPIA_INTERNAL_LANGLIST 1#define QTOPIA_INTERNAL_LANGLIST
2 2
3#include <stdio.h> 3#include <stdio.h>
4#include <stdlib.h> 4#include <stdlib.h>
5#include <unistd.h> 5#include <unistd.h>
6#include <sys/file.h> 6#include <sys/file.h>
7 7
8 8
9#include <qdir.h> 9#include <qdir.h>
10#include <qdialog.h> 10#include <qdialog.h>
11#include <qdragobject.h> 11#include <qdragobject.h>
12#include <qevent.h> 12#include <qevent.h>
13#include <qlabel.h> 13#include <qlabel.h>
14#include <qlist.h> 14#include <qlist.h>
15#include <qtextstream.h> 15#include <qtextstream.h>
16#include <qtextcodec.h> 16#include <qtextcodec.h>
17#include <qpalette.h> 17#include <qpalette.h>
18#include <qptrdict.h> 18#include <qptrdict.h>
19#include <qregexp.h> 19#include <qregexp.h>
20#include <qtimer.h> 20#include <qtimer.h>
21 21
22#include <qpe/custom.h> 22#include <qpe/custom.h>
23#include <qpe/alarmserver.h> 23#include <qpe/alarmserver.h>
24#include <qpe/applnk.h> 24#include <qpe/applnk.h>
25#include <qpe/qpemenubar.h> 25#include <qpe/qpemenubar.h>
26#include <qpe/textcodecinterface.h> 26#include <qpe/textcodecinterface.h>
27#include <qpe/imagecodecinterface.h> 27#include <qpe/imagecodecinterface.h>
28#include <qpe/qlibrary.h> 28#include <qpe/qlibrary.h>
29#include <qpe/qpestyle.h> 29#include <qpe/qpestyle.h>
30#include <qpe/styleinterface.h> 30#include <qpe/styleinterface.h>
31#include <qpe/global.h> 31#include <qpe/global.h>
32#include <qpe/resource.h> 32#include <qpe/resource.h>
33#include <qpe/config.h> 33#include <qpe/config.h>
34#include <qpe/network.h> 34#include <qpe/network.h>
35 35
36#include <qpe/qpeapplication.h> 36#include <qpe/qpeapplication.h>
37#include <qpe/timestring.h> 37#include <qpe/timestring.h>
38#include <qpe/qcopenvelope_qws.h> 38#include <qpe/qcopenvelope_qws.h>
39 39
40 40
41#include <X11/Xlib.h> 41#include <X11/Xlib.h>
42#include <X11/Xutil.h> 42#include <X11/Xutil.h>
43 43
44const int XKeyPress = KeyPress; 44const int XKeyPress = KeyPress;
45const int XKeyRelease = KeyRelease; 45const int XKeyRelease = KeyRelease;
46#undef KeyPress 46#undef KeyPress
47#undef KeyRelease 47#undef KeyRelease
48 48
49namespace { 49namespace {
50 struct QCopRec{ 50 struct QCopRec{
51 QCopRec( const QCString& ch, const QCString& msg, const QByteArray& ar ) 51 QCopRec( const QCString& ch, const QCString& msg, const QByteArray& ar )
52 : channel(ch), message(msg), data(ar) { 52 : channel(ch), message(msg), data(ar) {
53 53
54 } 54 }
55 QCString channel; 55 QCString channel;
56 QCString message; 56 QCString message;
57 QByteArray data; 57 QByteArray data;
58 }; 58 };
59}; 59};
60 60
61 61
62class QPEApplication::Private { 62class QPEApplication::Private {
63public: 63public:
64 Private(); 64 Private();
65 ~Private(); 65 ~Private();
66 void enqueueQCop( const QCString& ch, const QCString& msg, 66 void enqueueQCop( const QCString& ch, const QCString& msg,
67 const QByteArray& ); 67 const QByteArray& );
68 void sendQCopQ(); 68 void sendQCopQ();
69 static void show_mx(QWidget* mw, bool nomaximize ); 69 static void show_mx(QWidget* mw, bool nomaximize );
70 void show( QWidget* mw, bool nomax ); 70 void show( QWidget* mw, bool nomax );
71 void loadTextCodecs(); 71 void loadTextCodecs();
72 void loadImageCodecs(); 72 void loadImageCodecs();
73 73
74 int kbgrabber; 74 int kbgrabber;
75 int presstimer; 75 int presstimer;
76 76
77 bool rightpressed : 1; 77 bool rightpressed : 1;
78 bool kbregrab : 1; 78 bool kbregrab : 1;
79 bool notbusysent : 1; 79 bool notbusysent : 1;
80 bool preloaded : 1; 80 bool preloaded : 1;
81 bool forceshow : 1; 81 bool forceshow : 1;
82 bool nomaximize : 1; 82 bool nomaximize : 1;
83 bool keep_running : 1; 83 bool keep_running : 1;
84 84
85 QWidget* presswidget; 85 QWidget* presswidget;
86 QPoint presspos; 86 QPoint presspos;
87 QWidget* qpe_main_widget; 87 QWidget* qpe_main_widget;
88 QString appName; 88 QString appName;
89 QString styleName; 89 QString styleName;
90 QString decorationName; 90 QString decorationName;
91 Atom wm_delete_window; 91 Atom wm_delete_window;
92 Atom wm_take_focus; 92 Atom wm_take_focus;
93 Atom wm_context_help; 93 Atom wm_context_help;
94 Atom wm_context_accept; 94 Atom wm_context_accept;
95 Atom wm_protocols; 95 Atom wm_protocols;
96 96
97private: 97private:
98 QList<QCopRec> qcopq; 98 QList<QCopRec> qcopq;
99}; 99};
100QPEApplication::Private::~Private() { 100QPEApplication::Private::~Private() {
101} 101}
102QPEApplication::Private::Private() 102QPEApplication::Private::Private()
103 : kbgrabber(0 ), presstimer(0 ), rightpressed( FALSE ), kbregrab( FALSE ), notbusysent( FALSE ), 103 : kbgrabber(0 ), presstimer(0 ), rightpressed( FALSE ), kbregrab( FALSE ), notbusysent( FALSE ),
104 preloaded( FALSE ), forceshow( FALSE ), nomaximize( FALSE ), keep_running( TRUE ), 104 preloaded( FALSE ), forceshow( FALSE ), nomaximize( FALSE ), keep_running( TRUE ),
105 presswidget( 0 ), qpe_main_widget(0 ) { 105 presswidget( 0 ), qpe_main_widget(0 ) {
106 106
107 qcopq.setAutoDelete( TRUE ); 107 qcopq.setAutoDelete( TRUE );
108} 108}
109void QPEApplication::Private::enqueueQCop( const QCString& chan, const QCString& msg, 109void QPEApplication::Private::enqueueQCop( const QCString& chan, const QCString& msg,
110 const QByteArray& ar ) { 110 const QByteArray& ar ) {
111 qcopq.append( new QCopRec(chan, msg, ar ) ); 111 qcopq.append( new QCopRec(chan, msg, ar ) );
112} 112}
113void QPEApplication::Private::sendQCopQ() { 113void QPEApplication::Private::sendQCopQ() {
114 QCopRec* r; 114 QCopRec* r;
115 for ( r = qcopq.first(); r; r = qcopq.next() ) { 115 for ( r = qcopq.first(); r; r = qcopq.next() ) {
116 QCopChannel::sendLocally( r->channel, r->message, r->data ); 116 QCopChannel::sendLocally( r->channel, r->message, r->data );
117 } 117 }
118 qcopq.clear(); 118 qcopq.clear();
119} 119}
120void QPEApplication::Private::show_mx(QWidget* mw, bool nomaximize ) { 120void QPEApplication::Private::show_mx(QWidget* mw, bool nomaximize ) {
121 if (mw->layout() && mw->inherits("QDialog") ) { 121 if (mw->layout() && mw->inherits("QDialog") ) {
122 QPEApplication::showDialog( (QDialog*)mw, nomaximize ); 122 QPEApplication::showDialog( (QDialog*)mw, nomaximize );
123 }else { 123 }else {
124 if (!nomaximize ) 124 if (!nomaximize )
125 mw->showMaximized(); 125 mw->showMaximized();
126 else 126 else
127 mw->show(); 127 mw->show();
128 } 128 }
129} 129}
130void QPEApplication::Private::show( QWidget* mw, bool nomax ) { 130void QPEApplication::Private::show( QWidget* mw, bool nomax ) {
131 nomaximize = nomax; 131 nomaximize = nomax;
132 qpe_main_widget = mw; 132 qpe_main_widget = mw;
133 133
134 sendQCopQ(); 134 sendQCopQ();
135 135
136 if ( preloaded ) { 136 if ( preloaded ) {
137 if (forceshow ) 137 if (forceshow )
138 show_mx(mw, nomax ); 138 show_mx(mw, nomax );
139 }else if ( keep_running ) 139 }else if ( keep_running )
140 show_mx( mw, nomax ); 140 show_mx( mw, nomax );
141} 141}
142void QPEApplication::Private::loadTextCodecs() { 142void QPEApplication::Private::loadTextCodecs() {
143 QString path = QPEApplication::qpeDir() + "/plugins/textcodecs"; 143 QString path = QPEApplication::qpeDir() + "/plugins/textcodecs";
144 QDir dir( path, "lib*.so" ); 144 QDir dir( path, "lib*.so" );
145 QStringList list = dir.entryList(); 145 QStringList list = dir.entryList();
146 QStringList::Iterator it; 146 QStringList::Iterator it;
147 for ( it = list.begin(); it != list.end(); ++it ) { 147 for ( it = list.begin(); it != list.end(); ++it ) {
148 TextCodecInterface *iface = 0; 148 TextCodecInterface *iface = 0;
149 QLibrary *lib = new QLibrary( path + "/" + *it ); 149 QLibrary *lib = new QLibrary( path + "/" + *it );
150 if ( lib->queryInterface( IID_QtopiaTextCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) { 150 if ( lib->queryInterface( IID_QtopiaTextCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) {
151 QValueList<int> mibs = iface->mibEnums(); 151 QValueList<int> mibs = iface->mibEnums();
152 for (QValueList<int>::ConstIterator i = mibs.begin(); i != mibs.end(); ++i) { 152 for (QValueList<int>::ConstIterator i = mibs.begin(); i != mibs.end(); ++i) {
153 (void)iface->createForMib(*i); 153 (void)iface->createForMib(*i);
154 // ### it exists now; need to remember if we can delete it 154 // ### it exists now; need to remember if we can delete it
155 } 155 }
156 } 156 }
157 else { 157 else {
158 lib->unload(); 158 lib->unload();
159 delete lib; 159 delete lib;
160 } 160 }
161 } 161 }
162} 162}
163void QPEApplication::Private::loadImageCodecs() { 163void QPEApplication::Private::loadImageCodecs() {
164 QString path = QPEApplication::qpeDir() + "/plugins/imagecodecs"; 164 QString path = QPEApplication::qpeDir() + "/plugins/imagecodecs";
165 QDir dir( path, "lib*.so" ); 165 QDir dir( path, "lib*.so" );
166 QStringList list = dir.entryList(); 166 QStringList list = dir.entryList();
167 QStringList::Iterator it; 167 QStringList::Iterator it;
168 for ( it = list.begin(); it != list.end(); ++it ) { 168 for ( it = list.begin(); it != list.end(); ++it ) {
169 ImageCodecInterface *iface = 0; 169 ImageCodecInterface *iface = 0;
170 QLibrary *lib = new QLibrary( path + "/" + *it ); 170 QLibrary *lib = new QLibrary( path + "/" + *it );
171 if ( lib->queryInterface( IID_QtopiaImageCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) { 171 if ( lib->queryInterface( IID_QtopiaImageCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) {
172 QStringList formats = iface->keys(); 172 QStringList formats = iface->keys();
173 for (QStringList::ConstIterator i = formats.begin(); i != formats.end(); ++i) { 173 for (QStringList::ConstIterator i = formats.begin(); i != formats.end(); ++i) {
174 (void)iface->installIOHandler(*i); 174 (void)iface->installIOHandler(*i);
175 // ### it exists now; need to remember if we can delete it 175 // ### it exists now; need to remember if we can delete it
176 } 176 }
177 } 177 }
178 else { 178 else {
179 lib->unload(); 179 lib->unload();
180 delete lib; 180 delete lib;
181 } 181 }
182 } 182 }
183} 183}
184 184
185// The Help System hook 185// The Help System hook
186namespace { 186namespace {
187 class ResourceMimeFactory : public QMimeSourceFactory 187 class ResourceMimeFactory : public QMimeSourceFactory
188 { 188 {
189 public: 189 public:
190 ResourceMimeFactory(); 190 ResourceMimeFactory();
191 ~ResourceMimeFactory(); 191 ~ResourceMimeFactory();
192 const QMimeSource* data( const QString& abs_name )const; 192 const QMimeSource* data( const QString& abs_name )const;
193 }; 193 };
194 ResourceMimeFactory::ResourceMimeFactory() 194 ResourceMimeFactory::ResourceMimeFactory()
195 { 195 {
196 setFilePath( Global::helpPath() ); 196 setFilePath( Global::helpPath() );
197 setExtensionType( "html", "text/html;charset=UTF-8" ); 197 setExtensionType( "html", "text/html;charset=UTF-8" );
198 } 198 }
199 ResourceMimeFactory::~ResourceMimeFactory() { 199 ResourceMimeFactory::~ResourceMimeFactory() {
200 } 200 }
201 201
202 const QMimeSource* ResourceMimeFactory::data( const QString& abs_name ) const 202 const QMimeSource* ResourceMimeFactory::data( const QString& abs_name ) const
203 { 203 {
204 const QMimeSource * r = QMimeSourceFactory::data( abs_name ); 204 const QMimeSource * r = QMimeSourceFactory::data( abs_name );
205 if ( !r ) { 205 if ( !r ) {
206 int sl = abs_name.length(); 206 int sl = abs_name.length();
207 do { 207 do {
208 sl = abs_name.findRev( '/', sl - 1 ); 208 sl = abs_name.findRev( '/', sl - 1 );
209 QString name = sl >= 0 ? abs_name.mid( sl + 1 ) : abs_name; 209 QString name = sl >= 0 ? abs_name.mid( sl + 1 ) : abs_name;
210 int dot = name.findRev( '.' ); 210 int dot = name.findRev( '.' );
211 if ( dot >= 0 ) 211 if ( dot >= 0 )
212 name = name.left( dot ); 212 name = name.left( dot );
213 QImage img = Resource::loadImage( name ); 213 QImage img = Resource::loadImage( name );
214 if ( !img.isNull() ) 214 if ( !img.isNull() )
215 r = new QImageDrag( img ); 215 r = new QImageDrag( img );
216 } 216 }
217 while ( !r && sl > 0 ); 217 while ( !r && sl > 0 );
218 } 218 }
219 return r; 219 return r;
220 }; 220 };
221}; 221};
222// QPEApplication 222// QPEApplication
223QPEApplication::~QPEApplication() { 223QPEApplication::~QPEApplication() {
224 qWarning("~QPEApplication"); 224 qWarning("~QPEApplication");
225 ungrabKeyboard(); 225 ungrabKeyboard();
226 qWarning("UngrabKeyboard"); 226 qWarning("UngrabKeyboard");
227 227
228// delete m_sys; 228// delete m_sys;
229// delete m_pid; 229// delete m_pid;
230 230
231 delete d; 231 delete d;
232} 232}
233QPEApplication::QPEApplication(int &arg, char** argv, Type t) 233QPEApplication::QPEApplication(int &arg, char** argv, Type t)
234 : QApplication( arg, argv, t ) { 234 : QApplication( arg, argv, t ) {
235 d = new Private; 235 d = new Private;
236 d->loadTextCodecs(); 236 d->loadTextCodecs();
237 d->loadImageCodecs(); 237 d->loadImageCodecs();
238 238
239 // Init X-Atom 239 // Init X-Atom
240 Atom *atoms[5]; 240 Atom *atoms[5];
241 Atom atoms_re[5]; 241 Atom atoms_re[5];
242 char* names[5]; 242 char* names[5];
243 int n = 0; 243 int n = 0;
244 atoms[n] = &d->wm_delete_window; 244 atoms[n] = &d->wm_delete_window;
245 names[n++] = "WM_DELETE_WINDOW"; 245 names[n++] = "WM_DELETE_WINDOW";
246 246
247 atoms[n] = &d->wm_take_focus; 247 atoms[n] = &d->wm_take_focus;
248 names[n++] = "WM_TAKE_FOCUS"; 248 names[n++] = "WM_TAKE_FOCUS";
249 249
250 atoms[n] = &d->wm_context_help; 250 atoms[n] = &d->wm_context_help;
251 names[n++] = "_NET_WM_CONTEXT_HELP"; 251 names[n++] = "_NET_WM_CONTEXT_HELP";
252 252
253 atoms[n] = &d->wm_context_accept; 253 atoms[n] = &d->wm_context_accept;
254 names[n++] = "_NET_WM_CONTEXT_ACCEPT"; 254 names[n++] = "_NET_WM_CONTEXT_ACCEPT";
255 255
256 atoms[n] = &d->wm_protocols; 256 atoms[n] = &d->wm_protocols;
257 names[n++] = "WM_PROTOCOLS"; 257 names[n++] = "WM_PROTOCOLS";
258 258
259 XInternAtoms( qt_xdisplay(), names, n, FALSE, atoms_re); 259 XInternAtoms( qt_xdisplay(), names, n, FALSE, atoms_re);
260 // now copy the values over to the properties 260 // now copy the values over to the properties
261 for (int i = 0; i < n; i++ ) 261 for (int i = 0; i < n; i++ )
262 *atoms[i] = atoms_re[i]; 262 *atoms[i] = atoms_re[i];
263 // done with X11 Stuff 263 // done with X11 Stuff
264 264
265 int dw = desktop()->width(); 265 int dw = desktop()->width();
266 if ( dw < 200 ) { 266 if ( dw < 200 ) {
267 setFont( QFont( "helvetica", 8 ) ); 267 setFont( QFont( "helvetica", 8 ) );
268 AppLnk::setSmallIconSize( 10 ); 268 AppLnk::setSmallIconSize( 10 );
269 AppLnk::setBigIconSize( 28 ); 269 AppLnk::setBigIconSize( 28 );
270 }else if ( dw > 600 ) { 270 }else if ( dw > 600 ) {
271 setFont( QFont( "helvetica", 12 ) ); 271 setFont( QFont( "helvetica", 12 ) );
272 AppLnk::setSmallIconSize( 24 ); 272 AppLnk::setSmallIconSize( 24 );
273 AppLnk::setBigIconSize( 48 ); 273 AppLnk::setBigIconSize( 48 );
274 }else if ( dw > 200 ) { 274 }else if ( dw > 200 ) {
275 setFont( QFont( "helvetica", 10 ) ); 275 setFont( QFont( "helvetica", 10 ) );
276 AppLnk::setSmallIconSize( 16 ); 276 AppLnk::setSmallIconSize( 16 );
277 AppLnk::setBigIconSize( 32 ); 277 AppLnk::setBigIconSize( 32 );
278 } 278 }
279 QMimeSourceFactory::setDefaultFactory( new ResourceMimeFactory ); 279 QMimeSourceFactory::setDefaultFactory( new ResourceMimeFactory );
280 280
281 connect( this, SIGNAL( lastWindowClosed() ), this, SLOT(hideOrQuit() ) ); 281 connect( this, SIGNAL( lastWindowClosed() ), this, SLOT(hideOrQuit() ) );
282 282
283 QString qcopfn( "/tmp/qcop-msg-" ); 283 QString qcopfn( "/tmp/qcop-msg-" );
284 qcopfn += QString( argv[0] ); // append command name to the QCOP name 284 qcopfn += QString( argv[0] ); // append command name to the QCOP name
285 QFile file( qcopfn ); 285 QFile file( qcopfn );
286 if (file.open(IO_ReadOnly ) ) { 286 if (file.open(IO_ReadOnly ) ) {
287 flock( file.handle(), LOCK_EX ); 287 flock( file.handle(), LOCK_EX );
288 } 288 }
289 289
290 /* Hmmm damn we need to make the parent 0l otherwise it get's deleted 290 /* Hmmm damn we need to make the parent 0l otherwise it get's deleted
291 * past the QApplication 291 * past the QApplication
292 */ 292 */
293 m_sys = new QCopChannel( "QPE/System", 0l); 293 m_sys = new QCopChannel( "QPE/System", 0l);
294 connect(m_sys, SIGNAL( received( const QCString&, const QByteArray& ) ), 294 connect(m_sys, SIGNAL( received(const QCString&,const QByteArray&) ),
295 this, SLOT(systemMessage( const QCString&, const QByteArray& ) ) ); 295 this, SLOT(systemMessage(const QCString&,const QByteArray&) ) );
296 296
297 // private channel QPE/Application/appname 297 // private channel QPE/Application/appname
298 QCString channel = QCString( argv[0] ); 298 QCString channel = QCString( argv[0] );
299 channel.replace( QRegExp( ".*/"), "" ); 299 channel.replace( QRegExp( ".*/"), "" );
300 d->appName = channel; 300 d->appName = channel;
301 channel = "QPE/Application/"+ channel; 301 channel = "QPE/Application/"+ channel;
302 m_pid = new QCopChannel( channel, 0l ); 302 m_pid = new QCopChannel( channel, 0l );
303 connect(m_pid, SIGNAL( received( const QCString&, const QByteArray& ) ), 303 connect(m_pid, SIGNAL( received(const QCString&,const QByteArray&) ),
304 this, SLOT( pidMessage( const QCString&, const QByteArray& ) ) ); 304 this, SLOT( pidMessage(const QCString&,const QByteArray&) ) );
305 305
306 // read the Pre QCOP Stuff from the file 306 // read the Pre QCOP Stuff from the file
307 if ( file.isOpen() ) { 307 if ( file.isOpen() ) {
308 d->keep_running = FALSE; 308 d->keep_running = FALSE;
309 QDataStream ds( &file ); 309 QDataStream ds( &file );
310 QCString chanel, message; 310 QCString chanel, message;
311 QByteArray data; 311 QByteArray data;
312 while (!ds.atEnd() ) { 312 while (!ds.atEnd() ) {
313 ds >> chanel >> message >> data; 313 ds >> chanel >> message >> data;
314 d->enqueueQCop( chanel, message, data ); 314 d->enqueueQCop( chanel, message, data );
315 } 315 }
316 flock( file.handle(), LOCK_UN ); 316 flock( file.handle(), LOCK_UN );
317 file.close(); 317 file.close();
318 file.remove(); 318 file.remove();
319 } 319 }
320 320
321 // read in some stuff from the command line 321 // read in some stuff from the command line
322 // we do not have setArgs so we need to take 322 // we do not have setArgs so we need to take
323 // care of that 323 // care of that
324 for ( int a = 0; a < arg; a++ ) { 324 for ( int a = 0; a < arg; a++ ) {
325 if ( qstrcmp( argv[a], "-preload" ) == 0 ) { 325 if ( qstrcmp( argv[a], "-preload" ) == 0 ) {
326 d->preloaded = TRUE; 326 d->preloaded = TRUE;
327 }else if ( qstrcmp( argv[a ] , "-preload-show" ) == 0 ) { 327 }else if ( qstrcmp( argv[a ] , "-preload-show" ) == 0 ) {
328 d->preloaded = TRUE; 328 d->preloaded = TRUE;
329 d->forceshow = TRUE; 329 d->forceshow = TRUE;
330 } 330 }
331 } 331 }
332 initTranslations(); 332 initTranslations();
333 applyStyle(); 333 applyStyle();
334 334
335 if ( type() == GuiServer ) 335 if ( type() == GuiServer )
336 ; 336 ;
337 337
338 installEventFilter( this ); 338 installEventFilter( this );
339 QPEMenuToolFocusManager::initialize(); 339 QPEMenuToolFocusManager::initialize();
340} 340}
341void QPEApplication::initTranslations() { 341void QPEApplication::initTranslations() {
342 // Translations add it 342 // Translations add it
343 QStringList langs = Global::languageList(); 343 QStringList langs = Global::languageList();
344 for ( QStringList::ConstIterator it = langs.begin(); it != langs.end(); ++it ) { 344 for ( QStringList::ConstIterator it = langs.begin(); it != langs.end(); ++it ) {
345 QString lang = *it; 345 QString lang = *it;
346 346
347 QTranslator * trans; 347 QTranslator * trans;
348 QString tfn; 348 QString tfn;
349 349
350 trans = new QTranslator( this ); 350 trans = new QTranslator( this );
351 tfn = qpeDir() + "/i18n/" + lang + "/libqpe.qm"; 351 tfn = qpeDir() + "/i18n/" + lang + "/libqpe.qm";
352 if ( trans->load( tfn ) ) 352 if ( trans->load( tfn ) )
353 installTranslator( trans ); 353 installTranslator( trans );
354 else 354 else
355 delete trans; 355 delete trans;
356 356
357 trans = new QTranslator( this ); 357 trans = new QTranslator( this );
358 tfn = qpeDir() + "/i18n/" + lang + "/" + d->appName + ".qm"; 358 tfn = qpeDir() + "/i18n/" + lang + "/" + d->appName + ".qm";
359 if ( trans->load( tfn ) ) 359 if ( trans->load( tfn ) )
360 installTranslator( trans ); 360 installTranslator( trans );
361 else 361 else
362 delete trans; 362 delete trans;
363 } 363 }
364} 364}
365QString QPEApplication::qpeDir() { 365QString QPEApplication::qpeDir() {
366 const char * base = getenv( "OPIEDIR" ); 366 const char * base = getenv( "OPIEDIR" );
367 if ( base ) 367 if ( base )
368 return QString( base ) + "/"; 368 return QString( base ) + "/";
369 369
370 return QString( "../" ); 370 return QString( "../" );
371} 371}
372QString QPEApplication::documentDir() { 372QString QPEApplication::documentDir() {
373 const char* base = getenv( "HOME"); 373 const char* base = getenv( "HOME");
374 if ( base ) 374 if ( base )
375 return QString( base ) + "/Documents"; 375 return QString( base ) + "/Documents";
376 376
377 return QString( "../Documents" ); 377 return QString( "../Documents" );
378} 378}
379void QPEApplication::applyStyle() { 379void QPEApplication::applyStyle() {
380 Config config( "qpe" ); 380 Config config( "qpe" );
381 381
382 config.setGroup( "Appearance" ); 382 config.setGroup( "Appearance" );
383 383
384 // Widget style 384 // Widget style
385 QString style = config.readEntry( "Style", "Light" ); 385 QString style = config.readEntry( "Style", "Light" );
386 internalSetStyle( style ); 386 internalSetStyle( style );
387 387
388 // Colors 388 // Colors
389 QColor bgcolor( config.readEntry( "Background", "#E5E1D5" ) ); 389 QColor bgcolor( config.readEntry( "Background", "#E5E1D5" ) );
390 QColor btncolor( config.readEntry( "Button", "#D6CDBB" ) ); 390 QColor btncolor( config.readEntry( "Button", "#D6CDBB" ) );
391 QPalette pal( btncolor, bgcolor ); 391 QPalette pal( btncolor, bgcolor );
392 QString color = config.readEntry( "Highlight", "#800000" ); 392 QString color = config.readEntry( "Highlight", "#800000" );
393 pal.setColor( QColorGroup::Highlight, QColor( color ) ); 393 pal.setColor( QColorGroup::Highlight, QColor( color ) );
394 color = config.readEntry( "HighlightedText", "#FFFFFF" ); 394 color = config.readEntry( "HighlightedText", "#FFFFFF" );
395 pal.setColor( QColorGroup::HighlightedText, QColor( color ) ); 395 pal.setColor( QColorGroup::HighlightedText, QColor( color ) );
396 color = config.readEntry( "Text", "#000000" ); 396 color = config.readEntry( "Text", "#000000" );
397 pal.setColor( QColorGroup::Text, QColor( color ) ); 397 pal.setColor( QColorGroup::Text, QColor( color ) );
398 color = config.readEntry( "ButtonText", "#000000" ); 398 color = config.readEntry( "ButtonText", "#000000" );
399 pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) ); 399 pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) );
400 color = config.readEntry( "Base", "#FFFFFF" ); 400 color = config.readEntry( "Base", "#FFFFFF" );
401 pal.setColor( QColorGroup::Base, QColor( color ) ); 401 pal.setColor( QColorGroup::Base, QColor( color ) );
402 402
403 pal.setColor( QPalette::Disabled, QColorGroup::Text, 403 pal.setColor( QPalette::Disabled, QColorGroup::Text,
404 pal.color( QPalette::Active, QColorGroup::Background ).dark() ); 404 pal.color( QPalette::Active, QColorGroup::Background ).dark() );
405 405
406 setPalette( pal, TRUE ); 406 setPalette( pal, TRUE );
407 407
408 408
409 409
410 // Font 410 // Font
411 QString ff = config.readEntry( "FontFamily", font().family() ); 411 QString ff = config.readEntry( "FontFamily", font().family() );
412 int fs = config.readNumEntry( "FontSize", font().pointSize() ); 412 int fs = config.readNumEntry( "FontSize", font().pointSize() );
413 setFont( QFont(ff, fs) ); 413 setFont( QFont(ff, fs) );
414} 414}
415int QPEApplication::defaultRotation() { 415int QPEApplication::defaultRotation() {
416 return 0; 416 return 0;
417} 417}
418void QPEApplication::setDefaultRotation(int r ) { 418void QPEApplication::setDefaultRotation(int r ) {
419 419
420} 420}
421void QPEApplication::grabKeyboard() { 421void QPEApplication::grabKeyboard() {
422 QPEApplication::Private * d = ( ( QPEApplication* ) qApp ) ->d; 422 QPEApplication::Private * d = ( ( QPEApplication* ) qApp ) ->d;
423 if ( qApp->type() == QApplication::GuiServer ) 423 if ( qApp->type() == QApplication::GuiServer )
424 d->kbgrabber = 0; 424 d->kbgrabber = 0;
425 else { 425 else {
426 QCopEnvelope e( "QPE/System", "grabKeyboard(QString)" ); 426 QCopEnvelope e( "QPE/System", "grabKeyboard(QString)" );
427 e << d->appName; 427 e << d->appName;
428 428
429 d->kbgrabber = 2; // me 429 d->kbgrabber = 2; // me
430 } 430 }
431} 431}
432void QPEApplication::ungrabKeyboard() { 432void QPEApplication::ungrabKeyboard() {
433 QPEApplication::Private * d = ( ( QPEApplication* ) qApp ) ->d; 433 QPEApplication::Private * d = ( ( QPEApplication* ) qApp ) ->d;
434 if ( d->kbgrabber == 2 ) { 434 if ( d->kbgrabber == 2 ) {
435 QCopEnvelope e( "QPE/System", "grabKeyboard(QString)" ); 435 QCopEnvelope e( "QPE/System", "grabKeyboard(QString)" );
436 e << QString::null; 436 e << QString::null;
437 437
438 d->kbregrab = FALSE; 438 d->kbregrab = FALSE;
439 d->kbgrabber = 0; 439 d->kbgrabber = 0;
440 } 440 }
441} 441}
442void QPEApplication::showMainWidget( QWidget* wid, bool b) { 442void QPEApplication::showMainWidget( QWidget* wid, bool b) {
443 d->show(wid, b ); 443 d->show(wid, b );
444} 444}
445void QPEApplication::showMainDocumentWidget( QWidget* mw, bool m) { 445void QPEApplication::showMainDocumentWidget( QWidget* mw, bool m) {
446 if ( mw && argc() == 2 ) 446 if ( mw && argc() == 2 )
447 Global::setDocument( mw, QString::fromUtf8(argv()[1] ) ); 447 Global::setDocument( mw, QString::fromUtf8(argv()[1] ) );
448 448
449 d->show(mw, m ); 449 d->show(mw, m );
450} 450}
451void QPEApplication::showDialog( QDialog* d, bool nomax ) { 451void QPEApplication::showDialog( QDialog* d, bool nomax ) {
452 QSize sh = d->sizeHint(); 452 QSize sh = d->sizeHint();
453 int w = QMAX(sh.width(),d->width()); 453 int w = QMAX(sh.width(),d->width());
454 int h = QMAX(sh.height(),d->height()); 454 int h = QMAX(sh.height(),d->height());
455 if ( !nomax 455 if ( !nomax
456 && ( w > qApp->desktop()->width()*3/4 456 && ( w > qApp->desktop()->width()*3/4
457 || h > qApp->desktop()->height()*3/4 ) ) 457 || h > qApp->desktop()->height()*3/4 ) )
458 { 458 {
459 d->showMaximized(); 459 d->showMaximized();
460 } else { 460 } else {
461 d->resize(w,h); 461 d->resize(w,h);
462 d->show(); 462 d->show();
463 } 463 }
464} 464}
465int QPEApplication::execDialog( QDialog* d, bool nomax) { 465int QPEApplication::execDialog( QDialog* d, bool nomax) {
466 showDialog(d,nomax); 466 showDialog(d,nomax);
467 return d->exec(); 467 return d->exec();
468} 468}
469void QPEApplication::setKeepRunning() { 469void QPEApplication::setKeepRunning() {
470 if ( qApp && qApp->inherits( "QPEApplication" ) ) { 470 if ( qApp && qApp->inherits( "QPEApplication" ) ) {
471 QPEApplication * qpeApp = ( QPEApplication* ) qApp; 471 QPEApplication * qpeApp = ( QPEApplication* ) qApp;
472 qpeApp->d->keep_running = TRUE; 472 qpeApp->d->keep_running = TRUE;
473 } 473 }
474} 474}
475bool QPEApplication::keepRunning()const { 475bool QPEApplication::keepRunning()const {
476 return d->keep_running; 476 return d->keep_running;
477} 477}
478bool QPEApplication::keyboardGrabbed()const { 478bool QPEApplication::keyboardGrabbed()const {
479 return d->kbgrabber; 479 return d->kbgrabber;
480} 480}
481int QPEApplication::exec() { 481int QPEApplication::exec() {
482 /* now send the QCOP stuff gotten from the file */ 482 /* now send the QCOP stuff gotten from the file */
483 d->sendQCopQ(); 483 d->sendQCopQ();
484 484
485 if ( d->keep_running ) { 485 if ( d->keep_running ) {
486 qWarning("going to exec"); 486 qWarning("going to exec");
487 int a = QApplication::exec(); 487 int a = QApplication::exec();
488 qWarning("left"); 488 qWarning("left");
489 return a; 489 return a;
490 } 490 }
491 491
492 { 492 {
493 QCopEnvelope e( "QPE/System", "closing(QString)" ); 493 QCopEnvelope e( "QPE/System", "closing(QString)" );
494 e << d->appName; 494 e << d->appName;
495 } 495 }
496 qWarning("processing events!"); 496 qWarning("processing events!");
497 processEvents(); 497 processEvents();
498 return 0; 498 return 0;
499} 499}
500void QPEApplication::internalSetStyle( const QString& ) { 500void QPEApplication::internalSetStyle( const QString& ) {
501 501
502} 502}
503void QPEApplication::systemMessage( const QCString& chan, const QByteArray& ) { 503void QPEApplication::systemMessage( const QCString& chan, const QByteArray& ) {
504 qWarning("QPEApplication::systemMessage( %s )", chan.data() ); 504 qWarning("QPEApplication::systemMessage( %s )", chan.data() );
505} 505}
506void QPEApplication::pidMessage( const QCString& msg, const QByteArray& ) { 506void QPEApplication::pidMessage( const QCString& msg, const QByteArray& ) {
507 if ( msg == "flush()" ) { 507 if ( msg == "flush()" ) {
508 emit flush(); 508 emit flush();
509 QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" ); 509 QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" );
510 e << d->appName; 510 e << d->appName;
511 }else if ( msg == "reload()" ) { 511 }else if ( msg == "reload()" ) {
512 emit reload(); 512 emit reload();
513 } 513 }
514 514
515} 515}
516void QPEApplication::timerEvent( QTimerEvent* e ) { 516void QPEApplication::timerEvent( QTimerEvent* e ) {
517 if ( e->timerId() == d->presstimer && d->presswidget ) { 517 if ( e->timerId() == d->presstimer && d->presswidget ) {
518 // Right pressed 518 // Right pressed
519 postEvent( d->presswidget, 519 postEvent( d->presswidget,
520 new QMouseEvent( QEvent::MouseButtonPress, d->presspos, 520 new QMouseEvent( QEvent::MouseButtonPress, d->presspos,
521 RightButton, LeftButton ) ); 521 RightButton, LeftButton ) );
522 killTimer( d->presstimer ); 522 killTimer( d->presstimer );
523 d->presstimer = 0; 523 d->presstimer = 0;
524 } 524 }
525} 525}
526 526
527// InputMethods Hints 527// InputMethods Hints
528namespace { 528namespace {
529 static QPtrDict<void>* inputMethodDict = 0; 529 static QPtrDict<void>* inputMethodDict = 0;
530 static void createInputMethodDict(){ 530 static void createInputMethodDict(){
531 if ( !inputMethodDict ) 531 if ( !inputMethodDict )
532 inputMethodDict = new QPtrDict<void>; 532 inputMethodDict = new QPtrDict<void>;
533 } 533 }
534 534
535 static QPtrDict<void>* stylusDict = 0; 535 static QPtrDict<void>* stylusDict = 0;
536 static void createDict() { 536 static void createDict() {
537 if ( !stylusDict ) 537 if ( !stylusDict )
538 stylusDict = new QPtrDict<void>; 538 stylusDict = new QPtrDict<void>;
539 } 539 }
540}; 540};
541 541
542void QPEApplication::setInputMethodHint( QWidget* w, InputMethodHint mode ) { 542void QPEApplication::setInputMethodHint( QWidget* w, InputMethodHint mode ) {
543 createInputMethodDict(); 543 createInputMethodDict();
544 if ( mode == Normal ) { 544 if ( mode == Normal ) {
545 inputMethodDict->remove 545 inputMethodDict->remove
546 ( w ); 546 ( w );
547 }else { 547 }else {
548 inputMethodDict->insert( w, ( void* ) mode ); 548 inputMethodDict->insert( w, ( void* ) mode );
549 } 549 }
550} 550}
551QPEApplication::InputMethodHint QPEApplication::inputMethodHint( QWidget* w) { 551QPEApplication::InputMethodHint QPEApplication::inputMethodHint( QWidget* w) {
552 if ( inputMethodDict && w ) 552 if ( inputMethodDict && w )
553 return ( InputMethodHint ) ( int ) inputMethodDict->find( w ); 553 return ( InputMethodHint ) ( int ) inputMethodDict->find( w );
554 return Normal; 554 return Normal;
555} 555}
556 556
557 557
558void QPEApplication::removeSenderFromStylusDict() { 558void QPEApplication::removeSenderFromStylusDict() {
559 stylusDict->remove( ( void* ) sender() ); 559 stylusDict->remove( ( void* ) sender() );
560 if ( d->presswidget == sender() ) 560 if ( d->presswidget == sender() )
561 d->presswidget = 0; 561 d->presswidget = 0;
562} 562}
563void QPEApplication::setStylusOperation( QWidget* w, StylusMode mode) { 563void QPEApplication::setStylusOperation( QWidget* w, StylusMode mode) {
564 createDict(); 564 createDict();
565 if ( mode == LeftOnly ) { 565 if ( mode == LeftOnly ) {
566 stylusDict->remove 566 stylusDict->remove
567 ( w ); 567 ( w );
568 w->removeEventFilter( qApp ); 568 w->removeEventFilter( qApp );
569 }else { 569 }else {
570 stylusDict->insert( w, ( void* ) mode ); 570 stylusDict->insert( w, ( void* ) mode );
571 connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) ); 571 connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) );
572 w->installEventFilter( qApp ); 572 w->installEventFilter( qApp );
573 } 573 }
574} 574}
575QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w) { 575QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w) {
576 if ( stylusDict ) 576 if ( stylusDict )
577 return ( StylusMode ) ( int ) stylusDict->find( w ); 577 return ( StylusMode ) ( int ) stylusDict->find( w );
578 return LeftOnly; 578 return LeftOnly;
579} 579}
580 580
581// eventFilter...... 581// eventFilter......
582bool QPEApplication::eventFilter( QObject* o, QEvent* e ) { 582bool QPEApplication::eventFilter( QObject* o, QEvent* e ) {
583 /* 583 /*
584 * We want our WM to show Ok and a X button 584 * We want our WM to show Ok and a X button
585 * on dialogs 585 * on dialogs
586 * our part is to set the _NET_WM_CONTEXT_ACCEPT 586 * our part is to set the _NET_WM_CONTEXT_ACCEPT
587 * propery 587 * propery
588 * and then wait for a client message -zecke 588 * and then wait for a client message -zecke
589 * on show we will add the prop 589 * on show we will add the prop
590 */ 590 */
591 if (o->inherits("QDialog") && e->type() == QEvent::Show ) { 591 if (o->inherits("QDialog") && e->type() == QEvent::Show ) {
592 QDialog* dialog = (QDialog*)o; 592 QDialog* dialog = (QDialog*)o;
593 Atom wm_prot[45]; 593 Atom wm_prot[45];
594 int n = 0; 594 int n = 0;
595 wm_prot[n++] = d->wm_delete_window; 595 wm_prot[n++] = d->wm_delete_window;
596 wm_prot[n++] = d->wm_take_focus; 596 wm_prot[n++] = d->wm_take_focus;
597 wm_prot[n++] = d->wm_context_accept; 597 wm_prot[n++] = d->wm_context_accept;
598 if ( dialog->testWFlags( WStyle_ContextHelp ) ) 598 if ( dialog->testWFlags( WStyle_ContextHelp ) )
599 wm_prot[n++] = d->wm_context_help; 599 wm_prot[n++] = d->wm_context_help;
600 XSetWMProtocols( qt_xdisplay(), dialog->winId(), wm_prot, n ); 600 XSetWMProtocols( qt_xdisplay(), dialog->winId(), wm_prot, n );
601 return TRUE; // should be save 601 return TRUE; // should be save
602 } 602 }
603 if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) { 603 if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) {
604 QMouseEvent * me = ( QMouseEvent* ) e; 604 QMouseEvent * me = ( QMouseEvent* ) e;
605 StylusMode mode = (StylusMode)(int)stylusDict->find(o); 605 StylusMode mode = (StylusMode)(int)stylusDict->find(o);
606 switch (mode) { 606 switch (mode) {
607 case RightOnHold: 607 case RightOnHold:
608 switch ( me->type() ) { 608 switch ( me->type() ) {
609 case QEvent::MouseButtonPress: 609 case QEvent::MouseButtonPress:
610 if ( me->button() == LeftButton ) { 610 if ( me->button() == LeftButton ) {
611 d->presstimer = startTimer(500); // #### pref. 611 d->presstimer = startTimer(500); // #### pref.
612 d->presswidget = (QWidget*)o; 612 d->presswidget = (QWidget*)o;
613 d->presspos = me->pos(); 613 d->presspos = me->pos();
614 d->rightpressed = FALSE; 614 d->rightpressed = FALSE;
615 } 615 }
616 break; 616 break;
617 case QEvent::MouseMove: 617 case QEvent::MouseMove:
618 if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) { 618 if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) {
619 killTimer(d->presstimer); 619 killTimer(d->presstimer);
620 d->presstimer = 0; 620 d->presstimer = 0;
621 } 621 }
622 break; 622 break;
623 case QEvent::MouseButtonRelease: 623 case QEvent::MouseButtonRelease:
624 if ( me->button() == LeftButton ) { 624 if ( me->button() == LeftButton ) {
625 if ( d->presstimer ) { 625 if ( d->presstimer ) {
626 killTimer(d->presstimer); 626 killTimer(d->presstimer);
627 d->presstimer = 0; 627 d->presstimer = 0;
628 } 628 }
629 if ( d->rightpressed && d->presswidget ) { 629 if ( d->rightpressed && d->presswidget ) {
630 // Right released 630 // Right released
631 postEvent( d->presswidget, 631 postEvent( d->presswidget,
632 new QMouseEvent( QEvent::MouseButtonRelease, me->pos(), 632 new QMouseEvent( QEvent::MouseButtonRelease, me->pos(),
633 RightButton, LeftButton + RightButton ) ); 633 RightButton, LeftButton + RightButton ) );
634 // Left released, off-widget 634 // Left released, off-widget
635 postEvent( d->presswidget, 635 postEvent( d->presswidget,
636 new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1), 636 new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1),
637 LeftButton, LeftButton ) ); 637 LeftButton, LeftButton ) );
638 postEvent( d->presswidget, 638 postEvent( d->presswidget,
639 new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1), 639 new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1),
640 LeftButton, LeftButton ) ); 640 LeftButton, LeftButton ) );
641 d->rightpressed = FALSE; 641 d->rightpressed = FALSE;
642 return TRUE; // don't send the real Left release 642 return TRUE; // don't send the real Left release
643 } 643 }
644 } 644 }
645 break; 645 break;
646 default: 646 default:
647 break; 647 break;
648 } 648 }
649 break; 649 break;
650 default: 650 default:
651 ; 651 ;
652 } 652 }
653 } 653 }
654 else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { 654 else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
655 QKeyEvent *ke = (QKeyEvent *)e; 655 QKeyEvent *ke = (QKeyEvent *)e;
656 if ( ke->key() == Key_Enter ) { 656 if ( ke->key() == Key_Enter ) {
657 if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) { 657 if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) {
658 postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ', 658 postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ',
659 ke->state(), " ", ke->isAutoRepeat(), ke->count() ) ); 659 ke->state(), " ", ke->isAutoRepeat(), ke->count() ) );
660 return TRUE; 660 return TRUE;
661 } 661 }
662 } 662 }
663 } 663 }
664 return FALSE; 664 return FALSE;
665} 665}
666 666
667// Quit stuff 667// Quit stuff
668void QPEApplication::restart() { 668void QPEApplication::restart() {
669 669
670} 670}
671void QPEApplication::shutdown() { 671void QPEApplication::shutdown() {
672 672
673} 673}
674void QPEApplication::tryQuit() { 674void QPEApplication::tryQuit() {
675 qWarning("TryQuit!!"); 675 qWarning("TryQuit!!");
676 if ( activeModalWidget() || strcmp( argv() [ 0 ], "embeddedkonsole" ) == 0 ) 676 if ( activeModalWidget() || strcmp( argv() [ 0 ], "embeddedkonsole" ) == 0 )
677 return ; // Inside modal loop or konsole. Too hard to save state. 677 return ; // Inside modal loop or konsole. Too hard to save state.
678 { 678 {
679 QCopEnvelope e( "QPE/System", "closing(QString)" ); 679 QCopEnvelope e( "QPE/System", "closing(QString)" );
680 e << d->appName; 680 e << d->appName;
681 } 681 }
682 processEvents(); 682 processEvents();
683 683
684 quit(); 684 quit();
685} 685}
686void QPEApplication::hideOrQuit() { 686void QPEApplication::hideOrQuit() {
687 qWarning("hide or close"); 687 qWarning("hide or close");
688 processEvents(); 688 processEvents();
689 qWarning("past processing"); 689 qWarning("past processing");
690 690
691 // If we are a preloaded application we don't actually quit, so emit 691 // If we are a preloaded application we don't actually quit, so emit
692 // a System message indicating we're quasi-closing. 692 // a System message indicating we're quasi-closing.
693 if ( d->preloaded && d->qpe_main_widget ) 693 if ( d->preloaded && d->qpe_main_widget )
694 694
695 { 695 {
696 qWarning("hiding"); 696 qWarning("hiding");
697 QCopEnvelope e("QPE/System", "fastAppHiding(QString)" ); 697 QCopEnvelope e("QPE/System", "fastAppHiding(QString)" );
698 e << d->appName; 698 e << d->appName;
699 d->qpe_main_widget->hide(); 699 d->qpe_main_widget->hide();
700 } 700 }
701 else 701 else
702 quit(); 702 quit();
703} 703}
704 704
705/*! 705/*!
706 \internal 706 \internal
707*/ 707*/
708void QPEApplication::prepareForTermination( bool willrestart ) 708void QPEApplication::prepareForTermination( bool willrestart )
709{ 709{
710 if ( willrestart ) { 710 if ( willrestart ) {
711 // Draw a big wait icon, the image can be altered in later revisions 711 // Draw a big wait icon, the image can be altered in later revisions
712 // QWidget *d = QApplication::desktop(); 712 // QWidget *d = QApplication::desktop();
713 QImage img = Resource::loadImage( "launcher/new_wait" ); 713 QImage img = Resource::loadImage( "launcher/new_wait" );
714 QPixmap pix; 714 QPixmap pix;
715 pix.convertFromImage( img.smoothScale( 1 * img.width(), 1 * img.height() ) ); 715 pix.convertFromImage( img.smoothScale( 1 * img.width(), 1 * img.height() ) );
716 QLabel *lblWait = new QLabel( 0, "wait hack!", QWidget::WStyle_Customize | 716 QLabel *lblWait = new QLabel( 0, "wait hack!", QWidget::WStyle_Customize |
717 QWidget::WStyle_NoBorder | QWidget::WStyle_Tool ); 717 QWidget::WStyle_NoBorder | QWidget::WStyle_Tool );
718 lblWait->setPixmap( pix ); 718 lblWait->setPixmap( pix );
719 lblWait->setAlignment( QWidget::AlignCenter ); 719 lblWait->setAlignment( QWidget::AlignCenter );
720 lblWait->show(); 720 lblWait->show();
721 lblWait->showMaximized(); 721 lblWait->showMaximized();
722 } 722 }
723#ifndef SINGLE_APP 723#ifndef SINGLE_APP
724 { QCopEnvelope envelope( "QPE/System", "forceQuit()" ); 724 { QCopEnvelope envelope( "QPE/System", "forceQuit()" );
725 } 725 }
726 processEvents(); // ensure the message goes out. 726 processEvents(); // ensure the message goes out.
727 sleep( 1 ); // You have 1 second to comply. 727 sleep( 1 ); // You have 1 second to comply.
728#endif 728#endif
729} 729}
730int QPEApplication::x11ClientMessage(QWidget* w, XEvent* event, bool b ) { 730int QPEApplication::x11ClientMessage(QWidget* w, XEvent* event, bool b ) {
731 qWarning("X11 ClientMessage %d %d", event->type, ClientMessage); 731 qWarning("X11 ClientMessage %d %d", event->type, ClientMessage);
732 if ( event->type == ClientMessage ) { 732 if ( event->type == ClientMessage ) {
733 if ( (event->xclient.message_type == d->wm_protocols) && 733 if ( (event->xclient.message_type == d->wm_protocols) &&
734 (event->xclient.data.l[0] == d->wm_context_accept ) ) { 734 (event->xclient.data.l[0] == d->wm_context_accept ) ) {
735 qWarning("accepted!!!"); 735 qWarning("accepted!!!");
736 /* 736 /*
737 * I'm not sure if we should use activeWidget 737 * I'm not sure if we should use activeWidget
738 * or activeModalWidget 738 * or activeModalWidget
739 * a QDialog could be not modal too 739 * a QDialog could be not modal too
740 */ 740 */
741 if ( w->inherits("QDialog" ) ) { 741 if ( w->inherits("QDialog" ) ) {
742 qWarning("inherits QDialog!!!"); 742 qWarning("inherits QDialog!!!");
743 QDialog* dia = (QDialog*)w; 743 QDialog* dia = (QDialog*)w;
744 /* 744 /*
745 * call it directly or via QTimer::singleShot? 745 * call it directly or via QTimer::singleShot?
746 */ 746 */
747 QTimer::singleShot(0, dia, SLOT(accept() ) ); 747 QTimer::singleShot(0, dia, SLOT(accept() ) );
748 return 0; 748 return 0;
749 } 749 }
750 750
751 } 751 }
752 } 752 }
753 return QApplication::x11ClientMessage(w, event, b ); 753 return QApplication::x11ClientMessage(w, event, b );
754} 754}
755 755
756#define KeyPress XKeyPress 756#define KeyPress XKeyPress
757#define KeyRelease XKeyRelease 757#define KeyRelease XKeyRelease
758 758
759#if defined(OPIE_NEW_MALLOC) 759#if defined(OPIE_NEW_MALLOC)
760 760
761// The libraries with the skiff package (and possibly others) have 761// The libraries with the skiff package (and possibly others) have
762// completely useless implementations of builtin new and delete that 762// completely useless implementations of builtin new and delete that
763// use about 50% of your CPU. Here we revert to the simple libc 763// use about 50% of your CPU. Here we revert to the simple libc
764// functions. 764// functions.
765 765
766void* operator new[]( size_t size ) 766void* operator new[]( size_t size )
767{ 767{
768 return malloc( size ); 768 return malloc( size );
769} 769}
770 770
771void* operator new( size_t size ) 771void* operator new( size_t size )
772{ 772{
773 return malloc( size ); 773 return malloc( size );
774} 774}
775 775
776void operator delete[]( void* p ) 776void operator delete[]( void* p )
777{ 777{
778 free( p ); 778 free( p );
779} 779}
780 780
781void operator delete[]( void* p, size_t /*size*/ ) 781void operator delete[]( void* p, size_t /*size*/ )
782{ 782{
783 free( p ); 783 free( p );
784} 784}
785 785
786void operator delete( void* p ) 786void operator delete( void* p )
787{ 787{
788 free( p ); 788 free( p );
789} 789}
790 790
791void operator delete( void* p, size_t /*size*/ ) 791void operator delete( void* p, size_t /*size*/ )
792{ 792{
793 free( p ); 793 free( p );
794} 794}
795 795
796#endif 796#endif
diff --git a/x11/libqpe-x11/qt/qcopchannel_qws.cpp b/x11/libqpe-x11/qt/qcopchannel_qws.cpp
index 706756e..a82ba4d 100644
--- a/x11/libqpe-x11/qt/qcopchannel_qws.cpp
+++ b/x11/libqpe-x11/qt/qcopchannel_qws.cpp
@@ -1,83 +1,83 @@
1 1
2#include "../../ipc/client/ocopclient.h" 2#include "../../ipc/client/ocopclient.h"
3 3
4#include <qcopchannel_qws.h> 4#include <qcopchannel_qws.h>
5 5
6QList<QCopChannel>* QCopChannel::m_list = 0; 6QList<QCopChannel>* QCopChannel::m_list = 0;
7QMap<QCString, int> QCopChannel::m_refCount; 7QMap<QCString, int> QCopChannel::m_refCount;
8 8
9QCopChannel::QCopChannel( const QCString& channel, QObject* parent, 9QCopChannel::QCopChannel( const QCString& channel, QObject* parent,
10 const char* name ) 10 const char* name )
11 : QObject( parent, name ),m_chan(channel) { 11 : QObject( parent, name ),m_chan(channel) {
12 if (!m_list ) { 12 if (!m_list ) {
13 m_list = new QList<QCopChannel>; 13 m_list = new QList<QCopChannel>;
14 /* only connect once */ 14 /* only connect once */
15 connect(OCOPClient::self(), SIGNAL(called(const QCString&, const QCString&, const QByteArray& ) ), 15 connect(OCOPClient::self(), SIGNAL(called(const QCString&,const QCString&,const QByteArray&) ),
16 this, SLOT(rev(const QCString&, const QCString&, const QByteArray&) ) ); 16 this, SLOT(rev(const QCString&,const QCString&,const QByteArray&) ) );
17 } 17 }
18 /* first registration or ref count is 0 for m_chan*/ 18 /* first registration or ref count is 0 for m_chan*/
19 if (!m_refCount.contains( m_chan ) || !m_refCount[m_chan] ) { 19 if (!m_refCount.contains( m_chan ) || !m_refCount[m_chan] ) {
20 qWarning("adding channel %s", m_chan.data() ); 20 qWarning("adding channel %s", m_chan.data() );
21 m_refCount[m_chan] = 1; 21 m_refCount[m_chan] = 1;
22 OCOPClient::self()->addChannel( m_chan ); 22 OCOPClient::self()->addChannel( m_chan );
23 }else{ 23 }else{
24 qWarning("reffing up for %s %d", m_chan.data(), m_refCount[m_chan] ); 24 qWarning("reffing up for %s %d", m_chan.data(), m_refCount[m_chan] );
25 m_refCount[m_chan]++; 25 m_refCount[m_chan]++;
26 } 26 }
27 27
28 m_list->append(this); 28 m_list->append(this);
29} 29}
30void QCopChannel::receive( const QCString& msg, const QByteArray& ar ) { 30void QCopChannel::receive( const QCString& msg, const QByteArray& ar ) {
31 emit received( msg, ar ); 31 emit received( msg, ar );
32} 32}
33QCopChannel::~QCopChannel() { 33QCopChannel::~QCopChannel() {
34 if (m_refCount[m_chan] == 1 ) { 34 if (m_refCount[m_chan] == 1 ) {
35 OCOPClient::self()->delChannel( m_chan ); 35 OCOPClient::self()->delChannel( m_chan );
36 m_refCount[m_chan] = 0; 36 m_refCount[m_chan] = 0;
37 }else 37 }else
38 m_refCount[m_chan]--; 38 m_refCount[m_chan]--;
39 39
40 40
41 m_list->remove(this); 41 m_list->remove(this);
42 if (m_list->count() == 0 ) { 42 if (m_list->count() == 0 ) {
43 delete m_list; 43 delete m_list;
44 m_list = 0; 44 m_list = 0;
45 } 45 }
46 46
47} 47}
48QCString QCopChannel::channel()const { 48QCString QCopChannel::channel()const {
49 return m_chan; 49 return m_chan;
50} 50}
51bool QCopChannel::isRegistered( const QCString& chan) { 51bool QCopChannel::isRegistered( const QCString& chan) {
52 if (m_refCount.contains(chan) ) { 52 if (m_refCount.contains(chan) ) {
53 qDebug("Client:locally contains"); 53 qDebug("Client:locally contains");
54 return true; 54 return true;
55 } 55 }
56 return OCOPClient::self()->isRegistered( chan ); 56 return OCOPClient::self()->isRegistered( chan );
57} 57}
58bool QCopChannel::send( const QCString& chan, const QCString& msg ) { 58bool QCopChannel::send( const QCString& chan, const QCString& msg ) {
59 QByteArray ar; 59 QByteArray ar;
60 return send(chan, msg, ar ); 60 return send(chan, msg, ar );
61} 61}
62bool QCopChannel::send( const QCString& chan, const QCString& msg, 62bool QCopChannel::send( const QCString& chan, const QCString& msg,
63 const QByteArray& ar ) { 63 const QByteArray& ar ) {
64 OCOPClient::self()->send( chan, msg, ar ); 64 OCOPClient::self()->send( chan, msg, ar );
65 return true; 65 return true;
66} 66}
67bool QCopChannel::sendLocally( const QCString& chann, const QCString& msg, 67bool QCopChannel::sendLocally( const QCString& chann, const QCString& msg,
68 const QByteArray& ar ) { 68 const QByteArray& ar ) {
69 qWarning("Client:sendLocally %s %s", chann.data(), msg.data() ); 69 qWarning("Client:sendLocally %s %s", chann.data(), msg.data() );
70 if (!m_list ) 70 if (!m_list )
71 return true; 71 return true;
72 QCopChannel* chan; 72 QCopChannel* chan;
73 73
74 for ( chan = m_list->first(); chan; chan = m_list->next() ) { 74 for ( chan = m_list->first(); chan; chan = m_list->next() ) {
75 if ( chan->channel() == chann ) 75 if ( chan->channel() == chann )
76 chan->receive( msg, ar ); 76 chan->receive( msg, ar );
77 } 77 }
78 78
79 return true; 79 return true;
80} 80}
81void QCopChannel::rev( const QCString& chan, const QCString& msg, const QByteArray& ar ) { 81void QCopChannel::rev( const QCString& chan, const QCString& msg, const QByteArray& ar ) {
82 sendLocally( chan, msg, ar ); 82 sendLocally( chan, msg, ar );
83} 83}