summaryrefslogtreecommitdiff
authorchicken <chicken>2004-03-01 18:10:37 (UTC)
committer chicken <chicken>2004-03-01 18:10:37 (UTC)
commit7fd20d139e2d9bc37ce22bbdb07f4ebc54903f91 (patch) (unidiff)
tree15ef5e3d00c5476ea98ca36ba6c8392eb02e53c8
parent5b4e342004537f84fa53911a46cd00d810378da7 (diff)
downloadopie-7fd20d139e2d9bc37ce22bbdb07f4ebc54903f91.zip
opie-7fd20d139e2d9bc37ce22bbdb07f4ebc54903f91.tar.gz
opie-7fd20d139e2d9bc37ce22bbdb07f4ebc54903f91.tar.bz2
fix includes
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--library/alarmserver.cpp5
-rw-r--r--library/applnk.cpp4
-rw-r--r--library/categoryedit_p.cpp3
-rw-r--r--library/categorymenu.cpp2
-rw-r--r--library/config.cpp2
-rw-r--r--library/datebookdb.cpp5
-rw-r--r--library/datebookmonth.cpp5
-rw-r--r--library/filemanager.cpp3
-rw-r--r--library/fileselector.cpp2
-rw-r--r--library/finddialog.cpp1
-rw-r--r--library/findwidget_p.cpp6
-rw-r--r--library/fontdatabase.cpp2
-rw-r--r--library/global.cpp2
-rw-r--r--library/imageedit.cpp1
-rw-r--r--library/ir.cpp2
-rw-r--r--library/lnkproperties.cpp3
-rw-r--r--library/mimetype.cpp4
-rw-r--r--library/qcopenvelope_qws.cpp2
-rw-r--r--library/qdawg.cpp2
-rw-r--r--library/qpeapplication.cpp1
-rw-r--r--library/qpemenubar.cpp1
-rw-r--r--library/qpestyle.cpp3
-rw-r--r--library/qpetoolbar.cpp2
-rw-r--r--library/qt_override.cpp2
-rw-r--r--library/resource.cpp3
-rw-r--r--library/sound.cpp2
-rw-r--r--library/storage.cpp4
-rw-r--r--library/tzselect.cpp1
28 files changed, 1 insertions, 74 deletions
diff --git a/library/alarmserver.cpp b/library/alarmserver.cpp
index 6f6f32d..48ab9c1 100644
--- a/library/alarmserver.cpp
+++ b/library/alarmserver.cpp
@@ -1,512 +1,507 @@
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 <qdir.h> 21#include <qdir.h>
22#include <qfile.h>
23#include <qmessagebox.h>
24#include <qtextstream.h>
25 22
26 23
27#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
28#include "global.h"
29#include "resource.h"
30 25
31#include <qpe/qcopenvelope_qws.h> 26#include <qpe/qcopenvelope_qws.h>
32#include "alarmserver.h" 27#include "alarmserver.h"
33#include <qpe/timeconversion.h> 28#include <qpe/timeconversion.h>
34 29
35#include <sys/types.h> 30#include <sys/types.h>
36#include <sys/stat.h> 31#include <sys/stat.h>
37 32
38#include <stdlib.h> 33#include <stdlib.h>
39#include <unistd.h> 34#include <unistd.h>
40 35
41 36
42#undef USE_ATD // not used anymore -- we run opie-alarm on suspend/resume 37#undef USE_ATD // not used anymore -- we run opie-alarm on suspend/resume
43 38
44 39
45struct timerEventItem 40struct timerEventItem
46{ 41{
47 time_t UTCtime; 42 time_t UTCtime;
48 QCString channel, message; 43 QCString channel, message;
49 int data; 44 int data;
50 bool operator==( const timerEventItem &right ) const 45 bool operator==( const timerEventItem &right ) const
51 { 46 {
52 return ( UTCtime == right.UTCtime 47 return ( UTCtime == right.UTCtime
53 && channel == right.channel 48 && channel == right.channel
54 && message == right.message 49 && message == right.message
55 && data == right.data ); 50 && data == right.data );
56 } 51 }
57}; 52};
58 53
59class TimerReceiverObject : public QObject 54class TimerReceiverObject : public QObject
60{ 55{
61public: 56public:
62 TimerReceiverObject() 57 TimerReceiverObject()
63 { } 58 { }
64 ~TimerReceiverObject() 59 ~TimerReceiverObject()
65 { } 60 { }
66 void resetTimer(); 61 void resetTimer();
67 void setTimerEventItem(); 62 void setTimerEventItem();
68 void deleteTimer(); 63 void deleteTimer();
69protected: 64protected:
70 void timerEvent( QTimerEvent *te ); 65 void timerEvent( QTimerEvent *te );
71 66
72#ifdef USE_ATD 67#ifdef USE_ATD
73private: 68private:
74 QString atfilename; 69 QString atfilename;
75#endif 70#endif
76}; 71};
77 72
78TimerReceiverObject *timerEventReceiver = NULL; 73TimerReceiverObject *timerEventReceiver = NULL;
79QList<timerEventItem> timerEventList; 74QList<timerEventItem> timerEventList;
80timerEventItem *nearestTimerEvent = NULL; 75timerEventItem *nearestTimerEvent = NULL;
81 76
82 77
83// set the timer to go off on the next event in the list 78// set the timer to go off on the next event in the list
84void setNearestTimerEvent() 79void setNearestTimerEvent()
85{ 80{
86 nearestTimerEvent = NULL; 81 nearestTimerEvent = NULL;
87 QListIterator<timerEventItem> it( timerEventList ); 82 QListIterator<timerEventItem> it( timerEventList );
88 if ( *it ) 83 if ( *it )
89 nearestTimerEvent = *it; 84 nearestTimerEvent = *it;
90 for ( ; *it; ++it ) 85 for ( ; *it; ++it )
91 if ( (*it)->UTCtime < nearestTimerEvent->UTCtime ) 86 if ( (*it)->UTCtime < nearestTimerEvent->UTCtime )
92 nearestTimerEvent = *it; 87 nearestTimerEvent = *it;
93 if (nearestTimerEvent) 88 if (nearestTimerEvent)
94 timerEventReceiver->resetTimer(); 89 timerEventReceiver->resetTimer();
95 else 90 else
96 timerEventReceiver->deleteTimer(); 91 timerEventReceiver->deleteTimer();
97} 92}
98 93
99 94
100//store current state to file 95//store current state to file
101//Simple implementation. Should run on a timer. 96//Simple implementation. Should run on a timer.
102 97
103static void saveState() 98static void saveState()
104{ 99{
105 QString savefilename = Global::applicationFileName( "AlarmServer", "saveFile" ); 100 QString savefilename = Global::applicationFileName( "AlarmServer", "saveFile" );
106 if ( timerEventList.isEmpty() ) { 101 if ( timerEventList.isEmpty() ) {
107 unlink( savefilename ); 102 unlink( savefilename );
108 return ; 103 return ;
109 } 104 }
110 105
111 QFile savefile(savefilename + ".new"); 106 QFile savefile(savefilename + ".new");
112 if ( savefile.open(IO_WriteOnly) ) { 107 if ( savefile.open(IO_WriteOnly) ) {
113 QDataStream ds( &savefile ); 108 QDataStream ds( &savefile );
114 109
115 //save 110 //save
116 111
117 QListIterator<timerEventItem> it( timerEventList ); 112 QListIterator<timerEventItem> it( timerEventList );
118 for ( ; *it; ++it ) { 113 for ( ; *it; ++it ) {
119 ds << it.current()->UTCtime; 114 ds << it.current()->UTCtime;
120 ds << it.current()->channel; 115 ds << it.current()->channel;
121 ds << it.current()->message; 116 ds << it.current()->message;
122 ds << it.current()->data; 117 ds << it.current()->data;
123 } 118 }
124 119
125 120
126 savefile.close(); 121 savefile.close();
127 unlink( savefilename ); 122 unlink( savefilename );
128 QDir d; 123 QDir d;
129 d.rename(savefilename + ".new", savefilename); 124 d.rename(savefilename + ".new", savefilename);
130 125
131 } 126 }
132} 127}
133 128
134/*! 129/*!
135 Sets up the alarm server. Restoring to previous state (session management). 130 Sets up the alarm server. Restoring to previous state (session management).
136 */ 131 */
137void AlarmServer::initialize() 132void AlarmServer::initialize()
138{ 133{
139 //read autosave file and put events in timerEventList 134 //read autosave file and put events in timerEventList
140 135
141 QString savefilename = Global::applicationFileName( "AlarmServer", "saveFile" ); 136 QString savefilename = Global::applicationFileName( "AlarmServer", "saveFile" );
142 137
143 QFile savefile(savefilename); 138 QFile savefile(savefilename);
144 if ( savefile.open(IO_ReadOnly) ) { 139 if ( savefile.open(IO_ReadOnly) ) {
145 QDataStream ds( &savefile ); 140 QDataStream ds( &savefile );
146 while ( !ds.atEnd() ) { 141 while ( !ds.atEnd() ) {
147 timerEventItem *newTimerEventItem = new timerEventItem; 142 timerEventItem *newTimerEventItem = new timerEventItem;
148 ds >> newTimerEventItem->UTCtime; 143 ds >> newTimerEventItem->UTCtime;
149 ds >> newTimerEventItem->channel; 144 ds >> newTimerEventItem->channel;
150 ds >> newTimerEventItem->message; 145 ds >> newTimerEventItem->message;
151 ds >> newTimerEventItem->data; 146 ds >> newTimerEventItem->data;
152 timerEventList.append( newTimerEventItem ); 147 timerEventList.append( newTimerEventItem );
153 } 148 }
154 savefile.close(); 149 savefile.close();
155 if (!timerEventReceiver) 150 if (!timerEventReceiver)
156 timerEventReceiver = new TimerReceiverObject; 151 timerEventReceiver = new TimerReceiverObject;
157 setNearestTimerEvent(); 152 setNearestTimerEvent();
158 } 153 }
159} 154}
160 155
161 156
162#ifdef USE_ATD 157#ifdef USE_ATD
163 158
164static const char* atdir = "/var/spool/at/"; 159static const char* atdir = "/var/spool/at/";
165 160
166static bool triggerAtd( bool writeHWClock = FALSE ) 161static bool triggerAtd( bool writeHWClock = FALSE )
167{ 162{
168 QFile trigger(QString(atdir) + "trigger"); 163 QFile trigger(QString(atdir) + "trigger");
169 if ( trigger.open(IO_WriteOnly | IO_Raw) ) { 164 if ( trigger.open(IO_WriteOnly | IO_Raw) ) {
170 if ( trigger.writeBlock("\n", 2) != 2 ) { 165 if ( trigger.writeBlock("\n", 2) != 2 ) {
171 QMessageBox::critical( 0, QObject::tr( "Out of Space" ), 166 QMessageBox::critical( 0, QObject::tr( "Out of Space" ),
172 QObject::tr( "Unable to schedule alarm.\nFree some memory and try again." ) ); 167 QObject::tr( "Unable to schedule alarm.\nFree some memory and try again." ) );
173 trigger.close(); 168 trigger.close();
174 QFile::remove 169 QFile::remove
175 ( trigger.name() ); 170 ( trigger.name() );
176 return FALSE; 171 return FALSE;
177 } 172 }
178 return TRUE; 173 return TRUE;
179 } 174 }
180 return FALSE; 175 return FALSE;
181} 176}
182 177
183#else 178#else
184 179
185static bool writeResumeAt ( time_t wakeup ) 180static bool writeResumeAt ( time_t wakeup )
186{ 181{
187 FILE *fp = ::fopen ( "/var/run/resumeat", "w" ); 182 FILE *fp = ::fopen ( "/var/run/resumeat", "w" );
188 183
189 if ( fp ) { 184 if ( fp ) {
190 ::fprintf ( fp, "%d\n", (int) wakeup ); 185 ::fprintf ( fp, "%d\n", (int) wakeup );
191 ::fclose ( fp ); 186 ::fclose ( fp );
192 } 187 }
193 else 188 else
194 qWarning ( "Failed to write wakeup time to /var/run/resumeat" ); 189 qWarning ( "Failed to write wakeup time to /var/run/resumeat" );
195 190
196 return ( fp ); 191 return ( fp );
197} 192}
198 193
199#endif 194#endif
200 195
201void TimerReceiverObject::deleteTimer() 196void TimerReceiverObject::deleteTimer()
202{ 197{
203#ifdef USE_ATD 198#ifdef USE_ATD
204 if ( !atfilename.isEmpty() ) { 199 if ( !atfilename.isEmpty() ) {
205 unlink( atfilename ); 200 unlink( atfilename );
206 atfilename = QString::null; 201 atfilename = QString::null;
207 triggerAtd( FALSE ); 202 triggerAtd( FALSE );
208 } 203 }
209#else 204#else
210 writeResumeAt ( 0 ); 205 writeResumeAt ( 0 );
211#endif 206#endif
212} 207}
213 208
214void TimerReceiverObject::resetTimer() 209void TimerReceiverObject::resetTimer()
215{ 210{
216 const int maxsecs = 2147000; 211 const int maxsecs = 2147000;
217 QDateTime nearest = TimeConversion::fromUTC(nearestTimerEvent->UTCtime); 212 QDateTime nearest = TimeConversion::fromUTC(nearestTimerEvent->UTCtime);
218 QDateTime now = QDateTime::currentDateTime(); 213 QDateTime now = QDateTime::currentDateTime();
219 if ( nearest < now ) 214 if ( nearest < now )
220 nearest = now; 215 nearest = now;
221 int secs = TimeConversion::secsTo( now, nearest ); 216 int secs = TimeConversion::secsTo( now, nearest );
222 if ( secs > maxsecs ) { 217 if ( secs > maxsecs ) {
223 // too far for millisecond timing 218 // too far for millisecond timing
224 secs = maxsecs; 219 secs = maxsecs;
225 } 220 }
226 221
227 // System timer (needed so that we wake from deep sleep), 222 // System timer (needed so that we wake from deep sleep),
228 // from the Epoch in seconds. 223 // from the Epoch in seconds.
229 // 224 //
230 int at_secs = TimeConversion::toUTC(nearest); 225 int at_secs = TimeConversion::toUTC(nearest);
231 // qDebug("reset timer to %d seconds from Epoch",at_secs); 226 // qDebug("reset timer to %d seconds from Epoch",at_secs);
232 227
233#ifdef USE_ATD 228#ifdef USE_ATD
234 229
235 QString fn = atdir + QString::number(at_secs) + "." 230 QString fn = atdir + QString::number(at_secs) + "."
236 + QString::number(getpid()); 231 + QString::number(getpid());
237 if ( fn != atfilename ) { 232 if ( fn != atfilename ) {
238 QFile atfile(fn + ".new"); 233 QFile atfile(fn + ".new");
239 if ( atfile.open(IO_WriteOnly | IO_Raw) ) { 234 if ( atfile.open(IO_WriteOnly | IO_Raw) ) {
240 int total_written; 235 int total_written;
241 236
242 // just wake up and delete the at file 237 // just wake up and delete the at file
243 QString cmd = "#!/bin/sh\nrm " + fn; 238 QString cmd = "#!/bin/sh\nrm " + fn;
244 total_written = atfile.writeBlock(cmd.latin1(), cmd.length()); 239 total_written = atfile.writeBlock(cmd.latin1(), cmd.length());
245 if ( total_written != int(cmd.length()) ) { 240 if ( total_written != int(cmd.length()) ) {
246 QMessageBox::critical( 0, tr("Out of Space"), 241 QMessageBox::critical( 0, tr("Out of Space"),
247 tr("Unable to schedule alarm.\n" 242 tr("Unable to schedule alarm.\n"
248 "Please free up space and try again") ); 243 "Please free up space and try again") );
249 atfile.close(); 244 atfile.close();
250 QFile::remove 245 QFile::remove
251 ( atfile.name() ); 246 ( atfile.name() );
252 return ; 247 return ;
253 } 248 }
254 atfile.close(); 249 atfile.close();
255 unlink( atfilename ); 250 unlink( atfilename );
256 QDir d; 251 QDir d;
257 d.rename(fn + ".new", fn); 252 d.rename(fn + ".new", fn);
258 chmod(fn.latin1(), 0755); 253 chmod(fn.latin1(), 0755);
259 atfilename = fn; 254 atfilename = fn;
260 triggerAtd( FALSE ); 255 triggerAtd( FALSE );
261 } 256 }
262 else { 257 else {
263 qWarning("Cannot open atd file %s", fn.latin1()); 258 qWarning("Cannot open atd file %s", fn.latin1());
264 } 259 }
265 } 260 }
266#else 261#else
267 writeResumeAt ( at_secs ); 262 writeResumeAt ( at_secs );
268 263
269#endif 264#endif
270 265
271 // Qt timers (does the actual alarm) 266 // Qt timers (does the actual alarm)
272 // from now in milliseconds 267 // from now in milliseconds
273 // 268 //
274 qDebug("AlarmServer waiting %d seconds", secs); 269 qDebug("AlarmServer waiting %d seconds", secs);
275 startTimer( 1000 * secs + 500 ); 270 startTimer( 1000 * secs + 500 );
276} 271}
277 272
278void TimerReceiverObject::timerEvent( QTimerEvent * ) 273void TimerReceiverObject::timerEvent( QTimerEvent * )
279{ 274{
280 bool needSave = FALSE; 275 bool needSave = FALSE;
281 killTimers(); 276 killTimers();
282 if (nearestTimerEvent) { 277 if (nearestTimerEvent) {
283 if ( nearestTimerEvent->UTCtime 278 if ( nearestTimerEvent->UTCtime
284 <= TimeConversion::toUTC(QDateTime::currentDateTime()) ) { 279 <= TimeConversion::toUTC(QDateTime::currentDateTime()) ) {
285#ifndef QT_NO_COP 280#ifndef QT_NO_COP
286 QCopEnvelope e( nearestTimerEvent->channel, 281 QCopEnvelope e( nearestTimerEvent->channel,
287 nearestTimerEvent->message ); 282 nearestTimerEvent->message );
288 e << TimeConversion::fromUTC( nearestTimerEvent->UTCtime ) 283 e << TimeConversion::fromUTC( nearestTimerEvent->UTCtime )
289 << nearestTimerEvent->data; 284 << nearestTimerEvent->data;
290#endif 285#endif
291 286
292 timerEventList.remove( nearestTimerEvent ); 287 timerEventList.remove( nearestTimerEvent );
293 needSave = TRUE; 288 needSave = TRUE;
294 } 289 }
295 setNearestTimerEvent(); 290 setNearestTimerEvent();
296 } 291 }
297 else { 292 else {
298 resetTimer(); 293 resetTimer();
299 } 294 }
300 if ( needSave ) 295 if ( needSave )
301 saveState(); 296 saveState();
302} 297}
303 298
304/*! 299/*!
305 \class AlarmServer alarmserver.h 300 \class AlarmServer alarmserver.h
306 \brief The AlarmServer class allows alarms to be scheduled and unscheduled. 301 \brief The AlarmServer class allows alarms to be scheduled and unscheduled.
307 302
308 Applications can schedule alarms with addAlarm() and can 303 Applications can schedule alarms with addAlarm() and can
309 unschedule alarms with deleteAlarm(). When the time for an alarm 304 unschedule alarms with deleteAlarm(). When the time for an alarm
310 to go off is reached the specified \link qcop.html QCop\endlink 305 to go off is reached the specified \link qcop.html QCop\endlink
311 message is sent on the specified channel (optionally with 306 message is sent on the specified channel (optionally with
312 additional data). 307 additional data).
313 308
314 Scheduling an alarm using this class is important (rather just using 309 Scheduling an alarm using this class is important (rather just using
315 a QTimer) since the machine may be asleep and needs to get woken up using 310 a QTimer) since the machine may be asleep and needs to get woken up using
316 the Linux kernel which implements this at the kernel level to minimize 311 the Linux kernel which implements this at the kernel level to minimize
317 battery usage while asleep. 312 battery usage while asleep.
318 313
319 A small example on how to use AlarmServer. 314 A small example on how to use AlarmServer.
320 315
321 First we need to connect a slot the AppMessage QCOP call. appMessage 316 First we need to connect a slot the AppMessage QCOP call. appMessage
322 will be emitted if QPE/Application/appname gets called. 317 will be emitted if QPE/Application/appname gets called.
323 318
324 \code 319 \code
325 TestApp::TestApp(QWidget *parent, const char* name, WFlags fl ) 320 TestApp::TestApp(QWidget *parent, const char* name, WFlags fl )
326 : QMainWindow(parent,name,fl){ 321 : QMainWindow(parent,name,fl){
327 connect(qApp,SIGNAL(appMessage(const QCString&,const QByteArray&)), 322 connect(qApp,SIGNAL(appMessage(const QCString&,const QByteArray&)),
328 this,SLOT(slotAppMessage(const QCString&,const QByteArray&))); 323 this,SLOT(slotAppMessage(const QCString&,const QByteArray&)));
329 } 324 }
330 \endcode 325 \endcode
331 326
332 To add / delete an alarm, you can use the static method AlarmServer::addAlarm and 327 To add / delete an alarm, you can use the static method AlarmServer::addAlarm and
333 AlarmServer::deleteAlarm. Note that an old (expired) alarm will automatically be deleted 328 AlarmServer::deleteAlarm. Note that an old (expired) alarm will automatically be deleted
334 from the alarmserver list, but a change in timing will have the effect, that both 329 from the alarmserver list, but a change in timing will have the effect, that both
335 alarms will be emitted. So if you change an Alarm be sure to delete the old one! 330 alarms will be emitted. So if you change an Alarm be sure to delete the old one!
336 @see addAlarm 331 @see addAlarm
337 332
338 \code 333 \code
339 QDateTime oldDt = oldAlarmDateTime(); 334 QDateTime oldDt = oldAlarmDateTime();
340 QPEApplication::execDialog(ourDlg); 335 QPEApplication::execDialog(ourDlg);
341 QDateTime newDt = ourDlg->dateTime(); 336 QDateTime newDt = ourDlg->dateTime();
342 if(newDt == oldDt ) return; 337 if(newDt == oldDt ) return;
343 @slash* code is missing for unsetting an alarm *@slash 338 @slash* code is missing for unsetting an alarm *@slash
344 339
345 AlarmServer::deleteAlarm(oldDt,"QPE/Application/appname","checkAlarm(QDateTime,int)",0); 340 AlarmServer::deleteAlarm(oldDt,"QPE/Application/appname","checkAlarm(QDateTime,int)",0);
346 AlarmServer::addAlarm( newDt,"QPE/AlarmServer/appname","checkAlarm(QDateTime,int)",0); 341 AlarmServer::addAlarm( newDt,"QPE/AlarmServer/appname","checkAlarm(QDateTime,int)",0);
347 342
348 \endcode 343 \endcode
349 344
350 Now once the Alarm is emitted you need to check the appMessage and then do what you want. 345 Now once the Alarm is emitted you need to check the appMessage and then do what you want.
351 \code 346 \code
352 void TestApp::slotAppMessage(const QCString& str, const QByteArray& ar ){ 347 void TestApp::slotAppMessage(const QCString& str, const QByteArray& ar ){
353 QDataStream stream(ar,IO_ReadOnly); 348 QDataStream stream(ar,IO_ReadOnly);
354 if(str == "checkAlarm(QDateTime,int)" ){ 349 if(str == "checkAlarm(QDateTime,int)" ){
355 QDateTime dt; 350 QDateTime dt;
356 int a; 351 int a;
357 stream >> dt >> a; 352 stream >> dt >> a;
358 // fire up alarm 353 // fire up alarm
359 } 354 }
360 } 355 }
361 \endcode 356 \endcode
362 357
363 \ingroup qtopiaemb 358 \ingroup qtopiaemb
364 \sa QCopEnvelope 359 \sa QCopEnvelope
365 @see QPEApplication::appMessage(const QCString&,const QByteArray&) 360 @see QPEApplication::appMessage(const QCString&,const QByteArray&)
366 @see OPimMainWindow 361 @see OPimMainWindow
367 @see ODevice::alarmSound() 362 @see ODevice::alarmSound()
368 @see Sound::soundAlarm() 363 @see Sound::soundAlarm()
369*/ 364*/
370 365
371/*! 366/*!
372 Schedules an alarm to go off at (or soon after) time \a when. When 367 Schedules an alarm to go off at (or soon after) time \a when. When
373 the alarm goes off, the \link qcop.html QCop\endlink \a message will 368 the alarm goes off, the \link qcop.html QCop\endlink \a message will
374 be sent to \a channel, with \a data as a parameter. 369 be sent to \a channel, with \a data as a parameter.
375 370
376 If this function is called with exactly the same data as a previous 371 If this function is called with exactly the same data as a previous
377 call the subsequent call is ignored, so there is only ever one alarm 372 call the subsequent call is ignored, so there is only ever one alarm
378 with a given set of parameters. 373 with a given set of parameters.
379 374
380 Once an alarm is emitted. The \a channel with a \a message will be emitted 375 Once an alarm is emitted. The \a channel with a \a message will be emitted
381 and data will be send. 376 and data will be send.
382 The QDateTime and int are the two parameters included in the QCOP message. 377 The QDateTime and int are the two parameters included in the QCOP message.
383 You can specify channel, message and the integer parameter. QDateTime will be 378 You can specify channel, message and the integer parameter. QDateTime will be
384 the datetime of the QCop call. 379 the datetime of the QCop call.
385 380
386 @param when The QDateTime of the alarm 381 @param when The QDateTime of the alarm
387 @param channel The channel which gets called once the alarm is emitted 382 @param channel The channel which gets called once the alarm is emitted
388 @param message The message to be send to the channel 383 @param message The message to be send to the channel
389 @param data Additional data as integer 384 @param data Additional data as integer
390 385
391 @see QCopChannel 386 @see QCopChannel
392 \sa deleteAlarm() 387 \sa deleteAlarm()
393*/ 388*/
394void AlarmServer::addAlarm ( QDateTime when, const QCString& channel, 389void AlarmServer::addAlarm ( QDateTime when, const QCString& channel,
395 const QCString& message, int data) 390 const QCString& message, int data)
396{ 391{
397 if ( qApp->type() == QApplication::GuiServer ) { 392 if ( qApp->type() == QApplication::GuiServer ) {
398 bool needSave = FALSE; 393 bool needSave = FALSE;
399 // Here we are the server so either it has been directly called from 394 // Here we are the server so either it has been directly called from
400 // within the server or it has been sent to us from a client via QCop 395 // within the server or it has been sent to us from a client via QCop
401 if (!timerEventReceiver) 396 if (!timerEventReceiver)
402 timerEventReceiver = new TimerReceiverObject; 397 timerEventReceiver = new TimerReceiverObject;
403 398
404 timerEventItem *newTimerEventItem = new timerEventItem; 399 timerEventItem *newTimerEventItem = new timerEventItem;
405 newTimerEventItem->UTCtime = TimeConversion::toUTC( when ); 400 newTimerEventItem->UTCtime = TimeConversion::toUTC( when );
406 newTimerEventItem->channel = channel; 401 newTimerEventItem->channel = channel;
407 newTimerEventItem->message = message; 402 newTimerEventItem->message = message;
408 newTimerEventItem->data = data; 403 newTimerEventItem->data = data;
409 // explore the case of already having the event in here... 404 // explore the case of already having the event in here...
410 QListIterator<timerEventItem> it( timerEventList ); 405 QListIterator<timerEventItem> it( timerEventList );
411 for ( ; *it; ++it ) 406 for ( ; *it; ++it )
412 if ( *(*it) == *newTimerEventItem ) 407 if ( *(*it) == *newTimerEventItem )
413 return ; 408 return ;
414 // if we made it here, it is okay to add the item... 409 // if we made it here, it is okay to add the item...
415 timerEventList.append( newTimerEventItem ); 410 timerEventList.append( newTimerEventItem );
416 needSave = TRUE; 411 needSave = TRUE;
417 // quicker than using setNearestTimerEvent() 412 // quicker than using setNearestTimerEvent()
418 if ( nearestTimerEvent ) { 413 if ( nearestTimerEvent ) {
419 if (newTimerEventItem->UTCtime < nearestTimerEvent->UTCtime) { 414 if (newTimerEventItem->UTCtime < nearestTimerEvent->UTCtime) {
420 nearestTimerEvent = newTimerEventItem; 415 nearestTimerEvent = newTimerEventItem;
421 timerEventReceiver->killTimers(); 416 timerEventReceiver->killTimers();
422 timerEventReceiver->resetTimer(); 417 timerEventReceiver->resetTimer();
423 } 418 }
424 } 419 }
425 else { 420 else {
426 nearestTimerEvent = newTimerEventItem; 421 nearestTimerEvent = newTimerEventItem;
427 timerEventReceiver->resetTimer(); 422 timerEventReceiver->resetTimer();
428 } 423 }
429 if ( needSave ) 424 if ( needSave )
430 saveState(); 425 saveState();
431 } 426 }
432 else { 427 else {
433#ifndef QT_NO_COP 428#ifndef QT_NO_COP
434 QCopEnvelope e( "QPE/System", "addAlarm(QDateTime,QCString,QCString,int)" ); 429 QCopEnvelope e( "QPE/System", "addAlarm(QDateTime,QCString,QCString,int)" );
435 e << when << channel << message << data; 430 e << when << channel << message << data;
436#endif 431#endif
437 432
438 } 433 }
439} 434}
440 435
441/*! 436/*!
442 Deletes previously scheduled alarms which match \a when, \a channel, 437 Deletes previously scheduled alarms which match \a when, \a channel,
443 \a message, and \a data. 438 \a message, and \a data.
444 439
445 Passing null values for \a when, \a channel, or for the \link 440 Passing null values for \a when, \a channel, or for the \link
446 qcop.html QCop\endlink \a message, acts as a wildcard meaning "any". 441 qcop.html QCop\endlink \a message, acts as a wildcard meaning "any".
447 Similarly, passing -1 for \a data indicates "any". 442 Similarly, passing -1 for \a data indicates "any".
448 443
449 If there is no matching alarm, nothing happens. 444 If there is no matching alarm, nothing happens.
450 445
451 \sa addAlarm() 446 \sa addAlarm()
452 447
453*/ 448*/
454void AlarmServer::deleteAlarm (QDateTime when, const QCString& channel, const QCString& message, int data) 449void AlarmServer::deleteAlarm (QDateTime when, const QCString& channel, const QCString& message, int data)
455{ 450{
456 if ( qApp->type() == QApplication::GuiServer) { 451 if ( qApp->type() == QApplication::GuiServer) {
457 bool needSave = FALSE; 452 bool needSave = FALSE;
458 if ( timerEventReceiver != NULL ) { 453 if ( timerEventReceiver != NULL ) {
459 timerEventReceiver->killTimers(); 454 timerEventReceiver->killTimers();
460 455
461 // iterate over the list of events 456 // iterate over the list of events
462 QListIterator<timerEventItem> it( timerEventList ); 457 QListIterator<timerEventItem> it( timerEventList );
463 time_t deleteTime = TimeConversion::toUTC( when ); 458 time_t deleteTime = TimeConversion::toUTC( when );
464 for ( ; *it; ++it ) { 459 for ( ; *it; ++it ) {
465 // if its a match, delete it 460 // if its a match, delete it
466 if ( ( (*it)->UTCtime == deleteTime || when.isNull() ) 461 if ( ( (*it)->UTCtime == deleteTime || when.isNull() )
467 && ( channel.isNull() || (*it)->channel == channel ) 462 && ( channel.isNull() || (*it)->channel == channel )
468 && ( message.isNull() || (*it)->message == message ) 463 && ( message.isNull() || (*it)->message == message )
469 && ( data == -1 || (*it)->data == data ) ) { 464 && ( data == -1 || (*it)->data == data ) ) {
470 // if it's first, then we need to update the timer 465 // if it's first, then we need to update the timer
471 if ( (*it) == nearestTimerEvent ) { 466 if ( (*it) == nearestTimerEvent ) {
472 timerEventList.remove(*it); 467 timerEventList.remove(*it);
473 setNearestTimerEvent(); 468 setNearestTimerEvent();
474 } 469 }
475 else { 470 else {
476 timerEventList.remove(*it); 471 timerEventList.remove(*it);
477 } 472 }
478 needSave = TRUE; 473 needSave = TRUE;
479 } 474 }
480 } 475 }
481 if ( nearestTimerEvent ) 476 if ( nearestTimerEvent )
482 timerEventReceiver->resetTimer(); 477 timerEventReceiver->resetTimer();
483 } 478 }
484 if ( needSave ) 479 if ( needSave )
485 saveState(); 480 saveState();
486 } 481 }
487 else { 482 else {
488#ifndef QT_NO_COP 483#ifndef QT_NO_COP
489 QCopEnvelope e( "QPE/System", "deleteAlarm(QDateTime,QCString,QCString,int)" ); 484 QCopEnvelope e( "QPE/System", "deleteAlarm(QDateTime,QCString,QCString,int)" );
490 e << when << channel << message << data; 485 e << when << channel << message << data;
491#endif 486#endif
492 487
493 } 488 }
494} 489}
495 490
496/*! 491/*!
497 The implementation depends on the mode of AlarmServer. If the AlarmServer 492 The implementation depends on the mode of AlarmServer. If the AlarmServer
498 uses atd the current system time will be written to the hardware clock. 493 uses atd the current system time will be written to the hardware clock.
499 If the AlarmServer relies on opie-alarm the time will be written once the 494 If the AlarmServer relies on opie-alarm the time will be written once the
500 device gets suspended. opie-alarm is used by the Zaurus, iPAQs and SIMpad 495 device gets suspended. opie-alarm is used by the Zaurus, iPAQs and SIMpad
501*/ 496*/
502void Global::writeHWClock() 497void Global::writeHWClock()
503{ 498{
504#ifdef USE_ATD 499#ifdef USE_ATD
505 if ( !triggerAtd( TRUE ) ) { 500 if ( !triggerAtd( TRUE ) ) {
506 // atd not running? set it ourselves 501 // atd not running? set it ourselves
507 system("/sbin/hwclock --systohc"); // ##### UTC? 502 system("/sbin/hwclock --systohc"); // ##### UTC?
508 } 503 }
509#else 504#else
510 // hwclock is written on suspend 505 // hwclock is written on suspend
511#endif 506#endif
512} 507}
diff --git a/library/applnk.cpp b/library/applnk.cpp
index 8763eb2..9c60f1a 100644
--- a/library/applnk.cpp
+++ b/library/applnk.cpp
@@ -1,1497 +1,1493 @@
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_MIMEEXT 21#define QTOPIA_INTERNAL_MIMEEXT
22#define QTOPIA_INTERNAL_PRELOADACCESS 22#define QTOPIA_INTERNAL_PRELOADACCESS
23#define QTOPIA_INTERNAL_APPLNKASSIGN 23#define QTOPIA_INTERNAL_APPLNKASSIGN
24 24
25#include "applnk.h" 25#include "applnk.h"
26 26
27#include <qpe/qpeapplication.h> 27#include <qpe/qpeapplication.h>
28#include <qpe/categories.h> 28#include <qpe/categories.h>
29#include <qpe/categoryselect.h> 29#include <qpe/categoryselect.h>
30#include <qpe/qcopenvelope_qws.h> 30#include <qpe/qcopenvelope_qws.h>
31#include <qpe/global.h>
32#include <qpe/mimetype.h> 31#include <qpe/mimetype.h>
33#include <qpe/config.h> 32#include <qpe/config.h>
34#include <qpe/storage.h> 33#include <qpe/storage.h>
35#include <qpe/resource.h> 34#include <qpe/resource.h>
36 35
37#include <qdict.h>
38#include <qdir.h> 36#include <qdir.h>
39#include <qregexp.h>
40 37
41#include <qgfx_qws.h>
42 38
43#include <stdlib.h> 39#include <stdlib.h>
44 40
45int AppLnk::lastId = 5000; 41int AppLnk::lastId = 5000;
46 42
47static int smallSize = 14; 43static int smallSize = 14;
48static int bigSize = 32; 44static int bigSize = 32;
49 45
50static QString safeFileName(const QString& n) 46static QString safeFileName(const QString& n)
51{ 47{
52 QString safename=n; 48 QString safename=n;
53 safename.replace(QRegExp("[^0-9A-Za-z.]"),"_"); 49 safename.replace(QRegExp("[^0-9A-Za-z.]"),"_");
54 safename.replace(QRegExp("^[^A-Za-z]*"),""); 50 safename.replace(QRegExp("^[^A-Za-z]*"),"");
55 if ( safename.isEmpty() ) 51 if ( safename.isEmpty() )
56 safename = "_"; 52 safename = "_";
57 return safename; 53 return safename;
58} 54}
59 55
60static bool prepareDirectories(const QString& lf) 56static bool prepareDirectories(const QString& lf)
61{ 57{
62 if ( !QFile::exists(lf) ) { 58 if ( !QFile::exists(lf) ) {
63 // May need to create directories 59 // May need to create directories
64 QFileInfo fi(lf); 60 QFileInfo fi(lf);
65 if ( system(("mkdir -p "+fi.dirPath(TRUE))) ) 61 if ( system(("mkdir -p "+fi.dirPath(TRUE))) )
66 return FALSE; 62 return FALSE;
67 } 63 }
68 return TRUE; 64 return TRUE;
69} 65}
70 66
71class AppLnkPrivate 67class AppLnkPrivate
72{ 68{
73public: 69public:
74 /* the size of the Pixmap */ 70 /* the size of the Pixmap */
75 enum Size {Normal = 0, Big }; 71 enum Size {Normal = 0, Big };
76 AppLnkPrivate() { 72 AppLnkPrivate() {
77 /* we want one normal and one big item */ 73 /* we want one normal and one big item */
78 74
79 QPixmap pix; 75 QPixmap pix;
80 mPixmaps.insert(0, pix ); 76 mPixmaps.insert(0, pix );
81 mPixmaps.insert(1, pix); 77 mPixmaps.insert(1, pix);
82 } 78 }
83 79
84 QStringList mCatList; // always correct 80 QStringList mCatList; // always correct
85 QArray<int> mCat; // cached value; correct if not empty 81 QArray<int> mCat; // cached value; correct if not empty
86 QMap<int, QPixmap> mPixmaps; 82 QMap<int, QPixmap> mPixmaps;
87 83
88 void updateCatListFromArray() 84 void updateCatListFromArray()
89 { 85 {
90 Categories cat( 0 ); 86 Categories cat( 0 );
91 cat.load( categoryFileName() ); 87 cat.load( categoryFileName() );
92 // we need to update the names for the mCat... to mCatList 88 // we need to update the names for the mCat... to mCatList
93 mCatList.clear(); 89 mCatList.clear();
94 for (uint i = 0; i < mCat.count(); i++ ) 90 for (uint i = 0; i < mCat.count(); i++ )
95 mCatList << cat.label("Document View", mCat[i] ); 91 mCatList << cat.label("Document View", mCat[i] );
96 92
97 } 93 }
98 94
99 void setCatArrayDirty() 95 void setCatArrayDirty()
100 { 96 {
101 mCat.resize(0); 97 mCat.resize(0);
102 } 98 }
103 99
104 void ensureCatArray() 100 void ensureCatArray()
105 { 101 {
106 if ( mCat.count() > 0 || mCatList.count()==0 ) 102 if ( mCat.count() > 0 || mCatList.count()==0 )
107 return; 103 return;
108 104
109 Categories cat( 0 ); 105 Categories cat( 0 );
110 cat.load( categoryFileName() ); 106 cat.load( categoryFileName() );
111 mCat.resize( mCatList.count() ); 107 mCat.resize( mCatList.count() );
112 int i; 108 int i;
113 QStringList::ConstIterator it; 109 QStringList::ConstIterator it;
114 for ( i = 0, it = mCatList.begin(); it != mCatList.end(); 110 for ( i = 0, it = mCatList.begin(); it != mCatList.end();
115 ++it, i++ ) { 111 ++it, i++ ) {
116 112
117 bool number; 113 bool number;
118 int id = (*it).toInt( &number ); 114 int id = (*it).toInt( &number );
119 if ( !number ) { 115 if ( !number ) {
120 id = cat.id( "Document View", *it ); 116 id = cat.id( "Document View", *it );
121 if ( id == 0 ) 117 if ( id == 0 )
122 id = cat.addCategory( "Document View", *it ); 118 id = cat.addCategory( "Document View", *it );
123 } 119 }
124 mCat[i] = id; 120 mCat[i] = id;
125 } 121 }
126 } 122 }
127}; 123};
128 124
129/*! 125/*!
130 \class AppLnk applnk.h 126 \class AppLnk applnk.h
131 \brief The AppLnk class represents an application available on the system. 127 \brief The AppLnk class represents an application available on the system.
132 128
133 Every Qtopia application \e app has a corresponding \e app.desktop 129 Every Qtopia application \e app has a corresponding \e app.desktop
134 file. When one of these files is read its data is stored as an 130 file. When one of these files is read its data is stored as an
135 AppLnk object. 131 AppLnk object.
136 132
137 The AppLnk class introduces some Qtopia-specific concepts, and 133 The AppLnk class introduces some Qtopia-specific concepts, and
138 provides a variety of functions, as described in the following 134 provides a variety of functions, as described in the following
139 sections. 135 sections.
140 \tableofcontents 136 \tableofcontents
141 137
142 \target Types 138 \target Types
143 \section1 Types 139 \section1 Types
144 140
145 Every AppLnk object has a \e type. For applications, games and 141 Every AppLnk object has a \e type. For applications, games and
146 settings the type is \c Application; for documents the 142 settings the type is \c Application; for documents the
147 type is the document's MIME type. 143 type is the document's MIME type.
148 144
149 \target files-and-links 145 \target files-and-links
150 \section1 Files and Links 146 \section1 Files and Links
151 147
152 When you create an AppLnk (or more likely, a \link doclnk.html 148 When you create an AppLnk (or more likely, a \link doclnk.html
153 DocLnk\endlink), you don't deal directly with filenames in the 149 DocLnk\endlink), you don't deal directly with filenames in the
154 filesystem. Instead you do this: 150 filesystem. Instead you do this:
155 \code 151 \code
156 DocLnk d; 152 DocLnk d;
157 d.setType("text/plain"); 153 d.setType("text/plain");
158 d.setName("My Nicely Named Document / Whatever"); // Yes, "/" is legal. 154 d.setName("My Nicely Named Document / Whatever"); // Yes, "/" is legal.
159 \endcode 155 \endcode
160 At this point, the file() and linkFile() are unknown. Normally 156 At this point, the file() and linkFile() are unknown. Normally
161 this is uninteresting, and the names become automatically known, 157 this is uninteresting, and the names become automatically known,
162 and more importantly, becomes reserved, when you ask what they are: 158 and more importantly, becomes reserved, when you ask what they are:
163 159
164 \code 160 \code
165 QString fn = d.file(); 161 QString fn = d.file();
166 \endcode 162 \endcode
167 This invents a filename, and creates the file on disk (an empty 163 This invents a filename, and creates the file on disk (an empty
168 reservation file) to prevent the name being used by another 164 reservation file) to prevent the name being used by another
169 application. 165 application.
170 166
171 In some circumstances, you don't want to create the file if it 167 In some circumstances, you don't want to create the file if it
172 doesn't already exist (e.g. in the Document tab, some of the \link 168 doesn't already exist (e.g. in the Document tab, some of the \link
173 doclnk.html DocLnk\endlink objects represented by icons are 169 doclnk.html DocLnk\endlink objects represented by icons are
174 DocLnk's created just for that view - they don't have 170 DocLnk's created just for that view - they don't have
175 corresponding \c .desktop files. To avoid littering empty 171 corresponding \c .desktop files. To avoid littering empty
176 reservation files around, we check in a few places to see whether 172 reservation files around, we check in a few places to see whether
177 the file really needs to exist). 173 the file really needs to exist).
178 174
179 \section1 Functionality 175 \section1 Functionality
180 176
181 AppLnk objects are created by calling the constructor with the 177 AppLnk objects are created by calling the constructor with the
182 name of a \e .desktop file. The object can be checked for validity 178 name of a \e .desktop file. The object can be checked for validity
183 using isValid(). 179 using isValid().
184 180
185 The following functions are used to set or retrieve information 181 The following functions are used to set or retrieve information
186 about the application: 182 about the application:
187 \table 183 \table
188 \header \i Get Function \i Set Function \i Short Description 184 \header \i Get Function \i Set Function \i Short Description
189 \row \i \l name() \i \l setName() \i application's name 185 \row \i \l name() \i \l setName() \i application's name
190 \row \i \l pixmap() \i \e none \i application's icon 186 \row \i \l pixmap() \i \e none \i application's icon
191 \row \i \l bigPixmap() \i \e none \i application's large icon 187 \row \i \l bigPixmap() \i \e none \i application's large icon
192 \row \i \e none \i setIcon() \i sets the icon's filename 188 \row \i \e none \i setIcon() \i sets the icon's filename
193 \row \i \l type() \i \l setType() \i see \link #Types Types\endlink above 189 \row \i \l type() \i \l setType() \i see \link #Types Types\endlink above
194 \row \i \l rotation() \i \e none \i 0, 90, 180 or 270 degrees 190 \row \i \l rotation() \i \e none \i 0, 90, 180 or 270 degrees
195 \row \i \l comment() \i \l setComment() \i text for the Details dialog 191 \row \i \l comment() \i \l setComment() \i text for the Details dialog
196 \row \i \l exec() \i \l setExec() \i executable's filename 192 \row \i \l exec() \i \l setExec() \i executable's filename
197 \row \i \l file() \i \e none \i document's filename 193 \row \i \l file() \i \e none \i document's filename
198 \row \i \l linkFile() \i \l setLinkFile() \i \e .desktop filename 194 \row \i \l linkFile() \i \l setLinkFile() \i \e .desktop filename
199 \row \i \l mimeTypes() \i \e none \i the mime types the application can view or edit 195 \row \i \l mimeTypes() \i \e none \i the mime types the application can view or edit
200 \row \i \l categories() \i \l setCategories() \i \e{see the function descriptions} 196 \row \i \l categories() \i \l setCategories() \i \e{see the function descriptions}
201 \row \i \l fileKnown() \i \e none \i see \link 197 \row \i \l fileKnown() \i \e none \i see \link
202#files-and-links Files and Links\endlink above 198#files-and-links Files and Links\endlink above
203 \row \i \l linkFileKnown() \i \e none \i see \link 199 \row \i \l linkFileKnown() \i \e none \i see \link
204#files-and-links Files and Links\endlink above 200#files-and-links Files and Links\endlink above
205 \row \i \l property() \i \l setProperty() \i any AppLnk property 201 \row \i \l property() \i \l setProperty() \i any AppLnk property
206 can be retrieved or set (if writeable) using these 202 can be retrieved or set (if writeable) using these
207 \endtable 203 \endtable
208 204
209 To save an AppLnk to disk use writeLink(). To execute the 205 To save an AppLnk to disk use writeLink(). To execute the
210 application that the AppLnk object refers to, use execute(). 206 application that the AppLnk object refers to, use execute().
211 207
212 AppLnk's can be deleted from disk using removeLinkFile(). To 208 AppLnk's can be deleted from disk using removeLinkFile(). To
213 remove both the link and the application's executable use 209 remove both the link and the application's executable use
214 removeFiles(). 210 removeFiles().
215 211
216 Icon sizes can be globally changed (but only for AppLnk objects 212 Icon sizes can be globally changed (but only for AppLnk objects
217 created after the calls) with setSmallIconSize() and 213 created after the calls) with setSmallIconSize() and
218 setBigIconSize(). 214 setBigIconSize().
219 215
220 \ingroup qtopiaemb 216 \ingroup qtopiaemb
221*/ 217*/
222 218
223/*! 219/*!
224 Sets the size used for small icons to \a small pixels. 220 Sets the size used for small icons to \a small pixels.
225 Only affects AppLnk objects created after the call. 221 Only affects AppLnk objects created after the call.
226 222
227 \sa smallIconSize() setIcon() 223 \sa smallIconSize() setIcon()
228*/ 224*/
229void AppLnk::setSmallIconSize(int small) 225void AppLnk::setSmallIconSize(int small)
230{ 226{
231 smallSize = small; 227 smallSize = small;
232} 228}
233 229
234/*! 230/*!
235 Returns the size used for small icons. 231 Returns the size used for small icons.
236 232
237 \sa setSmallIconSize() setIcon() 233 \sa setSmallIconSize() setIcon()
238*/ 234*/
239int AppLnk::smallIconSize() 235int AppLnk::smallIconSize()
240{ 236{
241 return smallSize; 237 return smallSize;
242} 238}
243 239
244 240
245/*! 241/*!
246 Sets the size used for large icons to \a big pixels. 242 Sets the size used for large icons to \a big pixels.
247 Only affects AppLnk objects created after the call. 243 Only affects AppLnk objects created after the call.
248 244
249 \sa bigIconSize() setIcon() 245 \sa bigIconSize() setIcon()
250*/ 246*/
251void AppLnk::setBigIconSize(int big) 247void AppLnk::setBigIconSize(int big)
252{ 248{
253 bigSize = big; 249 bigSize = big;
254} 250}
255 251
256/*! 252/*!
257 Returns the size used for large icons. 253 Returns the size used for large icons.
258 254
259 \sa setBigIconSize() setIcon() 255 \sa setBigIconSize() setIcon()
260*/ 256*/
261int AppLnk::bigIconSize() 257int AppLnk::bigIconSize()
262{ 258{
263 return bigSize; 259 return bigSize;
264} 260}
265 261
266 262
267/*! 263/*!
268 \fn QString AppLnk::name() const 264 \fn QString AppLnk::name() const
269 265
270 Returns the Name property. This is the user-visible name for the 266 Returns the Name property. This is the user-visible name for the
271 document or application, not the filename. 267 document or application, not the filename.
272 268
273 See \link #files-and-links Files and Links\endlink. 269 See \link #files-and-links Files and Links\endlink.
274 270
275 \sa setName() 271 \sa setName()
276*/ 272*/
277/*! 273/*!
278 \fn QString AppLnk::exec() const 274 \fn QString AppLnk::exec() const
279 275
280 Returns the Exec property. This is the name of the executable 276 Returns the Exec property. This is the name of the executable
281 program associated with the AppLnk. 277 program associated with the AppLnk.
282 278
283 \sa setExec() 279 \sa setExec()
284*/ 280*/
285/*! 281/*!
286 \fn QString AppLnk::rotation() const 282 \fn QString AppLnk::rotation() const
287 283
288 Returns the Rotation property. The value is 0, 90, 180 or 270 284 Returns the Rotation property. The value is 0, 90, 180 or 270
289 degrees. 285 degrees.
290*/ 286*/
291/*! 287/*!
292 \fn QString AppLnk::comment() const 288 \fn QString AppLnk::comment() const
293 289
294 Returns the Comment property. 290 Returns the Comment property.
295 291
296 \sa setComment() 292 \sa setComment()
297*/ 293*/
298/*! 294/*!
299 \fn QStringList AppLnk::mimeTypes() const 295 \fn QStringList AppLnk::mimeTypes() const
300 296
301 Returns the MimeTypes property. This is the list of MIME types 297 Returns the MimeTypes property. This is the list of MIME types
302 that the application can view or edit. 298 that the application can view or edit.
303*/ 299*/
304/*! 300/*!
305 \fn const QArray<int>& AppLnk::categories() const 301 \fn const QArray<int>& AppLnk::categories() const
306 302
307 Returns the Categories property. 303 Returns the Categories property.
308 304
309 See the CategoryWidget for more details. 305 See the CategoryWidget for more details.
310 306
311 \sa setCategories() 307 \sa setCategories()
312*/ 308*/
313 309
314const QArray<int>& AppLnk::categories() const 310const QArray<int>& AppLnk::categories() const
315{ 311{
316 d->ensureCatArray(); 312 d->ensureCatArray();
317 return d->mCat; 313 return d->mCat;
318} 314}
319 315
320/*! 316/*!
321 \fn int AppLnk::id() const 317 \fn int AppLnk::id() const
322 318
323 Returns the id of the AppLnk. If the AppLnk is not in an AppLnkSet, 319 Returns the id of the AppLnk. If the AppLnk is not in an AppLnkSet,
324 this value is 0, otherwise it is a value that is unique for the 320 this value is 0, otherwise it is a value that is unique for the
325 duration of the current process. 321 duration of the current process.
326 322
327 \sa AppLnkSet::find() 323 \sa AppLnkSet::find()
328*/ 324*/
329 325
330/*! 326/*!
331 \fn bool AppLnk::isValid() const 327 \fn bool AppLnk::isValid() const
332 328
333 Returns TRUE if this AppLnk is valid; otherwise returns FALSE. 329 Returns TRUE if this AppLnk is valid; otherwise returns FALSE.
334*/ 330*/
335/*! 331/*!
336 \fn bool AppLnk::fileKnown() const 332 \fn bool AppLnk::fileKnown() const
337 333
338 If the with the AppLnk associated file is not equal to QString::null 334 If the with the AppLnk associated file is not equal to QString::null
339*/ 335*/
340/*! 336/*!
341 \fn bool AppLnk::linkFileKnown()const 337 \fn bool AppLnk::linkFileKnown()const
342 338
343 The filename of the AppLnk 339 The filename of the AppLnk
344 340
345*/ 341*/
346/*! 342/*!
347 \fn void AppLnk::setRotation( const QString& ) 343 \fn void AppLnk::setRotation( const QString& )
348 344
349 The default rotation of the associated application. This 345 The default rotation of the associated application. This
350 function is included inline for binary compatible issues 346 function is included inline for binary compatible issues
351*/ 347*/
352/*! 348/*!
353 Creates an invalid AppLnk. 349 Creates an invalid AppLnk.
354 350
355 \sa isValid() 351 \sa isValid()
356*/ 352*/
357AppLnk::AppLnk() 353AppLnk::AppLnk()
358{ 354{
359 mId = 0; 355 mId = 0;
360 d = new AppLnkPrivate(); 356 d = new AppLnkPrivate();
361} 357}
362 358
363/*! 359/*!
364 Loads \a file (e.g. \e app.desktop) as an AppLnk. 360 Loads \a file (e.g. \e app.desktop) as an AppLnk.
365 361
366 \sa writeLink() 362 \sa writeLink()
367*/ 363*/
368AppLnk::AppLnk( const QString &file ) 364AppLnk::AppLnk( const QString &file )
369{ 365{
370 QStringList sl; 366 QStringList sl;
371 d = new AppLnkPrivate(); 367 d = new AppLnkPrivate();
372 if ( !file.isNull() ) { 368 if ( !file.isNull() ) {
373 Config config( file, Config::File ); 369 Config config( file, Config::File );
374 370
375 if ( config.isValid() ) { 371 if ( config.isValid() ) {
376 config.setGroup( "Desktop Entry" ); 372 config.setGroup( "Desktop Entry" );
377 373
378 mName = config.readEntry( "Name", file ); 374 mName = config.readEntry( "Name", file );
379 mExec = config.readEntry( "Exec" ); 375 mExec = config.readEntry( "Exec" );
380 mType = config.readEntry( "Type", QString::null ); 376 mType = config.readEntry( "Type", QString::null );
381 mIconFile = config.readEntry( "Icon", QString::null ); 377 mIconFile = config.readEntry( "Icon", QString::null );
382 mRotation = config.readEntry( "Rotation", "" ); 378 mRotation = config.readEntry( "Rotation", "" );
383 mComment = config.readEntry( "Comment", QString::null ); 379 mComment = config.readEntry( "Comment", QString::null );
384 // MIME types are case-insensitive. 380 // MIME types are case-insensitive.
385 mMimeTypes = config.readListEntry( "MimeType", ';' ); 381 mMimeTypes = config.readListEntry( "MimeType", ';' );
386 for (QStringList::Iterator it=mMimeTypes.begin(); it!=mMimeTypes.end(); ++it) 382 for (QStringList::Iterator it=mMimeTypes.begin(); it!=mMimeTypes.end(); ++it)
387 *it = (*it).lower(); 383 *it = (*it).lower();
388 mMimeTypeIcons = config.readListEntry( "MimeTypeIcons", ';' ); 384 mMimeTypeIcons = config.readListEntry( "MimeTypeIcons", ';' );
389 mLinkFile = file; 385 mLinkFile = file;
390 mFile = config.readEntry("File", QString::null); 386 mFile = config.readEntry("File", QString::null);
391 if ( !mExec. isEmpty ( )) { 387 if ( !mExec. isEmpty ( )) {
392 mFile = QString::null; 388 mFile = QString::null;
393 } 389 }
394 else if ( mFile[0] != '/' ) { 390 else if ( mFile[0] != '/' ) {
395 int slash = file.findRev('/'); 391 int slash = file.findRev('/');
396 if ( slash >= 0 ) { 392 if ( slash >= 0 ) {
397 mFile = file.left(slash) + '/' + mFile; 393 mFile = file.left(slash) + '/' + mFile;
398 } 394 }
399 } 395 }
400 d->mCatList = config.readListEntry("Categories", ';'); 396 d->mCatList = config.readListEntry("Categories", ';');
401 if ( d->mCatList[0].toInt() < -1 ) { 397 if ( d->mCatList[0].toInt() < -1 ) {
402 // numeric cats in file! convert to text 398 // numeric cats in file! convert to text
403 Categories cat( 0 ); 399 Categories cat( 0 );
404 cat.load( categoryFileName() ); 400 cat.load( categoryFileName() );
405 d->mCat.resize( d->mCatList.count() ); 401 d->mCat.resize( d->mCatList.count() );
406 int i; 402 int i;
407 QStringList::ConstIterator it; 403 QStringList::ConstIterator it;
408 for ( i = 0, it = d->mCatList.begin(); it != d->mCatList.end(); 404 for ( i = 0, it = d->mCatList.begin(); it != d->mCatList.end();
409 ++it, i++ ) { 405 ++it, i++ ) {
410 bool number; 406 bool number;
411 int id = (*it).toInt( &number ); 407 int id = (*it).toInt( &number );
412 if ( !number ) { 408 if ( !number ) {
413 // convert from text 409 // convert from text
414 id = cat.id( "Document View", *it ); 410 id = cat.id( "Document View", *it );
415 if ( id == 0 ) 411 if ( id == 0 )
416 id = cat.addCategory( "Document View", *it ); 412 id = cat.addCategory( "Document View", *it );
417 } 413 }
418 d->mCat[i] = id; 414 d->mCat[i] = id;
419 } 415 }
420 d->updateCatListFromArray(); 416 d->updateCatListFromArray();
421 } 417 }
422 } 418 }
423 } 419 }
424 mId = 0; 420 mId = 0;
425} 421}
426 422
427AppLnk& AppLnk::operator=(const AppLnk &copy) 423AppLnk& AppLnk::operator=(const AppLnk &copy)
428{ 424{
429 if ( this == &copy ) return *this; 425 if ( this == &copy ) return *this;
430 if ( mId ) 426 if ( mId )
431 qWarning("Deleting AppLnk that is in an AppLnkSet"); 427 qWarning("Deleting AppLnk that is in an AppLnkSet");
432 if ( d ) 428 if ( d )
433 delete d; 429 delete d;
434 430
435 431
436 mName = copy.mName; 432 mName = copy.mName;
437 433
438 /* remove for Qtopia 3.0 -zecke */ 434 /* remove for Qtopia 3.0 -zecke */
439 mPixmap = copy.mPixmap; 435 mPixmap = copy.mPixmap;
440 mBigPixmap = copy.mBigPixmap; 436 mBigPixmap = copy.mBigPixmap;
441 437
442 mExec = copy.mExec; 438 mExec = copy.mExec;
443 mType = copy.mType; 439 mType = copy.mType;
444 mRotation = copy.mRotation; 440 mRotation = copy.mRotation;
445 mComment = copy.mComment; 441 mComment = copy.mComment;
446 mFile = copy.mFile; 442 mFile = copy.mFile;
447 mLinkFile = copy.mLinkFile; 443 mLinkFile = copy.mLinkFile;
448 mIconFile = copy.mIconFile; 444 mIconFile = copy.mIconFile;
449 mMimeTypes = copy.mMimeTypes; 445 mMimeTypes = copy.mMimeTypes;
450 mMimeTypeIcons = copy.mMimeTypeIcons; 446 mMimeTypeIcons = copy.mMimeTypeIcons;
451 mId = 0; 447 mId = 0;
452 d = new AppLnkPrivate(); 448 d = new AppLnkPrivate();
453 d->mCat = copy.d->mCat; 449 d->mCat = copy.d->mCat;
454 d->mCatList = copy.d->mCatList; 450 d->mCatList = copy.d->mCatList;
455 d->mPixmaps = copy.d->mPixmaps; 451 d->mPixmaps = copy.d->mPixmaps;
456 452
457 return *this; 453 return *this;
458} 454}
459/*! 455/*!
460 protected internally to share code 456 protected internally to share code
461 should I document that at all? 457 should I document that at all?
462 I don't know the TT style for that 458 I don't know the TT style for that
463*/ 459*/
464const QPixmap& AppLnk::pixmap( int pos, int size ) const { 460const QPixmap& AppLnk::pixmap( int pos, int size ) const {
465 if ( d->mPixmaps[pos].isNull() ) { 461 if ( d->mPixmaps[pos].isNull() ) {
466 AppLnk* that = (AppLnk*)this; 462 AppLnk* that = (AppLnk*)this;
467 if ( mIconFile.isEmpty() ) { 463 if ( mIconFile.isEmpty() ) {
468 MimeType mt(type()); 464 MimeType mt(type());
469 that->d->mPixmaps[pos] = pos ? mt.bigPixmap() : mt.pixmap(); 465 that->d->mPixmaps[pos] = pos ? mt.bigPixmap() : mt.pixmap();
470 if ( that->d->mPixmaps[pos].isNull() ) 466 if ( that->d->mPixmaps[pos].isNull() )
471 that->d->mPixmaps[pos].convertFromImage( 467 that->d->mPixmaps[pos].convertFromImage(
472 Resource::loadImage("UnknownDocument") 468 Resource::loadImage("UnknownDocument")
473 .smoothScale( size, size ) ); 469 .smoothScale( size, size ) );
474 return that->d->mPixmaps[pos]; 470 return that->d->mPixmaps[pos];
475 } 471 }
476 QImage unscaledIcon = Resource::loadImage( that->mIconFile ); 472 QImage unscaledIcon = Resource::loadImage( that->mIconFile );
477 if ( unscaledIcon.isNull() ) { 473 if ( unscaledIcon.isNull() ) {
478 // qDebug( "Cannot find icon: %s", that->mIconFile.latin1() ); 474 // qDebug( "Cannot find icon: %s", that->mIconFile.latin1() );
479 that->d->mPixmaps[pos].convertFromImage( 475 that->d->mPixmaps[pos].convertFromImage(
480 Resource::loadImage("UnknownDocument") 476 Resource::loadImage("UnknownDocument")
481 .smoothScale( size, size ) ); 477 .smoothScale( size, size ) );
482 } else { 478 } else {
483 that->d->mPixmaps[0].convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) ); 479 that->d->mPixmaps[0].convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) );
484 that->d->mPixmaps[1].convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) ); 480 that->d->mPixmaps[1].convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) );
485 } 481 }
486 return that->d->mPixmaps[pos]; 482 return that->d->mPixmaps[pos];
487 } 483 }
488 return d->mPixmaps[pos]; 484 return d->mPixmaps[pos];
489} 485}
490 486
491/*! 487/*!
492 Returns a small pixmap associated with the application. 488 Returns a small pixmap associated with the application.
493 489
494 \sa bigPixmap() setIcon() 490 \sa bigPixmap() setIcon()
495*/ 491*/
496const QPixmap& AppLnk::pixmap() const 492const QPixmap& AppLnk::pixmap() const
497{ 493{
498 if ( d->mPixmaps[0].isNull() ) { 494 if ( d->mPixmaps[0].isNull() ) {
499 return pixmap(AppLnkPrivate::Normal, smallSize ); 495 return pixmap(AppLnkPrivate::Normal, smallSize );
500 } 496 }
501 return d->mPixmaps[0]; 497 return d->mPixmaps[0];
502} 498}
503 499
504/*! 500/*!
505 Returns a large pixmap associated with the application. 501 Returns a large pixmap associated with the application.
506 502
507 \sa pixmap() setIcon() 503 \sa pixmap() setIcon()
508*/ 504*/
509const QPixmap& AppLnk::bigPixmap() const 505const QPixmap& AppLnk::bigPixmap() const
510{ 506{
511 if ( d->mPixmaps[1].isNull() ) { 507 if ( d->mPixmaps[1].isNull() ) {
512 return pixmap( AppLnkPrivate::Big, bigSize ); 508 return pixmap( AppLnkPrivate::Big, bigSize );
513 } 509 }
514 return d->mPixmaps[1]; 510 return d->mPixmaps[1];
515} 511}
516 512
517/*! 513/*!
518 Returns the type of the AppLnk. For applications, games and 514 Returns the type of the AppLnk. For applications, games and
519 settings the type is \c Application; for documents the type is the 515 settings the type is \c Application; for documents the type is the
520 document's MIME type. 516 document's MIME type.
521*/ 517*/
522QString AppLnk::type() const 518QString AppLnk::type() const
523{ 519{
524 if ( mType.isNull() ) { 520 if ( mType.isNull() ) {
525 AppLnk* that = (AppLnk*)this; 521 AppLnk* that = (AppLnk*)this;
526 QString f = file(); 522 QString f = file();
527 if ( !f.isNull() ) { 523 if ( !f.isNull() ) {
528 MimeType mt(f); 524 MimeType mt(f);
529 that->mType = mt.id(); 525 that->mType = mt.id();
530 return that->mType; 526 return that->mType;
531 } 527 }
532 } 528 }
533 return mType; 529 return mType;
534} 530}
535 531
536/*! 532/*!
537 Returns the file associated with the AppLnk. 533 Returns the file associated with the AppLnk.
538 534
539 \sa exec() name() 535 \sa exec() name()
540*/ 536*/
541QString AppLnk::file() const 537QString AppLnk::file() const
542{ 538{
543 if ( mExec.isEmpty ( ) && mFile.isNull() ) { 539 if ( mExec.isEmpty ( ) && mFile.isNull() ) {
544 AppLnk* that = (AppLnk*)this; 540 AppLnk* that = (AppLnk*)this;
545 QString ext = MimeType(mType).extension(); 541 QString ext = MimeType(mType).extension();
546 if ( !ext.isEmpty() ) 542 if ( !ext.isEmpty() )
547 ext = "." + ext; 543 ext = "." + ext;
548 if ( !mLinkFile.isEmpty() ) { 544 if ( !mLinkFile.isEmpty() ) {
549 that->mFile = 545 that->mFile =
550 mLinkFile.right(8)==".desktop" // 8 = strlen(".desktop") 546 mLinkFile.right(8)==".desktop" // 8 = strlen(".desktop")
551 ? mLinkFile.left(mLinkFile.length()-8) : mLinkFile; 547 ? mLinkFile.left(mLinkFile.length()-8) : mLinkFile;
552 qDebug("mFile now == %s", mFile.latin1()); 548 qDebug("mFile now == %s", mFile.latin1());
553 } else if ( mType.contains('/') ) { 549 } else if ( mType.contains('/') ) {
554 that->mFile = 550 that->mFile =
555 QString(getenv("HOME"))+"/Documents/"+mType+"/"+safeFileName(that->mName); 551 QString(getenv("HOME"))+"/Documents/"+mType+"/"+safeFileName(that->mName);
556 /* 552 /*
557 * A file with the same name or a .desktop file already exists 553 * A file with the same name or a .desktop file already exists
558 */ 554 */
559 if ( QFile::exists(that->mFile+ext) || QFile::exists(that->mFile+".desktop") ) { 555 if ( QFile::exists(that->mFile+ext) || QFile::exists(that->mFile+".desktop") ) {
560 int n=1; 556 int n=1;
561 QString nn; 557 QString nn;
562 while (QFile::exists((nn=(that->mFile+"_"+QString::number(n)))+ext) 558 while (QFile::exists((nn=(that->mFile+"_"+QString::number(n)))+ext)
563 || QFile::exists(nn+".desktop")) 559 || QFile::exists(nn+".desktop"))
564 n++; 560 n++;
565 that->mFile = nn; 561 that->mFile = nn;
566 } 562 }
567 that->mLinkFile = that->mFile+".desktop"; 563 that->mLinkFile = that->mFile+".desktop";
568 that->mFile += ext; 564 that->mFile += ext;
569 } 565 }
570 prepareDirectories(that->mFile); 566 prepareDirectories(that->mFile);
571 if ( !that->mFile.isEmpty() ) { 567 if ( !that->mFile.isEmpty() ) {
572 QFile f(that->mFile); 568 QFile f(that->mFile);
573 if ( !f.open(IO_WriteOnly) ) 569 if ( !f.open(IO_WriteOnly) )
574 that->mFile = QString::null; 570 that->mFile = QString::null;
575 return that->mFile; 571 return that->mFile;
576 } 572 }
577 } 573 }
578 return mFile; 574 return mFile;
579} 575}
580 576
581/*! 577/*!
582 Returns the desktop file corresponding to this AppLnk. 578 Returns the desktop file corresponding to this AppLnk.
583 579
584 \sa file() exec() name() 580 \sa file() exec() name()
585*/ 581*/
586QString AppLnk::linkFile() const 582QString AppLnk::linkFile() const
587{ 583{
588 if ( mLinkFile.isNull() ) { 584 if ( mLinkFile.isNull() ) {
589 AppLnk* that = (AppLnk*)this; 585 AppLnk* that = (AppLnk*)this;
590 if ( type().contains('/') ) { 586 if ( type().contains('/') ) {
591 StorageInfo storage; 587 StorageInfo storage;
592 const FileSystem *fs = storage.fileSystemOf( that->mFile ); 588 const FileSystem *fs = storage.fileSystemOf( that->mFile );
593 /* tmpfs + and ramfs are available too but not removable 589 /* tmpfs + and ramfs are available too but not removable
594 * either we fix storage or add this 590 * either we fix storage or add this
595 */ 591 */
596 if ( fs && ( fs->isRemovable() || fs->disk() == "/dev/mtdblock6" || fs->disk() == "tmpfs") ) { 592 if ( fs && ( fs->isRemovable() || fs->disk() == "/dev/mtdblock6" || fs->disk() == "tmpfs") ) {
597 that->mLinkFile = fs->path(); 593 that->mLinkFile = fs->path();
598 } else 594 } else
599 that->mLinkFile = getenv( "HOME" ); 595 that->mLinkFile = getenv( "HOME" );
600 that->mLinkFile += "/Documents/"+type()+"/"+safeFileName(that->mName); 596 that->mLinkFile += "/Documents/"+type()+"/"+safeFileName(that->mName);
601 597
602 /* the desktop file exists make sure we don't point to the same file */ 598 /* the desktop file exists make sure we don't point to the same file */
603 if ( QFile::exists(that->mLinkFile+".desktop") ) { 599 if ( QFile::exists(that->mLinkFile+".desktop") ) {
604 AppLnk lnk( that->mLinkFile + ".desktop" ); 600 AppLnk lnk( that->mLinkFile + ".desktop" );
605 601
606 /* the linked is different */ 602 /* the linked is different */
607 if(that->file() != lnk.file() ) { 603 if(that->file() != lnk.file() ) {
608 int n = 1; 604 int n = 1;
609 QString nn; 605 QString nn;
610 while (QFile::exists((nn=that->mLinkFile+"_"+QString::number(n))+".desktop")) { 606 while (QFile::exists((nn=that->mLinkFile+"_"+QString::number(n))+".desktop")) {
611 n++; 607 n++;
612 /* just to be sure */ 608 /* just to be sure */
613 AppLnk lnk(nn ); 609 AppLnk lnk(nn );
614 if (lnk.file() == that->file() ) 610 if (lnk.file() == that->file() )
615 break; 611 break;
616 } 612 }
617 that->mLinkFile = nn; 613 that->mLinkFile = nn;
618 } 614 }
619 } 615 }
620 that->mLinkFile += ".desktop"; 616 that->mLinkFile += ".desktop";
621 storeLink(); 617 storeLink();
622 } 618 }
623 return that->mLinkFile; 619 return that->mLinkFile;
624 } 620 }
625 return mLinkFile; 621 return mLinkFile;
626} 622}
627 623
628/*! 624/*!
629 Copies \a copy. 625 Copies \a copy.
630*/ 626*/
631AppLnk::AppLnk( const AppLnk &copy ) 627AppLnk::AppLnk( const AppLnk &copy )
632{ 628{
633 mName = copy.mName; 629 mName = copy.mName;
634 mPixmap = copy.mPixmap; 630 mPixmap = copy.mPixmap;
635 mBigPixmap = copy.mBigPixmap; 631 mBigPixmap = copy.mBigPixmap;
636 mExec = copy.mExec; 632 mExec = copy.mExec;
637 mType = copy.mType; 633 mType = copy.mType;
638 mRotation = copy.mRotation; 634 mRotation = copy.mRotation;
639 mComment = copy.mComment; 635 mComment = copy.mComment;
640 mFile = copy.mFile; 636 mFile = copy.mFile;
641 mLinkFile = copy.mLinkFile; 637 mLinkFile = copy.mLinkFile;
642 mIconFile = copy.mIconFile; 638 mIconFile = copy.mIconFile;
643 mMimeTypes = copy.mMimeTypes; 639 mMimeTypes = copy.mMimeTypes;
644 mMimeTypeIcons = copy.mMimeTypeIcons; 640 mMimeTypeIcons = copy.mMimeTypeIcons;
645 mId = 0; 641 mId = 0;
646 d = new AppLnkPrivate(); 642 d = new AppLnkPrivate();
647 d->mCat = copy.d->mCat; 643 d->mCat = copy.d->mCat;
648 d->mCatList = copy.d->mCatList; 644 d->mCatList = copy.d->mCatList;
649 d->mPixmaps = copy.d->mPixmaps; 645 d->mPixmaps = copy.d->mPixmaps;
650} 646}
651 647
652/*! 648/*!
653 Destroys the AppLnk. Note that if the AppLnk is currently a member 649 Destroys the AppLnk. Note that if the AppLnk is currently a member
654 of an AppLnkSet, this will produce a run-time warning. 650 of an AppLnkSet, this will produce a run-time warning.
655 651
656 \sa AppLnkSet::add() AppLnkSet::remove() 652 \sa AppLnkSet::add() AppLnkSet::remove()
657*/ 653*/
658AppLnk::~AppLnk() 654AppLnk::~AppLnk()
659{ 655{
660 if ( mId ) 656 if ( mId )
661 qWarning("Deleting AppLnk that is in an AppLnkSet"); 657 qWarning("Deleting AppLnk that is in an AppLnkSet");
662 if ( d ) 658 if ( d )
663 delete d; 659 delete d;
664} 660}
665 661
666/*! 662/*!
667 \overload 663 \overload
668 Executes the application associated with this AppLnk. 664 Executes the application associated with this AppLnk.
669 665
670 \sa exec() 666 \sa exec()
671*/ 667*/
672void AppLnk::execute() const 668void AppLnk::execute() const
673{ 669{
674 execute(QStringList()); 670 execute(QStringList());
675} 671}
676 672
677/*! 673/*!
678 Executes the application associated with this AppLnk, with 674 Executes the application associated with this AppLnk, with
679 \a args as arguments. 675 \a args as arguments.
680 676
681 \sa exec() 677 \sa exec()
682*/ 678*/
683void AppLnk::execute(const QStringList& args) const 679void AppLnk::execute(const QStringList& args) const
684{ 680{
685#ifdef Q_WS_QWS 681#ifdef Q_WS_QWS
686 if ( !mRotation.isEmpty() ) { 682 if ( !mRotation.isEmpty() ) {
687 // ######## this will only work in the server 683 // ######## this will only work in the server
688 int rot = QPEApplication::defaultRotation(); 684 int rot = QPEApplication::defaultRotation();
689 rot = (rot+mRotation.toInt())%360; 685 rot = (rot+mRotation.toInt())%360;
690 QCString old = getenv("QWS_DISPLAY"); 686 QCString old = getenv("QWS_DISPLAY");
691 setenv("QWS_DISPLAY", QString("Transformed:Rot%1:0").arg(rot), 1); 687 setenv("QWS_DISPLAY", QString("Transformed:Rot%1:0").arg(rot), 1);
692 invoke(args); 688 invoke(args);
693 setenv("QWS_DISPLAY", old.data(), 1); 689 setenv("QWS_DISPLAY", old.data(), 1);
694 } else 690 } else
695#endif 691#endif
696 invoke(args); 692 invoke(args);
697} 693}
698 694
699/*! 695/*!
700 Invokes the application associated with this AppLnk, with 696 Invokes the application associated with this AppLnk, with
701 \a args as arguments. Rotation is not taken into account by 697 \a args as arguments. Rotation is not taken into account by
702 this function, so you should not call it directly. 698 this function, so you should not call it directly.
703 699
704 \sa execute() 700 \sa execute()
705*/ 701*/
706void AppLnk::invoke(const QStringList& args) const 702void AppLnk::invoke(const QStringList& args) const
707{ 703{
708 Global::execute( exec(), args[0] ); 704 Global::execute( exec(), args[0] );
709} 705}
710 706
711/*! 707/*!
712 Sets the Exec property to \a exec. 708 Sets the Exec property to \a exec.
713 709
714 \sa exec() name() 710 \sa exec() name()
715*/ 711*/
716void AppLnk::setExec( const QString& exec ) 712void AppLnk::setExec( const QString& exec )
717{ 713{
718 mExec = exec; 714 mExec = exec;
719} 715}
720 716
721#if 0 // this was inlined for better BC 717#if 0 // this was inlined for better BC
722/*! 718/*!
723 Sets the Rotation property to \a rot. 719 Sets the Rotation property to \a rot.
724 720
725 \sa rotation() 721 \sa rotation()
726*/ 722*/
727void AppLnk::setRotation ( const QString &rot ) 723void AppLnk::setRotation ( const QString &rot )
728{ 724{
729 mRotation = rot; 725 mRotation = rot;
730} 726}
731#endif 727#endif
732 728
733/*! 729/*!
734 Sets the Name property to \a docname. 730 Sets the Name property to \a docname.
735 731
736 \sa name() 732 \sa name()
737*/ 733*/
738void AppLnk::setName( const QString& docname ) 734void AppLnk::setName( const QString& docname )
739{ 735{
740 mName = docname; 736 mName = docname;
741} 737}
742 738
743/*! 739/*!
744 Sets the File property to \a filename. 740 Sets the File property to \a filename.
745 741
746 \sa file() name() 742 \sa file() name()
747*/ 743*/
748void AppLnk::setFile( const QString& filename ) 744void AppLnk::setFile( const QString& filename )
749{ 745{
750 mFile = filename; 746 mFile = filename;
751} 747}
752 748
753/*! 749/*!
754 Sets the LinkFile property to \a filename. 750 Sets the LinkFile property to \a filename.
755 751
756 \sa linkFile() 752 \sa linkFile()
757*/ 753*/
758void AppLnk::setLinkFile( const QString& filename ) 754void AppLnk::setLinkFile( const QString& filename )
759{ 755{
760 mLinkFile = filename; 756 mLinkFile = filename;
761} 757}
762 758
763/*! 759/*!
764 Sets the Comment property to \a comment. 760 Sets the Comment property to \a comment.
765 761
766 This text is displayed in the 'Details Dialog', for example if the 762 This text is displayed in the 'Details Dialog', for example if the
767 user uses the 'press-and-hold' gesture. 763 user uses the 'press-and-hold' gesture.
768 764
769 \sa comment() 765 \sa comment()
770*/ 766*/
771void AppLnk::setComment( const QString& comment ) 767void AppLnk::setComment( const QString& comment )
772{ 768{
773 mComment = comment; 769 mComment = comment;
774} 770}
775 771
776/*! 772/*!
777 Sets the Type property to \a type. 773 Sets the Type property to \a type.
778 774
779 For applications, games and settings the type should be \c 775 For applications, games and settings the type should be \c
780 Application; for documents the type should be the document's MIME 776 Application; for documents the type should be the document's MIME
781 type. 777 type.
782 778
783 \sa type() 779 \sa type()
784*/ 780*/
785void AppLnk::setType( const QString& type ) 781void AppLnk::setType( const QString& type )
786{ 782{
787 mType = type; 783 mType = type;
788} 784}
789 785
790/*! 786/*!
791 \fn QString AppLnk::icon() const 787 \fn QString AppLnk::icon() const
792 788
793 Returns the Icon property. 789 Returns the Icon property.
794 790
795 \sa setIcon() 791 \sa setIcon()
796*/ 792*/
797 793
798/*! 794/*!
799 Sets the Icon property to \a iconname. This is the filename from 795 Sets the Icon property to \a iconname. This is the filename from
800 which the pixmap() and bigPixmap() are obtained. 796 which the pixmap() and bigPixmap() are obtained.
801 797
802 \sa icon() setSmallIconSize() setBigIconSize() 798 \sa icon() setSmallIconSize() setBigIconSize()
803*/ 799*/
804void AppLnk::setIcon( const QString& iconname ) 800void AppLnk::setIcon( const QString& iconname )
805{ 801{
806 mIconFile = iconname; 802 mIconFile = iconname;
807 QImage unscaledIcon = Resource::loadImage( mIconFile ); 803 QImage unscaledIcon = Resource::loadImage( mIconFile );
808 d->mPixmaps[0].convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) ); 804 d->mPixmaps[0].convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) );
809 d->mPixmaps[1].convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) ); 805 d->mPixmaps[1].convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) );
810} 806}
811 807
812/*! 808/*!
813 Sets the Categories property to \a c. 809 Sets the Categories property to \a c.
814 810
815 See the CategoryWidget for more details. 811 See the CategoryWidget for more details.
816 812
817 \sa categories() 813 \sa categories()
818*/ 814*/
819void AppLnk::setCategories( const QArray<int>& c ) 815void AppLnk::setCategories( const QArray<int>& c )
820{ 816{
821 d->mCat = c; 817 d->mCat = c;
822 d->updateCatListFromArray(); 818 d->updateCatListFromArray();
823} 819}
824 820
825/*! 821/*!
826 \fn QStringList AppLnk::mimeTypeIcons() const 822 \fn QStringList AppLnk::mimeTypeIcons() const
827 823
828 Returns the MimeTypeIcons property of the AppLnk. 824 Returns the MimeTypeIcons property of the AppLnk.
829*/ 825*/
830 826
831/*! 827/*!
832 Attempts to ensure that the link file for this AppLnk exists, 828 Attempts to ensure that the link file for this AppLnk exists,
833 including creating any required directories. Returns TRUE if 829 including creating any required directories. Returns TRUE if
834 successful; otherwise returns FALSE. 830 successful; otherwise returns FALSE.
835 831
836 You should not need to use this function. 832 You should not need to use this function.
837*/ 833*/
838bool AppLnk::ensureLinkExists() const 834bool AppLnk::ensureLinkExists() const
839{ 835{
840 QString lf = linkFile(); 836 QString lf = linkFile();
841 return prepareDirectories(lf); 837 return prepareDirectories(lf);
842} 838}
843 839
844/*! 840/*!
845 Commits the AppLnk to disk. Returns TRUE if the operation succeeded; 841 Commits the AppLnk to disk. Returns TRUE if the operation succeeded;
846 otherwise returns FALSE. 842 otherwise returns FALSE.
847 843
848 In addition, the "linkChanged(QString)" message is sent to the 844 In addition, the "linkChanged(QString)" message is sent to the
849 "QPE/System" \link qcop.html QCop\endlink channel. 845 "QPE/System" \link qcop.html QCop\endlink channel.
850*/ 846*/
851bool AppLnk::writeLink() const 847bool AppLnk::writeLink() const
852{ 848{
853 // Only re-writes settable parts 849 // Only re-writes settable parts
854 QString lf = linkFile(); 850 QString lf = linkFile();
855 if ( !ensureLinkExists() ) 851 if ( !ensureLinkExists() )
856 return FALSE; 852 return FALSE;
857 storeLink(); 853 storeLink();
858 return TRUE; 854 return TRUE;
859} 855}
860 856
861/*! 857/*!
862 \internal 858 \internal
863*/ 859*/
864void AppLnk::storeLink() const 860void AppLnk::storeLink() const
865{ 861{
866 Config config( mLinkFile, Config::File ); 862 Config config( mLinkFile, Config::File );
867 config.setGroup("Desktop Entry"); 863 config.setGroup("Desktop Entry");
868 config.writeEntry("Name",mName); 864 config.writeEntry("Name",mName);
869 if ( !mIconFile.isNull() ) config.writeEntry("Icon",mIconFile); 865 if ( !mIconFile.isNull() ) config.writeEntry("Icon",mIconFile);
870 config.writeEntry("Type",type()); 866 config.writeEntry("Type",type());
871 if(!rotation().isEmpty()) 867 if(!rotation().isEmpty())
872 config.writeEntry("Rotation",rotation()); 868 config.writeEntry("Rotation",rotation());
873 else 869 else
874 config.removeEntry("Rotation"); 870 config.removeEntry("Rotation");
875 if ( !mComment.isNull() ) config.writeEntry("Comment",mComment); 871 if ( !mComment.isNull() ) config.writeEntry("Comment",mComment);
876 QString f = file(); 872 QString f = file();
877 int i = 0; 873 int i = 0;
878 while ( i < (int)f.length() && i < (int)mLinkFile.length() && f[i] == mLinkFile[i] ) 874 while ( i < (int)f.length() && i < (int)mLinkFile.length() && f[i] == mLinkFile[i] )
879 i++; 875 i++;
880 while ( i && f[i] != '/' ) 876 while ( i && f[i] != '/' )
881 i--; 877 i--;
882 // simple case where in the same directory 878 // simple case where in the same directory
883 if ( mLinkFile.find( '/', i + 1 ) < 0 ) 879 if ( mLinkFile.find( '/', i + 1 ) < 0 )
884 f = f.mid(i+1); 880 f = f.mid(i+1);
885 // ### could do relative ie ../../otherDocs/file.doc 881 // ### could do relative ie ../../otherDocs/file.doc
886 config.writeEntry("File",f); 882 config.writeEntry("File",f);
887 config.writeEntry( "Categories", d->mCatList, ';' ); 883 config.writeEntry( "Categories", d->mCatList, ';' );
888 884
889#ifndef QT_NO_COP 885#ifndef QT_NO_COP
890 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 886 QCopEnvelope e("QPE/System", "linkChanged(QString)");
891 e << mLinkFile; 887 e << mLinkFile;
892#endif 888#endif
893} 889}
894 890
895/*! 891/*!
896 Sets the property named \a key to \a value. 892 Sets the property named \a key to \a value.
897 893
898 \sa property() 894 \sa property()
899*/ 895*/
900void AppLnk::setProperty(const QString& key, const QString& value) 896void AppLnk::setProperty(const QString& key, const QString& value)
901{ 897{
902 if ( ensureLinkExists() ) { 898 if ( ensureLinkExists() ) {
903 Config cfg(linkFile(), Config::File); 899 Config cfg(linkFile(), Config::File);
904 cfg.writeEntry(key,value); 900 cfg.writeEntry(key,value);
905 } 901 }
906} 902}
907 903
908/*! 904/*!
909 Returns the property named \a key. 905 Returns the property named \a key.
910 906
911 \sa setProperty() 907 \sa setProperty()
912*/ 908*/
913QString AppLnk::property(const QString& key) const 909QString AppLnk::property(const QString& key) const
914{ 910{
915 QString lf = linkFile(); 911 QString lf = linkFile();
916 if ( !QFile::exists(lf) ) 912 if ( !QFile::exists(lf) )
917 return QString::null; 913 return QString::null;
918 Config cfg(lf, Config::File); 914 Config cfg(lf, Config::File);
919 return cfg.readEntry(key); 915 return cfg.readEntry(key);
920} 916}
921 917
922bool AppLnk::isPreloaded() const { 918bool AppLnk::isPreloaded() const {
923 // Preload information is stored in the Launcher config in v1.5. 919 // Preload information is stored in the Launcher config in v1.5.
924 Config cfg("Launcher"); 920 Config cfg("Launcher");
925 cfg.setGroup("Preload"); 921 cfg.setGroup("Preload");
926 QStringList apps = cfg.readListEntry("Apps",','); 922 QStringList apps = cfg.readListEntry("Apps",',');
927 if (apps.contains(exec())) 923 if (apps.contains(exec()))
928 return true; 924 return true;
929 return false; 925 return false;
930} 926}
931 927
932void AppLnk::setPreloaded(bool yesNo) { 928void AppLnk::setPreloaded(bool yesNo) {
933 // Preload information is stored in the Launcher config in v1.5. 929 // Preload information is stored in the Launcher config in v1.5.
934 Config cfg("Launcher"); 930 Config cfg("Launcher");
935 cfg.setGroup("Preload"); 931 cfg.setGroup("Preload");
936 QStringList apps = cfg.readListEntry("Apps", ','); 932 QStringList apps = cfg.readListEntry("Apps", ',');
937 if (apps.contains(exec()) && !yesNo) 933 if (apps.contains(exec()) && !yesNo)
938 apps.remove(exec()); 934 apps.remove(exec());
939 else if (yesNo && !apps.contains(exec())) 935 else if (yesNo && !apps.contains(exec()))
940 apps.append(exec()); 936 apps.append(exec());
941 cfg.writeEntry("Apps", apps, ','); 937 cfg.writeEntry("Apps", apps, ',');
942} 938}
943 939
944 940
945/*! 941/*!
946 Deletes both the linkFile() and the file() associated with this AppLnk. 942 Deletes both the linkFile() and the file() associated with this AppLnk.
947 943
948 \sa removeLinkFile() 944 \sa removeLinkFile()
949*/ 945*/
950void AppLnk::removeFiles() 946void AppLnk::removeFiles()
951{ 947{
952 bool valid = isValid(); 948 bool valid = isValid();
953 if ( !valid || !linkFileKnown() || QFile::remove(linkFile()) ) { 949 if ( !valid || !linkFileKnown() || QFile::remove(linkFile()) ) {
954 if ( QFile::remove(file()) ) { 950 if ( QFile::remove(file()) ) {
955#ifndef QT_NO_COP 951#ifndef QT_NO_COP
956 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 952 QCopEnvelope e("QPE/System", "linkChanged(QString)");
957 if ( linkFileKnown() ) 953 if ( linkFileKnown() )
958 e << linkFile(); 954 e << linkFile();
959 else 955 else
960 e << file(); 956 e << file();
961#endif 957#endif
962 } else if ( valid ) { 958 } else if ( valid ) {
963 // restore link 959 // restore link
964 writeLink(); 960 writeLink();
965 } 961 }
966 } 962 }
967} 963}
968 964
969/*! 965/*!
970 Deletes the linkFile(), leaving any file() untouched. 966 Deletes the linkFile(), leaving any file() untouched.
971 967
972 \sa removeFiles() 968 \sa removeFiles()
973*/ 969*/
974void AppLnk::removeLinkFile() 970void AppLnk::removeLinkFile()
975{ 971{
976 if ( isValid() && linkFileKnown() && QFile::remove(linkFile()) ) { 972 if ( isValid() && linkFileKnown() && QFile::remove(linkFile()) ) {
977#ifndef QT_NO_COP 973#ifndef QT_NO_COP
978 QCopEnvelope e("QPE/System", "linkChanged(QString)"); 974 QCopEnvelope e("QPE/System", "linkChanged(QString)");
979 e << linkFile(); 975 e << linkFile();
980#endif 976#endif
981 } 977 }
982} 978}
983 979
984class AppLnkSetPrivate { 980class AppLnkSetPrivate {
985public: 981public:
986 AppLnkSetPrivate() 982 AppLnkSetPrivate()
987 { 983 {
988 typPix.setAutoDelete(TRUE); 984 typPix.setAutoDelete(TRUE);
989 typPixBig.setAutoDelete(TRUE); 985 typPixBig.setAutoDelete(TRUE);
990 typName.setAutoDelete(TRUE); 986 typName.setAutoDelete(TRUE);
991 } 987 }
992 988
993 QDict<QPixmap> typPix; 989 QDict<QPixmap> typPix;
994 QDict<QPixmap> typPixBig; 990 QDict<QPixmap> typPixBig;
995 QDict<QString> typName; 991 QDict<QString> typName;
996}; 992};
997 993
998/*! 994/*!
999 \class AppLnkSet applnk.h 995 \class AppLnkSet applnk.h
1000 \brief The AppLnkSet class is a set of AppLnk objects. 996 \brief The AppLnkSet class is a set of AppLnk objects.
1001*/ 997*/
1002 998
1003/*! 999/*!
1004 \fn QStringList AppLnkSet::types() const 1000 \fn QStringList AppLnkSet::types() const
1005 1001
1006 Returns the list of \link applnk.html#Types types\endlink in the set. 1002 Returns the list of \link applnk.html#Types types\endlink in the set.
1007 1003
1008 For applications, games and settings the type is \c Application; 1004 For applications, games and settings the type is \c Application;
1009 for documents the type is the document's MIME type. 1005 for documents the type is the document's MIME type.
1010 1006
1011 \sa AppLnk::type(), typeName(), typePixmap(), typeBigPixmap() 1007 \sa AppLnk::type(), typeName(), typePixmap(), typeBigPixmap()
1012*/ 1008*/
1013 1009
1014/*! 1010/*!
1015 \fn const QList<AppLnk>& AppLnkSet::children() const 1011 \fn const QList<AppLnk>& AppLnkSet::children() const
1016 1012
1017 Returns the members of the set. 1013 Returns the members of the set.
1018*/ 1014*/
1019 1015
1020/*! 1016/*!
1021 Constructs an empty AppLnkSet. 1017 Constructs an empty AppLnkSet.
1022*/ 1018*/
1023AppLnkSet::AppLnkSet() : 1019AppLnkSet::AppLnkSet() :
1024 d(new AppLnkSetPrivate) 1020 d(new AppLnkSetPrivate)
1025{ 1021{
1026} 1022}
1027 1023
1028/*! 1024/*!
1029 Constructs an AppLnkSet that contains AppLnk objects representing 1025 Constructs an AppLnkSet that contains AppLnk objects representing
1030 all the files in the given \a directory (and any subdirectories 1026 all the files in the given \a directory (and any subdirectories
1031 recursively). 1027 recursively).
1032 1028
1033 \omit 1029 \omit
1034 The directories may contain ".directory" files which override 1030 The directories may contain ".directory" files which override
1035 any AppLnk::type() values for AppLnk objects found in the directory. 1031 any AppLnk::type() values for AppLnk objects found in the directory.
1036 This allows simple localization of application types. 1032 This allows simple localization of application types.
1037 \endomit 1033 \endomit
1038*/ 1034*/
1039AppLnkSet::AppLnkSet( const QString &directory ) : 1035AppLnkSet::AppLnkSet( const QString &directory ) :
1040 d(new AppLnkSetPrivate) 1036 d(new AppLnkSetPrivate)
1041{ 1037{
1042 QDir dir( directory ); 1038 QDir dir( directory );
1043 mFile = directory; 1039 mFile = directory;
1044 findChildren(directory,QString::null,QString::null); 1040 findChildren(directory,QString::null,QString::null);
1045} 1041}
1046 1042
1047/*! 1043/*!
1048 Detaches all AppLnk objects from the set. The set become empty and 1044 Detaches all AppLnk objects from the set. The set become empty and
1049 the caller becomes responsible for deleting the AppLnk objects. 1045 the caller becomes responsible for deleting the AppLnk objects.
1050*/ 1046*/
1051void AppLnkSet::detachChildren() 1047void AppLnkSet::detachChildren()
1052{ 1048{
1053 QListIterator<AppLnk> it( mApps ); 1049 QListIterator<AppLnk> it( mApps );
1054 for ( ; it.current(); ) { 1050 for ( ; it.current(); ) {
1055 AppLnk* a = *it; 1051 AppLnk* a = *it;
1056 ++it; 1052 ++it;
1057 a->mId = 0; 1053 a->mId = 0;
1058 } 1054 }
1059 mApps.clear(); 1055 mApps.clear();
1060} 1056}
1061 1057
1062/*! 1058/*!
1063 Destroys the set, deleting all the AppLnk objects it contains. 1059 Destroys the set, deleting all the AppLnk objects it contains.
1064 1060
1065 \sa detachChildren() 1061 \sa detachChildren()
1066*/ 1062*/
1067AppLnkSet::~AppLnkSet() 1063AppLnkSet::~AppLnkSet()
1068{ 1064{
1069 QListIterator<AppLnk> it( mApps ); 1065 QListIterator<AppLnk> it( mApps );
1070 for ( ; it.current(); ) { 1066 for ( ; it.current(); ) {
1071 AppLnk* a = *it; 1067 AppLnk* a = *it;
1072 ++it; 1068 ++it;
1073 a->mId = 0; 1069 a->mId = 0;
1074 delete a; 1070 delete a;
1075 } 1071 }
1076 delete d; 1072 delete d;
1077} 1073}
1078 1074
1079void AppLnkSet::findChildren(const QString &dr, const QString& typ, const QString& typName, int depth) 1075void AppLnkSet::findChildren(const QString &dr, const QString& typ, const QString& typName, int depth)
1080{ 1076{
1081 depth++; 1077 depth++;
1082 if ( depth > 10 ) 1078 if ( depth > 10 )
1083 return; 1079 return;
1084 1080
1085 QDir dir( dr ); 1081 QDir dir( dr );
1086 QString typNameLocal = typName; 1082 QString typNameLocal = typName;
1087 1083
1088 if ( dir.exists( ".directory" ) ) { 1084 if ( dir.exists( ".directory" ) ) {
1089 Config config( dr + "/.directory", Config::File ); 1085 Config config( dr + "/.directory", Config::File );
1090 config.setGroup( "Desktop Entry" ); 1086 config.setGroup( "Desktop Entry" );
1091 typNameLocal = config.readEntry( "Name", typNameLocal ); 1087 typNameLocal = config.readEntry( "Name", typNameLocal );
1092 if ( !typ.isEmpty() ) { 1088 if ( !typ.isEmpty() ) {
1093 QString iconFile = config.readEntry( "Icon", "AppsIcon" ); 1089 QString iconFile = config.readEntry( "Icon", "AppsIcon" );
1094 QImage unscaledIcon = Resource::loadImage( iconFile ); 1090 QImage unscaledIcon = Resource::loadImage( iconFile );
1095 QPixmap pm, bpm; 1091 QPixmap pm, bpm;
1096 pm.convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) ); 1092 pm.convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) );
1097 bpm.convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) ); 1093 bpm.convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) );
1098 d->typPix.insert(typ, new QPixmap(pm)); 1094 d->typPix.insert(typ, new QPixmap(pm));
1099 d->typPixBig.insert(typ, new QPixmap(bpm)); 1095 d->typPixBig.insert(typ, new QPixmap(bpm));
1100 d->typName.insert(typ, new QString(typNameLocal)); 1096 d->typName.insert(typ, new QString(typNameLocal));
1101 } 1097 }
1102 } 1098 }
1103 1099
1104 const QFileInfoList *list = dir.entryInfoList(); 1100 const QFileInfoList *list = dir.entryInfoList();
1105 if ( list ) { 1101 if ( list ) {
1106 QFileInfo* fi; 1102 QFileInfo* fi;
1107 bool cadded=FALSE; 1103 bool cadded=FALSE;
1108 for ( QFileInfoListIterator it(*list); (fi=*it); ++it ) { 1104 for ( QFileInfoListIterator it(*list); (fi=*it); ++it ) {
1109 QString bn = fi->fileName(); 1105 QString bn = fi->fileName();
1110// qDebug("findChildren "+bn); 1106// qDebug("findChildren "+bn);
1111 if ( bn[0] != '.' && bn != "CVS" ) { 1107 if ( bn[0] != '.' && bn != "CVS" ) {
1112 if ( fi->isDir() ) { 1108 if ( fi->isDir() ) {
1113 QString c = typ.isNull() ? bn : typ+"/"+bn; 1109 QString c = typ.isNull() ? bn : typ+"/"+bn;
1114 QString d = typNameLocal.isNull() ? bn : typNameLocal+"/"+bn; 1110 QString d = typNameLocal.isNull() ? bn : typNameLocal+"/"+bn;
1115 findChildren(fi->filePath(), c, d, depth ); 1111 findChildren(fi->filePath(), c, d, depth );
1116 } else { 1112 } else {
1117 if ( fi->extension(FALSE) == "desktop" ) { 1113 if ( fi->extension(FALSE) == "desktop" ) {
1118 AppLnk* app = new AppLnk( fi->filePath() ); 1114 AppLnk* app = new AppLnk( fi->filePath() );
1119#ifdef QT_NO_QWS_MULTIPROCESS 1115#ifdef QT_NO_QWS_MULTIPROCESS
1120 if ( !Global::isBuiltinCommand( app->exec() ) ) 1116 if ( !Global::isBuiltinCommand( app->exec() ) )
1121 delete app; 1117 delete app;
1122 else 1118 else
1123#endif 1119#endif
1124 { 1120 {
1125 if ( !typ.isEmpty() ) { 1121 if ( !typ.isEmpty() ) {
1126 if ( !cadded ) { 1122 if ( !cadded ) {
1127 typs.append(typ); 1123 typs.append(typ);
1128 cadded = TRUE; 1124 cadded = TRUE;
1129 } 1125 }
1130 app->setType(typ); 1126 app->setType(typ);
1131 } 1127 }
1132 add(app); 1128 add(app);
1133 } 1129 }
1134 } 1130 }
1135 } 1131 }
1136 } 1132 }
1137 } 1133 }
1138 } 1134 }
1139} 1135}
1140 1136
1141/*! 1137/*!
1142 Adds AppLnk \a f to the set. The set takes responsibility for 1138 Adds AppLnk \a f to the set. The set takes responsibility for
1143 deleting \a f. 1139 deleting \a f.
1144 1140
1145 \sa remove() 1141 \sa remove()
1146*/ 1142*/
1147void AppLnkSet::add( AppLnk *f ) 1143void AppLnkSet::add( AppLnk *f )
1148{ 1144{
1149 if ( f->mId == 0 ) { 1145 if ( f->mId == 0 ) {
1150 AppLnk::lastId++; 1146 AppLnk::lastId++;
1151 f->mId = AppLnk::lastId; 1147 f->mId = AppLnk::lastId;
1152 mApps.append( f ); 1148 mApps.append( f );
1153 } else { 1149 } else {
1154 qWarning("Attempt to add an AppLnk twice"); 1150 qWarning("Attempt to add an AppLnk twice");
1155 } 1151 }
1156} 1152}
1157 1153
1158/*! 1154/*!
1159 Removes AppLnk \a f to the set. The caller becomes responsible for 1155 Removes AppLnk \a f to the set. The caller becomes responsible for
1160 deleting \a f. Returns TRUE if \a f was in the set; otherwise 1156 deleting \a f. Returns TRUE if \a f was in the set; otherwise
1161 returns FALSE. 1157 returns FALSE.
1162 1158
1163 \sa add() 1159 \sa add()
1164*/ 1160*/
1165bool AppLnkSet::remove( AppLnk *f ) 1161bool AppLnkSet::remove( AppLnk *f )
1166{ 1162{
1167 if ( mApps.remove( f ) ) { 1163 if ( mApps.remove( f ) ) {
1168 f->mId = 0; 1164 f->mId = 0;
1169 return TRUE; 1165 return TRUE;
1170 } 1166 }
1171 return FALSE; 1167 return FALSE;
1172} 1168}
1173 1169
1174 1170
1175/*! 1171/*!
1176 Returns the localized name for type \a t. 1172 Returns the localized name for type \a t.
1177 1173
1178 For applications, games and settings the type is \c Application; 1174 For applications, games and settings the type is \c Application;
1179 for documents the type is the document's MIME type. 1175 for documents the type is the document's MIME type.
1180*/ 1176*/
1181QString AppLnkSet::typeName( const QString& t ) const 1177QString AppLnkSet::typeName( const QString& t ) const
1182{ 1178{
1183 QString *st = d->typName.find(t); 1179 QString *st = d->typName.find(t);
1184 return st ? *st : QString::null; 1180 return st ? *st : QString::null;
1185} 1181}
1186 1182
1187/*! 1183/*!
1188 Returns the small pixmap associated with type \a t. 1184 Returns the small pixmap associated with type \a t.
1189 1185
1190 For applications, games and settings the type is \c Application; 1186 For applications, games and settings the type is \c Application;
1191 for documents the type is the document's MIME type. 1187 for documents the type is the document's MIME type.
1192*/ 1188*/
1193QPixmap AppLnkSet::typePixmap( const QString& t ) const 1189QPixmap AppLnkSet::typePixmap( const QString& t ) const
1194{ 1190{
1195 QPixmap *pm = d->typPix.find(t); 1191 QPixmap *pm = d->typPix.find(t);
1196 return pm ? *pm : QPixmap(); 1192 return pm ? *pm : QPixmap();
1197} 1193}
1198 1194
1199/*! 1195/*!
1200 Returns the large pixmap associated with type \a t. 1196 Returns the large pixmap associated with type \a t.
1201 1197
1202 For applications, games and settings the type is \c Application; 1198 For applications, games and settings the type is \c Application;
1203 for documents the type is the document's MIME type. 1199 for documents the type is the document's MIME type.
1204*/ 1200*/
1205QPixmap AppLnkSet::typeBigPixmap( const QString& t ) const 1201QPixmap AppLnkSet::typeBigPixmap( const QString& t ) const
1206{ 1202{
1207 QPixmap *pm = d->typPixBig.find(t); 1203 QPixmap *pm = d->typPixBig.find(t);
1208 return pm ? *pm : QPixmap(); 1204 return pm ? *pm : QPixmap();
1209} 1205}
1210 1206
1211/*! 1207/*!
1212 Returns the AppLnk with the given \a id. 1208 Returns the AppLnk with the given \a id.
1213*/ 1209*/
1214const AppLnk *AppLnkSet::find( int id ) const 1210const AppLnk *AppLnkSet::find( int id ) const
1215{ 1211{
1216 QListIterator<AppLnk> it( children() ); 1212 QListIterator<AppLnk> it( children() );
1217 1213
1218 for ( ; it.current(); ++it ) { 1214 for ( ; it.current(); ++it ) {
1219 const AppLnk *app = it.current(); 1215 const AppLnk *app = it.current();
1220 if ( app->id() == id ) 1216 if ( app->id() == id )
1221 return app; 1217 return app;
1222 } 1218 }
1223 1219
1224 return 0; 1220 return 0;
1225} 1221}
1226 1222
1227/*! 1223/*!
1228 Returns the AppLnk with the given \a exec attribute. 1224 Returns the AppLnk with the given \a exec attribute.
1229*/ 1225*/
1230const AppLnk *AppLnkSet::findExec( const QString& exec ) const 1226const AppLnk *AppLnkSet::findExec( const QString& exec ) const
1231{ 1227{
1232 QListIterator<AppLnk> it( children() ); 1228 QListIterator<AppLnk> it( children() );
1233 1229
1234 for ( ; it.current(); ++it ) { 1230 for ( ; it.current(); ++it ) {
1235 const AppLnk *app = it.current(); 1231 const AppLnk *app = it.current();
1236 if ( app->exec() == exec ) 1232 if ( app->exec() == exec )
1237 return app; 1233 return app;
1238 } 1234 }
1239 1235
1240 return 0; 1236 return 0;
1241} 1237}
1242 1238
1243/*! 1239/*!
1244 \class DocLnkSet applnk.h 1240 \class DocLnkSet applnk.h
1245 \brief The DocLnkSet class is a set of DocLnk objects. 1241 \brief The DocLnkSet class is a set of DocLnk objects.
1246*/ 1242*/
1247 1243
1248/*! 1244/*!
1249 \fn const QList<DocLnk>& DocLnkSet::children() const 1245 \fn const QList<DocLnk>& DocLnkSet::children() const
1250 1246
1251 Returns the members of the set. 1247 Returns the members of the set.
1252*/ 1248*/
1253 1249
1254/*! 1250/*!
1255 Constructs an empty DocLnkSet. 1251 Constructs an empty DocLnkSet.
1256 1252
1257 \sa appendFrom() 1253 \sa appendFrom()
1258*/ 1254*/
1259DocLnkSet::DocLnkSet() 1255DocLnkSet::DocLnkSet()
1260{ 1256{
1261} 1257}
1262 1258
1263/*! 1259/*!
1264 Constructs a DocLnkSet that contains DocLnk objects representing all 1260 Constructs a DocLnkSet that contains DocLnk objects representing all
1265 the files in the \a directory (and any subdirectories, recursively). 1261 the files in the \a directory (and any subdirectories, recursively).
1266 1262
1267 If \a mimefilter is not null, 1263 If \a mimefilter is not null,
1268 only documents with a MIME type matching \a mimefilter are selected. 1264 only documents with a MIME type matching \a mimefilter are selected.
1269 The value may contain multiple wild-card patterns separated by ";", 1265 The value may contain multiple wild-card patterns separated by ";",
1270 such as \c{*o/mpeg;audio/x-wav}. 1266 such as \c{*o/mpeg;audio/x-wav}.
1271 1267
1272 See also \link applnk.html#files-and-links Files and Links\endlink. 1268 See also \link applnk.html#files-and-links Files and Links\endlink.
1273 1269
1274*/ 1270*/
1275DocLnkSet::DocLnkSet( const QString &directory, const QString& mimefilter ) : 1271DocLnkSet::DocLnkSet( const QString &directory, const QString& mimefilter ) :
1276 AppLnkSet() 1272 AppLnkSet()
1277{ 1273{
1278 QDir dir( directory ); 1274 QDir dir( directory );
1279 mFile = dir.dirName(); 1275 mFile = dir.dirName();
1280 QDict<void> reference; 1276 QDict<void> reference;
1281 1277
1282 QStringList subFilter = QStringList::split(";", mimefilter); 1278 QStringList subFilter = QStringList::split(";", mimefilter);
1283 QValueList<QRegExp> mimeFilters; 1279 QValueList<QRegExp> mimeFilters;
1284 for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++ it ) 1280 for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++ it )
1285 mimeFilters.append( QRegExp(*it, FALSE, TRUE) ); 1281 mimeFilters.append( QRegExp(*it, FALSE, TRUE) );
1286 1282
1287 findChildren(directory, mimeFilters, reference); 1283 findChildren(directory, mimeFilters, reference);
1288 1284
1289 const QList<DocLnk> &list = children(); 1285 const QList<DocLnk> &list = children();
1290 for ( QListIterator<DocLnk> it( list ); it.current(); ++it ) { 1286 for ( QListIterator<DocLnk> it( list ); it.current(); ++it ) {
1291 reference.remove( (*it)->file() ); 1287 reference.remove( (*it)->file() );
1292 } 1288 }
1293 for ( QDictIterator<void> dit(reference); dit.current(); ++dit ) { 1289 for ( QDictIterator<void> dit(reference); dit.current(); ++dit ) {
1294 if ( dit.current() == (void*)2 ) { 1290 if ( dit.current() == (void*)2 ) {
1295 // Unreferenced, make an unwritten link 1291 // Unreferenced, make an unwritten link
1296 DocLnk* dl = new DocLnk; 1292 DocLnk* dl = new DocLnk;
1297 QFileInfo fi( dit.currentKey() ); 1293 QFileInfo fi( dit.currentKey() );
1298 dl->setFile(fi.filePath()); 1294 dl->setFile(fi.filePath());
1299 dl->setName(fi.baseName()); 1295 dl->setName(fi.baseName());
1300 // #### default to current path? 1296 // #### default to current path?
1301 // dl->setCategories( ... ); 1297 // dl->setCategories( ... );
1302 bool match = mimefilter.isNull(); 1298 bool match = mimefilter.isNull();
1303 if ( !match ) 1299 if ( !match )
1304 for( QValueList<QRegExp>::Iterator it = mimeFilters.begin(); it != mimeFilters.end() && !match; ++ it ) 1300 for( QValueList<QRegExp>::Iterator it = mimeFilters.begin(); it != mimeFilters.end() && !match; ++ it )
1305 if ( (*it).match(dl->type()) >= 0 ) 1301 if ( (*it).match(dl->type()) >= 0 )
1306 match = TRUE; 1302 match = TRUE;
1307 if ( match /* && dl->type() != "application/octet-stream" */ 1303 if ( match /* && dl->type() != "application/octet-stream" */
1308 && !!dl->exec() ) 1304 && !!dl->exec() )
1309 add(dl); 1305 add(dl);
1310 else 1306 else
1311 delete dl; 1307 delete dl;
1312 } 1308 }
1313 } 1309 }
1314} 1310}
1315 1311
1316// other becomes empty 1312// other becomes empty
1317/*! 1313/*!
1318 Transfers all DocLnk objects from \a other to this set. \a other becomes 1314 Transfers all DocLnk objects from \a other to this set. \a other becomes
1319 empty. 1315 empty.
1320*/ 1316*/
1321void DocLnkSet::appendFrom( DocLnkSet& other ) 1317void DocLnkSet::appendFrom( DocLnkSet& other )
1322{ 1318{
1323 if ( &other == this ) 1319 if ( &other == this )
1324 return; 1320 return;
1325 QListIterator<AppLnk> it( other.mApps ); 1321 QListIterator<AppLnk> it( other.mApps );
1326 for ( ; it.current(); ) { 1322 for ( ; it.current(); ) {
1327 mApps.append(*it); 1323 mApps.append(*it);
1328 ++it; 1324 ++it;
1329 } 1325 }
1330 other.mApps.clear(); 1326 other.mApps.clear();
1331} 1327}
1332 1328
1333void DocLnkSet::findChildren(const QString &dr, const QValueList<QRegExp> &mimeFilters, QDict<void> &reference, int depth) 1329void DocLnkSet::findChildren(const QString &dr, const QValueList<QRegExp> &mimeFilters, QDict<void> &reference, int depth)
1334{ 1330{
1335 depth++; 1331 depth++;
1336 if ( depth > 10 ) 1332 if ( depth > 10 )
1337 return; 1333 return;
1338 1334
1339 QDir dir( dr ); 1335 QDir dir( dr );
1340 1336
1341 /* Opie got a different approach 1337 /* Opie got a different approach
1342 * I guess it's geek vs. consumer 1338 * I guess it's geek vs. consumer
1343 * in this case to be discussed 1339 * in this case to be discussed
1344 */ 1340 */
1345 if ( dir.exists( ".Qtopia-ignore" ) ) 1341 if ( dir.exists( ".Qtopia-ignore" ) )
1346 return; 1342 return;
1347 1343
1348 const QFileInfoList *list = dir.entryInfoList(); 1344 const QFileInfoList *list = dir.entryInfoList();
1349 if ( list ) { 1345 if ( list ) {
1350 QFileInfo* fi; 1346 QFileInfo* fi;
1351 for ( QFileInfoListIterator it(*list); (fi=*it); ++it ) { 1347 for ( QFileInfoListIterator it(*list); (fi=*it); ++it ) {
1352 QString bn = fi->fileName(); 1348 QString bn = fi->fileName();
1353 if ( bn[0] != '.' ) { 1349 if ( bn[0] != '.' ) {
1354 if ( fi->isDir() ) { 1350 if ( fi->isDir() ) {
1355 if ( bn != "CVS" && bn != "Qtopia" && bn != "QtPalmtop" ) 1351 if ( bn != "CVS" && bn != "Qtopia" && bn != "QtPalmtop" )
1356 findChildren(fi->filePath(), mimeFilters, reference, depth); 1352 findChildren(fi->filePath(), mimeFilters, reference, depth);
1357 } else { 1353 } else {
1358 if ( fi->extension(FALSE) == "desktop" ) { 1354 if ( fi->extension(FALSE) == "desktop" ) {
1359 DocLnk* dl = new DocLnk( fi->filePath() ); 1355 DocLnk* dl = new DocLnk( fi->filePath() );
1360 QFileInfo fi2(dl->file()); 1356 QFileInfo fi2(dl->file());
1361 bool match = FALSE; 1357 bool match = FALSE;
1362 if ( !fi2.exists() ) { 1358 if ( !fi2.exists() ) {
1363 dir.remove( dl->file() ); 1359 dir.remove( dl->file() );
1364 } 1360 }
1365 if ( mimeFilters.count() == 0 ) { 1361 if ( mimeFilters.count() == 0 ) {
1366 add( dl ); 1362 add( dl );
1367 match = TRUE; 1363 match = TRUE;
1368 } else { 1364 } else {
1369 for( QValueList<QRegExp>::ConstIterator it = mimeFilters.begin(); it != mimeFilters.end(); ++ it ) { 1365 for( QValueList<QRegExp>::ConstIterator it = mimeFilters.begin(); it != mimeFilters.end(); ++ it ) {
1370 if ( (*it).match(dl->type()) >= 0 ) { 1366 if ( (*it).match(dl->type()) >= 0 ) {
1371 add(dl); 1367 add(dl);
1372 match = TRUE; 1368 match = TRUE;
1373 } 1369 }
1374 } 1370 }
1375 } 1371 }
1376 if ( !match ) 1372 if ( !match )
1377 delete dl; 1373 delete dl;
1378 } else { 1374 } else {
1379 if ( !reference.find(fi->fileName()) ) 1375 if ( !reference.find(fi->fileName()) )
1380 reference.insert(fi->filePath(), (void*)2); 1376 reference.insert(fi->filePath(), (void*)2);
1381 } 1377 }
1382 } 1378 }
1383 } 1379 }
1384 } 1380 }
1385 } 1381 }
1386} 1382}
1387 1383
1388/*! 1384/*!
1389 \class DocLnk applnk.h 1385 \class DocLnk applnk.h
1390 \brief The DocLnk class represents loaded document references. 1386 \brief The DocLnk class represents loaded document references.
1391*/ 1387*/
1392 1388
1393/*! 1389/*!
1394 \fn DocLnk::DocLnk( const DocLnk &o ) 1390 \fn DocLnk::DocLnk( const DocLnk &o )
1395 1391
1396 Copies \a o. 1392 Copies \a o.
1397*/ 1393*/
1398 1394
1399/*! 1395/*!
1400 Constructs a DocLnk from a valid .desktop \a file or a new .desktop 1396 Constructs a DocLnk from a valid .desktop \a file or a new .desktop
1401 \a file for other files. 1397 \a file for other files.
1402*/ 1398*/
1403DocLnk::DocLnk( const QString &file ) : 1399DocLnk::DocLnk( const QString &file ) :
1404 AppLnk(file) 1400 AppLnk(file)
1405{ 1401{
1406 init(file); 1402 init(file);
1407} 1403}
1408 1404
1409/*! 1405/*!
1410 Constructs a DocLnk from a valid .desktop \a file or a new .desktop 1406 Constructs a DocLnk from a valid .desktop \a file or a new .desktop
1411 \a file for other files. If \a may_be_desktopfile is TRUE, then an 1407 \a file for other files. If \a may_be_desktopfile is TRUE, then an
1412 attempt is made to read \a file as a .desktop file; if that fails it 1408 attempt is made to read \a file as a .desktop file; if that fails it
1413 is read as a normal file. 1409 is read as a normal file.
1414*/ 1410*/
1415DocLnk::DocLnk( const QString &file, bool may_be_desktopfile ) : 1411DocLnk::DocLnk( const QString &file, bool may_be_desktopfile ) :
1416 AppLnk(may_be_desktopfile ? file : QString::null) 1412 AppLnk(may_be_desktopfile ? file : QString::null)
1417{ 1413{
1418 init(file); 1414 init(file);
1419} 1415}
1420 1416
1421void DocLnk::init(const QString &file) 1417void DocLnk::init(const QString &file)
1422{ 1418{
1423 if ( isValid() ) { 1419 if ( isValid() ) {
1424#ifndef FORCED_DIR_STRUCTURE_WAY 1420#ifndef FORCED_DIR_STRUCTURE_WAY
1425 if ( mType.isNull() ) 1421 if ( mType.isNull() )
1426 // try to infer it 1422 // try to infer it
1427#endif 1423#endif
1428 { 1424 {
1429 int s0 = file.findRev('/'); 1425 int s0 = file.findRev('/');
1430 if ( s0 > 0 ) { 1426 if ( s0 > 0 ) {
1431 int s1 = file.findRev('/',s0-1); 1427 int s1 = file.findRev('/',s0-1);
1432 if ( s1 > 0 ) { 1428 if ( s1 > 0 ) {
1433 int s2 = file.findRev('/',s1-1); 1429 int s2 = file.findRev('/',s1-1);
1434 if ( s2 > 0 ) { 1430 if ( s2 > 0 ) {
1435 mType = file.mid(s2+1,s0-s2-1); 1431 mType = file.mid(s2+1,s0-s2-1);
1436 } 1432 }
1437 } 1433 }
1438 } 1434 }
1439 } 1435 }
1440 } else if ( QFile::exists(file) ) { 1436 } else if ( QFile::exists(file) ) {
1441 QString n = file; 1437 QString n = file;
1442 n.replace(QRegExp(".*/"),""); 1438 n.replace(QRegExp(".*/"),"");
1443 n.replace(QRegExp("\\..*"),""); 1439 n.replace(QRegExp("\\..*"),"");
1444 setName( n ); 1440 setName( n );
1445 setFile( file ); 1441 setFile( file );
1446 } 1442 }
1447 MimeType mt(mType); 1443 MimeType mt(mType);
1448 if( mt.application() ) 1444 if( mt.application() )
1449 mExec = mt.application()->exec(); 1445 mExec = mt.application()->exec();
1450} 1446}
1451 1447
1452/*! 1448/*!
1453 Constructs an invalid DocLnk. 1449 Constructs an invalid DocLnk.
1454*/ 1450*/
1455DocLnk::DocLnk() 1451DocLnk::DocLnk()
1456{ 1452{
1457} 1453}
1458 1454
1459/*! 1455/*!
1460 Destroys the DocLnk. Just like AppLnk objects, a run-time error 1456 Destroys the DocLnk. Just like AppLnk objects, a run-time error
1461 occurs if the DocLnk is a member of a DocLnkSet (or AppLnkSet). 1457 occurs if the DocLnk is a member of a DocLnkSet (or AppLnkSet).
1462*/ 1458*/
1463DocLnk::~DocLnk() 1459DocLnk::~DocLnk()
1464{ 1460{
1465} 1461}
1466 1462
1467/*! 1463/*!
1468 \reimp 1464 \reimp
1469*/ 1465*/
1470QString DocLnk::exec() const 1466QString DocLnk::exec() const
1471{ 1467{
1472 MimeType mt(type()); 1468 MimeType mt(type());
1473 const AppLnk* app = mt.application(); 1469 const AppLnk* app = mt.application();
1474 if ( app ) 1470 if ( app )
1475 return app->exec(); 1471 return app->exec();
1476 else 1472 else
1477 return QString::null; 1473 return QString::null;
1478} 1474}
1479 1475
1480/*! 1476/*!
1481 \reimp 1477 \reimp
1482*/ 1478*/
1483void DocLnk::invoke(const QStringList& args) const 1479void DocLnk::invoke(const QStringList& args) const
1484{ 1480{
1485 MimeType mt(type()); 1481 MimeType mt(type());
1486 const AppLnk* app = mt.application(); 1482 const AppLnk* app = mt.application();
1487 if ( app ) { 1483 if ( app ) {
1488 QStringList a = args; 1484 QStringList a = args;
1489 if ( linkFileKnown() && QFile::exists( linkFile() ) ) 1485 if ( linkFileKnown() && QFile::exists( linkFile() ) )
1490 a.append(linkFile()); 1486 a.append(linkFile());
1491 else 1487 else
1492 a.append(file()); 1488 a.append(file());
1493 app->execute(a); 1489 app->execute(a);
1494 } 1490 }
1495} 1491}
1496 1492
1497 1493
diff --git a/library/categoryedit_p.cpp b/library/categoryedit_p.cpp
index 9321259..14ac2e1 100644
--- a/library/categoryedit_p.cpp
+++ b/library/categoryedit_p.cpp
@@ -1,230 +1,227 @@
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 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 "categoryedit_p.h" 21#include "categoryedit_p.h"
22 22
23#include <qpe/categories.h> 23#include <qpe/categories.h>
24 24
25#include <qdir.h> 25#include <qdir.h>
26#include <qcheckbox.h> 26#include <qcheckbox.h>
27#include <qlineedit.h> 27#include <qlineedit.h>
28#include <qlistview.h>
29#include <qstringlist.h>
30#include <qtoolbutton.h>
31 28
32#include <sys/types.h> 29#include <sys/types.h>
33#include <sys/stat.h> 30#include <sys/stat.h>
34 31
35#include <stdlib.h> 32#include <stdlib.h>
36 33
37 34
38using namespace Qtopia; 35using namespace Qtopia;
39 36
40class CategoryEditPrivate 37class CategoryEditPrivate
41{ 38{
42public: 39public:
43 CategoryEditPrivate( QWidget *parent, const QString &appName ) 40 CategoryEditPrivate( QWidget *parent, const QString &appName )
44 : mCategories( parent, "" ), 41 : mCategories( parent, "" ),
45 mStrApp( appName ) 42 mStrApp( appName )
46 { 43 {
47 editItem = 0; 44 editItem = 0;
48 mCategories.load( categoryFileName() ); 45 mCategories.load( categoryFileName() );
49 } 46 }
50 Categories mCategories; 47 Categories mCategories;
51 QListViewItem *editItem; 48 QListViewItem *editItem;
52 QString mStrApp; 49 QString mStrApp;
53 QString mVisible; 50 QString mVisible;
54}; 51};
55 52
56CategoryEdit::CategoryEdit( QWidget *parent, const char *name ) 53CategoryEdit::CategoryEdit( QWidget *parent, const char *name )
57 : CategoryEditBase( parent, name ) 54 : CategoryEditBase( parent, name )
58{ 55{
59 d = 0; 56 d = 0;
60} 57}
61 58
62CategoryEdit::CategoryEdit( const QArray<int> &recCats, 59CategoryEdit::CategoryEdit( const QArray<int> &recCats,
63 const QString &appName, const QString &visibleName, 60 const QString &appName, const QString &visibleName,
64 QWidget *parent, const char *name ) 61 QWidget *parent, const char *name )
65 : CategoryEditBase( parent, name ) 62 : CategoryEditBase( parent, name )
66{ 63{
67 d = 0; 64 d = 0;
68 setCategories( recCats, appName, visibleName ); 65 setCategories( recCats, appName, visibleName );
69} 66}
70 67
71void CategoryEdit::setCategories( const QArray<int> &recCats, 68void CategoryEdit::setCategories( const QArray<int> &recCats,
72 const QString &appName, const QString &visibleName ) 69 const QString &appName, const QString &visibleName )
73{ 70{
74 if ( !d ) 71 if ( !d )
75 d = new CategoryEditPrivate( (QWidget*)parent(), name() ); 72 d = new CategoryEditPrivate( (QWidget*)parent(), name() );
76 d->mStrApp = appName; 73 d->mStrApp = appName;
77 d->mVisible = visibleName; 74 d->mVisible = visibleName;
78 75
79 QStringList appCats = d->mCategories.labels( d->mStrApp ); 76 QStringList appCats = d->mCategories.labels( d->mStrApp );
80 QArray<int> cats = d->mCategories.ids(d->mStrApp, appCats); 77 QArray<int> cats = d->mCategories.ids(d->mStrApp, appCats);
81 lvView->clear(); 78 lvView->clear();
82 79
83 QStringList::ConstIterator it; 80 QStringList::ConstIterator it;
84 int i, j; 81 int i, j;
85 for ( i = 0, it = appCats.begin(); it != appCats.end(); i++, ++it ) { 82 for ( i = 0, it = appCats.begin(); it != appCats.end(); i++, ++it ) {
86 QCheckListItem *chk; 83 QCheckListItem *chk;
87 chk = new QCheckListItem( lvView, (*it), QCheckListItem::CheckBox ); 84 chk = new QCheckListItem( lvView, (*it), QCheckListItem::CheckBox );
88 if ( !d->mCategories.isGlobal((*it)) ) 85 if ( !d->mCategories.isGlobal((*it)) )
89 chk->setText( 1, tr(d->mVisible) ); 86 chk->setText( 1, tr(d->mVisible) );
90 else 87 else
91 chk->setText( 1, tr("All") ); 88 chk->setText( 1, tr("All") );
92 // Is this record using this category, then we should check it 89 // Is this record using this category, then we should check it
93 for ( j = 0; j < int(recCats.count()); j++ ) { 90 for ( j = 0; j < int(recCats.count()); j++ ) {
94 if ( cats[i] == recCats[j] ) { 91 if ( cats[i] == recCats[j] ) {
95 chk->setOn( true ); 92 chk->setOn( true );
96 break; 93 break;
97 } 94 }
98 } 95 }
99 } 96 }
100 lvView->setSorting( 0, TRUE ); 97 lvView->setSorting( 0, TRUE );
101 lvView->sort(); 98 lvView->sort();
102 if ( lvView->childCount() < 1 ) 99 if ( lvView->childCount() < 1 )
103 txtCat->setEnabled( FALSE ); 100 txtCat->setEnabled( FALSE );
104 else { 101 else {
105 lvView->setSelected( lvView->firstChild(), true ); 102 lvView->setSelected( lvView->firstChild(), true );
106 } 103 }
107} 104}
108 105
109CategoryEdit::~CategoryEdit() 106CategoryEdit::~CategoryEdit()
110{ 107{
111 if ( d ) 108 if ( d )
112 delete d; 109 delete d;
113} 110}
114 111
115void CategoryEdit::slotSetText( QListViewItem *selected ) 112void CategoryEdit::slotSetText( QListViewItem *selected )
116{ 113{
117 d->editItem = selected; 114 d->editItem = selected;
118 if ( !d->editItem ) 115 if ( !d->editItem )
119 return; 116 return;
120 txtCat->setText( d->editItem->text(0) ); 117 txtCat->setText( d->editItem->text(0) );
121 txtCat->setEnabled( true ); 118 txtCat->setEnabled( true );
122 if ( d->editItem->text(1) == tr("All") ) 119 if ( d->editItem->text(1) == tr("All") )
123 chkGlobal->setChecked( true ); 120 chkGlobal->setChecked( true );
124 else 121 else
125 chkGlobal->setChecked( false ); 122 chkGlobal->setChecked( false );
126} 123}
127 124
128void CategoryEdit::slotAdd() 125void CategoryEdit::slotAdd()
129{ 126{
130 QString name = tr( "New Category" ); 127 QString name = tr( "New Category" );
131 bool insertOk = FALSE; 128 bool insertOk = FALSE;
132 int num = 0; 129 int num = 0;
133 while ( !insertOk ) { 130 while ( !insertOk ) {
134 if ( num++ > 0 ) 131 if ( num++ > 0 )
135 name = tr("New Category ") + QString::number(num); 132 name = tr("New Category ") + QString::number(num);
136 insertOk = d->mCategories.addCategory( d->mStrApp, name ); 133 insertOk = d->mCategories.addCategory( d->mStrApp, name );
137 } 134 }
138 QCheckListItem *chk; 135 QCheckListItem *chk;
139 chk = new QCheckListItem( lvView, name, QCheckListItem::CheckBox ); 136 chk = new QCheckListItem( lvView, name, QCheckListItem::CheckBox );
140 if ( !chkGlobal->isChecked() ) 137 if ( !chkGlobal->isChecked() )
141 chk->setText( 1, tr(d->mVisible) ); 138 chk->setText( 1, tr(d->mVisible) );
142 else 139 else
143 chk->setText( 1, tr("All") ); 140 chk->setText( 1, tr("All") );
144 141
145 lvView->setSelected( chk, TRUE ); 142 lvView->setSelected( chk, TRUE );
146 txtCat->selectAll(); 143 txtCat->selectAll();
147 txtCat->setFocus(); 144 txtCat->setFocus();
148} 145}
149 146
150void CategoryEdit::slotRemove() 147void CategoryEdit::slotRemove()
151{ 148{
152 d->editItem = lvView->selectedItem(); 149 d->editItem = lvView->selectedItem();
153 if ( d->editItem ) { 150 if ( d->editItem ) {
154 QListViewItem *sibling = d->editItem->nextSibling(); 151 QListViewItem *sibling = d->editItem->nextSibling();
155 152
156 d->mCategories.removeCategory( d->mStrApp, d->editItem->text(0) ); 153 d->mCategories.removeCategory( d->mStrApp, d->editItem->text(0) );
157 154
158 delete d->editItem; 155 delete d->editItem;
159 d->editItem = 0; 156 d->editItem = 0;
160 157
161 if ( sibling ) 158 if ( sibling )
162 lvView->setSelected( sibling, TRUE ); 159 lvView->setSelected( sibling, TRUE );
163 } 160 }
164 if ( lvView->childCount() < 1 ) { 161 if ( lvView->childCount() < 1 ) {
165 txtCat->clear(); 162 txtCat->clear();
166 txtCat->setEnabled( FALSE ); 163 txtCat->setEnabled( FALSE );
167 } 164 }
168} 165}
169 166
170void CategoryEdit::slotSetGlobal( bool isChecked ) 167void CategoryEdit::slotSetGlobal( bool isChecked )
171{ 168{
172 if ( d->editItem ) { 169 if ( d->editItem ) {
173 if ( isChecked ) 170 if ( isChecked )
174 d->editItem->setText( 1, tr("All") ); 171 d->editItem->setText( 1, tr("All") );
175 else 172 else
176 d->editItem->setText( 1, tr(d->mVisible) ); 173 d->editItem->setText( 1, tr(d->mVisible) );
177 174
178 d->mCategories.setGlobal( d->mStrApp, d->editItem->text( 0 ), isChecked ); 175 d->mCategories.setGlobal( d->mStrApp, d->editItem->text( 0 ), isChecked );
179 } 176 }
180} 177}
181 178
182void CategoryEdit::slotTextChanged( const QString &strNew ) 179void CategoryEdit::slotTextChanged( const QString &strNew )
183{ 180{
184 if ( d->editItem ) { 181 if ( d->editItem ) {
185 if ( chkGlobal->isChecked() ) 182 if ( chkGlobal->isChecked() )
186 d->mCategories.renameGlobalCategory( d->editItem->text(0), strNew ); 183 d->mCategories.renameGlobalCategory( d->editItem->text(0), strNew );
187 else 184 else
188 d->mCategories.renameCategory( d->mStrApp, d->editItem->text(0), strNew ); 185 d->mCategories.renameCategory( d->mStrApp, d->editItem->text(0), strNew );
189 d->editItem->setText( 0, strNew ); 186 d->editItem->setText( 0, strNew );
190 } 187 }
191} 188}
192 189
193QArray<int> CategoryEdit::newCategories() 190QArray<int> CategoryEdit::newCategories()
194{ 191{
195 QArray<int> a; 192 QArray<int> a;
196 if ( d ) { 193 if ( d ) {
197 d->mCategories.save( categoryFileName() ); 194 d->mCategories.save( categoryFileName() );
198 QListViewItemIterator it( lvView ); 195 QListViewItemIterator it( lvView );
199 QValueList<int> l; 196 QValueList<int> l;
200 for ( ; it.current(); ++it ) { 197 for ( ; it.current(); ++it ) {
201 if ( reinterpret_cast<QCheckListItem*>(it.current())->isOn() ) 198 if ( reinterpret_cast<QCheckListItem*>(it.current())->isOn() )
202 l.append( d->mCategories.id( d->mStrApp, it.current()->text(0) ) ); 199 l.append( d->mCategories.id( d->mStrApp, it.current()->text(0) ) );
203 } 200 }
204 uint i = 0; 201 uint i = 0;
205 a.resize( l.count() ); 202 a.resize( l.count() );
206 for ( QValueList<int>::Iterator lit = l.begin(); lit != l.end(); ++lit ) 203 for ( QValueList<int>::Iterator lit = l.begin(); lit != l.end(); ++lit )
207 a[i++] = *lit; 204 a[i++] = *lit;
208 } 205 }
209 return a; 206 return a;
210} 207}
211 208
212void CategoryEdit::accept() 209void CategoryEdit::accept()
213{ 210{
214 // write our categories out... 211 // write our categories out...
215 d->mCategories.save( categoryFileName() ); 212 d->mCategories.save( categoryFileName() );
216 // QDialog::accept(); 213 // QDialog::accept();
217} 214}
218 215
219QString categoryFileName() 216QString categoryFileName()
220{ 217{
221 QDir dir = (QString(getenv("HOME")) + "/Settings"); 218 QDir dir = (QString(getenv("HOME")) + "/Settings");
222 if ( !dir.exists() ) 219 if ( !dir.exists() )
223 mkdir( dir.path().local8Bit(), 0700 ); 220 mkdir( dir.path().local8Bit(), 0700 );
224 return dir.path() + "/" + "Categories" + ".xml"; 221 return dir.path() + "/" + "Categories" + ".xml";
225} 222}
226 223
227void CategoryEdit::kludge() 224void CategoryEdit::kludge()
228{ 225{
229 lvView->setMaximumHeight( 130 ); 226 lvView->setMaximumHeight( 130 );
230} 227}
diff --git a/library/categorymenu.cpp b/library/categorymenu.cpp
index 5d7adf7..9bbb448 100644
--- a/library/categorymenu.cpp
+++ b/library/categorymenu.cpp
@@ -1,162 +1,160 @@
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 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 "categorymenu.h" 21#include "categorymenu.h"
22#include "backend/categories.h" 22#include "backend/categories.h"
23#include "categoryselect.h" 23#include "categoryselect.h"
24#include <qstring.h>
25#include <qmap.h>
26 24
27/*! 25/*!
28 \class CategoryMenu 26 \class CategoryMenu
29 \brief The CategoryMenu widget aids in filtering records or files by Category. 27 \brief The CategoryMenu widget aids in filtering records or files by Category.
30 28
31 The CategoryMenu widget provides a popup menu that will make filtering records 29 The CategoryMenu widget provides a popup menu that will make filtering records
32 or files by category much easier. The widget will lookup the available 30 or files by category much easier. The widget will lookup the available
33 categories for an application, populate the menu, and keep a track of which 31 categories for an application, populate the menu, and keep a track of which
34 categories are being filtered against. A set of categories can be tested 32 categories are being filtered against. A set of categories can be tested
35 by the isSelected() function to see if a record or file containing those 33 by the isSelected() function to see if a record or file containing those
36 categories would be allowed through by the filter. 34 categories would be allowed through by the filter.
37 35
38 \warning Currently this class is not suitable for extending. 36 \warning Currently this class is not suitable for extending.
39 37
40 \ingroup qtopiaemb 38 \ingroup qtopiaemb
41*/ 39*/
42 40
43/*! 41/*!
44 \fn void CategoryMenu::categoryChange() 42 \fn void CategoryMenu::categoryChange()
45 This signal is emitted when the user selects a different category in the 43 This signal is emitted when the user selects a different category in the
46 menu, hence changing what records or files should be selected. 44 menu, hence changing what records or files should be selected.
47*/ 45*/
48 46
49/*! 47/*!
50 Creates a new CategoryMenu with \a parent and \a name. The menu will be 48 Creates a new CategoryMenu with \a parent and \a name. The menu will be
51 populated with the available categories for \a application. 49 populated with the available categories for \a application.
52 50
53 If \a globals is TRUE then it will also poplulate the menu with the 51 If \a globals is TRUE then it will also poplulate the menu with the
54 global categories. 52 global categories.
55*/ 53*/
56CategoryMenu::CategoryMenu( const QString &n, bool ig = TRUE, 54CategoryMenu::CategoryMenu( const QString &n, bool ig = TRUE,
57 QWidget *parent, const char *name ) : 55 QWidget *parent, const char *name ) :
58 QPopupMenu(parent, name), 56 QPopupMenu(parent, name),
59 appName(n), 57 appName(n),
60 includeGlobal(ig) 58 includeGlobal(ig)
61{ 59{
62 currentMid = 1; 60 currentMid = 1;
63 reload(); 61 reload();
64 connect(this, SIGNAL(activated(int)), this, SLOT(mapMenuId(int))); 62 connect(this, SIGNAL(activated(int)), this, SLOT(mapMenuId(int)));
65} 63}
66 64
67/*! 65/*!
68 Destroys a CategoryMenu. 66 Destroys a CategoryMenu.
69*/ 67*/
70CategoryMenu::~CategoryMenu( ) 68CategoryMenu::~CategoryMenu( )
71{ 69{
72} 70}
73 71
74/*! 72/*!
75 Repopulates the widget's list of available categories. 73 Repopulates the widget's list of available categories.
76*/ 74*/
77void CategoryMenu::reload() 75void CategoryMenu::reload()
78{ 76{
79 clear(); 77 clear();
80 Categories c; 78 Categories c;
81 79
82 c.load(categoryFileName()); 80 c.load(categoryFileName());
83 81
84 QStringList sl = c.labels(appName, includeGlobal); 82 QStringList sl = c.labels(appName, includeGlobal);
85 int mid = 1; 83 int mid = 1;
86 84
87 insertItem(tr("All"), mid); 85 insertItem(tr("All"), mid);
88 mid++; 86 mid++;
89 insertItem(tr("Unfiled"), mid); 87 insertItem(tr("Unfiled"), mid);
90 mid++; 88 mid++;
91 89
92 for (QStringList::Iterator it = sl.begin(); 90 for (QStringList::Iterator it = sl.begin();
93 it != sl.end(); ++it ) { 91 it != sl.end(); ++it ) {
94 int cid = c.id(appName, *it); 92 int cid = c.id(appName, *it);
95 insertItem(*it, mid); 93 insertItem(*it, mid);
96 menuToId.insert(mid, cid); 94 menuToId.insert(mid, cid);
97 idToMenu.insert(cid, mid); 95 idToMenu.insert(cid, mid);
98 mid++; 96 mid++;
99 } 97 }
100 98
101 setItemChecked(currentMid, TRUE ); 99 setItemChecked(currentMid, TRUE );
102} 100}
103 101
104/*! 102/*!
105 \internal 103 \internal
106*/ 104*/
107void CategoryMenu::mapMenuId(int id) 105void CategoryMenu::mapMenuId(int id)
108{ 106{
109 if (id == currentMid) 107 if (id == currentMid)
110 return; 108 return;
111 setItemChecked( currentMid, FALSE ); 109 setItemChecked( currentMid, FALSE );
112 setItemChecked( id, TRUE ); 110 setItemChecked( id, TRUE );
113 currentMid = id; 111 currentMid = id;
114 112
115 emit categoryChange(); 113 emit categoryChange();
116} 114}
117 115
118/*! 116/*!
119 Returns TRUE if a record or file with the set of category ids \a cUids 117 Returns TRUE if a record or file with the set of category ids \a cUids
120 is allowed by the current selection in the CategoryMenu. 118 is allowed by the current selection in the CategoryMenu.
121 Otherwise returns FALSE. 119 Otherwise returns FALSE.
122*/ 120*/
123bool CategoryMenu::isSelected(const QArray<int> &cUids) const 121bool CategoryMenu::isSelected(const QArray<int> &cUids) const
124{ 122{
125 if (currentMid == 1) 123 if (currentMid == 1)
126 return TRUE; 124 return TRUE;
127 125
128 if (currentMid == 2 && cUids.count() == 0) 126 if (currentMid == 2 && cUids.count() == 0)
129 return TRUE; 127 return TRUE;
130 128
131 if (cUids.contains(menuToId[currentMid])) 129 if (cUids.contains(menuToId[currentMid]))
132 return TRUE; 130 return TRUE;
133 131
134 return FALSE; 132 return FALSE;
135} 133}
136 134
137/*! 135/*!
138 Sets the menu to have \a newCatUid as the currently selected Category. 136 Sets the menu to have \a newCatUid as the currently selected Category.
139*/ 137*/
140void CategoryMenu::setCurrentCategory( int newCatUid ) 138void CategoryMenu::setCurrentCategory( int newCatUid )
141{ 139{
142 if (!idToMenu.contains(newCatUid)) 140 if (!idToMenu.contains(newCatUid))
143 return; 141 return;
144 142
145 mapMenuId(idToMenu[newCatUid]); 143 mapMenuId(idToMenu[newCatUid]);
146} 144}
147 145
148/*! 146/*!
149 Sets the menu to allow all category sets. 147 Sets the menu to allow all category sets.
150*/ 148*/
151void CategoryMenu::setCurrentCategoryAll( ) 149void CategoryMenu::setCurrentCategoryAll( )
152{ 150{
153 mapMenuId(1); 151 mapMenuId(1);
154} 152}
155 153
156/*! 154/*!
157 Sets the menu to allow only empty category sets. 155 Sets the menu to allow only empty category sets.
158*/ 156*/
159void CategoryMenu::setCurrentCategoryUnfiled( ) 157void CategoryMenu::setCurrentCategoryUnfiled( )
160{ 158{
161 mapMenuId(2); 159 mapMenuId(2);
162} 160}
diff --git a/library/config.cpp b/library/config.cpp
index b28c771..8b60f60 100644
--- a/library/config.cpp
+++ b/library/config.cpp
@@ -1,580 +1,578 @@
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 <qdir.h> 21#include <qdir.h>
22#include <qfile.h>
23#include <qfileinfo.h>
24#include <qmessagebox.h> 22#include <qmessagebox.h>
25#if QT_VERSION <= 230 && defined(QT_NO_CODECS) 23#if QT_VERSION <= 230 && defined(QT_NO_CODECS)
26#include <qtextcodec.h> 24#include <qtextcodec.h>
27#endif 25#endif
28#include <qtextstream.h> 26#include <qtextstream.h>
29 27
30#include <sys/stat.h> 28#include <sys/stat.h>
31#include <sys/types.h> 29#include <sys/types.h>
32#include <fcntl.h> 30#include <fcntl.h>
33#include <stdlib.h> 31#include <stdlib.h>
34#include <unistd.h> 32#include <unistd.h>
35 33
36#define QTOPIA_INTERNAL_LANGLIST 34#define QTOPIA_INTERNAL_LANGLIST
37#include "config.h" 35#include "config.h"
38#include "global.h" 36#include "global.h"
39 37
40 38
41/*! 39/*!
42 \internal 40 \internal
43*/ 41*/
44QString Config::configFilename(const QString& name, Domain d) 42QString Config::configFilename(const QString& name, Domain d)
45{ 43{
46 switch (d) { 44 switch (d) {
47 case File: 45 case File:
48 return name; 46 return name;
49 case User: { 47 case User: {
50 QDir dir = (QString(getenv("HOME")) + "/Settings"); 48 QDir dir = (QString(getenv("HOME")) + "/Settings");
51 if ( !dir.exists() ) 49 if ( !dir.exists() )
52 mkdir(dir.path().local8Bit(),0700); 50 mkdir(dir.path().local8Bit(),0700);
53 return dir.path() + "/" + name + ".conf"; 51 return dir.path() + "/" + name + ".conf";
54 } 52 }
55 } 53 }
56 return name; 54 return name;
57} 55}
58 56
59/*! 57/*!
60 \class Config config.h 58 \class Config config.h
61 \brief The Config class provides for saving application cofniguration state. 59 \brief The Config class provides for saving application cofniguration state.
62 60
63 You should keep a Config in existence only while you do not want others 61 You should keep a Config in existence only while you do not want others
64 to be able to change the state. There is no locking currently, but there 62 to be able to change the state. There is no locking currently, but there
65 may be in the future. 63 may be in the future.
66*/ 64*/
67 65
68/*! 66/*!
69 \enum Config::ConfigGroup 67 \enum Config::ConfigGroup
70 \internal 68 \internal
71*/ 69*/
72 70
73/*! 71/*!
74 \enum Config::Domain 72 \enum Config::Domain
75 73
76 \value File 74 \value File
77 \value User 75 \value User
78 76
79 See Config for details. 77 See Config for details.
80*/ 78*/
81 79
82/*! 80/*!
83 Constructs a config that will load or create a configuration with the 81 Constructs a config that will load or create a configuration with the
84 given \a name in the given \a domain. 82 given \a name in the given \a domain.
85 83
86 You must call setGroup() before doing much else with the Config. 84 You must call setGroup() before doing much else with the Config.
87 85
88 In the default Domain, \e User, 86 In the default Domain, \e User,
89 the configuration is user-specific. \a name should not contain "/" in 87 the configuration is user-specific. \a name should not contain "/" in
90 this case, and in general should be the name of the C++ class that is 88 this case, and in general should be the name of the C++ class that is
91 primarily responsible for maintaining the configuration. 89 primarily responsible for maintaining the configuration.
92 90
93 In the File Domain, \a name is an absolute filename. 91 In the File Domain, \a name is an absolute filename.
94*/ 92*/
95Config::Config( const QString &name, Domain domain ) 93Config::Config( const QString &name, Domain domain )
96 : filename( configFilename(name,domain) ) 94 : filename( configFilename(name,domain) )
97{ 95{
98 git = groups.end(); 96 git = groups.end();
99 read(); 97 read();
100 QStringList l = Global::languageList(); 98 QStringList l = Global::languageList();
101 lang = l[0]; 99 lang = l[0];
102 glang = l[1]; 100 glang = l[1];
103} 101}
104 102
105 103
106// Sharp ROM compatibility 104// Sharp ROM compatibility
107Config::Config ( const QString &name, bool what ) 105Config::Config ( const QString &name, bool what )
108 : filename( configFilename(name,what ? User : File) ) 106 : filename( configFilename(name,what ? User : File) )
109{ 107{
110 git = groups.end(); 108 git = groups.end();
111 read(); 109 read();
112 QStringList l = Global::languageList(); 110 QStringList l = Global::languageList();
113 lang = l[0]; 111 lang = l[0];
114 glang = l[1]; 112 glang = l[1];
115} 113}
116 114
117/*! 115/*!
118 Writes any changes to disk and destroys the in-memory object. 116 Writes any changes to disk and destroys the in-memory object.
119*/ 117*/
120Config::~Config() 118Config::~Config()
121{ 119{
122 if ( changed ) 120 if ( changed )
123 write(); 121 write();
124} 122}
125 123
126/*! 124/*!
127 Returns whether the current group has an entry called \a key. 125 Returns whether the current group has an entry called \a key.
128*/ 126*/
129bool Config::hasKey( const QString &key ) const 127bool Config::hasKey( const QString &key ) const
130{ 128{
131 if ( groups.end() == git ) 129 if ( groups.end() == git )
132 return FALSE; 130 return FALSE;
133 ConfigGroup::ConstIterator it = ( *git ).find( key ); 131 ConfigGroup::ConstIterator it = ( *git ).find( key );
134 return it != ( *git ).end(); 132 return it != ( *git ).end();
135} 133}
136 134
137/*! 135/*!
138 Sets the current group for subsequent reading and writing of 136 Sets the current group for subsequent reading and writing of
139 entries to \a gname. Grouping allows the application to partition the namespace. 137 entries to \a gname. Grouping allows the application to partition the namespace.
140 138
141 This function must be called prior to any reading or writing 139 This function must be called prior to any reading or writing
142 of entries. 140 of entries.
143 141
144 The \a gname must not be empty. 142 The \a gname must not be empty.
145*/ 143*/
146void Config::setGroup( const QString &gname ) 144void Config::setGroup( const QString &gname )
147{ 145{
148 QMap< QString, ConfigGroup>::Iterator it = groups.find( gname ); 146 QMap< QString, ConfigGroup>::Iterator it = groups.find( gname );
149 if ( it == groups.end() ) { 147 if ( it == groups.end() ) {
150 git = groups.insert( gname, ConfigGroup() ); 148 git = groups.insert( gname, ConfigGroup() );
151 changed = TRUE; 149 changed = TRUE;
152 return; 150 return;
153 } 151 }
154 git = it; 152 git = it;
155} 153}
156 154
157/*! 155/*!
158 Writes a (\a key, \a value) entry to the current group. 156 Writes a (\a key, \a value) entry to the current group.
159 157
160 \sa readEntry() 158 \sa readEntry()
161*/ 159*/
162void Config::writeEntry( const QString &key, const char* value ) 160void Config::writeEntry( const QString &key, const char* value )
163{ 161{
164 writeEntry(key,QString(value)); 162 writeEntry(key,QString(value));
165} 163}
166 164
167/*! 165/*!
168 Writes a (\a key, \a value) entry to the current group. 166 Writes a (\a key, \a value) entry to the current group.
169 167
170 \sa readEntry() 168 \sa readEntry()
171*/ 169*/
172void Config::writeEntry( const QString &key, const QString &value ) 170void Config::writeEntry( const QString &key, const QString &value )
173{ 171{
174 if ( git == groups.end() ) { 172 if ( git == groups.end() ) {
175 qWarning( "no group set" ); 173 qWarning( "no group set" );
176 return; 174 return;
177 } 175 }
178 if ( (*git)[key] != value ) { 176 if ( (*git)[key] != value ) {
179 ( *git ).insert( key, value ); 177 ( *git ).insert( key, value );
180 changed = TRUE; 178 changed = TRUE;
181 } 179 }
182} 180}
183 181
184/* 182/*
185 Note that the degree of protection offered by the encryption here is 183 Note that the degree of protection offered by the encryption here is
186 only sufficient to avoid the most casual observation of the configuration 184 only sufficient to avoid the most casual observation of the configuration
187 files. People with access to the files can write down the contents and 185 files. People with access to the files can write down the contents and
188 decrypt it using this source code. 186 decrypt it using this source code.
189 187
190 Conceivably, and at some burden to the user, this encryption could 188 Conceivably, and at some burden to the user, this encryption could
191 be improved. 189 be improved.
192*/ 190*/
193static QString encipher(const QString& plain) 191static QString encipher(const QString& plain)
194{ 192{
195 // mainly, we make it long 193 // mainly, we make it long
196 QString cipher; 194 QString cipher;
197 int mix=28730492; 195 int mix=28730492;
198 for (int i=0; i<(int)plain.length(); i++) { 196 for (int i=0; i<(int)plain.length(); i++) {
199 int u = plain[i].unicode(); 197 int u = plain[i].unicode();
200 int c = u ^ mix; 198 int c = u ^ mix;
201 QString x = QString::number(c,36); 199 QString x = QString::number(c,36);
202 cipher.append(QChar('a'+x.length())); 200 cipher.append(QChar('a'+x.length()));
203 cipher.append(x); 201 cipher.append(x);
204 mix *= u; 202 mix *= u;
205 } 203 }
206 return cipher; 204 return cipher;
207} 205}
208 206
209static QString decipher(const QString& cipher) 207static QString decipher(const QString& cipher)
210{ 208{
211 QString plain; 209 QString plain;
212 int mix=28730492; 210 int mix=28730492;
213 for (int i=0; i<(int)cipher.length();) { 211 for (int i=0; i<(int)cipher.length();) {
214 int l = cipher[i].unicode()-'a'; 212 int l = cipher[i].unicode()-'a';
215 QString x = cipher.mid(i+1,l); i+=l+1; 213 QString x = cipher.mid(i+1,l); i+=l+1;
216 int u = x.toInt(0,36) ^ mix; 214 int u = x.toInt(0,36) ^ mix;
217 plain.append(QChar(u)); 215 plain.append(QChar(u));
218 mix *= u; 216 mix *= u;
219 } 217 }
220 return plain; 218 return plain;
221} 219}
222 220
223/*! 221/*!
224 Writes an encrypted (\a key, \a value) entry to the current group. 222 Writes an encrypted (\a key, \a value) entry to the current group.
225 223
226 Note that the degree of protection offered by the encryption is 224 Note that the degree of protection offered by the encryption is
227 only sufficient to avoid the most casual observation of the configuration 225 only sufficient to avoid the most casual observation of the configuration
228 files. 226 files.
229 227
230 \sa readEntry() 228 \sa readEntry()
231*/ 229*/
232void Config::writeEntryCrypt( const QString &key, const QString &value ) 230void Config::writeEntryCrypt( const QString &key, const QString &value )
233{ 231{
234 if ( git == groups.end() ) { 232 if ( git == groups.end() ) {
235 qWarning( "no group set" ); 233 qWarning( "no group set" );
236 return; 234 return;
237 } 235 }
238 QString evalue = encipher(value); 236 QString evalue = encipher(value);
239 if ( (*git)[key] != evalue ) { 237 if ( (*git)[key] != evalue ) {
240 ( *git ).insert( key, evalue ); 238 ( *git ).insert( key, evalue );
241 changed = TRUE; 239 changed = TRUE;
242 } 240 }
243} 241}
244 242
245/*! 243/*!
246 Writes a (\a key, \a num) entry to the current group. 244 Writes a (\a key, \a num) entry to the current group.
247 245
248 \sa readNumEntry() 246 \sa readNumEntry()
249*/ 247*/
250void Config::writeEntry( const QString &key, int num ) 248void Config::writeEntry( const QString &key, int num )
251{ 249{
252 QString s; 250 QString s;
253 s.setNum( num ); 251 s.setNum( num );
254 writeEntry( key, s ); 252 writeEntry( key, s );
255} 253}
256 254
257#ifdef Q_HAS_BOOL_TYPE 255#ifdef Q_HAS_BOOL_TYPE
258/*! 256/*!
259 Writes a (\a key, \a b) entry to the current group. This is equivalent 257 Writes a (\a key, \a b) entry to the current group. This is equivalent
260 to writing a 0 or 1 as an integer entry. 258 to writing a 0 or 1 as an integer entry.
261 259
262 \sa readBoolEntry() 260 \sa readBoolEntry()
263*/ 261*/
264void Config::writeEntry( const QString &key, bool b ) 262void Config::writeEntry( const QString &key, bool b )
265{ 263{
266 QString s; 264 QString s;
267 s.setNum( ( int )b ); 265 s.setNum( ( int )b );
268 writeEntry( key, s ); 266 writeEntry( key, s );
269} 267}
270#endif 268#endif
271 269
272/*! 270/*!
273 Writes a (\a key, \a lst) entry to the current group. The list 271 Writes a (\a key, \a lst) entry to the current group. The list
274 is separated by \a sep, so the strings must not contain that character. 272 is separated by \a sep, so the strings must not contain that character.
275 273
276 \sa readListEntry() 274 \sa readListEntry()
277*/ 275*/
278void Config::writeEntry( const QString &key, const QStringList &lst, const QChar &sep ) 276void Config::writeEntry( const QString &key, const QStringList &lst, const QChar &sep )
279{ 277{
280 QString s; 278 QString s;
281 QStringList::ConstIterator it = lst.begin(); 279 QStringList::ConstIterator it = lst.begin();
282 for ( ; it != lst.end(); ++it ) 280 for ( ; it != lst.end(); ++it )
283 s += *it + sep; 281 s += *it + sep;
284 writeEntry( key, s ); 282 writeEntry( key, s );
285} 283}
286 284
287/*! 285/*!
288 Removes the \a key entry from the current group. Does nothing if 286 Removes the \a key entry from the current group. Does nothing if
289 there is no such entry. 287 there is no such entry.
290*/ 288*/
291 289
292void Config::removeEntry( const QString &key ) 290void Config::removeEntry( const QString &key )
293{ 291{
294 if ( git == groups.end() ) { 292 if ( git == groups.end() ) {
295 qWarning( "no group set" ); 293 qWarning( "no group set" );
296 return; 294 return;
297 } 295 }
298 ( *git ).remove( key ); 296 ( *git ).remove( key );
299 changed = TRUE; 297 changed = TRUE;
300} 298}
301 299
302/*! 300/*!
303 \fn bool Config::operator == ( const Config & other ) const 301 \fn bool Config::operator == ( const Config & other ) const
304 302
305 Tests for equality with \a other. Config objects are equal if they refer to the same filename. 303 Tests for equality with \a other. Config objects are equal if they refer to the same filename.
306*/ 304*/
307 305
308/*! 306/*!
309 \fn bool Config::operator != ( const Config & other ) const 307 \fn bool Config::operator != ( const Config & other ) const
310 308
311 Tests for inequality with \a other. Config objects are equal if they refer to the same filename. 309 Tests for inequality with \a other. Config objects are equal if they refer to the same filename.
312*/ 310*/
313 311
314/*! 312/*!
315 \fn QString Config::readEntry( const QString &key, const QString &deflt ) const 313 \fn QString Config::readEntry( const QString &key, const QString &deflt ) const
316 314
317 Reads a string entry stored with \a key, defaulting to \a deflt if there is no entry. 315 Reads a string entry stored with \a key, defaulting to \a deflt if there is no entry.
318*/ 316*/
319 317
320/*! 318/*!
321 \internal 319 \internal
322 For compatibility, non-const version. 320 For compatibility, non-const version.
323*/ 321*/
324QString Config::readEntry( const QString &key, const QString &deflt ) 322QString Config::readEntry( const QString &key, const QString &deflt )
325{ 323{
326 QString res = readEntryDirect( key+"["+lang+"]" ); 324 QString res = readEntryDirect( key+"["+lang+"]" );
327 if ( !res.isNull() ) 325 if ( !res.isNull() )
328 return res; 326 return res;
329 if ( !glang.isEmpty() ) { 327 if ( !glang.isEmpty() ) {
330 res = readEntryDirect( key+"["+glang+"]" ); 328 res = readEntryDirect( key+"["+glang+"]" );
331 if ( !res.isNull() ) 329 if ( !res.isNull() )
332 return res; 330 return res;
333 } 331 }
334 return readEntryDirect( key, deflt ); 332 return readEntryDirect( key, deflt );
335} 333}
336 334
337/*! 335/*!
338 \fn QString Config::readEntryCrypt( const QString &key, const QString &deflt ) const 336 \fn QString Config::readEntryCrypt( const QString &key, const QString &deflt ) const
339 337
340 Reads an encrypted string entry stored with \a key, defaulting to \a deflt if there is no entry. 338 Reads an encrypted string entry stored with \a key, defaulting to \a deflt if there is no entry.
341*/ 339*/
342 340
343/*! 341/*!
344 \internal 342 \internal
345 For compatibility, non-const version. 343 For compatibility, non-const version.
346*/ 344*/
347QString Config::readEntryCrypt( const QString &key, const QString &deflt ) 345QString Config::readEntryCrypt( const QString &key, const QString &deflt )
348{ 346{
349 QString res = readEntryDirect( key+"["+lang+"]" ); 347 QString res = readEntryDirect( key+"["+lang+"]" );
350 if ( res.isNull() && glang.isEmpty() ) 348 if ( res.isNull() && glang.isEmpty() )
351 res = readEntryDirect( key+"["+glang+"]" ); 349 res = readEntryDirect( key+"["+glang+"]" );
352 if ( res.isNull() ) 350 if ( res.isNull() )
353 res = readEntryDirect( key, QString::null ); 351 res = readEntryDirect( key, QString::null );
354 if ( res.isNull() ) 352 if ( res.isNull() )
355 return deflt; 353 return deflt;
356 return decipher(res); 354 return decipher(res);
357} 355}
358 356
359/*! 357/*!
360 \fn QString Config::readEntryDirect( const QString &key, const QString &deflt ) const 358 \fn QString Config::readEntryDirect( const QString &key, const QString &deflt ) const
361 \internal 359 \internal
362*/ 360*/
363 361
364/*! 362/*!
365 \internal 363 \internal
366 For compatibility, non-const version. 364 For compatibility, non-const version.
367*/ 365*/
368QString Config::readEntryDirect( const QString &key, const QString &deflt ) 366QString Config::readEntryDirect( const QString &key, const QString &deflt )
369{ 367{
370 if ( git == groups.end() ) { 368 if ( git == groups.end() ) {
371 //qWarning( "no group set" ); 369 //qWarning( "no group set" );
372 return deflt; 370 return deflt;
373 } 371 }
374 ConfigGroup::ConstIterator it = ( *git ).find( key ); 372 ConfigGroup::ConstIterator it = ( *git ).find( key );
375 if ( it != ( *git ).end() ) 373 if ( it != ( *git ).end() )
376 return *it; 374 return *it;
377 else 375 else
378 return deflt; 376 return deflt;
379} 377}
380 378
381/*! 379/*!
382 \fn int Config::readNumEntry( const QString &key, int deflt ) const 380 \fn int Config::readNumEntry( const QString &key, int deflt ) const
383 Reads a numeric entry stored with \a key, defaulting to \a deflt if there is no entry. 381 Reads a numeric entry stored with \a key, defaulting to \a deflt if there is no entry.
384*/ 382*/
385 383
386/*! 384/*!
387 \internal 385 \internal
388 For compatibility, non-const version. 386 For compatibility, non-const version.
389*/ 387*/
390int Config::readNumEntry( const QString &key, int deflt ) 388int Config::readNumEntry( const QString &key, int deflt )
391{ 389{
392 QString s = readEntry( key ); 390 QString s = readEntry( key );
393 if ( s.isEmpty() ) 391 if ( s.isEmpty() )
394 return deflt; 392 return deflt;
395 else 393 else
396 return s.toInt(); 394 return s.toInt();
397} 395}
398 396
399/*! 397/*!
400 \fn bool Config::readBoolEntry( const QString &key, bool deflt ) const 398 \fn bool Config::readBoolEntry( const QString &key, bool deflt ) const
401 Reads a bool entry stored with \a key, defaulting to \a deflt if there is no entry. 399 Reads a bool entry stored with \a key, defaulting to \a deflt if there is no entry.
402*/ 400*/
403 401
404/*! 402/*!
405 \internal 403 \internal
406 For compatibility, non-const version. 404 For compatibility, non-const version.
407*/ 405*/
408bool Config::readBoolEntry( const QString &key, bool deflt ) 406bool Config::readBoolEntry( const QString &key, bool deflt )
409{ 407{
410 QString s = readEntry( key ); 408 QString s = readEntry( key );
411 if ( s.isEmpty() ) 409 if ( s.isEmpty() )
412 return deflt; 410 return deflt;
413 else 411 else
414 return (bool)s.toInt(); 412 return (bool)s.toInt();
415} 413}
416 414
417/*! 415/*!
418 \fn QStringList Config::readListEntry( const QString &key, const QChar &sep ) const 416 \fn QStringList Config::readListEntry( const QString &key, const QChar &sep ) const
419 Reads a string list entry stored with \a key, and with \a sep as the separator. 417 Reads a string list entry stored with \a key, and with \a sep as the separator.
420*/ 418*/
421 419
422/*! 420/*!
423 \internal 421 \internal
424 For compatibility, non-const version. 422 For compatibility, non-const version.
425*/ 423*/
426QStringList Config::readListEntry( const QString &key, const QChar &sep ) 424QStringList Config::readListEntry( const QString &key, const QChar &sep )
427{ 425{
428 QString s = readEntry( key ); 426 QString s = readEntry( key );
429 if ( s.isEmpty() ) 427 if ( s.isEmpty() )
430 return QStringList(); 428 return QStringList();
431 else 429 else
432 return QStringList::split( sep, s ); 430 return QStringList::split( sep, s );
433} 431}
434 432
435/*! 433/*!
436 Removes all entries from the current group. 434 Removes all entries from the current group.
437*/ 435*/
438void Config::clearGroup() 436void Config::clearGroup()
439{ 437{
440 if ( git == groups.end() ) { 438 if ( git == groups.end() ) {
441 qWarning( "no group set" ); 439 qWarning( "no group set" );
442 return; 440 return;
443 } 441 }
444 if ( !(*git).isEmpty() ) { 442 if ( !(*git).isEmpty() ) {
445 ( *git ).clear(); 443 ( *git ).clear();
446 changed = TRUE; 444 changed = TRUE;
447 } 445 }
448} 446}
449 447
450/*! 448/*!
451 \internal 449 \internal
452*/ 450*/
453void Config::write( const QString &fn ) 451void Config::write( const QString &fn )
454{ 452{
455 QString strNewFile; 453 QString strNewFile;
456 if ( !fn.isEmpty() ) 454 if ( !fn.isEmpty() )
457 filename = fn; 455 filename = fn;
458 strNewFile = filename + ".new"; 456 strNewFile = filename + ".new";
459 457
460 QFile f( strNewFile ); 458 QFile f( strNewFile );
461 if ( !f.open( IO_WriteOnly|IO_Raw ) ) { 459 if ( !f.open( IO_WriteOnly|IO_Raw ) ) {
462 qWarning( "could not open for writing `%s'", strNewFile.latin1() ); 460 qWarning( "could not open for writing `%s'", strNewFile.latin1() );
463 git = groups.end(); 461 git = groups.end();
464 return; 462 return;
465 } 463 }
466 464
467 QString str; 465 QString str;
468 QCString cstr; 466 QCString cstr;
469 QMap< QString, ConfigGroup >::Iterator g_it = groups.begin(); 467 QMap< QString, ConfigGroup >::Iterator g_it = groups.begin();
470 468
471 for ( ; g_it != groups.end(); ++g_it ) { 469 for ( ; g_it != groups.end(); ++g_it ) {
472 str += "[" + g_it.key() + "]\n"; 470 str += "[" + g_it.key() + "]\n";
473 ConfigGroup::Iterator e_it = ( *g_it ).begin(); 471 ConfigGroup::Iterator e_it = ( *g_it ).begin();
474 for ( ; e_it != ( *g_it ).end(); ++e_it ) 472 for ( ; e_it != ( *g_it ).end(); ++e_it )
475 str += e_it.key() + " = " + *e_it + "\n"; 473 str += e_it.key() + " = " + *e_it + "\n";
476 } 474 }
477 cstr = str.utf8(); 475 cstr = str.utf8();
478 476
479 int total_length; 477 int total_length;
480 total_length = f.writeBlock( cstr.data(), cstr.length() ); 478 total_length = f.writeBlock( cstr.data(), cstr.length() );
481 if ( total_length != int(cstr.length()) ) { 479 if ( total_length != int(cstr.length()) ) {
482 QMessageBox::critical( 0, QObject::tr("Out of Space"), 480 QMessageBox::critical( 0, QObject::tr("Out of Space"),
483 QObject::tr("There was a problem creating\nConfiguration Information \nfor this program.\n\nPlease free up some space and\ntry again.") ); 481 QObject::tr("There was a problem creating\nConfiguration Information \nfor this program.\n\nPlease free up some space and\ntry again.") );
484 f.close(); 482 f.close();
485 QFile::remove( strNewFile ); 483 QFile::remove( strNewFile );
486 return; 484 return;
487 } 485 }
488 486
489 f.close(); 487 f.close();
490 // now rename the file... 488 // now rename the file...
491 if ( rename( strNewFile, filename ) < 0 ) { 489 if ( rename( strNewFile, filename ) < 0 ) {
492 qWarning( "problem renaming the file %s to %s", strNewFile.latin1(), 490 qWarning( "problem renaming the file %s to %s", strNewFile.latin1(),
493 filename.latin1() ); 491 filename.latin1() );
494 QFile::remove( strNewFile ); 492 QFile::remove( strNewFile );
495 } 493 }
496} 494}
497 495
498/*! 496/*!
499 Returns whether the Config is in a valid state. 497 Returns whether the Config is in a valid state.
500*/ 498*/
501bool Config::isValid() const 499bool Config::isValid() const
502{ 500{
503 return groups.end() != git; 501 return groups.end() != git;
504} 502}
505 503
506/*! 504/*!
507 \internal 505 \internal
508*/ 506*/
509void Config::read() 507void Config::read()
510{ 508{
511 changed = FALSE; 509 changed = FALSE;
512 510
513 if ( !QFileInfo( filename ).exists() ) { 511 if ( !QFileInfo( filename ).exists() ) {
514 git = groups.end(); 512 git = groups.end();
515 return; 513 return;
516 } 514 }
517 515
518 QFile f( filename ); 516 QFile f( filename );
519 if ( !f.open( IO_ReadOnly ) ) { 517 if ( !f.open( IO_ReadOnly ) ) {
520 git = groups.end(); 518 git = groups.end();
521 return; 519 return;
522 } 520 }
523 521
524 522
525 // hack to avoid problems if big files are passed to test 523 // hack to avoid problems if big files are passed to test
526 // if they are valid configs ( like passing a mp3 ... ) 524 // if they are valid configs ( like passing a mp3 ... )
527 // I just hope that there are no conf files > 100000 byte 525 // I just hope that there are no conf files > 100000 byte
528 // not the best solution, find something else later 526 // not the best solution, find something else later
529 if ( f.size() > 100000 ) { 527 if ( f.size() > 100000 ) {
530 return; 528 return;
531 } 529 }
532 530
533 531
534 QTextStream s( &f ); 532 QTextStream s( &f );
535#if QT_VERSION <= 230 && defined(QT_NO_CODECS) 533#if QT_VERSION <= 230 && defined(QT_NO_CODECS)
536 // The below should work, but doesn't in Qt 2.3.0 534 // The below should work, but doesn't in Qt 2.3.0
537 s.setCodec( QTextCodec::codecForMib( 106 ) ); 535 s.setCodec( QTextCodec::codecForMib( 106 ) );
538#else 536#else
539 s.setEncoding( QTextStream::UnicodeUTF8 ); 537 s.setEncoding( QTextStream::UnicodeUTF8 );
540#endif 538#endif
541 539
542 QStringList list = QStringList::split('\n', s.read() ); 540 QStringList list = QStringList::split('\n', s.read() );
543 f.close(); 541 f.close();
544 542
545 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { 543 for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
546 if ( !parse( *it ) ) { 544 if ( !parse( *it ) ) {
547 git = groups.end(); 545 git = groups.end();
548 return; 546 return;
549 } 547 }
550 } 548 }
551} 549}
552 550
553/*! 551/*!
554 \internal 552 \internal
555*/ 553*/
556bool Config::parse( const QString &l ) 554bool Config::parse( const QString &l )
557{ 555{
558 QString line = l.stripWhiteSpace(); 556 QString line = l.stripWhiteSpace();
559 557
560 if ( line [0] == QChar ( '#' )) 558 if ( line [0] == QChar ( '#' ))
561 return true; // ignore comments 559 return true; // ignore comments
562 560
563 if ( line[ 0 ] == QChar( '[' ) ) { 561 if ( line[ 0 ] == QChar( '[' ) ) {
564 QString gname = line; 562 QString gname = line;
565 gname = gname.remove( 0, 1 ); 563 gname = gname.remove( 0, 1 );
566 if ( gname[ (int)gname.length() - 1 ] == QChar( ']' ) ) 564 if ( gname[ (int)gname.length() - 1 ] == QChar( ']' ) )
567 gname = gname.remove( gname.length() - 1, 1 ); 565 gname = gname.remove( gname.length() - 1, 1 );
568 git = groups.insert( gname, ConfigGroup() ); 566 git = groups.insert( gname, ConfigGroup() );
569 } else if ( !line.isEmpty() ) { 567 } else if ( !line.isEmpty() ) {
570 if ( git == groups.end() ) 568 if ( git == groups.end() )
571 return FALSE; 569 return FALSE;
572 int eq = line.find( '=' ); 570 int eq = line.find( '=' );
573 if ( eq == -1 ) 571 if ( eq == -1 )
574 return FALSE; 572 return FALSE;
575 QString key = line.left(eq).stripWhiteSpace(); 573 QString key = line.left(eq).stripWhiteSpace();
576 QString value = line.mid(eq+1).stripWhiteSpace(); 574 QString value = line.mid(eq+1).stripWhiteSpace();
577 ( *git ).insert( key, value ); 575 ( *git ).insert( key, value );
578 } 576 }
579 return TRUE; 577 return TRUE;
580} 578}
diff --git a/library/datebookdb.cpp b/library/datebookdb.cpp
index 188d8e1..e4ec2bf 100644
--- a/library/datebookdb.cpp
+++ b/library/datebookdb.cpp
@@ -1,1146 +1,1141 @@
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 <qasciidict.h> 21#include <qasciidict.h>
22#include <qfile.h>
23#include <qmessagebox.h> 22#include <qmessagebox.h>
24#include <qstring.h>
25#include <qtextcodec.h>
26#include <qtextstream.h>
27#include <qtl.h> 23#include <qtl.h>
28 24
29#include <qpe/alarmserver.h> 25#include <qpe/alarmserver.h>
30#include <qpe/global.h> 26#include <qpe/global.h>
31#include "datebookdb.h" 27#include "datebookdb.h"
32#include <qpe/stringutil.h> 28#include <qpe/stringutil.h>
33#include <qpe/timeconversion.h>
34 29
35#include <errno.h> 30#include <errno.h>
36#include <stdlib.h> 31#include <stdlib.h>
37 32
38 33
39class DateBookDBPrivate 34class DateBookDBPrivate
40{ 35{
41public: 36public:
42 bool clean; // indcate whether we need to write to disk... 37 bool clean; // indcate whether we need to write to disk...
43}; 38};
44 39
45 40
46// Helper functions 41// Helper functions
47 42
48static QString dateBookJournalFile() 43static QString dateBookJournalFile()
49{ 44{
50 QString str = getenv("HOME"); 45 QString str = getenv("HOME");
51 return QString( str +"/.caljournal" ); 46 return QString( str +"/.caljournal" );
52} 47}
53 48
54static QString dateBookFilename() 49static QString dateBookFilename()
55{ 50{
56 return Global::applicationFileName("datebook","datebook.xml"); 51 return Global::applicationFileName("datebook","datebook.xml");
57} 52}
58 53
59/* Calculating the next event of a recuring event is actually 54/* Calculating the next event of a recuring event is actually
60 computationally inexpensive, esp. compared to checking each day 55 computationally inexpensive, esp. compared to checking each day
61 individually. There are bad worse cases for say the 29th of 56 individually. There are bad worse cases for say the 29th of
62 february or the 31st of some other months. However 57 february or the 31st of some other months. However
63 these are still bounded */ 58 these are still bounded */
64bool nextOccurance(const Event &e, const QDate &from, QDateTime &next) 59bool nextOccurance(const Event &e, const QDate &from, QDateTime &next)
65{ 60{
66 // easy checks, first are we too far in the future or too far in the past? 61 // easy checks, first are we too far in the future or too far in the past?
67 QDate tmpDate; 62 QDate tmpDate;
68 int freq = e.repeatPattern().frequency; 63 int freq = e.repeatPattern().frequency;
69 int diff, diff2, a; 64 int diff, diff2, a;
70 int iday, imonth, iyear; 65 int iday, imonth, iyear;
71 int dayOfWeek = 0; 66 int dayOfWeek = 0;
72 int firstOfWeek = 0; 67 int firstOfWeek = 0;
73 int weekOfMonth; 68 int weekOfMonth;
74 69
75 70
76 if (e.repeatPattern().hasEndDate && e.repeatPattern().endDate() < from) 71 if (e.repeatPattern().hasEndDate && e.repeatPattern().endDate() < from)
77 return FALSE; 72 return FALSE;
78 73
79 if (e.start() >= from) { 74 if (e.start() >= from) {
80 next = e.start(); 75 next = e.start();
81 return TRUE; 76 return TRUE;
82 } 77 }
83 78
84 switch ( e.repeatPattern().type ) { 79 switch ( e.repeatPattern().type ) {
85 case Event::Weekly: 80 case Event::Weekly:
86 /* weekly is just daily by 7 */ 81 /* weekly is just daily by 7 */
87 /* first convert the repeatPattern.Days() mask to the next 82 /* first convert the repeatPattern.Days() mask to the next
88 day of week valid after from */ 83 day of week valid after from */
89 dayOfWeek = from.dayOfWeek(); 84 dayOfWeek = from.dayOfWeek();
90 dayOfWeek--; /* we want 0-6, doco for above specs 1-7 */ 85 dayOfWeek--; /* we want 0-6, doco for above specs 1-7 */
91 86
92 /* this is done in case freq > 1 and from in week not 87 /* this is done in case freq > 1 and from in week not
93 for this round */ 88 for this round */
94 // firstOfWeek = 0; this is already done at decl. 89 // firstOfWeek = 0; this is already done at decl.
95 while(!((1 << firstOfWeek) & e.repeatPattern().days)) 90 while(!((1 << firstOfWeek) & e.repeatPattern().days))
96 firstOfWeek++; 91 firstOfWeek++;
97 92
98 93
99 94
100 /* there is at least one 'day', or there would be no event */ 95 /* there is at least one 'day', or there would be no event */
101 while(!((1 << (dayOfWeek % 7)) & e.repeatPattern().days)) 96 while(!((1 << (dayOfWeek % 7)) & e.repeatPattern().days))
102 dayOfWeek++; 97 dayOfWeek++;
103 98
104 99
105 dayOfWeek = dayOfWeek % 7; /* the actual day of week */ 100 dayOfWeek = dayOfWeek % 7; /* the actual day of week */
106 dayOfWeek -= e.start().date().dayOfWeek() -1; 101 dayOfWeek -= e.start().date().dayOfWeek() -1;
107 102
108 firstOfWeek = firstOfWeek % 7; /* the actual first of week */ 103 firstOfWeek = firstOfWeek % 7; /* the actual first of week */
109 firstOfWeek -= e.start().date().dayOfWeek() -1; 104 firstOfWeek -= e.start().date().dayOfWeek() -1;
110 105
111 // dayOfWeek may be negitive now 106 // dayOfWeek may be negitive now
112 // day of week is number of days to add to start day 107 // day of week is number of days to add to start day
113 108
114 freq *= 7; 109 freq *= 7;
115 // FALL-THROUGH !!!!! 110 // FALL-THROUGH !!!!!
116 case Event::Daily: 111 case Event::Daily:
117 // the add is for the possible fall through from weekly */ 112 // the add is for the possible fall through from weekly */
118 if(e.start().date().addDays(dayOfWeek) > from) { 113 if(e.start().date().addDays(dayOfWeek) > from) {
119 /* first week exception */ 114 /* first week exception */
120 next = QDateTime(e.start().date().addDays(dayOfWeek), 115 next = QDateTime(e.start().date().addDays(dayOfWeek),
121 e.start().time()); 116 e.start().time());
122 if ((next.date() > e.repeatPattern().endDate()) 117 if ((next.date() > e.repeatPattern().endDate())
123 && e.repeatPattern().hasEndDate) 118 && e.repeatPattern().hasEndDate)
124 return FALSE; 119 return FALSE;
125 return TRUE; 120 return TRUE;
126 } 121 }
127 /* if from is middle of a non-week */ 122 /* if from is middle of a non-week */
128 123
129 diff = e.start().date().addDays(dayOfWeek).daysTo(from) % freq; 124 diff = e.start().date().addDays(dayOfWeek).daysTo(from) % freq;
130 diff2 = e.start().date().addDays(firstOfWeek).daysTo(from) % freq; 125 diff2 = e.start().date().addDays(firstOfWeek).daysTo(from) % freq;
131 126
132 if(diff != 0) 127 if(diff != 0)
133 diff = freq - diff; 128 diff = freq - diff;
134 if(diff2 != 0) 129 if(diff2 != 0)
135 diff2 = freq - diff2; 130 diff2 = freq - diff2;
136 diff = QMIN(diff, diff2); 131 diff = QMIN(diff, diff2);
137 132
138 next = QDateTime(from.addDays(diff), e.start().time()); 133 next = QDateTime(from.addDays(diff), e.start().time());
139 if ( (next.date() > e.repeatPattern().endDate()) 134 if ( (next.date() > e.repeatPattern().endDate())
140 && e.repeatPattern().hasEndDate ) 135 && e.repeatPattern().hasEndDate )
141 return FALSE; 136 return FALSE;
142 return TRUE; 137 return TRUE;
143 case Event::MonthlyDay: 138 case Event::MonthlyDay:
144 iday = from.day(); 139 iday = from.day();
145 iyear = from.year(); 140 iyear = from.year();
146 imonth = from.month(); 141 imonth = from.month();
147 /* find equivelent day of month for this month */ 142 /* find equivelent day of month for this month */
148 dayOfWeek = e.start().date().dayOfWeek(); 143 dayOfWeek = e.start().date().dayOfWeek();
149 weekOfMonth = (e.start().date().day() - 1) / 7; 144 weekOfMonth = (e.start().date().day() - 1) / 7;
150 145
151 /* work out when the next valid month is */ 146 /* work out when the next valid month is */
152 a = from.year() - e.start().date().year(); 147 a = from.year() - e.start().date().year();
153 a *= 12; 148 a *= 12;
154 a = a + (imonth - e.start().date().month()); 149 a = a + (imonth - e.start().date().month());
155 /* a is e.start()monthsFrom(from); */ 150 /* a is e.start()monthsFrom(from); */
156 if(a % freq) { 151 if(a % freq) {
157 a = freq - (a % freq); 152 a = freq - (a % freq);
158 imonth = from.month() + a; 153 imonth = from.month() + a;
159 if (imonth > 12) { 154 if (imonth > 12) {
160 imonth--; 155 imonth--;
161 iyear += imonth / 12; 156 iyear += imonth / 12;
162 imonth = imonth % 12; 157 imonth = imonth % 12;
163 imonth++; 158 imonth++;
164 } 159 }
165 } 160 }
166 /* imonth is now the first month after or on 161 /* imonth is now the first month after or on
167 from that matches the frequency given */ 162 from that matches the frequency given */
168 163
169 /* find for this month */ 164 /* find for this month */
170 tmpDate = QDate( iyear, imonth, 1 ); 165 tmpDate = QDate( iyear, imonth, 1 );
171 166
172 iday = 1; 167 iday = 1;
173 iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7; 168 iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7;
174 iday += 7 * weekOfMonth; 169 iday += 7 * weekOfMonth;
175 while (iday > tmpDate.daysInMonth()) { 170 while (iday > tmpDate.daysInMonth()) {
176 imonth += freq; 171 imonth += freq;
177 if (imonth > 12) { 172 if (imonth > 12) {
178 imonth--; 173 imonth--;
179 iyear += imonth / 12; 174 iyear += imonth / 12;
180 imonth = imonth % 12; 175 imonth = imonth % 12;
181 imonth++; 176 imonth++;
182 } 177 }
183 tmpDate = QDate( iyear, imonth, 1 ); 178 tmpDate = QDate( iyear, imonth, 1 );
184 /* these loops could go for a while, check end case now */ 179 /* these loops could go for a while, check end case now */
185 if ((tmpDate > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 180 if ((tmpDate > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
186 return FALSE; 181 return FALSE;
187 iday = 1; 182 iday = 1;
188 iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7; 183 iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7;
189 iday += 7 * weekOfMonth; 184 iday += 7 * weekOfMonth;
190 } 185 }
191 tmpDate = QDate(iyear, imonth, iday); 186 tmpDate = QDate(iyear, imonth, iday);
192 187
193 if (tmpDate >= from) { 188 if (tmpDate >= from) {
194 next = QDateTime(tmpDate, e.start().time()); 189 next = QDateTime(tmpDate, e.start().time());
195 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 190 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
196 return FALSE; 191 return FALSE;
197 return TRUE; 192 return TRUE;
198 } 193 }
199 194
200 /* need to find the next iteration */ 195 /* need to find the next iteration */
201 do { 196 do {
202 imonth += freq; 197 imonth += freq;
203 if (imonth > 12) { 198 if (imonth > 12) {
204 imonth--; 199 imonth--;
205 iyear += imonth / 12; 200 iyear += imonth / 12;
206 imonth = imonth % 12; 201 imonth = imonth % 12;
207 imonth++; 202 imonth++;
208 } 203 }
209 tmpDate = QDate( iyear, imonth, 1 ); 204 tmpDate = QDate( iyear, imonth, 1 );
210 /* these loops could go for a while, check end case now */ 205 /* these loops could go for a while, check end case now */
211 if ((tmpDate > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 206 if ((tmpDate > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
212 return FALSE; 207 return FALSE;
213 iday = 1; 208 iday = 1;
214 iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7; 209 iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7;
215 iday += 7 * weekOfMonth; 210 iday += 7 * weekOfMonth;
216 } while (iday > tmpDate.daysInMonth()); 211 } while (iday > tmpDate.daysInMonth());
217 tmpDate = QDate(iyear, imonth, iday); 212 tmpDate = QDate(iyear, imonth, iday);
218 213
219 next = QDateTime(tmpDate, e.start().time()); 214 next = QDateTime(tmpDate, e.start().time());
220 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 215 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
221 return FALSE; 216 return FALSE;
222 return TRUE; 217 return TRUE;
223 case Event::MonthlyDate: 218 case Event::MonthlyDate:
224 iday = e.start().date().day(); 219 iday = e.start().date().day();
225 iyear = from.year(); 220 iyear = from.year();
226 imonth = from.month(); 221 imonth = from.month();
227 222
228 a = from.year() - e.start().date().year(); 223 a = from.year() - e.start().date().year();
229 a *= 12; 224 a *= 12;
230 a = a + (imonth - e.start().date().month()); 225 a = a + (imonth - e.start().date().month());
231 /* a is e.start()monthsFrom(from); */ 226 /* a is e.start()monthsFrom(from); */
232 if(a % freq) { 227 if(a % freq) {
233 a = freq - (a % freq); 228 a = freq - (a % freq);
234 imonth = from.month() + a; 229 imonth = from.month() + a;
235 if (imonth > 12) { 230 if (imonth > 12) {
236 imonth--; 231 imonth--;
237 iyear += imonth / 12; 232 iyear += imonth / 12;
238 imonth = imonth % 12; 233 imonth = imonth % 12;
239 imonth++; 234 imonth++;
240 } 235 }
241 } 236 }
242 /* imonth is now the first month after or on 237 /* imonth is now the first month after or on
243 from that matches the frequencey given */ 238 from that matches the frequencey given */
244 239
245 /* this could go for a while, worse case, 4*12 iterations, probably */ 240 /* this could go for a while, worse case, 4*12 iterations, probably */
246 while(!QDate::isValid(iyear, imonth, iday) ) { 241 while(!QDate::isValid(iyear, imonth, iday) ) {
247 imonth += freq; 242 imonth += freq;
248 if (imonth > 12) { 243 if (imonth > 12) {
249 imonth--; 244 imonth--;
250 iyear += imonth / 12; 245 iyear += imonth / 12;
251 imonth = imonth % 12; 246 imonth = imonth % 12;
252 imonth++; 247 imonth++;
253 } 248 }
254 /* these loops could go for a while, check end case now */ 249 /* these loops could go for a while, check end case now */
255 if ((QDate(iyear, imonth, 1) > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 250 if ((QDate(iyear, imonth, 1) > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
256 return FALSE; 251 return FALSE;
257 } 252 }
258 253
259 if(QDate(iyear, imonth, iday) >= from) { 254 if(QDate(iyear, imonth, iday) >= from) {
260 /* done */ 255 /* done */
261 next = QDateTime(QDate(iyear, imonth, iday), 256 next = QDateTime(QDate(iyear, imonth, iday),
262 e.start().time()); 257 e.start().time());
263 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 258 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
264 return FALSE; 259 return FALSE;
265 return TRUE; 260 return TRUE;
266 } 261 }
267 262
268 /* ok, need to cycle */ 263 /* ok, need to cycle */
269 imonth += freq; 264 imonth += freq;
270 imonth--; 265 imonth--;
271 iyear += imonth / 12; 266 iyear += imonth / 12;
272 imonth = imonth % 12; 267 imonth = imonth % 12;
273 imonth++; 268 imonth++;
274 269
275 while(!QDate::isValid(iyear, imonth, iday) ) { 270 while(!QDate::isValid(iyear, imonth, iday) ) {
276 imonth += freq; 271 imonth += freq;
277 imonth--; 272 imonth--;
278 iyear += imonth / 12; 273 iyear += imonth / 12;
279 imonth = imonth % 12; 274 imonth = imonth % 12;
280 imonth++; 275 imonth++;
281 if ((QDate(iyear, imonth, 1) > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 276 if ((QDate(iyear, imonth, 1) > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
282 return FALSE; 277 return FALSE;
283 } 278 }
284 279
285 next = QDateTime(QDate(iyear, imonth, iday), e.start().time()); 280 next = QDateTime(QDate(iyear, imonth, iday), e.start().time());
286 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 281 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
287 return FALSE; 282 return FALSE;
288 return TRUE; 283 return TRUE;
289 case Event::Yearly: 284 case Event::Yearly:
290 iday = e.start().date().day(); 285 iday = e.start().date().day();
291 imonth = e.start().date().month(); 286 imonth = e.start().date().month();
292 iyear = from.year(); // after all, we want to start in this year 287 iyear = from.year(); // after all, we want to start in this year
293 288
294 diff = 1; 289 diff = 1;
295 if(imonth == 2 && iday > 28) { 290 if(imonth == 2 && iday > 28) {
296 /* leap year, and it counts, calculate actual frequency */ 291 /* leap year, and it counts, calculate actual frequency */
297 if(freq % 4) 292 if(freq % 4)
298 if (freq % 2) 293 if (freq % 2)
299 freq = freq * 4; 294 freq = freq * 4;
300 else 295 else
301 freq = freq * 2; 296 freq = freq * 2;
302 /* else divides by 4 already, leave freq alone */ 297 /* else divides by 4 already, leave freq alone */
303 diff = 4; 298 diff = 4;
304 } 299 }
305 300
306 a = from.year() - e.start().date().year(); 301 a = from.year() - e.start().date().year();
307 if(a % freq) { 302 if(a % freq) {
308 a = freq - (a % freq); 303 a = freq - (a % freq);
309 iyear = iyear + a; 304 iyear = iyear + a;
310 } 305 }
311 306
312 /* under the assumption we won't hit one of the special not-leap years twice */ 307 /* under the assumption we won't hit one of the special not-leap years twice */
313 if(!QDate::isValid(iyear, imonth, iday)) { 308 if(!QDate::isValid(iyear, imonth, iday)) {
314 /* must have been skipping by leap years and hit one that wasn't, (e.g. 2100) */ 309 /* must have been skipping by leap years and hit one that wasn't, (e.g. 2100) */
315 iyear += freq; 310 iyear += freq;
316 } 311 }
317 312
318 if(QDate(iyear, imonth, iday) >= from) { 313 if(QDate(iyear, imonth, iday) >= from) {
319 next = QDateTime(QDate(iyear, imonth, iday), 314 next = QDateTime(QDate(iyear, imonth, iday),
320 e.start().time()); 315 e.start().time());
321 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 316 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
322 return FALSE; 317 return FALSE;
323 return TRUE; 318 return TRUE;
324 } 319 }
325 /* iyear == from.year(), need to advance again */ 320 /* iyear == from.year(), need to advance again */
326 iyear += freq; 321 iyear += freq;
327 /* under the assumption we won't hit one of the special not-leap years twice */ 322 /* under the assumption we won't hit one of the special not-leap years twice */
328 if(!QDate::isValid(iyear, imonth, iday)) { 323 if(!QDate::isValid(iyear, imonth, iday)) {
329 /* must have been skipping by leap years and hit one that wasn't, (e.g. 2100) */ 324 /* must have been skipping by leap years and hit one that wasn't, (e.g. 2100) */
330 iyear += freq; 325 iyear += freq;
331 } 326 }
332 327
333 next = QDateTime(QDate(iyear, imonth, iday), e.start().time()); 328 next = QDateTime(QDate(iyear, imonth, iday), e.start().time());
334 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate) 329 if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
335 return FALSE; 330 return FALSE;
336 return TRUE; 331 return TRUE;
337 default: 332 default:
338 return FALSE; 333 return FALSE;
339 } 334 }
340} 335}
341 336
342static bool nextAlarm( const Event &ev, QDateTime& when, int& warn) 337static bool nextAlarm( const Event &ev, QDateTime& when, int& warn)
343{ 338{
344 QDateTime now = QDateTime::currentDateTime(); 339 QDateTime now = QDateTime::currentDateTime();
345 if ( ev.hasRepeat() ) { 340 if ( ev.hasRepeat() ) {
346 QDateTime ralarm; 341 QDateTime ralarm;
347 if (nextOccurance(ev, now.date(), ralarm)) { 342 if (nextOccurance(ev, now.date(), ralarm)) {
348 ralarm = ralarm.addSecs(-ev.alarmTime()*60); 343 ralarm = ralarm.addSecs(-ev.alarmTime()*60);
349 if ( ralarm > now ) { 344 if ( ralarm > now ) {
350 when = ralarm; 345 when = ralarm;
351 warn = ev.alarmTime(); 346 warn = ev.alarmTime();
352 } else if ( nextOccurance(ev, now.date().addDays(1), ralarm) ) { 347 } else if ( nextOccurance(ev, now.date().addDays(1), ralarm) ) {
353 ralarm = ralarm.addSecs( -ev.alarmTime()*60 ); 348 ralarm = ralarm.addSecs( -ev.alarmTime()*60 );
354 if ( ralarm > now ) { 349 if ( ralarm > now ) {
355 when = ralarm; 350 when = ralarm;
356 warn = ev.alarmTime(); 351 warn = ev.alarmTime();
357 } 352 }
358 } 353 }
359 } 354 }
360 } else { 355 } else {
361 warn = ev.alarmTime(); 356 warn = ev.alarmTime();
362 when = ev.start().addSecs( -ev.alarmTime()*60 ); 357 when = ev.start().addSecs( -ev.alarmTime()*60 );
363 } 358 }
364 return when > now; 359 return when > now;
365} 360}
366 361
367static void addEventAlarm( const Event &ev ) 362static void addEventAlarm( const Event &ev )
368{ 363{
369 QDateTime when; 364 QDateTime when;
370 int warn; 365 int warn;
371 if ( nextAlarm(ev,when,warn) ) 366 if ( nextAlarm(ev,when,warn) )
372 AlarmServer::addAlarm( when, 367 AlarmServer::addAlarm( when,
373 "QPE/Application/datebook", 368 "QPE/Application/datebook",
374 "alarm(QDateTime,int)", warn ); 369 "alarm(QDateTime,int)", warn );
375} 370}
376 371
377static void delEventAlarm( const Event &ev ) 372static void delEventAlarm( const Event &ev )
378{ 373{
379 QDateTime when; 374 QDateTime when;
380 int warn; 375 int warn;
381 if ( nextAlarm(ev,when,warn) ) 376 if ( nextAlarm(ev,when,warn) )
382 AlarmServer::deleteAlarm( when, 377 AlarmServer::deleteAlarm( when,
383 "QPE/Application/datebook", 378 "QPE/Application/datebook",
384 "alarm(QDateTime,int)", warn ); 379 "alarm(QDateTime,int)", warn );
385} 380}
386 381
387 382
388DateBookDB::DateBookDB() 383DateBookDB::DateBookDB()
389{ 384{
390 init(); 385 init();
391} 386}
392 387
393DateBookDB::~DateBookDB() 388DateBookDB::~DateBookDB()
394{ 389{
395 save(); 390 save();
396 eventList.clear(); 391 eventList.clear();
397 repeatEvents.clear(); 392 repeatEvents.clear();
398} 393}
399 394
400 395
401//#### Why is this code duplicated in getEffectiveEvents ????? 396//#### Why is this code duplicated in getEffectiveEvents ?????
402//#### Addendum. Don't use this function, lets faze it out if we can. 397//#### Addendum. Don't use this function, lets faze it out if we can.
403QValueList<Event> DateBookDB::getEvents( const QDate &from, const QDate &to ) 398QValueList<Event> DateBookDB::getEvents( const QDate &from, const QDate &to )
404{ 399{
405 QValueList<Event> tmpList; 400 QValueList<Event> tmpList;
406 tmpList = getNonRepeatingEvents( from, to ); 401 tmpList = getNonRepeatingEvents( from, to );
407 402
408 // check for repeating events... 403 // check for repeating events...
409 for (QValueList<Event>::ConstIterator it = repeatEvents.begin(); 404 for (QValueList<Event>::ConstIterator it = repeatEvents.begin();
410 it != repeatEvents.end(); ++it) { 405 it != repeatEvents.end(); ++it) {
411 QDate itDate = from; 406 QDate itDate = from;
412 QDateTime due; 407 QDateTime due;
413 408
414 /* create a false end date, to short circuit on hard 409 /* create a false end date, to short circuit on hard
415 MonthlyDay recurences */ 410 MonthlyDay recurences */
416 Event dummy_event = *it; 411 Event dummy_event = *it;
417 Event::RepeatPattern r = dummy_event.repeatPattern(); 412 Event::RepeatPattern r = dummy_event.repeatPattern();
418 if ( !r.hasEndDate || r.endDate() > to ) { 413 if ( !r.hasEndDate || r.endDate() > to ) {
419 r.setEndDate( to ); 414 r.setEndDate( to );
420 r.hasEndDate = TRUE; 415 r.hasEndDate = TRUE;
421 } 416 }
422 dummy_event.setRepeat(TRUE, r); 417 dummy_event.setRepeat(TRUE, r);
423 418
424 while (nextOccurance(dummy_event, itDate, due)) { 419 while (nextOccurance(dummy_event, itDate, due)) {
425 if (due.date() > to) 420 if (due.date() > to)
426 break; 421 break;
427 Event newEvent = *it; 422 Event newEvent = *it;
428 newEvent.setStart(due); 423 newEvent.setStart(due);
429 newEvent.setEnd(due.addSecs((*it).start().secsTo((*it).end()))); 424 newEvent.setEnd(due.addSecs((*it).start().secsTo((*it).end())));
430 425
431 tmpList.append(newEvent); 426 tmpList.append(newEvent);
432 itDate = due.date().addDays(1); /* the next event */ 427 itDate = due.date().addDays(1); /* the next event */
433 } 428 }
434 } 429 }
435 qHeapSort(tmpList); 430 qHeapSort(tmpList);
436 return tmpList; 431 return tmpList;
437} 432}
438 433
439QValueList<Event> DateBookDB::getEvents( const QDateTime &start ) 434QValueList<Event> DateBookDB::getEvents( const QDateTime &start )
440{ 435{
441 QValueList<Event> day = getEvents(start.date(),start.date()); 436 QValueList<Event> day = getEvents(start.date(),start.date());
442 437
443 QValueListConstIterator<Event> it; 438 QValueListConstIterator<Event> it;
444 QDateTime dtTmp; 439 QDateTime dtTmp;
445 QValueList<Event> tmpList; 440 QValueList<Event> tmpList;
446 for (it = day.begin(); it != day.end(); ++it ) { 441 for (it = day.begin(); it != day.end(); ++it ) {
447 dtTmp = (*it).start(TRUE); 442 dtTmp = (*it).start(TRUE);
448 if ( dtTmp == start ) 443 if ( dtTmp == start )
449 tmpList.append( *it ); 444 tmpList.append( *it );
450 } 445 }
451 return tmpList; 446 return tmpList;
452} 447}
453 448
454//#### Why is this code duplicated in getEvents ????? 449//#### Why is this code duplicated in getEvents ?????
455 450
456QValueList<EffectiveEvent> DateBookDB::getEffectiveEvents( const QDate &from, 451QValueList<EffectiveEvent> DateBookDB::getEffectiveEvents( const QDate &from,
457 const QDate &to ) 452 const QDate &to )
458{ 453{
459 QValueList<EffectiveEvent> tmpList; 454 QValueList<EffectiveEvent> tmpList;
460 QValueListIterator<Event> it; 455 QValueListIterator<Event> it;
461 456
462 EffectiveEvent effEv; 457 EffectiveEvent effEv;
463 QDateTime dtTmp, 458 QDateTime dtTmp,
464 dtEnd; 459 dtEnd;
465 460
466 for (it = eventList.begin(); it != eventList.end(); ++it ) { 461 for (it = eventList.begin(); it != eventList.end(); ++it ) {
467 if (!(*it).isValidUid()) 462 if (!(*it).isValidUid())
468 (*it).assignUid(); // FIXME: Hack to restore cleared uids 463 (*it).assignUid(); // FIXME: Hack to restore cleared uids
469 464
470 dtTmp = (*it).start(TRUE); 465 dtTmp = (*it).start(TRUE);
471 dtEnd = (*it).end(TRUE); 466 dtEnd = (*it).end(TRUE);
472 467
473 if ( dtTmp.date() >= from && dtTmp.date() <= to ) { 468 if ( dtTmp.date() >= from && dtTmp.date() <= to ) {
474 Event tmpEv = *it; 469 Event tmpEv = *it;
475 effEv.setEvent(tmpEv); 470 effEv.setEvent(tmpEv);
476 effEv.setDate( dtTmp.date() ); 471 effEv.setDate( dtTmp.date() );
477 effEv.setStart( dtTmp.time() ); 472 effEv.setStart( dtTmp.time() );
478 if ( dtTmp.date() != dtEnd.date() ) 473 if ( dtTmp.date() != dtEnd.date() )
479 effEv.setEnd( QTime(23, 59, 0) ); 474 effEv.setEnd( QTime(23, 59, 0) );
480 else 475 else
481 effEv.setEnd( dtEnd.time() ); 476 effEv.setEnd( dtEnd.time() );
482 tmpList.append( effEv ); 477 tmpList.append( effEv );
483 } 478 }
484 // we must also check for end date information... 479 // we must also check for end date information...
485 if ( dtEnd.date() != dtTmp.date() && dtEnd.date() >= from ) { 480 if ( dtEnd.date() != dtTmp.date() && dtEnd.date() >= from ) {
486 QDateTime dt = dtTmp.addDays( 1 ); 481 QDateTime dt = dtTmp.addDays( 1 );
487 dt.setTime( QTime(0, 0, 0) ); 482 dt.setTime( QTime(0, 0, 0) );
488 QDateTime dtStop; 483 QDateTime dtStop;
489 if ( dtEnd > to ) { 484 if ( dtEnd > to ) {
490 dtStop = to; 485 dtStop = to;
491 } else 486 } else
492 dtStop = dtEnd; 487 dtStop = dtEnd;
493 while ( dt <= dtStop ) { 488 while ( dt <= dtStop ) {
494 Event tmpEv = *it; 489 Event tmpEv = *it;
495 effEv.setEvent( tmpEv ); 490 effEv.setEvent( tmpEv );
496 effEv.setDate( dt.date() ); 491 effEv.setDate( dt.date() );
497 if ( dt >= from ) { 492 if ( dt >= from ) {
498 effEv.setStart( QTime(0, 0, 0) ); 493 effEv.setStart( QTime(0, 0, 0) );
499 if ( dt.date() == dtEnd.date() ) 494 if ( dt.date() == dtEnd.date() )
500 effEv.setEnd( dtEnd.time() ); 495 effEv.setEnd( dtEnd.time() );
501 else 496 else
502 effEv.setEnd( QTime(23, 59, 59) ); 497 effEv.setEnd( QTime(23, 59, 59) );
503 tmpList.append( effEv ); 498 tmpList.append( effEv );
504 } 499 }
505 dt = dt.addDays( 1 ); 500 dt = dt.addDays( 1 );
506 } 501 }
507 } 502 }
508 } 503 }
509 // check for repeating events... 504 // check for repeating events...
510 QDateTime repeat; 505 QDateTime repeat;
511 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) { 506 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) {
512 if (!(*it).isValidUid()) 507 if (!(*it).isValidUid())
513 (*it).assignUid(); // FIXME: Hack to restore cleared uids 508 (*it).assignUid(); // FIXME: Hack to restore cleared uids
514 509
515 /* create a false end date, to short circuit on hard 510 /* create a false end date, to short circuit on hard
516 MonthlyDay recurences */ 511 MonthlyDay recurences */
517 Event dummy_event = *it; 512 Event dummy_event = *it;
518 int duration = (*it).start().date().daysTo( (*it).end().date() ); 513 int duration = (*it).start().date().daysTo( (*it).end().date() );
519 QDate itDate = from.addDays(-duration); 514 QDate itDate = from.addDays(-duration);
520 515
521 Event::RepeatPattern r = dummy_event.repeatPattern(); 516 Event::RepeatPattern r = dummy_event.repeatPattern();
522 if ( !r.hasEndDate || r.endDate() > to ) { 517 if ( !r.hasEndDate || r.endDate() > to ) {
523 r.setEndDate( to ); 518 r.setEndDate( to );
524 r.hasEndDate = TRUE; 519 r.hasEndDate = TRUE;
525 } 520 }
526 dummy_event.setRepeat(TRUE, r); 521 dummy_event.setRepeat(TRUE, r);
527 522
528 while (nextOccurance(dummy_event, itDate, repeat)) { 523 while (nextOccurance(dummy_event, itDate, repeat)) {
529 if(repeat.date() > to) 524 if(repeat.date() > to)
530 break; 525 break;
531 effEv.setDate( repeat.date() ); 526 effEv.setDate( repeat.date() );
532 if ((*it).type() == Event::AllDay) { 527 if ((*it).type() == Event::AllDay) {
533 effEv.setStart( QTime(0,0,0) ); 528 effEv.setStart( QTime(0,0,0) );
534 effEv.setEnd( QTime(23,59,59) ); 529 effEv.setEnd( QTime(23,59,59) );
535 } else { 530 } else {
536 /* we only occur by days, not hours/minutes/seconds. Hence 531 /* we only occur by days, not hours/minutes/seconds. Hence
537 the actual end and start times will be the same for 532 the actual end and start times will be the same for
538 every repeated event. For multi day events this is 533 every repeated event. For multi day events this is
539 fixed up later if on wronge day span */ 534 fixed up later if on wronge day span */
540 effEv.setStart( (*it).start().time() ); 535 effEv.setStart( (*it).start().time() );
541 effEv.setEnd( (*it).end().time() ); 536 effEv.setEnd( (*it).end().time() );
542 } 537 }
543 if ( duration != 0 ) { 538 if ( duration != 0 ) {
544 // multi-day repeating events 539 // multi-day repeating events
545 QDate sub_it = QMAX( repeat.date(), from ); 540 QDate sub_it = QMAX( repeat.date(), from );
546 QDate startDate = repeat.date(); 541 QDate startDate = repeat.date();
547 QDate endDate = startDate.addDays( duration ); 542 QDate endDate = startDate.addDays( duration );
548 543
549 while ( sub_it <= endDate && sub_it <= to ) { 544 while ( sub_it <= endDate && sub_it <= to ) {
550 EffectiveEvent tmpEffEv = effEv; 545 EffectiveEvent tmpEffEv = effEv;
551 Event tmpEv = *it; 546 Event tmpEv = *it;
552 tmpEffEv.setEvent( tmpEv ); 547 tmpEffEv.setEvent( tmpEv );
553 548
554 if ( sub_it != startDate ) 549 if ( sub_it != startDate )
555 tmpEffEv.setStart( QTime(0,0,0) ); 550 tmpEffEv.setStart( QTime(0,0,0) );
556 if ( sub_it != endDate ) 551 if ( sub_it != endDate )
557 tmpEffEv.setEnd( QTime(23,59,59) ); 552 tmpEffEv.setEnd( QTime(23,59,59) );
558 tmpEffEv.setDate( sub_it ); 553 tmpEffEv.setDate( sub_it );
559 tmpEffEv.setEffectiveDates( startDate, endDate ); 554 tmpEffEv.setEffectiveDates( startDate, endDate );
560 tmpList.append( tmpEffEv ); 555 tmpList.append( tmpEffEv );
561 sub_it = sub_it.addDays( 1 ); 556 sub_it = sub_it.addDays( 1 );
562 } 557 }
563 itDate = endDate; 558 itDate = endDate;
564 } else { 559 } else {
565 Event tmpEv = *it; 560 Event tmpEv = *it;
566 effEv.setEvent( tmpEv ); 561 effEv.setEvent( tmpEv );
567 tmpList.append( effEv ); 562 tmpList.append( effEv );
568 itDate = repeat.date().addDays( 1 ); 563 itDate = repeat.date().addDays( 1 );
569 } 564 }
570 } 565 }
571 } 566 }
572 567
573 qHeapSort( tmpList ); 568 qHeapSort( tmpList );
574 return tmpList; 569 return tmpList;
575} 570}
576 571
577QValueList<EffectiveEvent> DateBookDB::getEffectiveEvents( const QDateTime &dt) 572QValueList<EffectiveEvent> DateBookDB::getEffectiveEvents( const QDateTime &dt)
578{ 573{
579 QValueList<EffectiveEvent> day = getEffectiveEvents(dt.date(), dt.date()); 574 QValueList<EffectiveEvent> day = getEffectiveEvents(dt.date(), dt.date());
580 QValueListConstIterator<EffectiveEvent> it; 575 QValueListConstIterator<EffectiveEvent> it;
581 QValueList<EffectiveEvent> tmpList; 576 QValueList<EffectiveEvent> tmpList;
582 QDateTime dtTmp; 577 QDateTime dtTmp;
583 578
584 for (it = day.begin(); it != day.end(); ++it ) { 579 for (it = day.begin(); it != day.end(); ++it ) {
585 dtTmp = QDateTime( (*it).date(), (*it).start() ); 580 dtTmp = QDateTime( (*it).date(), (*it).start() );
586 // at the moment we don't have second granularity, be nice about that.. 581 // at the moment we don't have second granularity, be nice about that..
587 if ( QABS(dt.secsTo(dtTmp)) < 60 ) 582 if ( QABS(dt.secsTo(dtTmp)) < 60 )
588 tmpList.append( *it ); 583 tmpList.append( *it );
589 } 584 }
590 return tmpList; 585 return tmpList;
591} 586}
592 587
593void DateBookDB::addEvent( const Event &ev, bool doalarm ) 588void DateBookDB::addEvent( const Event &ev, bool doalarm )
594{ 589{
595 // write to the journal... 590 // write to the journal...
596 saveJournalEntry( ev, ACTION_ADD, -1, false ); 591 saveJournalEntry( ev, ACTION_ADD, -1, false );
597 addJFEvent( ev, doalarm ); 592 addJFEvent( ev, doalarm );
598 d->clean = false; 593 d->clean = false;
599} 594}
600 595
601void DateBookDB::addJFEvent( const Event &ev, bool doalarm ) 596void DateBookDB::addJFEvent( const Event &ev, bool doalarm )
602{ 597{
603 if ( doalarm && ev.hasAlarm() ) 598 if ( doalarm && ev.hasAlarm() )
604 addEventAlarm( ev ); 599 addEventAlarm( ev );
605 if ( ev.hasRepeat() ) 600 if ( ev.hasRepeat() )
606 repeatEvents.append( ev ); 601 repeatEvents.append( ev );
607 else 602 else
608 eventList.append( ev ); 603 eventList.append( ev );
609} 604}
610 605
611void DateBookDB::editEvent( const Event &old, Event &editedEv ) 606void DateBookDB::editEvent( const Event &old, Event &editedEv )
612{ 607{
613 int oldIndex=0; 608 int oldIndex=0;
614 bool oldHadRepeat = old.hasRepeat(); 609 bool oldHadRepeat = old.hasRepeat();
615 Event orig; 610 Event orig;
616 611
617 // write to the journal... 612 // write to the journal...
618 if ( oldHadRepeat ) { 613 if ( oldHadRepeat ) {
619 if ( origRepeat( old, orig ) ) // should work always... 614 if ( origRepeat( old, orig ) ) // should work always...
620 oldIndex = repeatEvents.findIndex( orig ); 615 oldIndex = repeatEvents.findIndex( orig );
621 } else 616 } else
622 oldIndex = eventList.findIndex( old ); 617 oldIndex = eventList.findIndex( old );
623 saveJournalEntry( editedEv, ACTION_REPLACE, oldIndex, oldHadRepeat ); 618 saveJournalEntry( editedEv, ACTION_REPLACE, oldIndex, oldHadRepeat );
624 619
625 // Delete old event 620 // Delete old event
626 if ( old.hasAlarm() ) 621 if ( old.hasAlarm() )
627 delEventAlarm( old ); 622 delEventAlarm( old );
628 if ( oldHadRepeat ) { 623 if ( oldHadRepeat ) {
629 if ( editedEv.hasRepeat() ) { // This mean that origRepeat was run above and 624 if ( editedEv.hasRepeat() ) { // This mean that origRepeat was run above and
630 // orig is initialized 625 // orig is initialized
631 // assumption, when someone edits a repeating event, they 626 // assumption, when someone edits a repeating event, they
632 // want to change them all, maybe not perfect, but it works 627 // want to change them all, maybe not perfect, but it works
633 // for the moment... 628 // for the moment...
634 repeatEvents.remove( orig ); 629 repeatEvents.remove( orig );
635 } else 630 } else
636 removeRepeat( old ); 631 removeRepeat( old );
637 } else { 632 } else {
638 QValueList<Event>::Iterator it = eventList.find( old ); 633 QValueList<Event>::Iterator it = eventList.find( old );
639 if ( it != eventList.end() ) 634 if ( it != eventList.end() )
640 eventList.remove( it ); 635 eventList.remove( it );
641 } 636 }
642 637
643 // Add new event 638 // Add new event
644 if ( editedEv.hasAlarm() ) 639 if ( editedEv.hasAlarm() )
645 addEventAlarm( editedEv ); 640 addEventAlarm( editedEv );
646 if ( editedEv.hasRepeat() ) 641 if ( editedEv.hasRepeat() )
647 repeatEvents.append( editedEv ); 642 repeatEvents.append( editedEv );
648 else 643 else
649 eventList.append( editedEv ); 644 eventList.append( editedEv );
650 645
651 d->clean = false; 646 d->clean = false;
652} 647}
653 648
654void DateBookDB::removeEvent( const Event &ev ) 649void DateBookDB::removeEvent( const Event &ev )
655{ 650{
656 // write to the journal... 651 // write to the journal...
657 saveJournalEntry( ev, ACTION_REMOVE, -1, false ); 652 saveJournalEntry( ev, ACTION_REMOVE, -1, false );
658 removeJFEvent( ev ); 653 removeJFEvent( ev );
659 d->clean = false; 654 d->clean = false;
660} 655}
661 656
662void DateBookDB::removeJFEvent( const Event&ev ) 657void DateBookDB::removeJFEvent( const Event&ev )
663{ 658{
664 if ( ev.hasAlarm() ) 659 if ( ev.hasAlarm() )
665 delEventAlarm( ev ); 660 delEventAlarm( ev );
666 if ( ev.hasRepeat() ) { 661 if ( ev.hasRepeat() ) {
667 removeRepeat( ev ); 662 removeRepeat( ev );
668 } else { 663 } else {
669 QValueList<Event>::Iterator it = eventList.find( ev ); 664 QValueList<Event>::Iterator it = eventList.find( ev );
670 if ( it != eventList.end() ) 665 if ( it != eventList.end() )
671 eventList.remove( it ); 666 eventList.remove( it );
672 } 667 }
673} 668}
674 669
675// also handles journaling... 670// also handles journaling...
676void DateBookDB::loadFile( const QString &strFile ) 671void DateBookDB::loadFile( const QString &strFile )
677{ 672{
678 673
679 QFile f( strFile ); 674 QFile f( strFile );
680 if ( !f.open( IO_ReadOnly ) ) 675 if ( !f.open( IO_ReadOnly ) )
681 return; 676 return;
682 677
683 enum Attribute { 678 enum Attribute {
684 FDescription = 0, 679 FDescription = 0,
685 FLocation, 680 FLocation,
686 FCategories, 681 FCategories,
687 FUid, 682 FUid,
688 FType, 683 FType,
689 FAlarm, 684 FAlarm,
690 FSound, 685 FSound,
691 FRType, 686 FRType,
692 FRWeekdays, 687 FRWeekdays,
693 FRPosition, 688 FRPosition,
694 FRFreq, 689 FRFreq,
695 FRHasEndDate, 690 FRHasEndDate,
696 FREndDate, 691 FREndDate,
697 FRStart, 692 FRStart,
698 FREnd, 693 FREnd,
699 FNote, 694 FNote,
700 FCreated, 695 FCreated,
701 FAction, 696 FAction,
702 FActionKey, 697 FActionKey,
703 FJournalOrigHadRepeat 698 FJournalOrigHadRepeat
704 }; 699 };
705 700
706 QAsciiDict<int> dict( 97 ); 701 QAsciiDict<int> dict( 97 );
707 dict.setAutoDelete( TRUE ); 702 dict.setAutoDelete( TRUE );
708 dict.insert( "description", new int(FDescription) ); 703 dict.insert( "description", new int(FDescription) );
709 dict.insert( "location", new int(FLocation) ); 704 dict.insert( "location", new int(FLocation) );
710 dict.insert( "categories", new int(FCategories) ); 705 dict.insert( "categories", new int(FCategories) );
711 dict.insert( "uid", new int(FUid) ); 706 dict.insert( "uid", new int(FUid) );
712 dict.insert( "type", new int(FType) ); 707 dict.insert( "type", new int(FType) );
713 dict.insert( "alarm", new int(FAlarm) ); 708 dict.insert( "alarm", new int(FAlarm) );
714 dict.insert( "sound", new int(FSound) ); 709 dict.insert( "sound", new int(FSound) );
715 dict.insert( "rtype", new int(FRType) ); 710 dict.insert( "rtype", new int(FRType) );
716 dict.insert( "rweekdays", new int(FRWeekdays) ); 711 dict.insert( "rweekdays", new int(FRWeekdays) );
717 dict.insert( "rposition", new int(FRPosition) ); 712 dict.insert( "rposition", new int(FRPosition) );
718 dict.insert( "rfreq", new int(FRFreq) ); 713 dict.insert( "rfreq", new int(FRFreq) );
719 dict.insert( "rhasenddate", new int(FRHasEndDate) ); 714 dict.insert( "rhasenddate", new int(FRHasEndDate) );
720 dict.insert( "enddt", new int(FREndDate) ); 715 dict.insert( "enddt", new int(FREndDate) );
721 dict.insert( "start", new int(FRStart) ); 716 dict.insert( "start", new int(FRStart) );
722 dict.insert( "end", new int(FREnd) ); 717 dict.insert( "end", new int(FREnd) );
723 dict.insert( "note", new int(FNote) ); 718 dict.insert( "note", new int(FNote) );
724 dict.insert( "created", new int(FCreated) ); 719 dict.insert( "created", new int(FCreated) );
725 dict.insert( "action", new int(FAction) ); 720 dict.insert( "action", new int(FAction) );
726 dict.insert( "actionkey", new int(FActionKey) ); 721 dict.insert( "actionkey", new int(FActionKey) );
727 dict.insert( "actionorig", new int (FJournalOrigHadRepeat) ); 722 dict.insert( "actionorig", new int (FJournalOrigHadRepeat) );
728 723
729 724
730 QByteArray ba = f.readAll(); 725 QByteArray ba = f.readAll();
731 char* dt = ba.data(); 726 char* dt = ba.data();
732 int len = ba.size(); 727 int len = ba.size();
733 int currentAction, 728 int currentAction,
734 journalKey, 729 journalKey,
735 origHadRepeat; // should be bool, but we need tri-state(not being used) 730 origHadRepeat; // should be bool, but we need tri-state(not being used)
736 731
737 int i = 0; 732 int i = 0;
738 char *point; 733 char *point;
739 // hack to get rid of segfaults after reading </DATEBOOK> 734 // hack to get rid of segfaults after reading </DATEBOOK>
740 while ( (dt+i != 0) && (( point = strstr( dt+i, "<event " ) ) != 0 )) { 735 while ( (dt+i != 0) && (( point = strstr( dt+i, "<event " ) ) != 0 )) {
741 i = point - dt; 736 i = point - dt;
742 // if we are reading in events in the general case, 737 // if we are reading in events in the general case,
743 // we are just adding them, so let the actions represent that... 738 // we are just adding them, so let the actions represent that...
744 currentAction = ACTION_ADD; 739 currentAction = ACTION_ADD;
745 journalKey = -1; 740 journalKey = -1;
746 origHadRepeat = -1; 741 origHadRepeat = -1;
747 // some temporary variables for dates and times ... 742 // some temporary variables for dates and times ...
748 //int startY = 0, startM = 0, startD = 0, starth = 0, startm = 0, starts = 0; 743 //int startY = 0, startM = 0, startD = 0, starth = 0, startm = 0, starts = 0;
749 //int endY = 0, endM = 0, endD = 0, endh = 0, endm = 0, ends = 0; 744 //int endY = 0, endM = 0, endD = 0, endh = 0, endm = 0, ends = 0;
750 //int enddtY = 0, enddtM = 0, enddtD = 0; 745 //int enddtY = 0, enddtM = 0, enddtD = 0;
751 746
752 // ... for the alarm settings ... 747 // ... for the alarm settings ...
753 int alarmTime = -1; Event::SoundTypeChoice alarmSound = Event::Silent; 748 int alarmTime = -1; Event::SoundTypeChoice alarmSound = Event::Silent;
754 // ... and for the recurrence 749 // ... and for the recurrence
755 Event::RepeatPattern rp; 750 Event::RepeatPattern rp;
756 Event e; 751 Event e;
757 752
758 i += 7; 753 i += 7;
759 754
760 while( 1 ) { 755 while( 1 ) {
761 while ( i < len && (dt[i] == ' ' || dt[i] == '\n' || dt[i] == '\r') ) 756 while ( i < len && (dt[i] == ' ' || dt[i] == '\n' || dt[i] == '\r') )
762 ++i; 757 ++i;
763 if ( i >= len-2 || (dt[i] == '/' && dt[i+1] == '>') ) 758 if ( i >= len-2 || (dt[i] == '/' && dt[i+1] == '>') )
764 break; 759 break;
765 // we have another attribute, read it. 760 // we have another attribute, read it.
766 int j = i; 761 int j = i;
767 while ( j < len && dt[j] != '=' ) 762 while ( j < len && dt[j] != '=' )
768 ++j; 763 ++j;
769 char *attr = dt+i; 764 char *attr = dt+i;
770 dt[j] = '\0'; 765 dt[j] = '\0';
771 i = ++j; // skip = 766 i = ++j; // skip =
772 while ( i < len && dt[i] != '"' ) 767 while ( i < len && dt[i] != '"' )
773 ++i; 768 ++i;
774 j = ++i; 769 j = ++i;
775 bool haveAmp = FALSE; 770 bool haveAmp = FALSE;
776 bool haveUtf = FALSE; 771 bool haveUtf = FALSE;
777 while ( j < len && dt[j] != '"' ) { 772 while ( j < len && dt[j] != '"' ) {
778 if ( dt[j] == '&' ) 773 if ( dt[j] == '&' )
779 haveAmp = TRUE; 774 haveAmp = TRUE;
780 if ( ((unsigned char)dt[j]) > 0x7f ) 775 if ( ((unsigned char)dt[j]) > 0x7f )
781 haveUtf = TRUE; 776 haveUtf = TRUE;
782 ++j; 777 ++j;
783 } 778 }
784 779
785 if ( i == j ) { 780 if ( i == j ) {
786 // leave out empty attributes 781 // leave out empty attributes
787 i = j + 1; 782 i = j + 1;
788 continue; 783 continue;
789 } 784 }
790 785
791 QString value = haveUtf ? QString::fromUtf8( dt+i, j-i ) 786 QString value = haveUtf ? QString::fromUtf8( dt+i, j-i )
792 : QString::fromLatin1( dt+i, j-i ); 787 : QString::fromLatin1( dt+i, j-i );
793 if ( haveAmp ) 788 if ( haveAmp )
794 value = Qtopia::plainString( value ); 789 value = Qtopia::plainString( value );
795 i = j + 1; 790 i = j + 1;
796 791
797 //qDebug("attr='%s' value='%s'", attr.data(), value.latin1() ); 792 //qDebug("attr='%s' value='%s'", attr.data(), value.latin1() );
798 int * find = dict[ attr ]; 793 int * find = dict[ attr ];
799#if 1 794#if 1
800 if ( !find ) { 795 if ( !find ) {
801 // custom field 796 // custom field
802 e.setCustomField(attr, value); 797 e.setCustomField(attr, value);
803 continue; 798 continue;
804 } 799 }
805 800
806 switch( *find ) { 801 switch( *find ) {
807 case FDescription: 802 case FDescription:
808 e.setDescription( value ); 803 e.setDescription( value );
809 break; 804 break;
810 case FLocation: 805 case FLocation:
811 e.setLocation( value ); 806 e.setLocation( value );
812 break; 807 break;
813 case FCategories: 808 case FCategories:
814 e.setCategories( Qtopia::Record::idsFromString( value ) ); 809 e.setCategories( Qtopia::Record::idsFromString( value ) );
815 break; 810 break;
816 case FUid: 811 case FUid:
817 e.setUid( value.toInt() ); 812 e.setUid( value.toInt() );
818 break; 813 break;
819 case FType: 814 case FType:
820 if ( value == "AllDay" ) 815 if ( value == "AllDay" )
821 e.setType( Event::AllDay ); 816 e.setType( Event::AllDay );
822 else 817 else
823 e.setType( Event::Normal ); 818 e.setType( Event::Normal );
824 break; 819 break;
825 case FAlarm: 820 case FAlarm:
826 alarmTime = value.toInt(); 821 alarmTime = value.toInt();
827 break; 822 break;
828 case FSound: 823 case FSound:
829 alarmSound = value == "loud" ? Event::Loud : Event::Silent; 824 alarmSound = value == "loud" ? Event::Loud : Event::Silent;
830 break; 825 break;
831 // recurrence stuff 826 // recurrence stuff
832 case FRType: 827 case FRType:
833 if ( value == "Daily" ) 828 if ( value == "Daily" )
834 rp.type = Event::Daily; 829 rp.type = Event::Daily;
835 else if ( value == "Weekly" ) 830 else if ( value == "Weekly" )
836 rp.type = Event::Weekly; 831 rp.type = Event::Weekly;
837 else if ( value == "MonthlyDay" ) 832 else if ( value == "MonthlyDay" )
838 rp.type = Event::MonthlyDay; 833 rp.type = Event::MonthlyDay;
839 else if ( value == "MonthlyDate" ) 834 else if ( value == "MonthlyDate" )
840 rp.type = Event::MonthlyDate; 835 rp.type = Event::MonthlyDate;
841 else if ( value == "Yearly" ) 836 else if ( value == "Yearly" )
842 rp.type = Event::Yearly; 837 rp.type = Event::Yearly;
843 else 838 else
844 rp.type = Event::NoRepeat; 839 rp.type = Event::NoRepeat;
845 break; 840 break;
846 case FRWeekdays: 841 case FRWeekdays:
847 // QtopiaDesktop 1.6 sometimes creates 'rweekdays="0"' 842 // QtopiaDesktop 1.6 sometimes creates 'rweekdays="0"'
848 // when it goes mad. This causes datebook to crash.. (se) 843 // when it goes mad. This causes datebook to crash.. (se)
849 if ( value.toInt() != 0 ) 844 if ( value.toInt() != 0 )
850 rp.days = value.toInt(); 845 rp.days = value.toInt();
851 else 846 else
852 rp.days = 1; 847 rp.days = 1;
853 break; 848 break;
854 case FRPosition: 849 case FRPosition:
855 rp.position = value.toInt(); 850 rp.position = value.toInt();
856 break; 851 break;
857 case FRFreq: 852 case FRFreq:
858 rp.frequency = value.toInt(); 853 rp.frequency = value.toInt();
859 break; 854 break;
860 case FRHasEndDate: 855 case FRHasEndDate:
861 rp.hasEndDate = value.toInt(); 856 rp.hasEndDate = value.toInt();
862 break; 857 break;
863 case FREndDate: { 858 case FREndDate: {
864 rp.endDateUTC = (time_t) value.toLong(); 859 rp.endDateUTC = (time_t) value.toLong();
865 break; 860 break;
866 } 861 }
867 case FRStart: { 862 case FRStart: {
868 e.setStart( (time_t) value.toLong() ); 863 e.setStart( (time_t) value.toLong() );
869 break; 864 break;
870 } 865 }
871 case FREnd: { 866 case FREnd: {
872 e.setEnd( (time_t) value.toLong() ); 867 e.setEnd( (time_t) value.toLong() );
873 break; 868 break;
874 } 869 }
875 case FNote: 870 case FNote:
876 e.setNotes( value ); 871 e.setNotes( value );
877 break; 872 break;
878 case FCreated: 873 case FCreated:
879 rp.createTime = value.toInt(); 874 rp.createTime = value.toInt();
880 break; 875 break;
881 case FAction: 876 case FAction:
882 currentAction = value.toInt(); 877 currentAction = value.toInt();
883 break; 878 break;
884 case FActionKey: 879 case FActionKey:
885 journalKey = value.toInt(); 880 journalKey = value.toInt();
886 break; 881 break;
887 case FJournalOrigHadRepeat: 882 case FJournalOrigHadRepeat:
888 origHadRepeat = value.toInt(); 883 origHadRepeat = value.toInt();
889 break; 884 break;
890 default: 885 default:
891 qDebug( "huh??? missing enum? -- attr.: %s", attr ); 886 qDebug( "huh??? missing enum? -- attr.: %s", attr );
892 break; 887 break;
893 } 888 }
894#endif 889#endif
895 } 890 }
896 // "post processing" (dates, times, alarm, recurrence) 891 // "post processing" (dates, times, alarm, recurrence)
897 892
898 // other half of 1169 fixlet without getting into regression 893 // other half of 1169 fixlet without getting into regression
899 // if rp.days == 0 and rp.type == Event::Weekly 894 // if rp.days == 0 and rp.type == Event::Weekly
900 if ( rp.type == Event::Weekly && rp.days == 0 ) 895 if ( rp.type == Event::Weekly && rp.days == 0 )
901 rp.days = Event::day( e.start().date().dayOfWeek() ); 896 rp.days = Event::day( e.start().date().dayOfWeek() );
902 897
903 898
904 // start date/time 899 // start date/time
905 e.setRepeat( rp.type != Event::NoRepeat, rp ); 900 e.setRepeat( rp.type != Event::NoRepeat, rp );
906 901
907 if ( alarmTime != -1 ) 902 if ( alarmTime != -1 )
908 e.setAlarm( TRUE, alarmTime, alarmSound ); 903 e.setAlarm( TRUE, alarmTime, alarmSound );
909 904
910 // now do our action based on the current action... 905 // now do our action based on the current action...
911 switch ( currentAction ) { 906 switch ( currentAction ) {
912 case ACTION_ADD: 907 case ACTION_ADD:
913 addJFEvent( e ); 908 addJFEvent( e );
914 break; 909 break;
915 case ACTION_REMOVE: 910 case ACTION_REMOVE:
916 removeJFEvent( e ); 911 removeJFEvent( e );
917 break; 912 break;
918 case ACTION_REPLACE: 913 case ACTION_REPLACE:
919 // be a little bit careful, 914 // be a little bit careful,
920 // in case of a messed up journal... 915 // in case of a messed up journal...
921 if ( journalKey > -1 && origHadRepeat > -1 ) { 916 if ( journalKey > -1 && origHadRepeat > -1 ) {
922 // get the original from proper list... 917 // get the original from proper list...
923 if ( origHadRepeat ) 918 if ( origHadRepeat )
924 removeJFEvent( *(repeatEvents.at(journalKey)) ); 919 removeJFEvent( *(repeatEvents.at(journalKey)) );
925 else 920 else
926 removeJFEvent( *(eventList.at(journalKey)) ); 921 removeJFEvent( *(eventList.at(journalKey)) );
927 addJFEvent( e ); 922 addJFEvent( e );
928 } 923 }
929 break; 924 break;
930 default: 925 default:
931 break; 926 break;
932 } 927 }
933 } 928 }
934 f.close(); 929 f.close();
935} 930}
936 931
937void DateBookDB::init() 932void DateBookDB::init()
938{ 933{
939 d = new DateBookDBPrivate; 934 d = new DateBookDBPrivate;
940 d->clean = false; 935 d->clean = false;
941 QString str = dateBookFilename(); 936 QString str = dateBookFilename();
942 if ( str.isNull() ) { 937 if ( str.isNull() ) {
943 QMessageBox::warning( 0, QObject::tr("Out of Space"), 938 QMessageBox::warning( 0, QObject::tr("Out of Space"),
944 QObject::tr("Unable to create start up files\n" 939 QObject::tr("Unable to create start up files\n"
945 "Please free up some space\n" 940 "Please free up some space\n"
946 "before entering data") ); 941 "before entering data") );
947 } 942 }
948 // continuing along, we call this datebook filename again, 943 // continuing along, we call this datebook filename again,
949 // because they may fix it before continuing, though it seems 944 // because they may fix it before continuing, though it seems
950 // pretty unlikely... 945 // pretty unlikely...
951 loadFile( dateBookFilename() ); 946 loadFile( dateBookFilename() );
952 947
953 if ( QFile::exists( dateBookJournalFile() ) ) { 948 if ( QFile::exists( dateBookJournalFile() ) ) {
954 // merge the journal 949 // merge the journal
955 loadFile( dateBookJournalFile() ); 950 loadFile( dateBookJournalFile() );
956 // save in our changes and remove the journal... 951 // save in our changes and remove the journal...
957 save(); 952 save();
958 } 953 }
959 d->clean = true; 954 d->clean = true;
960} 955}
961 956
962bool DateBookDB::save() 957bool DateBookDB::save()
963{ 958{
964 if ( d->clean == true ) 959 if ( d->clean == true )
965 return true; 960 return true;
966 QValueListIterator<Event> it; 961 QValueListIterator<Event> it;
967 int total_written; 962 int total_written;
968 QString strFileNew = dateBookFilename() + ".new"; 963 QString strFileNew = dateBookFilename() + ".new";
969 964
970 QFile f( strFileNew ); 965 QFile f( strFileNew );
971 if ( !f.open( IO_WriteOnly|IO_Raw ) ) 966 if ( !f.open( IO_WriteOnly|IO_Raw ) )
972 return FALSE; 967 return FALSE;
973 968
974 QString buf( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ); 969 QString buf( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
975 buf += "<!DOCTYPE DATEBOOK><DATEBOOK>\n"; 970 buf += "<!DOCTYPE DATEBOOK><DATEBOOK>\n";
976 buf += "<events>\n"; 971 buf += "<events>\n";
977 QCString str = buf.utf8(); 972 QCString str = buf.utf8();
978 total_written = f.writeBlock( str.data(), str.length() ); 973 total_written = f.writeBlock( str.data(), str.length() );
979 if ( total_written != int(str.length()) ) { 974 if ( total_written != int(str.length()) ) {
980 f.close(); 975 f.close();
981 QFile::remove( strFileNew ); 976 QFile::remove( strFileNew );
982 return false; 977 return false;
983 } 978 }
984 979
985 for ( it = eventList.begin(); it != eventList.end(); ++it ) { 980 for ( it = eventList.begin(); it != eventList.end(); ++it ) {
986 buf = "<event"; 981 buf = "<event";
987 (*it).save( buf ); 982 (*it).save( buf );
988 buf += " />\n"; 983 buf += " />\n";
989 str = buf.utf8(); 984 str = buf.utf8();
990 total_written = f.writeBlock( str.data(), str.length() ); 985 total_written = f.writeBlock( str.data(), str.length() );
991 if ( total_written != int(str.length()) ) { 986 if ( total_written != int(str.length()) ) {
992 f.close(); 987 f.close();
993 QFile::remove( strFileNew ); 988 QFile::remove( strFileNew );
994 return false; 989 return false;
995 } 990 }
996 } 991 }
997 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) { 992 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) {
998 buf = "<event"; 993 buf = "<event";
999 (*it).save( buf ); 994 (*it).save( buf );
1000 buf += " />\n"; 995 buf += " />\n";
1001 str = buf.utf8(); 996 str = buf.utf8();
1002 total_written = f.writeBlock( str.data(), str.length() ); 997 total_written = f.writeBlock( str.data(), str.length() );
1003 if ( total_written != int(str.length()) ) { 998 if ( total_written != int(str.length()) ) {
1004 f.close(); 999 f.close();
1005 QFile::remove( strFileNew ); 1000 QFile::remove( strFileNew );
1006 return false; 1001 return false;
1007 } 1002 }
1008 } 1003 }
1009 buf = "</events>\n</DATEBOOK>\n"; 1004 buf = "</events>\n</DATEBOOK>\n";
1010 str = buf.utf8(); 1005 str = buf.utf8();
1011 total_written = f.writeBlock( str.data(), str.length() ); 1006 total_written = f.writeBlock( str.data(), str.length() );
1012 if ( total_written != int(str.length()) ) { 1007 if ( total_written != int(str.length()) ) {
1013 f.close(); 1008 f.close();
1014 QFile::remove( strFileNew ); 1009 QFile::remove( strFileNew );
1015 return false; 1010 return false;
1016 } 1011 }
1017 f.close(); 1012 f.close();
1018 1013
1019 // now rename... I like to use the systemcall 1014 // now rename... I like to use the systemcall
1020 if ( ::rename( strFileNew, dateBookFilename() ) < 0 ) { 1015 if ( ::rename( strFileNew, dateBookFilename() ) < 0 ) {
1021 qWarning( "problem renaming file %s to %s errno %d", 1016 qWarning( "problem renaming file %s to %s errno %d",
1022 strFileNew.latin1(), dateBookFilename().latin1(), errno ); 1017 strFileNew.latin1(), dateBookFilename().latin1(), errno );
1023 // remove the file, otherwise it will just stick around... 1018 // remove the file, otherwise it will just stick around...
1024 QFile::remove( strFileNew ); 1019 QFile::remove( strFileNew );
1025 } 1020 }
1026 1021
1027 // may as well remove the journal file... 1022 // may as well remove the journal file...
1028 QFile::remove( dateBookJournalFile() ); 1023 QFile::remove( dateBookJournalFile() );
1029 d->clean = true; 1024 d->clean = true;
1030 return true; 1025 return true;
1031} 1026}
1032 1027
1033void DateBookDB::reload() 1028void DateBookDB::reload()
1034{ 1029{
1035 QValueList<Event>::Iterator it = eventList.begin(); 1030 QValueList<Event>::Iterator it = eventList.begin();
1036 for ( ; it != eventList.end(); ++it ) { 1031 for ( ; it != eventList.end(); ++it ) {
1037 if ( (*it).hasAlarm() ) 1032 if ( (*it).hasAlarm() )
1038 delEventAlarm( *it ); 1033 delEventAlarm( *it );
1039 if ( (*it).hasRepeat() ) 1034 if ( (*it).hasRepeat() )
1040 removeRepeat( *it ); 1035 removeRepeat( *it );
1041 } 1036 }
1042 eventList.clear(); 1037 eventList.clear();
1043 repeatEvents.clear(); // should be a NOP 1038 repeatEvents.clear(); // should be a NOP
1044 init(); 1039 init();
1045} 1040}
1046 1041
1047bool DateBookDB::removeRepeat( const Event &ev ) 1042bool DateBookDB::removeRepeat( const Event &ev )
1048{ 1043{
1049 time_t removeMe = ev.repeatPattern().createTime; 1044 time_t removeMe = ev.repeatPattern().createTime;
1050 QValueListIterator<Event> it; 1045 QValueListIterator<Event> it;
1051 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) { 1046 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) {
1052 if ( removeMe == (*it).repeatPattern().createTime ) { 1047 if ( removeMe == (*it).repeatPattern().createTime ) {
1053 (void)repeatEvents.remove( it ); 1048 (void)repeatEvents.remove( it );
1054 // best break, or we are going into undefined territory! 1049 // best break, or we are going into undefined territory!
1055 return TRUE; 1050 return TRUE;
1056 } 1051 }
1057 } 1052 }
1058 return FALSE; 1053 return FALSE;
1059} 1054}
1060 1055
1061bool DateBookDB::origRepeat( const Event &ev, Event &orig ) const 1056bool DateBookDB::origRepeat( const Event &ev, Event &orig ) const
1062{ 1057{
1063 time_t removeMe = ev.repeatPattern().createTime; 1058 time_t removeMe = ev.repeatPattern().createTime;
1064 QValueListConstIterator<Event> it; 1059 QValueListConstIterator<Event> it;
1065 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) { 1060 for ( it = repeatEvents.begin(); it != repeatEvents.end(); ++it ) {
1066 if ( removeMe == (*it).repeatPattern().createTime ) { 1061 if ( removeMe == (*it).repeatPattern().createTime ) {
1067 orig = (*it); 1062 orig = (*it);
1068 return TRUE; 1063 return TRUE;
1069 } 1064 }
1070 } 1065 }
1071 return FALSE; 1066 return FALSE;
1072} 1067}
1073 1068
1074void DateBookDB::saveJournalEntry( const Event &ev, journal_action action ) 1069void DateBookDB::saveJournalEntry( const Event &ev, journal_action action )
1075{ 1070{
1076 saveJournalEntry( ev, action, -1, false ); 1071 saveJournalEntry( ev, action, -1, false );
1077} 1072}
1078 1073
1079bool DateBookDB::saveJournalEntry( const Event &evOld, journal_action action, 1074bool DateBookDB::saveJournalEntry( const Event &evOld, journal_action action,
1080 int key, bool origHadRepeat ) 1075 int key, bool origHadRepeat )
1081{ 1076{
1082 bool status = false; 1077 bool status = false;
1083 Event ev = evOld; 1078 Event ev = evOld;
1084 // write our log based on the action 1079 // write our log based on the action
1085 QFile f( dateBookJournalFile() ); 1080 QFile f( dateBookJournalFile() );
1086 if ( !f.open( IO_WriteOnly|IO_Append ) ) 1081 if ( !f.open( IO_WriteOnly|IO_Append ) )
1087 return false; 1082 return false;
1088 QString buf = "<event"; 1083 QString buf = "<event";
1089 ev.save( buf ); 1084 ev.save( buf );
1090 buf += " action="; 1085 buf += " action=";
1091 buf += "\"" + QString::number(action) + "\""; 1086 buf += "\"" + QString::number(action) + "\"";
1092 buf += " actionkey=\"" + QString::number(key) + "\""; 1087 buf += " actionkey=\"" + QString::number(key) + "\"";
1093 buf += " actionorig=\"" + QString::number(origHadRepeat) +"\""; 1088 buf += " actionorig=\"" + QString::number(origHadRepeat) +"\"";
1094 buf += " />\n"; 1089 buf += " />\n";
1095 QString str = buf.utf8(); 1090 QString str = buf.utf8();
1096 status = ( f.writeBlock( str.data(), str.length() ) == int(str.length()) ); 1091 status = ( f.writeBlock( str.data(), str.length() ) == int(str.length()) );
1097 f.close(); 1092 f.close();
1098 return status; 1093 return status;
1099} 1094}
1100 1095
1101QValueList<Event> DateBookDB::getRawRepeats() const 1096QValueList<Event> DateBookDB::getRawRepeats() const
1102{ 1097{
1103 return repeatEvents; 1098 return repeatEvents;
1104} 1099}
1105 1100
1106QValueList<Event> DateBookDB::getNonRepeatingEvents( const QDate &from, 1101QValueList<Event> DateBookDB::getNonRepeatingEvents( const QDate &from,
1107 const QDate &to ) const 1102 const QDate &to ) const
1108{ 1103{
1109 QValueListConstIterator<Event> it; 1104 QValueListConstIterator<Event> it;
1110 QDateTime dtTmp, dtEnd; 1105 QDateTime dtTmp, dtEnd;
1111 QValueList<Event> tmpList; 1106 QValueList<Event> tmpList;
1112 for (it = eventList.begin(); it != eventList.end(); ++it ) { 1107 for (it = eventList.begin(); it != eventList.end(); ++it ) {
1113 dtTmp = (*it).start(TRUE); 1108 dtTmp = (*it).start(TRUE);
1114 dtEnd = (*it).end(TRUE); 1109 dtEnd = (*it).end(TRUE);
1115 1110
1116 if ( dtTmp.date() >= from && dtTmp.date() <= to ) { 1111 if ( dtTmp.date() >= from && dtTmp.date() <= to ) {
1117 Event e = *it; 1112 Event e = *it;
1118 if ( dtTmp.date() != dtEnd.date() ) 1113 if ( dtTmp.date() != dtEnd.date() )
1119 e.setEnd( QDateTime(dtTmp.date(), QTime(23, 59, 0)) ); 1114 e.setEnd( QDateTime(dtTmp.date(), QTime(23, 59, 0)) );
1120 tmpList.append( e ); 1115 tmpList.append( e );
1121 } 1116 }
1122 // we must also check for end date information... 1117 // we must also check for end date information...
1123 if ( dtEnd.date() != dtTmp.date() && dtEnd.date() >= from ) { 1118 if ( dtEnd.date() != dtTmp.date() && dtEnd.date() >= from ) {
1124 QDateTime dt = dtTmp.addDays( 1 ); 1119 QDateTime dt = dtTmp.addDays( 1 );
1125 dt.setTime( QTime(0, 0, 0) ); 1120 dt.setTime( QTime(0, 0, 0) );
1126 QDateTime dtStop; 1121 QDateTime dtStop;
1127 if ( dtEnd > to ) { 1122 if ( dtEnd > to ) {
1128 dtStop = to; 1123 dtStop = to;
1129 } else 1124 } else
1130 dtStop = dtEnd; 1125 dtStop = dtEnd;
1131 while ( dt <= dtStop ) { 1126 while ( dt <= dtStop ) {
1132 Event ev = *it; 1127 Event ev = *it;
1133 if ( dt >= from ) { 1128 if ( dt >= from ) {
1134 ev.setStart( QDateTime(dt.date(), QTime(0, 0, 0)) ); 1129 ev.setStart( QDateTime(dt.date(), QTime(0, 0, 0)) );
1135 if ( dt.date() == dtEnd.date() ) 1130 if ( dt.date() == dtEnd.date() )
1136 ev.setEnd( QDateTime(dt.date(), dtEnd.time()) ); 1131 ev.setEnd( QDateTime(dt.date(), dtEnd.time()) );
1137 else 1132 else
1138 ev.setEnd( QDateTime(dt.date(), QTime(23, 59, 0)) ); 1133 ev.setEnd( QDateTime(dt.date(), QTime(23, 59, 0)) );
1139 tmpList.append( ev ); 1134 tmpList.append( ev );
1140 } 1135 }
1141 dt = dt.addDays( 1 ); 1136 dt = dt.addDays( 1 );
1142 } 1137 }
1143 } 1138 }
1144 } 1139 }
1145 return tmpList; 1140 return tmpList;
1146} 1141}
diff --git a/library/datebookmonth.cpp b/library/datebookmonth.cpp
index 728045f..76e022f 100644
--- a/library/datebookmonth.cpp
+++ b/library/datebookmonth.cpp
@@ -1,767 +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 <qtopia/private/event.h>
24#include "resource.h" 23#include "resource.h"
25#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
26#include "timestring.h"
27 25
28#include <qtoolbutton.h> 26#include <qtoolbutton.h>
29#include <qspinbox.h> 27#include <qspinbox.h>
30#include <qcombobox.h> 28#include <qcombobox.h>
31#include <qdatetime.h>
32#include <qpainter.h>
33#include <qpopupmenu.h>
34#include <qvaluestack.h> 29#include <qvaluestack.h>
35#include <qwhatsthis.h> 30#include <qwhatsthis.h>
36 31
37 32
38DateBookMonthHeader::DateBookMonthHeader( QWidget *parent, const char *name ) 33DateBookMonthHeader::DateBookMonthHeader( QWidget *parent, const char *name )
39 : QHBox( parent, name ) 34 : QHBox( parent, name )
40{ 35{
41 setBackgroundMode( PaletteButton ); 36 setBackgroundMode( PaletteButton );
42 37
43 begin = new QToolButton( this ); 38 begin = new QToolButton( this );
44 begin->setFocusPolicy(NoFocus); 39 begin->setFocusPolicy(NoFocus);
45 begin->setPixmap( Resource::loadPixmap( "start" ) ); 40 begin->setPixmap( Resource::loadPixmap( "start" ) );
46 begin->setAutoRaise( TRUE ); 41 begin->setAutoRaise( TRUE );
47 begin->setFixedSize( begin->sizeHint() ); 42 begin->setFixedSize( begin->sizeHint() );
48 QWhatsThis::add( begin, tr("Show January in the selected year") ); 43 QWhatsThis::add( begin, tr("Show January in the selected year") );
49 44
50 back = new QToolButton( this ); 45 back = new QToolButton( this );
51 back->setFocusPolicy(NoFocus); 46 back->setFocusPolicy(NoFocus);
52 back->setPixmap( Resource::loadPixmap( "back" ) ); 47 back->setPixmap( Resource::loadPixmap( "back" ) );
53 back->setAutoRaise( TRUE ); 48 back->setAutoRaise( TRUE );
54 back->setFixedSize( back->sizeHint() ); 49 back->setFixedSize( back->sizeHint() );
55 QWhatsThis::add( back, tr("Show the previous month") ); 50 QWhatsThis::add( back, tr("Show the previous month") );
56 51
57 month = new QComboBox( FALSE, this ); 52 month = new QComboBox( FALSE, this );
58 for ( int i = 0; i < 12; ++i ) 53 for ( int i = 0; i < 12; ++i )
59 month->insertItem( Calendar::nameOfMonth( i + 1 ) ); 54 month->insertItem( Calendar::nameOfMonth( i + 1 ) );
60 55
61 year = new QSpinBox( 1752, 8000, 1, this ); 56 year = new QSpinBox( 1752, 8000, 1, this );
62 57
63 next = new QToolButton( this ); 58 next = new QToolButton( this );
64 next->setFocusPolicy(NoFocus); 59 next->setFocusPolicy(NoFocus);
65 next->setPixmap( Resource::loadPixmap( "forward" ) ); 60 next->setPixmap( Resource::loadPixmap( "forward" ) );
66 next->setAutoRaise( TRUE ); 61 next->setAutoRaise( TRUE );
67 next->setFixedSize( next->sizeHint() ); 62 next->setFixedSize( next->sizeHint() );
68 QWhatsThis::add( next, tr("Show the next month") ); 63 QWhatsThis::add( next, tr("Show the next month") );
69 64
70 end = new QToolButton( this ); 65 end = new QToolButton( this );
71 end->setFocusPolicy(NoFocus); 66 end->setFocusPolicy(NoFocus);
72 end->setPixmap( Resource::loadPixmap( "finish" ) ); 67 end->setPixmap( Resource::loadPixmap( "finish" ) );
73 end->setAutoRaise( TRUE ); 68 end->setAutoRaise( TRUE );
74 end->setFixedSize( end->sizeHint() ); 69 end->setFixedSize( end->sizeHint() );
75 QWhatsThis::add( end, tr("Show December in the selected year") ); 70 QWhatsThis::add( end, tr("Show December in the selected year") );
76 71
77 connect( month, SIGNAL( activated( int ) ), 72 connect( month, SIGNAL( activated( int ) ),
78 this, SLOT( updateDate() ) ); 73 this, SLOT( updateDate() ) );
79 connect( year, SIGNAL( valueChanged( int ) ), 74 connect( year, SIGNAL( valueChanged( int ) ),
80 this, SLOT( updateDate() ) ); 75 this, SLOT( updateDate() ) );
81 connect( begin, SIGNAL( clicked() ), 76 connect( begin, SIGNAL( clicked() ),
82 this, SLOT( firstMonth() ) ); 77 this, SLOT( firstMonth() ) );
83 connect( end, SIGNAL( clicked() ), 78 connect( end, SIGNAL( clicked() ),
84 this, SLOT( lastMonth() ) ); 79 this, SLOT( lastMonth() ) );
85 connect( back, SIGNAL( clicked() ), 80 connect( back, SIGNAL( clicked() ),
86 this, SLOT( monthBack() ) ); 81 this, SLOT( monthBack() ) );
87 connect( next, SIGNAL( clicked() ), 82 connect( next, SIGNAL( clicked() ),
88 this, SLOT( monthForward() ) ); 83 this, SLOT( monthForward() ) );
89 back->setAutoRepeat( TRUE ); 84 back->setAutoRepeat( TRUE );
90 next->setAutoRepeat( TRUE ); 85 next->setAutoRepeat( TRUE );
91} 86}
92 87
93 88
94DateBookMonthHeader::~DateBookMonthHeader() 89DateBookMonthHeader::~DateBookMonthHeader()
95{ 90{
96 91
97} 92}
98 93
99void DateBookMonthHeader::updateDate() 94void DateBookMonthHeader::updateDate()
100{ 95{
101 emit dateChanged( year->value(), month->currentItem() + 1 ); 96 emit dateChanged( year->value(), month->currentItem() + 1 );
102} 97}
103 98
104void DateBookMonthHeader::firstMonth() 99void DateBookMonthHeader::firstMonth()
105{ 100{
106 emit dateChanged( year->value(), 1 ); 101 emit dateChanged( year->value(), 1 );
107 month->setCurrentItem( 0 ); 102 month->setCurrentItem( 0 );
108} 103}
109 104
110void DateBookMonthHeader::lastMonth() 105void DateBookMonthHeader::lastMonth()
111{ 106{
112 emit dateChanged( year->value(), 12 ); 107 emit dateChanged( year->value(), 12 );
113 month->setCurrentItem( 11 ); 108 month->setCurrentItem( 11 );
114} 109}
115 110
116void DateBookMonthHeader::monthBack() 111void DateBookMonthHeader::monthBack()
117{ 112{
118 if ( month->currentItem() > 0 ) { 113 if ( month->currentItem() > 0 ) {
119 emit dateChanged( year->value(), month->currentItem() ); 114 emit dateChanged( year->value(), month->currentItem() );
120 month->setCurrentItem( month->currentItem() - 1 ); 115 month->setCurrentItem( month->currentItem() - 1 );
121 } else { 116 } else {
122 emit dateChanged( year->value() - 1, 12 ); 117 emit dateChanged( year->value() - 1, 12 );
123 // 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
124 // year to get the result... 119 // year to get the result...
125 month->setCurrentItem( 11 ); 120 month->setCurrentItem( 11 );
126 year->setValue( year->value() - 1 ); 121 year->setValue( year->value() - 1 );
127 } 122 }
128} 123}
129 124
130void DateBookMonthHeader::monthForward() 125void DateBookMonthHeader::monthForward()
131{ 126{
132 if ( month->currentItem() < 11 ) { 127 if ( month->currentItem() < 11 ) {
133 emit dateChanged( year->value(), month->currentItem() + 2 ); 128 emit dateChanged( year->value(), month->currentItem() + 2 );
134 month->setCurrentItem( month->currentItem() + 1 ); 129 month->setCurrentItem( month->currentItem() + 1 );
135 } else { 130 } else {
136 // 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
137 // year to get the result... 132 // year to get the result...
138 month->setCurrentItem( 0 ); 133 month->setCurrentItem( 0 );
139 year->setValue( year->value() + 1 ); 134 year->setValue( year->value() + 1 );
140 } 135 }
141} 136}
142 137
143void DateBookMonthHeader::setDate( int y, int m ) 138void DateBookMonthHeader::setDate( int y, int m )
144{ 139{
145 year->setValue( y ); 140 year->setValue( y );
146 month->setCurrentItem( m - 1 ); 141 month->setCurrentItem( m - 1 );
147} 142}
148 143
149//--------------------------------------------------------------------------- 144//---------------------------------------------------------------------------
150 145
151class DateBookMonthTablePrivate 146class DateBookMonthTablePrivate
152{ 147{
153public: 148public:
154 DateBookMonthTablePrivate() {}; 149 DateBookMonthTablePrivate() {};
155 ~DateBookMonthTablePrivate() { mMonthEvents.clear(); }; 150 ~DateBookMonthTablePrivate() { mMonthEvents.clear(); };
156 151
157 QValueList<EffectiveEvent> mMonthEvents; 152 QValueList<EffectiveEvent> mMonthEvents;
158 bool onMonday; 153 bool onMonday;
159}; 154};
160 155
161DateBookMonthTable::DateBookMonthTable( QWidget *parent, const char *name, 156DateBookMonthTable::DateBookMonthTable( QWidget *parent, const char *name,
162 DateBookDB *newDb ) 157 DateBookDB *newDb )
163 : QTable( 6, 7, parent, name ), 158 : QTable( 6, 7, parent, name ),
164 db( newDb ) 159 db( newDb )
165{ 160{
166 d = new DateBookMonthTablePrivate(); 161 d = new DateBookMonthTablePrivate();
167 selYear = -1; 162 selYear = -1;
168 selMonth = -1; 163 selMonth = -1;
169 selDay = -1; 164 selDay = -1;
170 165
171 /* 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 */
172 year = -1; 167 year = -1;
173 month = -1; 168 month = -1;
174 day = -1; 169 day = -1;
175 170
176 Config cfg( "qpe" ); 171 Config cfg( "qpe" );
177 cfg.setGroup( "Time" ); 172 cfg.setGroup( "Time" );
178 d->onMonday = cfg.readBoolEntry( "MONDAY" ); 173 d->onMonday = cfg.readBoolEntry( "MONDAY" );
179 174
180 horizontalHeader()->setResizeEnabled( FALSE ); 175 horizontalHeader()->setResizeEnabled( FALSE );
181 // we have to do this here... or suffer the consequences later... 176 // we have to do this here... or suffer the consequences later...
182 for ( int i = 0; i < 7; i++ ){ 177 for ( int i = 0; i < 7; i++ ){
183 horizontalHeader()->resizeSection( i, 30 ); 178 horizontalHeader()->resizeSection( i, 30 );
184 setColumnStretchable( i, TRUE ); 179 setColumnStretchable( i, TRUE );
185 } 180 }
186 setupLabels(); 181 setupLabels();
187 182
188 verticalHeader()->hide(); 183 verticalHeader()->hide();
189 setLeftMargin( 0 ); 184 setLeftMargin( 0 );
190 for ( int i = 0; i < 6; ++i ) 185 for ( int i = 0; i < 6; ++i )
191 setRowStretchable( i, TRUE ); 186 setRowStretchable( i, TRUE );
192 187
193 setSelectionMode( NoSelection ); 188 setSelectionMode( NoSelection );
194 189
195 connect( this, SIGNAL( clicked( int, int, int, const QPoint & ) ), 190 connect( this, SIGNAL( clicked( int, int, int, const QPoint & ) ),
196 this, SLOT( dayClicked( int, int ) ) ); 191 this, SLOT( dayClicked( int, int ) ) );
197 connect( this, SIGNAL( currentChanged( int, int ) ), 192 connect( this, SIGNAL( currentChanged( int, int ) ),
198 this, SLOT( dragDay( int, int ) ) ); 193 this, SLOT( dragDay( int, int ) ) );
199 setVScrollBarMode( AlwaysOff ); 194 setVScrollBarMode( AlwaysOff );
200 setHScrollBarMode( AlwaysOff ); 195 setHScrollBarMode( AlwaysOff );
201} 196}
202 197
203DateBookMonthTable::~DateBookMonthTable() 198DateBookMonthTable::~DateBookMonthTable()
204{ 199{
205 monthsEvents.clear(); 200 monthsEvents.clear();
206 delete d; 201 delete d;
207} 202}
208 203
209void DateBookMonthTable::setDate(int y, int m, int d) 204void DateBookMonthTable::setDate(int y, int m, int d)
210{ 205{
211 if (month == m && year == y) { 206 if (month == m && year == y) {
212 if ( selYear == -1 ) 207 if ( selYear == -1 )
213 year = selYear; 208 year = selYear;
214 if ( selMonth == -1 ) 209 if ( selMonth == -1 )
215 month = selMonth; 210 month = selMonth;
216 int r1, c1, r2, c2; 211 int r1, c1, r2, c2;
217 findDay(selDay, r1, c1); 212 findDay(selDay, r1, c1);
218 selDay = day = d; 213 selDay = day = d;
219 findDay(selDay, r2, c2); 214 findDay(selDay, r2, c2);
220 setCurrentCell( r2, c2 ); 215 setCurrentCell( r2, c2 );
221 //updateCell(r1,c1); 216 //updateCell(r1,c1);
222 //updateCell(r2,c2); 217 //updateCell(r2,c2);
223 } else { 218 } else {
224 selYear = year = y; 219 selYear = year = y;
225 selMonth = month = m; 220 selMonth = month = m;
226 selDay = day = d; 221 selDay = day = d;
227 setupTable(); 222 setupTable();
228 } 223 }
229} 224}
230 225
231void DateBookMonthTable::redraw() 226void DateBookMonthTable::redraw()
232{ 227{
233 setupLabels(); 228 setupLabels();
234 setupTable(); 229 setupTable();
235} 230}
236 231
237void DateBookMonthTable::setWeekStart( bool onMonday ) 232void DateBookMonthTable::setWeekStart( bool onMonday )
238{ 233{
239 d->onMonday = onMonday; 234 d->onMonday = onMonday;
240 setupLabels(); 235 setupLabels();
241 setupTable(); 236 setupTable();
242} 237}
243 238
244void DateBookMonthTable::setupTable() 239void DateBookMonthTable::setupTable()
245{ 240{
246 QValueList<Calendar::Day> days = Calendar::daysOfMonth( year, month, d->onMonday ); 241 QValueList<Calendar::Day> days = Calendar::daysOfMonth( year, month, d->onMonday );
247 QValueList<Calendar::Day>::Iterator it = days.begin(); 242 QValueList<Calendar::Day>::Iterator it = days.begin();
248 int row = 0, col = 0; 243 int row = 0, col = 0;
249 int crow = 0; 244 int crow = 0;
250 int ccol = 0; 245 int ccol = 0;
251 for ( ; it != days.end(); ++it ) { 246 for ( ; it != days.end(); ++it ) {
252 DayItemMonth *i = (DayItemMonth *)item( row, col ); 247 DayItemMonth *i = (DayItemMonth *)item( row, col );
253 if ( !i ) { 248 if ( !i ) {
254 i = new DayItemMonth( this, QTableItem::Never, "" ); 249 i = new DayItemMonth( this, QTableItem::Never, "" );
255 setItem( row, col, i ); 250 setItem( row, col, i );
256 } 251 }
257 Calendar::Day calDay = *it; 252 Calendar::Day calDay = *it;
258 i->clearEffEvents(); 253 i->clearEffEvents();
259 i->setDay( calDay.date ); 254 i->setDay( calDay.date );
260 i->setType( calDay.type ); 255 i->setType( calDay.type );
261 if ( i->day() == day && calDay.type == Calendar::Day::ThisMonth ) { 256 if ( i->day() == day && calDay.type == Calendar::Day::ThisMonth ) {
262 crow = row; 257 crow = row;
263 ccol = col; 258 ccol = col;
264 } 259 }
265 260
266 updateCell( row, col ); 261 updateCell( row, col );
267 262
268 if ( col == 6 ) { 263 if ( col == 6 ) {
269 ++row; 264 ++row;
270 col = 0; 265 col = 0;
271 } else { 266 } else {
272 ++col; 267 ++col;
273 } 268 }
274 } 269 }
275 setCurrentCell( crow, ccol ); 270 setCurrentCell( crow, ccol );
276 getEvents(); 271 getEvents();
277} 272}
278 273
279void DateBookMonthTable::findDay( int day, int &row, int &col ) 274void DateBookMonthTable::findDay( int day, int &row, int &col )
280{ 275{
281 QDate dtBegin( year, month, 1 ); 276 QDate dtBegin( year, month, 1 );
282 int skips = dtBegin.dayOfWeek(); 277 int skips = dtBegin.dayOfWeek();
283 int effective_day = day + skips - 1; // row/columns begin at 0 278 int effective_day = day + skips - 1; // row/columns begin at 0
284 // make an extra adjustment if we start on Mondays. 279 // make an extra adjustment if we start on Mondays.
285 if ( d->onMonday ) 280 if ( d->onMonday )
286 effective_day--; 281 effective_day--;
287 row = effective_day / 7; 282 row = effective_day / 7;
288 col = effective_day % 7; 283 col = effective_day % 7;
289} 284}
290 285
291void DateBookMonthTable::dayClicked( int row, int col ) 286void DateBookMonthTable::dayClicked( int row, int col )
292{ 287{
293 changeDaySelection( row, col ); 288 changeDaySelection( row, col );
294 emit dateClicked( selYear, selMonth, selDay ); 289 emit dateClicked( selYear, selMonth, selDay );
295} 290}
296 291
297void DateBookMonthTable::dragDay( int row, int col ) 292void DateBookMonthTable::dragDay( int row, int col )
298{ 293{
299 changeDaySelection( row, col ); 294 changeDaySelection( row, col );
300} 295}
301 296
302void DateBookMonthTable::changeDaySelection( int row, int col ) 297void DateBookMonthTable::changeDaySelection( int row, int col )
303{ 298{
304 DayItemMonth *i = (DayItemMonth*)item( row, col ); 299 DayItemMonth *i = (DayItemMonth*)item( row, col );
305 if ( !i ) 300 if ( !i )
306 return; 301 return;
307 switch ( i->type() ) { 302 switch ( i->type() ) {
308 case Calendar::Day::ThisMonth: 303 case Calendar::Day::ThisMonth:
309 selMonth = month; 304 selMonth = month;
310 break; 305 break;
311 case Calendar::Day::PrevMonth: 306 case Calendar::Day::PrevMonth:
312 selMonth = month-1; 307 selMonth = month-1;
313 break; 308 break;
314 default: 309 default:
315 selMonth = month+1; 310 selMonth = month+1;
316 } 311 }
317 312
318 selYear = year; 313 selYear = year;
319 if ( selMonth <= 0 ) { 314 if ( selMonth <= 0 ) {
320 selMonth = 12; 315 selMonth = 12;
321 selYear--; 316 selYear--;
322 } else if ( selMonth > 12 ) { 317 } else if ( selMonth > 12 ) {
323 selMonth = 1; 318 selMonth = 1;
324 selYear++; 319 selYear++;
325 } 320 }
326 selDay = i->day(); 321 selDay = i->day();
327} 322}
328 323
329 324
330void DateBookMonthTable::viewportMouseReleaseEvent( QMouseEvent * ) 325void DateBookMonthTable::viewportMouseReleaseEvent( QMouseEvent * )
331{ 326{
332 dayClicked( currentRow(), currentColumn() ); 327 dayClicked( currentRow(), currentColumn() );
333} 328}
334 329
335void DateBookMonthTable::getEvents() 330void DateBookMonthTable::getEvents()
336{ 331{
337 if ( !db ) 332 if ( !db )
338 return; 333 return;
339 334
340 QDate dtStart( year, month, 1 ); 335 QDate dtStart( year, month, 1 );
341 d->mMonthEvents = db->getEffectiveEvents( dtStart, 336 d->mMonthEvents = db->getEffectiveEvents( dtStart,
342 QDate( year, month, 337 QDate( year, month,
343 dtStart.daysInMonth() ) ); 338 dtStart.daysInMonth() ) );
344 QValueListIterator<EffectiveEvent> it = d->mMonthEvents.begin(); 339 QValueListIterator<EffectiveEvent> it = d->mMonthEvents.begin();
345 // 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
346 // 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...
347 // clear all the items... 342 // clear all the items...
348 while ( it != d->mMonthEvents.end() ) { 343 while ( it != d->mMonthEvents.end() ) {
349 QValueList<EffectiveEvent> dayEvent; 344 QValueList<EffectiveEvent> dayEvent;
350 EffectiveEvent e = *it; 345 EffectiveEvent e = *it;
351 ++it; 346 ++it;
352 dayEvent.append( e ); 347 dayEvent.append( e );
353 while ( it != d->mMonthEvents.end() 348 while ( it != d->mMonthEvents.end()
354 && e.date() == (*it).date() ) { 349 && e.date() == (*it).date() ) {
355 dayEvent.append( *it ); 350 dayEvent.append( *it );
356 ++it; 351 ++it;
357 } 352 }
358 int row, col; 353 int row, col;
359 findDay( e.date().day(), row, col ); 354 findDay( e.date().day(), row, col );
360 DayItemMonth* w = static_cast<DayItemMonth*>( item( row, col ) ); 355 DayItemMonth* w = static_cast<DayItemMonth*>( item( row, col ) );
361 w->setEvents( dayEvent ); 356 w->setEvents( dayEvent );
362 updateCell( row, col ); 357 updateCell( row, col );
363 dayEvent.clear(); 358 dayEvent.clear();
364 } 359 }
365} 360}
366 361
367 362
368void DateBookMonthTable::setupLabels() 363void DateBookMonthTable::setupLabels()
369{ 364{
370 for ( int i = 0; i < 7; ++i ) { 365 for ( int i = 0; i < 7; ++i ) {
371 // horizontalHeader()->resizeSection( i, 30 ); 366 // horizontalHeader()->resizeSection( i, 30 );
372 // setColumnStretchable( i, TRUE ); 367 // setColumnStretchable( i, TRUE );
373 if ( d->onMonday ) 368 if ( d->onMonday )
374 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i + 1 ) ); 369 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i + 1 ) );
375 else { 370 else {
376 if ( i == 0 ) 371 if ( i == 0 )
377 horizontalHeader()->setLabel( i, Calendar::nameOfDay( 7 ) ); 372 horizontalHeader()->setLabel( i, Calendar::nameOfDay( 7 ) );
378 else 373 else
379 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i ) ); 374 horizontalHeader()->setLabel( i, Calendar::nameOfDay( i ) );
380 } 375 }
381 } 376 }
382} 377}
383 378
384 379
385//--------------------------------------------------------------------------- 380//---------------------------------------------------------------------------
386 381
387DateBookMonth::DateBookMonth( QWidget *parent, const char *name, bool ac, 382DateBookMonth::DateBookMonth( QWidget *parent, const char *name, bool ac,
388 DateBookDB *data ) 383 DateBookDB *data )
389 : QVBox( parent, name ), 384 : QVBox( parent, name ),
390 autoClose( ac ) 385 autoClose( ac )
391{ 386{
392 setFocusPolicy(StrongFocus); 387 setFocusPolicy(StrongFocus);
393 year = QDate::currentDate().year(); 388 year = QDate::currentDate().year();
394 month = QDate::currentDate().month(); 389 month = QDate::currentDate().month();
395 day = QDate::currentDate().day(); 390 day = QDate::currentDate().day();
396 header = new DateBookMonthHeader( this, "DateBookMonthHeader" ); 391 header = new DateBookMonthHeader( this, "DateBookMonthHeader" );
397 table = new DateBookMonthTable( this, "DateBookMonthTable", data ); 392 table = new DateBookMonthTable( this, "DateBookMonthTable", data );
398 header->setDate( year, month ); 393 header->setDate( year, month );
399 table->setDate( year, month, QDate::currentDate().day() ); 394 table->setDate( year, month, QDate::currentDate().day() );
400 header->setFocusPolicy(NoFocus); 395 header->setFocusPolicy(NoFocus);
401 table->setFocusPolicy(NoFocus); 396 table->setFocusPolicy(NoFocus);
402 connect( header, SIGNAL( dateChanged( int, int ) ), 397 connect( header, SIGNAL( dateChanged( int, int ) ),
403 this, SLOT( setDate( int, int ) ) ); 398 this, SLOT( setDate( int, int ) ) );
404 connect( table, SIGNAL( dateClicked( int, int, int ) ), 399 connect( table, SIGNAL( dateClicked( int, int, int ) ),
405 this, SLOT( finalDate(int, int, int) ) ); 400 this, SLOT( finalDate(int, int, int) ) );
406 connect( qApp, SIGNAL(weekChanged(bool)), this, 401 connect( qApp, SIGNAL(weekChanged(bool)), this,
407 SLOT(slotWeekChange(bool)) ); 402 SLOT(slotWeekChange(bool)) );
408 table->setFocus(); 403 table->setFocus();
409} 404}
410 405
411DateBookMonth::~DateBookMonth() 406DateBookMonth::~DateBookMonth()
412{ 407{
413 408
414} 409}
415 410
416void DateBookMonth::setDate( int y, int m ) 411void DateBookMonth::setDate( int y, int m )
417{ 412{
418 /* only change the date if this is a different date, 413 /* only change the date if this is a different date,
419 * other wise we may mistakenly overide the day */ 414 * other wise we may mistakenly overide the day */
420 if ( (y != year) || (m != month) ) { 415 if ( (y != year) || (m != month) ) {
421 year = y; 416 year = y;
422 month = m; 417 month = m;
423 QDate nd( y, m, 1 ); 418 QDate nd( y, m, 1 );
424 if ( nd.daysInMonth() < day ) 419 if ( nd.daysInMonth() < day )
425 day = nd.daysInMonth(); 420 day = nd.daysInMonth();
426 table->setDate( year, month, day ); 421 table->setDate( year, month, day );
427 } 422 }
428} 423}
429 424
430void DateBookMonth::setDate( int y, int m, int d ) 425void DateBookMonth::setDate( int y, int m, int d )
431{ 426{
432 header->setDate( y, m); 427 header->setDate( y, m);
433 table->setDate( y, m, d); 428 table->setDate( y, m, d);
434 year = y; 429 year = y;
435 month = m; 430 month = m;
436 day = d; 431 day = d;
437} 432}
438 433
439/* called when we wish to close or pass back the date */ 434/* called when we wish to close or pass back the date */
440void DateBookMonth::finalDate(int y, int m, int d) 435void DateBookMonth::finalDate(int y, int m, int d)
441{ 436{
442 setDate( y, m, d ); 437 setDate( y, m, d );
443 438
444 emit dateClicked(y, m, d); 439 emit dateClicked(y, m, d);
445 // emit dateClicked(QDate(y, m, d).toString()); 440 // emit dateClicked(QDate(y, m, d).toString());
446 441
447 if ( autoClose && parentWidget() ) 442 if ( autoClose && parentWidget() )
448 parentWidget()->close(); 443 parentWidget()->close();
449} 444}
450 445
451void DateBookMonth::setDate( QDate d) 446void DateBookMonth::setDate( QDate d)
452{ 447{
453 setDate(d.year(), d.month(), d.day()); 448 setDate(d.year(), d.month(), d.day());
454} 449}
455 450
456void DateBookMonth::redraw() 451void DateBookMonth::redraw()
457{ 452{
458 table->setDate( year, month, day ); 453 table->setDate( year, month, day );
459 table->redraw(); 454 table->redraw();
460} 455}
461 456
462QDate DateBookMonth::selectedDate() const 457QDate DateBookMonth::selectedDate() const
463{ 458{
464 if ( !table ) 459 if ( !table )
465 return QDate::currentDate(); 460 return QDate::currentDate();
466 int y, m, d; 461 int y, m, d;
467 table->getDate( y, m, d ); 462 table->getDate( y, m, d );
468 return QDate( y, m, d ); 463 return QDate( y, m, d );
469} 464}
470 465
471void DateBookMonth::slotWeekChange( bool startOnMonday ) 466void DateBookMonth::slotWeekChange( bool startOnMonday )
472{ 467{
473 table->setWeekStart( startOnMonday ); 468 table->setWeekStart( startOnMonday );
474} 469}
475 470
476void DateBookMonth::keyPressEvent( QKeyEvent *e ) 471void DateBookMonth::keyPressEvent( QKeyEvent *e )
477{ 472{
478 switch(e->key()) { 473 switch(e->key()) {
479 case Key_Up: 474 case Key_Up:
480 setDate(QDate(year, month, day).addDays(-7)); 475 setDate(QDate(year, month, day).addDays(-7));
481 break; 476 break;
482 case Key_Down: 477 case Key_Down:
483 setDate(QDate(year, month, day).addDays(7)); 478 setDate(QDate(year, month, day).addDays(7));
484 break; 479 break;
485 case Key_Left: 480 case Key_Left:
486 setDate(QDate(year, month, day).addDays(-1)); 481 setDate(QDate(year, month, day).addDays(-1));
487 break; 482 break;
488 case Key_Right: 483 case Key_Right:
489 setDate(QDate(year, month, day).addDays(1)); 484 setDate(QDate(year, month, day).addDays(1));
490 break; 485 break;
491 case Key_Space: 486 case Key_Space:
492 qWarning("space"); 487 qWarning("space");
493 emit dateClicked(year, month, day); 488 emit dateClicked(year, month, day);
494 if ( autoClose && parentWidget() ) 489 if ( autoClose && parentWidget() )
495 parentWidget()->close(); 490 parentWidget()->close();
496 break; 491 break;
497 default: 492 default:
498 qWarning("ignore"); 493 qWarning("ignore");
499 e->ignore(); 494 e->ignore();
500 break; 495 break;
501 } 496 }
502} 497}
503 498
504//--------------------------------------------------------------------------- 499//---------------------------------------------------------------------------
505class DayItemMonthPrivate 500class DayItemMonthPrivate
506{ 501{
507public: 502public:
508 DayItemMonthPrivate() {}; 503 DayItemMonthPrivate() {};
509 ~DayItemMonthPrivate() { mDayEvents.clear(); }; 504 ~DayItemMonthPrivate() { mDayEvents.clear(); };
510 QValueList<EffectiveEvent> mDayEvents; 505 QValueList<EffectiveEvent> mDayEvents;
511}; 506};
512 507
513DayItemMonth::DayItemMonth( QTable *table, EditType et, const QString &t ) 508DayItemMonth::DayItemMonth( QTable *table, EditType et, const QString &t )
514 : QTableItem( table, et, t ) 509 : QTableItem( table, et, t )
515{ 510{
516 d = new DayItemMonthPrivate(); 511 d = new DayItemMonthPrivate();
517} 512}
518 513
519DayItemMonth::~DayItemMonth() 514DayItemMonth::~DayItemMonth()
520{ 515{
521 daysEvents.clear(); 516 daysEvents.clear();
522 delete d; 517 delete d;
523} 518}
524 519
525void DayItemMonth::setEvents( const QValueList<EffectiveEvent> &effEv ) 520void DayItemMonth::setEvents( const QValueList<EffectiveEvent> &effEv )
526{ 521{
527 d->mDayEvents = effEv; 522 d->mDayEvents = effEv;
528} 523}
529 524
530void DayItemMonth::clearEffEvents() 525void DayItemMonth::clearEffEvents()
531{ 526{
532 d->mDayEvents.clear(); 527 d->mDayEvents.clear();
533} 528}
534 529
535void DayItemMonth::paint( QPainter *p, const QColorGroup &cg, 530void DayItemMonth::paint( QPainter *p, const QColorGroup &cg,
536 const QRect &cr, bool selected ) 531 const QRect &cr, bool selected )
537{ 532{
538 p->save(); 533 p->save();
539 534
540 QColorGroup g( cg ); 535 QColorGroup g( cg );
541 g.setBrush( QColorGroup::Base, back ); 536 g.setBrush( QColorGroup::Base, back );
542 g.setColor( QColorGroup::Text, forg ); 537 g.setColor( QColorGroup::Text, forg );
543 if ( selected ) 538 if ( selected )
544 p->setPen( g.highlightedText() ); 539 p->setPen( g.highlightedText() );
545 else 540 else
546 p->setPen( g.text() ); 541 p->setPen( g.text() );
547 542
548 QValueStack<int> normalLine; 543 QValueStack<int> normalLine;
549 QValueStack<int> repeatLine; 544 QValueStack<int> repeatLine;
550 QValueStack<int> travelLine; 545 QValueStack<int> travelLine;
551 546
552 bool normalAllDay = FALSE; 547 bool normalAllDay = FALSE;
553 bool repeatAllDay = FALSE; 548 bool repeatAllDay = FALSE;
554 bool travelAllDay = FALSE; 549 bool travelAllDay = FALSE;
555 550
556 QValueListIterator<EffectiveEvent> itDays = d->mDayEvents.begin(); 551 QValueListIterator<EffectiveEvent> itDays = d->mDayEvents.begin();
557 552
558 for ( ; itDays != d->mDayEvents.end(); ++itDays ) { 553 for ( ; itDays != d->mDayEvents.end(); ++itDays ) {
559 int w = cr.width(); 554 int w = cr.width();
560 Event ev = (*itDays).event(); 555 Event ev = (*itDays).event();
561 556
562 int f = (*itDays).start().hour(); // assume Effective event 557 int f = (*itDays).start().hour(); // assume Effective event
563 int t = (*itDays).end().hour(); // is truncated. 558 int t = (*itDays).end().hour(); // is truncated.
564 559
565 if (ev.isAllDay()) { 560 if (ev.isAllDay()) {
566 if (!ev.hasRepeat()) 561 if (!ev.hasRepeat())
567 normalAllDay = TRUE; 562 normalAllDay = TRUE;
568 else 563 else
569 repeatAllDay = TRUE; 564 repeatAllDay = TRUE;
570 } else { 565 } else {
571 int sLine, eLine; 566 int sLine, eLine;
572 if (f == 0) 567 if (f == 0)
573 sLine = 0; 568 sLine = 0;
574 else if (f < 8 ) 569 else if (f < 8 )
575 sLine = 1; 570 sLine = 1;
576 else if (f >= 17) 571 else if (f >= 17)
577 sLine = w - 4; 572 sLine = w - 4;
578 else { 573 else {
579 sLine = (f - 8) * (w - 8); 574 sLine = (f - 8) * (w - 8);
580 if (sLine) 575 if (sLine)
581 sLine /= 8; 576 sLine /= 8;
582 sLine += 4; 577 sLine += 4;
583 } 578 }
584 if (t == 23) 579 if (t == 23)
585 eLine = w; 580 eLine = w;
586 else if (t < 8) 581 else if (t < 8)
587 eLine = 4; 582 eLine = 4;
588 else if (t >= 17) 583 else if (t >= 17)
589 eLine = w - 1; 584 eLine = w - 1;
590 else { 585 else {
591 eLine = (t - 8) * (w - 8); 586 eLine = (t - 8) * (w - 8);
592 if (eLine) 587 if (eLine)
593 eLine /= 8; 588 eLine /= 8;
594 eLine += 4; 589 eLine += 4;
595 } 590 }
596 if (!ev.hasRepeat()) { 591 if (!ev.hasRepeat()) {
597 normalLine.push(sLine); 592 normalLine.push(sLine);
598 normalLine.push(eLine); 593 normalLine.push(eLine);
599 } else { 594 } else {
600 repeatLine.push(sLine); 595 repeatLine.push(sLine);
601 repeatLine.push(eLine); 596 repeatLine.push(eLine);
602 } 597 }
603 } 598 }
604 } 599 }
605 600
606 // draw the background 601 // draw the background
607 if (normalAllDay || repeatAllDay || travelAllDay) { 602 if (normalAllDay || repeatAllDay || travelAllDay) {
608 p->save(); 603 p->save();
609 604
610 if (normalAllDay) 605 if (normalAllDay)
611 if (repeatAllDay) { 606 if (repeatAllDay) {
612 p->fillRect( 0, 0, cr.width(), cr.height() / 2, 607 p->fillRect( 0, 0, cr.width(), cr.height() / 2,
613 colorNormalLight ); 608 colorNormalLight );
614 p->fillRect( 0, cr.height() / 2, cr.width(), cr.height() / 2, 609 p->fillRect( 0, cr.height() / 2, cr.width(), cr.height() / 2,
615 colorRepeatLight ); 610 colorRepeatLight );
616 } else 611 } else
617 p->fillRect( 0, 0, cr.width(), cr.height(), 612 p->fillRect( 0, 0, cr.width(), cr.height(),
618 colorNormalLight ); 613 colorNormalLight );
619 else if (repeatAllDay) 614 else if (repeatAllDay)
620 p->fillRect( 0, 0, cr.width(), cr.height(), 615 p->fillRect( 0, 0, cr.width(), cr.height(),
621 colorRepeatLight ); 616 colorRepeatLight );
622 } else { 617 } else {
623 p->fillRect( 0, 0, cr.width(), 618 p->fillRect( 0, 0, cr.width(),
624 cr.height(), selected 619 cr.height(), selected
625 ? g.brush( QColorGroup::Highlight ) 620 ? g.brush( QColorGroup::Highlight )
626 : g.brush( QColorGroup::Base ) ); 621 : g.brush( QColorGroup::Base ) );
627 } 622 }
628 623
629 // The lines 624 // The lines
630 // now for the lines. 625 // now for the lines.
631 int h = 5; 626 int h = 5;
632 int y = cr.height() / 2 - h; 627 int y = cr.height() / 2 - h;
633 628
634 while(normalLine.count() >= 2) { 629 while(normalLine.count() >= 2) {
635 int x2 = normalLine.pop(); 630 int x2 = normalLine.pop();
636 int x1 = normalLine.pop(); 631 int x1 = normalLine.pop();
637 if (x2 < x1 + 2) 632 if (x2 < x1 + 2)
638 x2 = x1 + 2; 633 x2 = x1 + 2;
639 p->fillRect(x1, y, x2 - x1, h, colorNormal); 634 p->fillRect(x1, y, x2 - x1, h, colorNormal);
640 } 635 }
641 636
642 y += h; 637 y += h;
643 638
644 while(repeatLine.count() >= 2) { 639 while(repeatLine.count() >= 2) {
645 int x2 = repeatLine.pop(); 640 int x2 = repeatLine.pop();
646 int x1 = repeatLine.pop(); 641 int x1 = repeatLine.pop();
647 if (x2 < x1 + 2) 642 if (x2 < x1 + 2)
648 x2 = x1 + 2; 643 x2 = x1 + 2;
649 p->fillRect(x1, y, x2 - x1, h, colorRepeat); 644 p->fillRect(x1, y, x2 - x1, h, colorRepeat);
650 } 645 }
651 646
652 647
653 // Finally, draw the number. 648 // Finally, draw the number.
654 QFont f = p->font(); 649 QFont f = p->font();
655 f.setPointSize( ( f.pointSize() / 3 ) * 2 ); 650 f.setPointSize( ( f.pointSize() / 3 ) * 2 );
656 p->setFont( f ); 651 p->setFont( f );
657 QFontMetrics fm( f ); 652 QFontMetrics fm( f );
658 p->drawText( 1, 1 + fm.ascent(), QString::number( day() ) ); 653 p->drawText( 1, 1 + fm.ascent(), QString::number( day() ) );
659 654
660 p->restore(); 655 p->restore();
661} 656}
662 657
663 658
664 659
665void DayItemMonth::setType( Calendar::Day::Type t ) 660void DayItemMonth::setType( Calendar::Day::Type t )
666{ 661{
667 switch ( t ) { 662 switch ( t ) {
668 case Calendar::Day::PrevMonth: 663 case Calendar::Day::PrevMonth:
669 case Calendar::Day::NextMonth: 664 case Calendar::Day::NextMonth:
670 back = QBrush( QColor( 224, 224, 224 ) ); 665 back = QBrush( QColor( 224, 224, 224 ) );
671 forg = black; 666 forg = black;
672 break; 667 break;
673 case Calendar::Day::ThisMonth: 668 case Calendar::Day::ThisMonth:
674 back = QBrush( white ); 669 back = QBrush( white );
675 forg = black; 670 forg = black;
676 break; 671 break;
677 } 672 }
678 typ = t; 673 typ = t;
679} 674}
680 675
681 676
682 677
683DateButton::DateButton( bool longDate, QWidget *parent, const char * name ) 678DateButton::DateButton( bool longDate, QWidget *parent, const char * name )
684 :QPushButton( parent, name ) 679 :QPushButton( parent, name )
685{ 680{
686 longFormat = longDate; 681 longFormat = longDate;
687 df = DateFormat('/', DateFormat::MonthDayYear, DateFormat::MonthDayYear); 682 df = DateFormat('/', DateFormat::MonthDayYear, DateFormat::MonthDayYear);
688 setDate( QDate::currentDate() ); 683 setDate( QDate::currentDate() );
689 684
690 connect(this,SIGNAL(pressed()),this,SLOT(pickDate())); 685 connect(this,SIGNAL(pressed()),this,SLOT(pickDate()));
691 686
692 687
693} 688}
694 689
695 690
696void DateButton::pickDate() 691void DateButton::pickDate()
697{ 692{
698 static QPopupMenu *m1 = 0; 693 static QPopupMenu *m1 = 0;
699 static DateBookMonth *picker = 0; 694 static DateBookMonth *picker = 0;
700 if ( !m1 ) { 695 if ( !m1 ) {
701 m1 = new QPopupMenu( this ); 696 m1 = new QPopupMenu( this );
702 picker = new DateBookMonth( m1, 0, TRUE ); 697 picker = new DateBookMonth( m1, 0, TRUE );
703 m1->insertItem( picker ); 698 m1->insertItem( picker );
704 connect( picker, SIGNAL( dateClicked( int, int, int ) ), 699 connect( picker, SIGNAL( dateClicked( int, int, int ) ),
705 this, SLOT( setDate( int, int, int ) ) ); 700 this, SLOT( setDate( int, int, int ) ) );
706 connect( picker, SIGNAL( dateClicked( int, int, int ) ), 701 connect( picker, SIGNAL( dateClicked( int, int, int ) ),
707 this, SIGNAL( dateSelected( int, int, int ) ) ); 702 this, SIGNAL( dateSelected( int, int, int ) ) );
708 connect( m1, SIGNAL( aboutToHide() ), 703 connect( m1, SIGNAL( aboutToHide() ),
709 this, SLOT( gotHide() ) ); 704 this, SLOT( gotHide() ) );
710 } 705 }
711 picker->slotWeekChange( weekStartsMonday ); 706 picker->slotWeekChange( weekStartsMonday );
712 picker->setDate( currDate.year(), currDate.month(), currDate.day() ); 707 picker->setDate( currDate.year(), currDate.month(), currDate.day() );
713 m1->popup(mapToGlobal(QPoint(0,height()))); 708 m1->popup(mapToGlobal(QPoint(0,height())));
714 picker->setFocus(); 709 picker->setFocus();
715} 710}
716 711
717 712
718void DateButton::gotHide() 713void DateButton::gotHide()
719{ 714{
720 // we have to redo the button... 715 // we have to redo the button...
721 setDown( false ); 716 setDown( false );
722} 717}
723 718
724 719
725// void dateSelected( int year, int month, int day ); 720// void dateSelected( int year, int month, int day );
726 721
727void DateButton::setWeekStartsMonday( int b ) 722void DateButton::setWeekStartsMonday( int b )
728{ 723{
729 weekStartsMonday = b; 724 weekStartsMonday = b;
730} 725}
731 726
732void DateButton::setDate( int y, int m, int d ) 727void DateButton::setDate( int y, int m, int d )
733{ 728{
734 setDate( QDate( y,m,d) ); 729 setDate( QDate( y,m,d) );
735} 730}
736 731
737void DateButton::setDate( QDate d ) 732void DateButton::setDate( QDate d )
738{ 733{
739 currDate = d; 734 currDate = d;
740 setText( longFormat ? TimeString::longDateString( d, df ) : 735 setText( longFormat ? TimeString::longDateString( d, df ) :
741 TimeString::shortDate( d, df ) ); 736 TimeString::shortDate( d, df ) );
742 737
743} 738}
744 739
745void DateButton::setDateFormat( DateFormat f ) 740void DateButton::setDateFormat( DateFormat f )
746{ 741{
747 df = f; 742 df = f;
748 setDate( currDate ); 743 setDate( currDate );
749} 744}
750 745
751bool DateButton::customWhatsThis() const 746bool DateButton::customWhatsThis() const
752{ 747{
753 return TRUE; 748 return TRUE;
754} 749}
755 750
756 751
757// this class is only here for Sharp ROM compatibility 752// this class is only here for Sharp ROM compatibility
758// I have reverse engineered this class and it seems to 753// I have reverse engineered this class and it seems to
759// work (only qtmail seems to use it) - sandman 754// work (only qtmail seems to use it) - sandman
760// DO NOT USE IT IN NEW CODE !! 755// DO NOT USE IT IN NEW CODE !!
761 756
762DateBookMonthPopup::DateBookMonthPopup ( QWidget *w ) 757DateBookMonthPopup::DateBookMonthPopup ( QWidget *w )
763 : QPopupMenu ( w ) 758 : QPopupMenu ( w )
764{ 759{
765 m_dbm = new DateBookMonth( this, 0, TRUE ); 760 m_dbm = new DateBookMonth( this, 0, TRUE );
766 insertItem( m_dbm ); 761 insertItem( m_dbm );
767} 762}
diff --git a/library/filemanager.cpp b/library/filemanager.cpp
index 408be20..1e7384e 100644
--- a/library/filemanager.cpp
+++ b/library/filemanager.cpp
@@ -1,443 +1,440 @@
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 "filemanager.h" 20#include "filemanager.h"
21#include "applnk.h" 21#include "applnk.h"
22 22
23#include <qdir.h>
24#include <qfile.h>
25#include <qfileinfo.h> 23#include <qfileinfo.h>
26#include <qtextstream.h> 24#include <qtextstream.h>
27#include <qtextcodec.h>
28 25
29#include <errno.h> 26#include <errno.h>
30#include <stdlib.h> 27#include <stdlib.h>
31#include <unistd.h> 28#include <unistd.h>
32#include <sys/stat.h> 29#include <sys/stat.h>
33#include <dirent.h> 30#include <dirent.h>
34#ifdef Q_OS_MACX 31#ifdef Q_OS_MACX
35// MacOS X does not have sendfile.. :( 32// MacOS X does not have sendfile.. :(
36// But maybe in the future.. !? 33// But maybe in the future.. !?
37# ifdef SENDFILE 34# ifdef SENDFILE
38# include <sys/types.h> 35# include <sys/types.h>
39# include <sys/socket.h> 36# include <sys/socket.h>
40# endif 37# endif
41#else 38#else
42# include <sys/sendfile.h> 39# include <sys/sendfile.h>
43#endif /* Q_OS_MACX */ 40#endif /* Q_OS_MACX */
44#include <fcntl.h> 41#include <fcntl.h>
45 42
46/*! 43/*!
47 \class FileManager 44 \class FileManager
48 \brief The FileManager class assists with AppLnk input/output. 45 \brief The FileManager class assists with AppLnk input/output.
49*/ 46*/
50 47
51/*! 48/*!
52 Constructs a FileManager. 49 Constructs a FileManager.
53*/ 50*/
54FileManager::FileManager() 51FileManager::FileManager()
55{ 52{
56} 53}
57 54
58/*! 55/*!
59 Destroys a FileManager. 56 Destroys a FileManager.
60*/ 57*/
61FileManager::~FileManager() 58FileManager::~FileManager()
62{ 59{
63 60
64} 61}
65 62
66/*! 63/*!
67 Saves \a data as the document specified by \a f. 64 Saves \a data as the document specified by \a f.
68 65
69 Returns whether the operation succeeded. 66 Returns whether the operation succeeded.
70*/ 67*/
71bool FileManager::saveFile( const DocLnk &f, const QByteArray &data ) 68bool FileManager::saveFile( const DocLnk &f, const QByteArray &data )
72{ 69{
73 QString fn = f.file() + ".new"; 70 QString fn = f.file() + ".new";
74 ensurePathExists( fn ); 71 ensurePathExists( fn );
75 QFile fl( fn ); 72 QFile fl( fn );
76 if ( !fl.open( IO_WriteOnly|IO_Raw ) ) { 73 if ( !fl.open( IO_WriteOnly|IO_Raw ) ) {
77 qWarning("open failed"); 74 qWarning("open failed");
78 return FALSE; 75 return FALSE;
79 } 76 }
80 int total_written = fl.writeBlock( data ); 77 int total_written = fl.writeBlock( data );
81 fl.close(); 78 fl.close();
82 if ( total_written != int(data.size()) || !f.writeLink() ) { 79 if ( total_written != int(data.size()) || !f.writeLink() ) {
83 QFile::remove( fn ); 80 QFile::remove( fn );
84 return FALSE; 81 return FALSE;
85 } 82 }
86 qDebug("total written %d out of %d", total_written, data.size()); 83 qDebug("total written %d out of %d", total_written, data.size());
87 // else rename the file... 84 // else rename the file...
88 if ( !renameFile( fn.latin1(), f.file().latin1() ) ) { 85 if ( !renameFile( fn.latin1(), f.file().latin1() ) ) {
89 qWarning( "problem renaming file %s to %s, errno: %d", fn.latin1(), 86 qWarning( "problem renaming file %s to %s, errno: %d", fn.latin1(),
90 f.file().latin1(), errno ); 87 f.file().latin1(), errno );
91 // remove the file... 88 // remove the file...
92 } 89 }
93 return TRUE; 90 return TRUE;
94} 91}
95 92
96/*! 93/*!
97 Saves \a text as the document specified by \a f. 94 Saves \a text as the document specified by \a f.
98 95
99 The text is saved in UTF8 format. 96 The text is saved in UTF8 format.
100 97
101 Returns whether the operation succeeded. 98 Returns whether the operation succeeded.
102*/ 99*/
103bool FileManager::saveFile( const DocLnk &f, const QString &text ) 100bool FileManager::saveFile( const DocLnk &f, const QString &text )
104{ 101{
105 QString fn = f.file() + ".new"; 102 QString fn = f.file() + ".new";
106 ensurePathExists( fn ); 103 ensurePathExists( fn );
107 QFile fl( fn ); 104 QFile fl( fn );
108 if ( !fl.open( IO_WriteOnly|IO_Raw ) ) { 105 if ( !fl.open( IO_WriteOnly|IO_Raw ) ) {
109 qWarning("open failed"); 106 qWarning("open failed");
110 return FALSE; 107 return FALSE;
111 } 108 }
112 109
113 QCString cstr = text.utf8(); 110 QCString cstr = text.utf8();
114 int total_written; 111 int total_written;
115 total_written = fl.writeBlock( cstr.data(), cstr.length() ); 112 total_written = fl.writeBlock( cstr.data(), cstr.length() );
116 fl.close(); 113 fl.close();
117 if ( total_written != int(cstr.length()) || !f.writeLink() ) { 114 if ( total_written != int(cstr.length()) || !f.writeLink() ) {
118 QFile::remove( fn ); 115 QFile::remove( fn );
119 return FALSE; 116 return FALSE;
120 } 117 }
121 // okay now rename the file.. 118 // okay now rename the file..
122 if ( !renameFile( fn.latin1(), f.file().latin1() ) ) { 119 if ( !renameFile( fn.latin1(), f.file().latin1() ) ) {
123 qWarning( "problem renaming file %s to %s, errno: %d", fn.latin1(), 120 qWarning( "problem renaming file %s to %s, errno: %d", fn.latin1(),
124 f.file().latin1(), errno ); 121 f.file().latin1(), errno );
125 122
126 } 123 }
127 return TRUE; 124 return TRUE;
128} 125}
129 126
130 127
131/*! 128/*!
132 Loads \a text from the document specified by \a f. 129 Loads \a text from the document specified by \a f.
133 130
134 The text is required to be in UTF8 format. 131 The text is required to be in UTF8 format.
135 132
136 Returns whether the operation succeeded. 133 Returns whether the operation succeeded.
137*/ 134*/
138bool FileManager::loadFile( const DocLnk &f, QString &text ) 135bool FileManager::loadFile( const DocLnk &f, QString &text )
139{ 136{
140 QString fn = f.file(); 137 QString fn = f.file();
141 QFile fl( fn ); 138 QFile fl( fn );
142 if ( !fl.open( IO_ReadOnly ) ) 139 if ( !fl.open( IO_ReadOnly ) )
143 return FALSE; 140 return FALSE;
144 QTextStream ts( &fl ); 141 QTextStream ts( &fl );
145#if QT_VERSION <= 230 && defined(QT_NO_CODECS) 142#if QT_VERSION <= 230 && defined(QT_NO_CODECS)
146 // The below should work, but doesn't in Qt 2.3.0 143 // The below should work, but doesn't in Qt 2.3.0
147 ts.setCodec( QTextCodec::codecForMib( 106 ) ); 144 ts.setCodec( QTextCodec::codecForMib( 106 ) );
148#else 145#else
149 ts.setEncoding( QTextStream::UnicodeUTF8 ); 146 ts.setEncoding( QTextStream::UnicodeUTF8 );
150#endif 147#endif
151 text = ts.read(); 148 text = ts.read();
152 fl.close(); 149 fl.close();
153 return TRUE; 150 return TRUE;
154} 151}
155 152
156 153
157/*! 154/*!
158 Loads \a ba from the document specified by \a f. 155 Loads \a ba from the document specified by \a f.
159 156
160 Returns whether the operation succeeded. 157 Returns whether the operation succeeded.
161*/ 158*/
162bool FileManager::loadFile( const DocLnk &f, QByteArray &ba ) 159bool FileManager::loadFile( const DocLnk &f, QByteArray &ba )
163{ 160{
164 QString fn = f.file(); 161 QString fn = f.file();
165 QFile fl( fn ); 162 QFile fl( fn );
166 if ( !fl.open( IO_ReadOnly ) ) 163 if ( !fl.open( IO_ReadOnly ) )
167 return FALSE; 164 return FALSE;
168 ba.resize( fl.size() ); 165 ba.resize( fl.size() );
169 if ( fl.size() > 0 ) 166 if ( fl.size() > 0 )
170 fl.readBlock( ba.data(), fl.size() ); 167 fl.readBlock( ba.data(), fl.size() );
171 fl.close(); 168 fl.close();
172 return TRUE; 169 return TRUE;
173} 170}
174 171
175/*! 172/*!
176 Copies the document specified by \a src to the document specified 173 Copies the document specified by \a src to the document specified
177 by \a dest. 174 by \a dest.
178 175
179 Returns whether the operation succeeded. 176 Returns whether the operation succeeded.
180*/ 177*/
181bool FileManager::copyFile( const AppLnk &src, const AppLnk &dest ) 178bool FileManager::copyFile( const AppLnk &src, const AppLnk &dest )
182{ 179{
183 QFile sf( src.file() ); 180 QFile sf( src.file() );
184 if ( !sf.open( IO_ReadOnly ) ) 181 if ( !sf.open( IO_ReadOnly ) )
185 return FALSE; 182 return FALSE;
186 183
187 QString fn = dest.file() + ".new"; 184 QString fn = dest.file() + ".new";
188 ensurePathExists( fn ); 185 ensurePathExists( fn );
189 QFile df( fn ); 186 QFile df( fn );
190 if ( !df.open( IO_WriteOnly|IO_Raw ) ) 187 if ( !df.open( IO_WriteOnly|IO_Raw ) )
191 return FALSE; 188 return FALSE;
192 189
193 const int bufsize = 16384; 190 const int bufsize = 16384;
194 char buffer[bufsize]; 191 char buffer[bufsize];
195 bool ok = TRUE; 192 bool ok = TRUE;
196 int bytesRead = 0; 193 int bytesRead = 0;
197 while ( ok && !sf.atEnd() ) { 194 while ( ok && !sf.atEnd() ) {
198 bytesRead = sf.readBlock( buffer, bufsize ); 195 bytesRead = sf.readBlock( buffer, bufsize );
199 if ( bytesRead < 0 ) 196 if ( bytesRead < 0 )
200 ok = FALSE; 197 ok = FALSE;
201 while ( ok && bytesRead > 0 ) { 198 while ( ok && bytesRead > 0 ) {
202 int bytesWritten = df.writeBlock( buffer, bytesRead ); 199 int bytesWritten = df.writeBlock( buffer, bytesRead );
203 if ( bytesWritten < 0 ) 200 if ( bytesWritten < 0 )
204 ok = FALSE; 201 ok = FALSE;
205 else 202 else
206 bytesRead -= bytesWritten; 203 bytesRead -= bytesWritten;
207 } 204 }
208 } 205 }
209 206
210 if ( ok ) 207 if ( ok )
211 ok = dest.writeLink(); 208 ok = dest.writeLink();
212 209
213 if ( ok ) { 210 if ( ok ) {
214 // okay now rename the file... 211 // okay now rename the file...
215 if ( !renameFile( fn.latin1(), dest.file().latin1() ) ) { 212 if ( !renameFile( fn.latin1(), dest.file().latin1() ) ) {
216 qWarning( "problem renaming file %s to %s, errno: %d", fn.latin1(), 213 qWarning( "problem renaming file %s to %s, errno: %d", fn.latin1(),
217 dest.file().latin1(), errno ); 214 dest.file().latin1(), errno );
218 // remove the tmp file, otherwise, it will just lay around... 215 // remove the tmp file, otherwise, it will just lay around...
219 QFile::remove( fn.latin1() ); 216 QFile::remove( fn.latin1() );
220 } 217 }
221 } else { 218 } else {
222 QFile::remove( fn.latin1() ); 219 QFile::remove( fn.latin1() );
223 } 220 }
224 221
225 return ok; 222 return ok;
226} 223}
227 224
228bool FileManager::copyFile( const QString & src, const QString & dest ) { 225bool FileManager::copyFile( const QString & src, const QString & dest ) {
229 bool success = true; 226 bool success = true;
230 struct stat status; 227 struct stat status;
231 int read_fd=0; 228 int read_fd=0;
232 int write_fd=0; 229 int write_fd=0;
233 struct stat stat_buf; 230 struct stat stat_buf;
234 off_t offset = 0; 231 off_t offset = 0;
235 QFile srcFile(src); 232 QFile srcFile(src);
236 QFile destFile(dest); 233 QFile destFile(dest);
237 234
238 if(!srcFile.open( IO_ReadOnly|IO_Raw)) { 235 if(!srcFile.open( IO_ReadOnly|IO_Raw)) {
239 return success = false; 236 return success = false;
240 } 237 }
241 read_fd = srcFile.handle(); 238 read_fd = srcFile.handle();
242 if(read_fd != -1) { 239 if(read_fd != -1) {
243 fstat (read_fd, &stat_buf); 240 fstat (read_fd, &stat_buf);
244 if( !destFile.open( IO_WriteOnly|IO_Raw ) ) 241 if( !destFile.open( IO_WriteOnly|IO_Raw ) )
245 return success = false; 242 return success = false;
246 write_fd = destFile.handle(); 243 write_fd = destFile.handle();
247 if(write_fd != -1) { 244 if(write_fd != -1) {
248 int err=0; 245 int err=0;
249 QString msg; 246 QString msg;
250#ifdef Q_OS_MACX 247#ifdef Q_OS_MACX
251#ifdef SENDFILE 248#ifdef SENDFILE
252 /* FreeBSD does support a different kind of 249 /* FreeBSD does support a different kind of
253 * sendfile. (eilers) 250 * sendfile. (eilers)
254 * I took this from Very Secure FTPd 251 * I took this from Very Secure FTPd
255 * Licence: GPL 252 * Licence: GPL
256 * Author: Chris Evans 253 * Author: Chris Evans
257 * sysdeputil.c 254 * sysdeputil.c
258 */ 255 */
259 /* XXX - start_pos will truncate on 32-bit machines - can we 256 /* XXX - start_pos will truncate on 32-bit machines - can we
260 * say "start from current pos"? 257 * say "start from current pos"?
261 */ 258 */
262 off_t written = 0; 259 off_t written = 0;
263 int retval = 0; 260 int retval = 0;
264 retval = sendfile(read_fd, write_fd, offset, stat_buf.st_size, NULL, 261 retval = sendfile(read_fd, write_fd, offset, stat_buf.st_size, NULL,
265 &written, 0); 262 &written, 0);
266 /* Translate to Linux-like retval */ 263 /* Translate to Linux-like retval */
267 if (written > 0) 264 if (written > 0)
268 { 265 {
269 err = (int) written; 266 err = (int) written;
270 } 267 }
271#else /* SENDFILE */ 268#else /* SENDFILE */
272 err == -1; 269 err == -1;
273 msg = "FAILURE: Using unsupported function \"sendfile()\" Need Workaround !!"; 270 msg = "FAILURE: Using unsupported function \"sendfile()\" Need Workaround !!";
274 success = false; 271 success = false;
275# warning "Need workaround for sendfile!!(eilers)" 272# warning "Need workaround for sendfile!!(eilers)"
276#endif /* SENDFILE */ 273#endif /* SENDFILE */
277 274
278#else 275#else
279 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size); 276 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
280 if( err == -1) { 277 if( err == -1) {
281 switch(err) { 278 switch(err) {
282 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. "; 279 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. ";
283 case EINVAL: msg = "Descriptor is not valid or locked. "; 280 case EINVAL: msg = "Descriptor is not valid or locked. ";
284 case ENOMEM: msg = "Insufficient memory to read from in_fd."; 281 case ENOMEM: msg = "Insufficient memory to read from in_fd.";
285 case EIO: msg = "Unspecified error while reading from in_fd."; 282 case EIO: msg = "Unspecified error while reading from in_fd.";
286 }; 283 };
287 success = false; 284 success = false;
288 } 285 }
289#endif /* Q_OS_MACX */ 286#endif /* Q_OS_MACX */
290 if( !success ) 287 if( !success )
291 qWarning( msg ); 288 qWarning( msg );
292 } else { 289 } else {
293 qWarning("open write failed %s, %s",src.latin1(), dest.latin1()); 290 qWarning("open write failed %s, %s",src.latin1(), dest.latin1());
294 success = false; 291 success = false;
295 } 292 }
296 } else { 293 } else {
297 qWarning("open read failed %s, %s",src.latin1(), dest.latin1()); 294 qWarning("open read failed %s, %s",src.latin1(), dest.latin1());
298 success = false; 295 success = false;
299 } 296 }
300 srcFile.close(); 297 srcFile.close();
301 destFile.close(); 298 destFile.close();
302 // Set file permissions 299 // Set file permissions
303 if( stat( (const char *) src, &status ) == 0 ) { 300 if( stat( (const char *) src, &status ) == 0 ) {
304 chmod( (const char *) dest, status.st_mode ); 301 chmod( (const char *) dest, status.st_mode );
305 } 302 }
306 303
307 return success; 304 return success;
308} 305}
309 306
310 307
311bool FileManager::renameFile( const QString & src, const QString & dest ) { 308bool FileManager::renameFile( const QString & src, const QString & dest ) {
312 if(copyFile( src, dest )) { 309 if(copyFile( src, dest )) {
313 if(QFile::remove(src) ) { 310 if(QFile::remove(src) ) {
314 return true; 311 return true;
315 } 312 }
316 } 313 }
317 return false; 314 return false;
318} 315}
319 316
320/* 317/*
321bool FileManager::copyFile( const QString & src, const QString & dest ) { 318bool FileManager::copyFile( const QString & src, const QString & dest ) {
322 bool success = true; 319 bool success = true;
323 struct stat status; 320 struct stat status;
324 int read_fd=0; 321 int read_fd=0;
325 int write_fd=0; 322 int write_fd=0;
326 struct stat stat_buf; 323 struct stat stat_buf;
327 off_t offset = 0; 324 off_t offset = 0;
328 QFile srcFile(src); 325 QFile srcFile(src);
329 QFile destFile(dest); 326 QFile destFile(dest);
330 327
331 if(!srcFile.open( IO_ReadOnly|IO_Raw)) { 328 if(!srcFile.open( IO_ReadOnly|IO_Raw)) {
332 return success = false; 329 return success = false;
333 } 330 }
334 read_fd = srcFile.handle(); 331 read_fd = srcFile.handle();
335 if(read_fd != -1) { 332 if(read_fd != -1) {
336 fstat (read_fd, &stat_buf); 333 fstat (read_fd, &stat_buf);
337 if( !destFile.open( IO_WriteOnly|IO_Raw ) ) 334 if( !destFile.open( IO_WriteOnly|IO_Raw ) )
338 return success = false; 335 return success = false;
339 write_fd = destFile.handle(); 336 write_fd = destFile.handle();
340 if(write_fd != -1) { 337 if(write_fd != -1) {
341 int err=0; 338 int err=0;
342 QString msg; 339 QString msg;
343 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size); 340 err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size);
344 if( err == -1) { 341 if( err == -1) {
345 switch(err) { 342 switch(err) {
346 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. "; 343 case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. ";
347 case EINVAL: msg = "Descriptor is not valid or locked. "; 344 case EINVAL: msg = "Descriptor is not valid or locked. ";
348 case ENOMEM: msg = "Insufficient memory to read from in_fd."; 345 case ENOMEM: msg = "Insufficient memory to read from in_fd.";
349 case EIO: msg = "Unspecified error while reading from in_fd."; 346 case EIO: msg = "Unspecified error while reading from in_fd.";
350 }; 347 };
351 success = false; 348 success = false;
352 } 349 }
353 } else { 350 } else {
354 qWarning("open write failed %s, %s",src.latin1(), dest.latin1()); 351 qWarning("open write failed %s, %s",src.latin1(), dest.latin1());
355 success = false; 352 success = false;
356 } 353 }
357 } else { 354 } else {
358 qWarning("open read failed %s, %s",src.latin1(), dest.latin1()); 355 qWarning("open read failed %s, %s",src.latin1(), dest.latin1());
359 success = false; 356 success = false;
360 } 357 }
361 srcFile.close(); 358 srcFile.close();
362 destFile.close(); 359 destFile.close();
363 // Set file permissions 360 // Set file permissions
364 if( stat( (const char *) src, &status ) == 0 ) { 361 if( stat( (const char *) src, &status ) == 0 ) {
365 chmod( (const char *) dest, status.st_mode ); 362 chmod( (const char *) dest, status.st_mode );
366 } 363 }
367 364
368 return success; 365 return success;
369} 366}
370 367
371 368
372bool FileManager::renameFile( const QString & src, const QString & dest ) { 369bool FileManager::renameFile( const QString & src, const QString & dest ) {
373 if(copyFile( src, dest )) { 370 if(copyFile( src, dest )) {
374 if(QFile::remove(src) ) { 371 if(QFile::remove(src) ) {
375 return true; 372 return true;
376 } 373 }
377 } 374 }
378 return false; 375 return false;
379} 376}
380*/ 377*/
381 378
382/*! 379/*!
383 Opens the document specified by \a f as a readable QIODevice. 380 Opens the document specified by \a f as a readable QIODevice.
384 The caller must delete the return value. 381 The caller must delete the return value.
385 382
386 Returns 0 if the operation fails. 383 Returns 0 if the operation fails.
387*/ 384*/
388QIODevice* FileManager::openFile( const DocLnk& f ) 385QIODevice* FileManager::openFile( const DocLnk& f )
389{ 386{
390 QString fn = f.file(); 387 QString fn = f.file();
391 QFile* fl = new QFile( fn ); 388 QFile* fl = new QFile( fn );
392 if ( !fl->open( IO_ReadOnly ) ) { 389 if ( !fl->open( IO_ReadOnly ) ) {
393 delete fl; 390 delete fl;
394 fl = 0; 391 fl = 0;
395 } 392 }
396 return fl; 393 return fl;
397} 394}
398 395
399/*! 396/*!
400 Opens the document specified by \a f as a writable QIODevice. 397 Opens the document specified by \a f as a writable QIODevice.
401 The caller must delete the return value. 398 The caller must delete the return value.
402 399
403 Returns 0 if the operation fails. 400 Returns 0 if the operation fails.
404*/ 401*/
405QIODevice* FileManager::saveFile( const DocLnk& f ) 402QIODevice* FileManager::saveFile( const DocLnk& f )
406{ 403{
407 QString fn = f.file(); 404 QString fn = f.file();
408 ensurePathExists( fn ); 405 ensurePathExists( fn );
409 QFile* fl = new QFile( fn ); 406 QFile* fl = new QFile( fn );
410 if ( fl->open( IO_WriteOnly ) ) { 407 if ( fl->open( IO_WriteOnly ) ) {
411 f.writeLink(); 408 f.writeLink();
412 } else { 409 } else {
413 delete fl; 410 delete fl;
414 fl = 0; 411 fl = 0;
415 } 412 }
416 return fl; 413 return fl;
417} 414}
418 415
419/*! 416/*!
420 Returns whether the document specified by \a f current exists 417 Returns whether the document specified by \a f current exists
421 as a file on disk. 418 as a file on disk.
422*/ 419*/
423bool FileManager::exists( const DocLnk &f ) 420bool FileManager::exists( const DocLnk &f )
424{ 421{
425 return QFile::exists(f.file()); 422 return QFile::exists(f.file());
426} 423}
427 424
428 425
429/*! 426/*!
430 Ensures that the path \a fn exists, by creating required directories. 427 Ensures that the path \a fn exists, by creating required directories.
431 Returns TRUE if successful. 428 Returns TRUE if successful.
432*/ 429*/
433bool FileManager::ensurePathExists( const QString &fn ) 430bool FileManager::ensurePathExists( const QString &fn )
434{ 431{
435 QFileInfo fi(fn); 432 QFileInfo fi(fn);
436 fi.setFile( fi.dirPath(TRUE) ); 433 fi.setFile( fi.dirPath(TRUE) );
437 if ( !fi.exists() ) { 434 if ( !fi.exists() ) {
438 if ( system(("mkdir -p "+fi.filePath())) ) 435 if ( system(("mkdir -p "+fi.filePath())) )
439 return FALSE; 436 return FALSE;
440 } 437 }
441 438
442 return TRUE; 439 return TRUE;
443} 440}
diff --git a/library/fileselector.cpp b/library/fileselector.cpp
index 4039243..7c29aba 100644
--- a/library/fileselector.cpp
+++ b/library/fileselector.cpp
@@ -1,581 +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 "applnk.h"
31#include "storage.h" 30#include "storage.h"
32#include "qpemenubar.h" 31#include "qpemenubar.h"
33#include <qcopchannel_qws.h> 32#include <qcopchannel_qws.h>
34#include "lnkproperties.h" 33#include "lnkproperties.h"
35#include "applnk.h"
36#include <qpe/qpeapplication.h> 34#include <qpe/qpeapplication.h>
37#include "categorymenu.h" 35#include "categorymenu.h"
38#include "categoryselect.h" 36#include "categoryselect.h"
39#include "mimetype.h" 37#include "mimetype.h"
40#include <qpe/categories.h> 38#include <qpe/categories.h>
41 39
42#include <stdlib.h> 40#include <stdlib.h>
43 41
44#include <qdir.h> 42#include <qdir.h>
45#include <qwidget.h> 43#include <qwidget.h>
46#include <qpopupmenu.h> 44#include <qpopupmenu.h>
47#include <qtoolbutton.h> 45#include <qtoolbutton.h>
48#include <qpushbutton.h> 46#include <qpushbutton.h>
49#include <qheader.h> 47#include <qheader.h>
50#include <qtooltip.h> 48#include <qtooltip.h>
51#include <qwhatsthis.h> 49#include <qwhatsthis.h>
52 50
53class TypeCombo : public QComboBox 51class TypeCombo : public QComboBox
54{ 52{
55 Q_OBJECT 53 Q_OBJECT
56public: 54public:
57 TypeCombo( QWidget *parent, const char *name=0 ) 55 TypeCombo( QWidget *parent, const char *name=0 )
58 : QComboBox( parent, name ) 56 : QComboBox( parent, name )
59 { 57 {
60 connect( this, SIGNAL(activated(int)), this, SLOT(selectType(int)) ); 58 connect( this, SIGNAL(activated(int)), this, SLOT(selectType(int)) );
61 } 59 }
62 60
63 void reread( DocLnkSet &files, const QString &filter ); 61 void reread( DocLnkSet &files, const QString &filter );
64 62
65signals: 63signals:
66 void selected( const QString & ); 64 void selected( const QString & );
67 65
68protected slots: 66protected slots:
69 void selectType( int idx ) { 67 void selectType( int idx ) {
70 emit selected( typelist[idx] ); 68 emit selected( typelist[idx] );
71 } 69 }
72 70
73protected: 71protected:
74 QStringList typelist; 72 QStringList typelist;
75 QString prev; 73 QString prev;
76}; 74};
77 75
78void TypeCombo::reread( DocLnkSet &files, const QString &filter ) 76void TypeCombo::reread( DocLnkSet &files, const QString &filter )
79{ 77{
80 typelist.clear(); 78 typelist.clear();
81 QStringList filters = QStringList::split( ';', filter ); 79 QStringList filters = QStringList::split( ';', filter );
82 int pos = filter.find( '/' ); 80 int pos = filter.find( '/' );
83 //### do for each filter 81 //### do for each filter
84 if ( filters.count() == 1 && pos >= 0 && filter[pos+1] != '*' ) { 82 if ( filters.count() == 1 && pos >= 0 && filter[pos+1] != '*' ) {
85 typelist.append( filter ); 83 typelist.append( filter );
86 clear(); 84 clear();
87 QString minor = filter.mid( pos+1 ); 85 QString minor = filter.mid( pos+1 );
88 minor[0] = minor[0].upper(); 86 minor[0] = minor[0].upper();
89 insertItem( tr("%1 files").arg(minor) ); 87 insertItem( tr("%1 files").arg(minor) );
90 setCurrentItem(0); 88 setCurrentItem(0);
91 setEnabled( FALSE ); 89 setEnabled( FALSE );
92 return; 90 return;
93 } 91 }
94 92
95 QListIterator<DocLnk> dit( files.children() ); 93 QListIterator<DocLnk> dit( files.children() );
96 for ( ; dit.current(); ++dit ) { 94 for ( ; dit.current(); ++dit ) {
97 if ( !typelist.contains( (*dit)->type() ) ) 95 if ( !typelist.contains( (*dit)->type() ) )
98 typelist.append( (*dit)->type() ); 96 typelist.append( (*dit)->type() );
99 } 97 }
100 98
101 QStringList types; 99 QStringList types;
102 QStringList::ConstIterator it; 100 QStringList::ConstIterator it;
103 for (it = typelist.begin(); it!=typelist.end(); ++it) { 101 for (it = typelist.begin(); it!=typelist.end(); ++it) {
104 QString t = *it; 102 QString t = *it;
105 if ( t.left(12) == "application/" ) { 103 if ( t.left(12) == "application/" ) {
106 MimeType mt(t); 104 MimeType mt(t);
107 const AppLnk* app = mt.application(); 105 const AppLnk* app = mt.application();
108 if ( app ) 106 if ( app )
109 t = app->name(); 107 t = app->name();
110 else 108 else
111 t = t.mid(12); 109 t = t.mid(12);
112 } else { 110 } else {
113 QString major, minor; 111 QString major, minor;
114 int pos = t.find( '/' ); 112 int pos = t.find( '/' );
115 if ( pos >= 0 ) { 113 if ( pos >= 0 ) {
116 major = t.left( pos ); 114 major = t.left( pos );
117 minor = t.mid( pos+1 ); 115 minor = t.mid( pos+1 );
118 } 116 }
119 if ( minor.find( "x-" ) == 0 ) 117 if ( minor.find( "x-" ) == 0 )
120 minor = minor.mid( 2 ); 118 minor = minor.mid( 2 );
121 minor[0] = minor[0].upper(); 119 minor[0] = minor[0].upper();
122 major[0] = major[0].upper(); 120 major[0] = major[0].upper();
123 if ( filters.count() > 1 ) 121 if ( filters.count() > 1 )
124 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);
125 else 123 else
126 t = minor; 124 t = minor;
127 } 125 }
128 types += tr("%1 files").arg(t); 126 types += tr("%1 files").arg(t);
129 } 127 }
130 for (it = filters.begin(); it!=filters.end(); ++it) { 128 for (it = filters.begin(); it!=filters.end(); ++it) {
131 typelist.append( *it ); 129 typelist.append( *it );
132 int pos = (*it).find( '/' ); 130 int pos = (*it).find( '/' );
133 if ( pos >= 0 ) { 131 if ( pos >= 0 ) {
134 QString maj = (*it).left( pos ); 132 QString maj = (*it).left( pos );
135 maj[0] = maj[0].upper(); 133 maj[0] = maj[0].upper();
136 types << tr("All %1 files").arg(maj); 134 types << tr("All %1 files").arg(maj);
137 } 135 }
138 } 136 }
139 if ( filters.count() > 1 ) { 137 if ( filters.count() > 1 ) {
140 typelist.append( filter ); 138 typelist.append( filter );
141 types << tr("All files"); 139 types << tr("All files");
142 } 140 }
143 prev = currentText(); 141 prev = currentText();
144 clear(); 142 clear();
145 insertStringList(types); 143 insertStringList(types);
146 for (int i=0; i<count(); i++) { 144 for (int i=0; i<count(); i++) {
147 if ( text(i) == prev ) { 145 if ( text(i) == prev ) {
148 setCurrentItem(i); 146 setCurrentItem(i);
149 break; 147 break;
150 } 148 }
151 } 149 }
152 if ( prev.isNull() ) 150 if ( prev.isNull() )
153 setCurrentItem(count()-1); 151 setCurrentItem(count()-1);
154 setEnabled( TRUE ); 152 setEnabled( TRUE );
155} 153}
156 154
157 155
158//=========================================================================== 156//===========================================================================
159 157
160FileSelectorItem::FileSelectorItem( QListView *parent, const DocLnk &f ) 158FileSelectorItem::FileSelectorItem( QListView *parent, const DocLnk &f )
161 : QListViewItem( parent ), fl( f ) 159 : QListViewItem( parent ), fl( f )
162{ 160{
163 setText( 0, f.name() ); 161 setText( 0, f.name() );
164 setPixmap( 0, f.pixmap() ); 162 setPixmap( 0, f.pixmap() );
165} 163}
166 164
167FileSelectorItem::~FileSelectorItem() 165FileSelectorItem::~FileSelectorItem()
168{ 166{
169} 167}
170 168
171FileSelectorView::FileSelectorView( QWidget *parent, const char *name ) 169FileSelectorView::FileSelectorView( QWidget *parent, const char *name )
172 : QListView( parent, name ) 170 : QListView( parent, name )
173{ 171{
174 setAllColumnsShowFocus( TRUE ); 172 setAllColumnsShowFocus( TRUE );
175 addColumn( tr( "Name" ) ); 173 addColumn( tr( "Name" ) );
176 header()->hide(); 174 header()->hide();
177} 175}
178 176
179FileSelectorView::~FileSelectorView() 177FileSelectorView::~FileSelectorView()
180{ 178{
181} 179}
182 180
183void FileSelectorView::keyPressEvent( QKeyEvent *e ) 181void FileSelectorView::keyPressEvent( QKeyEvent *e )
184{ 182{
185 QString txt = e->text(); 183 QString txt = e->text();
186 if (e->key() == Key_Space) 184 if (e->key() == Key_Space)
187 emit returnPressed( currentItem() ); 185 emit returnPressed( currentItem() );
188 else if ( !txt.isNull() && txt[0] > ' ' && e->key() < 0x1000 ) 186 else if ( !txt.isNull() && txt[0] > ' ' && e->key() < 0x1000 )
189 e->ignore(); 187 e->ignore();
190 else 188 else
191 QListView::keyPressEvent(e); 189 QListView::keyPressEvent(e);
192} 190}
193 191
194class NewDocItem : public FileSelectorItem 192class NewDocItem : public FileSelectorItem
195{ 193{
196public: 194public:
197 NewDocItem( QListView *parent, const DocLnk &f ) 195 NewDocItem( QListView *parent, const DocLnk &f )
198 : FileSelectorItem( parent, f ) { 196 : FileSelectorItem( parent, f ) {
199 setText( 0, QObject::tr("New Document") ); 197 setText( 0, QObject::tr("New Document") );
200 QImage img( Resource::loadImage( "new" ) ); 198 QImage img( Resource::loadImage( "new" ) );
201 QPixmap pm; 199 QPixmap pm;
202 pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); 200 pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() );
203 setPixmap( 0, pm ); 201 setPixmap( 0, pm );
204 } 202 }
205 QString key ( int, bool ) const { 203 QString key ( int, bool ) const {
206 return QString("\n"); 204 return QString("\n");
207 } 205 }
208 206
209 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 ) {
210 QFont oldFont = p->font(); 208 QFont oldFont = p->font();
211 QFont newFont = p->font(); 209 QFont newFont = p->font();
212 newFont.setWeight( QFont::Bold ); 210 newFont.setWeight( QFont::Bold );
213 p->setFont( newFont ); 211 p->setFont( newFont );
214 FileSelectorItem::paintCell( p, cg, column, width, alignment ); 212 FileSelectorItem::paintCell( p, cg, column, width, alignment );
215 p->setFont( oldFont ); 213 p->setFont( oldFont );
216 } 214 }
217 215
218 int width( const QFontMetrics &fm, const QListView *v, int c ) const { 216 int width( const QFontMetrics &fm, const QListView *v, int c ) const {
219 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
220 } 218 }
221}; 219};
222 220
223//=========================================================================== 221//===========================================================================
224 222
225class FileSelectorPrivate 223class FileSelectorPrivate
226{ 224{
227public: 225public:
228 TypeCombo *typeCombo; 226 TypeCombo *typeCombo;
229 CategorySelect *catSelect; 227 CategorySelect *catSelect;
230 QValueList<QRegExp> mimeFilters; 228 QValueList<QRegExp> mimeFilters;
231 int catId; 229 int catId;
232 bool showNew; 230 bool showNew;
233 NewDocItem *newDocItem; 231 NewDocItem *newDocItem;
234 DocLnkSet files; 232 DocLnkSet files;
235 QHBox *toolbar; 233 QHBox *toolbar;
236}; 234};
237 235
238/*! 236/*!
239 \class FileSelector fileselector.h 237 \class FileSelector fileselector.h
240 \brief The FileSelector widget allows the user to select DocLnk objects. 238 \brief The FileSelector widget allows the user to select DocLnk objects.
241 239
242 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
243 is usually the first widget seen in a \link docwidget.html 241 is usually the first widget seen in a \link docwidget.html
244 document-oriented application\endlink. The developer will most often 242 document-oriented application\endlink. The developer will most often
245 create this widget in combination with a <a 243 create this widget in combination with a <a
246 href="../qt/qwidgetstack.html"> QWidgetStack</a> and the appropriate 244 href="../qt/qwidgetstack.html"> QWidgetStack</a> and the appropriate
247 editor and/or viewer widget for their application. This widget 245 editor and/or viewer widget for their application. This widget
248 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
249 they wish to operate on. Please refer to the implementation of 247 they wish to operate on. Please refer to the implementation of
250 texteditor for an example of how to tie these classes together. 248 texteditor for an example of how to tie these classes together.
251 249
252 Use setNewVisible() depending on whether the application can be used 250 Use setNewVisible() depending on whether the application can be used
253 to create new files or not. Use setCloseVisible() depending on 251 to create new files or not. Use setCloseVisible() depending on
254 whether the user may leave the dialog without creating or selecting 252 whether the user may leave the dialog without creating or selecting
255 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
256 fileCount(). To force the view to be updated call reread(). 254 fileCount(). To force the view to be updated call reread().
257 255
258 If the user presses the 'New Document' button the newSelected() 256 If the user presses the 'New Document' button the newSelected()
259 signal is emitted. If the user selects an existing file the 257 signal is emitted. If the user selects an existing file the
260 fileSelected() signal is emitted. The selected file's \link 258 fileSelected() signal is emitted. The selected file's \link
261 doclnk.html DocLnk\endlink is available from the selected() 259 doclnk.html DocLnk\endlink is available from the selected()
262 function. If the file selector is no longer necessary the closeMe() 260 function. If the file selector is no longer necessary the closeMe()
263 signal is emitted. 261 signal is emitted.
264 262
265 \ingroup qtopiaemb 263 \ingroup qtopiaemb
266 \sa FileManager 264 \sa FileManager
267*/ 265*/
268 266
269/*! 267/*!
270 Constructs a FileSelector with mime filter \a f. 268 Constructs a FileSelector with mime filter \a f.
271 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
272 parent widget. 270 parent widget.
273 271
274 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
275 the create "new" documents; this is useful for applications that can 273 the create "new" documents; this is useful for applications that can
276 create and edit documents but not suitable for applications that 274 create and edit documents but not suitable for applications that
277 only provide viewing. 275 only provide viewing.
278 276
279 \a closeVisible is deprecated 277 \a closeVisible is deprecated
280 278
281 \sa DocLnkSet::DocLnkSet() 279 \sa DocLnkSet::DocLnkSet()
282*/ 280*/
283FileSelector::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 )
284 : QVBox( parent, name ), filter( f ) 282 : QVBox( parent, name ), filter( f )
285{ 283{
286 setMargin( 0 ); 284 setMargin( 0 );
287 setSpacing( 0 ); 285 setSpacing( 0 );
288 286
289 d = new FileSelectorPrivate(); 287 d = new FileSelectorPrivate();
290 d->newDocItem = 0; 288 d->newDocItem = 0;
291 d->showNew = newVisible; 289 d->showNew = newVisible;
292 d->catId = -2; // All files 290 d->catId = -2; // All files
293 291
294 d->toolbar = new QHBox( this ); 292 d->toolbar = new QHBox( this );
295 d->toolbar->setBackgroundMode( PaletteButton ); // same colour as toolbars 293 d->toolbar->setBackgroundMode( PaletteButton ); // same colour as toolbars
296 d->toolbar->setSpacing( 0 ); 294 d->toolbar->setSpacing( 0 );
297 d->toolbar->hide(); 295 d->toolbar->hide();
298 296
299 QWidget *spacer = new QWidget( d->toolbar ); 297 QWidget *spacer = new QWidget( d->toolbar );
300 spacer->setBackgroundMode( PaletteButton ); 298 spacer->setBackgroundMode( PaletteButton );
301 299
302 QToolButton *tb = new QToolButton( d->toolbar ); 300 QToolButton *tb = new QToolButton( d->toolbar );
303 tb->setPixmap( Resource::loadPixmap( "close" ) ); 301 tb->setPixmap( Resource::loadPixmap( "close" ) );
304 connect( tb, SIGNAL( clicked() ), this, SIGNAL( closeMe() ) ); 302 connect( tb, SIGNAL( clicked() ), this, SIGNAL( closeMe() ) );
305 buttonClose = tb; 303 buttonClose = tb;
306 tb->setFixedSize( 18, 20 ); // tb->sizeHint() ); 304 tb->setFixedSize( 18, 20 ); // tb->sizeHint() );
307 tb->setAutoRaise( TRUE ); 305 tb->setAutoRaise( TRUE );
308 QToolTip::add( tb, tr( "Close the File Selector" ) ); 306 QToolTip::add( tb, tr( "Close the File Selector" ) );
309 QPEMenuToolFocusManager::manager()->addWidget( tb ); 307 QPEMenuToolFocusManager::manager()->addWidget( tb );
310 308
311 view = new FileSelectorView( this, "fileview" ); 309 view = new FileSelectorView( this, "fileview" );
312 QPEApplication::setStylusOperation( view->viewport(), QPEApplication::RightOnHold ); 310 QPEApplication::setStylusOperation( view->viewport(), QPEApplication::RightOnHold );
313 connect( view, SIGNAL( mouseButtonClicked( int, QListViewItem *, const QPoint &, int ) ), 311 connect( view, SIGNAL( mouseButtonClicked( int, QListViewItem *, const QPoint &, int ) ),
314 this, SLOT( fileClicked( int, QListViewItem *, const QPoint &, int ) ) ); 312 this, SLOT( fileClicked( int, QListViewItem *, const QPoint &, int ) ) );
315 connect( view, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint &, int ) ), 313 connect( view, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint &, int ) ),
316 this, SLOT( filePressed( int, QListViewItem *, const QPoint &, int ) ) ); 314 this, SLOT( filePressed( int, QListViewItem *, const QPoint &, int ) ) );
317 connect( view, SIGNAL( returnPressed( QListViewItem * ) ), 315 connect( view, SIGNAL( returnPressed( QListViewItem * ) ),
318 this, SLOT( fileClicked( QListViewItem * ) ) ); 316 this, SLOT( fileClicked( QListViewItem * ) ) );
319 317
320 QHBox *hb = new QHBox( this ); 318 QHBox *hb = new QHBox( this );
321 319
322 d->typeCombo = new TypeCombo( hb ); 320 d->typeCombo = new TypeCombo( hb );
323 connect( d->typeCombo, SIGNAL(selected(const QString&)), 321 connect( d->typeCombo, SIGNAL(selected(const QString&)),
324 this, SLOT(typeSelected(const QString&)) ); 322 this, SLOT(typeSelected(const QString&)) );
325 QWhatsThis::add( d->typeCombo, tr("Show documents of this type") ); 323 QWhatsThis::add( d->typeCombo, tr("Show documents of this type") );
326 324
327 Categories c; 325 Categories c;
328 c.load(categoryFileName()); 326 c.load(categoryFileName());
329 QArray<int> vl( 0 ); 327 QArray<int> vl( 0 );
330 d->catSelect = new CategorySelect( hb ); 328 d->catSelect = new CategorySelect( hb );
331 d->catSelect->setRemoveCategoryEdit( TRUE ); 329 d->catSelect->setRemoveCategoryEdit( TRUE );
332 d->catSelect->setCategories( vl, "Document View", tr("Document View") ); 330 d->catSelect->setCategories( vl, "Document View", tr("Document View") );
333 d->catSelect->setAllCategories( TRUE ); 331 d->catSelect->setAllCategories( TRUE );
334 connect( d->catSelect, SIGNAL(signalSelected(int)), this, SLOT(catSelected(int)) ); 332 connect( d->catSelect, SIGNAL(signalSelected(int)), this, SLOT(catSelected(int)) );
335 QWhatsThis::add( d->catSelect, tr("Show documents in this category") ); 333 QWhatsThis::add( d->catSelect, tr("Show documents in this category") );
336 334
337 setCloseVisible( closeVisible ); 335 setCloseVisible( closeVisible );
338 336
339 QCopChannel *channel = new QCopChannel( "QPE/Card", this ); 337 QCopChannel *channel = new QCopChannel( "QPE/Card", this );
340 connect( channel, SIGNAL(received(const QCString &, const QByteArray &)), 338 connect( channel, SIGNAL(received(const QCString &, const QByteArray &)),
341 this, SLOT(cardMessage( const QCString &, const QByteArray &)) ); 339 this, SLOT(cardMessage( const QCString &, const QByteArray &)) );
342 340
343 reread(); 341 reread();
344 updateWhatsThis(); 342 updateWhatsThis();
345} 343}
346 344
347/*! 345/*!
348 Destroys the widget. 346 Destroys the widget.
349*/ 347*/
350FileSelector::~FileSelector() 348FileSelector::~FileSelector()
351{ 349{
352 delete d; 350 delete d;
353} 351}
354 352
355/*! 353/*!
356 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
357 application might bypass the selector and immediately start with 355 application might bypass the selector and immediately start with
358 a "new" document. 356 a "new" document.
359*/ 357*/
360int FileSelector::fileCount() 358int FileSelector::fileCount()
361{ 359{
362 return d->files.children().count();; 360 return d->files.children().count();;
363} 361}
364 362
365/*! 363/*!
366 Calling this function is the programmatic equivalent of the user 364 Calling this function is the programmatic equivalent of the user
367 pressing the "new" button. 365 pressing the "new" button.
368 366
369 \sa newSelected(), closeMe() 367 \sa newSelected(), closeMe()
370*/ 368*/
371void FileSelector::createNew() 369void FileSelector::createNew()
372{ 370{
373 DocLnk f; 371 DocLnk f;
374 emit newSelected( f ); 372 emit newSelected( f );
375 emit closeMe(); 373 emit closeMe();
376} 374}
377 375
378void FileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int ) 376void FileSelector::fileClicked( int button, QListViewItem *i, const QPoint &, int )
379{ 377{
380 if ( !i ) 378 if ( !i )
381 return; 379 return;
382 if ( button == Qt::LeftButton ) { 380 if ( button == Qt::LeftButton ) {
383 fileClicked( i ); 381 fileClicked( i );
384 } 382 }
385} 383}
386 384
387void FileSelector::filePressed( int button, QListViewItem *i, const QPoint &, int ) 385void FileSelector::filePressed( int button, QListViewItem *i, const QPoint &, int )
388{ 386{
389 if ( !i || i == d->newDocItem ) 387 if ( !i || i == d->newDocItem )
390 return; 388 return;
391 if ( button == Qt::RightButton ) { 389 if ( button == Qt::RightButton ) {
392 DocLnk l = ((FileSelectorItem *)i)->file(); 390 DocLnk l = ((FileSelectorItem *)i)->file();
393 LnkProperties prop( &l ); 391 LnkProperties prop( &l );
394 prop.showMaximized(); 392 prop.showMaximized();
395 prop.exec(); 393 prop.exec();
396 reread(); 394 reread();
397 } 395 }
398} 396}
399 397
400void FileSelector::fileClicked( QListViewItem *i ) 398void FileSelector::fileClicked( QListViewItem *i )
401{ 399{
402 if ( !i ) 400 if ( !i )
403 return; 401 return;
404 if ( i == d->newDocItem ) { 402 if ( i == d->newDocItem ) {
405 createNew(); 403 createNew();
406 } else { 404 } else {
407 emit fileSelected( ( (FileSelectorItem*)i )->file() ); 405 emit fileSelected( ( (FileSelectorItem*)i )->file() );
408 emit closeMe(); 406 emit closeMe();
409 } 407 }
410} 408}
411 409
412void FileSelector::typeSelected( const QString &type ) 410void FileSelector::typeSelected( const QString &type )
413{ 411{
414 d->mimeFilters.clear(); 412 d->mimeFilters.clear();
415 QStringList subFilter = QStringList::split(";", type); 413 QStringList subFilter = QStringList::split(";", type);
416 for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++it ) 414 for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++it )
417 d->mimeFilters.append( QRegExp(*it, FALSE, TRUE) ); 415 d->mimeFilters.append( QRegExp(*it, FALSE, TRUE) );
418 updateView(); 416 updateView();
419} 417}
420 418
421void FileSelector::catSelected( int c ) 419void FileSelector::catSelected( int c )
422{ 420{
423 d->catId = c; 421 d->catId = c;
424 updateView(); 422 updateView();
425} 423}
426 424
427void FileSelector::cardMessage( const QCString &msg, const QByteArray &) 425void FileSelector::cardMessage( const QCString &msg, const QByteArray &)
428{ 426{
429 if ( msg == "mtabChanged()" ) 427 if ( msg == "mtabChanged()" )
430 reread(); 428 reread();
431} 429}
432 430
433 431
434/*! 432/*!
435 Returns the selected \link doclnk.html DocLnk\endlink. The caller is 433 Returns the selected \link doclnk.html DocLnk\endlink. The caller is
436 responsible for deleting the returned value. 434 responsible for deleting the returned value.
437*/ 435*/
438const DocLnk *FileSelector::selected() 436const DocLnk *FileSelector::selected()
439{ 437{
440 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem(); 438 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem();
441 if ( item && item != d->newDocItem ) 439 if ( item && item != d->newDocItem )
442 return new DocLnk( item->file() ); 440 return new DocLnk( item->file() );
443 return NULL; 441 return NULL;
444} 442}
445 443
446/*! 444/*!
447 \fn void FileSelector::fileSelected( const DocLnk &f ) 445 \fn void FileSelector::fileSelected( const DocLnk &f )
448 446
449 This signal is emitted when the user selects a document. 447 This signal is emitted when the user selects a document.
450 \a f is the document. 448 \a f is the document.
451*/ 449*/
452 450
453/*! 451/*!
454 \fn void FileSelector::newSelected( const DocLnk &f ) 452 \fn void FileSelector::newSelected( const DocLnk &f )
455 453
456 This signal is emitted when the user selects a "new" document. 454 This signal is emitted when the user selects a "new" document.
457 \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
458 of the document after copying it. 456 of the document after copying it.
459*/ 457*/
460 458
461/*! 459/*!
462 \fn void FileSelector::closeMe() 460 \fn void FileSelector::closeMe()
463 461
464 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.
465*/ 463*/
466 464
467 465
468/*! 466/*!
469 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
470 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
471 documents from the dialog. 469 documents from the dialog.
472*/ 470*/
473void FileSelector::setNewVisible( bool b ) 471void FileSelector::setNewVisible( bool b )
474{ 472{
475 if ( d->showNew != b ) { 473 if ( d->showNew != b ) {
476 d->showNew = b; 474 d->showNew = b;
477 updateView(); 475 updateView();
478 updateWhatsThis(); 476 updateWhatsThis();
479 } 477 }
480} 478}
481 479
482/*! 480/*!
483 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
484 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
485 leave the dialog without creating or selecting a document. 483 leave the dialog without creating or selecting a document.
486 484
487 This function is deprecated. 485 This function is deprecated.
488*/ 486*/
489void FileSelector::setCloseVisible( bool b ) 487void FileSelector::setCloseVisible( bool b )
490{ 488{
491 if ( b ) 489 if ( b )
492 d->toolbar->show(); 490 d->toolbar->show();
493 else 491 else
494 d->toolbar->hide(); 492 d->toolbar->hide();
495} 493}
496 494
497/*! 495/*!
498 496
499*/ 497*/
500void FileSelector::setTypeComboVisible( bool b ) { 498void FileSelector::setTypeComboVisible( bool b ) {
501 if ( b ) 499 if ( b )
502 d->typeCombo->show(); 500 d->typeCombo->show();
503 else 501 else
504 d->typeCombo->hide(); 502 d->typeCombo->hide();
505} 503}
506/*! 504/*!
507 505
508*/ 506*/
509void FileSelector::setCategorySelectVisible( bool b ) { 507void FileSelector::setCategorySelectVisible( bool b ) {
510 if ( b ) 508 if ( b )
511 d->catSelect->show(); 509 d->catSelect->show();
512 else 510 else
513 d->catSelect->hide(); 511 d->catSelect->hide();
514} 512}
515 513
516/*! 514/*!
517 Rereads the list of documents. 515 Rereads the list of documents.
518*/ 516*/
519void FileSelector::reread() 517void FileSelector::reread()
520{ 518{
521 d->files.clear(); 519 d->files.clear();
522 Global::findDocuments(&d->files, filter); 520 Global::findDocuments(&d->files, filter);
523 d->typeCombo->reread( d->files, filter ); 521 d->typeCombo->reread( d->files, filter );
524 updateView(); 522 updateView();
525} 523}
526 524
527void FileSelector::updateView() 525void FileSelector::updateView()
528{ 526{
529 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem(); 527 FileSelectorItem *item = (FileSelectorItem *)view->selectedItem();
530 if ( item == d->newDocItem ) 528 if ( item == d->newDocItem )
531 item = 0; 529 item = 0;
532 QString oldFile; 530 QString oldFile;
533 if ( item ) 531 if ( item )
534 oldFile = item->file().file(); 532 oldFile = item->file().file();
535 view->clear(); 533 view->clear();
536 QListIterator<DocLnk> dit( d->files.children() ); 534 QListIterator<DocLnk> dit( d->files.children() );
537 for ( ; dit.current(); ++dit ) { 535 for ( ; dit.current(); ++dit ) {
538 bool mimeMatch = FALSE; 536 bool mimeMatch = FALSE;
539 if ( d->mimeFilters.count() ) { 537 if ( d->mimeFilters.count() ) {
540 QValueList<QRegExp>::Iterator it; 538 QValueList<QRegExp>::Iterator it;
541 for ( it = d->mimeFilters.begin(); it != d->mimeFilters.end(); ++it ) { 539 for ( it = d->mimeFilters.begin(); it != d->mimeFilters.end(); ++it ) {
542 if ( (*it).match((*dit)->type()) >= 0 ) { 540 if ( (*it).match((*dit)->type()) >= 0 ) {
543 mimeMatch = TRUE; 541 mimeMatch = TRUE;
544 break; 542 break;
545 } 543 }
546 } 544 }
547 } else { 545 } else {
548 mimeMatch = TRUE; 546 mimeMatch = TRUE;
549 } 547 }
550 if ( mimeMatch && 548 if ( mimeMatch &&
551 (d->catId == -2 || (*dit)->categories().contains(d->catId) || 549 (d->catId == -2 || (*dit)->categories().contains(d->catId) ||
552 (d->catId == -1 && (*dit)->categories().isEmpty())) ) { 550 (d->catId == -1 && (*dit)->categories().isEmpty())) ) {
553 item = new FileSelectorItem( view, **dit ); 551 item = new FileSelectorItem( view, **dit );
554 if ( item->file().file() == oldFile ) 552 if ( item->file().file() == oldFile )
555 view->setCurrentItem( item ); 553 view->setCurrentItem( item );
556 } 554 }
557 } 555 }
558 556
559 if ( d->showNew ) 557 if ( d->showNew )
560 d->newDocItem = new NewDocItem( view, DocLnk() ); 558 d->newDocItem = new NewDocItem( view, DocLnk() );
561 else 559 else
562 d->newDocItem = 0; 560 d->newDocItem = 0;
563 561
564 if ( !view->selectedItem() || view->childCount() == 1 ) { 562 if ( !view->selectedItem() || view->childCount() == 1 ) {
565 view->setCurrentItem( view->firstChild() ); 563 view->setCurrentItem( view->firstChild() );
566 view->setSelected( view->firstChild(), TRUE ); 564 view->setSelected( view->firstChild(), TRUE );
567 } 565 }
568} 566}
569 567
570void FileSelector::updateWhatsThis() 568void FileSelector::updateWhatsThis()
571{ 569{
572 QWhatsThis::remove( this ); 570 QWhatsThis::remove( this );
573 QString text = tr("Click to select a document from the list"); 571 QString text = tr("Click to select a document from the list");
574 if ( d->showNew ) 572 if ( d->showNew )
575 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.");
576 text += tr("<br><br>Click and hold for document properties."); 574 text += tr("<br><br>Click and hold for document properties.");
577 QWhatsThis::add( this, text ); 575 QWhatsThis::add( this, text );
578} 576}
579 577
580#include "fileselector.moc" 578#include "fileselector.moc"
581 579
diff --git a/library/finddialog.cpp b/library/finddialog.cpp
index ddf41a7..64487c9 100644
--- a/library/finddialog.cpp
+++ b/library/finddialog.cpp
@@ -1,85 +1,84 @@
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#include <qpushbutton.h>
30 29
31/*! 30/*!
32 \class FindDialog finddialog.h 31 \class FindDialog finddialog.h
33 \brief A simple FindDialog 32 \brief A simple FindDialog
34 33
35 A find dialog. FIXME!!!! 34 A find dialog. FIXME!!!!
36 35
37*/ 36*/
38FindDialog::FindDialog( const QString &appName, QWidget *parent, 37FindDialog::FindDialog( const QString &appName, QWidget *parent,
39 const char *name, bool modal ) 38 const char *name, bool modal )
40 : QDialog( parent, name, modal ) 39 : QDialog( parent, name, modal )
41{ 40{
42 setCaption( tr("Find") ); 41 setCaption( tr("Find") );
43 QVBoxLayout *vb; 42 QVBoxLayout *vb;
44 vb = new QVBoxLayout( this ); 43 vb = new QVBoxLayout( this );
45 fw = new FindWidget( appName, this, "Find Widget" ); 44 fw = new FindWidget( appName, this, "Find Widget" );
46 vb->addWidget( fw ); 45 vb->addWidget( fw );
47 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&, 46 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&,
48 bool,bool,int)), 47 bool,bool,int)),
49 this, SIGNAL(signalFindClicked(const QString&, 48 this, SIGNAL(signalFindClicked(const QString&,
50 bool,bool,int)) ); 49 bool,bool,int)) );
51 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&,const QDate&, 50 QObject::connect( fw, SIGNAL(signalFindClicked(const QString&,const QDate&,
52 bool,bool,int)), 51 bool,bool,int)),
53 this, SIGNAL(signalFindClicked(const QString&, 52 this, SIGNAL(signalFindClicked(const QString&,
54 const QDate&,bool,bool,int)) ); 53 const QDate&,bool,bool,int)) );
55 d = 0; 54 d = 0;
56} 55}
57 56
58FindDialog::~FindDialog() 57FindDialog::~FindDialog()
59{ 58{
60} 59}
61 60
62QString FindDialog::findText() const 61QString FindDialog::findText() const
63{ 62{
64 return fw->findText(); 63 return fw->findText();
65} 64}
66 65
67void FindDialog::setUseDate( bool show ) 66void FindDialog::setUseDate( bool show )
68{ 67{
69 fw->setUseDate( show ); 68 fw->setUseDate( show );
70} 69}
71 70
72void FindDialog::setDate( const QDate &dt ) 71void FindDialog::setDate( const QDate &dt )
73{ 72{
74 fw->setDate( dt ); 73 fw->setDate( dt );
75} 74}
76 75
77void FindDialog::slotNotFound() 76void FindDialog::slotNotFound()
78{ 77{
79 fw->slotNotFound(); 78 fw->slotNotFound();
80} 79}
81 80
82void FindDialog::slotWrapAround() 81void FindDialog::slotWrapAround()
83{ 82{
84 fw->slotWrapAround(); 83 fw->slotWrapAround();
85} 84}
diff --git a/library/findwidget_p.cpp b/library/findwidget_p.cpp
index 287e125..e91d789 100644
--- a/library/findwidget_p.cpp
+++ b/library/findwidget_p.cpp
@@ -1,120 +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/categories.h>
24#include <qpe/categoryselect.h> 23#include <qpe/categoryselect.h>
25#include <qpe/datebookmonth.h> 24#include <qpe/datebookmonth.h>
26#include <qpe/timestring.h>
27 25
28#include <qcheckbox.h> 26#include <qcheckbox.h>
29#include <qlabel.h> 27#include <qlabel.h>
30#include <qlineedit.h> 28#include <qlineedit.h>
31#include <qmessagebox.h>
32#include <qpushbutton.h>
33#include <qpopupmenu.h>
34#include <qtoolbutton.h>
35 29
36FindWidget::FindWidget( const QString &appName, QWidget *parent, 30FindWidget::FindWidget( const QString &appName, QWidget *parent,
37 const char *name ) 31 const char *name )
38 : FindWidgetBase( parent, name ), 32 : FindWidgetBase( parent, name ),
39 mStrApp( appName ), 33 mStrApp( appName ),
40 mDate( QDate::currentDate() ) 34 mDate( QDate::currentDate() )
41{ 35{
42 setMaximumSize( sizeHint() ); 36 setMaximumSize( sizeHint() );
43 QArray<int> vl(0); 37 QArray<int> vl(0);
44 cmbCat->setCategories( vl, mStrApp ); 38 cmbCat->setCategories( vl, mStrApp );
45 cmbCat->setRemoveCategoryEdit( TRUE ); 39 cmbCat->setRemoveCategoryEdit( TRUE );
46 cmbCat->setAllCategories( TRUE ); 40 cmbCat->setAllCategories( TRUE );
47 // hide junk for the moment... 41 // hide junk for the moment...
48 lblStartDate->hide(); 42 lblStartDate->hide();
49 cmdStartDate->hide(); 43 cmdStartDate->hide();
50 QPopupMenu *m1 = new QPopupMenu( this ); 44 QPopupMenu *m1 = new QPopupMenu( this );
51 dtPicker = new DateBookMonth( m1, 0, TRUE ); 45 dtPicker = new DateBookMonth( m1, 0, TRUE );
52 dtPicker->setDate( mDate.year(), mDate.month(), mDate.day() ); 46 dtPicker->setDate( mDate.year(), mDate.month(), mDate.day() );
53 m1->insertItem( dtPicker ); 47 m1->insertItem( dtPicker );
54 cmdStartDate->setPopup( m1 ); 48 cmdStartDate->setPopup( m1 );
55 cmdStartDate->setText( TimeString::shortDate(mDate) ); 49 cmdStartDate->setText( TimeString::shortDate(mDate) );
56 QObject::connect( dtPicker, SIGNAL(dateClicked(int, int, int)), 50 QObject::connect( dtPicker, SIGNAL(dateClicked(int, int, int)),
57 this, SLOT(slotDateChanged(int, int, int)) ); 51 this, SLOT(slotDateChanged(int, int, int)) );
58 52
59 QObject::connect( cmdFind, SIGNAL(clicked()), 53 QObject::connect( cmdFind, SIGNAL(clicked()),
60 this, SLOT(slotFindClicked()) ); 54 this, SLOT(slotFindClicked()) );
61} 55}
62 56
63FindWidget::~FindWidget() 57FindWidget::~FindWidget()
64{ 58{
65} 59}
66 60
67QString FindWidget::findText() const 61QString FindWidget::findText() const
68{ 62{
69 return txtFind->text(); 63 return txtFind->text();
70} 64}
71 65
72void FindWidget::slotFindClicked() 66void FindWidget::slotFindClicked()
73{ 67{
74 lblStatus->setText( "" ); 68 lblStatus->setText( "" );
75 if ( cmdStartDate->isVisible() ) 69 if ( cmdStartDate->isVisible() )
76 emit signalFindClicked( findText(), 70 emit signalFindClicked( findText(),
77 mDate, 71 mDate,
78 chkCase->isChecked(), 72 chkCase->isChecked(),
79 chkBackwards->isChecked(), 73 chkBackwards->isChecked(),
80 cmbCat->currentCategory() ); 74 cmbCat->currentCategory() );
81 else 75 else
82 emit signalFindClicked( findText(), chkCase->isChecked(), 76 emit signalFindClicked( findText(), chkCase->isChecked(),
83 chkBackwards->isChecked(), 77 chkBackwards->isChecked(),
84 cmbCat->currentCategory() ); 78 cmbCat->currentCategory() );
85} 79}
86 80
87void FindWidget::setUseDate( bool show ) 81void FindWidget::setUseDate( bool show )
88{ 82{
89 if ( show ) { 83 if ( show ) {
90 lblStartDate->show(); 84 lblStartDate->show();
91 cmdStartDate->show(); 85 cmdStartDate->show();
92 } else { 86 } else {
93 lblStartDate->hide(); 87 lblStartDate->hide();
94 cmdStartDate->hide(); 88 cmdStartDate->hide();
95 } 89 }
96 chkBackwards->setDisabled( show ); 90 chkBackwards->setDisabled( show );
97} 91}
98 92
99void FindWidget::setDate( const QDate &dt ) 93void FindWidget::setDate( const QDate &dt )
100{ 94{
101 slotDateChanged( dt.year(), dt.month(), dt.day() ); 95 slotDateChanged( dt.year(), dt.month(), dt.day() );
102} 96}
103 97
104void FindWidget::slotNotFound() 98void FindWidget::slotNotFound()
105{ 99{
106 lblStatus->setText( tr("String Not Found.") ); 100 lblStatus->setText( tr("String Not Found.") );
107} 101}
108 102
109void FindWidget::slotWrapAround() 103void FindWidget::slotWrapAround()
110{ 104{
111 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")
112 .arg(TimeString::shortDate( mDate ) ) ); 106 .arg(TimeString::shortDate( mDate ) ) );
113} 107}
114 108
115void FindWidget::slotDateChanged( int year, int month, int day ) 109void FindWidget::slotDateChanged( int year, int month, int day )
116{ 110{
117 mDate.setYMD( year, month, day ); 111 mDate.setYMD( year, month, day );
118 cmdStartDate->setText( TimeString::shortDate( mDate ) ); 112 cmdStartDate->setText( TimeString::shortDate( mDate ) );
119 dtPicker->setDate( year, month, day ); 113 dtPicker->setDate( year, month, day );
120} 114}
diff --git a/library/fontdatabase.cpp b/library/fontdatabase.cpp
index 2ad8e95..d94e338 100644
--- a/library/fontdatabase.cpp
+++ b/library/fontdatabase.cpp
@@ -1,253 +1,251 @@
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 <qpe/qpeapplication.h> 21#include <qpe/qpeapplication.h>
22#include "fontfactoryinterface.h"
23#include "fontdatabase.h" 22#include "fontdatabase.h"
24 23
25#include <qpe/qlibrary.h> 24#include <qpe/qlibrary.h>
26 25
27#include <qfontmanager_qws.h> 26#include <qfontmanager_qws.h>
28#include <qdir.h> 27#include <qdir.h>
29#include <qdict.h>
30#include <stdio.h> 28#include <stdio.h>
31#include <stdlib.h> 29#include <stdlib.h>
32 30
33static QString fontDir() 31static QString fontDir()
34{ 32{
35 QString qtdir = getenv("QTDIR"); 33 QString qtdir = getenv("QTDIR");
36 if ( qtdir.isEmpty() ) qtdir = "/usr/local/qt-embedded"; 34 if ( qtdir.isEmpty() ) qtdir = "/usr/local/qt-embedded";
37 return qtdir+"/lib/fonts/"; 35 return qtdir+"/lib/fonts/";
38} 36}
39 37
40#ifdef QT_NO_FONTDATABASE 38#ifdef QT_NO_FONTDATABASE
41static QString fontFamily( const QString& key ) 39static QString fontFamily( const QString& key )
42{ 40{
43 int u0 = key.find('_'); 41 int u0 = key.find('_');
44 int u1 = key.find('_',u0+1); 42 int u1 = key.find('_',u0+1);
45 int u2 = key.find('_',u1+1); 43 int u2 = key.find('_',u1+1);
46 QString family = key.left(u0); 44 QString family = key.left(u0);
47 //int pointSize = key.mid(u0+1,u1-u0-1).toInt(); 45 //int pointSize = key.mid(u0+1,u1-u0-1).toInt();
48 //int weight = key.mid(u1+1,u2-u1-1).toInt(); 46 //int weight = key.mid(u1+1,u2-u1-1).toInt();
49 //bool italic = key.mid(u2-1,1) == "i"; 47 //bool italic = key.mid(u2-1,1) == "i";
50 // #### ignores _t and _I fields 48 // #### ignores _t and _I fields
51 return family; 49 return family;
52} 50}
53#endif 51#endif
54 52
55 53
56QValueList<FontFactory> *FontDatabase::factoryList = 0; 54QValueList<FontFactory> *FontDatabase::factoryList = 0;
57/*! 55/*!
58 \class FontDatabase fontdatabase.h 56 \class FontDatabase fontdatabase.h
59 \brief The FontDatabase class provides information about available fonts. 57 \brief The FontDatabase class provides information about available fonts.
60 58
61 Most often you will simply want to query the database for the 59 Most often you will simply want to query the database for the
62 available font families(). 60 available font families().
63 61
64 Use FontDatabase rather than QFontDatabase when you may need access 62 Use FontDatabase rather than QFontDatabase when you may need access
65 to fonts that are not normally available. For example, if the 63 to fonts that are not normally available. For example, if the
66 freetype library and the Qtopia freetype plugin are installed, 64 freetype library and the Qtopia freetype plugin are installed,
67 TrueType fonts will be available to your application. Font renderer 65 TrueType fonts will be available to your application. Font renderer
68 plugins have greater resource requirements than system fonts so they 66 plugins have greater resource requirements than system fonts so they
69 should be used only when necessary. You can force the loading of 67 should be used only when necessary. You can force the loading of
70 font renderer plugins with loadRenderers(). 68 font renderer plugins with loadRenderers().
71 69
72 \ingroup qtopiaemb 70 \ingroup qtopiaemb
73*/ 71*/
74 72
75/*! 73/*!
76 Constructs a FontDatabase object. 74 Constructs a FontDatabase object.
77*/ 75*/
78FontDatabase::FontDatabase() 76FontDatabase::FontDatabase()
79#ifndef QT_NO_FONTDATABASE 77#ifndef QT_NO_FONTDATABASE
80 : QFontDatabase() 78 : QFontDatabase()
81#endif 79#endif
82{ 80{
83 if ( !factoryList ) 81 if ( !factoryList )
84 loadRenderers(); 82 loadRenderers();
85} 83}
86 84
87/*! 85/*!
88 Returns a list of names of all the available font families. 86 Returns a list of names of all the available font families.
89*/ 87*/
90QStringList FontDatabase::families() const 88QStringList FontDatabase::families() const
91{ 89{
92#ifndef QT_NO_FONTDATABASE 90#ifndef QT_NO_FONTDATABASE
93 return QFontDatabase::families(); 91 return QFontDatabase::families();
94#else 92#else
95 93
96#ifndef QWS 94#ifndef QWS
97 QStringList list; 95 QStringList list;
98 return list; 96 return list;
99#else 97#else
100 QStringList list; 98 QStringList list;
101 QDict<void> familyDict; 99 QDict<void> familyDict;
102 QDiskFont *qdf; 100 QDiskFont *qdf;
103 for ( qdf=qt_fontmanager->diskfonts.first(); qdf!=0; 101 for ( qdf=qt_fontmanager->diskfonts.first(); qdf!=0;
104 qdf=qt_fontmanager->diskfonts.next()) { 102 qdf=qt_fontmanager->diskfonts.next()) {
105 QString familyname = qdf->name; 103 QString familyname = qdf->name;
106 if ( !familyDict.find( familyname ) ) { 104 if ( !familyDict.find( familyname ) ) {
107 familyDict.insert( familyname, (void *)1 ); 105 familyDict.insert( familyname, (void *)1 );
108 list.append( familyname ); 106 list.append( familyname );
109 } 107 }
110 } 108 }
111 109
112 QDir dir(fontDir(),"*.qpf"); 110 QDir dir(fontDir(),"*.qpf");
113 for (int i=0; i<(int)dir.count(); i++) { 111 for (int i=0; i<(int)dir.count(); i++) {
114 QString familyname = fontFamily(dir[i]); 112 QString familyname = fontFamily(dir[i]);
115 if ( !familyDict.find( familyname ) ) { 113 if ( !familyDict.find( familyname ) ) {
116 familyDict.insert( familyname, (void *)1 ); 114 familyDict.insert( familyname, (void *)1 );
117 list.append( familyname ); 115 list.append( familyname );
118 } 116 }
119 } 117 }
120 118
121 return list; 119 return list;
122#endif 120#endif
123#endif 121#endif
124} 122}
125 123
126#ifdef QT_NO_FONTDATABASE 124#ifdef QT_NO_FONTDATABASE
127/*! 125/*!
128 Returns a list of standard fontsizes. 126 Returns a list of standard fontsizes.
129*/ 127*/
130QValueList<int> FontDatabase::standardSizes() 128QValueList<int> FontDatabase::standardSizes()
131{ 129{
132 static int s[]={ 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 130 static int s[]={ 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28,
133 36, 48, 72, 0 }; 131 36, 48, 72, 0 };
134 static bool first = TRUE; 132 static bool first = TRUE;
135 static QValueList<int> sList; 133 static QValueList<int> sList;
136 if ( first ) { 134 if ( first ) {
137 first = FALSE; 135 first = FALSE;
138 int i = 0; 136 int i = 0;
139 while( s[i] ) 137 while( s[i] )
140 sList.append( s[i++] ); 138 sList.append( s[i++] );
141 } 139 }
142 return sList; 140 return sList;
143} 141}
144 142
145#endif 143#endif
146 144
147/*! 145/*!
148 Load any font renderer plugins that are available and make the fonts 146 Load any font renderer plugins that are available and make the fonts
149 that the plugins can read available. 147 that the plugins can read available.
150*/ 148*/
151void FontDatabase::loadRenderers() 149void FontDatabase::loadRenderers()
152{ 150{
153#ifndef QWS 151#ifndef QWS
154 return; 152 return;
155#else 153#else
156 154
157#ifndef QT_NO_COMPONENT 155#ifndef QT_NO_COMPONENT
158 if ( !factoryList ) 156 if ( !factoryList )
159 factoryList = new QValueList<FontFactory>; 157 factoryList = new QValueList<FontFactory>;
160 158
161 QValueList<FontFactory>::Iterator mit; 159 QValueList<FontFactory>::Iterator mit;
162 for ( mit = factoryList->begin(); mit != factoryList->end(); ++mit ) { 160 for ( mit = factoryList->begin(); mit != factoryList->end(); ++mit ) {
163 qt_fontmanager->factories.setAutoDelete( false ); 161 qt_fontmanager->factories.setAutoDelete( false );
164 qt_fontmanager->factories.removeRef( (*mit).factory ); 162 qt_fontmanager->factories.removeRef( (*mit).factory );
165 qt_fontmanager->factories.setAutoDelete( true ); 163 qt_fontmanager->factories.setAutoDelete( true );
166 (*mit).interface->release(); 164 (*mit).interface->release();
167 (*mit).library->unload(); 165 (*mit).library->unload();
168 delete (*mit).library; 166 delete (*mit).library;
169 } 167 }
170 factoryList->clear(); 168 factoryList->clear();
171 169
172 QString path = QPEApplication::qpeDir() + "/plugins/fontfactories"; 170 QString path = QPEApplication::qpeDir() + "/plugins/fontfactories";
173#ifdef Q_OS_MACX 171#ifdef Q_OS_MACX
174 QDir dir( path, "lib*.dylib" ); 172 QDir dir( path, "lib*.dylib" );
175#else 173#else
176 QDir dir( path, "lib*.so" ); 174 QDir dir( path, "lib*.so" );
177#endif 175#endif
178 176
179 if ( !dir.exists()) 177 if ( !dir.exists())
180 return; 178 return;
181 179
182 QStringList list = dir.entryList(); 180 QStringList list = dir.entryList();
183 QStringList::Iterator it; 181 QStringList::Iterator it;
184 for ( it = list.begin(); it != list.end(); ++it ) { 182 for ( it = list.begin(); it != list.end(); ++it ) {
185 FontFactoryInterface *iface = 0; 183 FontFactoryInterface *iface = 0;
186 QLibrary *lib = new QLibrary( path + "/" + *it ); 184 QLibrary *lib = new QLibrary( path + "/" + *it );
187 if ( lib->queryInterface( IID_FontFactory, (QUnknownInterface**)&iface ) == QS_OK ) { 185 if ( lib->queryInterface( IID_FontFactory, (QUnknownInterface**)&iface ) == QS_OK ) {
188 FontFactory factory; 186 FontFactory factory;
189 factory.library = lib; 187 factory.library = lib;
190 factory.interface = iface; 188 factory.interface = iface;
191 factory.factory = factory.interface->fontFactory(); 189 factory.factory = factory.interface->fontFactory();
192 factoryList->append( factory ); 190 factoryList->append( factory );
193 qt_fontmanager->factories.append( factory.factory ); 191 qt_fontmanager->factories.append( factory.factory );
194 readFonts( factory.factory ); 192 readFonts( factory.factory );
195 } else { 193 } else {
196 delete lib; 194 delete lib;
197 } 195 }
198 } 196 }
199#endif 197#endif
200#endif 198#endif
201} 199}
202 200
203/*! 201/*!
204 \internal 202 \internal
205*/ 203*/
206void FontDatabase::readFonts( QFontFactory *factory ) 204void FontDatabase::readFonts( QFontFactory *factory )
207{ 205{
208#ifndef QWS 206#ifndef QWS
209return; 207return;
210#else 208#else
211 // Load in font definition file 209 // Load in font definition file
212 QString fn = fontDir() + "fontdir"; 210 QString fn = fontDir() + "fontdir";
213 FILE* fontdef=fopen(fn.local8Bit(),"r"); 211 FILE* fontdef=fopen(fn.local8Bit(),"r");
214 if(!fontdef) { 212 if(!fontdef) {
215 QCString temp=fn.local8Bit(); 213 QCString temp=fn.local8Bit();
216 qWarning("Cannot find font definition file %s - is $QTDIR set correctly?", 214 qWarning("Cannot find font definition file %s - is $QTDIR set correctly?",
217 temp.data()); 215 temp.data());
218 return; 216 return;
219 } 217 }
220 char buf[200]=""; 218 char buf[200]="";
221 char name[200]=""; 219 char name[200]="";
222 char render[200]=""; 220 char render[200]="";
223 char file[200]=""; 221 char file[200]="";
224 char flags[200]=""; 222 char flags[200]="";
225 char isitalic[10]=""; 223 char isitalic[10]="";
226 fgets(buf,200,fontdef); 224 fgets(buf,200,fontdef);
227 while(!feof(fontdef)) { 225 while(!feof(fontdef)) {
228 if ( buf[0] != '#' ) { 226 if ( buf[0] != '#' ) {
229 int weight=50; 227 int weight=50;
230 int size=0; 228 int size=0;
231 flags[0]=0; 229 flags[0]=0;
232 sscanf(buf,"%s %s %s %s %d %d %s",name,file,render,isitalic,&weight,&size,flags); 230 sscanf(buf,"%s %s %s %s %d %d %s",name,file,render,isitalic,&weight,&size,flags);
233 QString filename; 231 QString filename;
234 if ( file[0] != '/' ) 232 if ( file[0] != '/' )
235 filename = fontDir(); 233 filename = fontDir();
236 filename += file; 234 filename += file;
237 if ( QFile::exists(filename) ) { 235 if ( QFile::exists(filename) ) {
238 if( factory->name() == render ) { 236 if( factory->name() == render ) {
239 QDiskFont * qdf=new QDiskFont(factory,name,isitalic[0]=='y', 237 QDiskFont * qdf=new QDiskFont(factory,name,isitalic[0]=='y',
240 weight,size,flags,filename); 238 weight,size,flags,filename);
241 qt_fontmanager->diskfonts.append(qdf); 239 qt_fontmanager->diskfonts.append(qdf);
242#if QT_VERSION >= 232 240#if QT_VERSION >= 232
243 QFontDatabase::qwsAddDiskFont( qdf ); 241 QFontDatabase::qwsAddDiskFont( qdf );
244#endif 242#endif
245 } 243 }
246 } 244 }
247 } 245 }
248 fgets(buf,200,fontdef); 246 fgets(buf,200,fontdef);
249 } 247 }
250 fclose(fontdef); 248 fclose(fontdef);
251#endif 249#endif
252} 250}
253 251
diff --git a/library/global.cpp b/library/global.cpp
index a627348..5ac969b 100644
--- a/library/global.cpp
+++ b/library/global.cpp
@@ -1,814 +1,812 @@
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 <qpe/qpedebug.h> 21#include <qpe/qpedebug.h>
22#include <qpe/global.h> 22#include <qpe/global.h>
23#include <qpe/qdawg.h> 23#include <qpe/qdawg.h>
24#include <qpe/qpeapplication.h> 24#include <qpe/qpeapplication.h>
25#include <qpe/resource.h> 25#include <qpe/resource.h>
26#include <qpe/storage.h> 26#include <qpe/storage.h>
27#include <qpe/applnk.h> 27#include <qpe/applnk.h>
28#include <qpe/qcopenvelope_qws.h> 28#include <qpe/qcopenvelope_qws.h>
29#include <qpe/config.h> 29#include <qpe/config.h>
30 30
31#include <qfile.h>
32#include <qlabel.h> 31#include <qlabel.h>
33#include <qtimer.h> 32#include <qtimer.h>
34#include <qmap.h> 33#include <qmap.h>
35#include <qdict.h> 34#include <qdict.h>
36#include <qdir.h> 35#include <qdir.h>
37#include <qmessagebox.h> 36#include <qmessagebox.h>
38#include <qregexp.h> 37#include <qregexp.h>
39 38
40#include <stdlib.h> 39#include <stdlib.h>
41#include <sys/stat.h> 40#include <sys/stat.h>
42#include <sys/wait.h> 41#include <sys/wait.h>
43#include <sys/types.h> 42#include <sys/types.h>
44#include <fcntl.h> 43#include <fcntl.h>
45#include <unistd.h> 44#include <unistd.h>
46#include <errno.h> 45#include <errno.h>
47 46
48#include <qwindowsystem_qws.h> // for qwsServer 47#include <qwindowsystem_qws.h> // for qwsServer
49#include <qdatetime.h> 48#include <qdatetime.h>
50 49
51#include <qfile.h>
52 50
53//#include "quickexec_p.h" 51//#include "quickexec_p.h"
54 52
55class Emitter : public QObject { 53class Emitter : public QObject {
56 Q_OBJECT 54 Q_OBJECT
57public: 55public:
58 Emitter( QWidget* receiver, const QString& document ) 56 Emitter( QWidget* receiver, const QString& document )
59 { 57 {
60 connect(this, SIGNAL(setDocument(const QString&)), 58 connect(this, SIGNAL(setDocument(const QString&)),
61 receiver, SLOT(setDocument(const QString&))); 59 receiver, SLOT(setDocument(const QString&)));
62 emit setDocument(document); 60 emit setDocument(document);
63 disconnect(this, SIGNAL(setDocument(const QString&)), 61 disconnect(this, SIGNAL(setDocument(const QString&)),
64 receiver, SLOT(setDocument(const QString&))); 62 receiver, SLOT(setDocument(const QString&)));
65 } 63 }
66 64
67signals: 65signals:
68 void setDocument(const QString&); 66 void setDocument(const QString&);
69}; 67};
70 68
71 69
72class StartingAppList : public QObject { 70class StartingAppList : public QObject {
73 Q_OBJECT 71 Q_OBJECT
74public: 72public:
75 static void add( const QString& name ); 73 static void add( const QString& name );
76 static bool isStarting( const QString name ); 74 static bool isStarting( const QString name );
77private slots: 75private slots:
78 void handleNewChannel( const QString &); 76 void handleNewChannel( const QString &);
79private: 77private:
80 StartingAppList( QObject *parent=0, const char* name=0 ) ; 78 StartingAppList( QObject *parent=0, const char* name=0 ) ;
81 79
82 QDict<QTime> dict; 80 QDict<QTime> dict;
83 static StartingAppList *appl; 81 static StartingAppList *appl;
84}; 82};
85 83
86StartingAppList* StartingAppList::appl = 0; 84StartingAppList* StartingAppList::appl = 0;
87 85
88StartingAppList::StartingAppList( QObject *parent, const char* name ) 86StartingAppList::StartingAppList( QObject *parent, const char* name )
89 :QObject( parent, name ) 87 :QObject( parent, name )
90{ 88{
91#if QT_VERSION >= 232 && defined(QWS) 89#if QT_VERSION >= 232 && defined(QWS)
92 connect( qwsServer, SIGNAL( newChannel(const QString&)), 90 connect( qwsServer, SIGNAL( newChannel(const QString&)),
93 this, SLOT( handleNewChannel(const QString&)) ); 91 this, SLOT( handleNewChannel(const QString&)) );
94#endif 92#endif
95 dict.setAutoDelete( TRUE ); 93 dict.setAutoDelete( TRUE );
96} 94}
97 95
98void StartingAppList::add( const QString& name ) 96void StartingAppList::add( const QString& name )
99{ 97{
100#if QT_VERSION >= 232 && !defined(QT_NO_COP) 98#if QT_VERSION >= 232 && !defined(QT_NO_COP)
101 if ( !appl ) 99 if ( !appl )
102 appl = new StartingAppList; 100 appl = new StartingAppList;
103 QTime *t = new QTime; 101 QTime *t = new QTime;
104 t->start(); 102 t->start();
105 appl->dict.insert( "QPE/Application/" + name, t ); 103 appl->dict.insert( "QPE/Application/" + name, t );
106#endif 104#endif
107} 105}
108 106
109bool StartingAppList::isStarting( const QString name ) 107bool StartingAppList::isStarting( const QString name )
110{ 108{
111#if QT_VERSION >= 232 && !defined(QT_NO_COP) 109#if QT_VERSION >= 232 && !defined(QT_NO_COP)
112 if ( appl ) { 110 if ( appl ) {
113 QTime *t = appl->dict.find( "QPE/Application/" + name ); 111 QTime *t = appl->dict.find( "QPE/Application/" + name );
114 if ( !t ) 112 if ( !t )
115 return FALSE; 113 return FALSE;
116 if ( t->elapsed() > 10000 ) { 114 if ( t->elapsed() > 10000 ) {
117 // timeout in case of crash or something 115 // timeout in case of crash or something
118 appl->dict.remove( "QPE/Application/" + name ); 116 appl->dict.remove( "QPE/Application/" + name );
119 return FALSE; 117 return FALSE;
120 } 118 }
121 return TRUE; 119 return TRUE;
122 } 120 }
123#endif 121#endif
124 return FALSE; 122 return FALSE;
125} 123}
126 124
127void StartingAppList::handleNewChannel( const QString & name ) 125void StartingAppList::handleNewChannel( const QString & name )
128{ 126{
129#if QT_VERSION >= 232 && !defined(QT_NO_COP) 127#if QT_VERSION >= 232 && !defined(QT_NO_COP)
130 dict.remove( name ); 128 dict.remove( name );
131#endif 129#endif
132} 130}
133 131
134static bool docDirCreated = FALSE; 132static bool docDirCreated = FALSE;
135static QDawg* fixed_dawg = 0; 133static QDawg* fixed_dawg = 0;
136static QDict<QDawg> *named_dawg = 0; 134static QDict<QDawg> *named_dawg = 0;
137 135
138static QString qpeDir() 136static QString qpeDir()
139{ 137{
140 QString dir = getenv("OPIEDIR"); 138 QString dir = getenv("OPIEDIR");
141 if ( dir.isEmpty() ) dir = ".."; 139 if ( dir.isEmpty() ) dir = "..";
142 return dir; 140 return dir;
143} 141}
144 142
145static QString dictDir() 143static QString dictDir()
146{ 144{
147 return qpeDir() + "/etc/dict"; 145 return qpeDir() + "/etc/dict";
148} 146}
149 147
150/*! 148/*!
151 \class Global global.h 149 \class Global global.h
152 \brief The Global class provides application-wide global functions. 150 \brief The Global class provides application-wide global functions.
153 151
154 The Global functions are grouped as follows: 152 The Global functions are grouped as follows:
155 \tableofcontents 153 \tableofcontents
156 154
157 \section1 User Interface 155 \section1 User Interface
158 156
159 The statusMessage() function provides short-duration messages to the 157 The statusMessage() function provides short-duration messages to the
160 user. The showInputMethod() function shows the current input method, 158 user. The showInputMethod() function shows the current input method,
161 and hideInputMethod() hides the input method. 159 and hideInputMethod() hides the input method.
162 160
163 \section1 Document related 161 \section1 Document related
164 162
165 The findDocuments() function creates a set of \link doclnk.html 163 The findDocuments() function creates a set of \link doclnk.html
166 DocLnk\endlink objects in a particular folder. 164 DocLnk\endlink objects in a particular folder.
167 165
168 \section1 Filesystem related 166 \section1 Filesystem related
169 167
170 Global provides an applicationFileName() function that returns the 168 Global provides an applicationFileName() function that returns the
171 full path of an application-specific file. 169 full path of an application-specific file.
172 170
173 The execute() function runs an application. 171 The execute() function runs an application.
174 172
175 \section1 Word list related 173 \section1 Word list related
176 174
177 A list of words relevant to the current locale is maintained by the 175 A list of words relevant to the current locale is maintained by the
178 system. The list is held in a \link qdawg.html DAWG\endlink 176 system. The list is held in a \link qdawg.html DAWG\endlink
179 (implemented by the QDawg class). This list is used, for example, by 177 (implemented by the QDawg class). This list is used, for example, by
180 the pickboard input method. 178 the pickboard input method.
181 179
182 The global QDawg is returned by fixedDawg(); this cannot be updated. 180 The global QDawg is returned by fixedDawg(); this cannot be updated.
183 An updatable copy of the global QDawg is returned by addedDawg(). 181 An updatable copy of the global QDawg is returned by addedDawg().
184 Applications may have their own word lists stored in \l{QDawg}s 182 Applications may have their own word lists stored in \l{QDawg}s
185 which are returned by dawg(). Use addWords() to add words to the 183 which are returned by dawg(). Use addWords() to add words to the
186 updateable copy of the global QDawg or to named application 184 updateable copy of the global QDawg or to named application
187 \l{QDawg}s. 185 \l{QDawg}s.
188 186
189 \section1 Quoting 187 \section1 Quoting
190 188
191 The shellQuote() function quotes a string suitable for passing to a 189 The shellQuote() function quotes a string suitable for passing to a
192 shell. The stringQuote() function backslash escapes '\' and '"' 190 shell. The stringQuote() function backslash escapes '\' and '"'
193 characters. 191 characters.
194 192
195 \section1 Hardware 193 \section1 Hardware
196 194
197 The implementation of the writeHWClock() function depends on the AlarmServer 195 The implementation of the writeHWClock() function depends on the AlarmServer
198 implementation. If the AlarmServer is using atd the clock will be synced to 196 implementation. If the AlarmServer is using atd the clock will be synced to
199 hardware. If opie-alarm is used the hardware clock will be synced before 197 hardware. If opie-alarm is used the hardware clock will be synced before
200 suspending the device. opie-alarm is used by iPAQ and Zaurii implementation 198 suspending the device. opie-alarm is used by iPAQ and Zaurii implementation
201 199
202 \ingroup qtopiaemb 200 \ingroup qtopiaemb
203*/ 201*/
204 202
205/*! 203/*!
206 \internal 204 \internal
207*/ 205*/
208Global::Global() 206Global::Global()
209{ 207{
210} 208}
211 209
212/*! 210/*!
213 Returns the unchangeable QDawg that contains general 211 Returns the unchangeable QDawg that contains general
214 words for the current locale. 212 words for the current locale.
215 213
216 \sa addedDawg() 214 \sa addedDawg()
217*/ 215*/
218const QDawg& Global::fixedDawg() 216const QDawg& Global::fixedDawg()
219{ 217{
220 if ( !fixed_dawg ) { 218 if ( !fixed_dawg ) {
221 if ( !docDirCreated ) 219 if ( !docDirCreated )
222 createDocDir(); 220 createDocDir();
223 221
224 fixed_dawg = new QDawg; 222 fixed_dawg = new QDawg;
225 QString dawgfilename = dictDir() + "/dawg"; 223 QString dawgfilename = dictDir() + "/dawg";
226 QString words_lang; 224 QString words_lang;
227 QStringList langs = Global::languageList(); 225 QStringList langs = Global::languageList();
228 for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) { 226 for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) {
229 QString lang = *it; 227 QString lang = *it;
230 words_lang = dictDir() + "/words." + lang; 228 words_lang = dictDir() + "/words." + lang;
231 QString dawgfilename_lang = dawgfilename + "." + lang; 229 QString dawgfilename_lang = dawgfilename + "." + lang;
232 if ( QFile::exists(dawgfilename_lang) || 230 if ( QFile::exists(dawgfilename_lang) ||
233 QFile::exists(words_lang) ) { 231 QFile::exists(words_lang) ) {
234 dawgfilename = dawgfilename_lang; 232 dawgfilename = dawgfilename_lang;
235 break; 233 break;
236 } 234 }
237 } 235 }
238 QFile dawgfile(dawgfilename); 236 QFile dawgfile(dawgfilename);
239 237
240 if ( !dawgfile.exists() ) { 238 if ( !dawgfile.exists() ) {
241 QString fn = dictDir() + "/words"; 239 QString fn = dictDir() + "/words";
242 if ( QFile::exists(words_lang) ) 240 if ( QFile::exists(words_lang) )
243 fn = words_lang; 241 fn = words_lang;
244 QFile in(fn); 242 QFile in(fn);
245 if ( in.open(IO_ReadOnly) ) { 243 if ( in.open(IO_ReadOnly) ) {
246 fixed_dawg->createFromWords(&in); 244 fixed_dawg->createFromWords(&in);
247 dawgfile.open(IO_WriteOnly); 245 dawgfile.open(IO_WriteOnly);
248 fixed_dawg->write(&dawgfile); 246 fixed_dawg->write(&dawgfile);
249 dawgfile.close(); 247 dawgfile.close();
250 } 248 }
251 } else { 249 } else {
252 fixed_dawg->readFile(dawgfilename); 250 fixed_dawg->readFile(dawgfilename);
253 } 251 }
254 } 252 }
255 253
256 return *fixed_dawg; 254 return *fixed_dawg;
257} 255}
258 256
259/*! 257/*!
260 Returns the changeable QDawg that contains general 258 Returns the changeable QDawg that contains general
261 words for the current locale. 259 words for the current locale.
262 260
263 \sa fixedDawg() 261 \sa fixedDawg()
264*/ 262*/
265const QDawg& Global::addedDawg() 263const QDawg& Global::addedDawg()
266{ 264{
267 return dawg("local"); 265 return dawg("local");
268} 266}
269 267
270/*! 268/*!
271 Returns the QDawg with the given \a name. 269 Returns the QDawg with the given \a name.
272 This is an application-specific word list. 270 This is an application-specific word list.
273 271
274 \a name should not contain "/". 272 \a name should not contain "/".
275*/ 273*/
276const QDawg& Global::dawg(const QString& name) 274const QDawg& Global::dawg(const QString& name)
277{ 275{
278 createDocDir(); 276 createDocDir();
279 if ( !named_dawg ) 277 if ( !named_dawg )
280 named_dawg = new QDict<QDawg>; 278 named_dawg = new QDict<QDawg>;
281 QDawg* r = named_dawg->find(name); 279 QDawg* r = named_dawg->find(name);
282 if ( !r ) { 280 if ( !r ) {
283 r = new QDawg; 281 r = new QDawg;
284 named_dawg->insert(name,r); 282 named_dawg->insert(name,r);
285 QString dawgfilename = applicationFileName("Dictionary", name ) + ".dawg"; 283 QString dawgfilename = applicationFileName("Dictionary", name ) + ".dawg";
286 QFile dawgfile(dawgfilename); 284 QFile dawgfile(dawgfilename);
287 if ( dawgfile.open(IO_ReadOnly) ) 285 if ( dawgfile.open(IO_ReadOnly) )
288 r->readFile(dawgfilename); 286 r->readFile(dawgfilename);
289 } 287 }
290 return *r; 288 return *r;
291} 289}
292 290
293/*! 291/*!
294 \overload 292 \overload
295 Adds \a wordlist to the addedDawg(). 293 Adds \a wordlist to the addedDawg().
296 294
297 Note that the addition of words persists between program executions 295 Note that the addition of words persists between program executions
298 (they are saved in the dictionary files), so you should confirm the 296 (they are saved in the dictionary files), so you should confirm the
299 words with the user before adding them. 297 words with the user before adding them.
300*/ 298*/
301void Global::addWords(const QStringList& wordlist) 299void Global::addWords(const QStringList& wordlist)
302{ 300{
303 addWords("local",wordlist); 301 addWords("local",wordlist);
304} 302}
305 303
306/*! 304/*!
307 \overload 305 \overload
308 Adds \a wordlist to the addedDawg(). 306 Adds \a wordlist to the addedDawg().
309 307
310 Note that the addition of words persists between program executions 308 Note that the addition of words persists between program executions
311 (they are saved in the dictionary files), so you should confirm the 309 (they are saved in the dictionary files), so you should confirm the
312 words with the user before adding them. 310 words with the user before adding them.
313*/ 311*/
314void Global::addWords(const QString& dictname, const QStringList& wordlist) 312void Global::addWords(const QString& dictname, const QStringList& wordlist)
315{ 313{
316 QDawg& d = (QDawg&)dawg(dictname); 314 QDawg& d = (QDawg&)dawg(dictname);
317 QStringList all = d.allWords() + wordlist; 315 QStringList all = d.allWords() + wordlist;
318 d.createFromWords(all); 316 d.createFromWords(all);
319 317
320 QString dawgfilename = applicationFileName("Dictionary", dictname) + ".dawg"; 318 QString dawgfilename = applicationFileName("Dictionary", dictname) + ".dawg";
321 QFile dawgfile(dawgfilename); 319 QFile dawgfile(dawgfilename);
322 if ( dawgfile.open(IO_WriteOnly) ) { 320 if ( dawgfile.open(IO_WriteOnly) ) {
323 d.write(&dawgfile); 321 d.write(&dawgfile);
324 dawgfile.close(); 322 dawgfile.close();
325 } 323 }
326 324
327 // #### Re-read the dawg here if we use mmap(). 325 // #### Re-read the dawg here if we use mmap().
328 326
329 // #### Signal other processes to re-read. 327 // #### Signal other processes to re-read.
330} 328}
331 329
332 330
333/*! 331/*!
334 Returns the full path for the application called \a appname, with the 332 Returns the full path for the application called \a appname, with the
335 given \a filename. Returns QString::null if there was a problem creating 333 given \a filename. Returns QString::null if there was a problem creating
336 the directory tree for \a appname. 334 the directory tree for \a appname.
337 If \a filename contains "/", it is the caller's responsibility to 335 If \a filename contains "/", it is the caller's responsibility to
338 ensure that those directories exist. 336 ensure that those directories exist.
339*/ 337*/
340QString Global::applicationFileName(const QString& appname, const QString& filename) 338QString Global::applicationFileName(const QString& appname, const QString& filename)
341{ 339{
342 QDir d; 340 QDir d;
343 QString r = getenv("HOME"); 341 QString r = getenv("HOME");
344 r += "/Applications/"; 342 r += "/Applications/";
345 if ( !QFile::exists( r ) ) 343 if ( !QFile::exists( r ) )
346 if ( d.mkdir(r) == false ) 344 if ( d.mkdir(r) == false )
347 return QString::null; 345 return QString::null;
348 r += appname; 346 r += appname;
349 if ( !QFile::exists( r ) ) 347 if ( !QFile::exists( r ) )
350 if ( d.mkdir(r) == false ) 348 if ( d.mkdir(r) == false )
351 return QString::null; 349 return QString::null;
352 r += "/"; r += filename; 350 r += "/"; r += filename;
353 return r; 351 return r;
354} 352}
355 353
356/*! 354/*!
357 \internal 355 \internal
358*/ 356*/
359void Global::createDocDir() 357void Global::createDocDir()
360{ 358{
361 if ( !docDirCreated ) { 359 if ( !docDirCreated ) {
362 docDirCreated = TRUE; 360 docDirCreated = TRUE;
363 mkdir( QPEApplication::documentDir().latin1(), 0755 ); 361 mkdir( QPEApplication::documentDir().latin1(), 0755 );
364 } 362 }
365} 363}
366 364
367 365
368/*! 366/*!
369 Displays a status \a message to the user. This usually appears 367 Displays a status \a message to the user. This usually appears
370 in the taskbar for a short amount of time, then disappears. 368 in the taskbar for a short amount of time, then disappears.
371*/ 369*/
372void Global::statusMessage(const QString& message) 370void Global::statusMessage(const QString& message)
373{ 371{
374#if !defined(QT_NO_COP) 372#if !defined(QT_NO_COP)
375 QCopEnvelope e( "QPE/TaskBar", "message(QString)" ); 373 QCopEnvelope e( "QPE/TaskBar", "message(QString)" );
376 e << message; 374 e << message;
377#endif 375#endif
378} 376}
379 377
380/*! 378/*!
381 \internal 379 \internal
382*/ 380*/
383void Global::applyStyle() 381void Global::applyStyle()
384{ 382{
385#if !defined(QT_NO_COP) 383#if !defined(QT_NO_COP)
386 QCopChannel::send( "QPE/System", "applyStyle()" ); 384 QCopChannel::send( "QPE/System", "applyStyle()" );
387#else 385#else
388 ((QPEApplication *)qApp)->applyStyle(); // apply without needing QCop for floppy version 386 ((QPEApplication *)qApp)->applyStyle(); // apply without needing QCop for floppy version
389#endif 387#endif
390} 388}
391 389
392/*! 390/*!
393 \internal 391 \internal
394*/ 392*/
395QWidget *Global::shutdown( bool ) 393QWidget *Global::shutdown( bool )
396{ 394{
397#if !defined(QT_NO_COP) 395#if !defined(QT_NO_COP)
398 QCopChannel::send( "QPE/System", "shutdown()" ); 396 QCopChannel::send( "QPE/System", "shutdown()" );
399#endif 397#endif
400 return 0; 398 return 0;
401} 399}
402 400
403/*! 401/*!
404 \internal 402 \internal
405*/ 403*/
406QWidget *Global::restart( bool ) 404QWidget *Global::restart( bool )
407{ 405{
408#if !defined(QT_NO_COP) 406#if !defined(QT_NO_COP)
409 QCopChannel::send( "QPE/System", "restart()" ); 407 QCopChannel::send( "QPE/System", "restart()" );
410#endif 408#endif
411 return 0; 409 return 0;
412} 410}
413 411
414/*! 412/*!
415 Explicitly show the current input method. 413 Explicitly show the current input method.
416 414
417 Input methods are indicated in the taskbar by a small icon. If the 415 Input methods are indicated in the taskbar by a small icon. If the
418 input method is activated (shown) then it takes up some proportion 416 input method is activated (shown) then it takes up some proportion
419 of the bottom of the screen, to allow the user to interact (input 417 of the bottom of the screen, to allow the user to interact (input
420 characters) with it. 418 characters) with it.
421 419
422 \sa hideInputMethod() 420 \sa hideInputMethod()
423*/ 421*/
424void Global::showInputMethod() 422void Global::showInputMethod()
425{ 423{
426#if !defined(QT_NO_COP) 424#if !defined(QT_NO_COP)
427 QCopChannel::send( "QPE/TaskBar", "showInputMethod()" ); 425 QCopChannel::send( "QPE/TaskBar", "showInputMethod()" );
428#endif 426#endif
429} 427}
430 428
431/*! 429/*!
432 Explicitly hide the current input method. 430 Explicitly hide the current input method.
433 431
434 The current input method is still indicated in the taskbar, but no 432 The current input method is still indicated in the taskbar, but no
435 longer takes up screen space, and can no longer be interacted with. 433 longer takes up screen space, and can no longer be interacted with.
436 434
437 \sa showInputMethod() 435 \sa showInputMethod()
438*/ 436*/
439void Global::hideInputMethod() 437void Global::hideInputMethod()
440{ 438{
441#if !defined(QT_NO_COP) 439#if !defined(QT_NO_COP)
442 QCopChannel::send( "QPE/TaskBar", "hideInputMethod()" ); 440 QCopChannel::send( "QPE/TaskBar", "hideInputMethod()" );
443#endif 441#endif
444} 442}
445 443
446 444
447/*! 445/*!
448 \internal 446 \internal
449*/ 447*/
450bool Global::isBuiltinCommand( const QString &name ) 448bool Global::isBuiltinCommand( const QString &name )
451{ 449{
452 if(!builtin) 450 if(!builtin)
453 return FALSE; // yes, it can happen 451 return FALSE; // yes, it can happen
454 for (int i = 0; builtin[i].file; i++) { 452 for (int i = 0; builtin[i].file; i++) {
455 if ( builtin[i].file == name ) { 453 if ( builtin[i].file == name ) {
456 return TRUE; 454 return TRUE;
457 } 455 }
458 } 456 }
459 return FALSE; 457 return FALSE;
460} 458}
461 459
462Global::Command* Global::builtin=0; 460Global::Command* Global::builtin=0;
463QGuardedPtr<QWidget> *Global::running=0; 461QGuardedPtr<QWidget> *Global::running=0;
464 462
465/*! 463/*!
466 \class Global::Command 464 \class Global::Command
467 \brief The Global::Command class is internal. 465 \brief The Global::Command class is internal.
468 \internal 466 \internal
469*/ 467*/
470 468
471/*! 469/*!
472 \internal 470 \internal
473*/ 471*/
474void Global::setBuiltinCommands( Command* list ) 472void Global::setBuiltinCommands( Command* list )
475{ 473{
476 if ( running ) 474 if ( running )
477 delete [] running; 475 delete [] running;
478 476
479 builtin = list; 477 builtin = list;
480 int count = 0; 478 int count = 0;
481 if (!builtin) 479 if (!builtin)
482 return; 480 return;
483 while ( builtin[count].file ) 481 while ( builtin[count].file )
484 count++; 482 count++;
485 483
486 running = new QGuardedPtr<QWidget> [ count ]; 484 running = new QGuardedPtr<QWidget> [ count ];
487} 485}
488 486
489/*! 487/*!
490 \internal 488 \internal
491*/ 489*/
492void Global::setDocument( QWidget* receiver, const QString& document ) 490void Global::setDocument( QWidget* receiver, const QString& document )
493{ 491{
494 Emitter emitter(receiver,document); 492 Emitter emitter(receiver,document);
495} 493}
496 494
497/*! 495/*!
498 \internal 496 \internal
499*/ 497*/
500bool Global::terminateBuiltin( const QString& n ) 498bool Global::terminateBuiltin( const QString& n )
501{ 499{
502 if (!builtin) 500 if (!builtin)
503 return FALSE; 501 return FALSE;
504 for (int i = 0; builtin[i].file; i++) { 502 for (int i = 0; builtin[i].file; i++) {
505 if ( builtin[i].file == n ) { 503 if ( builtin[i].file == n ) {
506 delete running[i]; 504 delete running[i];
507 return TRUE; 505 return TRUE;
508 } 506 }
509 } 507 }
510 return FALSE; 508 return FALSE;
511} 509}
512 510
513/*! 511/*!
514 \internal 512 \internal
515*/ 513*/
516void Global::terminate( const AppLnk* app ) 514void Global::terminate( const AppLnk* app )
517{ 515{
518 //if ( terminateBuiltin(app->exec()) ) return; // maybe? haven't tried this 516 //if ( terminateBuiltin(app->exec()) ) return; // maybe? haven't tried this
519 517
520#ifndef QT_NO_COP 518#ifndef QT_NO_COP
521 QCString channel = "QPE/Application/" + app->exec().utf8(); 519 QCString channel = "QPE/Application/" + app->exec().utf8();
522 if ( QCopChannel::isRegistered(channel) ) { 520 if ( QCopChannel::isRegistered(channel) ) {
523 QCopEnvelope e(channel, "quit()"); 521 QCopEnvelope e(channel, "quit()");
524 } 522 }
525#endif 523#endif
526} 524}
527 525
528/*! 526/*!
529 Low-level function to run command \a c. 527 Low-level function to run command \a c.
530 528
531 \warning Do not use this function. Use execute instead. 529 \warning Do not use this function. Use execute instead.
532 530
533 \sa execute() 531 \sa execute()
534*/ 532*/
535void Global::invoke(const QString &c) 533void Global::invoke(const QString &c)
536{ 534{
537 // Convert the command line in to a list of arguments 535 // Convert the command line in to a list of arguments
538 QStringList list = QStringList::split(QRegExp(" *"),c); 536 QStringList list = QStringList::split(QRegExp(" *"),c);
539 537
540#if !defined(QT_NO_COP) 538#if !defined(QT_NO_COP)
541 QString ap=list[0]; 539 QString ap=list[0];
542 // see if the application is already running 540 // see if the application is already running
543 // XXX should lock file /tmp/qcop-msg-ap 541 // XXX should lock file /tmp/qcop-msg-ap
544 if ( QCopChannel::isRegistered( ("QPE/Application/" + ap).latin1() ) ) { 542 if ( QCopChannel::isRegistered( ("QPE/Application/" + ap).latin1() ) ) {
545 // If the channel is already register, the app is already running, so show it. 543 // If the channel is already register, the app is already running, so show it.
546 { QCopEnvelope env( ("QPE/Application/" + ap).latin1(), "raise()" ); } 544 { QCopEnvelope env( ("QPE/Application/" + ap).latin1(), "raise()" ); }
547 545
548 //QCopEnvelope e("QPE/System", "notBusy(QString)" ); 546 //QCopEnvelope e("QPE/System", "notBusy(QString)" );
549 //e << ap; 547 //e << ap;
550 return; 548 return;
551 } 549 }
552 // XXX should unlock file /tmp/qcop-msg-ap 550 // XXX should unlock file /tmp/qcop-msg-ap
553 //see if it is being started 551 //see if it is being started
554 if ( StartingAppList::isStarting( ap ) ) { 552 if ( StartingAppList::isStarting( ap ) ) {
555 // FIXME take it out for now, since it leads to a much to short showing of wait if 553 // FIXME take it out for now, since it leads to a much to short showing of wait if
556 // some entry is clicked. 554 // some entry is clicked.
557 // Real cause is that ::execute is called twice for document tab. But it would need some larger changes 555 // Real cause is that ::execute is called twice for document tab. But it would need some larger changes
558 // to fix that, and with future syncs with qtopia 1.6 it will change anyway big time since somebody there 556 // to fix that, and with future syncs with qtopia 1.6 it will change anyway big time since somebody there
559 // had the idea that an apploader belongs to the launcher ... 557 // had the idea that an apploader belongs to the launcher ...
560 //QCopEnvelope e("QPE/System", "notBusy(QString)" ); 558 //QCopEnvelope e("QPE/System", "notBusy(QString)" );
561 //e << ap; 559 //e << ap;
562 return; 560 return;
563 } 561 }
564 562
565#endif 563#endif
566 564
567#ifdef QT_NO_QWS_MULTIPROCESS 565#ifdef QT_NO_QWS_MULTIPROCESS
568 QMessageBox::warning( 0, "Error", "Could not find the application " + c, "Ok", 0, 0, 0, 1 ); 566 QMessageBox::warning( 0, "Error", "Could not find the application " + c, "Ok", 0, 0, 0, 1 );
569#else 567#else
570 568
571 QStrList slist; 569 QStrList slist;
572 unsigned int j; 570 unsigned int j;
573 for ( j = 0; j < list.count(); j++ ) 571 for ( j = 0; j < list.count(); j++ )
574 slist.append( list[j].utf8() ); 572 slist.append( list[j].utf8() );
575 573
576 const char **args = new (const char *)[slist.count() + 1]; 574 const char **args = new (const char *)[slist.count() + 1];
577 for ( j = 0; j < slist.count(); j++ ) 575 for ( j = 0; j < slist.count(); j++ )
578 args[j] = slist.at(j); 576 args[j] = slist.at(j);
579 args[j] = NULL; 577 args[j] = NULL;
580 578
581#if !defined(QT_NO_COP) 579#if !defined(QT_NO_COP)
582 // an attempt to show a wait... 580 // an attempt to show a wait...
583 // more logic should be used, but this will be fine for the moment... 581 // more logic should be used, but this will be fine for the moment...
584 QCopEnvelope ( "QPE/System", "busy()" ); 582 QCopEnvelope ( "QPE/System", "busy()" );
585#endif 583#endif
586 584
587#ifdef HAVE_QUICKEXEC 585#ifdef HAVE_QUICKEXEC
588#ifdef Q_OS_MACX 586#ifdef Q_OS_MACX
589 QString libexe = qpeDir()+"/binlib/lib"+args[0] + ".dylib"; 587 QString libexe = qpeDir()+"/binlib/lib"+args[0] + ".dylib";
590#else 588#else
591 QString libexe = qpeDir()+"/binlib/lib"+args[0] + ".so"; 589 QString libexe = qpeDir()+"/binlib/lib"+args[0] + ".so";
592#endif 590#endif
593 qDebug("libfile = %s", libexe.latin1() ); 591 qDebug("libfile = %s", libexe.latin1() );
594 if ( QFile::exists( libexe ) ) { 592 if ( QFile::exists( libexe ) ) {
595 qDebug("calling quickexec %s", libexe.latin1() ); 593 qDebug("calling quickexec %s", libexe.latin1() );
596 quickexecv( libexe.utf8().data(), (const char **)args ); 594 quickexecv( libexe.utf8().data(), (const char **)args );
597 } else 595 } else
598#endif 596#endif
599 { 597 {
600 bool success = false; 598 bool success = false;
601 int pfd [2]; 599 int pfd [2];
602 if ( ::pipe ( pfd ) < 0 ) 600 if ( ::pipe ( pfd ) < 0 )
603 pfd [0] = pfd [1] = -1; 601 pfd [0] = pfd [1] = -1;
604 602
605 pid_t pid = ::fork ( ); 603 pid_t pid = ::fork ( );
606 604
607 if ( pid == 0 ) { // child 605 if ( pid == 0 ) { // child
608 for ( int fd = 3; fd < 100; fd++ ) { 606 for ( int fd = 3; fd < 100; fd++ ) {
609 if ( fd != pfd [1] ) 607 if ( fd != pfd [1] )
610 ::close ( fd ); 608 ::close ( fd );
611 } 609 }
612 ::setpgid ( ::getpid ( ), ::getppid ( )); 610 ::setpgid ( ::getpid ( ), ::getppid ( ));
613 611
614 // Closing of fd[1] indicates that the execvp succeeded! 612 // Closing of fd[1] indicates that the execvp succeeded!
615 if ( pfd [1] >= 0 ) 613 if ( pfd [1] >= 0 )
616 ::fcntl ( pfd [1], F_SETFD, FD_CLOEXEC ); 614 ::fcntl ( pfd [1], F_SETFD, FD_CLOEXEC );
617 615
618 // Try bindir first, so that foo/bar works too 616 // Try bindir first, so that foo/bar works too
619 ::execv ( qpeDir ( ) + "/bin/" + args [0], (char * const *) args ); 617 ::execv ( qpeDir ( ) + "/bin/" + args [0], (char * const *) args );
620 ::execvp ( args [0], (char * const *) args ); 618 ::execvp ( args [0], (char * const *) args );
621 619
622 char resultByte = 1; 620 char resultByte = 1;
623 if ( pfd [1] >= 0 ) 621 if ( pfd [1] >= 0 )
624 ::write ( pfd [1], &resultByte, 1 ); 622 ::write ( pfd [1], &resultByte, 1 );
625 ::_exit ( -1 ); 623 ::_exit ( -1 );
626 } 624 }
627 else if ( pid > 0 ) { 625 else if ( pid > 0 ) {
628 success = true; 626 success = true;
629 627
630 if ( pfd [1] >= 0 ) 628 if ( pfd [1] >= 0 )
631 ::close ( pfd [1] ); 629 ::close ( pfd [1] );
632 if ( pfd [0] >= 0 ) { 630 if ( pfd [0] >= 0 ) {
633 while ( true ) { 631 while ( true ) {
634 char resultByte; 632 char resultByte;
635 int n = ::read ( pfd [0], &resultByte, 1 ); 633 int n = ::read ( pfd [0], &resultByte, 1 );
636 if ( n == 1 ) { 634 if ( n == 1 ) {
637 success = false; 635 success = false;
638 break; 636 break;
639 } 637 }
640 if (( n == -1 ) && (( errno == ECHILD ) || ( errno == EINTR ))) 638 if (( n == -1 ) && (( errno == ECHILD ) || ( errno == EINTR )))
641 continue; 639 continue;
642 640
643 break; // success 641 break; // success
644 } 642 }
645 ::close ( pfd [0] ); 643 ::close ( pfd [0] );
646 } 644 }
647 } 645 }
648 if ( success ) 646 if ( success )
649 StartingAppList::add( list[0] ); 647 StartingAppList::add( list[0] );
650 else 648 else
651 QMessageBox::warning( 0, "Error", "Could not start the application " + c, "Ok", 0, 0, 0, 1 ); 649 QMessageBox::warning( 0, "Error", "Could not start the application " + c, "Ok", 0, 0, 0, 1 );
652 } 650 }
653#endif //QT_NO_QWS_MULTIPROCESS 651#endif //QT_NO_QWS_MULTIPROCESS
654} 652}
655 653
656 654
657/*! 655/*!
658 Executes the application identfied by \a c, passing \a 656 Executes the application identfied by \a c, passing \a
659 document if it isn't null. 657 document if it isn't null.
660 658
661 Note that a better approach might be to send a QCop message to the 659 Note that a better approach might be to send a QCop message to the
662 application's QPE/Application/\e{appname} channel. 660 application's QPE/Application/\e{appname} channel.
663*/ 661*/
664void Global::execute( const QString &c, const QString& document ) 662void Global::execute( const QString &c, const QString& document )
665{ 663{
666 // ask the server to do the work 664 // ask the server to do the work
667#if !defined(QT_NO_COP) 665#if !defined(QT_NO_COP)
668 if ( document.isNull() ) { 666 if ( document.isNull() ) {
669 QCopEnvelope e( "QPE/System", "execute(QString)" ); 667 QCopEnvelope e( "QPE/System", "execute(QString)" );
670 e << c; 668 e << c;
671 } else { 669 } else {
672 QCopEnvelope e( "QPE/System", "execute(QString,QString)" ); 670 QCopEnvelope e( "QPE/System", "execute(QString,QString)" );
673 e << c << document; 671 e << c << document;
674 } 672 }
675#endif 673#endif
676 return; 674 return;
677} 675}
678 676
679/*! 677/*!
680 Returns the string \a s with the characters '\', '"', and '$' quoted 678 Returns the string \a s with the characters '\', '"', and '$' quoted
681 by a preceeding '\'. 679 by a preceeding '\'.
682 680
683 \sa stringQuote() 681 \sa stringQuote()
684*/ 682*/
685QString Global::shellQuote(const QString& s) 683QString Global::shellQuote(const QString& s)
686{ 684{
687 QString r="\""; 685 QString r="\"";
688 for (int i=0; i<(int)s.length(); i++) { 686 for (int i=0; i<(int)s.length(); i++) {
689 char c = s[i].latin1(); 687 char c = s[i].latin1();
690 switch (c) { 688 switch (c) {
691 case '\\': case '"': case '$': 689 case '\\': case '"': case '$':
692 r+="\\"; 690 r+="\\";
693 } 691 }
694 r += s[i]; 692 r += s[i];
695 } 693 }
696 r += "\""; 694 r += "\"";
697 return r; 695 return r;
698} 696}
699 697
700/*! 698/*!
701 Returns the string \a s with the characters '\' and '"' quoted by a 699 Returns the string \a s with the characters '\' and '"' quoted by a
702 preceeding '\'. 700 preceeding '\'.
703 701
704 \sa shellQuote() 702 \sa shellQuote()
705*/ 703*/
706QString Global::stringQuote(const QString& s) 704QString Global::stringQuote(const QString& s)
707{ 705{
708 QString r="\""; 706 QString r="\"";
709 for (int i=0; i<(int)s.length(); i++) { 707 for (int i=0; i<(int)s.length(); i++) {
710 char c = s[i].latin1(); 708 char c = s[i].latin1();
711 switch (c) { 709 switch (c) {
712 case '\\': case '"': 710 case '\\': case '"':
713 r+="\\"; 711 r+="\\";
714 } 712 }
715 r += s[i]; 713 r += s[i];
716 } 714 }
717 r += "\""; 715 r += "\"";
718 return r; 716 return r;
719} 717}
720 718
721/*! 719/*!
722 Finds all documents on the system's document directories which 720 Finds all documents on the system's document directories which
723 match the filter \a mimefilter, and appends the resulting DocLnk 721 match the filter \a mimefilter, and appends the resulting DocLnk
724 objects to \a folder. 722 objects to \a folder.
725*/ 723*/
726void Global::findDocuments(DocLnkSet* folder, const QString &mimefilter) 724void Global::findDocuments(DocLnkSet* folder, const QString &mimefilter)
727{ 725{
728 QString homedocs = QString(getenv("HOME")) + "/Documents"; 726 QString homedocs = QString(getenv("HOME")) + "/Documents";
729 DocLnkSet d(homedocs,mimefilter); 727 DocLnkSet d(homedocs,mimefilter);
730 folder->appendFrom(d); 728 folder->appendFrom(d);
731 /** let's do intellegint way of searching these files 729 /** let's do intellegint way of searching these files
732 * a) the user don't want to check mediums global 730 * a) the user don't want to check mediums global
733 * b) the user wants to check but use the global options for it 731 * b) the user wants to check but use the global options for it
734 * c) the user wants to check it but not this medium 732 * c) the user wants to check it but not this medium
735 * d) the user wants to check and this medium as well 733 * d) the user wants to check and this medium as well
736 * 734 *
737 * In all cases we need to apply a different mimefilter to 735 * In all cases we need to apply a different mimefilter to
738 * the medium. 736 * the medium.
739 * a) mimefilter.isEmpty() we need to apply the responding filter 737 * a) mimefilter.isEmpty() we need to apply the responding filter
740 * either the global or the one on the medium 738 * either the global or the one on the medium
741 * 739 *
742 * b) mimefilter is set to an application we need to find out if the 740 * b) mimefilter is set to an application we need to find out if the
743 * mimetypes are included in the mime mask of the medium 741 * mimetypes are included in the mime mask of the medium
744 */ 742 */
745 StorageInfo storage; 743 StorageInfo storage;
746 const QList<FileSystem> &fs = storage.fileSystems(); 744 const QList<FileSystem> &fs = storage.fileSystems();
747 QListIterator<FileSystem> it ( fs ); 745 QListIterator<FileSystem> it ( fs );
748 for ( ; it.current(); ++it ) { 746 for ( ; it.current(); ++it ) {
749 if ( (*it)->isRemovable() ) { // let's find out if we should search on it 747 if ( (*it)->isRemovable() ) { // let's find out if we should search on it
750 // this is a candidate look at the cf and see if we should search on it 748 // this is a candidate look at the cf and see if we should search on it
751 QString path = (*it)->path(); 749 QString path = (*it)->path();
752 Config conf((*it)->path() + "/.opiestorage.cf", Config::File ); 750 Config conf((*it)->path() + "/.opiestorage.cf", Config::File );
753 conf.setGroup("main"); 751 conf.setGroup("main");
754 if (!conf.readBoolEntry("check",true)) { 752 if (!conf.readBoolEntry("check",true)) {
755 continue; 753 continue;
756 } 754 }
757 conf.setGroup("subdirs"); 755 conf.setGroup("subdirs");
758 if (conf.readBoolEntry("wholemedia",true)) { 756 if (conf.readBoolEntry("wholemedia",true)) {
759 DocLnkSet ide( path,mimefilter); 757 DocLnkSet ide( path,mimefilter);
760 folder->appendFrom(ide); 758 folder->appendFrom(ide);
761 } else { 759 } else {
762 QStringList subDirs = conf.readListEntry("subdirs",':'); 760 QStringList subDirs = conf.readListEntry("subdirs",':');
763 if (subDirs.isEmpty()) { 761 if (subDirs.isEmpty()) {
764 subDirs.append("Documents"); 762 subDirs.append("Documents");
765 } 763 }
766 for (unsigned c = 0; c < subDirs.count();++c) { 764 for (unsigned c = 0; c < subDirs.count();++c) {
767 DocLnkSet ide( path+"/"+subDirs[c], mimefilter ); 765 DocLnkSet ide( path+"/"+subDirs[c], mimefilter );
768 folder->appendFrom(ide); 766 folder->appendFrom(ide);
769 } 767 }
770 } 768 }
771 } else if ( (*it)->disk() == "/dev/mtdblock6" || (*it)->disk() == "tmpfs" ) { 769 } else if ( (*it)->disk() == "/dev/mtdblock6" || (*it)->disk() == "tmpfs" ) {
772 QString path = (*it)->path() + "/Documents"; 770 QString path = (*it)->path() + "/Documents";
773 DocLnkSet ide( path, mimefilter ); 771 DocLnkSet ide( path, mimefilter );
774 folder->appendFrom(ide); 772 folder->appendFrom(ide);
775 } 773 }
776 } 774 }
777} 775}
778 776
779QStringList Global::languageList() 777QStringList Global::languageList()
780{ 778{
781 QString lang = getenv("LANG"); 779 QString lang = getenv("LANG");
782 QStringList langs; 780 QStringList langs;
783 langs.append(lang); 781 langs.append(lang);
784 int i = lang.find("."); 782 int i = lang.find(".");
785 if ( i > 0 ) 783 if ( i > 0 )
786 lang = lang.left( i ); 784 lang = lang.left( i );
787 i = lang.find( "_" ); 785 i = lang.find( "_" );
788 if ( i > 0 ) 786 if ( i > 0 )
789 langs.append(lang.left(i)); 787 langs.append(lang.left(i));
790 return langs; 788 return langs;
791} 789}
792 790
793QStringList Global::helpPath() 791QStringList Global::helpPath()
794{ 792{
795 QString qpeDir = QPEApplication::qpeDir(); 793 QString qpeDir = QPEApplication::qpeDir();
796 QStringList path; 794 QStringList path;
797 QStringList langs = Global::languageList(); 795 QStringList langs = Global::languageList();
798 for (QStringList::ConstIterator it = langs.fromLast(); it!=langs.end(); --it) { 796 for (QStringList::ConstIterator it = langs.fromLast(); it!=langs.end(); --it) {
799 QString lang = *it; 797 QString lang = *it;
800 if ( !lang.isEmpty() ) 798 if ( !lang.isEmpty() )
801 path += qpeDir + "/help/" + lang + "/html"; 799 path += qpeDir + "/help/" + lang + "/html";
802 } 800 }
803 path += qpeDir + "/pics"; 801 path += qpeDir + "/pics";
804 path += qpeDir + "/help/html"; 802 path += qpeDir + "/help/html";
805 /* we even put english into the en dir so try it as fallback as well for opie */ 803 /* we even put english into the en dir so try it as fallback as well for opie */
806 path += qpeDir + "/help/en/html"; 804 path += qpeDir + "/help/en/html";
807 path += qpeDir + "/docs"; 805 path += qpeDir + "/docs";
808 806
809 807
810 return path; 808 return path;
811} 809}
812 810
813 811
814#include "global.moc" 812#include "global.moc"
diff --git a/library/imageedit.cpp b/library/imageedit.cpp
index caa538a..3a559f4 100644
--- a/library/imageedit.cpp
+++ b/library/imageedit.cpp
@@ -1,97 +1,96 @@
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 "imageedit.h" 20#include "imageedit.h"
21#include <qpainter.h>
22 21
23ImageEdit::ImageEdit( QWidget *parent, const char *name) 22ImageEdit::ImageEdit( QWidget *parent, const char *name)
24 : QScrollView( parent, name, WNorthWestGravity | WResizeNoErase ), buffer() 23 : QScrollView( parent, name, WNorthWestGravity | WResizeNoErase ), buffer()
25{ 24{
26 buffer.resize( size() ); 25 buffer.resize( size() );
27 buffer.fill( colorGroup().color( QColorGroup::Base ) ); 26 buffer.fill( colorGroup().color( QColorGroup::Base ) );
28} 27}
29 28
30ImageEdit::~ImageEdit() 29ImageEdit::~ImageEdit()
31{ 30{
32 31
33} 32}
34 33
35void ImageEdit::contentsMousePressEvent( QMouseEvent *e ) 34void ImageEdit::contentsMousePressEvent( QMouseEvent *e )
36{ 35{
37 lastPos = e->pos(); 36 lastPos = e->pos();
38} 37}
39 38
40void ImageEdit::contentsMouseMoveEvent( QMouseEvent *e ) 39void ImageEdit::contentsMouseMoveEvent( QMouseEvent *e )
41{ 40{
42 QPainter pw( viewport() ); 41 QPainter pw( viewport() );
43 QPainter pb( &buffer ); 42 QPainter pb( &buffer );
44 pb.drawLine( lastPos, e->pos() ); 43 pb.drawLine( lastPos, e->pos() );
45 pw.drawLine( contentsToViewport( lastPos ), 44 pw.drawLine( contentsToViewport( lastPos ),
46 contentsToViewport( e->pos() ) ); 45 contentsToViewport( e->pos() ) );
47 lastPos = e->pos(); 46 lastPos = e->pos();
48} 47}
49 48
50void ImageEdit::contentsMouseReleaseEvent( QMouseEvent * ) 49void ImageEdit::contentsMouseReleaseEvent( QMouseEvent * )
51{ 50{
52} 51}
53 52
54void ImageEdit::viewportResizeEvent( QResizeEvent *e ) 53void ImageEdit::viewportResizeEvent( QResizeEvent *e )
55{ 54{
56 enlargeBuffer(e->size()); 55 enlargeBuffer(e->size());
57} 56}
58 57
59void ImageEdit::enlargeBuffer( const QSize& sz ) 58void ImageEdit::enlargeBuffer( const QSize& sz )
60{ 59{
61 QSize osz = buffer.size(); 60 QSize osz = buffer.size();
62 QSize nsz( QMAX( osz.width(), sz.width() ), QMAX( osz.height(), sz.height() ) ); 61 QSize nsz( QMAX( osz.width(), sz.width() ), QMAX( osz.height(), sz.height() ) );
63 buffer.resize( nsz.width(), nsz.height() ); 62 buffer.resize( nsz.width(), nsz.height() );
64 // clear new area 63 // clear new area
65 QPainter p( &buffer ); 64 QPainter p( &buffer );
66 if ( sz.width() > osz.width() ) 65 if ( sz.width() > osz.width() )
67 p.fillRect( osz.width(), 0, sz.width() - osz.width(), nsz.height(), colorGroup().color( QColorGroup::Base ) ); 66 p.fillRect( osz.width(), 0, sz.width() - osz.width(), nsz.height(), colorGroup().color( QColorGroup::Base ) );
68 if ( sz.height() > osz.height() ) 67 if ( sz.height() > osz.height() )
69 p.fillRect( 0, osz.height(), nsz.width(), sz.height() - osz.height(), colorGroup().color( QColorGroup::Base ) ); 68 p.fillRect( 0, osz.height(), nsz.width(), sz.height() - osz.height(), colorGroup().color( QColorGroup::Base ) );
70 p.end(); 69 p.end();
71} 70}
72 71
73void ImageEdit::drawContents( QPainter *p, int cx, int cy, int cw, int ch ) 72void ImageEdit::drawContents( QPainter *p, int cx, int cy, int cw, int ch )
74{ 73{
75 p->drawPixmap( cx, cy, buffer, cx, cy, cw, ch ); 74 p->drawPixmap( cx, cy, buffer, cx, cy, cw, ch );
76} 75}
77 76
78void ImageEdit::setPixmap( const QPixmap &pm ) 77void ImageEdit::setPixmap( const QPixmap &pm )
79{ 78{
80 QSize osz = buffer.size(); 79 QSize osz = buffer.size();
81 if ( pm.width() < osz.width() || pm.height() < osz.height() ) { 80 if ( pm.width() < osz.width() || pm.height() < osz.height() ) {
82 buffer.fill(white); 81 buffer.fill(white);
83 enlargeBuffer( pm.size() ); 82 enlargeBuffer( pm.size() );
84 QPainter p(&buffer); 83 QPainter p(&buffer);
85 p.drawPixmap(0,0,pm); 84 p.drawPixmap(0,0,pm);
86 } else { 85 } else {
87 buffer = pm; 86 buffer = pm;
88 } 87 }
89 resizeContents( buffer.width(), buffer.height() ); 88 resizeContents( buffer.width(), buffer.height() );
90 viewport()->repaint( FALSE ); 89 viewport()->repaint( FALSE );
91} 90}
92 91
93QPixmap ImageEdit::pixmap() const 92QPixmap ImageEdit::pixmap() const
94{ 93{
95 return buffer; 94 return buffer;
96} 95}
97 96
diff --git a/library/ir.cpp b/library/ir.cpp
index b5b726d..32c0925 100644
--- a/library/ir.cpp
+++ b/library/ir.cpp
@@ -1,118 +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 <qstring.h>
24#include "qcopenvelope_qws.h" 23#include "qcopenvelope_qws.h"
25#include <qcopchannel_qws.h>
26#include "applnk.h" 24#include "applnk.h"
27 25
28/*! 26/*!
29 \class Ir ir.h 27 \class Ir ir.h
30 \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
31 infrared communication link. 29 infrared communication link.
32 30
33 Both \link doclnk.html DocLnk\endlink objects and files can be 31 Both \link doclnk.html DocLnk\endlink objects and files can be
34 sent to another device via the infrared link using the send() 32 sent to another device via the infrared link using the send()
35 function. When the send has completed the done() signal is 33 function. When the send has completed the done() signal is
36 emitted. 34 emitted.
37 35
38 The supported() function returns whether the device supports 36 The supported() function returns whether the device supports
39 infrared communication or not. 37 infrared communication or not.
40 38
41 \ingroup qtopiaemb 39 \ingroup qtopiaemb
42*/ 40*/
43 41
44/*! 42/*!
45 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
46 standard QObject parameters. 44 standard QObject parameters.
47*/ 45*/
48Ir::Ir( QObject *parent, const char *name ) 46Ir::Ir( QObject *parent, const char *name )
49 : QObject( parent, name ) 47 : QObject( parent, name )
50{ 48{
51#ifndef QT_NO_COP 49#ifndef QT_NO_COP
52 ch = new QCopChannel( "QPE/Obex" ); 50 ch = new QCopChannel( "QPE/Obex" );
53 connect( ch, SIGNAL(received(const QCString &, const QByteArray &)), 51 connect( ch, SIGNAL(received(const QCString &, const QByteArray &)),
54 this, SLOT(obexMessage( const QCString &, const QByteArray &)) ); 52 this, SLOT(obexMessage( const QCString &, const QByteArray &)) );
55#endif 53#endif
56} 54}
57 55
58/*! 56/*!
59 Returns TRUE if the system supports infrared communication; 57 Returns TRUE if the system supports infrared communication;
60 otherwise returns FALSE. 58 otherwise returns FALSE.
61*/ 59*/
62bool Ir::supported() 60bool Ir::supported()
63{ 61{
64#ifndef QT_NO_COP 62#ifndef QT_NO_COP
65 return QCopChannel::isRegistered( "QPE/Obex" ); 63 return QCopChannel::isRegistered( "QPE/Obex" );
66#endif 64#endif
67} 65}
68 66
69/*! 67/*!
70 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
71 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
72 is in progress. The optional \a mimetype parameter specifies the 70 is in progress. The optional \a mimetype parameter specifies the
73 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
74 determined by the the filename's suffix. 72 determined by the the filename's suffix.
75 73
76 \sa done() 74 \sa done()
77*/ 75*/
78void Ir::send( const QString &fn, const QString &description, const QString &mimetype) 76void Ir::send( const QString &fn, const QString &description, const QString &mimetype)
79{ 77{
80 if ( !filename.isEmpty() ) return; 78 if ( !filename.isEmpty() ) return;
81 filename = fn; 79 filename = fn;
82#ifndef QT_NO_COP 80#ifndef QT_NO_COP
83 QCopEnvelope e("QPE/Obex", "send(QString,QString,QString)"); 81 QCopEnvelope e("QPE/Obex", "send(QString,QString,QString)");
84 e << description << filename << mimetype; 82 e << description << filename << mimetype;
85#endif 83#endif
86} 84}
87 85
88/*! 86/*!
89 \overload 87 \overload
90 88
91 Uses the DocLnk::file() and DocLnk::type() of \a doc. 89 Uses the DocLnk::file() and DocLnk::type() of \a doc.
92 90
93 \sa done() 91 \sa done()
94*/ 92*/
95void Ir::send( const DocLnk &doc, const QString &description ) 93void Ir::send( const DocLnk &doc, const QString &description )
96{ 94{
97 send( doc.file(), description, doc.type() ); 95 send( doc.file(), description, doc.type() );
98} 96}
99 97
100/*! 98/*!
101 \fn Ir::done( Ir *ir ); 99 \fn Ir::done( Ir *ir );
102 100
103 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.
104*/ 102*/
105 103
106/*!\internal 104/*!\internal
107 */ 105 */
108void Ir::obexMessage( const QCString &msg, const QByteArray &data) 106void Ir::obexMessage( const QCString &msg, const QByteArray &data)
109{ 107{
110 if ( msg == "done(QString)" ) { 108 if ( msg == "done(QString)" ) {
111 QString fn; 109 QString fn;
112 QDataStream stream( data, IO_ReadOnly ); 110 QDataStream stream( data, IO_ReadOnly );
113 stream >> fn; 111 stream >> fn;
114 if ( fn == filename ) 112 if ( fn == filename )
115 emit done( this ); 113 emit done( this );
116 } 114 }
117} 115}
118 116
diff --git a/library/lnkproperties.cpp b/library/lnkproperties.cpp
index 8dca4ab..0661423 100644
--- a/library/lnkproperties.cpp
+++ b/library/lnkproperties.cpp
@@ -1,347 +1,346 @@
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#include "lnkproperties.h"
25#include "lnkproperties.h"
26#include "lnkpropertiesbase_p.h" 24#include "lnkpropertiesbase_p.h"
25#include "lnkproperties.h"
27#include "ir.h" 26#include "ir.h"
28 27
29#include <qpe/qpeapplication.h> 28#include <qpe/qpeapplication.h>
30#include <qpe/applnk.h> 29#include <qpe/applnk.h>
31#include <qpe/global.h> 30#include <qpe/global.h>
32#include <qpe/categorywidget.h> 31#include <qpe/categorywidget.h>
33#include <qpe/qcopenvelope_qws.h> 32#include <qpe/qcopenvelope_qws.h>
34#include <qpe/filemanager.h> 33#include <qpe/filemanager.h>
35#include <qpe/config.h> 34#include <qpe/config.h>
36#include <qpe/storage.h> 35#include <qpe/storage.h>
37#include <qpe/qpemessagebox.h> 36#include <qpe/qpemessagebox.h>
38#include <qpe/mimetype.h> 37#include <qpe/mimetype.h>
39 38
40#include <qlineedit.h> 39#include <qlineedit.h>
41#include <qtoolbutton.h> 40#include <qtoolbutton.h>
42#include <qpushbutton.h> 41#include <qpushbutton.h>
43#include <qgroupbox.h> 42#include <qgroupbox.h>
44#include <qcheckbox.h> 43#include <qcheckbox.h>
45#include <qlabel.h> 44#include <qlabel.h>
46#include <qlayout.h> 45#include <qlayout.h>
47#include <qfile.h> 46#include <qfile.h>
48#include <qfileinfo.h> 47#include <qfileinfo.h>
49#include <qmessagebox.h> 48#include <qmessagebox.h>
50#include <qsize.h> 49#include <qsize.h>
51#include <qcombobox.h> 50#include <qcombobox.h>
52#include <qregexp.h> 51#include <qregexp.h>
53#include <qbuttongroup.h> 52#include <qbuttongroup.h>
54 53
55#include <stdlib.h> 54#include <stdlib.h>
56 55
57LnkProperties::LnkProperties( AppLnk* l, QWidget* parent ) 56LnkProperties::LnkProperties( AppLnk* l, QWidget* parent )
58 : QDialog( parent, 0, TRUE ), lnk(l), fileSize( 0 ) 57 : QDialog( parent, 0, TRUE ), lnk(l), fileSize( 0 )
59{ 58{
60 setCaption( tr("Properties") ); 59 setCaption( tr("Properties") );
61 60
62 QVBoxLayout *vbox = new QVBoxLayout( this ); 61 QVBoxLayout *vbox = new QVBoxLayout( this );
63 d = new LnkPropertiesBase( this ); 62 d = new LnkPropertiesBase( this );
64 vbox->add( d ); 63 vbox->add( d );
65 64
66 // hide custom rotation feature for now, need a new implementation to fit quicklauch, 65 // hide custom rotation feature for now, need a new implementation to fit quicklauch,
67 // is confusing for the user and doubtable useful since life rotation 66 // is confusing for the user and doubtable useful since life rotation
68 d->rotate->hide(); 67 d->rotate->hide();
69 d->rotateButtons->hide(); 68 d->rotateButtons->hide();
70 69
71 d->docname->setText(l->name()); 70 d->docname->setText(l->name());
72 QString inf; 71 QString inf;
73 if ( l->type().isEmpty() ) { 72 if ( l->type().isEmpty() ) {
74 d->type->hide(); 73 d->type->hide();
75 d->typeLabel->hide(); 74 d->typeLabel->hide();
76 } else { 75 } else {
77 d->type->setText( l->type() ); 76 d->type->setText( l->type() );
78 } 77 }
79 78
80 if ( l->comment().isEmpty() ) { 79 if ( l->comment().isEmpty() ) {
81 d->comment->hide(); 80 d->comment->hide();
82 d->commentLabel->hide(); 81 d->commentLabel->hide();
83 } else { 82 } else {
84 d->comment->setText( l->comment() ); 83 d->comment->setText( l->comment() );
85 } 84 }
86 85
87 connect(d->beam,SIGNAL(clicked()),this,SLOT(beamLnk())); 86 connect(d->beam,SIGNAL(clicked()),this,SLOT(beamLnk()));
88 if ( lnk->type().contains('/') ) { // A document? (#### better predicate needed) 87 if ( lnk->type().contains('/') ) { // A document? (#### better predicate needed)
89 connect(d->unlink,SIGNAL(clicked()),this,SLOT(unlinkLnk())); 88 connect(d->unlink,SIGNAL(clicked()),this,SLOT(unlinkLnk()));
90 connect(d->duplicate,SIGNAL(clicked()),this,SLOT(duplicateLnk())); 89 connect(d->duplicate,SIGNAL(clicked()),this,SLOT(duplicateLnk()));
91 90
92 d->docname->setReadOnly( FALSE ); 91 d->docname->setReadOnly( FALSE );
93 d->preload->hide(); 92 d->preload->hide();
94 d->rotate->hide(); 93 d->rotate->hide();
95 d->rotateButtons->hide(); 94 d->rotateButtons->hide();
96 d->labelspacer->hide(); 95 d->labelspacer->hide();
97 96
98 // ### THIS MUST GO, FIX WIERD BUG in QLAYOUT 97 // ### THIS MUST GO, FIX WIERD BUG in QLAYOUT
99 d->categoryEdit->kludge(); 98 d->categoryEdit->kludge();
100 99
101 d->categoryEdit->setCategories( lnk->categories(), 100 d->categoryEdit->setCategories( lnk->categories(),
102 "Document View", 101 "Document View",
103 tr("Document View") ); 102 tr("Document View") );
104 setupLocations(); 103 setupLocations();
105 } else { 104 } else {
106 d->unlink->hide(); 105 d->unlink->hide();
107 d->duplicate->hide(); 106 d->duplicate->hide();
108 d->beam->hide(); 107 d->beam->hide();
109 d->hline->hide(); 108 d->hline->hide();
110 d->locationLabel->hide(); 109 d->locationLabel->hide();
111 d->locationCombo->hide(); 110 d->locationCombo->hide();
112 111
113 // Can't edit categories, since the app .desktop files are global, 112 // Can't edit categories, since the app .desktop files are global,
114 // possibly read-only. 113 // possibly read-only.
115 d->categoryEdit->hide(); 114 d->categoryEdit->hide();
116 115
117 d->docname->setReadOnly( TRUE ); 116 d->docname->setReadOnly( TRUE );
118 117
119 if ( l->property("CanFastload") == "0" ) 118 if ( l->property("CanFastload") == "0" )
120 d->preload->hide(); 119 d->preload->hide();
121 if ( !l->property("Rotation"). isEmpty ()) { 120 if ( !l->property("Rotation"). isEmpty ()) {
122 d->rotate->setChecked ( true ); 121 d->rotate->setChecked ( true );
123 //don't use rotate buttons for now (see comment above) 122 //don't use rotate buttons for now (see comment above)
124 //d->rotateButtons->setButton((l->rotation().toInt()%360)/90); 123 //d->rotateButtons->setButton((l->rotation().toInt()%360)/90);
125 } 124 }
126 else { 125 else {
127 d->rotateButtons->setEnabled(false); 126 d->rotateButtons->setEnabled(false);
128 } 127 }
129 128
130 Config cfg("Launcher"); 129 Config cfg("Launcher");
131 cfg.setGroup("Preload"); 130 cfg.setGroup("Preload");
132 QStringList apps = cfg.readListEntry("Apps",','); 131 QStringList apps = cfg.readListEntry("Apps",',');
133 d->preload->setChecked( apps.contains(l->exec()) ); 132 d->preload->setChecked( apps.contains(l->exec()) );
134 if ( Global::isBuiltinCommand(lnk->exec()) ) 133 if ( Global::isBuiltinCommand(lnk->exec()) )
135 d->preload->hide(); // builtins are always fast 134 d->preload->hide(); // builtins are always fast
136 135
137 currentLocation = 0; // apps not movable (yet) 136 currentLocation = 0; // apps not movable (yet)
138 } 137 }
139} 138}
140 139
141LnkProperties::~LnkProperties() 140LnkProperties::~LnkProperties()
142{ 141{
143} 142}
144 143
145void LnkProperties::unlinkLnk() 144void LnkProperties::unlinkLnk()
146{ 145{
147 if ( QPEMessageBox::confirmDelete( this, tr("Delete"), lnk->name() ) ) { 146 if ( QPEMessageBox::confirmDelete( this, tr("Delete"), lnk->name() ) ) {
148 lnk->removeFiles(); 147 lnk->removeFiles();
149 if ( QFile::exists(lnk->file()) ) { 148 if ( QFile::exists(lnk->file()) ) {
150 QMessageBox::warning( this, tr("Delete"), tr("File deletion failed.") ); 149 QMessageBox::warning( this, tr("Delete"), tr("File deletion failed.") );
151 } else { 150 } else {
152 reject(); 151 reject();
153 } 152 }
154 } 153 }
155} 154}
156 155
157void LnkProperties::setupLocations() 156void LnkProperties::setupLocations()
158{ 157{
159 QFileInfo fi( lnk->file() ); 158 QFileInfo fi( lnk->file() );
160 fileSize = fi.size(); 159 fileSize = fi.size();
161 StorageInfo storage; 160 StorageInfo storage;
162 const QList<FileSystem> &fs = storage.fileSystems(); 161 const QList<FileSystem> &fs = storage.fileSystems();
163 QListIterator<FileSystem> it ( fs ); 162 QListIterator<FileSystem> it ( fs );
164 QString s; 163 QString s;
165 QString homeDir = getenv("HOME"); 164 QString homeDir = getenv("HOME");
166 QString hardDiskHome; 165 QString hardDiskHome;
167 QString hardDiskPath; 166 QString hardDiskPath;
168 int index = 0; 167 int index = 0;
169 currentLocation = -1; 168 currentLocation = -1;
170 for ( ; it.current(); ++it ) { 169 for ( ; it.current(); ++it ) {
171 // we add 10k to the file size so we are sure we can also save the desktop file 170 // we add 10k to the file size so we are sure we can also save the desktop file
172 if ( (ulong)(*it)->availBlocks() * (ulong)(*it)->blockSize() > (ulong)fileSize + 10000 ) { 171 if ( (ulong)(*it)->availBlocks() * (ulong)(*it)->blockSize() > (ulong)fileSize + 10000 ) {
173 if ( (*it)->isRemovable() || 172 if ( (*it)->isRemovable() ||
174 (*it)->disk() == "/dev/mtdblock1" || 173 (*it)->disk() == "/dev/mtdblock1" ||
175 (*it)->disk() == "/dev/mtdblock/1" || 174 (*it)->disk() == "/dev/mtdblock/1" ||
176 (*it)->disk().left(13) == "/dev/mtdblock" || 175 (*it)->disk().left(13) == "/dev/mtdblock" ||
177 (*it)->disk() == "/dev/mtdblock6" || 176 (*it)->disk() == "/dev/mtdblock6" ||
178 (*it )->disk() == "/dev/root" || 177 (*it )->disk() == "/dev/root" ||
179 (*it)->disk() == "tmpfs" ) { 178 (*it)->disk() == "tmpfs" ) {
180 d->locationCombo->insertItem( (*it)->name(), index ); 179 d->locationCombo->insertItem( (*it)->name(), index );
181 locations.append( ( ((*it)->isRemovable() || 180 locations.append( ( ((*it)->isRemovable() ||
182 (*it)->disk() == "/dev/mtdblock6" || 181 (*it)->disk() == "/dev/mtdblock6" ||
183 (*it)->disk() == "tmpfs" ) 182 (*it)->disk() == "tmpfs" )
184 ? (*it)->path() : homeDir) ); 183 ? (*it)->path() : homeDir) );
185 if ( lnk->file().contains( (*it)->path() ) ) { 184 if ( lnk->file().contains( (*it)->path() ) ) {
186 d->locationCombo->setCurrentItem( index ); 185 d->locationCombo->setCurrentItem( index );
187 currentLocation = index; 186 currentLocation = index;
188 } 187 }
189 index++; 188 index++;
190 } else if ( (*it)->name().contains( tr("Hard Disk") ) && 189 } else if ( (*it)->name().contains( tr("Hard Disk") ) &&
191 homeDir.contains( (*it)->path() ) && 190 homeDir.contains( (*it)->path() ) &&
192 (*it)->path().length() > hardDiskHome.length() ) { 191 (*it)->path().length() > hardDiskHome.length() ) {
193 hardDiskHome = (*it)->name(); 192 hardDiskHome = (*it)->name();
194 hardDiskPath = (*it)->path(); 193 hardDiskPath = (*it)->path();
195 } 194 }
196 } 195 }
197 } 196 }
198 if ( !hardDiskHome.isEmpty() ) { 197 if ( !hardDiskHome.isEmpty() ) {
199 d->locationCombo->insertItem( hardDiskHome ); 198 d->locationCombo->insertItem( hardDiskHome );
200 locations.append( hardDiskPath ); 199 locations.append( hardDiskPath );
201 if ( currentLocation == -1 ) { // assume it's the hard disk 200 if ( currentLocation == -1 ) { // assume it's the hard disk
202 d->locationCombo->setCurrentItem( index ); 201 d->locationCombo->setCurrentItem( index );
203 currentLocation = index; 202 currentLocation = index;
204 } 203 }
205 } 204 }
206} 205}
207 206
208void LnkProperties::duplicateLnk() 207void LnkProperties::duplicateLnk()
209{ 208{
210 // The duplicate takes the new properties. 209 // The duplicate takes the new properties.
211 DocLnk newdoc( *((DocLnk *)lnk) ); 210 DocLnk newdoc( *((DocLnk *)lnk) );
212 if ( d->docname->text() == lnk->name() ) 211 if ( d->docname->text() == lnk->name() )
213 newdoc.setName(tr("Copy of ")+d->docname->text()); 212 newdoc.setName(tr("Copy of ")+d->docname->text());
214 else 213 else
215 newdoc.setName(d->docname->text()); 214 newdoc.setName(d->docname->text());
216 215
217 if ( !copyFile( newdoc ) ) { 216 if ( !copyFile( newdoc ) ) {
218 QMessageBox::warning( this, tr("Duplicate"), tr("File copy failed.") ); 217 QMessageBox::warning( this, tr("Duplicate"), tr("File copy failed.") );
219 return; 218 return;
220 } 219 }
221 reject(); 220 reject();
222} 221}
223 222
224bool LnkProperties::moveLnk() 223bool LnkProperties::moveLnk()
225{ 224{
226 DocLnk newdoc( *((DocLnk *)lnk) ); 225 DocLnk newdoc( *((DocLnk *)lnk) );
227 newdoc.setName(d->docname->text()); 226 newdoc.setName(d->docname->text());
228 227
229 if ( !copyFile( newdoc ) ) { 228 if ( !copyFile( newdoc ) ) {
230 QMessageBox::warning( this, tr("Details"), tr("Moving Document failed.") ); 229 QMessageBox::warning( this, tr("Details"), tr("Moving Document failed.") );
231 return FALSE; 230 return FALSE;
232 } 231 }
233 // remove old lnk 232 // remove old lnk
234 lnk->removeFiles(); 233 lnk->removeFiles();
235 234
236 return TRUE; 235 return TRUE;
237} 236}
238 237
239void LnkProperties::beamLnk() 238void LnkProperties::beamLnk()
240{ 239{
241 Ir ir; 240 Ir ir;
242 DocLnk doc( *((DocLnk *)lnk) ); 241 DocLnk doc( *((DocLnk *)lnk) );
243 doc.setName(d->docname->text()); 242 doc.setName(d->docname->text());
244 reject(); 243 reject();
245 ir.send( doc, doc.comment() ); 244 ir.send( doc, doc.comment() );
246} 245}
247 246
248bool LnkProperties::copyFile( DocLnk &newdoc ) 247bool LnkProperties::copyFile( DocLnk &newdoc )
249{ 248{
250 const char *linkExtn = ".desktop"; 249 const char *linkExtn = ".desktop";
251 QString fileExtn; 250 QString fileExtn;
252 int extnPos = lnk->file().findRev( '.' ); 251 int extnPos = lnk->file().findRev( '.' );
253 if ( extnPos > 0 ) 252 if ( extnPos > 0 )
254 fileExtn = lnk->file().mid( extnPos ); 253 fileExtn = lnk->file().mid( extnPos );
255 254
256 QString safename = newdoc.name(); 255 QString safename = newdoc.name();
257 safename.replace(QRegExp("/"),"_"); 256 safename.replace(QRegExp("/"),"_");
258 257
259 QString fn = locations[ d->locationCombo->currentItem() ] 258 QString fn = locations[ d->locationCombo->currentItem() ]
260 + "/Documents/" + newdoc.type() + "/" + safename; 259 + "/Documents/" + newdoc.type() + "/" + safename;
261 if ( QFile::exists(fn + fileExtn) || QFile::exists(fn + linkExtn) ) { 260 if ( QFile::exists(fn + fileExtn) || QFile::exists(fn + linkExtn) ) {
262 int n=1; 261 int n=1;
263 QString nn = fn + "_" + QString::number(n); 262 QString nn = fn + "_" + QString::number(n);
264 while ( QFile::exists(nn+fileExtn) || QFile::exists(nn+linkExtn) ) { 263 while ( QFile::exists(nn+fileExtn) || QFile::exists(nn+linkExtn) ) {
265 n++; 264 n++;
266 nn = fn + "_" + QString::number(n); 265 nn = fn + "_" + QString::number(n);
267 } 266 }
268 fn = nn; 267 fn = nn;
269 } 268 }
270 newdoc.setFile( fn + fileExtn ); 269 newdoc.setFile( fn + fileExtn );
271 newdoc.setLinkFile( fn + linkExtn ); 270 newdoc.setLinkFile( fn + linkExtn );
272 271
273 // Copy file 272 // Copy file
274 FileManager fm; 273 FileManager fm;
275 if ( !fm.copyFile( *lnk, newdoc ) ) 274 if ( !fm.copyFile( *lnk, newdoc ) )
276 return FALSE; 275 return FALSE;
277 return TRUE; 276 return TRUE;
278} 277}
279 278
280void LnkProperties::done(int ok) 279void LnkProperties::done(int ok)
281{ 280{
282 if ( ok ) { 281 if ( ok ) {
283 bool changed=FALSE; 282 bool changed=FALSE;
284 bool reloadMime=FALSE; 283 bool reloadMime=FALSE;
285 284
286 if ( lnk->name() != d->docname->text() ) { 285 if ( lnk->name() != d->docname->text() ) {
287 lnk->setName(d->docname->text()); 286 lnk->setName(d->docname->text());
288 changed=TRUE; 287 changed=TRUE;
289 } 288 }
290 if ( d->categoryEdit->isVisible() ) { 289 if ( d->categoryEdit->isVisible() ) {
291 QArray<int> tmp = d->categoryEdit->newCategories(); 290 QArray<int> tmp = d->categoryEdit->newCategories();
292 if ( lnk->categories() != tmp ) { 291 if ( lnk->categories() != tmp ) {
293 lnk->setCategories( tmp ); 292 lnk->setCategories( tmp );
294 changed = TRUE; 293 changed = TRUE;
295 } 294 }
296 } 295 }
297 if ( !d->rotate->isHidden()) { 296 if ( !d->rotate->isHidden()) {
298 QString newrot; 297 QString newrot;
299 298
300 if ( d->rotate->isChecked() ) { 299 if ( d->rotate->isChecked() ) {
301 int rot=0; 300 int rot=0;
302 for(; rot<4; rot++) { 301 for(; rot<4; rot++) {
303 if (d->rotateButtons->find(rot)->isOn()) 302 if (d->rotateButtons->find(rot)->isOn())
304 break; 303 break;
305 } 304 }
306 newrot = QString::number((rot*90)%360); 305 newrot = QString::number((rot*90)%360);
307 } 306 }
308 if ( newrot != lnk->rotation() ) { 307 if ( newrot != lnk->rotation() ) {
309 lnk-> setRotation(newrot); 308 lnk-> setRotation(newrot);
310 changed = TRUE; 309 changed = TRUE;
311 reloadMime = TRUE; 310 reloadMime = TRUE;
312 } 311 }
313 } 312 }
314 if ( d->preload->isHidden() && d->locationCombo->currentItem() != currentLocation ) { 313 if ( d->preload->isHidden() && d->locationCombo->currentItem() != currentLocation ) {
315 moveLnk(); 314 moveLnk();
316 } else if ( changed ) { 315 } else if ( changed ) {
317 lnk->writeLink(); 316 lnk->writeLink();
318 } 317 }
319 318
320 if ( !d->preload->isHidden() ) { 319 if ( !d->preload->isHidden() ) {
321 Config cfg("Launcher"); 320 Config cfg("Launcher");
322 cfg.setGroup("Preload"); 321 cfg.setGroup("Preload");
323 QStringList apps = cfg.readListEntry("Apps",','); 322 QStringList apps = cfg.readListEntry("Apps",',');
324 QString exe = lnk->exec(); 323 QString exe = lnk->exec();
325 if ( apps.contains(exe) != d->preload->isChecked() ) { 324 if ( apps.contains(exe) != d->preload->isChecked() ) {
326 if ( d->preload->isChecked() ) { 325 if ( d->preload->isChecked() ) {
327 apps.append(exe); 326 apps.append(exe);
328#ifndef QT_NO_COP 327#ifndef QT_NO_COP
329 QCopEnvelope e("QPE/Application/"+exe.local8Bit(), 328 QCopEnvelope e("QPE/Application/"+exe.local8Bit(),
330 "enablePreload()"); 329 "enablePreload()");
331#endif 330#endif
332 } else { 331 } else {
333 apps.remove(exe); 332 apps.remove(exe);
334#ifndef QT_NO_COP 333#ifndef QT_NO_COP
335 QCopEnvelope e("QPE/Application/"+exe.local8Bit(), 334 QCopEnvelope e("QPE/Application/"+exe.local8Bit(),
336 "quitIfInvisible()"); 335 "quitIfInvisible()");
337#endif 336#endif
338 } 337 }
339 cfg.writeEntry("Apps",apps,','); 338 cfg.writeEntry("Apps",apps,',');
340 } 339 }
341 } 340 }
342 if ( reloadMime ) 341 if ( reloadMime )
343 MimeType::updateApplications ( ); 342 MimeType::updateApplications ( );
344 } 343 }
345 QDialog::done( ok ); 344 QDialog::done( ok );
346} 345}
347 346
diff --git a/library/mimetype.cpp b/library/mimetype.cpp
index d0a578e..23de70b 100644
--- a/library/mimetype.cpp
+++ b/library/mimetype.cpp
@@ -1,370 +1,366 @@
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_MIMEEXT 21#define QTOPIA_INTERNAL_MIMEEXT
22#include "mimetype.h" 22#include "mimetype.h"
23#include "applnk.h" 23#include "applnk.h"
24#include "resource.h" 24#include "resource.h"
25#include <qpe/qpeapplication.h> 25#include <qpe/qpeapplication.h>
26#include "config.h" 26#include "config.h"
27 27
28#include <qfile.h> 28#include <qfile.h>
29#include <qdict.h>
30#include <qregexp.h>
31#include <qstringlist.h>
32#include <qtextstream.h> 29#include <qtextstream.h>
33#include <qmap.h>
34 30
35 31
36static void cleanupMime() 32static void cleanupMime()
37{ 33{
38 MimeType::clear(); 34 MimeType::clear();
39} 35}
40 36
41class MimeTypeData { 37class MimeTypeData {
42public: 38public:
43 MimeTypeData(const QString& i) : 39 MimeTypeData(const QString& i) :
44 id(i) 40 id(i)
45 { 41 {
46 apps.setAutoDelete(TRUE); 42 apps.setAutoDelete(TRUE);
47 } 43 }
48 QString id; 44 QString id;
49 QString extension; 45 QString extension;
50 QList<AppLnk> apps; 46 QList<AppLnk> apps;
51 47
52 QString description() 48 QString description()
53 { 49 {
54 if ( desc.isEmpty() ) 50 if ( desc.isEmpty() )
55 desc = QPEApplication::tr("%1 document").arg(apps.first()->name()); 51 desc = QPEApplication::tr("%1 document").arg(apps.first()->name());
56 return desc; 52 return desc;
57 } 53 }
58 54
59 QPixmap regIcon() 55 QPixmap regIcon()
60 { 56 {
61 if ( regicon.isNull() ) 57 if ( regicon.isNull() )
62 loadPixmaps(); 58 loadPixmaps();
63 return regicon; 59 return regicon;
64 } 60 }
65 61
66 QPixmap bigIcon() 62 QPixmap bigIcon()
67 { 63 {
68 if ( bigicon.isNull() ) 64 if ( bigicon.isNull() )
69 loadPixmaps(); 65 loadPixmaps();
70 return bigicon; 66 return bigicon;
71 } 67 }
72 68
73private: 69private:
74 void loadPixmaps() 70 void loadPixmaps()
75 { 71 {
76 if ( apps.count() ) { 72 if ( apps.count() ) {
77 QString icon; 73 QString icon;
78 for (AppLnk* lnk = apps.first(); icon.isNull() && lnk; lnk=apps.next()) { 74 for (AppLnk* lnk = apps.first(); icon.isNull() && lnk; lnk=apps.next()) {
79 QStringList icons = lnk->mimeTypeIcons(); 75 QStringList icons = lnk->mimeTypeIcons();
80 if ( icons.count() ) { 76 if ( icons.count() ) {
81 QStringList types = lnk->mimeTypes(); 77 QStringList types = lnk->mimeTypes();
82 for (QStringList::ConstIterator t=types.begin(),i=icons.begin(); t!=types.end() && i!=icons.end(); ++i,++t) { 78 for (QStringList::ConstIterator t=types.begin(),i=icons.begin(); t!=types.end() && i!=icons.end(); ++i,++t) {
83 if ( *t == id ) { 79 if ( *t == id ) {
84 icon = *i; 80 icon = *i;
85 break; 81 break;
86 } 82 }
87 } 83 }
88 } 84 }
89 } 85 }
90 if ( icon.isNull() ) { 86 if ( icon.isNull() ) {
91 AppLnk* lnk = apps.first(); 87 AppLnk* lnk = apps.first();
92 regicon = lnk->pixmap(); 88 regicon = lnk->pixmap();
93 bigicon = lnk->bigPixmap(); 89 bigicon = lnk->bigPixmap();
94 } else { 90 } else {
95 QImage unscaledIcon = Resource::loadImage( icon ); 91 QImage unscaledIcon = Resource::loadImage( icon );
96 regicon.convertFromImage( unscaledIcon.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ) ); 92 regicon.convertFromImage( unscaledIcon.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ) );
97 bigicon.convertFromImage( unscaledIcon.smoothScale( AppLnk::bigIconSize(), AppLnk::bigIconSize() ) ); 93 bigicon.convertFromImage( unscaledIcon.smoothScale( AppLnk::bigIconSize(), AppLnk::bigIconSize() ) );
98 } 94 }
99 } 95 }
100 } 96 }
101 97
102 QPixmap regicon; 98 QPixmap regicon;
103 QPixmap bigicon; 99 QPixmap bigicon;
104 QString desc; 100 QString desc;
105}; 101};
106 102
107class MimeType::Private : public QDict<MimeTypeData> { 103class MimeType::Private : public QDict<MimeTypeData> {
108public: 104public:
109 Private() {} 105 Private() {}
110 ~Private() {} 106 ~Private() {}
111 107
112 // ... 108 // ...
113}; 109};
114 110
115MimeType::Private* MimeType::d=0; 111MimeType::Private* MimeType::d=0;
116static QMap<QString,QString> *typeFor = 0; 112static QMap<QString,QString> *typeFor = 0;
117static QMap<QString,QStringList> *extFor = 0; 113static QMap<QString,QStringList> *extFor = 0;
118 114
119MimeType::Private& MimeType::data() 115MimeType::Private& MimeType::data()
120{ 116{
121 if ( !d ) { 117 if ( !d ) {
122 d = new Private; 118 d = new Private;
123 d->setAutoDelete(TRUE); 119 d->setAutoDelete(TRUE);
124 static bool setCleanup = FALSE; 120 static bool setCleanup = FALSE;
125 if ( !setCleanup ) { 121 if ( !setCleanup ) {
126 qAddPostRoutine( cleanupMime ); 122 qAddPostRoutine( cleanupMime );
127 setCleanup = TRUE; 123 setCleanup = TRUE;
128 } 124 }
129 } 125 }
130 return *d; 126 return *d;
131} 127}
132 128
133/*! 129/*!
134 \class MimeType mimetype.h 130 \class MimeType mimetype.h
135 \brief The MimeType class provides MIME type information. 131 \brief The MimeType class provides MIME type information.
136 132
137 A MimeType object is a light-weight value which 133 A MimeType object is a light-weight value which
138 provides information about a MIME type. 134 provides information about a MIME type.
139 135
140 \ingroup qtopiaemb 136 \ingroup qtopiaemb
141*/ 137*/
142 138
143/*! 139/*!
144 Constructs a MimeType. 140 Constructs a MimeType.
145 Normally, \a ext_or_id is a MIME type, 141 Normally, \a ext_or_id is a MIME type,
146 but if \a ext_or_id starts with / or contains no /, 142 but if \a ext_or_id starts with / or contains no /,
147 it is interpretted as a filename and the 143 it is interpretted as a filename and the
148 extension (eg. .txt) is used as the 144 extension (eg. .txt) is used as the
149 MIME type. 145 MIME type.
150*/ 146*/
151MimeType::MimeType( const QString& ext_or_id ) 147MimeType::MimeType( const QString& ext_or_id )
152{ 148{
153 init(ext_or_id); 149 init(ext_or_id);
154} 150}
155 151
156/*! 152/*!
157 Constructs a MimeType from the type() of \a lnk. 153 Constructs a MimeType from the type() of \a lnk.
158*/ 154*/
159MimeType::MimeType( const DocLnk& lnk ) 155MimeType::MimeType( const DocLnk& lnk )
160{ 156{
161 init(lnk.type()); 157 init(lnk.type());
162} 158}
163 159
164/*! 160/*!
165 Returns the MIME type identifier. 161 Returns the MIME type identifier.
166*/ 162*/
167QString MimeType::id() const 163QString MimeType::id() const
168{ 164{
169 return i; 165 return i;
170} 166}
171 167
172/*! 168/*!
173 Returns a description of the MIME Type. This is usually based 169 Returns a description of the MIME Type. This is usually based
174 on the application() associated with the type. 170 on the application() associated with the type.
175*/ 171*/
176QString MimeType::description() const 172QString MimeType::description() const
177{ 173{
178 MimeTypeData* d = data(i); 174 MimeTypeData* d = data(i);
179 return d ? d->description() : QString::null; 175 return d ? d->description() : QString::null;
180} 176}
181 177
182/*! 178/*!
183 Returns a small QPixmap appropriate for the MIME type. 179 Returns a small QPixmap appropriate for the MIME type.
184*/ 180*/
185QPixmap MimeType::pixmap() const 181QPixmap MimeType::pixmap() const
186{ 182{
187 MimeTypeData* d = data(i); 183 MimeTypeData* d = data(i);
188 return d ? d->regIcon() : QPixmap(); 184 return d ? d->regIcon() : QPixmap();
189} 185}
190 186
191/*! 187/*!
192 \internal 188 \internal
193 This function is not generally available. 189 This function is not generally available.
194*/ 190*/
195QString MimeType::extension() const 191QString MimeType::extension() const
196{ 192{
197 return extensions().first(); 193 return extensions().first();
198} 194}
199 195
200 196
201/*! 197/*!
202 \internal 198 \internal
203 This function is not generally available. 199 This function is not generally available.
204*/ 200*/
205QStringList MimeType::extensions() const 201QStringList MimeType::extensions() const
206{ 202{
207 loadExtensions(); 203 loadExtensions();
208 return *(*extFor).find(i); 204 return *(*extFor).find(i);
209} 205}
210 206
211/*! 207/*!
212 Returns a larger QPixmap appropriate for the MIME type. 208 Returns a larger QPixmap appropriate for the MIME type.
213*/ 209*/
214QPixmap MimeType::bigPixmap() const 210QPixmap MimeType::bigPixmap() const
215{ 211{
216 MimeTypeData* d = data(i); 212 MimeTypeData* d = data(i);
217 return d ? d->bigIcon() : QPixmap(); 213 return d ? d->bigIcon() : QPixmap();
218} 214}
219 215
220/*! 216/*!
221 Returns the AppLnk defining the application associated 217 Returns the AppLnk defining the application associated
222 with this MIME type, or 0 if none is associated. 218 with this MIME type, or 0 if none is associated.
223 219
224 The caller must not retain the pointer, 220 The caller must not retain the pointer,
225 but of course you can dereference it to take a copy if needed. 221 but of course you can dereference it to take a copy if needed.
226 222
227 \sa Service::binding() 223 \sa Service::binding()
228*/ 224*/
229const AppLnk* MimeType::application() const 225const AppLnk* MimeType::application() const
230{ 226{
231 MimeTypeData* d = data(i); 227 MimeTypeData* d = data(i);
232 return d ? d->apps.first() : 0; 228 return d ? d->apps.first() : 0;
233} 229}
234 230
235static QString serviceBinding(const QString& service) 231static QString serviceBinding(const QString& service)
236{ 232{
237 // Copied from qtopiaservices 233 // Copied from qtopiaservices
238 QString svrc = service; 234 QString svrc = service;
239 for (int i=0; i<(int)svrc.length(); i++) 235 for (int i=0; i<(int)svrc.length(); i++)
240 if ( svrc[i]=='/' ) svrc[i] = '-'; 236 if ( svrc[i]=='/' ) svrc[i] = '-';
241 return "Service-"+svrc; 237 return "Service-"+svrc;
242} 238}
243 239
244/*! 240/*!
245 \internal 241 \internal
246*/ 242*/
247void MimeType::registerApp( const AppLnk& lnk ) 243void MimeType::registerApp( const AppLnk& lnk )
248{ 244{
249 QStringList list = lnk.mimeTypes(); 245 QStringList list = lnk.mimeTypes();
250 for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) { 246 for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) {
251 MimeTypeData* cur = data()[*it]; 247 MimeTypeData* cur = data()[*it];
252 AppLnk* l = new AppLnk(lnk); 248 AppLnk* l = new AppLnk(lnk);
253 if ( !cur ) { 249 if ( !cur ) {
254 cur = new MimeTypeData( *it ); 250 cur = new MimeTypeData( *it );
255 data().insert( *it, cur ); 251 data().insert( *it, cur );
256 cur->apps.append(l); 252 cur->apps.append(l);
257 } else if ( cur->apps.count() ) { 253 } else if ( cur->apps.count() ) {
258 Config binding(serviceBinding("Open/"+*it)); 254 Config binding(serviceBinding("Open/"+*it));
259 binding.setGroup("Service"); 255 binding.setGroup("Service");
260 QString def = binding.readEntry("default"); 256 QString def = binding.readEntry("default");
261 if ( l->exec() == def ) 257 if ( l->exec() == def )
262 cur->apps.prepend(l); 258 cur->apps.prepend(l);
263 else 259 else
264 cur->apps.append(l); 260 cur->apps.append(l);
265 } else { 261 } else {
266 cur->apps.append(l); 262 cur->apps.append(l);
267 } 263 }
268 } 264 }
269} 265}
270 266
271/*! 267/*!
272 \internal 268 \internal
273*/ 269*/
274void MimeType::clear() 270void MimeType::clear()
275{ 271{
276 delete d; 272 delete d;
277 d = 0; 273 d = 0;
278} 274}
279 275
280void MimeType::loadExtensions() 276void MimeType::loadExtensions()
281{ 277{
282 if ( !typeFor ) { 278 if ( !typeFor ) {
283 extFor = new QMap<QString,QStringList>; 279 extFor = new QMap<QString,QStringList>;
284 typeFor = new QMap<QString,QString>; 280 typeFor = new QMap<QString,QString>;
285 loadExtensions("/etc/mime.types"); 281 loadExtensions("/etc/mime.types");
286 loadExtensions(QPEApplication::qpeDir()+"etc/mime.types"); 282 loadExtensions(QPEApplication::qpeDir()+"etc/mime.types");
287 } 283 }
288} 284}
289 285
290void MimeType::loadExtensions(const QString& filename) 286void MimeType::loadExtensions(const QString& filename)
291{ 287{
292 QFile file(filename); 288 QFile file(filename);
293 if ( file.open(IO_ReadOnly) ) { 289 if ( file.open(IO_ReadOnly) ) {
294 QTextStream in(&file); 290 QTextStream in(&file);
295 QRegExp space("[ \t]+"); 291 QRegExp space("[ \t]+");
296 while (!in.atEnd()) { 292 while (!in.atEnd()) {
297 QStringList tokens = QStringList::split(space, in.readLine()); 293 QStringList tokens = QStringList::split(space, in.readLine());
298 QStringList::ConstIterator it = tokens.begin(); 294 QStringList::ConstIterator it = tokens.begin();
299 if ( it != tokens.end() ) { 295 if ( it != tokens.end() ) {
300 QString id = *it; ++it; 296 QString id = *it; ++it;
301 // new override old (though left overrides right) 297 // new override old (though left overrides right)
302 QStringList exts = (*extFor)[id]; 298 QStringList exts = (*extFor)[id];
303 QStringList newexts; 299 QStringList newexts;
304 while ( it != tokens.end() ) { 300 while ( it != tokens.end() ) {
305 exts.remove(*it); 301 exts.remove(*it);
306 if ( !newexts.contains(*it) ) 302 if ( !newexts.contains(*it) )
307 newexts.append(*it); 303 newexts.append(*it);
308 (*typeFor)[*it] = id; 304 (*typeFor)[*it] = id;
309 ++it; 305 ++it;
310 } 306 }
311 (*extFor)[id] = newexts + exts; 307 (*extFor)[id] = newexts + exts;
312 } 308 }
313 } 309 }
314 } 310 }
315} 311}
316 312
317void MimeType::init( const QString& ext_or_id ) 313void MimeType::init( const QString& ext_or_id )
318{ 314{
319 if ( ext_or_id[0] != '/' && ext_or_id.contains('/') ) { 315 if ( ext_or_id[0] != '/' && ext_or_id.contains('/') ) {
320 i = ext_or_id.lower(); 316 i = ext_or_id.lower();
321 } else { 317 } else {
322 loadExtensions(); 318 loadExtensions();
323 int dot = ext_or_id.findRev('.'); 319 int dot = ext_or_id.findRev('.');
324 QString ext = dot >= 0 ? ext_or_id.mid(dot+1) : ext_or_id; 320 QString ext = dot >= 0 ? ext_or_id.mid(dot+1) : ext_or_id;
325 i = (*typeFor)[ext.lower()]; 321 i = (*typeFor)[ext.lower()];
326 if ( i.isNull() ) 322 if ( i.isNull() )
327 i = "application/octet-stream"; 323 i = "application/octet-stream";
328 } 324 }
329 static bool appsUpdated = FALSE; 325 static bool appsUpdated = FALSE;
330 if ( !appsUpdated ) { 326 if ( !appsUpdated ) {
331 appsUpdated = TRUE; 327 appsUpdated = TRUE;
332 updateApplications(); 328 updateApplications();
333 } 329 }
334} 330}
335 331
336MimeTypeData* MimeType::data(const QString& id) 332MimeTypeData* MimeType::data(const QString& id)
337{ 333{
338 MimeTypeData* d = data()[id]; 334 MimeTypeData* d = data()[id];
339 if ( !d ) { 335 if ( !d ) {
340 int s = id.find('/'); 336 int s = id.find('/');
341 QString idw = id.left(s)+"/*"; 337 QString idw = id.left(s)+"/*";
342 d = data()[idw]; 338 d = data()[idw];
343 } 339 }
344 return d; 340 return d;
345} 341}
346 342
347/*! 343/*!
348 Returns a Qtopia folder containing application definitions. 344 Returns a Qtopia folder containing application definitions.
349*/ 345*/
350QString MimeType::appsFolderName() 346QString MimeType::appsFolderName()
351{ 347{
352 return QPEApplication::qpeDir() + "apps"; 348 return QPEApplication::qpeDir() + "apps";
353} 349}
354 350
355/*! 351/*!
356 Reloads application definitions. 352 Reloads application definitions.
357*/ 353*/
358void MimeType::updateApplications() 354void MimeType::updateApplications()
359{ 355{
360 clear(); 356 clear();
361 AppLnkSet apps( appsFolderName() ); 357 AppLnkSet apps( appsFolderName() );
362 updateApplications(&apps); 358 updateApplications(&apps);
363} 359}
364 360
365void MimeType::updateApplications(AppLnkSet* folder) 361void MimeType::updateApplications(AppLnkSet* folder)
366{ 362{
367 for ( QListIterator<AppLnk> it( folder->children() ); it.current(); ++it ) { 363 for ( QListIterator<AppLnk> it( folder->children() ); it.current(); ++it ) {
368 registerApp(*it.current()); 364 registerApp(*it.current());
369 } 365 }
370} 366}
diff --git a/library/qcopenvelope_qws.cpp b/library/qcopenvelope_qws.cpp
index 0aac32b..8f58787 100644
--- a/library/qcopenvelope_qws.cpp
+++ b/library/qcopenvelope_qws.cpp
@@ -1,147 +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 "global.h"
25#include <qbuffer.h> 24#include <qbuffer.h>
26#include <qdatastream.h>
27#include <qfile.h> 25#include <qfile.h>
28#include <unistd.h> 26#include <unistd.h>
29#include <errno.h> 27#include <errno.h>
30#include <sys/file.h> 28#include <sys/file.h>
31#include <sys/types.h> 29#include <sys/types.h>
32#include <sys/stat.h> 30#include <sys/stat.h>
33#include <time.h> 31#include <time.h>
34 32
35#ifndef QT_NO_COP 33#ifndef QT_NO_COP
36 34
37/*! 35/*!
38 \class QCopEnvelope qcopenvelope_qws.h 36 \class QCopEnvelope qcopenvelope_qws.h
39 \brief The QCopEnvelope class encapsulates and sends QCop messages 37 \brief The QCopEnvelope class encapsulates and sends QCop messages
40 over QCopChannels. 38 over QCopChannels.
41 39
42 QCop messages allow applications to communicate with each other. 40 QCop messages allow applications to communicate with each other.
43 These messages are sent using QCopEnvelope, and received by connecting 41 These messages are sent using QCopEnvelope, and received by connecting
44 to a QCopChannel. 42 to a QCopChannel.
45 43
46 To send a message, use the following protocol: 44 To send a message, use the following protocol:
47 45
48 \code 46 \code
49 QCopEnvelope e(channelname, messagename); 47 QCopEnvelope e(channelname, messagename);
50 e << parameter1 << parameter2 << ...; 48 e << parameter1 << parameter2 << ...;
51 \endcode 49 \endcode
52 50
53 For messages without parameters, simply use: 51 For messages without parameters, simply use:
54 52
55 \code 53 \code
56 QCopEnvelope e(channelname, messagename); 54 QCopEnvelope e(channelname, messagename);
57 \endcode 55 \endcode
58 56
59 (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
60 compilers.) 58 compilers.)
61 59
62 The \c{channelname} of channels within Qtopia all start with "QPE/". 60 The \c{channelname} of channels within Qtopia all start with "QPE/".
63 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
64 in parentheses. There is no whitespace in the message name. 62 in parentheses. There is no whitespace in the message name.
65 63
66 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
67 predefined QPE/Application/\e{appname} channel 65 predefined QPE/Application/\e{appname} channel
68 (see QPEApplication::appMessage()), but you can make another channel 66 (see QPEApplication::appMessage()), but you can make another channel
69 and connect it to a slot like this: 67 and connect it to a slot like this:
70 68
71 \code 69 \code
72 myChannel = new QCopChannel( "QPE/FooBar", this ); 70 myChannel = new QCopChannel( "QPE/FooBar", this );
73 connect( myChannel, SIGNAL(received(const QCString &, const QByteArray &)), 71 connect( myChannel, SIGNAL(received(const QCString &, const QByteArray &)),
74 this, SLOT(fooBarMessage( const QCString &, const QByteArray &)) ); 72 this, SLOT(fooBarMessage( const QCString &, const QByteArray &)) );
75 \endcode 73 \endcode
76 74
77 See also, the \link qcop.html list of Qtopia messages\endlink. 75 See also, the \link qcop.html list of Qtopia messages\endlink.
78*/ 76*/
79 77
80/*! 78/*!
81 Constructs a QCopEnvelope that will write \a message to \a channel. 79 Constructs a QCopEnvelope that will write \a message to \a channel.
82 If \a message has parameters, you must then use operator<<() to 80 If \a message has parameters, you must then use operator<<() to
83 add these parameters to the envelope. 81 add these parameters to the envelope.
84*/ 82*/
85QCopEnvelope::QCopEnvelope( const QCString& channel, const QCString& message ) : 83QCopEnvelope::QCopEnvelope( const QCString& channel, const QCString& message ) :
86 QDataStream(new QBuffer), 84 QDataStream(new QBuffer),
87 ch(channel), msg(message) 85 ch(channel), msg(message)
88{ 86{
89 device()->open(IO_WriteOnly); 87 device()->open(IO_WriteOnly);
90} 88}
91 89
92/*! 90/*!
93 Writes the message and then destroys the QCopEnvelope. 91 Writes the message and then destroys the QCopEnvelope.
94*/ 92*/
95QCopEnvelope::~QCopEnvelope() 93QCopEnvelope::~QCopEnvelope()
96{ 94{
97 QByteArray data = ((QBuffer*)device())->buffer(); 95 QByteArray data = ((QBuffer*)device())->buffer();
98 const int pref=16; 96 const int pref=16;
99 if ( qstrncmp(ch.data(),"QPE/Application/",pref)==0 ) { 97 if ( qstrncmp(ch.data(),"QPE/Application/",pref)==0 ) {
100 QString qcopfn("/tmp/qcop-msg-"); 98 QString qcopfn("/tmp/qcop-msg-");
101 qcopfn += ch.mid(pref); 99 qcopfn += ch.mid(pref);
102 QFile qcopfile(qcopfn); 100 QFile qcopfile(qcopfn);
103 101
104 if ( qcopfile.open(IO_WriteOnly | IO_Append) ) { 102 if ( qcopfile.open(IO_WriteOnly | IO_Append) ) {
105#ifndef Q_OS_WIN32 103#ifndef Q_OS_WIN32
106 if(flock(qcopfile.handle(), LOCK_EX)) { 104 if(flock(qcopfile.handle(), LOCK_EX)) {
107 /* some error occurred */ 105 /* some error occurred */
108 qWarning(QString("Failed to obtain file lock on %1 (%2)") 106 qWarning(QString("Failed to obtain file lock on %1 (%2)")
109 .arg(qcopfn).arg( errno )); 107 .arg(qcopfn).arg( errno ));
110 } 108 }
111#endif 109#endif
112 { 110 {
113 QDataStream ds(&qcopfile); 111 QDataStream ds(&qcopfile);
114 ds << ch << msg << data; 112 ds << ch << msg << data;
115 qcopfile.flush(); 113 qcopfile.flush();
116#ifndef Q_OS_WIN32 114#ifndef Q_OS_WIN32
117 flock(qcopfile.handle(), LOCK_UN); 115 flock(qcopfile.handle(), LOCK_UN);
118#endif 116#endif
119 qcopfile.close(); 117 qcopfile.close();
120 } 118 }
121 119
122 QByteArray b; 120 QByteArray b;
123 QDataStream stream(b, IO_WriteOnly); 121 QDataStream stream(b, IO_WriteOnly);
124 stream << QString(ch.mid(pref)); 122 stream << QString(ch.mid(pref));
125 QCopChannel::send("QPE/Server", "processQCop(QString)", b); 123 QCopChannel::send("QPE/Server", "processQCop(QString)", b);
126 delete device(); 124 delete device();
127 return; 125 return;
128 } else { 126 } else {
129 qWarning(QString("Failed to open file %1") 127 qWarning(QString("Failed to open file %1")
130 .arg(qcopfn)); 128 .arg(qcopfn));
131 } // endif open 129 } // endif open
132 } 130 }
133 else if (qstrncmp(ch.data(), "QPE/SOAP/", 9) == 0) { 131 else if (qstrncmp(ch.data(), "QPE/SOAP/", 9) == 0) {
134 // 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
135 // endpoint URL to the data section. 133 // endpoint URL to the data section.
136 QString endpoint = ch.mid(9); 134 QString endpoint = ch.mid(9);
137 135
138 ch = "QPE/SOAP"; 136 ch = "QPE/SOAP";
139 // 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..
140 *this << endpoint; 138 *this << endpoint;
141 } 139 }
142 140
143 QCopChannel::send(ch,msg,data); 141 QCopChannel::send(ch,msg,data);
144 delete device(); 142 delete device();
145} 143}
146 144
147#endif 145#endif
diff --git a/library/qdawg.cpp b/library/qdawg.cpp
index af5dc82..2ea5734 100644
--- a/library/qdawg.cpp
+++ b/library/qdawg.cpp
@@ -1,627 +1,625 @@
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 "qdawg.h" 20#include "qdawg.h"
21#include <qintdict.h> 21#include <qintdict.h>
22#include <qvaluelist.h>
23#include <qtextstream.h>
24#include <qfile.h> 22#include <qfile.h>
25#include <qtl.h> 23#include <qtl.h>
26 24
27#include <limits.h> 25#include <limits.h>
28#include <stdio.h> 26#include <stdio.h>
29 27
30// for mmap 28// for mmap
31#include <sys/types.h> 29#include <sys/types.h>
32#include <sys/stat.h> 30#include <sys/stat.h>
33#include <sys/mman.h> 31#include <sys/mman.h>
34#include <fcntl.h> 32#include <fcntl.h>
35#include <errno.h> 33#include <errno.h>
36#include <unistd.h> 34#include <unistd.h>
37 35
38class QDawgPrivate; 36class QDawgPrivate;
39class QTrie; 37class QTrie;
40 38
41typedef QValueList<QTrie*> TrieClub; 39typedef QValueList<QTrie*> TrieClub;
42typedef QIntDict<TrieClub> TrieClubDirectory; 40typedef QIntDict<TrieClub> TrieClubDirectory;
43 41
44class TriePtr { 42class TriePtr {
45public: 43public:
46 QChar letter; 44 QChar letter;
47 QTrie* p; 45 QTrie* p;
48 int operator <(const TriePtr& o) const; 46 int operator <(const TriePtr& o) const;
49 int operator >(const TriePtr& o) const; 47 int operator >(const TriePtr& o) const;
50 int operator <=(const TriePtr& o) const; 48 int operator <=(const TriePtr& o) const;
51}; 49};
52 50
53class TrieList : public QValueList<TriePtr> { 51class TrieList : public QValueList<TriePtr> {
54 bool sorted; 52 bool sorted;
55public: 53public:
56 TrieList() 54 TrieList()
57 { 55 {
58 sorted=TRUE; 56 sorted=TRUE;
59 } 57 }
60 58
61 QTrie* findAdd(QChar c); 59 QTrie* findAdd(QChar c);
62 bool equal(TrieList& l); 60 bool equal(TrieList& l);
63 61
64 void sort() 62 void sort()
65 { 63 {
66 if ( !sorted ) { 64 if ( !sorted ) {
67 qHeapSort(*this); 65 qHeapSort(*this);
68 sorted = TRUE; 66 sorted = TRUE;
69 } 67 }
70 } 68 }
71}; 69};
72 70
73// A fast but memory-wasting temporary class. The Dawg is the goal. 71// A fast but memory-wasting temporary class. The Dawg is the goal.
74class QTrie { 72class QTrie {
75public: 73public:
76 QTrie(); 74 QTrie();
77 ~QTrie(); 75 ~QTrie();
78 76
79 void insertWord(const QString& s, uint index=0); 77 void insertWord(const QString& s, uint index=0);
80 bool equal(QTrie* o); 78 bool equal(QTrie* o);
81 void dump(int indent=0); 79 void dump(int indent=0);
82 80
83private: 81private:
84 TrieList children; 82 TrieList children;
85 bool isword; 83 bool isword;
86 84
87 friend class QDawgPrivate; 85 friend class QDawgPrivate;
88 int maxdepth; 86 int maxdepth;
89 int decendants; 87 int decendants;
90 int key; 88 int key;
91 void distributeKeys(TrieClubDirectory& directory); 89 void distributeKeys(TrieClubDirectory& directory);
92 QTrie* clubLeader(TrieClubDirectory& directory); 90 QTrie* clubLeader(TrieClubDirectory& directory);
93 int collectKeys(); 91 int collectKeys();
94 friend class TriePtr; 92 friend class TriePtr;
95 friend class TrieList; 93 friend class TrieList;
96}; 94};
97 95
98QTrie::QTrie() 96QTrie::QTrie()
99{ 97{
100 key = 0; 98 key = 0;
101 isword = FALSE; 99 isword = FALSE;
102} 100}
103 101
104QTrie::~QTrie() 102QTrie::~QTrie()
105{ 103{
106 // NOTE: we do not delete the children - after conversion to DAWG 104 // NOTE: we do not delete the children - after conversion to DAWG
107 // it's too difficult. The QTrie's are deleted via the directory. 105 // it's too difficult. The QTrie's are deleted via the directory.
108} 106}
109 107
110void QTrie::insertWord(const QString& s, uint index) 108void QTrie::insertWord(const QString& s, uint index)
111{ 109{
112 if ( index == s.length() ) { 110 if ( index == s.length() ) {
113 isword = TRUE; 111 isword = TRUE;
114 } else { 112 } else {
115 QTrie* t = children.findAdd(s[index]); 113 QTrie* t = children.findAdd(s[index]);
116 t->insertWord(s,index+1); 114 t->insertWord(s,index+1);
117 } 115 }
118} 116}
119 117
120bool QTrie::equal(QTrie* o) 118bool QTrie::equal(QTrie* o)
121{ 119{
122 if ( o == this ) return TRUE; 120 if ( o == this ) return TRUE;
123 if ( isword != o->isword ) 121 if ( isword != o->isword )
124 return FALSE; 122 return FALSE;
125 return children.equal(o->children); 123 return children.equal(o->children);
126} 124}
127 125
128void QTrie::dump(int indent) 126void QTrie::dump(int indent)
129{ 127{
130 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) { 128 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) {
131 QTrie* s = (*it).p; 129 QTrie* s = (*it).p;
132 for (int in=0; in<indent; in++) 130 for (int in=0; in<indent; in++)
133 fputc(' ',stderr); 131 fputc(' ',stderr);
134 fprintf(stderr," %c %d %s %p\n",(*it).letter.unicode(), 132 fprintf(stderr," %c %d %s %p\n",(*it).letter.unicode(),
135 s->key,s->isword?"word":"",s); 133 s->key,s->isword?"word":"",s);
136 s->dump(indent+2); 134 s->dump(indent+2);
137 } 135 }
138} 136}
139 137
140void QTrie::distributeKeys(TrieClubDirectory& directory) 138void QTrie::distributeKeys(TrieClubDirectory& directory)
141{ 139{
142 maxdepth = INT_MIN; 140 maxdepth = INT_MIN;
143 decendants = children.count(); 141 decendants = children.count();
144 key = 0; 142 key = 0;
145 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) { 143 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) {
146 QTrie* s = (*it).p; 144 QTrie* s = (*it).p;
147 QChar l = (*it).letter; 145 QChar l = (*it).letter;
148 s->distributeKeys(directory); 146 s->distributeKeys(directory);
149 key = key*64+l.unicode()+s->key*5; 147 key = key*64+l.unicode()+s->key*5;
150 decendants += s->decendants; 148 decendants += s->decendants;
151 if ( s->maxdepth+1 > maxdepth ) 149 if ( s->maxdepth+1 > maxdepth )
152 maxdepth = s->maxdepth+1; 150 maxdepth = s->maxdepth+1;
153 } 151 }
154 if ( decendants ) { 152 if ( decendants ) {
155 key += decendants + maxdepth*256 + children.count() * 65536; 153 key += decendants + maxdepth*256 + children.count() * 65536;
156 if ( !key ) key++; // unlikely 154 if ( !key ) key++; // unlikely
157 } 155 }
158 TrieClub* c = directory[key]; 156 TrieClub* c = directory[key];
159 if ( !c ) directory.insert(key, (c = new TrieClub) ); 157 if ( !c ) directory.insert(key, (c = new TrieClub) );
160 c->prepend(this); 158 c->prepend(this);
161} 159}
162 160
163QTrie* QTrie::clubLeader(TrieClubDirectory& directory) 161QTrie* QTrie::clubLeader(TrieClubDirectory& directory)
164{ 162{
165 if ( !key ) return directory[0]->first(); 163 if ( !key ) return directory[0]->first();
166 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) { 164 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) {
167 QTrie* t= (*it).p->clubLeader(directory); 165 QTrie* t= (*it).p->clubLeader(directory);
168 (*it).p = t; 166 (*it).p = t;
169 } 167 }
170 TrieClub *club = directory[key]; 168 TrieClub *club = directory[key];
171 for (TrieClub::Iterator it = club->begin(); it != club->end(); ++it) { 169 for (TrieClub::Iterator it = club->begin(); it != club->end(); ++it) {
172 QTrie* o = *it; 170 QTrie* o = *it;
173 if ( o->equal(this) ) 171 if ( o->equal(this) )
174 return o; 172 return o;
175 } 173 }
176 return this; 174 return this;
177} 175}
178 176
179int QTrie::collectKeys() 177int QTrie::collectKeys()
180{ 178{
181 int n=0; 179 int n=0;
182 if ( key ) key=0,n+=children.count(); 180 if ( key ) key=0,n+=children.count();
183 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it) 181 for (TrieList::Iterator it=children.begin(); it!=children.end(); ++it)
184 n += (*it).p->collectKeys(); 182 n += (*it).p->collectKeys();
185 return n; 183 return n;
186} 184}
187 185
188int TriePtr::operator <(const TriePtr& o) const 186int TriePtr::operator <(const TriePtr& o) const
189 { return letter < o.letter; } 187 { return letter < o.letter; }
190int TriePtr::operator >(const TriePtr& o) const 188int TriePtr::operator >(const TriePtr& o) const
191 { return letter > o.letter; } 189 { return letter > o.letter; }
192int TriePtr::operator <=(const TriePtr& o) const 190int TriePtr::operator <=(const TriePtr& o) const
193 { return letter <= o.letter; } 191 { return letter <= o.letter; }
194 192
195bool TrieList::equal(TrieList& l) 193bool TrieList::equal(TrieList& l)
196{ 194{
197 if ( count() != l.count() ) 195 if ( count() != l.count() )
198 return FALSE; 196 return FALSE;
199 sort(); l.sort(); 197 sort(); l.sort();
200 ConstIterator it2 = begin(); 198 ConstIterator it2 = begin();
201 ConstIterator it = l.begin(); 199 ConstIterator it = l.begin();
202 for( ; it != l.end(); ++it, ++it2 ) 200 for( ; it != l.end(); ++it, ++it2 )
203 if ( (*it).letter != (*it2).letter || ! (*it).p->equal((*it2).p) ) 201 if ( (*it).letter != (*it2).letter || ! (*it).p->equal((*it2).p) )
204 return FALSE; 202 return FALSE;
205 return TRUE; 203 return TRUE;
206} 204}
207QTrie* TrieList::findAdd(QChar c) 205QTrie* TrieList::findAdd(QChar c)
208{ 206{
209 for (Iterator it=begin(); it!=end(); ++it) { 207 for (Iterator it=begin(); it!=end(); ++it) {
210 if ( (*it).letter == c ) 208 if ( (*it).letter == c )
211 return (*it).p; 209 return (*it).p;
212 } 210 }
213 TriePtr p; 211 TriePtr p;
214 p.p = new QTrie; 212 p.p = new QTrie;
215 p.letter = c; 213 p.letter = c;
216 prepend(p); 214 prepend(p);
217 sorted=FALSE; 215 sorted=FALSE;
218 sort(); 216 sort();
219 return p.p; 217 return p.p;
220} 218}
221 219
222static const char* dawg_sig = "QDAWG100"; 220static const char* dawg_sig = "QDAWG100";
223 221
224class QDawgPrivate { 222class QDawgPrivate {
225public: 223public:
226 QDawgPrivate(QIODevice* dev) 224 QDawgPrivate(QIODevice* dev)
227 { 225 {
228 QDataStream ds(dev); 226 QDataStream ds(dev);
229 char sig[8]; 227 char sig[8];
230 ds.readRawBytes(sig,8); 228 ds.readRawBytes(sig,8);
231 if ( !strncmp(dawg_sig,sig,8) ) { 229 if ( !strncmp(dawg_sig,sig,8) ) {
232 uint n; 230 uint n;
233 char* nn; 231 char* nn;
234 ds.readBytes(nn,n); 232 ds.readBytes(nn,n);
235 233
236 // #### endianness problem ignored. 234 // #### endianness problem ignored.
237 node = (QDawg::Node*)nn; 235 node = (QDawg::Node*)nn;
238 nodes = n / sizeof(QDawg::Node); 236 nodes = n / sizeof(QDawg::Node);
239 } else { 237 } else {
240 node = 0; 238 node = 0;
241 } 239 }
242 } 240 }
243 241
244 bool ok() const { return node; } 242 bool ok() const { return node; }
245 243
246 QDawgPrivate(uchar* mem) 244 QDawgPrivate(uchar* mem)
247 { 245 {
248 if ( !strncmp(dawg_sig,(char*)mem,8) ) { 246 if ( !strncmp(dawg_sig,(char*)mem,8) ) {
249 mem += 8; 247 mem += 8;
250 248
251 int n = ((mem[0]*256+mem[1])*256+mem[2])*256+mem[3]; 249 int n = ((mem[0]*256+mem[1])*256+mem[2])*256+mem[3];
252 mem += 4; 250 mem += 4;
253 251
254 // #### endianness problem ignored. 252 // #### endianness problem ignored.
255 node = (QDawg::Node*)((char*)mem); 253 node = (QDawg::Node*)((char*)mem);
256 nodes = n / sizeof(QDawg::Node); 254 nodes = n / sizeof(QDawg::Node);
257 } 255 }
258 } 256 }
259 257
260 QDawgPrivate(QTrie* t) // destroys the QTrie. 258 QDawgPrivate(QTrie* t) // destroys the QTrie.
261 { 259 {
262 TrieClubDirectory directory(9973); 260 TrieClubDirectory directory(9973);
263 t->distributeKeys(directory); 261 t->distributeKeys(directory);
264 QTrie* l = t->clubLeader(directory); 262 QTrie* l = t->clubLeader(directory);
265 ASSERT(l==t); 263 ASSERT(l==t);
266 generateArray(t); 264 generateArray(t);
267 265
268 TrieClub *club; 266 TrieClub *club;
269 for (QIntDictIterator<TrieClub> dit(directory); (club=dit); ++dit) 267 for (QIntDictIterator<TrieClub> dit(directory); (club=dit); ++dit)
270 { 268 {
271 for (TrieClub::Iterator it = club->begin(); it != club->end(); ++it) { 269 for (TrieClub::Iterator it = club->begin(); it != club->end(); ++it) {
272 delete *it; 270 delete *it;
273 } 271 }
274 delete club; 272 delete club;
275 } 273 }
276 } 274 }
277 275
278 bool write(QIODevice* dev) 276 bool write(QIODevice* dev)
279 { 277 {
280 QDataStream ds(dev); 278 QDataStream ds(dev);
281 ds.writeRawBytes(dawg_sig,8); 279 ds.writeRawBytes(dawg_sig,8);
282 // #### endianness problem ignored. 280 // #### endianness problem ignored.
283 ds.writeBytes((char*)node,sizeof(QDawg::Node)*nodes); 281 ds.writeBytes((char*)node,sizeof(QDawg::Node)*nodes);
284 return dev->state() == IO_Ok; 282 return dev->state() == IO_Ok;
285 } 283 }
286 284
287 void dumpWords(int nid=0, int index=0) 285 void dumpWords(int nid=0, int index=0)
288 { 286 {
289 static char word[256]; // ick latin1 287 static char word[256]; // ick latin1
290 int i=0; 288 int i=0;
291 do { 289 do {
292 QDawg::Node& n = node[nid+i]; 290 QDawg::Node& n = node[nid+i];
293 word[index] = n.let; 291 word[index] = n.let;
294 if ( n.isword ) 292 if ( n.isword )
295 fprintf(stderr,"%.*s\n",index+1,word); 293 fprintf(stderr,"%.*s\n",index+1,word);
296 if ( n.offset ) dumpWords(n.offset+nid+i,index+1); 294 if ( n.offset ) dumpWords(n.offset+nid+i,index+1);
297 } while (!node[nid+i++].islast); 295 } while (!node[nid+i++].islast);
298 } 296 }
299 297
300 void dump(int nid=0, int indent=0) 298 void dump(int nid=0, int indent=0)
301 { 299 {
302 int i=0; 300 int i=0;
303 do { 301 do {
304 QDawg::Node& n = node[nid+i]; 302 QDawg::Node& n = node[nid+i];
305 fprintf(stderr,"%d: ",nid+i); 303 fprintf(stderr,"%d: ",nid+i);
306 for (int in=0; in<indent; in++) 304 for (int in=0; in<indent; in++)
307 fputc(' ',stderr); 305 fputc(' ',stderr);
308 fprintf(stderr," %c %d %d %d\n",n.let, 306 fprintf(stderr," %c %d %d %d\n",n.let,
309 n.isword,n.islast,n.offset); 307 n.isword,n.islast,n.offset);
310 if ( n.offset ) dump(n.offset+nid+i,indent+2); 308 if ( n.offset ) dump(n.offset+nid+i,indent+2);
311 } while (!node[nid+i++].islast); 309 } while (!node[nid+i++].islast);
312 } 310 }
313 311
314 int countWords(int nid=0) 312 int countWords(int nid=0)
315 { 313 {
316 int t=0; 314 int t=0;
317 int i=0; 315 int i=0;
318 do { 316 do {
319 QDawg::Node& n = node[nid+i]; 317 QDawg::Node& n = node[nid+i];
320 if ( n.isword ) 318 if ( n.isword )
321 t++; 319 t++;
322 if ( n.offset ) 320 if ( n.offset )
323 t+=countWords(n.offset+nid+i); 321 t+=countWords(n.offset+nid+i);
324 } while (!node[nid+i++].islast); 322 } while (!node[nid+i++].islast);
325 return t; 323 return t;
326 } 324 }
327 325
328 bool contains(const QString& s, int nid=0, int index=0) const 326 bool contains(const QString& s, int nid=0, int index=0) const
329 { 327 {
330 int i=0; 328 int i=0;
331 do { 329 do {
332 QDawg::Node& n = node[nid+i]; 330 QDawg::Node& n = node[nid+i];
333 if ( s[index] == QChar((ushort)n.let) ) { 331 if ( s[index] == QChar((ushort)n.let) ) {
334 if ( n.isword && index == (int)s.length()-1 ) 332 if ( n.isword && index == (int)s.length()-1 )
335 return TRUE; 333 return TRUE;
336 if ( n.offset ) 334 if ( n.offset )
337 return contains(s,n.offset+nid+i,index+1); 335 return contains(s,n.offset+nid+i,index+1);
338 } 336 }
339 } while (!node[nid+i++].islast); 337 } while (!node[nid+i++].islast);
340 return FALSE; 338 return FALSE;
341 } 339 }
342 340
343 void appendAllWords(QStringList& list, int nid=0, QString s="") const 341 void appendAllWords(QStringList& list, int nid=0, QString s="") const
344 { 342 {
345 int i=0; 343 int i=0;
346 int next = s.length(); 344 int next = s.length();
347 do { 345 do {
348 QDawg::Node& n = node[nid+i]; 346 QDawg::Node& n = node[nid+i];
349 s[next] = QChar((ushort)n.let); 347 s[next] = QChar((ushort)n.let);
350 if ( n.isword ) 348 if ( n.isword )
351 list.append(s); 349 list.append(s);
352 if ( n.offset ) 350 if ( n.offset )
353 appendAllWords(list, n.offset+nid+i, s); 351 appendAllWords(list, n.offset+nid+i, s);
354 } while (!node[nid+i++].islast); 352 } while (!node[nid+i++].islast);
355 } 353 }
356 354
357 const QDawg::Node* root() { return node; } 355 const QDawg::Node* root() { return node; }
358 356
359private: 357private:
360 void generateArray(QTrie* t) 358 void generateArray(QTrie* t)
361 { 359 {
362 nodes = 0; 360 nodes = 0;
363 int n = t->collectKeys(); 361 int n = t->collectKeys();
364 node = new QDawg::Node[n]; 362 node = new QDawg::Node[n];
365 appendToArray(t); 363 appendToArray(t);
366 ASSERT(n == nodes); 364 ASSERT(n == nodes);
367 } 365 }
368 366
369 int appendToArray(QTrie* t) 367 int appendToArray(QTrie* t)
370 { 368 {
371 if ( !t->key ) { 369 if ( !t->key ) {
372 if ( !t->children.count() ) 370 if ( !t->children.count() )
373 return 0; 371 return 0;
374 t->key = nodes; 372 t->key = nodes;
375 nodes += t->children.count(); 373 nodes += t->children.count();
376 QDawg::Node* n = &node[t->key-1]; 374 QDawg::Node* n = &node[t->key-1];
377 int here = t->key; 375 int here = t->key;
378 for (TrieList::Iterator it=t->children.begin(); it!=t->children.end(); ++it) { 376 for (TrieList::Iterator it=t->children.begin(); it!=t->children.end(); ++it) {
379 QTrie* s = (*it).p; 377 QTrie* s = (*it).p;
380 ++n; 378 ++n;
381 n->let = (*it).letter.unicode(); 379 n->let = (*it).letter.unicode();
382 n->isword = s->isword; 380 n->isword = s->isword;
383 n->islast = 0; 381 n->islast = 0;
384 n->offset = appendToArray(s); 382 n->offset = appendToArray(s);
385 if ( n->offset ) { 383 if ( n->offset ) {
386 int t = n->offset-here; 384 int t = n->offset-here;
387 n->offset=t; 385 n->offset=t;
388 if ( n->offset != t ) 386 if ( n->offset != t )
389 qWarning("Overflow: too many words"); 387 qWarning("Overflow: too many words");
390 } 388 }
391 here++; 389 here++;
392 } 390 }
393 n->islast = 1; 391 n->islast = 1;
394 } 392 }
395 return t->key; 393 return t->key;
396 } 394 }
397 395
398private: 396private:
399 int nodes; 397 int nodes;
400 QDawg::Node *node; 398 QDawg::Node *node;
401}; 399};
402 400
403/*! 401/*!
404 \class QDawg qdawg.h 402 \class QDawg qdawg.h
405 \brief The QDawg class provides an implementation of a Directed Acyclic Word Graph. 403 \brief The QDawg class provides an implementation of a Directed Acyclic Word Graph.
406 404
407 A DAWG provides very fast look-up of words in a word list. 405 A DAWG provides very fast look-up of words in a word list.
408 406
409 The word list is created using readFile(), read() or 407 The word list is created using readFile(), read() or
410 createFromWords(). A list of all the DAWG's words is returned by 408 createFromWords(). A list of all the DAWG's words is returned by
411 allWords(), and the total number of words is returned by 409 allWords(), and the total number of words is returned by
412 countWords(). Use contains() to see if a particular word is in the 410 countWords(). Use contains() to see if a particular word is in the
413 DAWG. The root \link qdawg-node.html node\endlink is returned by root(). 411 DAWG. The root \link qdawg-node.html node\endlink is returned by root().
414 412
415 A global DAWG is maintained for the current locale. See the 413 A global DAWG is maintained for the current locale. See the
416 \l Global class for details. 414 \l Global class for details.
417 415
418 The structure of a DAWG is a graph of \link qdawg-node.html 416 The structure of a DAWG is a graph of \link qdawg-node.html
419 Nodes\endlink. There are no cycles in the graph (since there are no 417 Nodes\endlink. There are no cycles in the graph (since there are no
420 inifinitely repeating words). Each \link qdawg-node.html 418 inifinitely repeating words). Each \link qdawg-node.html
421 Node\endlink is a member of a list of \link qdawg-node.html 419 Node\endlink is a member of a list of \link qdawg-node.html
422 Nodes\endlink called a child list. Each \link qdawg-node.html 420 Nodes\endlink called a child list. Each \link qdawg-node.html
423 Node\endlink in the child list has a \e letter, an \e isWord flag, 421 Node\endlink in the child list has a \e letter, an \e isWord flag,
424 at most one \e jump arc, and at most one arc to the next child in 422 at most one \e jump arc, and at most one arc to the next child in
425 the list. 423 the list.
426 424
427 If you traverse the \link qdawg-node.html Nodes\endlink in a DAWG, 425 If you traverse the \link qdawg-node.html Nodes\endlink in a DAWG,
428 starting from the root(), and you concatenate all the letters from 426 starting from the root(), and you concatenate all the letters from
429 the single child in each child list that you visit, at every \link 427 the single child in each child list that you visit, at every \link
430 qdawg-node.html Node\endlink which has the isWord flag set your 428 qdawg-node.html Node\endlink which has the isWord flag set your
431 concatenation will be a word in the list represented by the DAWG. 429 concatenation will be a word in the list represented by the DAWG.
432 430
433 For example, the DAWG below represents the word list: 431 For example, the DAWG below represents the word list:
434 ban, band, can, cane, cans, pan, pane, pans. 432 ban, band, can, cane, cans, pan, pane, pans.
435 433
436 This structuring not only provides O(1) lookup of words in the word list, 434 This structuring not only provides O(1) lookup of words in the word list,
437 but also produces a smaller storage file than a plain text file word list. 435 but also produces a smaller storage file than a plain text file word list.
438 436
439 \img qdawg.png 437 \img qdawg.png
440*/ 438*/
441 439
442/*! 440/*!
443 Constructs a new empty DAWG. 441 Constructs a new empty DAWG.
444*/ 442*/
445QDawg::QDawg() 443QDawg::QDawg()
446{ 444{
447 d = 0; 445 d = 0;
448} 446}
449 447
450/*! 448/*!
451 Deletes the DAWG. 449 Deletes the DAWG.
452*/ 450*/
453QDawg::~QDawg() 451QDawg::~QDawg()
454{ 452{
455 delete d; 453 delete d;
456} 454}
457 455
458/*! 456/*!
459 \overload 457 \overload
460 Replaces all the DAWG's words with words read from \a dev. 458 Replaces all the DAWG's words with words read from \a dev.
461*/ 459*/
462bool QDawg::createFromWords(QIODevice* dev) 460bool QDawg::createFromWords(QIODevice* dev)
463{ 461{
464 delete d; 462 delete d;
465 463
466 QTextStream i(dev); 464 QTextStream i(dev);
467 QTrie* trie = new QTrie; 465 QTrie* trie = new QTrie;
468 int n=0; 466 int n=0;
469 while (!i.atEnd()) { 467 while (!i.atEnd()) {
470 trie->insertWord(QString::fromUtf8(i.readLine())); 468 trie->insertWord(QString::fromUtf8(i.readLine()));
471 n++; 469 n++;
472 } 470 }
473 if ( n ) 471 if ( n )
474 d = new QDawgPrivate(trie); 472 d = new QDawgPrivate(trie);
475 else 473 else
476 d = 0; 474 d = 0;
477 return TRUE; 475 return TRUE;
478} 476}
479 477
480/*! 478/*!
481 Replaces all the DAWG's words with the words in the \a list. 479 Replaces all the DAWG's words with the words in the \a list.
482*/ 480*/
483void QDawg::createFromWords(const QStringList& list) 481void QDawg::createFromWords(const QStringList& list)
484{ 482{
485 delete d; 483 delete d;
486 484
487 if ( list.count() ) { 485 if ( list.count() ) {
488 QTrie* trie = new QTrie; 486 QTrie* trie = new QTrie;
489 for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) { 487 for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) {
490 trie->insertWord(*it); 488 trie->insertWord(*it);
491 } 489 }
492 d = new QDawgPrivate(trie); 490 d = new QDawgPrivate(trie);
493 } else { 491 } else {
494 d = 0; 492 d = 0;
495 } 493 }
496} 494}
497 495
498/*! 496/*!
499 Returns a list of all the words in the DAWG. 497 Returns a list of all the words in the DAWG.
500*/ 498*/
501QStringList QDawg::allWords() const 499QStringList QDawg::allWords() const
502{ 500{
503 QStringList result; 501 QStringList result;
504 if ( d ) d->appendAllWords(result); 502 if ( d ) d->appendAllWords(result);
505 return result; 503 return result;
506} 504}
507 505
508 506
509/*! 507/*!
510 Replaces the DAWG with the DAWG in \a filename. 508 Replaces the DAWG with the DAWG in \a filename.
511 The file is memory-mapped. 509 The file is memory-mapped.
512 510
513 \sa write() 511 \sa write()
514*/ 512*/
515bool QDawg::readFile(const QString& filename) 513bool QDawg::readFile(const QString& filename)
516{ 514{
517 delete d; 515 delete d;
518 d = 0; 516 d = 0;
519 int f = ::open( QFile::encodeName(filename), O_RDONLY ); 517 int f = ::open( QFile::encodeName(filename), O_RDONLY );
520 if ( f < 0 ) 518 if ( f < 0 )
521 return FALSE; 519 return FALSE;
522 struct stat st; 520 struct stat st;
523 if ( !fstat( f, &st ) ) { 521 if ( !fstat( f, &st ) ) {
524 char * tmp = (char*)mmap( 0, st.st_size, // any address, whole file 522 char * tmp = (char*)mmap( 0, st.st_size, // any address, whole file
525 PROT_READ, // read-only memory 523 PROT_READ, // read-only memory
526 MAP_FILE | MAP_PRIVATE, // swap-backed map from file 524 MAP_FILE | MAP_PRIVATE, // swap-backed map from file
527 f, 0 ); // from offset 0 of f 525 f, 0 ); // from offset 0 of f
528 if ( tmp && tmp != (char*)MAP_FAILED ) 526 if ( tmp && tmp != (char*)MAP_FAILED )
529 d = new QDawgPrivate((uchar*)tmp); 527 d = new QDawgPrivate((uchar*)tmp);
530 } 528 }
531 ::close( f ); 529 ::close( f );
532 return d; 530 return d;
533} 531}
534 532
535/*! 533/*!
536 Replaces the DAWG with the DAWG in \a dev. 534 Replaces the DAWG with the DAWG in \a dev.
537 The file is memory-mapped. 535 The file is memory-mapped.
538 536
539 \sa write() 537 \sa write()
540*/ 538*/
541bool QDawg::read(QIODevice* dev) 539bool QDawg::read(QIODevice* dev)
542{ 540{
543 delete d; 541 delete d;
544 d = new QDawgPrivate(dev); 542 d = new QDawgPrivate(dev);
545 if ( d->ok() ) 543 if ( d->ok() )
546 return TRUE; 544 return TRUE;
547 delete d; 545 delete d;
548 d = 0; 546 d = 0;
549 return FALSE; 547 return FALSE;
550} 548}
551 549
552/*! 550/*!
553 Writes the DAWG to \a dev, in a custom QDAWG format. 551 Writes the DAWG to \a dev, in a custom QDAWG format.
554*/ 552*/
555bool QDawg::write(QIODevice* dev) const 553bool QDawg::write(QIODevice* dev) const
556{ 554{
557 return d ? d->write(dev) : TRUE; 555 return d ? d->write(dev) : TRUE;
558} 556}
559 557
560/*! 558/*!
561 Returns the number of words in the DAWG. 559 Returns the number of words in the DAWG.
562*/ 560*/
563int QDawg::countWords() const 561int QDawg::countWords() const
564{ 562{
565 return d ? d->countWords() : 0; 563 return d ? d->countWords() : 0;
566} 564}
567 565
568/*! 566/*!
569 Returns the root \link qdawg-node.html Node\endlink of the DAWG. 567 Returns the root \link qdawg-node.html Node\endlink of the DAWG.
570*/ 568*/
571const QDawg::Node* QDawg::root() const 569const QDawg::Node* QDawg::root() const
572{ 570{
573 return d ? d->root() : 0; 571 return d ? d->root() : 0;
574} 572}
575 573
576/*! 574/*!
577 Returns TRUE if the DAWG contains the word \a s; otherwise returns 575 Returns TRUE if the DAWG contains the word \a s; otherwise returns
578 FALSE. 576 FALSE.
579*/ 577*/
580bool QDawg::contains(const QString& s) const 578bool QDawg::contains(const QString& s) const
581{ 579{
582 return d ? d->contains(s) : FALSE; 580 return d ? d->contains(s) : FALSE;
583} 581}
584 582
585/*! 583/*!
586 \internal 584 \internal
587 585
588 For debugging: prints out the DAWG contents. 586 For debugging: prints out the DAWG contents.
589*/ 587*/
590void QDawg::dump() const 588void QDawg::dump() const
591{ 589{
592 if ( d ) d->dump(); 590 if ( d ) d->dump();
593} 591}
594 592
595/*! 593/*!
596 \class QDawg::Node qdawg.h 594 \class QDawg::Node qdawg.h
597 \brief The QDawg::Node class represents one node of a QDawg. 595 \brief The QDawg::Node class represents one node of a QDawg.
598*/ 596*/
599 597
600/*! 598/*!
601 \fn QChar QDawg::Node::letter() const 599 \fn QChar QDawg::Node::letter() const
602 600
603 Returns this Node's letter. 601 Returns this Node's letter.
604*/ 602*/
605/*! 603/*!
606 \fn bool QDawg::Node::isWord() const 604 \fn bool QDawg::Node::isWord() const
607 605
608 Returns TRUE if this Node is the end of a word; otherwise returns 606 Returns TRUE if this Node is the end of a word; otherwise returns
609 FALSE. 607 FALSE.
610*/ 608*/
611/*! 609/*!
612 \fn bool QDawg::Node::isLast() const 610 \fn bool QDawg::Node::isLast() const
613 611
614 Returns TRUE if this Node is the last in the child list; otherwise 612 Returns TRUE if this Node is the last in the child list; otherwise
615 returns FALSE. 613 returns FALSE.
616*/ 614*/
617/*! 615/*!
618 \fn const Node* QDawg::Node::next() const 616 \fn const Node* QDawg::Node::next() const
619 617
620 Returns the next child Node in the child list or 0 if the current 618 Returns the next child Node in the child list or 0 if the current
621 Node isLast(). 619 Node isLast().
622*/ 620*/
623/*! 621/*!
624 \fn const Node* QDawg::Node::jump() const 622 \fn const Node* QDawg::Node::jump() const
625 623
626 Returns the node connected to this Node. 624 Returns the node connected to this Node.
627*/ 625*/
diff --git a/library/qpeapplication.cpp b/library/qpeapplication.cpp
index c7ef2b7..262221e 100644
--- a/library/qpeapplication.cpp
+++ b/library/qpeapplication.cpp
@@ -1,2100 +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#include <qpixmapcache.h>
1106 1105
1107extern void qws_clearLoadedFonts(); 1106extern void qws_clearLoadedFonts();
1108 1107
1109void QPEApplication::setCurrentMode( int x, int y, int depth ) 1108void QPEApplication::setCurrentMode( int x, int y, int depth )
1110{ 1109{
1111 // Reset the caches 1110 // Reset the caches
1112 qws_clearLoadedFonts(); 1111 qws_clearLoadedFonts();
1113 QPixmapCache::clear(); 1112 QPixmapCache::clear();
1114 1113
1115 // Change the screen mode 1114 // Change the screen mode
1116 qt_screen->setMode(x, y, depth); 1115 qt_screen->setMode(x, y, depth);
1117 1116
1118 if ( qApp->type() == GuiServer ) { 1117 if ( qApp->type() == GuiServer ) {
1119 // Reconfigure the GuiServer 1118 // Reconfigure the GuiServer
1120 qwsServer->beginDisplayReconfigure(); 1119 qwsServer->beginDisplayReconfigure();
1121 qwsServer->endDisplayReconfigure(); 1120 qwsServer->endDisplayReconfigure();
1122 1121
1123 // Get all the running apps to reset 1122 // Get all the running apps to reset
1124 QCopEnvelope env( "QPE/System", "reset()" ); 1123 QCopEnvelope env( "QPE/System", "reset()" );
1125 } 1124 }
1126} 1125}
1127 1126
1128void QPEApplication::reset() { 1127void QPEApplication::reset() {
1129 // Reconnect to the screen 1128 // Reconnect to the screen
1130 qt_screen->disconnect(); 1129 qt_screen->disconnect();
1131 qt_screen->connect( QString::null ); 1130 qt_screen->connect( QString::null );
1132 1131
1133 // Redraw everything 1132 // Redraw everything
1134 applyStyle(); 1133 applyStyle();
1135} 1134}
1136 1135
1137/*! 1136/*!
1138 \internal 1137 \internal
1139*/ 1138*/
1140void QPEApplication::applyStyle() 1139void QPEApplication::applyStyle()
1141{ 1140{
1142 Config config( "qpe" ); 1141 Config config( "qpe" );
1143 config.setGroup( "Appearance" ); 1142 config.setGroup( "Appearance" );
1144 1143
1145#if QT_VERSION > 233 1144#if QT_VERSION > 233
1146#if !defined(OPIE_NO_OVERRIDE_QT) 1145#if !defined(OPIE_NO_OVERRIDE_QT)
1147 // don't block ourselves ... 1146 // don't block ourselves ...
1148 Opie::force_appearance = 0; 1147 Opie::force_appearance = 0;
1149 1148
1150 static QString appname = Opie::binaryName ( ); 1149 static QString appname = Opie::binaryName ( );
1151 1150
1152 QStringList ex = config. readListEntry ( "NoStyle", ';' ); 1151 QStringList ex = config. readListEntry ( "NoStyle", ';' );
1153 int nostyle = 0; 1152 int nostyle = 0;
1154 for ( QStringList::Iterator it = ex. begin ( ); it != ex. end ( ); ++it ) { 1153 for ( QStringList::Iterator it = ex. begin ( ); it != ex. end ( ); ++it ) {
1155 if ( QRegExp (( *it ). mid ( 1 ), false, true ). find ( appname, 0 ) >= 0 ) { 1154 if ( QRegExp (( *it ). mid ( 1 ), false, true ). find ( appname, 0 ) >= 0 ) {
1156 nostyle = ( *it ). left ( 1 ). toInt ( 0, 32 ); 1155 nostyle = ( *it ). left ( 1 ). toInt ( 0, 32 );
1157 break; 1156 break;
1158 } 1157 }
1159 } 1158 }
1160#else 1159#else
1161 int nostyle = 0; 1160 int nostyle = 0;
1162#endif 1161#endif
1163 1162
1164 // Widget style 1163 // Widget style
1165 QString style = config.readEntry( "Style", "FlatStyle" ); 1164 QString style = config.readEntry( "Style", "FlatStyle" );
1166 1165
1167 // don't set a custom style 1166 // don't set a custom style
1168 if ( nostyle & Opie::Force_Style ) 1167 if ( nostyle & Opie::Force_Style )
1169 style = "FlatStyle"; 1168 style = "FlatStyle";
1170 1169
1171 internalSetStyle ( style ); 1170 internalSetStyle ( style );
1172 1171
1173 // Colors - from /etc/colors/Liquid.scheme 1172 // Colors - from /etc/colors/Liquid.scheme
1174 QColor bgcolor( config.readEntry( "Background", "#E0E0E0" ) ); 1173 QColor bgcolor( config.readEntry( "Background", "#E0E0E0" ) );
1175 QColor btncolor( config.readEntry( "Button", "#96c8fa" ) ); 1174 QColor btncolor( config.readEntry( "Button", "#96c8fa" ) );
1176 QPalette pal( btncolor, bgcolor ); 1175 QPalette pal( btncolor, bgcolor );
1177 QString color = config.readEntry( "Highlight", "#73adef" ); 1176 QString color = config.readEntry( "Highlight", "#73adef" );
1178 pal.setColor( QColorGroup::Highlight, QColor( color ) ); 1177 pal.setColor( QColorGroup::Highlight, QColor( color ) );
1179 color = config.readEntry( "HighlightedText", "#FFFFFF" ); 1178 color = config.readEntry( "HighlightedText", "#FFFFFF" );
1180 pal.setColor( QColorGroup::HighlightedText, QColor( color ) ); 1179 pal.setColor( QColorGroup::HighlightedText, QColor( color ) );
1181 color = config.readEntry( "Text", "#000000" ); 1180 color = config.readEntry( "Text", "#000000" );
1182 pal.setColor( QColorGroup::Text, QColor( color ) ); 1181 pal.setColor( QColorGroup::Text, QColor( color ) );
1183 color = config.readEntry( "ButtonText", "#000000" ); 1182 color = config.readEntry( "ButtonText", "#000000" );
1184 pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) ); 1183 pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) );
1185 color = config.readEntry( "Base", "#FFFFFF" ); 1184 color = config.readEntry( "Base", "#FFFFFF" );
1186 pal.setColor( QColorGroup::Base, QColor( color ) ); 1185 pal.setColor( QColorGroup::Base, QColor( color ) );
1187 1186
1188 pal.setColor( QPalette::Disabled, QColorGroup::Text, 1187 pal.setColor( QPalette::Disabled, QColorGroup::Text,
1189 pal.color( QPalette::Active, QColorGroup::Background ).dark() ); 1188 pal.color( QPalette::Active, QColorGroup::Background ).dark() );
1190 1189
1191 setPalette( pal, TRUE ); 1190 setPalette( pal, TRUE );
1192 1191
1193 // Window Decoration 1192 // Window Decoration
1194 QString dec = config.readEntry( "Decoration", "Flat" ); 1193 QString dec = config.readEntry( "Decoration", "Flat" );
1195 1194
1196 // don't set a custom deco 1195 // don't set a custom deco
1197 if ( nostyle & Opie::Force_Decoration ) 1196 if ( nostyle & Opie::Force_Decoration )
1198 dec = ""; 1197 dec = "";
1199 1198
1200 //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);
1201 1200
1202 if ( dec != d->decorationName ) { 1201 if ( dec != d->decorationName ) {
1203 qwsSetDecoration( new QPEDecoration( dec ) ); 1202 qwsSetDecoration( new QPEDecoration( dec ) );
1204 d->decorationName = dec; 1203 d->decorationName = dec;
1205 } 1204 }
1206 1205
1207 // Font 1206 // Font
1208 QString ff = config.readEntry( "FontFamily", font().family() ); 1207 QString ff = config.readEntry( "FontFamily", font().family() );
1209 int fs = config.readNumEntry( "FontSize", font().pointSize() ); 1208 int fs = config.readNumEntry( "FontSize", font().pointSize() );
1210 1209
1211 // don't set a custom font 1210 // don't set a custom font
1212 if ( nostyle & Opie::Force_Font ) { 1211 if ( nostyle & Opie::Force_Font ) {
1213 ff = "Vera"; 1212 ff = "Vera";
1214 fs = 10; 1213 fs = 10;
1215 } 1214 }
1216 1215
1217 setFont ( QFont ( ff, fs ), true ); 1216 setFont ( QFont ( ff, fs ), true );
1218 1217
1219#if !defined(OPIE_NO_OVERRIDE_QT) 1218#if !defined(OPIE_NO_OVERRIDE_QT)
1220 // revert to global blocking policy ... 1219 // revert to global blocking policy ...
1221 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;
1222 Opie::force_appearance &= ~nostyle; 1221 Opie::force_appearance &= ~nostyle;
1223#endif 1222#endif
1224#endif 1223#endif
1225} 1224}
1226 1225
1227void QPEApplication::systemMessage( const QCString& msg, const QByteArray& data ) 1226void QPEApplication::systemMessage( const QCString& msg, const QByteArray& data )
1228{ 1227{
1229#ifdef Q_WS_QWS 1228#ifdef Q_WS_QWS
1230 QDataStream stream( data, IO_ReadOnly ); 1229 QDataStream stream( data, IO_ReadOnly );
1231 if ( msg == "applyStyle()" ) { 1230 if ( msg == "applyStyle()" ) {
1232 applyStyle(); 1231 applyStyle();
1233 } 1232 }
1234 else if ( msg == "toggleApplicationMenu()" ) { 1233 else if ( msg == "toggleApplicationMenu()" ) {
1235 QWidget *active = activeWindow ( ); 1234 QWidget *active = activeWindow ( );
1236 1235
1237 if ( active ) { 1236 if ( active ) {
1238 QPEMenuToolFocusManager *man = QPEMenuToolFocusManager::manager ( ); 1237 QPEMenuToolFocusManager *man = QPEMenuToolFocusManager::manager ( );
1239 bool oldactive = man-> isActive ( ); 1238 bool oldactive = man-> isActive ( );
1240 1239
1241 man-> setActive( !man-> isActive() ); 1240 man-> setActive( !man-> isActive() );
1242 1241
1243 if ( !oldactive && !man-> isActive ( )) { // no menubar to toggle -> try O-Menu 1242 if ( !oldactive && !man-> isActive ( )) { // no menubar to toggle -> try O-Menu
1244 QCopEnvelope e ( "QPE/TaskBar", "toggleStartMenu()" ); 1243 QCopEnvelope e ( "QPE/TaskBar", "toggleStartMenu()" );
1245 } 1244 }
1246 } 1245 }
1247 } 1246 }
1248 else if ( msg == "setDefaultRotation(int)" ) { 1247 else if ( msg == "setDefaultRotation(int)" ) {
1249 if ( type() == GuiServer ) { 1248 if ( type() == GuiServer ) {
1250 int r; 1249 int r;
1251 stream >> r; 1250 stream >> r;
1252 setDefaultRotation( r ); 1251 setDefaultRotation( r );
1253 } 1252 }
1254 } 1253 }
1255 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>
1256 if ( type() == GuiServer ) { 1255 if ( type() == GuiServer ) {
1257 int x, y, depth; 1256 int x, y, depth;
1258 stream >> x; 1257 stream >> x;
1259 stream >> y; 1258 stream >> y;
1260 stream >> depth; 1259 stream >> depth;
1261 setCurrentMode( x, y, depth ); 1260 setCurrentMode( x, y, depth );
1262 } 1261 }
1263 } 1262 }
1264 else if ( msg == "reset()" ) { 1263 else if ( msg == "reset()" ) {
1265 if ( type() != GuiServer ) 1264 if ( type() != GuiServer )
1266 reset(); 1265 reset();
1267 } 1266 }
1268 else if ( msg == "setCurrentRotation(int)" ) { 1267 else if ( msg == "setCurrentRotation(int)" ) {
1269 int r; 1268 int r;
1270 stream >> r; 1269 stream >> r;
1271 setCurrentRotation( r ); 1270 setCurrentRotation( r );
1272 } 1271 }
1273 else if ( msg == "shutdown()" ) { 1272 else if ( msg == "shutdown()" ) {
1274 if ( type() == GuiServer ) 1273 if ( type() == GuiServer )
1275 shutdown(); 1274 shutdown();
1276 } 1275 }
1277 else if ( msg == "quit()" ) { 1276 else if ( msg == "quit()" ) {
1278 if ( type() != GuiServer ) 1277 if ( type() != GuiServer )
1279 tryQuit(); 1278 tryQuit();
1280 } 1279 }
1281 else if ( msg == "forceQuit()" ) { 1280 else if ( msg == "forceQuit()" ) {
1282 if ( type() != GuiServer ) 1281 if ( type() != GuiServer )
1283 quit(); 1282 quit();
1284 } 1283 }
1285 else if ( msg == "restart()" ) { 1284 else if ( msg == "restart()" ) {
1286 if ( type() == GuiServer ) 1285 if ( type() == GuiServer )
1287 restart(); 1286 restart();
1288 } 1287 }
1289 else if ( msg == "language(QString)" ) { 1288 else if ( msg == "language(QString)" ) {
1290 if ( type() == GuiServer ) { 1289 if ( type() == GuiServer ) {
1291 QString l; 1290 QString l;
1292 stream >> l; 1291 stream >> l;
1293 QString cl = getenv( "LANG" ); 1292 QString cl = getenv( "LANG" );
1294 if ( cl != l ) { 1293 if ( cl != l ) {
1295 if ( l.isNull() ) 1294 if ( l.isNull() )
1296 unsetenv( "LANG" ); 1295 unsetenv( "LANG" );
1297 else 1296 else
1298 setenv( "LANG", l.latin1(), 1 ); 1297 setenv( "LANG", l.latin1(), 1 );
1299 restart(); 1298 restart();
1300 } 1299 }
1301 } 1300 }
1302 } 1301 }
1303 else if ( msg == "timeChange(QString)" ) { 1302 else if ( msg == "timeChange(QString)" ) {
1304 QString t; 1303 QString t;
1305 stream >> t; 1304 stream >> t;
1306 if ( t.isNull() ) 1305 if ( t.isNull() )
1307 unsetenv( "TZ" ); 1306 unsetenv( "TZ" );
1308 else 1307 else
1309 setenv( "TZ", t.latin1(), 1 ); 1308 setenv( "TZ", t.latin1(), 1 );
1310 // emit the signal so everyone else knows... 1309 // emit the signal so everyone else knows...
1311 emit timeChanged(); 1310 emit timeChanged();
1312 } 1311 }
1313 else if ( msg == "addAlarm(QDateTime,QCString,QCString,int)" ) { 1312 else if ( msg == "addAlarm(QDateTime,QCString,QCString,int)" ) {
1314 if ( type() == GuiServer ) { 1313 if ( type() == GuiServer ) {
1315 QDateTime when; 1314 QDateTime when;
1316 QCString channel, message; 1315 QCString channel, message;
1317 int data; 1316 int data;
1318 stream >> when >> channel >> message >> data; 1317 stream >> when >> channel >> message >> data;
1319 AlarmServer::addAlarm( when, channel, message, data ); 1318 AlarmServer::addAlarm( when, channel, message, data );
1320 } 1319 }
1321 } 1320 }
1322 else if ( msg == "deleteAlarm(QDateTime,QCString,QCString,int)" ) { 1321 else if ( msg == "deleteAlarm(QDateTime,QCString,QCString,int)" ) {
1323 if ( type() == GuiServer ) { 1322 if ( type() == GuiServer ) {
1324 QDateTime when; 1323 QDateTime when;
1325 QCString channel, message; 1324 QCString channel, message;
1326 int data; 1325 int data;
1327 stream >> when >> channel >> message >> data; 1326 stream >> when >> channel >> message >> data;
1328 AlarmServer::deleteAlarm( when, channel, message, data ); 1327 AlarmServer::deleteAlarm( when, channel, message, data );
1329 } 1328 }
1330 } 1329 }
1331 else if ( msg == "clockChange(bool)" ) { 1330 else if ( msg == "clockChange(bool)" ) {
1332 int tmp; 1331 int tmp;
1333 stream >> tmp; 1332 stream >> tmp;
1334 emit clockChanged( tmp ); 1333 emit clockChanged( tmp );
1335 } 1334 }
1336 else if ( msg == "weekChange(bool)" ) { 1335 else if ( msg == "weekChange(bool)" ) {
1337 int tmp; 1336 int tmp;
1338 stream >> tmp; 1337 stream >> tmp;
1339 emit weekChanged( tmp ); 1338 emit weekChanged( tmp );
1340 } 1339 }
1341 else if ( msg == "setDateFormat(DateFormat)" ) { 1340 else if ( msg == "setDateFormat(DateFormat)" ) {
1342 DateFormat tmp; 1341 DateFormat tmp;
1343 stream >> tmp; 1342 stream >> tmp;
1344 emit dateFormatChanged( tmp ); 1343 emit dateFormatChanged( tmp );
1345 } 1344 }
1346 else if ( msg == "setVolume(int,int)" ) { 1345 else if ( msg == "setVolume(int,int)" ) {
1347 int t, v; 1346 int t, v;
1348 stream >> t >> v; 1347 stream >> t >> v;
1349 setVolume( t, v ); 1348 setVolume( t, v );
1350 emit volumeChanged( muted ); 1349 emit volumeChanged( muted );
1351 } 1350 }
1352 else if ( msg == "volumeChange(bool)" ) { 1351 else if ( msg == "volumeChange(bool)" ) {
1353 stream >> muted; 1352 stream >> muted;
1354 setVolume(); 1353 setVolume();
1355 emit volumeChanged( muted ); 1354 emit volumeChanged( muted );
1356 } 1355 }
1357 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>
1358 int t, v; 1357 int t, v;
1359 stream >> t >> v; 1358 stream >> t >> v;
1360 setMic( t, v ); 1359 setMic( t, v );
1361 emit micChanged( micMuted ); 1360 emit micChanged( micMuted );
1362 } 1361 }
1363 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>
1364 stream >> micMuted; 1363 stream >> micMuted;
1365 setMic(); 1364 setMic();
1366 emit micChanged( micMuted ); 1365 emit micChanged( micMuted );
1367 } 1366 }
1368 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>
1369 int t, v; 1368 int t, v;
1370 stream >> t >> v; 1369 stream >> t >> v;
1371 setBass( t, v ); 1370 setBass( t, v );
1372 } 1371 }
1373 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>
1374 setBass(); 1373 setBass();
1375 } 1374 }
1376 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>
1377 int t, v; 1376 int t, v;
1378 stream >> t >> v; 1377 stream >> t >> v;
1379 setTreble( t, v ); 1378 setTreble( t, v );
1380 } 1379 }
1381 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>
1382 setTreble(); 1381 setTreble();
1383 } else if ( msg == "getMarkedText()" ) { 1382 } else if ( msg == "getMarkedText()" ) {
1384 if ( type() == GuiServer ) { 1383 if ( type() == GuiServer ) {
1385 const ushort unicode = 'C'-'@'; 1384 const ushort unicode = 'C'-'@';
1386 const int scan = Key_C; 1385 const int scan = Key_C;
1387 qwsServer->processKeyEvent( unicode, scan, ControlButton, TRUE, FALSE ); 1386 qwsServer->processKeyEvent( unicode, scan, ControlButton, TRUE, FALSE );
1388 qwsServer->processKeyEvent( unicode, scan, ControlButton, FALSE, FALSE ); 1387 qwsServer->processKeyEvent( unicode, scan, ControlButton, FALSE, FALSE );
1389 } 1388 }
1390 } else if ( msg == "newChannel(QString)") { 1389 } else if ( msg == "newChannel(QString)") {
1391 QString myChannel = "QPE/Application/" + d->appName; 1390 QString myChannel = "QPE/Application/" + d->appName;
1392 QString channel; 1391 QString channel;
1393 stream >> channel; 1392 stream >> channel;
1394 if (channel == myChannel) { 1393 if (channel == myChannel) {
1395 processQCopFile(); 1394 processQCopFile();
1396 d->sendQCopQ(); 1395 d->sendQCopQ();
1397 } 1396 }
1398 } 1397 }
1399 1398
1400 1399
1401#endif 1400#endif
1402} 1401}
1403 1402
1404 1403
1405 1404
1406 1405
1407 1406
1408/*! 1407/*!
1409 \internal 1408 \internal
1410*/ 1409*/
1411bool QPEApplication::raiseAppropriateWindow() 1410bool QPEApplication::raiseAppropriateWindow()
1412{ 1411{
1413 bool r=FALSE; 1412 bool r=FALSE;
1414 1413
1415 // 1. Raise the main widget 1414 // 1. Raise the main widget
1416 QWidget *top = d->qpe_main_widget; 1415 QWidget *top = d->qpe_main_widget;
1417 if ( !top ) top = mainWidget(); 1416 if ( !top ) top = mainWidget();
1418 1417
1419 if ( top && d->keep_running ) { 1418 if ( top && d->keep_running ) {
1420 if ( top->isVisible() ) 1419 if ( top->isVisible() )
1421 r = TRUE; 1420 r = TRUE;
1422 else if (d->preloaded) { 1421 else if (d->preloaded) {
1423 // We are preloaded and not visible.. pretend we just started.. 1422 // We are preloaded and not visible.. pretend we just started..
1424#ifndef QT_NO_COP 1423#ifndef QT_NO_COP
1425 QCopEnvelope e("QPE/System", "fastAppShowing(QString)"); 1424 QCopEnvelope e("QPE/System", "fastAppShowing(QString)");
1426 e << d->appName; 1425 e << d->appName;
1427#endif 1426#endif
1428 } 1427 }
1429 1428
1430 d->show_mx(top,d->nomaximize, d->appName); 1429 d->show_mx(top,d->nomaximize, d->appName);
1431 top->raise(); 1430 top->raise();
1432 } 1431 }
1433 1432
1434 QWidget *topm = activeModalWidget(); 1433 QWidget *topm = activeModalWidget();
1435 1434
1436 // 2. Raise any parentless widgets (except top and topm, as they 1435 // 2. Raise any parentless widgets (except top and topm, as they
1437 // are raised before and after this loop). Order from most 1436 // are raised before and after this loop). Order from most
1438 // recently raised as deepest to least recently as top, so 1437 // recently raised as deepest to least recently as top, so
1439 // that repeated calls cycle through widgets. 1438 // that repeated calls cycle through widgets.
1440 QWidgetList *list = topLevelWidgets(); 1439 QWidgetList *list = topLevelWidgets();
1441 if ( list ) { 1440 if ( list ) {
1442 bool foundlast = FALSE; 1441 bool foundlast = FALSE;
1443 QWidget* topsub = 0; 1442 QWidget* topsub = 0;
1444 if ( d->lastraised ) { 1443 if ( d->lastraised ) {
1445 for (QWidget* w = list->first(); w; w = list->next()) { 1444 for (QWidget* w = list->first(); w; w = list->next()) {
1446 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) { 1445 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) {
1447 if ( w == d->lastraised ) 1446 if ( w == d->lastraised )
1448 foundlast = TRUE; 1447 foundlast = TRUE;
1449 if ( foundlast ) { 1448 if ( foundlast ) {
1450 w->raise(); 1449 w->raise();
1451 topsub = w; 1450 topsub = w;
1452 } 1451 }
1453 } 1452 }
1454 } 1453 }
1455 } 1454 }
1456 for (QWidget* w = list->first(); w; w = list->next()) { 1455 for (QWidget* w = list->first(); w; w = list->next()) {
1457 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) { 1456 if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) {
1458 if ( w == d->lastraised ) 1457 if ( w == d->lastraised )
1459 break; 1458 break;
1460 w->raise(); 1459 w->raise();
1461 topsub = w; 1460 topsub = w;
1462 } 1461 }
1463 } 1462 }
1464 d->lastraised = topsub; 1463 d->lastraised = topsub;
1465 delete list; 1464 delete list;
1466 } 1465 }
1467 1466
1468 // 3. Raise the active modal widget. 1467 // 3. Raise the active modal widget.
1469 if ( topm && topm != top ) { 1468 if ( topm && topm != top ) {
1470 topm->show(); 1469 topm->show();
1471 topm->raise(); 1470 topm->raise();
1472 // If we haven't already handled the fastAppShowing message 1471 // If we haven't already handled the fastAppShowing message
1473 if (!top && d->preloaded) { 1472 if (!top && d->preloaded) {
1474#ifndef QT_NO_COP 1473#ifndef QT_NO_COP
1475 QCopEnvelope e("QPE/System", "fastAppShowing(QString)"); 1474 QCopEnvelope e("QPE/System", "fastAppShowing(QString)");
1476 e << d->appName; 1475 e << d->appName;
1477#endif 1476#endif
1478 } 1477 }
1479 r = FALSE; 1478 r = FALSE;
1480 } 1479 }
1481 1480
1482 return r; 1481 return r;
1483} 1482}
1484 1483
1485 1484
1486void QPEApplication::pidMessage( const QCString& msg, const QByteArray& data) 1485void QPEApplication::pidMessage( const QCString& msg, const QByteArray& data)
1487{ 1486{
1488#ifdef Q_WS_QWS 1487#ifdef Q_WS_QWS
1489 1488
1490 if ( msg == "quit()" ) { 1489 if ( msg == "quit()" ) {
1491 tryQuit(); 1490 tryQuit();
1492 } 1491 }
1493 else if ( msg == "quitIfInvisible()" ) { 1492 else if ( msg == "quitIfInvisible()" ) {
1494 if ( d->qpe_main_widget && !d->qpe_main_widget->isVisible() ) 1493 if ( d->qpe_main_widget && !d->qpe_main_widget->isVisible() )
1495 quit(); 1494 quit();
1496 } 1495 }
1497 else if ( msg == "close()" ) { 1496 else if ( msg == "close()" ) {
1498 hideOrQuit(); 1497 hideOrQuit();
1499 } 1498 }
1500 else if ( msg == "disablePreload()" ) { 1499 else if ( msg == "disablePreload()" ) {
1501 d->preloaded = FALSE; 1500 d->preloaded = FALSE;
1502 d->keep_running = TRUE; 1501 d->keep_running = TRUE;
1503 /* so that quit will quit */ 1502 /* so that quit will quit */
1504 } 1503 }
1505 else if ( msg == "enablePreload()" ) { 1504 else if ( msg == "enablePreload()" ) {
1506 if (d->qpe_main_widget) 1505 if (d->qpe_main_widget)
1507 d->preloaded = TRUE; 1506 d->preloaded = TRUE;
1508 d->keep_running = TRUE; 1507 d->keep_running = TRUE;
1509 /* so next quit won't quit */ 1508 /* so next quit won't quit */
1510 } 1509 }
1511 else if ( msg == "raise()" ) { 1510 else if ( msg == "raise()" ) {
1512 d->keep_running = TRUE; 1511 d->keep_running = TRUE;
1513 d->notbusysent = FALSE; 1512 d->notbusysent = FALSE;
1514 raiseAppropriateWindow(); 1513 raiseAppropriateWindow();
1515 // Tell the system we're still chugging along... 1514 // Tell the system we're still chugging along...
1516 QCopEnvelope e("QPE/System", "appRaised(QString)"); 1515 QCopEnvelope e("QPE/System", "appRaised(QString)");
1517 e << d->appName; 1516 e << d->appName;
1518 } 1517 }
1519 else if ( msg == "flush()" ) { 1518 else if ( msg == "flush()" ) {
1520 emit flush(); 1519 emit flush();
1521 // we need to tell the desktop 1520 // we need to tell the desktop
1522 QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" ); 1521 QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" );
1523 e << d->appName; 1522 e << d->appName;
1524 } 1523 }
1525 else if ( msg == "reload()" ) { 1524 else if ( msg == "reload()" ) {
1526 emit reload(); 1525 emit reload();
1527 } 1526 }
1528 else if ( msg == "setDocument(QString)" ) { 1527 else if ( msg == "setDocument(QString)" ) {
1529 d->keep_running = TRUE; 1528 d->keep_running = TRUE;
1530 QDataStream stream( data, IO_ReadOnly ); 1529 QDataStream stream( data, IO_ReadOnly );
1531 QString doc; 1530 QString doc;
1532 stream >> doc; 1531 stream >> doc;
1533 QWidget *mw = mainWidget(); 1532 QWidget *mw = mainWidget();
1534 if ( !mw ) 1533 if ( !mw )
1535 mw = d->qpe_main_widget; 1534 mw = d->qpe_main_widget;
1536 if ( mw ) 1535 if ( mw )
1537 Global::setDocument( mw, doc ); 1536 Global::setDocument( mw, doc );
1538 1537
1539 } else if ( msg == "QPEProcessQCop()" ) { 1538 } else if ( msg == "QPEProcessQCop()" ) {
1540 processQCopFile(); 1539 processQCopFile();
1541 d->sendQCopQ(); 1540 d->sendQCopQ();
1542 }else 1541 }else
1543 { 1542 {
1544 bool p = d->keep_running; 1543 bool p = d->keep_running;
1545 d->keep_running = FALSE; 1544 d->keep_running = FALSE;
1546 emit appMessage( msg, data); 1545 emit appMessage( msg, data);
1547 if ( d->keep_running ) { 1546 if ( d->keep_running ) {
1548 d->notbusysent = FALSE; 1547 d->notbusysent = FALSE;
1549 raiseAppropriateWindow(); 1548 raiseAppropriateWindow();
1550 if ( !p ) { 1549 if ( !p ) {
1551 // Tell the system we're still chugging along... 1550 // Tell the system we're still chugging along...
1552#ifndef QT_NO_COP 1551#ifndef QT_NO_COP
1553 QCopEnvelope e("QPE/System", "appRaised(QString)"); 1552 QCopEnvelope e("QPE/System", "appRaised(QString)");
1554 e << d->appName; 1553 e << d->appName;
1555#endif 1554#endif
1556 } 1555 }
1557 } 1556 }
1558 if ( p ) 1557 if ( p )
1559 d->keep_running = p; 1558 d->keep_running = p;
1560 } 1559 }
1561#endif 1560#endif
1562} 1561}
1563 1562
1564 1563
1565/*! 1564/*!
1566 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,
1567 consider passing TRUE for \a nomaximize rather than the default FALSE. 1566 consider passing TRUE for \a nomaximize rather than the default FALSE.
1568 1567
1569 \sa showMainDocumentWidget() 1568 \sa showMainDocumentWidget()
1570*/ 1569*/
1571void QPEApplication::showMainWidget( QWidget* mw, bool nomaximize ) 1570void QPEApplication::showMainWidget( QWidget* mw, bool nomaximize )
1572{ 1571{
1573 // setMainWidget(mw); this breaks FastLoading because lastWindowClose() would quit 1572 // setMainWidget(mw); this breaks FastLoading because lastWindowClose() would quit
1574 d->show(mw, nomaximize ); 1573 d->show(mw, nomaximize );
1575} 1574}
1576 1575
1577/*! 1576/*!
1578 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,
1579 consider passing TRUE for \a nomaximize rather than the default FALSE. 1578 consider passing TRUE for \a nomaximize rather than the default FALSE.
1580 1579
1581 This calls designates the application as 1580 This calls designates the application as
1582 a \link docwidget.html document-oriented\endlink application. 1581 a \link docwidget.html document-oriented\endlink application.
1583 1582
1584 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&).
1585 1584
1586 \sa showMainWidget() 1585 \sa showMainWidget()
1587*/ 1586*/
1588void QPEApplication::showMainDocumentWidget( QWidget* mw, bool nomaximize ) 1587void QPEApplication::showMainDocumentWidget( QWidget* mw, bool nomaximize )
1589{ 1588{
1590 if ( mw && argc() == 2 ) 1589 if ( mw && argc() == 2 )
1591 Global::setDocument( mw, QString::fromUtf8(argv()[1]) ); 1590 Global::setDocument( mw, QString::fromUtf8(argv()[1]) );
1592 1591
1593 1592
1594 //setMainWidget(mw); see above 1593 //setMainWidget(mw); see above
1595 d->show(mw, nomaximize ); 1594 d->show(mw, nomaximize );
1596} 1595}
1597 1596
1598 1597
1599/*! 1598/*!
1600 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
1601 message, the application will process the \link qcop.html 1600 message, the application will process the \link qcop.html
1602 QCop\endlink message and then quit. If the application calls this 1601 QCop\endlink message and then quit. If the application calls this
1603 function while processing a \link qcop.html QCop\endlink message, 1602 function while processing a \link qcop.html QCop\endlink message,
1604 after processing its outstanding \link qcop.html QCop\endlink 1603 after processing its outstanding \link qcop.html QCop\endlink
1605 messages the application will start 'properly' and show itself. 1604 messages the application will start 'properly' and show itself.
1606 1605
1607 \sa keepRunning() 1606 \sa keepRunning()
1608*/ 1607*/
1609void QPEApplication::setKeepRunning() 1608void QPEApplication::setKeepRunning()
1610{ 1609{
1611 if ( qApp && qApp->inherits( "QPEApplication" ) ) { 1610 if ( qApp && qApp->inherits( "QPEApplication" ) ) {
1612 QPEApplication * qpeApp = ( QPEApplication* ) qApp; 1611 QPEApplication * qpeApp = ( QPEApplication* ) qApp;
1613 qpeApp->d->keep_running = TRUE; 1612 qpeApp->d->keep_running = TRUE;
1614 } 1613 }
1615} 1614}
1616 1615
1617/*! 1616/*!
1618 Returns TRUE if the application will quit after processing the 1617 Returns TRUE if the application will quit after processing the
1619 current list of qcop messages; otherwise returns FALSE. 1618 current list of qcop messages; otherwise returns FALSE.
1620 1619
1621 \sa setKeepRunning() 1620 \sa setKeepRunning()
1622*/ 1621*/
1623bool QPEApplication::keepRunning() const 1622bool QPEApplication::keepRunning() const
1624{ 1623{
1625 return d->keep_running; 1624 return d->keep_running;
1626} 1625}
1627 1626
1628/*! 1627/*!
1629 \internal 1628 \internal
1630*/ 1629*/
1631void QPEApplication::internalSetStyle( const QString &style ) 1630void QPEApplication::internalSetStyle( const QString &style )
1632{ 1631{
1633#if QT_VERSION >= 300 1632#if QT_VERSION >= 300
1634 if ( style == "QPE" ) { 1633 if ( style == "QPE" ) {
1635 setStyle( new QPEStyle ); 1634 setStyle( new QPEStyle );
1636 } 1635 }
1637 else { 1636 else {
1638 QStyle *s = QStyleFactory::create( style ); 1637 QStyle *s = QStyleFactory::create( style );
1639 if ( s ) 1638 if ( s )
1640 setStyle( s ); 1639 setStyle( s );
1641 } 1640 }
1642#else 1641#else
1643 if ( style == "Windows" ) { 1642 if ( style == "Windows" ) {
1644 setStyle( new QWindowsStyle ); 1643 setStyle( new QWindowsStyle );
1645 } 1644 }
1646 else if ( style == "QPE" ) { 1645 else if ( style == "QPE" ) {
1647 setStyle( new QPEStyle ); 1646 setStyle( new QPEStyle );
1648 } 1647 }
1649 else if ( style == "Light" ) { 1648 else if ( style == "Light" ) {
1650 setStyle( new LightStyle ); 1649 setStyle( new LightStyle );
1651 } 1650 }
1652#ifndef QT_NO_STYLE_PLATINUM 1651#ifndef QT_NO_STYLE_PLATINUM
1653 else if ( style == "Platinum" ) { 1652 else if ( style == "Platinum" ) {
1654 setStyle( new QPlatinumStyle ); 1653 setStyle( new QPlatinumStyle );
1655 } 1654 }
1656#endif 1655#endif
1657#ifndef QT_NO_STYLE_MOTIF 1656#ifndef QT_NO_STYLE_MOTIF
1658 else if ( style == "Motif" ) { 1657 else if ( style == "Motif" ) {
1659 setStyle( new QMotifStyle ); 1658 setStyle( new QMotifStyle );
1660 } 1659 }
1661#endif 1660#endif
1662#ifndef QT_NO_STYLE_MOTIFPLUS 1661#ifndef QT_NO_STYLE_MOTIFPLUS
1663 else if ( style == "MotifPlus" ) { 1662 else if ( style == "MotifPlus" ) {
1664 setStyle( new QMotifPlusStyle ); 1663 setStyle( new QMotifPlusStyle );
1665 } 1664 }
1666#endif 1665#endif
1667 1666
1668 else { 1667 else {
1669 QStyle *sty = 0; 1668 QStyle *sty = 0;
1670 QString path = QPEApplication::qpeDir ( ) + "/plugins/styles/"; 1669 QString path = QPEApplication::qpeDir ( ) + "/plugins/styles/";
1671 1670
1672#ifdef Q_OS_MACX 1671#ifdef Q_OS_MACX
1673 if ( style. find ( ".dylib" ) > 0 ) 1672 if ( style. find ( ".dylib" ) > 0 )
1674 path += style; 1673 path += style;
1675 else 1674 else
1676 path = path + "lib" + style. lower ( ) + ".dylib"; // compatibility 1675 path = path + "lib" + style. lower ( ) + ".dylib"; // compatibility
1677#else 1676#else
1678 if ( style. find ( ".so" ) > 0 ) 1677 if ( style. find ( ".so" ) > 0 )
1679 path += style; 1678 path += style;
1680 else 1679 else
1681 path = path + "lib" + style. lower ( ) + ".so"; // compatibility 1680 path = path + "lib" + style. lower ( ) + ".so"; // compatibility
1682#endif 1681#endif
1683 static QLibrary *lastlib = 0; 1682 static QLibrary *lastlib = 0;
1684 static StyleInterface *lastiface = 0; 1683 static StyleInterface *lastiface = 0;
1685 1684
1686 QLibrary *lib = new QLibrary ( path ); 1685 QLibrary *lib = new QLibrary ( path );
1687 StyleInterface *iface = 0; 1686 StyleInterface *iface = 0;
1688 1687
1689 if (( lib-> queryInterface ( IID_Style, ( QUnknownInterface ** ) &iface ) == QS_OK ) && iface ) 1688 if (( lib-> queryInterface ( IID_Style, ( QUnknownInterface ** ) &iface ) == QS_OK ) && iface )
1690 sty = iface-> style ( ); 1689 sty = iface-> style ( );
1691 1690
1692 if ( sty ) { 1691 if ( sty ) {
1693 setStyle ( sty ); 1692 setStyle ( sty );
1694 1693
1695 if ( lastiface ) 1694 if ( lastiface )
1696 lastiface-> release ( ); 1695 lastiface-> release ( );
1697 lastiface = iface; 1696 lastiface = iface;
1698 1697
1699 if ( lastlib ) { 1698 if ( lastlib ) {
1700 lastlib-> unload ( ); 1699 lastlib-> unload ( );
1701 delete lastlib; 1700 delete lastlib;
1702 } 1701 }
1703 lastlib = lib; 1702 lastlib = lib;
1704 } 1703 }
1705 else { 1704 else {
1706 if ( iface ) 1705 if ( iface )
1707 iface-> release ( ); 1706 iface-> release ( );
1708 delete lib; 1707 delete lib;
1709 1708
1710 setStyle ( new LightStyle ( )); 1709 setStyle ( new LightStyle ( ));
1711 } 1710 }
1712 } 1711 }
1713#endif 1712#endif
1714} 1713}
1715 1714
1716/*! 1715/*!
1717 \internal 1716 \internal
1718*/ 1717*/
1719void QPEApplication::prepareForTermination( bool willrestart ) 1718void QPEApplication::prepareForTermination( bool willrestart )
1720{ 1719{
1721 if ( willrestart ) { 1720 if ( willrestart ) {
1722 // 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
1723 // QWidget *d = QApplication::desktop(); 1722 // QWidget *d = QApplication::desktop();
1724 QImage img = Resource::loadImage( "launcher/new_wait" ); 1723 QImage img = Resource::loadImage( "launcher/new_wait" );
1725 QPixmap pix; 1724 QPixmap pix;
1726 pix.convertFromImage( img.smoothScale( 1 * img.width(), 1 * img.height() ) ); 1725 pix.convertFromImage( img.smoothScale( 1 * img.width(), 1 * img.height() ) );
1727 QLabel *lblWait = new QLabel( 0, "wait hack!", QWidget::WStyle_Customize | 1726 QLabel *lblWait = new QLabel( 0, "wait hack!", QWidget::WStyle_Customize |
1728 QWidget::WStyle_NoBorder | QWidget::WStyle_Tool ); 1727 QWidget::WStyle_NoBorder | QWidget::WStyle_Tool );
1729 lblWait->setPixmap( pix ); 1728 lblWait->setPixmap( pix );
1730 lblWait->setAlignment( QWidget::AlignCenter ); 1729 lblWait->setAlignment( QWidget::AlignCenter );
1731 lblWait->show(); 1730 lblWait->show();
1732 lblWait->showMaximized(); 1731 lblWait->showMaximized();
1733 } 1732 }
1734#ifndef SINGLE_APP 1733#ifndef SINGLE_APP
1735 { QCopEnvelope envelope( "QPE/System", "forceQuit()" ); 1734 { QCopEnvelope envelope( "QPE/System", "forceQuit()" );
1736 } 1735 }
1737 processEvents(); // ensure the message goes out. 1736 processEvents(); // ensure the message goes out.
1738 sleep( 1 ); // You have 1 second to comply. 1737 sleep( 1 ); // You have 1 second to comply.
1739#endif 1738#endif
1740} 1739}
1741 1740
1742/*! 1741/*!
1743 \internal 1742 \internal
1744*/ 1743*/
1745void QPEApplication::shutdown() 1744void QPEApplication::shutdown()
1746{ 1745{
1747 // Implement in server's QPEApplication subclass 1746 // Implement in server's QPEApplication subclass
1748} 1747}
1749 1748
1750/*! 1749/*!
1751 \internal 1750 \internal
1752*/ 1751*/
1753void QPEApplication::restart() 1752void QPEApplication::restart()
1754{ 1753{
1755 // Implement in server's QPEApplication subclass 1754 // Implement in server's QPEApplication subclass
1756} 1755}
1757 1756
1758static QPtrDict<void>* stylusDict = 0; 1757static QPtrDict<void>* stylusDict = 0;
1759static void createDict() 1758static void createDict()
1760{ 1759{
1761 if ( !stylusDict ) 1760 if ( !stylusDict )
1762 stylusDict = new QPtrDict<void>; 1761 stylusDict = new QPtrDict<void>;
1763} 1762}
1764 1763
1765/*! 1764/*!
1766 Returns the current StylusMode for widget \a w. 1765 Returns the current StylusMode for widget \a w.
1767 1766
1768 \sa setStylusOperation() StylusMode 1767 \sa setStylusOperation() StylusMode
1769*/ 1768*/
1770QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w ) 1769QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w )
1771{ 1770{
1772 if ( stylusDict ) 1771 if ( stylusDict )
1773 return ( StylusMode ) ( int ) stylusDict->find( w ); 1772 return ( StylusMode ) ( int ) stylusDict->find( w );
1774 return LeftOnly; 1773 return LeftOnly;
1775} 1774}
1776 1775
1777/*! 1776/*!
1778 \enum QPEApplication::StylusMode 1777 \enum QPEApplication::StylusMode
1779 1778
1780 \value LeftOnly the stylus only generates LeftButton 1779 \value LeftOnly the stylus only generates LeftButton
1781 events (the default). 1780 events (the default).
1782 \value RightOnHold the stylus generates RightButton events 1781 \value RightOnHold the stylus generates RightButton events
1783 if the user uses the press-and-hold gesture. 1782 if the user uses the press-and-hold gesture.
1784 1783
1785 \sa setStylusOperation() stylusOperation() 1784 \sa setStylusOperation() stylusOperation()
1786*/ 1785*/
1787 1786
1788/*! 1787/*!
1789 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
1790 \a mode. 1789 \a mode.
1791 1790
1792 \sa stylusOperation() StylusMode 1791 \sa stylusOperation() StylusMode
1793*/ 1792*/
1794void QPEApplication::setStylusOperation( QWidget * w, StylusMode mode ) 1793void QPEApplication::setStylusOperation( QWidget * w, StylusMode mode )
1795{ 1794{
1796 createDict(); 1795 createDict();
1797 if ( mode == LeftOnly ) { 1796 if ( mode == LeftOnly ) {
1798 stylusDict->remove 1797 stylusDict->remove
1799 ( w ); 1798 ( w );
1800 w->removeEventFilter( qApp ); 1799 w->removeEventFilter( qApp );
1801 } 1800 }
1802 else { 1801 else {
1803 stylusDict->insert( w, ( void* ) mode ); 1802 stylusDict->insert( w, ( void* ) mode );
1804 connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) ); 1803 connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) );
1805 w->installEventFilter( qApp ); 1804 w->installEventFilter( qApp );
1806 } 1805 }
1807} 1806}
1808 1807
1809 1808
1810/*! 1809/*!
1811 \reimp 1810 \reimp
1812*/ 1811*/
1813bool QPEApplication::eventFilter( QObject *o, QEvent *e ) 1812bool QPEApplication::eventFilter( QObject *o, QEvent *e )
1814{ 1813{
1815 if ( !o->isWidgetType() ) 1814 if ( !o->isWidgetType() )
1816 return FALSE; 1815 return FALSE;
1817 1816
1818 if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) { 1817 if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) {
1819 QMouseEvent * me = ( QMouseEvent* ) e; 1818 QMouseEvent * me = ( QMouseEvent* ) e;
1820 StylusMode mode = (StylusMode)(int)stylusDict->find(o); 1819 StylusMode mode = (StylusMode)(int)stylusDict->find(o);
1821 switch (mode) { 1820 switch (mode) {
1822 case RightOnHold: 1821 case RightOnHold:
1823 switch ( me->type() ) { 1822 switch ( me->type() ) {
1824 case QEvent::MouseButtonPress: 1823 case QEvent::MouseButtonPress:
1825 if ( me->button() == LeftButton ) { 1824 if ( me->button() == LeftButton ) {
1826 if (!d->presstimer ) 1825 if (!d->presstimer )
1827 d->presstimer = startTimer(500); // #### pref. 1826 d->presstimer = startTimer(500); // #### pref.
1828 d->presswidget = (QWidget*)o; 1827 d->presswidget = (QWidget*)o;
1829 d->presspos = me->pos(); 1828 d->presspos = me->pos();
1830 d->rightpressed = FALSE; 1829 d->rightpressed = FALSE;
1831 } 1830 }
1832 break; 1831 break;
1833 case QEvent::MouseMove: 1832 case QEvent::MouseMove:
1834 if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) { 1833 if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) {
1835 killTimer(d->presstimer); 1834 killTimer(d->presstimer);
1836 d->presstimer = 0; 1835 d->presstimer = 0;
1837 } 1836 }
1838 break; 1837 break;
1839 case QEvent::MouseButtonRelease: 1838 case QEvent::MouseButtonRelease:
1840 if ( me->button() == LeftButton ) { 1839 if ( me->button() == LeftButton ) {
1841 if ( d->presstimer ) { 1840 if ( d->presstimer ) {
1842 killTimer(d->presstimer); 1841 killTimer(d->presstimer);
1843 d->presstimer = 0; 1842 d->presstimer = 0;
1844 } 1843 }
1845 if ( d->rightpressed && d->presswidget ) { 1844 if ( d->rightpressed && d->presswidget ) {
1846 // Right released 1845 // Right released
1847 postEvent( d->presswidget, 1846 postEvent( d->presswidget,
1848 new QMouseEvent( QEvent::MouseButtonRelease, me->pos(), 1847 new QMouseEvent( QEvent::MouseButtonRelease, me->pos(),
1849 RightButton, LeftButton + RightButton ) ); 1848 RightButton, LeftButton + RightButton ) );
1850 // Left released, off-widget 1849 // Left released, off-widget
1851 postEvent( d->presswidget, 1850 postEvent( d->presswidget,
1852 new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1), 1851 new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1),
1853 LeftButton, LeftButton ) ); 1852 LeftButton, LeftButton ) );
1854 postEvent( d->presswidget, 1853 postEvent( d->presswidget,
1855 new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1), 1854 new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1),
1856 LeftButton, LeftButton ) ); 1855 LeftButton, LeftButton ) );
1857 d->rightpressed = FALSE; 1856 d->rightpressed = FALSE;
1858 return TRUE; // don't send the real Left release 1857 return TRUE; // don't send the real Left release
1859 } 1858 }
1860 } 1859 }
1861 break; 1860 break;
1862 default: 1861 default:
1863 break; 1862 break;
1864 } 1863 }
1865 break; 1864 break;
1866 default: 1865 default:
1867 ; 1866 ;
1868 } 1867 }
1869 } 1868 }
1870 else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { 1869 else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) {
1871 QKeyEvent *ke = (QKeyEvent *)e; 1870 QKeyEvent *ke = (QKeyEvent *)e;
1872 if ( ke->key() == Key_Enter ) { 1871 if ( ke->key() == Key_Enter ) {
1873 if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) { 1872 if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) {
1874 postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ', 1873 postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ',
1875 ke->state(), " ", ke->isAutoRepeat(), ke->count() ) ); 1874 ke->state(), " ", ke->isAutoRepeat(), ke->count() ) );
1876 return TRUE; 1875 return TRUE;
1877 } 1876 }
1878 } 1877 }
1879 } 1878 }
1880 return FALSE; 1879 return FALSE;
1881} 1880}
1882 1881
1883/*! 1882/*!
1884 \reimp 1883 \reimp
1885*/ 1884*/
1886void QPEApplication::timerEvent( QTimerEvent *e ) 1885void QPEApplication::timerEvent( QTimerEvent *e )
1887{ 1886{
1888 if ( e->timerId() == d->presstimer && d->presswidget ) { 1887 if ( e->timerId() == d->presstimer && d->presswidget ) {
1889 // Right pressed 1888 // Right pressed
1890 postEvent( d->presswidget, 1889 postEvent( d->presswidget,
1891 new QMouseEvent( QEvent::MouseButtonPress, d->presspos, 1890 new QMouseEvent( QEvent::MouseButtonPress, d->presspos,
1892 RightButton, LeftButton ) ); 1891 RightButton, LeftButton ) );
1893 killTimer( d->presstimer ); 1892 killTimer( d->presstimer );
1894 d->presstimer = 0; 1893 d->presstimer = 0;
1895 d->rightpressed = TRUE; 1894 d->rightpressed = TRUE;
1896 } 1895 }
1897} 1896}
1898 1897
1899void QPEApplication::removeSenderFromStylusDict() 1898void QPEApplication::removeSenderFromStylusDict()
1900{ 1899{
1901 stylusDict->remove 1900 stylusDict->remove
1902 ( ( void* ) sender() ); 1901 ( ( void* ) sender() );
1903 if ( d->presswidget == sender() ) 1902 if ( d->presswidget == sender() )
1904 d->presswidget = 0; 1903 d->presswidget = 0;
1905} 1904}
1906 1905
1907/*! 1906/*!
1908 \internal 1907 \internal
1909*/ 1908*/
1910bool QPEApplication::keyboardGrabbed() const 1909bool QPEApplication::keyboardGrabbed() const
1911{ 1910{
1912 return d->kbgrabbed; 1911 return d->kbgrabbed;
1913} 1912}
1914 1913
1915 1914
1916/*! 1915/*!
1917 Reverses the effect of grabKeyboard(). This is called automatically 1916 Reverses the effect of grabKeyboard(). This is called automatically
1918 on program exit. 1917 on program exit.
1919*/ 1918*/
1920void QPEApplication::ungrabKeyboard() 1919void QPEApplication::ungrabKeyboard()
1921{ 1920{
1922 ((QPEApplication *) qApp )-> d-> kbgrabbed = false; 1921 ((QPEApplication *) qApp )-> d-> kbgrabbed = false;
1923} 1922}
1924 1923
1925/*! 1924/*!
1926 Grabs the physical keyboard keys, e.g. the application's launching 1925 Grabs the physical keyboard keys, e.g. the application's launching
1927 keys. Instead of launching applications when these keys are pressed 1926 keys. Instead of launching applications when these keys are pressed
1928 the signals emitted are sent to this application instead. Some games 1927 the signals emitted are sent to this application instead. Some games
1929 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
1930 easier. 1929 easier.
1931 1930
1932 \sa ungrabKeyboard() 1931 \sa ungrabKeyboard()
1933*/ 1932*/
1934void QPEApplication::grabKeyboard() 1933void QPEApplication::grabKeyboard()
1935{ 1934{
1936 ((QPEApplication *) qApp )-> d-> kbgrabbed = true; 1935 ((QPEApplication *) qApp )-> d-> kbgrabbed = true;
1937} 1936}
1938 1937
1939/*! 1938/*!
1940 \reimp 1939 \reimp
1941*/ 1940*/
1942int QPEApplication::exec() 1941int QPEApplication::exec()
1943{ 1942{
1944 d->qcopQok = true; 1943 d->qcopQok = true;
1945#ifndef QT_NO_COP 1944#ifndef QT_NO_COP
1946 d->sendQCopQ(); 1945 d->sendQCopQ();
1947 if ( !d->keep_running ) 1946 if ( !d->keep_running )
1948 processEvents(); // we may have received QCop messages in the meantime. 1947 processEvents(); // we may have received QCop messages in the meantime.
1949#endif 1948#endif
1950 1949
1951 if ( d->keep_running ) 1950 if ( d->keep_running )
1952 //|| d->qpe_main_widget && d->qpe_main_widget->isVisible() ) 1951 //|| d->qpe_main_widget && d->qpe_main_widget->isVisible() )
1953 return QApplication::exec(); 1952 return QApplication::exec();
1954 1953
1955#ifndef QT_NO_COP 1954#ifndef QT_NO_COP
1956 1955
1957 { 1956 {
1958 QCopEnvelope e( "QPE/System", "closing(QString)" ); 1957 QCopEnvelope e( "QPE/System", "closing(QString)" );
1959 e << d->appName; 1958 e << d->appName;
1960 } 1959 }
1961#endif 1960#endif
1962 processEvents(); 1961 processEvents();
1963 return 0; 1962 return 0;
1964} 1963}
1965 1964
1966/*! 1965/*!
1967 \internal 1966 \internal
1968 External request for application to quit. Quits if possible without 1967 External request for application to quit. Quits if possible without
1969 loosing state. 1968 loosing state.
1970*/ 1969*/
1971void QPEApplication::tryQuit() 1970void QPEApplication::tryQuit()
1972{ 1971{
1973 if ( activeModalWidget() || strcmp( argv() [ 0 ], "embeddedkonsole" ) == 0 ) 1972 if ( activeModalWidget() || strcmp( argv() [ 0 ], "embeddedkonsole" ) == 0 )
1974 return ; // Inside modal loop or konsole. Too hard to save state. 1973 return ; // Inside modal loop or konsole. Too hard to save state.
1975#ifndef QT_NO_COP 1974#ifndef QT_NO_COP
1976 1975
1977 { 1976 {
1978 QCopEnvelope e( "QPE/System", "closing(QString)" ); 1977 QCopEnvelope e( "QPE/System", "closing(QString)" );
1979 e << d->appName; 1978 e << d->appName;
1980 } 1979 }
1981#endif 1980#endif
1982 processEvents(); 1981 processEvents();
1983 1982
1984 quit(); 1983 quit();
1985} 1984}
1986 1985
1987/*! 1986/*!
1988 \internal 1987 \internal
1989*/ 1988*/
1990void QPEApplication::installTranslation( const QString& baseName ) { 1989void QPEApplication::installTranslation( const QString& baseName ) {
1991 QTranslator* trans = new QTranslator(this); 1990 QTranslator* trans = new QTranslator(this);
1992 QString tfn = qpeDir() + "/i18n/"+baseName; 1991 QString tfn = qpeDir() + "/i18n/"+baseName;
1993 if ( trans->load( tfn ) ) 1992 if ( trans->load( tfn ) )
1994 installTranslator( trans ); 1993 installTranslator( trans );
1995 else 1994 else
1996 delete trans; 1995 delete trans;
1997} 1996}
1998 1997
1999/*! 1998/*!
2000 \internal 1999 \internal
2001 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
2002 hiding the window. If not it means quitting the application. 2001 hiding the window. If not it means quitting the application.
2003 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.
2004*/ 2003*/
2005void QPEApplication::hideOrQuit() 2004void QPEApplication::hideOrQuit()
2006{ 2005{
2007 processEvents(); 2006 processEvents();
2008 2007
2009 // 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
2010 // a System message indicating we're quasi-closing. 2009 // a System message indicating we're quasi-closing.
2011 if ( d->preloaded && d->qpe_main_widget ) 2010 if ( d->preloaded && d->qpe_main_widget )
2012#ifndef QT_NO_COP 2011#ifndef QT_NO_COP
2013 2012
2014 { 2013 {
2015 QCopEnvelope e("QPE/System", "fastAppHiding(QString)" ); 2014 QCopEnvelope e("QPE/System", "fastAppHiding(QString)" );
2016 e << d->appName; 2015 e << d->appName;
2017 d->qpe_main_widget->hide(); 2016 d->qpe_main_widget->hide();
2018 } 2017 }
2019#endif 2018#endif
2020 else 2019 else
2021 quit(); 2020 quit();
2022} 2021}
2023 2022
2024#if (__GNUC__ > 2 ) 2023#if (__GNUC__ > 2 )
2025extern "C" void __cxa_pure_virtual(); 2024extern "C" void __cxa_pure_virtual();
2026 2025
2027void __cxa_pure_virtual() 2026void __cxa_pure_virtual()
2028{ 2027{
2029 fprintf( stderr, "Pure virtual called\n"); 2028 fprintf( stderr, "Pure virtual called\n");
2030 abort(); 2029 abort();
2031 2030
2032} 2031}
2033 2032
2034#endif 2033#endif
2035 2034
2036 2035
2037#if defined(OPIE_NEW_MALLOC) 2036#if defined(OPIE_NEW_MALLOC)
2038 2037
2039// The libraries with the skiff package (and possibly others) have 2038// The libraries with the skiff package (and possibly others) have
2040// completely useless implementations of builtin new and delete that 2039// completely useless implementations of builtin new and delete that
2041// 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
2042// functions. 2041// functions.
2043 2042
2044void* operator new[]( size_t size ) 2043void* operator new[]( size_t size )
2045{ 2044{
2046 return malloc( size ); 2045 return malloc( size );
2047} 2046}
2048 2047
2049void* operator new( size_t size ) 2048void* operator new( size_t size )
2050{ 2049{
2051 return malloc( size ); 2050 return malloc( size );
2052} 2051}
2053 2052
2054void operator delete[]( void* p ) 2053void operator delete[]( void* p )
2055{ 2054{
2056 free( p ); 2055 free( p );
2057} 2056}
2058 2057
2059void operator delete[]( void* p, size_t /*size*/ ) 2058void operator delete[]( void* p, size_t /*size*/ )
2060{ 2059{
2061 free( p ); 2060 free( p );
2062} 2061}
2063 2062
2064 2063
2065void operator delete( void* p ) 2064void operator delete( void* p )
2066{ 2065{
2067 free( p ); 2066 free( p );
2068} 2067}
2069 2068
2070void operator delete( void* p, size_t /*size*/ ) 2069void operator delete( void* p, size_t /*size*/ )
2071{ 2070{
2072 free( p ); 2071 free( p );
2073} 2072}
2074 2073
2075#endif 2074#endif
2076 2075
2077#if ( QT_VERSION <= 230 ) && !defined(SINGLE_APP) 2076#if ( QT_VERSION <= 230 ) && !defined(SINGLE_APP)
2078#include <qwidgetlist.h> 2077#include <qwidgetlist.h>
2079#ifdef QWS 2078#ifdef QWS
2080#include <qgfx_qws.h> 2079#include <qgfx_qws.h>
2081extern QRect qt_maxWindowRect; 2080extern QRect qt_maxWindowRect;
2082void qt_setMaxWindowRect(const QRect& r ) 2081void qt_setMaxWindowRect(const QRect& r )
2083{ 2082{
2084 qt_maxWindowRect = qt_screen->mapFromDevice( r, 2083 qt_maxWindowRect = qt_screen->mapFromDevice( r,
2085 qt_screen->mapToDevice( QSize( qt_screen->width(), qt_screen->height() ) ) ); 2084 qt_screen->mapToDevice( QSize( qt_screen->width(), qt_screen->height() ) ) );
2086 // Re-resize any maximized windows 2085 // Re-resize any maximized windows
2087 QWidgetList* l = QApplication::topLevelWidgets(); 2086 QWidgetList* l = QApplication::topLevelWidgets();
2088 if ( l ) { 2087 if ( l ) {
2089 QWidget * w = l->first(); 2088 QWidget * w = l->first();
2090 while ( w ) { 2089 while ( w ) {
2091 if ( w->isVisible() && w->isMaximized() ) { 2090 if ( w->isVisible() && w->isMaximized() ) {
2092 w->showMaximized(); 2091 w->showMaximized();
2093 } 2092 }
2094 w = l->next(); 2093 w = l->next();
2095 } 2094 }
2096 delete l; 2095 delete l;
2097 } 2096 }
2098} 2097}
2099#endif 2098#endif
2100#endif 2099#endif
diff --git a/library/qpemenubar.cpp b/library/qpemenubar.cpp
index 3e5bad5..1d8eff4 100644
--- a/library/qpemenubar.cpp
+++ b/library/qpemenubar.cpp
@@ -1,330 +1,329 @@
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 INCLUDE_MENUITEM_DEF 21#define INCLUDE_MENUITEM_DEF
22 22
23#include "qpemenubar.h" 23#include "qpemenubar.h"
24#include <qapplication.h> 24#include <qapplication.h>
25#include <qguardedptr.h>
26#include <qtimer.h> 25#include <qtimer.h>
27 26
28 27
29class QMenuBarHack : public QMenuBar 28class QMenuBarHack : public QMenuBar
30{ 29{
31public: 30public:
32 int activeItem() const { return actItem; } 31 int activeItem() const { return actItem; }
33 32
34 void goodbye() 33 void goodbye()
35 { 34 {
36 activateItemAt(-1); 35 activateItemAt(-1);
37 for ( unsigned int i = 0; i < count(); i++ ) { 36 for ( unsigned int i = 0; i < count(); i++ ) {
38 QMenuItem *mi = findItem( idAt(i) ); 37 QMenuItem *mi = findItem( idAt(i) );
39 if ( mi->popup() ) { 38 if ( mi->popup() ) {
40 mi->popup()->hide(); 39 mi->popup()->hide();
41 } 40 }
42 } 41 }
43 } 42 }
44}; 43};
45 44
46 45
47// Sharp ROM compatibility 46// Sharp ROM compatibility
48void QPEMenuToolFocusManager::setMenukeyEnabled ( bool ) 47void QPEMenuToolFocusManager::setMenukeyEnabled ( bool )
49{ 48{
50} 49}
51int QPEMenuBar::getOldFocus ( ) 50int QPEMenuBar::getOldFocus ( )
52{ 51{
53 return 0; 52 return 0;
54} 53}
55 54
56QPEMenuToolFocusManager *QPEMenuToolFocusManager::me = 0; 55QPEMenuToolFocusManager *QPEMenuToolFocusManager::me = 0;
57 56
58QPEMenuToolFocusManager::QPEMenuToolFocusManager() : QObject() 57QPEMenuToolFocusManager::QPEMenuToolFocusManager() : QObject()
59{ 58{
60 qApp->installEventFilter( this ); 59 qApp->installEventFilter( this );
61} 60}
62 61
63void QPEMenuToolFocusManager::addWidget( QWidget *w ) 62void QPEMenuToolFocusManager::addWidget( QWidget *w )
64{ 63{
65 list.append( GuardedWidget(w) ); 64 list.append( GuardedWidget(w) );
66} 65}
67 66
68void QPEMenuToolFocusManager::removeWidget( QWidget *w ) 67void QPEMenuToolFocusManager::removeWidget( QWidget *w )
69{ 68{
70 list.remove( GuardedWidget(w) ); 69 list.remove( GuardedWidget(w) );
71} 70}
72 71
73void QPEMenuToolFocusManager::setActive( bool a ) 72void QPEMenuToolFocusManager::setActive( bool a )
74{ 73{
75 if ( a ) { 74 if ( a ) {
76 oldFocus = qApp->focusWidget(); 75 oldFocus = qApp->focusWidget();
77 QValueList<GuardedWidget>::Iterator it; 76 QValueList<GuardedWidget>::Iterator it;
78 it = list.begin(); 77 it = list.begin();
79 while ( it != list.end() ) { 78 while ( it != list.end() ) {
80 QWidget *w = (*it); 79 QWidget *w = (*it);
81 if ( w && w->isEnabled() && w->isVisible() && 80 if ( w && w->isEnabled() && w->isVisible() &&
82 w->topLevelWidget() == qApp->activeWindow() ) { 81 w->topLevelWidget() == qApp->activeWindow() ) {
83 setFocus( w ); 82 setFocus( w );
84 return; 83 return;
85 } 84 }
86 ++it; 85 ++it;
87 } 86 }
88 } else { 87 } else {
89 if ( inFocus ) { 88 if ( inFocus ) {
90 if ( inFocus->inherits( "QMenuBar" ) ) 89 if ( inFocus->inherits( "QMenuBar" ) )
91 ((QMenuBarHack *)(QWidget *)inFocus)->goodbye(); 90 ((QMenuBarHack *)(QWidget *)inFocus)->goodbye();
92 if ( inFocus->hasFocus() ) { 91 if ( inFocus->hasFocus() ) {
93 if ( oldFocus && oldFocus->isVisible() && oldFocus->isEnabled() ) { 92 if ( oldFocus && oldFocus->isVisible() && oldFocus->isEnabled() ) {
94 oldFocus->setFocus(); 93 oldFocus->setFocus();
95 } else { 94 } else {
96 inFocus->clearFocus(); 95 inFocus->clearFocus();
97 } 96 }
98 } 97 }
99 } 98 }
100 inFocus = 0; 99 inFocus = 0;
101 oldFocus = 0; 100 oldFocus = 0;
102 } 101 }
103} 102}
104 103
105bool QPEMenuToolFocusManager::isActive() const 104bool QPEMenuToolFocusManager::isActive() const
106{ 105{
107 return !inFocus.isNull(); 106 return !inFocus.isNull();
108} 107}
109 108
110void QPEMenuToolFocusManager::moveFocus( bool next ) 109void QPEMenuToolFocusManager::moveFocus( bool next )
111{ 110{
112 if ( !isActive() ) 111 if ( !isActive() )
113 return; 112 return;
114 113
115 int n = list.count(); 114 int n = list.count();
116 QValueList<GuardedWidget>::Iterator it; 115 QValueList<GuardedWidget>::Iterator it;
117 it = list.find( inFocus ); 116 it = list.find( inFocus );
118 if ( it == list.end() ) 117 if ( it == list.end() )
119 it = list.begin(); 118 it = list.begin();
120 while ( --n ) { 119 while ( --n ) {
121 if ( next ) { 120 if ( next ) {
122 ++it; 121 ++it;
123 if ( it == list.end() ) 122 if ( it == list.end() )
124 it = list.begin(); 123 it = list.begin();
125 } else { 124 } else {
126 if ( it == list.begin() ) 125 if ( it == list.begin() )
127 it = list.end(); 126 it = list.end();
128 --it; 127 --it;
129 } 128 }
130 QWidget *w = (*it); 129 QWidget *w = (*it);
131 if ( w && w->isEnabled() && w->isVisible() && !w->inherits("QToolBarSeparator") && 130 if ( w && w->isEnabled() && w->isVisible() && !w->inherits("QToolBarSeparator") &&
132 w->topLevelWidget() == qApp->activeWindow() ) { 131 w->topLevelWidget() == qApp->activeWindow() ) {
133 setFocus( w, next ); 132 setFocus( w, next );
134 return; 133 return;
135 } 134 }
136 } 135 }
137} 136}
138 137
139void QPEMenuToolFocusManager::initialize() 138void QPEMenuToolFocusManager::initialize()
140{ 139{
141 if ( !me ) 140 if ( !me )
142 me = new QPEMenuToolFocusManager; 141 me = new QPEMenuToolFocusManager;
143} 142}
144 143
145QPEMenuToolFocusManager *QPEMenuToolFocusManager::manager() 144QPEMenuToolFocusManager *QPEMenuToolFocusManager::manager()
146{ 145{
147 if ( !me ) 146 if ( !me )
148 me = new QPEMenuToolFocusManager; 147 me = new QPEMenuToolFocusManager;
149 148
150 return me; 149 return me;
151} 150}
152 151
153void QPEMenuToolFocusManager::setFocus( QWidget *w, bool next ) 152void QPEMenuToolFocusManager::setFocus( QWidget *w, bool next )
154{ 153{
155 inFocus = w; 154 inFocus = w;
156// qDebug( "Set focus on %s", w->className() ); 155// qDebug( "Set focus on %s", w->className() );
157 if ( inFocus->inherits( "QMenuBar" ) ) { 156 if ( inFocus->inherits( "QMenuBar" ) ) {
158 QMenuBar *mb = (QMenuBar *)(QWidget *)inFocus; 157 QMenuBar *mb = (QMenuBar *)(QWidget *)inFocus;
159 if ( next ) 158 if ( next )
160 mb->activateItemAt( 0 ); 159 mb->activateItemAt( 0 );
161 else 160 else
162 mb->activateItemAt( mb->count()-1 ); 161 mb->activateItemAt( mb->count()-1 );
163 } 162 }
164 inFocus->setFocus(); 163 inFocus->setFocus();
165} 164}
166 165
167bool QPEMenuToolFocusManager::eventFilter( QObject *object, QEvent *event ) 166bool QPEMenuToolFocusManager::eventFilter( QObject *object, QEvent *event )
168{ 167{
169 if ( event->type() == QEvent::KeyPress ) { 168 if ( event->type() == QEvent::KeyPress ) {
170 QKeyEvent *ke = (QKeyEvent *)event; 169 QKeyEvent *ke = (QKeyEvent *)event;
171 if ( isActive() ) { 170 if ( isActive() ) {
172 if ( object->inherits( "QButton" ) ) { 171 if ( object->inherits( "QButton" ) ) {
173 switch ( ke->key() ) { 172 switch ( ke->key() ) {
174 case Key_Left: 173 case Key_Left:
175 moveFocus( FALSE ); 174 moveFocus( FALSE );
176 return TRUE; 175 return TRUE;
177 176
178 case Key_Right: 177 case Key_Right:
179 moveFocus( TRUE ); 178 moveFocus( TRUE );
180 return TRUE; 179 return TRUE;
181 180
182 case Key_Up: 181 case Key_Up:
183 case Key_Down: 182 case Key_Down:
184 return TRUE; 183 return TRUE;
185 } 184 }
186 } else if ( object->inherits( "QPopupMenu" ) ) { 185 } else if ( object->inherits( "QPopupMenu" ) ) {
187 // Deactivate when a menu item is selected 186 // Deactivate when a menu item is selected
188 if ( ke->key() == Key_Enter || ke->key() == Key_Return || 187 if ( ke->key() == Key_Enter || ke->key() == Key_Return ||
189 ke->key() == Key_Escape ) { 188 ke->key() == Key_Escape ) {
190 QTimer::singleShot( 0, this, SLOT(deactivate()) ); 189 QTimer::singleShot( 0, this, SLOT(deactivate()) );
191 } 190 }
192 } else if ( object->inherits( "QMenuBar" ) ) { 191 } else if ( object->inherits( "QMenuBar" ) ) {
193 int dx = 0; 192 int dx = 0;
194 switch ( ke->key() ) { 193 switch ( ke->key() ) {
195 case Key_Left: 194 case Key_Left:
196 dx = -1; 195 dx = -1;
197 break; 196 break;
198 197
199 case Key_Right: 198 case Key_Right:
200 dx = 1; 199 dx = 1;
201 break; 200 break;
202 } 201 }
203 202
204 QMenuBarHack *mb = (QMenuBarHack *)object; 203 QMenuBarHack *mb = (QMenuBarHack *)object;
205 if ( dx && mb->activeItem() >= 0 ) { 204 if ( dx && mb->activeItem() >= 0 ) {
206 int i = mb->activeItem(); 205 int i = mb->activeItem();
207 int c = mb->count(); 206 int c = mb->count();
208 int n = c; 207 int n = c;
209 while ( n-- ) { 208 while ( n-- ) {
210 i = i + dx; 209 i = i + dx;
211 if ( i == c ) { 210 if ( i == c ) {
212 mb->goodbye(); 211 mb->goodbye();
213 moveFocus( TRUE ); 212 moveFocus( TRUE );
214 return TRUE; 213 return TRUE;
215 } else if ( i < 0 ) { 214 } else if ( i < 0 ) {
216 mb->goodbye(); 215 mb->goodbye();
217 moveFocus( FALSE ); 216 moveFocus( FALSE );
218 return TRUE; 217 return TRUE;
219 } 218 }
220 QMenuItem *mi = mb->findItem( mb->idAt(i) ); 219 QMenuItem *mi = mb->findItem( mb->idAt(i) );
221 if ( mi->isEnabled() && !mi->isSeparator() ) { 220 if ( mi->isEnabled() && !mi->isSeparator() ) {
222 break; 221 break;
223 } 222 }
224 } 223 }
225 } 224 }
226 } 225 }
227 } 226 }
228 } else if ( event->type() == QEvent::KeyRelease ) { 227 } else if ( event->type() == QEvent::KeyRelease ) {
229 QKeyEvent *ke = (QKeyEvent *)event; 228 QKeyEvent *ke = (QKeyEvent *)event;
230 if ( isActive() ) { 229 if ( isActive() ) {
231 if ( object->inherits( "QButton" ) ) { 230 if ( object->inherits( "QButton" ) ) {
232 // Deactivate when a button is selected 231 // Deactivate when a button is selected
233 if ( ke->key() == Key_Space ) 232 if ( ke->key() == Key_Space )
234 QTimer::singleShot( 0, this, SLOT(deactivate()) ); 233 QTimer::singleShot( 0, this, SLOT(deactivate()) );
235 } 234 }
236 } 235 }
237 } else if ( event->type() == QEvent::FocusIn ) { 236 } else if ( event->type() == QEvent::FocusIn ) {
238 if ( isActive() ) { 237 if ( isActive() ) {
239 // A non-menu/tool widget has been selected - we're deactivated 238 // A non-menu/tool widget has been selected - we're deactivated
240 QWidget *w = (QWidget *)object; 239 QWidget *w = (QWidget *)object;
241 if ( !w->isPopup() && !list.contains( GuardedWidget( w ) ) ) { 240 if ( !w->isPopup() && !list.contains( GuardedWidget( w ) ) ) {
242 inFocus = 0; 241 inFocus = 0;
243 } 242 }
244 } 243 }
245 } else if ( event->type() == QEvent::Hide ) { 244 } else if ( event->type() == QEvent::Hide ) {
246 if ( isActive() ) { 245 if ( isActive() ) {
247 // Deaticvate if a menu/tool has been hidden 246 // Deaticvate if a menu/tool has been hidden
248 QWidget *w = (QWidget *)object; 247 QWidget *w = (QWidget *)object;
249 if ( !w->isPopup() && !list.contains( GuardedWidget( w ) ) ) { 248 if ( !w->isPopup() && !list.contains( GuardedWidget( w ) ) ) {
250 setActive( FALSE ); 249 setActive( FALSE );
251 } 250 }
252 } 251 }
253 } else if ( event->type() == QEvent::ChildInserted ) { 252 } else if ( event->type() == QEvent::ChildInserted ) {
254 QChildEvent *ce = (QChildEvent *)event; 253 QChildEvent *ce = (QChildEvent *)event;
255 if ( ce->child()->isWidgetType() ) { 254 if ( ce->child()->isWidgetType() ) {
256 if ( ce->child()->inherits( "QMenuBar" ) ) { 255 if ( ce->child()->inherits( "QMenuBar" ) ) {
257 addWidget( (QWidget *)ce->child() ); 256 addWidget( (QWidget *)ce->child() );
258 ce->child()->installEventFilter( this ); 257 ce->child()->installEventFilter( this );
259 } else if ( object->inherits( "QToolBar" ) ) { 258 } else if ( object->inherits( "QToolBar" ) ) {
260 addWidget( (QWidget *)ce->child() ); 259 addWidget( (QWidget *)ce->child() );
261 } 260 }
262 } 261 }
263 } else if ( event->type() == QEvent::ChildRemoved ) { 262 } else if ( event->type() == QEvent::ChildRemoved ) {
264 QChildEvent *ce = (QChildEvent *)event; 263 QChildEvent *ce = (QChildEvent *)event;
265 if ( ce->child()->isWidgetType() ) { 264 if ( ce->child()->isWidgetType() ) {
266 if ( ce->child()->inherits( "QMenuBar" ) ) { 265 if ( ce->child()->inherits( "QMenuBar" ) ) {
267 removeWidget( (QWidget *)ce->child() ); 266 removeWidget( (QWidget *)ce->child() );
268 ce->child()->removeEventFilter( this ); 267 ce->child()->removeEventFilter( this );
269 } else if ( object->inherits( "QToolBar" ) ) { 268 } else if ( object->inherits( "QToolBar" ) ) {
270 removeWidget( (QWidget *)ce->child() ); 269 removeWidget( (QWidget *)ce->child() );
271 } 270 }
272 } 271 }
273 } 272 }
274 273
275 return FALSE; 274 return FALSE;
276} 275}
277 276
278void QPEMenuToolFocusManager::deactivate() 277void QPEMenuToolFocusManager::deactivate()
279{ 278{
280 setActive( FALSE ); 279 setActive( FALSE );
281} 280}
282 281
283/*! 282/*!
284 \class QPEMenuBar qpemenubar.h 283 \class QPEMenuBar qpemenubar.h
285 \brief The QPEMenuBar class is obsolete. Use QMenuBar instead. 284 \brief The QPEMenuBar class is obsolete. Use QMenuBar instead.
286 285
287 \obsolete 286 \obsolete
288 287
289 This class is obsolete. Use QMenuBar instead. 288 This class is obsolete. Use QMenuBar instead.
290 289
291*/ 290*/
292 291
293/*! 292/*!
294 Constructs a QPEMenuBar just as you would construct 293 Constructs a QPEMenuBar just as you would construct
295 a QMenuBar, passing \a parent and \a name. 294 a QMenuBar, passing \a parent and \a name.
296*/ 295*/
297QPEMenuBar::QPEMenuBar( QWidget *parent, const char *name ) 296QPEMenuBar::QPEMenuBar( QWidget *parent, const char *name )
298 : QMenuBar( parent, name ) 297 : QMenuBar( parent, name )
299{ 298{
300} 299}
301 300
302/*! 301/*!
303 \reimp 302 \reimp
304*/ 303*/
305QPEMenuBar::~QPEMenuBar() 304QPEMenuBar::~QPEMenuBar()
306{ 305{
307} 306}
308 307
309/*! 308/*!
310 \internal 309 \internal
311*/ 310*/
312void QPEMenuBar::keyPressEvent( QKeyEvent *e ) 311void QPEMenuBar::keyPressEvent( QKeyEvent *e )
313{ 312{
314 QMenuBar::keyPressEvent( e ); 313 QMenuBar::keyPressEvent( e );
315} 314}
316 315
317/*! 316/*!
318 \internal 317 \internal
319*/ 318*/
320void QPEMenuBar::activateItem( int index ) { 319void QPEMenuBar::activateItem( int index ) {
321 activateItemAt( index ); 320 activateItemAt( index );
322} 321}
323void QPEMenuBar::goodbye() { 322void QPEMenuBar::goodbye() {
324 activateItemAt(-1); 323 activateItemAt(-1);
325 for ( uint i = 0; i < count(); i++ ) { 324 for ( uint i = 0; i < count(); i++ ) {
326 QMenuItem* mi = findItem( idAt(i) ); 325 QMenuItem* mi = findItem( idAt(i) );
327 if (mi->popup() ) 326 if (mi->popup() )
328 mi->popup()->hide(); 327 mi->popup()->hide();
329 } 328 }
330} 329}
diff --git a/library/qpestyle.cpp b/library/qpestyle.cpp
index 665910c..b61ada4 100644
--- a/library/qpestyle.cpp
+++ b/library/qpestyle.cpp
@@ -1,1194 +1,1191 @@
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 "qpestyle.h" 21#include "qpestyle.h"
22#include <qpe/qpeapplication.h>
23#include <qpushbutton.h>
24 22
25#include <qpainter.h>
26 23
27#define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2) 24#define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2)
28 25
29#if QT_VERSION >= 300 26#if QT_VERSION >= 300
30 27
31#include <qdrawutil.h> 28#include <qdrawutil.h>
32#include <qcombobox.h> 29#include <qcombobox.h>
33#include <qtabbar.h> 30#include <qtabbar.h>
34 31
35QPEStyle::QPEStyle() 32QPEStyle::QPEStyle()
36{ 33{
37} 34}
38 35
39QPEStyle::~QPEStyle() 36QPEStyle::~QPEStyle()
40{ 37{
41} 38}
42 39
43void QPEStyle::drawPrimitive( PrimitiveElement pe, QPainter *p, const QRect &r, 40void QPEStyle::drawPrimitive( PrimitiveElement pe, QPainter *p, const QRect &r,
44 const QColorGroup &cg, SFlags flags, const QStyleOption &data) const 41 const QColorGroup &cg, SFlags flags, const QStyleOption &data) const
45{ 42{
46 switch ( pe ) { 43 switch ( pe ) {
47 case PE_ButtonTool: 44 case PE_ButtonTool:
48 { 45 {
49 QColorGroup mycg = cg; 46 QColorGroup mycg = cg;
50 if ( flags & Style_On ) { 47 if ( flags & Style_On ) {
51 QBrush fill( cg.mid(), Dense4Pattern ); 48 QBrush fill( cg.mid(), Dense4Pattern );
52 mycg.setBrush( QColorGroup::Button, fill ); 49 mycg.setBrush( QColorGroup::Button, fill );
53 } 50 }
54 drawPrimitive( PE_ButtonBevel, p, r, mycg, flags, data ); 51 drawPrimitive( PE_ButtonBevel, p, r, mycg, flags, data );
55 break; 52 break;
56 } 53 }
57 case PE_ButtonCommand: 54 case PE_ButtonCommand:
58 case PE_ButtonDefault: 55 case PE_ButtonDefault:
59 case PE_ButtonBevel: 56 case PE_ButtonBevel:
60 case PE_HeaderSection: 57 case PE_HeaderSection:
61 { 58 {
62 QPen oldPen = p->pen(); 59 QPen oldPen = p->pen();
63 p->fillRect( r.x()+1, r.y()+1, r.width()-2, r.height()-2, cg.brush(QColorGroup::Button) ); 60 p->fillRect( r.x()+1, r.y()+1, r.width()-2, r.height()-2, cg.brush(QColorGroup::Button) );
64 61
65 int x2 = r.right(); 62 int x2 = r.right();
66 int y2 = r.bottom(); 63 int y2 = r.bottom();
67 64
68 if ( flags & (Style_Sunken | Style_Down | Style_On) ) 65 if ( flags & (Style_Sunken | Style_Down | Style_On) )
69 p->setPen( cg.dark() ); 66 p->setPen( cg.dark() );
70 else 67 else
71 p->setPen( cg.light() ); 68 p->setPen( cg.light() );
72 p->drawLine( r.x(), r.y()+1, r.x(), y2-1 ); 69 p->drawLine( r.x(), r.y()+1, r.x(), y2-1 );
73 p->drawLine( r.x()+1, r.y(), x2-1, r.y() ); 70 p->drawLine( r.x()+1, r.y(), x2-1, r.y() );
74 71
75 if ( flags & (Style_Sunken | Style_Down | Style_On) ) 72 if ( flags & (Style_Sunken | Style_Down | Style_On) )
76 p->setPen( cg.light() ); 73 p->setPen( cg.light() );
77 else 74 else
78 p->setPen( cg.dark() ); 75 p->setPen( cg.dark() );
79 p->drawLine( x2, r.y()+1, x2, y2-1 ); 76 p->drawLine( x2, r.y()+1, x2, y2-1 );
80 p->drawLine( r.x()+1, y2, x2-1, y2 ); 77 p->drawLine( r.x()+1, y2, x2-1, y2 );
81 p->setPen( oldPen ); 78 p->setPen( oldPen );
82 break; 79 break;
83 } 80 }
84 case PE_FocusRect: 81 case PE_FocusRect:
85 break; 82 break;
86 case PE_Indicator: 83 case PE_Indicator:
87 { 84 {
88 QColorGroup mycg( cg ); 85 QColorGroup mycg( cg );
89 QBrush fill; 86 QBrush fill;
90 if ( flags & Style_Down ) 87 if ( flags & Style_Down )
91 fill = cg.brush( QColorGroup::Button ); 88 fill = cg.brush( QColorGroup::Button );
92 else 89 else
93 fill = cg.brush( (flags&Style_Enabled) ? QColorGroup::Base : QColorGroup::Background ); 90 fill = cg.brush( (flags&Style_Enabled) ? QColorGroup::Base : QColorGroup::Background );
94 mycg.setBrush( QColorGroup::Button, fill ); 91 mycg.setBrush( QColorGroup::Button, fill );
95 if ( flags&Style_Enabled ) 92 if ( flags&Style_Enabled )
96 flags |= Style_Sunken; 93 flags |= Style_Sunken;
97 drawPrimitive( PE_ButtonBevel, p, r, mycg, flags ); 94 drawPrimitive( PE_ButtonBevel, p, r, mycg, flags );
98 if ( flags & Style_On ) { 95 if ( flags & Style_On ) {
99 QPointArray a( 7*2 ); 96 QPointArray a( 7*2 );
100 int i, xx, yy; 97 int i, xx, yy;
101 xx = r.x()+3; 98 xx = r.x()+3;
102 yy = r.y()+5; 99 yy = r.y()+5;
103 for ( i=0; i<3; i++ ) { 100 for ( i=0; i<3; i++ ) {
104 a.setPoint( 2*i, xx, yy ); 101 a.setPoint( 2*i, xx, yy );
105 a.setPoint( 2*i+1, xx, yy+2 ); 102 a.setPoint( 2*i+1, xx, yy+2 );
106 xx++; yy++; 103 xx++; yy++;
107 } 104 }
108 yy -= 2; 105 yy -= 2;
109 for ( i=3; i<7; i++ ) { 106 for ( i=3; i<7; i++ ) {
110 a.setPoint( 2*i, xx, yy ); 107 a.setPoint( 2*i, xx, yy );
111 a.setPoint( 2*i+1, xx, yy+2 ); 108 a.setPoint( 2*i+1, xx, yy+2 );
112 xx++; yy--; 109 xx++; yy--;
113 } 110 }
114 if ( flags & Style_NoChange ) { 111 if ( flags & Style_NoChange ) {
115 p->setPen( mycg.dark() ); 112 p->setPen( mycg.dark() );
116 } else { 113 } else {
117 p->setPen( mycg.text() ); 114 p->setPen( mycg.text() );
118 } 115 }
119 p->drawLineSegments( a ); 116 p->drawLineSegments( a );
120 } 117 }
121 break; 118 break;
122 } 119 }
123 case PE_ExclusiveIndicator: 120 case PE_ExclusiveIndicator:
124 { 121 {
125 static const QCOORD pts1[] = { // dark lines 122 static const QCOORD pts1[] = { // dark lines
126 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 }; 123 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 };
127 static const QCOORD pts4[] = { // white lines 124 static const QCOORD pts4[] = { // white lines
128 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7, 125 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7,
129 11,4, 10,3, 10,2 }; 126 11,4, 10,3, 10,2 };
130 static const QCOORD pts5[] = { // inner fill 127 static const QCOORD pts5[] = { // inner fill
131 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 }; 128 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 };
132 129
133 int x, y, w, h; 130 int x, y, w, h;
134 r.rect( &x, &y, &w, &h ); 131 r.rect( &x, &y, &w, &h );
135 p->eraseRect( x, y, w, h ); 132 p->eraseRect( x, y, w, h );
136 QPointArray a( QCOORDARRLEN(pts1), pts1 ); 133 QPointArray a( QCOORDARRLEN(pts1), pts1 );
137 a.translate( x, y ); 134 a.translate( x, y );
138 p->setPen( cg.dark() ); 135 p->setPen( cg.dark() );
139 p->drawPolyline( a ); 136 p->drawPolyline( a );
140 a.setPoints( QCOORDARRLEN(pts4), pts4 ); 137 a.setPoints( QCOORDARRLEN(pts4), pts4 );
141 a.translate( x, y ); 138 a.translate( x, y );
142 p->setPen( cg.light() ); 139 p->setPen( cg.light() );
143 p->drawPolyline( a ); 140 p->drawPolyline( a );
144 a.setPoints( QCOORDARRLEN(pts5), pts5 ); 141 a.setPoints( QCOORDARRLEN(pts5), pts5 );
145 a.translate( x, y ); 142 a.translate( x, y );
146 QColor fillColor = ( flags&Style_Down || !(flags&Style_Enabled) ) ? cg.button() : cg.base(); 143 QColor fillColor = ( flags&Style_Down || !(flags&Style_Enabled) ) ? cg.button() : cg.base();
147 p->setPen( fillColor ); 144 p->setPen( fillColor );
148 p->setBrush( fillColor ) ; 145 p->setBrush( fillColor ) ;
149 p->drawPolygon( a ); 146 p->drawPolygon( a );
150 if ( flags&Style_On ) { 147 if ( flags&Style_On ) {
151 p->setPen( NoPen ); 148 p->setPen( NoPen );
152 p->setBrush( cg.text() ); 149 p->setBrush( cg.text() );
153 p->drawRect( x+5, y+4, 2, 4 ); 150 p->drawRect( x+5, y+4, 2, 4 );
154 p->drawRect( x+4, y+5, 4, 2 ); 151 p->drawRect( x+4, y+5, 4, 2 );
155 } 152 }
156 break; 153 break;
157 } 154 }
158 default: 155 default:
159 QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, data ); 156 QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, data );
160 break; 157 break;
161 } 158 }
162} 159}
163 160
164void QPEStyle::drawControl( ControlElement ce, QPainter *p, 161void QPEStyle::drawControl( ControlElement ce, QPainter *p,
165 const QWidget *widget, const QRect &r, 162 const QWidget *widget, const QRect &r,
166 const QColorGroup &cg, SFlags how, const QStyleOption &data) const 163 const QColorGroup &cg, SFlags how, const QStyleOption &data) const
167{ 164{
168 switch ( ce ) { 165 switch ( ce ) {
169 case CE_PushButton: 166 case CE_PushButton:
170 { 167 {
171 const QPushButton *btn = (QPushButton*)widget; 168 const QPushButton *btn = (QPushButton*)widget;
172 SFlags flags; 169 SFlags flags;
173 flags = Style_Default; 170 flags = Style_Default;
174 if ( btn->isDown() ) 171 if ( btn->isDown() )
175 flags |= Style_Down; 172 flags |= Style_Down;
176 if ( btn->isOn() ) 173 if ( btn->isOn() )
177 flags |= Style_On; 174 flags |= Style_On;
178 if ( btn->isEnabled() ) 175 if ( btn->isEnabled() )
179 flags |= Style_Enabled; 176 flags |= Style_Enabled;
180 if ( btn->isDefault() ) 177 if ( btn->isDefault() )
181 flags |= Style_Default; 178 flags |= Style_Default;
182 if (! btn->isFlat() && !(flags & Style_Down)) 179 if (! btn->isFlat() && !(flags & Style_Down))
183 flags |= Style_Raised; 180 flags |= Style_Raised;
184 p->setPen( cg.foreground() ); 181 p->setPen( cg.foreground() );
185 p->setBrush( QBrush(cg.button(), NoBrush) ); 182 p->setBrush( QBrush(cg.button(), NoBrush) );
186 QColorGroup mycg( cg ); 183 QColorGroup mycg( cg );
187 if ( flags & Style_On ) { 184 if ( flags & Style_On ) {
188 QBrush fill = QBrush( cg.mid(), Dense4Pattern ); 185 QBrush fill = QBrush( cg.mid(), Dense4Pattern );
189 mycg.setBrush( QColorGroup::Button, fill ); 186 mycg.setBrush( QColorGroup::Button, fill );
190 } 187 }
191 drawPrimitive( PE_ButtonBevel, p, r, mycg, flags, data ); 188 drawPrimitive( PE_ButtonBevel, p, r, mycg, flags, data );
192 break; 189 break;
193 } 190 }
194 case CE_TabBarTab: 191 case CE_TabBarTab:
195 { 192 {
196 if ( !widget || !widget->parentWidget() ) 193 if ( !widget || !widget->parentWidget() )
197 break; 194 break;
198 195
199 const QTabBar *tb = (const QTabBar *) widget; 196 const QTabBar *tb = (const QTabBar *) widget;
200 bool selected = how & Style_Selected; 197 bool selected = how & Style_Selected;
201 198
202 QRect r2(r); 199 QRect r2(r);
203 if ( tb->shape() == QTabBar::RoundedAbove ) { 200 if ( tb->shape() == QTabBar::RoundedAbove ) {
204 p->setPen( cg.light() ); 201 p->setPen( cg.light() );
205 p->drawLine( r2.left(), r2.bottom(), r2.right(), r2.bottom() ); 202 p->drawLine( r2.left(), r2.bottom(), r2.right(), r2.bottom() );
206 if ( r2.left() == 0 ) 203 if ( r2.left() == 0 )
207 p->drawPoint( tb->rect().bottomLeft() ); 204 p->drawPoint( tb->rect().bottomLeft() );
208 else { 205 else {
209 p->setPen( cg.light() ); 206 p->setPen( cg.light() );
210 p->drawLine( r2.left(), r2.bottom(), r2.right(), r2.bottom() ); 207 p->drawLine( r2.left(), r2.bottom(), r2.right(), r2.bottom() );
211 } 208 }
212 209
213 if ( selected ) { 210 if ( selected ) {
214 p->setPen( cg.background() ); 211 p->setPen( cg.background() );
215 p->drawLine( r2.left()+2, r2.top()+1, r2.right()-2, r2.top()+1 ); 212 p->drawLine( r2.left()+2, r2.top()+1, r2.right()-2, r2.top()+1 );
216 p->fillRect( QRect( r2.left()+1, r2.top()+2, r2.width()-2, r2.height()-2), 213 p->fillRect( QRect( r2.left()+1, r2.top()+2, r2.width()-2, r2.height()-2),
217 cg.brush( QColorGroup::Background )); 214 cg.brush( QColorGroup::Background ));
218 } else { 215 } else {
219 r2.setRect( r2.left() + 2, r2.top() + 2, 216 r2.setRect( r2.left() + 2, r2.top() + 2,
220 r2.width() - 4, r2.height() - 2 ); 217 r2.width() - 4, r2.height() - 2 );
221 p->setPen( cg.button() ); 218 p->setPen( cg.button() );
222 p->drawLine( r2.left()+2, r2.top()+1, r2.right()-2, r2.top()+1 ); 219 p->drawLine( r2.left()+2, r2.top()+1, r2.right()-2, r2.top()+1 );
223 p->fillRect( QRect( r2.left()+1, r2.top()+2, r2.width()-2, r2.height()-3), 220 p->fillRect( QRect( r2.left()+1, r2.top()+2, r2.width()-2, r2.height()-3),
224 cg.brush( QColorGroup::Button )); 221 cg.brush( QColorGroup::Button ));
225 222
226 //do shading; will not work for pixmap brushes 223 //do shading; will not work for pixmap brushes
227 QColor bg = cg.button(); 224 QColor bg = cg.button();
228 // int h,s,v; 225 // int h,s,v;
229 // bg.hsv( &h, &s, &v ); 226 // bg.hsv( &h, &s, &v );
230 int n = r2.height()/2; 227 int n = r2.height()/2;
231 int dark = 100; 228 int dark = 100;
232 for ( int i = 1; i < n; i++ ) { 229 for ( int i = 1; i < n; i++ ) {
233 dark = (dark * (100+(i*15)/n) )/100; 230 dark = (dark * (100+(i*15)/n) )/100;
234 p->setPen( bg.dark( dark ) ); 231 p->setPen( bg.dark( dark ) );
235 int y = r2.bottom()-n+i; 232 int y = r2.bottom()-n+i;
236 int x1 = r2.left()+1; 233 int x1 = r2.left()+1;
237 int x2 = r2.right()-1; 234 int x2 = r2.right()-1;
238 p->drawLine( x1, y, x2, y ); 235 p->drawLine( x1, y, x2, y );
239 } 236 }
240 } 237 }
241 238
242 p->setPen( cg.light() ); 239 p->setPen( cg.light() );
243 p->drawLine( r2.left(), r2.bottom()-1, r2.left(), r2.top() + 2 ); 240 p->drawLine( r2.left(), r2.bottom()-1, r2.left(), r2.top() + 2 );
244 p->drawPoint( r2.left()+1, r2.top() + 1 ); 241 p->drawPoint( r2.left()+1, r2.top() + 1 );
245 p->drawLine( r2.left()+2, r2.top(), 242 p->drawLine( r2.left()+2, r2.top(),
246 r2.right() - 2, r2.top() ); 243 r2.right() - 2, r2.top() );
247 244
248 p->setPen( cg.dark() ); 245 p->setPen( cg.dark() );
249 p->drawPoint( r2.right() - 1, r2.top() + 1 ); 246 p->drawPoint( r2.right() - 1, r2.top() + 1 );
250 p->drawLine( r2.right(), r2.top() + 2, r2.right(), r2.bottom() - 1); 247 p->drawLine( r2.right(), r2.top() + 2, r2.right(), r2.bottom() - 1);
251 } else if ( tb->shape() == QTabBar::RoundedBelow ) { 248 } else if ( tb->shape() == QTabBar::RoundedBelow ) {
252 if ( selected ) { 249 if ( selected ) {
253 p->setPen( cg.background() ); 250 p->setPen( cg.background() );
254 p->drawLine( r2.left()+2, r2.bottom()-1, r2.right()-2, r2.bottom()-1 ); 251 p->drawLine( r2.left()+2, r2.bottom()-1, r2.right()-2, r2.bottom()-1 );
255 p->fillRect( QRect( r2.left()+1, r2.top(), r2.width()-2, r2.height()-2), 252 p->fillRect( QRect( r2.left()+1, r2.top(), r2.width()-2, r2.height()-2),
256 tb->palette().normal().brush( QColorGroup::Background )); 253 tb->palette().normal().brush( QColorGroup::Background ));
257 } else { 254 } else {
258 p->setPen( cg.dark() ); 255 p->setPen( cg.dark() );
259 p->drawLine( r2.left(), r2.top(), 256 p->drawLine( r2.left(), r2.top(),
260 r2.right(), r2.top() ); 257 r2.right(), r2.top() );
261 r2.setRect( r2.left() + 2, r2.top(), 258 r2.setRect( r2.left() + 2, r2.top(),
262 r2.width() - 4, r2.height() - 2 ); 259 r2.width() - 4, r2.height() - 2 );
263 p->setPen( cg.button() ); 260 p->setPen( cg.button() );
264 p->drawLine( r2.left()+2, r2.bottom()-1, r2.right()-2, r2.bottom()-1 ); 261 p->drawLine( r2.left()+2, r2.bottom()-1, r2.right()-2, r2.bottom()-1 );
265 p->fillRect( QRect( r2.left()+1, r2.top()+1, r2.width()-2, r2.height()-3), 262 p->fillRect( QRect( r2.left()+1, r2.top()+1, r2.width()-2, r2.height()-3),
266 tb->palette().normal().brush( QColorGroup::Button )); 263 tb->palette().normal().brush( QColorGroup::Button ));
267 } 264 }
268 265
269 p->setPen( cg.dark() ); 266 p->setPen( cg.dark() );
270 p->drawLine( r2.right(), r2.top(), 267 p->drawLine( r2.right(), r2.top(),
271 r2.right(), r2.bottom() - 2 ); 268 r2.right(), r2.bottom() - 2 );
272 p->drawPoint( r2.right() - 1, r2.bottom() - 1 ); 269 p->drawPoint( r2.right() - 1, r2.bottom() - 1 );
273 p->drawLine( r2.right() - 2, r2.bottom(), 270 p->drawLine( r2.right() - 2, r2.bottom(),
274 r2.left() + 2, r2.bottom() ); 271 r2.left() + 2, r2.bottom() );
275 272
276 p->setPen( cg.light() ); 273 p->setPen( cg.light() );
277 p->drawLine( r2.left(), r2.top()+1, 274 p->drawLine( r2.left(), r2.top()+1,
278 r2.left(), r2.bottom() - 2 ); 275 r2.left(), r2.bottom() - 2 );
279 p->drawPoint( r2.left() + 1, r2.bottom() - 1 ); 276 p->drawPoint( r2.left() + 1, r2.bottom() - 1 );
280 if ( r2.left() == 0 ) 277 if ( r2.left() == 0 )
281 p->drawPoint( tb->rect().topLeft() ); 278 p->drawPoint( tb->rect().topLeft() );
282 279
283 } else { 280 } else {
284 QCommonStyle::drawControl( ce, p, widget, r, cg, how, data ); 281 QCommonStyle::drawControl( ce, p, widget, r, cg, how, data );
285 } 282 }
286 break; 283 break;
287 } 284 }
288 default: 285 default:
289 QWindowsStyle::drawControl( ce, p, widget, r, cg, how, data ); 286 QWindowsStyle::drawControl( ce, p, widget, r, cg, how, data );
290 break; 287 break;
291 } 288 }
292} 289}
293 290
294void QPEStyle::drawComplexControl( ComplexControl control, QPainter *p, 291void QPEStyle::drawComplexControl( ComplexControl control, QPainter *p,
295 const QWidget *widget, const QRect &r, 292 const QWidget *widget, const QRect &r,
296 const QColorGroup &cg, SFlags how, 293 const QColorGroup &cg, SFlags how,
297 SCFlags sub, SCFlags subActive, const QStyleOption &data) const 294 SCFlags sub, SCFlags subActive, const QStyleOption &data) const
298{ 295{
299 switch ( control ) { 296 switch ( control ) {
300 case CC_ComboBox: 297 case CC_ComboBox:
301 if ( sub & SC_ComboBoxArrow ) { 298 if ( sub & SC_ComboBoxArrow ) {
302 SFlags flags = Style_Default; 299 SFlags flags = Style_Default;
303 300
304 drawPrimitive( PE_ButtonBevel, p, r, cg, flags, data ); 301 drawPrimitive( PE_ButtonBevel, p, r, cg, flags, data );
305 302
306 QRect ar = 303 QRect ar =
307 QStyle::visualRect( querySubControlMetrics( CC_ComboBox, widget, 304 QStyle::visualRect( querySubControlMetrics( CC_ComboBox, widget,
308 SC_ComboBoxArrow ), widget ); 305 SC_ComboBoxArrow ), widget );
309 306
310 if ( subActive == SC_ComboBoxArrow ) { 307 if ( subActive == SC_ComboBoxArrow ) {
311 p->setPen( cg.dark() ); 308 p->setPen( cg.dark() );
312 p->setBrush( cg.brush( QColorGroup::Button ) ); 309 p->setBrush( cg.brush( QColorGroup::Button ) );
313 p->drawRect( ar ); 310 p->drawRect( ar );
314 } 311 }
315 312
316 ar.addCoords( 2, 2, -2, -2 ); 313 ar.addCoords( 2, 2, -2, -2 );
317 if ( widget->isEnabled() ) 314 if ( widget->isEnabled() )
318 flags |= Style_Enabled; 315 flags |= Style_Enabled;
319 316
320 if ( subActive & Style_Sunken ) { 317 if ( subActive & Style_Sunken ) {
321 flags |= Style_Sunken; 318 flags |= Style_Sunken;
322 } 319 }
323 drawPrimitive( PE_ArrowDown, p, ar, cg, flags ); 320 drawPrimitive( PE_ArrowDown, p, ar, cg, flags );
324 } 321 }
325 322
326 if ( sub & SC_ComboBoxEditField ) { 323 if ( sub & SC_ComboBoxEditField ) {
327 const QComboBox * cb = (const QComboBox *) widget; 324 const QComboBox * cb = (const QComboBox *) widget;
328 QRect re = 325 QRect re =
329 QStyle::visualRect( querySubControlMetrics( CC_ComboBox, widget, 326 QStyle::visualRect( querySubControlMetrics( CC_ComboBox, widget,
330 SC_ComboBoxEditField ), widget ); 327 SC_ComboBoxEditField ), widget );
331 if ( cb->hasFocus() && !cb->editable() ) 328 if ( cb->hasFocus() && !cb->editable() )
332 p->fillRect( re.x(), re.y(), re.width(), re.height(), 329 p->fillRect( re.x(), re.y(), re.width(), re.height(),
333 cg.brush( QColorGroup::Highlight ) ); 330 cg.brush( QColorGroup::Highlight ) );
334 331
335 if ( cb->hasFocus() ) { 332 if ( cb->hasFocus() ) {
336 p->setPen( cg.highlightedText() ); 333 p->setPen( cg.highlightedText() );
337 p->setBackgroundColor( cg.highlight() ); 334 p->setBackgroundColor( cg.highlight() );
338 335
339 } else { 336 } else {
340 p->setPen( cg.text() ); 337 p->setPen( cg.text() );
341 p->setBackgroundColor( cg.background() ); 338 p->setBackgroundColor( cg.background() );
342 } 339 }
343 340
344 if ( cb->hasFocus() && !cb->editable() ) { 341 if ( cb->hasFocus() && !cb->editable() ) {
345 QRect re = 342 QRect re =
346 QStyle::visualRect( subRect( SR_ComboBoxFocusRect, cb ), widget ); 343 QStyle::visualRect( subRect( SR_ComboBoxFocusRect, cb ), widget );
347 drawPrimitive( PE_FocusRect, p, re, cg, Style_FocusAtBorder, QStyleOption(cg.highlight())); 344 drawPrimitive( PE_FocusRect, p, re, cg, Style_FocusAtBorder, QStyleOption(cg.highlight()));
348 } 345 }
349 } 346 }
350 break; 347 break;
351 default: 348 default:
352 QWindowsStyle::drawComplexControl( control, p, widget, r, cg, how, 349 QWindowsStyle::drawComplexControl( control, p, widget, r, cg, how,
353 sub, subActive, data ); 350 sub, subActive, data );
354 break; 351 break;
355 } 352 }
356} 353}
357 354
358int QPEStyle::pixelMetric( PixelMetric metric, const QWidget *widget ) const 355int QPEStyle::pixelMetric( PixelMetric metric, const QWidget *widget ) const
359{ 356{
360 int ret; 357 int ret;
361 switch( metric ) { 358 switch( metric ) {
362 case PM_ButtonMargin: 359 case PM_ButtonMargin:
363 ret = 2; 360 ret = 2;
364 break; 361 break;
365 case PM_DefaultFrameWidth: 362 case PM_DefaultFrameWidth:
366 ret = 1; 363 ret = 1;
367 break; 364 break;
368 case PM_ButtonDefaultIndicator: 365 case PM_ButtonDefaultIndicator:
369 ret = 2; 366 ret = 2;
370 break; 367 break;
371 case PM_ButtonShiftHorizontal: 368 case PM_ButtonShiftHorizontal:
372 case PM_ButtonShiftVertical: 369 case PM_ButtonShiftVertical:
373 ret = -1; 370 ret = -1;
374 break; 371 break;
375 case PM_IndicatorWidth: 372 case PM_IndicatorWidth:
376 ret = 15; 373 ret = 15;
377 break; 374 break;
378 case PM_IndicatorHeight: 375 case PM_IndicatorHeight:
379 ret = 13; 376 ret = 13;
380 break; 377 break;
381 case PM_ExclusiveIndicatorHeight: 378 case PM_ExclusiveIndicatorHeight:
382 case PM_ExclusiveIndicatorWidth: 379 case PM_ExclusiveIndicatorWidth:
383 ret = 15; 380 ret = 15;
384 break; 381 break;
385 case PM_ScrollBarExtent: 382 case PM_ScrollBarExtent:
386 ret = 13; 383 ret = 13;
387 break; 384 break;
388 case PM_SliderLength: 385 case PM_SliderLength:
389 ret = 12; 386 ret = 12;
390 break; 387 break;
391 default: 388 default:
392 ret = QWindowsStyle::pixelMetric( metric, widget ); 389 ret = QWindowsStyle::pixelMetric( metric, widget );
393 break; 390 break;
394 } 391 }
395 return ret; 392 return ret;
396} 393}
397 394
398QSize QPEStyle::sizeFromContents( ContentsType contents, const QWidget *widget, 395QSize QPEStyle::sizeFromContents( ContentsType contents, const QWidget *widget,
399 const QSize &contentsSize, const QStyleOption &data) const 396 const QSize &contentsSize, const QStyleOption &data) const
400{ 397{
401 QSize sz(contentsSize); 398 QSize sz(contentsSize);
402 399
403 switch ( contents ) { 400 switch ( contents ) {
404 case CT_PopupMenuItem: 401 case CT_PopupMenuItem:
405 { 402 {
406 if ( !widget || data.isDefault() ) 403 if ( !widget || data.isDefault() )
407 break; 404 break;
408 sz = QWindowsStyle::sizeFromContents( contents, widget, contentsSize, data ); 405 sz = QWindowsStyle::sizeFromContents( contents, widget, contentsSize, data );
409 sz = QSize( sz.width(), sz.height()-2 ); 406 sz = QSize( sz.width(), sz.height()-2 );
410 break; 407 break;
411 } 408 }
412 default: 409 default:
413 sz = QWindowsStyle::sizeFromContents( contents, widget, contentsSize, data ); 410 sz = QWindowsStyle::sizeFromContents( contents, widget, contentsSize, data );
414 break; 411 break;
415 } 412 }
416 413
417 return sz; 414 return sz;
418} 415}
419 416
420#else 417#else
421 418
422#include <qfontmetrics.h> 419#include <qfontmetrics.h>
423#include <qpalette.h> 420#include <qpalette.h>
424#include <qdrawutil.h> 421#include <qdrawutil.h>
425#include <qscrollbar.h> 422#include <qscrollbar.h>
426#include <qbutton.h> 423#include <qbutton.h>
427#include <qframe.h> 424#include <qframe.h>
428#include <qtabbar.h> 425#include <qtabbar.h>
429 426
430#define INCLUDE_MENUITEM_DEF 427#define INCLUDE_MENUITEM_DEF
431#include <qmenudata.h> 428#include <qmenudata.h>
432 429
433QPEStyle::QPEStyle() 430QPEStyle::QPEStyle()
434{ 431{
435#if QT_VERSION < 300 432#if QT_VERSION < 300
436 setButtonMargin(buttonMargin()); 433 setButtonMargin(buttonMargin());
437 setScrollBarExtent(scrollBarExtent().width(),scrollBarExtent().height()); 434 setScrollBarExtent(scrollBarExtent().width(),scrollBarExtent().height());
438#endif 435#endif
439} 436}
440 437
441QPEStyle::~QPEStyle() 438QPEStyle::~QPEStyle()
442{ 439{
443} 440}
444 441
445int QPEStyle::buttonMargin() const 442int QPEStyle::buttonMargin() const
446{ 443{
447 return 2; 444 return 2;
448} 445}
449 446
450QSize QPEStyle::scrollBarExtent() const 447QSize QPEStyle::scrollBarExtent() const
451{ 448{
452 return QSize(13,13); 449 return QSize(13,13);
453} 450}
454 451
455void QPEStyle::polish ( QPalette & ) 452void QPEStyle::polish ( QPalette & )
456{ 453{
457} 454}
458 455
459void QPEStyle::polish( QWidget *w ) 456void QPEStyle::polish( QWidget *w )
460{ 457{
461 if ( w->inherits( "QListBox" ) || 458 if ( w->inherits( "QListBox" ) ||
462 w->inherits( "QListView" ) || 459 w->inherits( "QListView" ) ||
463 w->inherits( "QPopupMenu" ) || 460 w->inherits( "QPopupMenu" ) ||
464 w->inherits( "QSpinBox" ) ) { 461 w->inherits( "QSpinBox" ) ) {
465 QFrame *f = (QFrame *)w; 462 QFrame *f = (QFrame *)w;
466 f->setFrameShape( QFrame::StyledPanel ); 463 f->setFrameShape( QFrame::StyledPanel );
467 f->setLineWidth( 1 ); 464 f->setLineWidth( 1 );
468 } 465 }
469} 466}
470 467
471void QPEStyle::unPolish( QWidget *w ) 468void QPEStyle::unPolish( QWidget *w )
472{ 469{
473 if ( w->inherits( "QListBox" ) || 470 if ( w->inherits( "QListBox" ) ||
474 w->inherits( "QListView" ) || 471 w->inherits( "QListView" ) ||
475 w->inherits( "QPopupMenu" ) || 472 w->inherits( "QPopupMenu" ) ||
476 w->inherits( "QSpinBox" ) ) { 473 w->inherits( "QSpinBox" ) ) {
477 QFrame *f = (QFrame *)w; 474 QFrame *f = (QFrame *)w;
478 f->setFrameShape( QFrame::StyledPanel ); 475 f->setFrameShape( QFrame::StyledPanel );
479 f->setLineWidth( 2 ); 476 f->setLineWidth( 2 );
480 } 477 }
481} 478}
482 479
483int QPEStyle::defaultFrameWidth() const 480int QPEStyle::defaultFrameWidth() const
484{ 481{
485 return 1; 482 return 1;
486} 483}
487 484
488void QPEStyle::drawPanel ( QPainter * p, int x, int y, int w, int h, 485void QPEStyle::drawPanel ( QPainter * p, int x, int y, int w, int h,
489 const QColorGroup &g, bool sunken, int lineWidth, const QBrush * fill ) 486 const QColorGroup &g, bool sunken, int lineWidth, const QBrush * fill )
490{ 487{
491 qDrawShadePanel( p, QRect(x, y, w, h), g, sunken, lineWidth, fill ); 488 qDrawShadePanel( p, QRect(x, y, w, h), g, sunken, lineWidth, fill );
492} 489}
493 490
494void QPEStyle::drawButton( QPainter *p, int x, int y, int w, int h, 491void QPEStyle::drawButton( QPainter *p, int x, int y, int w, int h,
495 const QColorGroup &g, bool sunken, const QBrush* fill ) 492 const QColorGroup &g, bool sunken, const QBrush* fill )
496{ 493{
497 QPen oldPen = p->pen(); 494 QPen oldPen = p->pen();
498 if ( sunken ) 495 if ( sunken )
499 p->setPen( g.dark() ); 496 p->setPen( g.dark() );
500 else 497 else
501 p->setPen( g.light() ); 498 p->setPen( g.light() );
502 499
503 int x2 = x+w-1; 500 int x2 = x+w-1;
504 int y2 = y+h-1; 501 int y2 = y+h-1;
505 502
506 p->drawLine( x, y, x, y2 ); 503 p->drawLine( x, y, x, y2 );
507 p->drawLine( x, y, x2, y ); 504 p->drawLine( x, y, x2, y );
508 505
509 if ( sunken ) 506 if ( sunken )
510 p->setPen( g.light() ); 507 p->setPen( g.light() );
511 else 508 else
512 p->setPen( g.dark() ); 509 p->setPen( g.dark() );
513 510
514 p->drawLine( x2, y, x2, y2 ); 511 p->drawLine( x2, y, x2, y2 );
515 p->drawLine( x, y2, x2, y2 ); 512 p->drawLine( x, y2, x2, y2 );
516 p->setPen( oldPen ); 513 p->setPen( oldPen );
517 514
518 p->fillRect( x+1, y+1, w-2, h-2, fill?(*fill):g.brush(QColorGroup::Button) ); 515 p->fillRect( x+1, y+1, w-2, h-2, fill?(*fill):g.brush(QColorGroup::Button) );
519} 516}
520 517
521void QPEStyle::drawButtonMask ( QPainter * p, int x, int y, int w, int h ) 518void QPEStyle::drawButtonMask ( QPainter * p, int x, int y, int w, int h )
522{ 519{
523 p->fillRect( x, y, w, h, color1 ); 520 p->fillRect( x, y, w, h, color1 );
524} 521}
525 522
526void QPEStyle::drawBevelButton( QPainter *p, int x, int y, int w, int h, 523void QPEStyle::drawBevelButton( QPainter *p, int x, int y, int w, int h,
527 const QColorGroup &g, bool sunken, const QBrush* fill ) 524 const QColorGroup &g, bool sunken, const QBrush* fill )
528{ 525{
529 drawButton( p, x, y, w, h, g, sunken, fill ); 526 drawButton( p, x, y, w, h, g, sunken, fill );
530} 527}
531 528
532QRect QPEStyle::comboButtonRect( int x, int y, int w, int h) 529QRect QPEStyle::comboButtonRect( int x, int y, int w, int h)
533{ 530{
534 return QRect(x+1, y+1, w-2-14, h-2); 531 return QRect(x+1, y+1, w-2-14, h-2);
535} 532}
536 533
537 534
538QRect QPEStyle::comboButtonFocusRect( int x, int y, int w, int h) 535QRect QPEStyle::comboButtonFocusRect( int x, int y, int w, int h)
539{ 536{
540 return QRect(x+2, y+2, w-4-14, h-4); 537 return QRect(x+2, y+2, w-4-14, h-4);
541} 538}
542 539
543void QPEStyle::drawComboButton( QPainter *p, int x, int y, int w, int h, 540void QPEStyle::drawComboButton( QPainter *p, int x, int y, int w, int h,
544 const QColorGroup &g, bool sunken, 541 const QColorGroup &g, bool sunken,
545 bool /*editable*/, 542 bool /*editable*/,
546 bool enabled, 543 bool enabled,
547 const QBrush *fill ) 544 const QBrush *fill )
548{ 545{
549 drawBevelButton( p, x, y, w, h, g, FALSE, fill ); 546 drawBevelButton( p, x, y, w, h, g, FALSE, fill );
550 drawBevelButton( p, x+w-14, y, 14, h, g, sunken, fill ); 547 drawBevelButton( p, x+w-14, y, 14, h, g, sunken, fill );
551 drawArrow( p, QStyle::DownArrow, sunken, 548 drawArrow( p, QStyle::DownArrow, sunken,
552 x+w-14+ 2, y+ 2, 14- 4, h- 4, g, enabled, 549 x+w-14+ 2, y+ 2, 14- 4, h- 4, g, enabled,
553 &g.brush( QColorGroup::Button ) ); 550 &g.brush( QColorGroup::Button ) );
554 551
555} 552}
556 553
557 554
558void QPEStyle::drawExclusiveIndicator ( QPainter * p, int x, int y, int w, 555void QPEStyle::drawExclusiveIndicator ( QPainter * p, int x, int y, int w,
559 int h, const QColorGroup & g, bool on, bool down, bool enabled ) 556 int h, const QColorGroup & g, bool on, bool down, bool enabled )
560{ 557{
561 static const QCOORD pts1[] = { // dark lines 558 static const QCOORD pts1[] = { // dark lines
562 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 }; 559 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 };
563 static const QCOORD pts4[] = { // white lines 560 static const QCOORD pts4[] = { // white lines
564 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7, 561 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7,
565 11,4, 10,3, 10,2 }; 562 11,4, 10,3, 10,2 };
566 static const QCOORD pts5[] = { // inner fill 563 static const QCOORD pts5[] = { // inner fill
567 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 }; 564 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 };
568 565
569 p->eraseRect( x, y, w, h ); 566 p->eraseRect( x, y, w, h );
570 QPointArray a( QCOORDARRLEN(pts1), pts1 ); 567 QPointArray a( QCOORDARRLEN(pts1), pts1 );
571 a.translate( x, y ); 568 a.translate( x, y );
572 p->setPen( g.dark() ); 569 p->setPen( g.dark() );
573 p->drawPolyline( a ); 570 p->drawPolyline( a );
574 a.setPoints( QCOORDARRLEN(pts4), pts4 ); 571 a.setPoints( QCOORDARRLEN(pts4), pts4 );
575 a.translate( x, y ); 572 a.translate( x, y );
576 p->setPen( g.light() ); 573 p->setPen( g.light() );
577 p->drawPolyline( a ); 574 p->drawPolyline( a );
578 a.setPoints( QCOORDARRLEN(pts5), pts5 ); 575 a.setPoints( QCOORDARRLEN(pts5), pts5 );
579 a.translate( x, y ); 576 a.translate( x, y );
580 QColor fillColor = ( down || !enabled ) ? g.button() : g.base(); 577 QColor fillColor = ( down || !enabled ) ? g.button() : g.base();
581 p->setPen( fillColor ); 578 p->setPen( fillColor );
582 p->setBrush( fillColor ) ; 579 p->setBrush( fillColor ) ;
583 p->drawPolygon( a ); 580 p->drawPolygon( a );
584 if ( on ) { 581 if ( on ) {
585 p->setPen( NoPen ); 582 p->setPen( NoPen );
586 p->setBrush( g.text() ); 583 p->setBrush( g.text() );
587 p->drawRect( x+5, y+4, 2, 4 ); 584 p->drawRect( x+5, y+4, 2, 4 );
588 p->drawRect( x+4, y+5, 4, 2 ); 585 p->drawRect( x+4, y+5, 4, 2 );
589 } 586 }
590} 587}
591 588
592void QPEStyle::drawIndicator ( QPainter * p, int x, int y, int w, int h, 589void QPEStyle::drawIndicator ( QPainter * p, int x, int y, int w, int h,
593 const QColorGroup & g, int state, bool down, bool enabled ) 590 const QColorGroup & g, int state, bool down, bool enabled )
594{ 591{
595 592
596 QBrush fill; 593 QBrush fill;
597 if ( state == QButton::NoChange ) { 594 if ( state == QButton::NoChange ) {
598 QBrush b = p->brush(); 595 QBrush b = p->brush();
599 QColor c = p->backgroundColor(); 596 QColor c = p->backgroundColor();
600 p->setBackgroundMode( TransparentMode ); 597 p->setBackgroundMode( TransparentMode );
601 p->setBackgroundColor( green ); 598 p->setBackgroundColor( green );
602 fill = QBrush(g.base(), Dense4Pattern); 599 fill = QBrush(g.base(), Dense4Pattern);
603 p->setBackgroundColor( c ); 600 p->setBackgroundColor( c );
604 p->setBrush( b ); 601 p->setBrush( b );
605 } else if ( down ) 602 } else if ( down )
606 fill = g.brush( QColorGroup::Button ); 603 fill = g.brush( QColorGroup::Button );
607 else 604 else
608 fill = g.brush( enabled ? QColorGroup::Base : QColorGroup::Background ); 605 fill = g.brush( enabled ? QColorGroup::Base : QColorGroup::Background );
609 drawPanel( p, x, y, w, h, g, TRUE, 1, &fill ); 606 drawPanel( p, x, y, w, h, g, TRUE, 1, &fill );
610 if ( state != QButton::Off ) { 607 if ( state != QButton::Off ) {
611 QPointArray a( 7*2 ); 608 QPointArray a( 7*2 );
612 int i, xx, yy; 609 int i, xx, yy;
613 xx = x+3; 610 xx = x+3;
614 yy = y+5; 611 yy = y+5;
615 for ( i=0; i<3; i++ ) { 612 for ( i=0; i<3; i++ ) {
616 a.setPoint( 2*i, xx, yy ); 613 a.setPoint( 2*i, xx, yy );
617 a.setPoint( 2*i+1, xx, yy+2 ); 614 a.setPoint( 2*i+1, xx, yy+2 );
618 xx++; yy++; 615 xx++; yy++;
619 } 616 }
620 yy -= 2; 617 yy -= 2;
621 for ( i=3; i<7; i++ ) { 618 for ( i=3; i<7; i++ ) {
622 a.setPoint( 2*i, xx, yy ); 619 a.setPoint( 2*i, xx, yy );
623 a.setPoint( 2*i+1, xx, yy+2 ); 620 a.setPoint( 2*i+1, xx, yy+2 );
624 xx++; yy--; 621 xx++; yy--;
625 } 622 }
626 if ( state == QButton::NoChange ) { 623 if ( state == QButton::NoChange ) {
627 p->setPen( g.dark() ); 624 p->setPen( g.dark() );
628 } else { 625 } else {
629 p->setPen( g.text() ); 626 p->setPen( g.text() );
630 } 627 }
631 p->drawLineSegments( a ); 628 p->drawLineSegments( a );
632 } 629 }
633} 630}
634 631
635 #define HORIZONTAL(sb->orientation() == QScrollBar::Horizontal) 632 #define HORIZONTAL(sb->orientation() == QScrollBar::Horizontal)
636 #define VERTICAL!HORIZONTAL 633 #define VERTICAL!HORIZONTAL
637 #define MOTIF_BORDER2 634 #define MOTIF_BORDER2
638 #define SLIDER_MIN9 // ### motif says 6 but that's too small 635 #define SLIDER_MIN9 // ### motif says 6 but that's too small
639 636
640/*! \reimp */ 637/*! \reimp */
641 638
642void QPEStyle::scrollBarMetrics( const QScrollBar* sb, int &sliderMin, int &sliderMax, int &sliderLength, int& buttonDim ) 639void QPEStyle::scrollBarMetrics( const QScrollBar* sb, int &sliderMin, int &sliderMax, int &sliderLength, int& buttonDim )
643{ 640{
644 int maxLength; 641 int maxLength;
645 int length = HORIZONTAL ? sb->width() : sb->height(); 642 int length = HORIZONTAL ? sb->width() : sb->height();
646 int extent = HORIZONTAL ? sb->height() : sb->width(); 643 int extent = HORIZONTAL ? sb->height() : sb->width();
647 644
648 if ( length > (extent - 1)*2 ) 645 if ( length > (extent - 1)*2 )
649 buttonDim = extent; 646 buttonDim = extent;
650 else 647 else
651 buttonDim = length/2 - 1; 648 buttonDim = length/2 - 1;
652 649
653 sliderMin = 0; 650 sliderMin = 0;
654 maxLength = length - buttonDim*2; 651 maxLength = length - buttonDim*2;
655 652
656 if ( sb->maxValue() == sb->minValue() ) { 653 if ( sb->maxValue() == sb->minValue() ) {
657 sliderLength = maxLength; 654 sliderLength = maxLength;
658 } else { 655 } else {
659 sliderLength = (sb->pageStep()*maxLength)/ 656 sliderLength = (sb->pageStep()*maxLength)/
660 (sb->maxValue()-sb->minValue()+sb->pageStep()); 657 (sb->maxValue()-sb->minValue()+sb->pageStep());
661 uint range = sb->maxValue()-sb->minValue(); 658 uint range = sb->maxValue()-sb->minValue();
662 if ( sliderLength < SLIDER_MIN || range > INT_MAX/2 ) 659 if ( sliderLength < SLIDER_MIN || range > INT_MAX/2 )
663 sliderLength = SLIDER_MIN; 660 sliderLength = SLIDER_MIN;
664 if ( sliderLength > maxLength ) 661 if ( sliderLength > maxLength )
665 sliderLength = maxLength; 662 sliderLength = maxLength;
666 } 663 }
667 664
668 sliderMax = sliderMin + maxLength - sliderLength; 665 sliderMax = sliderMin + maxLength - sliderLength;
669} 666}
670 667
671/*!\reimp 668/*!\reimp
672 */ 669 */
673QStyle::ScrollControl QPEStyle::scrollBarPointOver( const QScrollBar* sb, int sliderStart, const QPoint& p ) 670QStyle::ScrollControl QPEStyle::scrollBarPointOver( const QScrollBar* sb, int sliderStart, const QPoint& p )
674{ 671{
675 if ( !sb->rect().contains( p ) ) 672 if ( !sb->rect().contains( p ) )
676 return NoScroll; 673 return NoScroll;
677 int sliderMin, sliderMax, sliderLength, buttonDim, pos; 674 int sliderMin, sliderMax, sliderLength, buttonDim, pos;
678 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim ); 675 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim );
679 676
680 if (sb->orientation() == QScrollBar::Horizontal) 677 if (sb->orientation() == QScrollBar::Horizontal)
681 pos = p.x(); 678 pos = p.x();
682 else 679 else
683 pos = p.y(); 680 pos = p.y();
684 681
685 if (pos < sliderStart) 682 if (pos < sliderStart)
686 return SubPage; 683 return SubPage;
687 if (pos < sliderStart + sliderLength) 684 if (pos < sliderStart + sliderLength)
688 return Slider; 685 return Slider;
689 if (pos < sliderMax + sliderLength) 686 if (pos < sliderMax + sliderLength)
690 return AddPage; 687 return AddPage;
691 if (pos < sliderMax + sliderLength + buttonDim) 688 if (pos < sliderMax + sliderLength + buttonDim)
692 return SubLine; 689 return SubLine;
693 return AddLine; 690 return AddLine;
694} 691}
695 692
696/*! \reimp */ 693/*! \reimp */
697 694
698void QPEStyle::drawScrollBarControls( QPainter* p, const QScrollBar* sb, int sliderStart, uint controls, uint activeControl ) 695void QPEStyle::drawScrollBarControls( QPainter* p, const QScrollBar* sb, int sliderStart, uint controls, uint activeControl )
699{ 696{
700#define ADD_LINE_ACTIVE ( activeControl == AddLine ) 697#define ADD_LINE_ACTIVE ( activeControl == AddLine )
701#define SUB_LINE_ACTIVE ( activeControl == SubLine ) 698#define SUB_LINE_ACTIVE ( activeControl == SubLine )
702 QColorGroup g = sb->colorGroup(); 699 QColorGroup g = sb->colorGroup();
703 700
704 int sliderMin, sliderMax, sliderLength, buttonDim; 701 int sliderMin, sliderMax, sliderLength, buttonDim;
705 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim ); 702 scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim );
706 703
707 if ( controls == (AddLine | SubLine | AddPage | SubPage | Slider | First | Last ) ) 704 if ( controls == (AddLine | SubLine | AddPage | SubPage | Slider | First | Last ) )
708 p->fillRect( 0, 0, sb->width(), sb->height(), g.brush( QColorGroup::Mid )); 705 p->fillRect( 0, 0, sb->width(), sb->height(), g.brush( QColorGroup::Mid ));
709 706
710 if (sliderStart > sliderMax) { // sanity check 707 if (sliderStart > sliderMax) { // sanity check
711 sliderStart = sliderMax; 708 sliderStart = sliderMax;
712 } 709 }
713 710
714 int dimB = buttonDim; 711 int dimB = buttonDim;
715 QRect addB; 712 QRect addB;
716 QRect subB; 713 QRect subB;
717 QRect addPageR; 714 QRect addPageR;
718 QRect subPageR; 715 QRect subPageR;
719 QRect sliderR; 716 QRect sliderR;
720 int addX, addY, subX, subY; 717 int addX, addY, subX, subY;
721 int length = HORIZONTAL ? sb->width() : sb->height(); 718 int length = HORIZONTAL ? sb->width() : sb->height();
722 int extent = HORIZONTAL ? sb->height() : sb->width(); 719 int extent = HORIZONTAL ? sb->height() : sb->width();
723 720
724 if ( HORIZONTAL ) { 721 if ( HORIZONTAL ) {
725 subY = addY = ( extent - dimB ) / 2; 722 subY = addY = ( extent - dimB ) / 2;
726 subX = length - dimB - dimB; 723 subX = length - dimB - dimB;
727 addX = length - dimB; 724 addX = length - dimB;
728 } else { 725 } else {
729 subX = addX = ( extent - dimB ) / 2; 726 subX = addX = ( extent - dimB ) / 2;
730 subY = length - dimB - dimB; 727 subY = length - dimB - dimB;
731 addY = length - dimB; 728 addY = length - dimB;
732 } 729 }
733 730
734 int sliderEnd = sliderStart + sliderLength; 731 int sliderEnd = sliderStart + sliderLength;
735 int sliderW = extent; 732 int sliderW = extent;
736 if ( HORIZONTAL ) { 733 if ( HORIZONTAL ) {
737 subB.setRect( subX,subY+1,dimB,dimB-1 ); 734 subB.setRect( subX,subY+1,dimB,dimB-1 );
738 addB.setRect( addX,addY+1,dimB,dimB-1 ); 735 addB.setRect( addX,addY+1,dimB,dimB-1 );
739 736
740 subPageR.setRect( 0, 0, 737 subPageR.setRect( 0, 0,
741 sliderStart+1, sliderW ); 738 sliderStart+1, sliderW );
742 addPageR.setRect( sliderEnd-1, 0, subX - sliderEnd+1, sliderW ); 739 addPageR.setRect( sliderEnd-1, 0, subX - sliderEnd+1, sliderW );
743 sliderR .setRect( sliderStart, 1, sliderLength, sliderW-1 ); 740 sliderR .setRect( sliderStart, 1, sliderLength, sliderW-1 );
744 741
745 } else { 742 } else {
746 subB.setRect( subX+1,subY,dimB-1,dimB ); 743 subB.setRect( subX+1,subY,dimB-1,dimB );
747 addB.setRect( addX+1,addY,dimB-1,dimB ); 744 addB.setRect( addX+1,addY,dimB-1,dimB );
748 745
749 subPageR.setRect( 0, 0, sliderW, 746 subPageR.setRect( 0, 0, sliderW,
750 sliderStart+1 ); 747 sliderStart+1 );
751 addPageR.setRect( 0, sliderEnd-1, sliderW, subY - sliderEnd+1 ); 748 addPageR.setRect( 0, sliderEnd-1, sliderW, subY - sliderEnd+1 );
752 sliderR .setRect( 1, sliderStart, sliderW-1, sliderLength ); 749 sliderR .setRect( 1, sliderStart, sliderW-1, sliderLength );
753 } 750 }
754 751
755 bool maxedOut = (sb->maxValue() == sb->minValue()); 752 bool maxedOut = (sb->maxValue() == sb->minValue());
756 if ( controls & AddLine ) { 753 if ( controls & AddLine ) {
757 drawBevelButton( p, addB.x(), addB.y(), 754 drawBevelButton( p, addB.x(), addB.y(),
758 addB.width(), addB.height(), g, 755 addB.width(), addB.height(), g,
759 ADD_LINE_ACTIVE); 756 ADD_LINE_ACTIVE);
760 p->setPen(g.shadow()); 757 p->setPen(g.shadow());
761 drawArrow( p, VERTICAL ? DownArrow : RightArrow, 758 drawArrow( p, VERTICAL ? DownArrow : RightArrow,
762 FALSE, addB.x()+2, addB.y()+2, 759 FALSE, addB.x()+2, addB.y()+2,
763 addB.width()-4, addB.height()-4, g, !maxedOut, 760 addB.width()-4, addB.height()-4, g, !maxedOut,
764 &g.brush( QColorGroup::Button )); 761 &g.brush( QColorGroup::Button ));
765 } 762 }
766 if ( controls & SubLine ) { 763 if ( controls & SubLine ) {
767 drawBevelButton( p, subB.x(), subB.y(), 764 drawBevelButton( p, subB.x(), subB.y(),
768 subB.width(), subB.height(), g, 765 subB.width(), subB.height(), g,
769 SUB_LINE_ACTIVE ); 766 SUB_LINE_ACTIVE );
770 p->setPen(g.shadow()); 767 p->setPen(g.shadow());
771 drawArrow( p, VERTICAL ? UpArrow : LeftArrow, 768 drawArrow( p, VERTICAL ? UpArrow : LeftArrow,
772 FALSE, subB.x()+2, subB.y()+2, 769 FALSE, subB.x()+2, subB.y()+2,
773 subB.width()-4, subB.height()-4, g, !maxedOut, 770 subB.width()-4, subB.height()-4, g, !maxedOut,
774 &g.brush( QColorGroup::Button )); 771 &g.brush( QColorGroup::Button ));
775 } 772 }
776 773
777 774
778 if ( controls & SubPage ) 775 if ( controls & SubPage )
779 p->fillRect( subPageR.x(), subPageR.y(), subPageR.width(), 776 p->fillRect( subPageR.x(), subPageR.y(), subPageR.width(),
780 subPageR.height(), g.brush( QColorGroup::Mid )); 777 subPageR.height(), g.brush( QColorGroup::Mid ));
781 if ( controls & AddPage ) 778 if ( controls & AddPage )
782 p->fillRect( addPageR.x(), addPageR.y(), addPageR.width(), 779 p->fillRect( addPageR.x(), addPageR.y(), addPageR.width(),
783 addPageR.height(), g.brush( QColorGroup::Mid )); 780 addPageR.height(), g.brush( QColorGroup::Mid ));
784 if ( controls & Slider ) { 781 if ( controls & Slider ) {
785 QPoint bo = p->brushOrigin(); 782 QPoint bo = p->brushOrigin();
786 p->setBrushOrigin(sliderR.topLeft()); 783 p->setBrushOrigin(sliderR.topLeft());
787 drawBevelButton( p, sliderR.x(), sliderR.y(), 784 drawBevelButton( p, sliderR.x(), sliderR.y(),
788 sliderR.width(), sliderR.height(), g, 785 sliderR.width(), sliderR.height(), g,
789 FALSE, &g.brush( QColorGroup::Button ) ); 786 FALSE, &g.brush( QColorGroup::Button ) );
790 p->setBrushOrigin(bo); 787 p->setBrushOrigin(bo);
791 drawRiffles( p, sliderR.x(), sliderR.y(), 788 drawRiffles( p, sliderR.x(), sliderR.y(),
792 sliderR.width(), sliderR.height(), g, HORIZONTAL ); 789 sliderR.width(), sliderR.height(), g, HORIZONTAL );
793 } 790 }
794 791
795 // ### perhaps this should not be able to accept focus if maxedOut? 792 // ### perhaps this should not be able to accept focus if maxedOut?
796 if ( sb->hasFocus() && (controls & Slider) ) 793 if ( sb->hasFocus() && (controls & Slider) )
797 p->drawWinFocusRect( sliderR.x()+2, sliderR.y()+2, 794 p->drawWinFocusRect( sliderR.x()+2, sliderR.y()+2,
798 sliderR.width()-5, sliderR.height()-5, 795 sliderR.width()-5, sliderR.height()-5,
799 sb->backgroundColor() ); 796 sb->backgroundColor() );
800 797
801} 798}
802 799
803void QPEStyle::drawRiffles( QPainter* p, int x, int y, int w, int h, 800void QPEStyle::drawRiffles( QPainter* p, int x, int y, int w, int h,
804 const QColorGroup &g, bool horizontal ) 801 const QColorGroup &g, bool horizontal )
805{ 802{
806 if (!horizontal) { 803 if (!horizontal) {
807 if (h > 20) { 804 if (h > 20) {
808 y += (h-20)/2 ; 805 y += (h-20)/2 ;
809 h = 20; 806 h = 20;
810 } 807 }
811 if (h > 12) { 808 if (h > 12) {
812 int n = 3; 809 int n = 3;
813 int my = y+h/2-4; 810 int my = y+h/2-4;
814 int i ; 811 int i ;
815 p->setPen(g.light()); 812 p->setPen(g.light());
816 for (i=0; i<n; i++) { 813 for (i=0; i<n; i++) {
817 p->drawLine(x+2, my+3*i, x+w-4, my+3*i); 814 p->drawLine(x+2, my+3*i, x+w-4, my+3*i);
818 } 815 }
819 p->setPen(g.dark()); 816 p->setPen(g.dark());
820 my++; 817 my++;
821 for (i=0; i<n; i++) { 818 for (i=0; i<n; i++) {
822 p->drawLine(x+2, my+3*i, x+w-4, my+3*i); 819 p->drawLine(x+2, my+3*i, x+w-4, my+3*i);
823 } 820 }
824 } 821 }
825 } 822 }
826 else { 823 else {
827 if (w > 20) { 824 if (w > 20) {
828 x += (w-20)/2 ; 825 x += (w-20)/2 ;
829 w = 20; 826 w = 20;
830 } 827 }
831 if (w > 12) { 828 if (w > 12) {
832 int n = 3; 829 int n = 3;
833 int mx = x+w/2-4; 830 int mx = x+w/2-4;
834 int i ; 831 int i ;
835 p->setPen(g.light()); 832 p->setPen(g.light());
836 for (i=0; i<n; i++) { 833 for (i=0; i<n; i++) {
837 p->drawLine(mx+3*i, y+2, mx + 3*i, y+h-4); 834 p->drawLine(mx+3*i, y+2, mx + 3*i, y+h-4);
838 } 835 }
839 p->setPen(g.dark()); 836 p->setPen(g.dark());
840 mx++; 837 mx++;
841 for (i=0; i<n; i++) { 838 for (i=0; i<n; i++) {
842 p->drawLine(mx+3*i, y+2, mx + 3*i, y+h-4); 839 p->drawLine(mx+3*i, y+2, mx + 3*i, y+h-4);
843 } 840 }
844 } 841 }
845 } 842 }
846} 843}
847 844
848int QPEStyle::sliderLength() const 845int QPEStyle::sliderLength() const
849{ 846{
850 return 12; 847 return 12;
851} 848}
852 849
853void QPEStyle::drawSlider( QPainter *p, int x, int y, int w, int h, 850void QPEStyle::drawSlider( QPainter *p, int x, int y, int w, int h,
854 const QColorGroup &g, Orientation o, bool tickAbove, bool tickBelow ) 851 const QColorGroup &g, Orientation o, bool tickAbove, bool tickBelow )
855{ 852{
856 int a = tickAbove ? 3 : 0; 853 int a = tickAbove ? 3 : 0;
857 int b = tickBelow ? 3 : 0; 854 int b = tickBelow ? 3 : 0;
858 855
859 if ( o == Horizontal ) { 856 if ( o == Horizontal ) {
860 drawBevelButton( p, x, y+a, w, h-a-b, g, FALSE, &g.brush( QColorGroup::Button ) ); 857 drawBevelButton( p, x, y+a, w, h-a-b, g, FALSE, &g.brush( QColorGroup::Button ) );
861 int xp = x + w/2; 858 int xp = x + w/2;
862 qDrawShadeLine( p, xp, y+a+2, xp, y+h-b-3, g ); 859 qDrawShadeLine( p, xp, y+a+2, xp, y+h-b-3, g );
863 } else { 860 } else {
864 drawBevelButton( p, x+a, y, w-a-b, h, g, FALSE, &g.brush( QColorGroup::Button ) ); 861 drawBevelButton( p, x+a, y, w-a-b, h, g, FALSE, &g.brush( QColorGroup::Button ) );
865 int yp = y + h/2; 862 int yp = y + h/2;
866 qDrawShadeLine( p, x+a+2, yp, x+w-b-3, yp, g ); 863 qDrawShadeLine( p, x+a+2, yp, x+w-b-3, yp, g );
867 } 864 }
868} 865}
869 866
870void QPEStyle::drawSliderMask ( QPainter * p, int x, int y, int w, int h, 867void QPEStyle::drawSliderMask ( QPainter * p, int x, int y, int w, int h,
871 Orientation o, bool tickAbove, bool tickBelow ) 868 Orientation o, bool tickAbove, bool tickBelow )
872{ 869{
873 int a = tickAbove ? 3 : 0; 870 int a = tickAbove ? 3 : 0;
874 int b = tickBelow ? 3 : 0; 871 int b = tickBelow ? 3 : 0;
875 if ( o == Horizontal ) 872 if ( o == Horizontal )
876 p->fillRect( x, y+a, w, h-a-b, color1 ); 873 p->fillRect( x, y+a, w, h-a-b, color1 );
877 else 874 else
878 p->fillRect( x+a, y, w-a-b, h, color1 ); 875 p->fillRect( x+a, y, w-a-b, h, color1 );
879} 876}
880 877
881/*!\reimp 878/*!\reimp
882 */ 879 */
883void QPEStyle::drawSliderGrooveMask( QPainter *p, 880void QPEStyle::drawSliderGrooveMask( QPainter *p,
884 int x, int y, int w, int h, 881 int x, int y, int w, int h,
885 const QColorGroup& , QCOORD c, 882 const QColorGroup& , QCOORD c,
886 Orientation orient ) 883 Orientation orient )
887{ 884{
888 if ( orient == Horizontal ) 885 if ( orient == Horizontal )
889 p->fillRect( x, y + c - 2, w, 4, color1 ); 886 p->fillRect( x, y + c - 2, w, 4, color1 );
890 else 887 else
891 p->fillRect( x + c - 2, y, 4, h, color1 ); 888 p->fillRect( x + c - 2, y, 4, h, color1 );
892} 889}
893 890
894void QPEStyle::drawTab( QPainter *p, const QTabBar *tb, QTab *t, bool selected ) 891void QPEStyle::drawTab( QPainter *p, const QTabBar *tb, QTab *t, bool selected )
895{ 892{
896 QRect r( t->rect() ); 893 QRect r( t->rect() );
897 if ( tb->shape() == QTabBar::RoundedAbove ) { 894 if ( tb->shape() == QTabBar::RoundedAbove ) {
898 p->setPen( tb->colorGroup().light() ); 895 p->setPen( tb->colorGroup().light() );
899 p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() ); 896 p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() );
900 if ( r.left() == 0 ) 897 if ( r.left() == 0 )
901 p->drawPoint( tb->rect().bottomLeft() ); 898 p->drawPoint( tb->rect().bottomLeft() );
902 else { 899 else {
903 p->setPen( tb->colorGroup().light() ); 900 p->setPen( tb->colorGroup().light() );
904 p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() ); 901 p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() );
905 } 902 }
906 903
907 if ( selected ) { 904 if ( selected ) {
908 p->setPen( tb->colorGroup().background() ); 905 p->setPen( tb->colorGroup().background() );
909 p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 ); 906 p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 );
910 p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-2), 907 p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-2),
911 tb->colorGroup().brush( QColorGroup::Background )); 908 tb->colorGroup().brush( QColorGroup::Background ));
912 } else { 909 } else {
913 r.setRect( r.left() + 2, r.top() + 2, 910 r.setRect( r.left() + 2, r.top() + 2,
914 r.width() - 4, r.height() - 2 ); 911 r.width() - 4, r.height() - 2 );
915 p->setPen( tb->colorGroup().button() ); 912 p->setPen( tb->colorGroup().button() );
916 p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 ); 913 p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 );
917 p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-3), 914 p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-3),
918 tb->colorGroup().brush( QColorGroup::Button )); 915 tb->colorGroup().brush( QColorGroup::Button ));
919 916
920 //do shading; will not work for pixmap brushes 917 //do shading; will not work for pixmap brushes
921 QColor bg = tb->colorGroup().button(); 918 QColor bg = tb->colorGroup().button();
922 // int h,s,v; 919 // int h,s,v;
923 // bg.hsv( &h, &s, &v ); 920 // bg.hsv( &h, &s, &v );
924 int n = r.height()/2; 921 int n = r.height()/2;
925 int dark = 100; 922 int dark = 100;
926 for ( int i = 1; i < n; i++ ) { 923 for ( int i = 1; i < n; i++ ) {
927 dark = (dark * (100+(i*15)/n) )/100; 924 dark = (dark * (100+(i*15)/n) )/100;
928 p->setPen( bg.dark( dark ) ); 925 p->setPen( bg.dark( dark ) );
929 int y = r.bottom()-n+i; 926 int y = r.bottom()-n+i;
930 int x1 = r.left()+1; 927 int x1 = r.left()+1;
931 int x2 = r.right()-1; 928 int x2 = r.right()-1;
932 p->drawLine( x1, y, x2, y ); 929 p->drawLine( x1, y, x2, y );
933 } 930 }
934 } 931 }
935 932
936 p->setPen( tb->colorGroup().light() ); 933 p->setPen( tb->colorGroup().light() );
937 p->drawLine( r.left(), r.bottom()-1, r.left(), r.top() + 2 ); 934 p->drawLine( r.left(), r.bottom()-1, r.left(), r.top() + 2 );
938 p->drawPoint( r.left()+1, r.top() + 1 ); 935 p->drawPoint( r.left()+1, r.top() + 1 );
939 p->drawLine( r.left()+2, r.top(), 936 p->drawLine( r.left()+2, r.top(),
940 r.right() - 2, r.top() ); 937 r.right() - 2, r.top() );
941 938
942 p->setPen( tb->colorGroup().dark() ); 939 p->setPen( tb->colorGroup().dark() );
943 p->drawPoint( r.right() - 1, r.top() + 1 ); 940 p->drawPoint( r.right() - 1, r.top() + 1 );
944 p->drawLine( r.right(), r.top() + 2, r.right(), r.bottom() - 1); 941 p->drawLine( r.right(), r.top() + 2, r.right(), r.bottom() - 1);
945 } else if ( tb->shape() == QTabBar::RoundedBelow ) { 942 } else if ( tb->shape() == QTabBar::RoundedBelow ) {
946 if ( selected ) { 943 if ( selected ) {
947 p->setPen( tb->colorGroup().background() ); 944 p->setPen( tb->colorGroup().background() );
948 p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 ); 945 p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 );
949 p->fillRect( QRect( r.left()+1, r.top(), r.width()-2, r.height()-2), 946 p->fillRect( QRect( r.left()+1, r.top(), r.width()-2, r.height()-2),
950 tb->palette().normal().brush( QColorGroup::Background )); 947 tb->palette().normal().brush( QColorGroup::Background ));
951 } else { 948 } else {
952 p->setPen( tb->colorGroup().dark() ); 949 p->setPen( tb->colorGroup().dark() );
953 p->drawLine( r.left(), r.top(), 950 p->drawLine( r.left(), r.top(),
954 r.right(), r.top() ); 951 r.right(), r.top() );
955 r.setRect( r.left() + 2, r.top(), 952 r.setRect( r.left() + 2, r.top(),
956 r.width() - 4, r.height() - 2 ); 953 r.width() - 4, r.height() - 2 );
957 p->setPen( tb->colorGroup().button() ); 954 p->setPen( tb->colorGroup().button() );
958 p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 ); 955 p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 );
959 p->fillRect( QRect( r.left()+1, r.top()+1, r.width()-2, r.height()-3), 956 p->fillRect( QRect( r.left()+1, r.top()+1, r.width()-2, r.height()-3),
960 tb->palette().normal().brush( QColorGroup::Button )); 957 tb->palette().normal().brush( QColorGroup::Button ));
961 } 958 }
962 959
963 p->setPen( tb->colorGroup().dark() ); 960 p->setPen( tb->colorGroup().dark() );
964 p->drawLine( r.right(), r.top(), 961 p->drawLine( r.right(), r.top(),
965 r.right(), r.bottom() - 2 ); 962 r.right(), r.bottom() - 2 );
966 p->drawPoint( r.right() - 1, r.bottom() - 1 ); 963 p->drawPoint( r.right() - 1, r.bottom() - 1 );
967 p->drawLine( r.right() - 2, r.bottom(), 964 p->drawLine( r.right() - 2, r.bottom(),
968 r.left() + 2, r.bottom() ); 965 r.left() + 2, r.bottom() );
969 966
970 p->setPen( tb->colorGroup().light() ); 967 p->setPen( tb->colorGroup().light() );
971 p->drawLine( r.left(), r.top()+1, 968 p->drawLine( r.left(), r.top()+1,
972 r.left(), r.bottom() - 2 ); 969 r.left(), r.bottom() - 2 );
973 p->drawPoint( r.left() + 1, r.bottom() - 1 ); 970 p->drawPoint( r.left() + 1, r.bottom() - 1 );
974 if ( r.left() == 0 ) 971 if ( r.left() == 0 )
975 p->drawPoint( tb->rect().topLeft() ); 972 p->drawPoint( tb->rect().topLeft() );
976 973
977 } else { 974 } else {
978 QCommonStyle::drawTab( p, tb, t, selected ); 975 QCommonStyle::drawTab( p, tb, t, selected );
979 } 976 }
980} 977}
981 978
982 static const int motifItemFrame = 0;// menu item frame width 979 static const int motifItemFrame = 0;// menu item frame width
983 static const int motifSepHeight = 2;// separator item height 980 static const int motifSepHeight = 2;// separator item height
984 static const int motifItemHMargin = 1;// menu item hor text margin 981 static const int motifItemHMargin = 1;// menu item hor text margin
985 static const int motifItemVMargin = 2;// menu item ver text margin 982 static const int motifItemVMargin = 2;// menu item ver text margin
986 static const int motifArrowHMargin = 0;// arrow horizontal margin 983 static const int motifArrowHMargin = 0;// arrow horizontal margin
987 static const int motifTabSpacing = 12;// space between text and tab 984 static const int motifTabSpacing = 12;// space between text and tab
988 static const int motifCheckMarkHMargin = 1;// horiz. margins of check mark 985 static const int motifCheckMarkHMargin = 1;// horiz. margins of check mark
989 static const int windowsRightBorder= 8; // right border on windows 986 static const int windowsRightBorder= 8; // right border on windows
990static const int windowsCheckMarkWidth = 2; // checkmarks width on windows 987static const int windowsCheckMarkWidth = 2; // checkmarks width on windows
991 988
992/*! \reimp 989/*! \reimp
993*/ 990*/
994int QPEStyle::extraPopupMenuItemWidth( bool checkable, int maxpmw, QMenuItem* mi, const QFontMetrics& /*fm*/ ) 991int QPEStyle::extraPopupMenuItemWidth( bool checkable, int maxpmw, QMenuItem* mi, const QFontMetrics& /*fm*/ )
995{ 992{
996#ifndef QT_NO_MENUDATA 993#ifndef QT_NO_MENUDATA
997 int w = 2*motifItemHMargin + 2*motifItemFrame; // a little bit of border can never harm 994 int w = 2*motifItemHMargin + 2*motifItemFrame; // a little bit of border can never harm
998 995
999 if ( mi->isSeparator() ) 996 if ( mi->isSeparator() )
1000 return 10; // arbitrary 997 return 10; // arbitrary
1001 else if ( mi->pixmap() ) 998 else if ( mi->pixmap() )
1002 w += mi->pixmap()->width();// pixmap only 999 w += mi->pixmap()->width();// pixmap only
1003 1000
1004 if ( !mi->text().isNull() ) { 1001 if ( !mi->text().isNull() ) {
1005 if ( mi->text().find('\t') >= 0 )// string contains tab 1002 if ( mi->text().find('\t') >= 0 )// string contains tab
1006 w += motifTabSpacing; 1003 w += motifTabSpacing;
1007 } 1004 }
1008 1005
1009 if ( maxpmw ) { // we have iconsets 1006 if ( maxpmw ) { // we have iconsets
1010 w += maxpmw; 1007 w += maxpmw;
1011 w += 6; // add a little extra border around the iconset 1008 w += 6; // add a little extra border around the iconset
1012 } 1009 }
1013 1010
1014 if ( checkable && maxpmw < windowsCheckMarkWidth ) { 1011 if ( checkable && maxpmw < windowsCheckMarkWidth ) {
1015 w += windowsCheckMarkWidth - maxpmw; // space for the checkmarks 1012 w += windowsCheckMarkWidth - maxpmw; // space for the checkmarks
1016 } 1013 }
1017 1014
1018 if ( maxpmw > 0 || checkable ) // we have a check-column ( iconsets or checkmarks) 1015 if ( maxpmw > 0 || checkable ) // we have a check-column ( iconsets or checkmarks)
1019 w += motifCheckMarkHMargin; // add space to separate the columns 1016 w += motifCheckMarkHMargin; // add space to separate the columns
1020 1017
1021 w += windowsRightBorder; // windows has a strange wide border on the right side 1018 w += windowsRightBorder; // windows has a strange wide border on the right side
1022 1019
1023 return w; 1020 return w;
1024#endif 1021#endif
1025} 1022}
1026 1023
1027/*! \reimp 1024/*! \reimp
1028*/ 1025*/
1029int QPEStyle::popupMenuItemHeight( bool /*checkable*/, QMenuItem* mi, const QFontMetrics& fm ) 1026int QPEStyle::popupMenuItemHeight( bool /*checkable*/, QMenuItem* mi, const QFontMetrics& fm )
1030{ 1027{
1031#ifndef QT_NO_MENUDATA 1028#ifndef QT_NO_MENUDATA
1032 int h = 0; 1029 int h = 0;
1033 if ( mi->isSeparator() ) // separator height 1030 if ( mi->isSeparator() ) // separator height
1034 h = motifSepHeight; 1031 h = motifSepHeight;
1035 else if ( mi->pixmap() ) // pixmap height 1032 else if ( mi->pixmap() ) // pixmap height
1036 h = mi->pixmap()->height() + 2*motifItemFrame; 1033 h = mi->pixmap()->height() + 2*motifItemFrame;
1037 else // text height 1034 else // text height
1038 h = fm.height() + 2*motifItemVMargin + 2*motifItemFrame - 1; 1035 h = fm.height() + 2*motifItemVMargin + 2*motifItemFrame - 1;
1039 1036
1040 if ( !mi->isSeparator() && mi->iconSet() != 0 ) { 1037 if ( !mi->isSeparator() && mi->iconSet() != 0 ) {
1041 h = QMAX( h, mi->iconSet()->pixmap( QIconSet::Small, QIconSet::Normal ).height() + 2*motifItemFrame ); 1038 h = QMAX( h, mi->iconSet()->pixmap( QIconSet::Small, QIconSet::Normal ).height() + 2*motifItemFrame );
1042 } 1039 }
1043 if ( mi->custom() ) 1040 if ( mi->custom() )
1044 h = QMAX( h, mi->custom()->sizeHint().height() + 2*motifItemVMargin + 2*motifItemFrame ) - 1; 1041 h = QMAX( h, mi->custom()->sizeHint().height() + 2*motifItemVMargin + 2*motifItemFrame ) - 1;
1045 return h; 1042 return h;
1046#endif 1043#endif
1047} 1044}
1048 1045
1049void QPEStyle::drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, int tab, QMenuItem* mi, 1046void QPEStyle::drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, int tab, QMenuItem* mi,
1050 const QPalette& pal, 1047 const QPalette& pal,
1051 bool act, bool enabled, int x, int y, int w, int h) 1048 bool act, bool enabled, int x, int y, int w, int h)
1052{ 1049{
1053#ifndef QT_NO_MENUDATA 1050#ifndef QT_NO_MENUDATA
1054 const QColorGroup & g = pal.active(); 1051 const QColorGroup & g = pal.active();
1055 bool dis = !enabled; 1052 bool dis = !enabled;
1056 QColorGroup itemg = dis ? pal.disabled() : pal.active(); 1053 QColorGroup itemg = dis ? pal.disabled() : pal.active();
1057 1054
1058 if ( checkable ) 1055 if ( checkable )
1059 maxpmw = QMAX( maxpmw, 8 ); // space for the checkmarks 1056 maxpmw = QMAX( maxpmw, 8 ); // space for the checkmarks
1060 1057
1061 int checkcol = maxpmw; 1058 int checkcol = maxpmw;
1062 1059
1063 if ( mi && mi->isSeparator() ) { // draw separator 1060 if ( mi && mi->isSeparator() ) { // draw separator
1064 p->setPen( g.dark() ); 1061 p->setPen( g.dark() );
1065 p->drawLine( x, y, x+w, y ); 1062 p->drawLine( x, y, x+w, y );
1066 p->setPen( g.light() ); 1063 p->setPen( g.light() );
1067 p->drawLine( x, y+1, x+w, y+1 ); 1064 p->drawLine( x, y+1, x+w, y+1 );
1068 return; 1065 return;
1069 } 1066 }
1070 1067
1071 QBrush fill = act? g.brush( QColorGroup::Highlight ) : 1068 QBrush fill = act? g.brush( QColorGroup::Highlight ) :
1072 g.brush( QColorGroup::Button ); 1069 g.brush( QColorGroup::Button );
1073 p->fillRect( x, y, w, h, fill); 1070 p->fillRect( x, y, w, h, fill);
1074 1071
1075 if ( !mi ) 1072 if ( !mi )
1076 return; 1073 return;
1077 1074
1078 if ( mi->isChecked() ) { 1075 if ( mi->isChecked() ) {
1079 if ( act && !dis ) { 1076 if ( act && !dis ) {
1080 qDrawShadePanel( p, x, y, checkcol, h, 1077 qDrawShadePanel( p, x, y, checkcol, h,
1081 g, TRUE, 1, &g.brush( QColorGroup::Button ) ); 1078 g, TRUE, 1, &g.brush( QColorGroup::Button ) );
1082 } else { 1079 } else {
1083 qDrawShadePanel( p, x, y, checkcol, h, 1080 qDrawShadePanel( p, x, y, checkcol, h,
1084 g, TRUE, 1, &g.brush( QColorGroup::Midlight ) ); 1081 g, TRUE, 1, &g.brush( QColorGroup::Midlight ) );
1085 } 1082 }
1086 } else if ( !act ) { 1083 } else if ( !act ) {
1087 p->fillRect(x, y, checkcol , h, 1084 p->fillRect(x, y, checkcol , h,
1088 g.brush( QColorGroup::Button )); 1085 g.brush( QColorGroup::Button ));
1089 } 1086 }
1090 1087
1091 if ( mi->iconSet() ) { // draw iconset 1088 if ( mi->iconSet() ) { // draw iconset
1092 QIconSet::Mode mode = dis ? QIconSet::Disabled : QIconSet::Normal; 1089 QIconSet::Mode mode = dis ? QIconSet::Disabled : QIconSet::Normal;
1093 if (act && !dis ) 1090 if (act && !dis )
1094 mode = QIconSet::Active; 1091 mode = QIconSet::Active;
1095 QPixmap pixmap = mi->iconSet()->pixmap( QIconSet::Small, mode ); 1092 QPixmap pixmap = mi->iconSet()->pixmap( QIconSet::Small, mode );
1096 int pixw = pixmap.width(); 1093 int pixw = pixmap.width();
1097 int pixh = pixmap.height(); 1094 int pixh = pixmap.height();
1098 if ( act && !dis ) { 1095 if ( act && !dis ) {
1099 if ( !mi->isChecked() ) 1096 if ( !mi->isChecked() )
1100 qDrawShadePanel( p, x, y, checkcol, h, g, FALSE, 1, &g.brush( QColorGroup::Button ) ); 1097 qDrawShadePanel( p, x, y, checkcol, h, g, FALSE, 1, &g.brush( QColorGroup::Button ) );
1101 } 1098 }
1102 QRect cr( x, y, checkcol, h ); 1099 QRect cr( x, y, checkcol, h );
1103 QRect pmr( 0, 0, pixw, pixh ); 1100 QRect pmr( 0, 0, pixw, pixh );
1104 pmr.moveCenter( cr.center() ); 1101 pmr.moveCenter( cr.center() );
1105 p->setPen( itemg.text() ); 1102 p->setPen( itemg.text() );
1106 p->drawPixmap( pmr.topLeft(), pixmap ); 1103 p->drawPixmap( pmr.topLeft(), pixmap );
1107 1104
1108 QBrush fill = act? g.brush( QColorGroup::Highlight ) : 1105 QBrush fill = act? g.brush( QColorGroup::Highlight ) :
1109 g.brush( QColorGroup::Button ); 1106 g.brush( QColorGroup::Button );
1110 p->fillRect( x+checkcol + 1, y, w - checkcol - 1, h, fill); 1107 p->fillRect( x+checkcol + 1, y, w - checkcol - 1, h, fill);
1111 } else if ( checkable ) {// just "checking"... 1108 } else if ( checkable ) {// just "checking"...
1112 int mw = checkcol + motifItemFrame; 1109 int mw = checkcol + motifItemFrame;
1113 int mh = h - 2*motifItemFrame; 1110 int mh = h - 2*motifItemFrame;
1114 if ( mi->isChecked() ) { 1111 if ( mi->isChecked() ) {
1115 drawCheckMark( p, x + motifItemFrame + 2, 1112 drawCheckMark( p, x + motifItemFrame + 2,
1116 y+motifItemFrame, mw, mh, itemg, act, dis ); 1113 y+motifItemFrame, mw, mh, itemg, act, dis );
1117 } 1114 }
1118 } 1115 }
1119 1116
1120 p->setPen( act ? g.highlightedText() : g.buttonText() ); 1117 p->setPen( act ? g.highlightedText() : g.buttonText() );
1121 1118
1122 QColor discol; 1119 QColor discol;
1123 if ( dis ) { 1120 if ( dis ) {
1124 discol = itemg.text(); 1121 discol = itemg.text();
1125 p->setPen( discol ); 1122 p->setPen( discol );
1126 } 1123 }
1127 1124
1128 int xm = motifItemFrame + checkcol + motifItemHMargin; 1125 int xm = motifItemFrame + checkcol + motifItemHMargin;
1129 1126
1130 if ( mi->custom() ) { 1127 if ( mi->custom() ) {
1131 int m = motifItemVMargin; 1128 int m = motifItemVMargin;
1132 p->save(); 1129 p->save();
1133 if ( dis && !act ) { 1130 if ( dis && !act ) {
1134 p->setPen( g.light() ); 1131 p->setPen( g.light() );
1135 mi->custom()->paint( p, itemg, act, enabled, 1132 mi->custom()->paint( p, itemg, act, enabled,
1136 x+xm+1, y+m+1, w-xm-tab+1, h-2*m ); 1133 x+xm+1, y+m+1, w-xm-tab+1, h-2*m );
1137 p->setPen( discol ); 1134 p->setPen( discol );
1138 } 1135 }
1139 mi->custom()->paint( p, itemg, act, enabled, 1136 mi->custom()->paint( p, itemg, act, enabled,
1140 x+xm, y+m, w-xm-tab+1, h-2*m ); 1137 x+xm, y+m, w-xm-tab+1, h-2*m );
1141 p->restore(); 1138 p->restore();
1142 } 1139 }
1143 QString s = mi->text(); 1140 QString s = mi->text();
1144 if ( !s.isNull() ) { // draw text 1141 if ( !s.isNull() ) { // draw text
1145 int t = s.find( '\t' ); 1142 int t = s.find( '\t' );
1146 int m = motifItemVMargin; 1143 int m = motifItemVMargin;
1147 const int text_flags = AlignVCenter|ShowPrefix | DontClip | SingleLine; 1144 const int text_flags = AlignVCenter|ShowPrefix | DontClip | SingleLine;
1148 if ( t >= 0 ) { // draw tab text 1145 if ( t >= 0 ) { // draw tab text
1149 if ( dis && !act ) { 1146 if ( dis && !act ) {
1150 p->setPen( g.light() ); 1147 p->setPen( g.light() );
1151 p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+1, 1148 p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+1,
1152 y+m+1, tab, h-2*m, text_flags, s.mid( t+1 )); 1149 y+m+1, tab, h-2*m, text_flags, s.mid( t+1 ));
1153 p->setPen( discol ); 1150 p->setPen( discol );
1154 } 1151 }
1155 p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame, 1152 p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame,
1156 y+m, tab, h-2*m, text_flags, s.mid( t+1 ) ); 1153 y+m, tab, h-2*m, text_flags, s.mid( t+1 ) );
1157 } 1154 }
1158 if ( dis && !act ) { 1155 if ( dis && !act ) {
1159 p->setPen( g.light() ); 1156 p->setPen( g.light() );
1160 p->drawText( x+xm+1, y+m+1, w-xm+1, h-2*m, text_flags, s, t ); 1157 p->drawText( x+xm+1, y+m+1, w-xm+1, h-2*m, text_flags, s, t );
1161 p->setPen( discol ); 1158 p->setPen( discol );
1162 } 1159 }
1163 p->drawText( x+xm, y+m, w-xm-tab+1, h-2*m, text_flags, s, t ); 1160 p->drawText( x+xm, y+m, w-xm-tab+1, h-2*m, text_flags, s, t );
1164 } else if ( mi->pixmap() ) { // draw pixmap 1161 } else if ( mi->pixmap() ) { // draw pixmap
1165 QPixmap *pixmap = mi->pixmap(); 1162 QPixmap *pixmap = mi->pixmap();
1166 if ( pixmap->depth() == 1 ) 1163 if ( pixmap->depth() == 1 )
1167 p->setBackgroundMode( OpaqueMode ); 1164 p->setBackgroundMode( OpaqueMode );
1168 p->drawPixmap( x+xm, y+motifItemFrame, *pixmap ); 1165 p->drawPixmap( x+xm, y+motifItemFrame, *pixmap );
1169 if ( pixmap->depth() == 1 ) 1166 if ( pixmap->depth() == 1 )
1170 p->setBackgroundMode( TransparentMode ); 1167 p->setBackgroundMode( TransparentMode );
1171 } 1168 }
1172 if ( mi->popup() ) { // draw sub menu arrow 1169 if ( mi->popup() ) { // draw sub menu arrow
1173 int dim = (h-2*motifItemFrame) / 2; 1170 int dim = (h-2*motifItemFrame) / 2;
1174 if ( act ) { 1171 if ( act ) {
1175 if ( !dis ) 1172 if ( !dis )
1176 discol = white; 1173 discol = white;
1177 QColorGroup g2( discol, g.highlight(), 1174 QColorGroup g2( discol, g.highlight(),
1178 white, white, 1175 white, white,
1179 dis ? discol : white, 1176 dis ? discol : white,
1180 discol, white ); 1177 discol, white );
1181 drawArrow( p, RightArrow, FALSE, 1178 drawArrow( p, RightArrow, FALSE,
1182 x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, 1179 x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2,
1183 dim, dim, g2, TRUE ); 1180 dim, dim, g2, TRUE );
1184 } else { 1181 } else {
1185 drawArrow( p, RightArrow, 1182 drawArrow( p, RightArrow,
1186 FALSE, 1183 FALSE,
1187 x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, 1184 x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2,
1188 dim, dim, g, mi->isEnabled() ); 1185 dim, dim, g, mi->isEnabled() );
1189 } 1186 }
1190 } 1187 }
1191#endif 1188#endif
1192} 1189}
1193 1190
1194#endif 1191#endif
diff --git a/library/qpetoolbar.cpp b/library/qpetoolbar.cpp
index 7f95eda..bd2c9b7 100644
--- a/library/qpetoolbar.cpp
+++ b/library/qpetoolbar.cpp
@@ -1,52 +1,50 @@
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 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 "qpetoolbar.h" 21#include "qpetoolbar.h"
22#include "qpemenubar.h"
23#include <qtoolbutton.h>
24 22
25/*! 23/*!
26 \class QPEToolBar qpemenubar.h 24 \class QPEToolBar qpemenubar.h
27 \brief The QPEToolBar class is obsolete. Use QToolBar instead. 25 \brief The QPEToolBar class is obsolete. Use QToolBar instead.
28 26
29 \obsolete 27 \obsolete
30 28
31 The QPEToolBar class is obsolete. Use QToolBar instead. 29 The QPEToolBar class is obsolete. Use QToolBar instead.
32 30
33 \sa QToolBar 31 \sa QToolBar
34 */ 32 */
35 33
36/*! 34/*!
37 Constructs a QPEToolBar just as you would construct 35 Constructs a QPEToolBar just as you would construct
38 a QToolBar, passing \a parent and \a name. 36 a QToolBar, passing \a parent and \a name.
39 */ 37 */
40QPEToolBar::QPEToolBar( QMainWindow *parent, const char *name ) 38QPEToolBar::QPEToolBar( QMainWindow *parent, const char *name )
41 : QToolBar( parent, name ) 39 : QToolBar( parent, name )
42{ 40{
43} 41}
44 42
45/*! 43/*!
46 \internal 44 \internal
47*/ 45*/
48void QPEToolBar::childEvent( QChildEvent *e ) 46void QPEToolBar::childEvent( QChildEvent *e )
49{ 47{
50 QToolBar::childEvent( e ); 48 QToolBar::childEvent( e );
51} 49}
52 50
diff --git a/library/qt_override.cpp b/library/qt_override.cpp
index df5a419..4d1f475 100644
--- a/library/qt_override.cpp
+++ b/library/qt_override.cpp
@@ -1,177 +1,175 @@
1 1
2#include <qpe/qpeapplication.h> 2#include <qpe/qpeapplication.h>
3#include <qwsdecoration_qws.h>
4#include <qcommonstyle.h>
5#include <qfontdatabase.h> 3#include <qfontdatabase.h>
6 4
7#include <unistd.h> 5#include <unistd.h>
8#include <stdlib.h> 6#include <stdlib.h>
9#include <stdio.h> 7#include <stdio.h>
10#include <limits.h> 8#include <limits.h>
11#include <sys/param.h> // for toolchains with old libc headers 9#include <sys/param.h> // for toolchains with old libc headers
12 10
13#include "qt_override_p.h" 11#include "qt_override_p.h"
14 12
15#if QT_VERSION > 233 13#if QT_VERSION > 233
16 14
17struct color_fix_t { 15struct color_fix_t {
18 char *m_app; 16 char *m_app;
19 char *m_class; 17 char *m_class;
20 char *m_name; 18 char *m_name;
21 QColorGroup::ColorRole m_set; 19 QColorGroup::ColorRole m_set;
22 QColorGroup::ColorRole m_get; 20 QColorGroup::ColorRole m_get;
23}; 21};
24 22
25#ifndef OPIE_NO_OVERRIDE_QT 23#ifndef OPIE_NO_OVERRIDE_QT
26 24
27static const color_fix_t apps_that_need_special_colors [] = { 25static const color_fix_t apps_that_need_special_colors [] = {
28 { "HancomMobileWord", "HTextEdit", 0, QColorGroup::Background, QColorGroup::Base }, 26 { "HancomMobileWord", "HTextEdit", 0, QColorGroup::Background, QColorGroup::Base },
29 { "neocal", "Display", 0, QColorGroup::Background, QColorGroup::Base }, 27 { "neocal", "Display", 0, QColorGroup::Background, QColorGroup::Base },
30 28
31 { 0, 0, 0, QColorGroup::Base, QColorGroup::Base } 29 { 0, 0, 0, QColorGroup::Base, QColorGroup::Base }
32}; 30};
33 31
34static const char * const apps_that_need_pointsizes_times_10 [] = { 32static const char * const apps_that_need_pointsizes_times_10 [] = {
35 "HancomMobileWord", 33 "HancomMobileWord",
36 "hancomsheet", 34 "hancomsheet",
37 "HancomPresenterViewer", 35 "HancomPresenterViewer",
38 36
39 0 37 0
40}; 38};
41 39
42 40
43 41
44 42
45int Opie::force_appearance = 0; 43int Opie::force_appearance = 0;
46 44
47 45
48// Return the *real* name of the binary - not just a quick guess 46// Return the *real* name of the binary - not just a quick guess
49// by looking at argv [0] (which could be anything) 47// by looking at argv [0] (which could be anything)
50 48
51static void binaryNameFree ( ) 49static void binaryNameFree ( )
52{ 50{
53 ::free ((void *) Opie::binaryName ( )); // we need to cast away the const here 51 ::free ((void *) Opie::binaryName ( )); // we need to cast away the const here
54} 52}
55 53
56const char *Opie::binaryName ( ) 54const char *Opie::binaryName ( )
57{ 55{
58 static const char *appname = 0; 56 static const char *appname = 0;
59 57
60 if ( !appname ) { 58 if ( !appname ) {
61 char dst [PATH_MAX + 1]; 59 char dst [PATH_MAX + 1];
62 int l = ::readlink ( "/proc/self/exe", dst, PATH_MAX ); 60 int l = ::readlink ( "/proc/self/exe", dst, PATH_MAX );
63 61
64 if ( l <= 0 ) 62 if ( l <= 0 )
65 l = 0; 63 l = 0;
66 64
67 dst [l] = 0; 65 dst [l] = 0;
68 const char *b = ::strrchr ( dst, '/' ); 66 const char *b = ::strrchr ( dst, '/' );
69 appname = ::strdup ( b ? b + 1 : dst ); 67 appname = ::strdup ( b ? b + 1 : dst );
70 68
71 ::atexit ( binaryNameFree ); 69 ::atexit ( binaryNameFree );
72 } 70 }
73 return appname; 71 return appname;
74} 72}
75 73
76#else 74#else
77int Opie::force_appearance = 0; 75int Opie::force_appearance = 0;
78#endif 76#endif
79 77
80// Fix for a toolchain incompatibility (binaries compiled with 78// Fix for a toolchain incompatibility (binaries compiled with
81// old tcs using shared libs compiled with newer tcs) 79// old tcs using shared libs compiled with newer tcs)
82 80
83extern "C" { 81extern "C" {
84 82
85extern void __gmon_start__ ( ) __attribute__(( weak )); 83extern void __gmon_start__ ( ) __attribute__(( weak ));
86 84
87extern void __gmon_start__ ( ) 85extern void __gmon_start__ ( )
88{ 86{
89} 87}
90 88
91} 89}
92 90
93 91
94// Fix for apps, that use QPainter::eraseRect() which doesn't work with styles 92// Fix for apps, that use QPainter::eraseRect() which doesn't work with styles
95// that set a background pixmap (it would be easier to fix eraseRect(), but 93// that set a background pixmap (it would be easier to fix eraseRect(), but
96// TT made it an inline ...) 94// TT made it an inline ...)
97 95
98void QPEApplication::polish ( QWidget *w ) 96void QPEApplication::polish ( QWidget *w )
99{ 97{
100#ifndef OPIE_NO_OVERRIDE_QT 98#ifndef OPIE_NO_OVERRIDE_QT
101 //qDebug ( "QPEApplication::polish()" ); 99 //qDebug ( "QPEApplication::polish()" );
102 100
103 for ( const color_fix_t *ptr = apps_that_need_special_colors; ptr-> m_app; ptr++ ) { 101 for ( const color_fix_t *ptr = apps_that_need_special_colors; ptr-> m_app; ptr++ ) {
104 if (( ::strcmp ( Opie::binaryName ( ), ptr-> m_app ) == 0 ) && 102 if (( ::strcmp ( Opie::binaryName ( ), ptr-> m_app ) == 0 ) &&
105 ( ptr-> m_class ? w-> inherits ( ptr-> m_class ) : true ) && 103 ( ptr-> m_class ? w-> inherits ( ptr-> m_class ) : true ) &&
106 ( ptr-> m_name ? ( ::strcmp ( w-> name ( ), ptr-> m_name ) == 0 ) : true )) { 104 ( ptr-> m_name ? ( ::strcmp ( w-> name ( ), ptr-> m_name ) == 0 ) : true )) {
107 QPalette pal = w-> palette ( ); 105 QPalette pal = w-> palette ( );
108 pal. setColor ( ptr-> m_set, pal. color ( QPalette::Active, ptr-> m_get )); 106 pal. setColor ( ptr-> m_set, pal. color ( QPalette::Active, ptr-> m_get ));
109 w-> setPalette ( pal ); 107 w-> setPalette ( pal );
110 } 108 }
111 } 109 }
112#endif 110#endif
113 QApplication::polish ( w ); 111 QApplication::polish ( w );
114} 112}
115 113
116 114
117#ifndef OPIE_NO_OVERRIDE_QT 115#ifndef OPIE_NO_OVERRIDE_QT
118// Fix for the binary incompatibility that TT introduced in Qt/E 2.3.4 -- point sizes 116// Fix for the binary incompatibility that TT introduced in Qt/E 2.3.4 -- point sizes
119// were multiplied by 10 (which was incorrect) 117// were multiplied by 10 (which was incorrect)
120 118
121QValueList <int> QFontDatabase::pointSizes ( QString const &family, QString const &style, QString const &charset ) 119QValueList <int> QFontDatabase::pointSizes ( QString const &family, QString const &style, QString const &charset )
122{ 120{
123 //qDebug ( "QFontDatabase::pointSizes()" ); 121 //qDebug ( "QFontDatabase::pointSizes()" );
124 122
125 QValueList <int> sl = pointSizes_NonWeak ( family, style, charset ); 123 QValueList <int> sl = pointSizes_NonWeak ( family, style, charset );
126 124
127 for ( const char * const *ptr = apps_that_need_pointsizes_times_10; *ptr; ptr++ ) { 125 for ( const char * const *ptr = apps_that_need_pointsizes_times_10; *ptr; ptr++ ) {
128 if ( ::strcmp ( Opie::binaryName ( ), *ptr ) == 0 ) { 126 if ( ::strcmp ( Opie::binaryName ( ), *ptr ) == 0 ) {
129 for ( QValueList <int>::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) 127 for ( QValueList <int>::Iterator it = sl. begin ( ); it != sl. end ( ); ++it )
130 *it *= 10; 128 *it *= 10;
131 } 129 }
132 } 130 }
133 return sl; 131 return sl;
134} 132}
135 133
136 134
137// Various style/font/color related overrides for weak symbols in Qt/E, 135// Various style/font/color related overrides for weak symbols in Qt/E,
138// which allows us to force the usage of the global Opie appearance. 136// which allows us to force the usage of the global Opie appearance.
139 137
140void QApplication::setStyle ( QStyle *style ) 138void QApplication::setStyle ( QStyle *style )
141{ 139{
142 //qDebug ( "QApplication::setStyle()" ); 140 //qDebug ( "QApplication::setStyle()" );
143 141
144 if ( Opie::force_appearance & Opie::Force_Style ) 142 if ( Opie::force_appearance & Opie::Force_Style )
145 delete style; 143 delete style;
146 else 144 else
147 QApplication::setStyle_NonWeak ( style ); 145 QApplication::setStyle_NonWeak ( style );
148} 146}
149 147
150void QApplication::setPalette ( const QPalette &pal, bool informWidgets, const char *className ) 148void QApplication::setPalette ( const QPalette &pal, bool informWidgets, const char *className )
151{ 149{
152 //qDebug ( "QApplication::setPalette()" ); 150 //qDebug ( "QApplication::setPalette()" );
153 151
154 if (!( Opie::force_appearance & Opie::Force_Style )) 152 if (!( Opie::force_appearance & Opie::Force_Style ))
155 QApplication::setPalette_NonWeak ( pal, informWidgets, className ); 153 QApplication::setPalette_NonWeak ( pal, informWidgets, className );
156} 154}
157 155
158void QApplication::setFont ( const QFont &fnt, bool informWidgets, const char *className ) 156void QApplication::setFont ( const QFont &fnt, bool informWidgets, const char *className )
159{ 157{
160 //qDebug ( "QApplication::setFont()" ); 158 //qDebug ( "QApplication::setFont()" );
161 159
162 if (!( Opie::force_appearance & Opie::Force_Font )) 160 if (!( Opie::force_appearance & Opie::Force_Font ))
163 QApplication::setFont_NonWeak ( fnt, informWidgets, className ); 161 QApplication::setFont_NonWeak ( fnt, informWidgets, className );
164} 162}
165 163
166 164
167void QApplication::qwsSetDecoration ( QWSDecoration *deco ) 165void QApplication::qwsSetDecoration ( QWSDecoration *deco )
168{ 166{
169 //qDebug ( "QApplication::qwsSetDecoration()" ); 167 //qDebug ( "QApplication::qwsSetDecoration()" );
170 168
171 if ( Opie::force_appearance & Opie::Force_Decoration ) 169 if ( Opie::force_appearance & Opie::Force_Decoration )
172 delete deco; 170 delete deco;
173 else 171 else
174 QApplication::qwsSetDecoration_NonWeak ( deco ); 172 QApplication::qwsSetDecoration_NonWeak ( deco );
175} 173}
176#endif 174#endif
177#endif 175#endif
diff --git a/library/resource.cpp b/library/resource.cpp
index f70658d..cfa0d26 100644
--- a/library/resource.cpp
+++ b/library/resource.cpp
@@ -1,233 +1,230 @@
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_MIMEEXT 21#define QTOPIA_INTERNAL_MIMEEXT
22#include <qpe/qpeapplication.h> 22#include <qpe/qpeapplication.h>
23#include "resource.h" 23#include "resource.h"
24#include "mimetype.h" 24#include "mimetype.h"
25#include <qdir.h> 25#include <qdir.h>
26#include <qfile.h>
27#include <qregexp.h>
28#include <qpixmapcache.h> 26#include <qpixmapcache.h>
29#include <qpainter.h>
30 27
31// this namespace is just a workaround for a gcc bug 28// this namespace is just a workaround for a gcc bug
32// gcc exports inline functions in the generated file 29// gcc exports inline functions in the generated file
33// inlinepics_p.h 30// inlinepics_p.h
34 31
35namespace { 32namespace {
36#include "inlinepics_p.h" 33#include "inlinepics_p.h"
37} 34}
38 35
39static bool g_notUseSet = ::getenv("OVERWRITE_ICON_SET"); 36static bool g_notUseSet = ::getenv("OVERWRITE_ICON_SET");
40 37
41/*! 38/*!
42 \class Resource resource.h 39 \class Resource resource.h
43 \brief The Resource class provides access to named resources. 40 \brief The Resource class provides access to named resources.
44 41
45 The resources may be provided from files or other sources. 42 The resources may be provided from files or other sources.
46 43
47 The allSounds() function returns a list of all the sounds available. 44 The allSounds() function returns a list of all the sounds available.
48 A particular sound can be searched for using findSound(). 45 A particular sound can be searched for using findSound().
49 46
50 Images can be loaded with loadImage(), loadPixmap(), loadBitmap() 47 Images can be loaded with loadImage(), loadPixmap(), loadBitmap()
51 and loadIconSet(). 48 and loadIconSet().
52 49
53 \ingroup qtopiaemb 50 \ingroup qtopiaemb
54*/ 51*/
55 52
56/*! 53/*!
57 \fn Resource::Resource() 54 \fn Resource::Resource()
58 \internal 55 \internal
59*/ 56*/
60 57
61/*! 58/*!
62 Returns the QPixmap called \a pix. You should avoid including 59 Returns the QPixmap called \a pix. You should avoid including
63 any filename type extension (e.g. .png, .xpm). 60 any filename type extension (e.g. .png, .xpm).
64*/ 61*/
65QPixmap Resource::loadPixmap( const QString &pix ) 62QPixmap Resource::loadPixmap( const QString &pix )
66{ 63{
67 QPixmap pm; 64 QPixmap pm;
68 QString key="QPE_"+pix; 65 QString key="QPE_"+pix;
69 if ( !QPixmapCache::find(key,pm) ) { 66 if ( !QPixmapCache::find(key,pm) ) {
70 pm.convertFromImage(loadImage(pix)); 67 pm.convertFromImage(loadImage(pix));
71 QPixmapCache::insert(key,pm); 68 QPixmapCache::insert(key,pm);
72 } 69 }
73 return pm; 70 return pm;
74} 71}
75 72
76/*! 73/*!
77 Returns the QBitmap called \a pix. You should avoid including 74 Returns the QBitmap called \a pix. You should avoid including
78 any filename type extension (e.g. .png, .xpm). 75 any filename type extension (e.g. .png, .xpm).
79*/ 76*/
80QBitmap Resource::loadBitmap( const QString &pix ) 77QBitmap Resource::loadBitmap( const QString &pix )
81{ 78{
82 QBitmap bm; 79 QBitmap bm;
83 bm = loadPixmap(pix); 80 bm = loadPixmap(pix);
84 return bm; 81 return bm;
85} 82}
86 83
87/*! 84/*!
88 Returns the filename of a pixmap called \a pix. You should avoid including 85 Returns the filename of a pixmap called \a pix. You should avoid including
89 any filename type extension (e.g. .png, .xpm). 86 any filename type extension (e.g. .png, .xpm).
90 87
91 Normally you will use loadPixmap() rather than this function. 88 Normally you will use loadPixmap() rather than this function.
92*/ 89*/
93QString Resource::findPixmap( const QString &pix ) 90QString Resource::findPixmap( const QString &pix )
94{ 91{
95 QString picsPath = QPEApplication::qpeDir() + "pics/"; 92 QString picsPath = QPEApplication::qpeDir() + "pics/";
96 93
97 QString f; 94 QString f;
98 95
99 // Common case optimizations... 96 // Common case optimizations...
100 f = picsPath + pix + ".png"; 97 f = picsPath + pix + ".png";
101 if ( QFile( f ).exists() ) 98 if ( QFile( f ).exists() )
102 return f; 99 return f;
103 f = picsPath + pix + ".xpm"; 100 f = picsPath + pix + ".xpm";
104 if ( QFile( f ).exists() ) 101 if ( QFile( f ).exists() )
105 return f; 102 return f;
106 103
107 104
108 // All formats... 105 // All formats...
109 QStrList fileFormats = QImageIO::inputFormats(); 106 QStrList fileFormats = QImageIO::inputFormats();
110 QString ff = fileFormats.first(); 107 QString ff = fileFormats.first();
111 while ( fileFormats.current() ) { 108 while ( fileFormats.current() ) {
112 QStringList exts = MimeType("image/"+ff.lower()).extensions(); 109 QStringList exts = MimeType("image/"+ff.lower()).extensions();
113 for ( QStringList::ConstIterator it = exts.begin(); it!=exts.end(); ++it ) { 110 for ( QStringList::ConstIterator it = exts.begin(); it!=exts.end(); ++it ) {
114 QString f = picsPath + pix + "." + *it; 111 QString f = picsPath + pix + "." + *it;
115 if ( QFile(f).exists() ) 112 if ( QFile(f).exists() )
116 return f; 113 return f;
117 } 114 }
118 ff = fileFormats.next(); 115 ff = fileFormats.next();
119 } 116 }
120 117
121 // Finally, no (or existing) extension... 118 // Finally, no (or existing) extension...
122 if ( QFile( picsPath + pix ).exists() ) 119 if ( QFile( picsPath + pix ).exists() )
123 return picsPath + pix; 120 return picsPath + pix;
124 121
125 //qDebug("Cannot find pixmap: %s", pix.latin1()); 122 //qDebug("Cannot find pixmap: %s", pix.latin1());
126 return QString(); 123 return QString();
127} 124}
128 125
129/*! 126/*!
130 Returns a sound file for a sound called \a name. 127 Returns a sound file for a sound called \a name.
131 128
132 You should avoid including any filename type extension (e.g. .wav), 129 You should avoid including any filename type extension (e.g. .wav),
133 as the system will search for only those fileformats which are supported 130 as the system will search for only those fileformats which are supported
134 by the library. 131 by the library.
135 132
136 Currently, only WAV files are supported. 133 Currently, only WAV files are supported.
137*/ 134*/
138QString Resource::findSound( const QString &name ) 135QString Resource::findSound( const QString &name )
139{ 136{
140 QString picsPath = QPEApplication::qpeDir() + "sounds/"; 137 QString picsPath = QPEApplication::qpeDir() + "sounds/";
141 138
142 QString result; 139 QString result;
143 if ( QFile( (result = picsPath + name + ".wav") ).exists() ) 140 if ( QFile( (result = picsPath + name + ".wav") ).exists() )
144 return result; 141 return result;
145 142
146 return QString(); 143 return QString();
147} 144}
148 145
149/*! 146/*!
150 Returns a list of all sound names. 147 Returns a list of all sound names.
151*/ 148*/
152QStringList Resource::allSounds() 149QStringList Resource::allSounds()
153{ 150{
154 QDir resourcedir( QPEApplication::qpeDir() + "sounds/", "*.wav" ); 151 QDir resourcedir( QPEApplication::qpeDir() + "sounds/", "*.wav" );
155 QStringList entries = resourcedir.entryList(); 152 QStringList entries = resourcedir.entryList();
156 QStringList result; 153 QStringList result;
157 for (QStringList::Iterator i=entries.begin(); i != entries.end(); ++i) 154 for (QStringList::Iterator i=entries.begin(); i != entries.end(); ++i)
158 result.append((*i).replace(QRegExp("\\.wav"),"")); 155 result.append((*i).replace(QRegExp("\\.wav"),""));
159 return result; 156 return result;
160} 157}
161 158
162static QImage load_image(const QString &name) 159static QImage load_image(const QString &name)
163{ 160{
164 if (g_notUseSet ) { 161 if (g_notUseSet ) {
165 // try file 162 // try file
166 QImage img; 163 QImage img;
167 QString f = Resource::findPixmap(name); 164 QString f = Resource::findPixmap(name);
168 if ( !f.isEmpty() ) 165 if ( !f.isEmpty() )
169 img.load(f); 166 img.load(f);
170 if (img.isNull() ) 167 if (img.isNull() )
171 img = qembed_findImage(name.latin1() ); 168 img = qembed_findImage(name.latin1() );
172 return img; 169 return img;
173 } 170 }
174 else{ 171 else{
175 QImage img = qembed_findImage(name.latin1()); 172 QImage img = qembed_findImage(name.latin1());
176 173
177 if ( img.isNull() ) { 174 if ( img.isNull() ) {
178 // No inlined image, try file 175 // No inlined image, try file
179 QString f = Resource::findPixmap(name); 176 QString f = Resource::findPixmap(name);
180 if ( !f.isEmpty() ) 177 if ( !f.isEmpty() )
181 img.load(f); 178 img.load(f);
182 } 179 }
183 return img; 180 return img;
184 } 181 }
185} 182}
186 183
187/*! 184/*!
188 Returns the QImage called \a name. You should avoid including 185 Returns the QImage called \a name. You should avoid including
189 any filename type extension (e.g. .png, .xpm). 186 any filename type extension (e.g. .png, .xpm).
190*/ 187*/
191QImage Resource::loadImage( const QString &name) 188QImage Resource::loadImage( const QString &name)
192{ 189{
193 #ifndef QT_NO_DEPTH_32// have alpha-blended pixmaps 190 #ifndef QT_NO_DEPTH_32// have alpha-blended pixmaps
194 static QImage last_enabled; 191 static QImage last_enabled;
195 static QString last_enabled_name; 192 static QString last_enabled_name;
196 if ( name == last_enabled_name ) 193 if ( name == last_enabled_name )
197 return last_enabled; 194 return last_enabled;
198#endif 195#endif
199 QImage img = load_image(name); 196 QImage img = load_image(name);
200 #ifndef QT_NO_DEPTH_32// have alpha-blended pixmaps 197 #ifndef QT_NO_DEPTH_32// have alpha-blended pixmaps
201 if ( img.isNull() ) { 198 if ( img.isNull() ) {
202 // No file, try generating 199 // No file, try generating
203 if ( name[name.length()-1]=='d' && name.right(9)=="_disabled" ) { 200 if ( name[name.length()-1]=='d' && name.right(9)=="_disabled" ) {
204 last_enabled_name = name.left(name.length()-9); 201 last_enabled_name = name.left(name.length()-9);
205 last_enabled = load_image(last_enabled_name); 202 last_enabled = load_image(last_enabled_name);
206 if ( last_enabled.isNull() ) { 203 if ( last_enabled.isNull() ) {
207 last_enabled_name = QString::null; 204 last_enabled_name = QString::null;
208 } else { 205 } else {
209 img.detach(); 206 img.detach();
210 img.create( last_enabled.width(), last_enabled.height(), 32 ); 207 img.create( last_enabled.width(), last_enabled.height(), 32 );
211 for ( int y = 0; y < img.height(); y++ ) { 208 for ( int y = 0; y < img.height(); y++ ) {
212 for ( int x = 0; x < img.width(); x++ ) { 209 for ( int x = 0; x < img.width(); x++ ) {
213 QRgb p = last_enabled.pixel( x, y ); 210 QRgb p = last_enabled.pixel( x, y );
214 int a = qAlpha(p)/3; 211 int a = qAlpha(p)/3;
215 int g = qGray(qRed(p),qGreen(p),qBlue(p)); 212 int g = qGray(qRed(p),qGreen(p),qBlue(p));
216 img.setPixel( x, y, qRgba(g,g,g,a) ); 213 img.setPixel( x, y, qRgba(g,g,g,a) );
217 } 214 }
218 } 215 }
219 img.setAlphaBuffer( TRUE ); 216 img.setAlphaBuffer( TRUE );
220 } 217 }
221 } 218 }
222 } 219 }
223#endif 220#endif
224 return img; 221 return img;
225} 222}
226 223
227/*! 224/*!
228 \fn QIconSet Resource::loadIconSet( const QString &name ) 225 \fn QIconSet Resource::loadIconSet( const QString &name )
229 226
230 Returns a QIconSet for the pixmap named \a name. A disabled icon is 227 Returns a QIconSet for the pixmap named \a name. A disabled icon is
231 generated that conforms to the Qtopia look & feel. You should avoid 228 generated that conforms to the Qtopia look & feel. You should avoid
232 including any filename type extension (eg. .png, .xpm). 229 including any filename type extension (eg. .png, .xpm).
233*/ 230*/
diff --git a/library/sound.cpp b/library/sound.cpp
index 5b67995..ee2aabc 100644
--- a/library/sound.cpp
+++ b/library/sound.cpp
@@ -1,224 +1,222 @@
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 <qpe/resource.h> 21#include <qpe/resource.h>
22#include <qpe/sound.h> 22#include <qpe/sound.h>
23#include <qpe/qcopenvelope_qws.h> 23#include <qpe/qcopenvelope_qws.h>
24 24
25#include <qsound.h> 25#include <qsound.h>
26#include <qfile.h> 26#include <qfile.h>
27 27
28#include <unistd.h> 28#include <unistd.h>
29#include <fcntl.h> 29#include <fcntl.h>
30#include <sys/ioctl.h> 30#include <sys/ioctl.h>
31 31
32#ifndef QT_NO_SOUND 32#ifndef QT_NO_SOUND
33#include <sys/soundcard.h> 33#include <sys/soundcard.h>
34#endif 34#endif
35 35
36#include "config.h"
37#include <qmessagebox.h>
38#ifndef QT_NO_SOUND 36#ifndef QT_NO_SOUND
39static int WAVsoundDuration(const QString& filename) 37static int WAVsoundDuration(const QString& filename)
40{ 38{
41 // bad solution 39 // bad solution
42 40
43 // most of this is copied from qsoundqss.cpp 41 // most of this is copied from qsoundqss.cpp
44 42
45 QFile input(filename); 43 QFile input(filename);
46 if ( !input.open(IO_ReadOnly) ) 44 if ( !input.open(IO_ReadOnly) )
47 return 0; 45 return 0;
48 46
49 struct QRiffChunk { 47 struct QRiffChunk {
50 char id[4]; 48 char id[4];
51 Q_UINT32 size; 49 Q_UINT32 size;
52 char data[4/*size*/]; 50 char data[4/*size*/];
53 } chunk; 51 } chunk;
54 52
55 struct { 53 struct {
56 Q_INT16 formatTag; 54 Q_INT16 formatTag;
57 Q_INT16 channels; 55 Q_INT16 channels;
58 Q_INT32 samplesPerSec; 56 Q_INT32 samplesPerSec;
59 Q_INT32 avgBytesPerSec; 57 Q_INT32 avgBytesPerSec;
60 Q_INT16 blockAlign; 58 Q_INT16 blockAlign;
61 Q_INT16 wBitsPerSample; 59 Q_INT16 wBitsPerSample;
62 } chunkdata; 60 } chunkdata;
63 61
64 int total = 0; 62 int total = 0;
65 63
66 while(1) { 64 while(1) {
67 // Keep reading chunks... 65 // Keep reading chunks...
68 const int n = sizeof(chunk)-sizeof(chunk.data); 66 const int n = sizeof(chunk)-sizeof(chunk.data);
69 if ( input.readBlock((char*)&chunk,n) != n ) 67 if ( input.readBlock((char*)&chunk,n) != n )
70 break; 68 break;
71 if ( qstrncmp(chunk.id,"data",4) == 0 ) { 69 if ( qstrncmp(chunk.id,"data",4) == 0 ) {
72 total += chunkdata.avgBytesPerSec ? 70 total += chunkdata.avgBytesPerSec ?
73 chunk.size * 1000 / chunkdata.avgBytesPerSec : 0; 71 chunk.size * 1000 / chunkdata.avgBytesPerSec : 0;
74//qDebug("%d bytes of PCM (%dms)", chunk.size,chunkdata.avgBytesPerSec ? chunk.size * 1000 / chunkdata.avgBytesPerSec : 0); 72//qDebug("%d bytes of PCM (%dms)", chunk.size,chunkdata.avgBytesPerSec ? chunk.size * 1000 / chunkdata.avgBytesPerSec : 0);
75 input.at(input.at()+chunk.size-4); 73 input.at(input.at()+chunk.size-4);
76 } else if ( qstrncmp(chunk.id,"RIFF",4) == 0 ) { 74 } else if ( qstrncmp(chunk.id,"RIFF",4) == 0 ) {
77 char d[4]; 75 char d[4];
78 if ( input.readBlock(d,4) != 4 ) 76 if ( input.readBlock(d,4) != 4 )
79 return 0; 77 return 0;
80 if ( qstrncmp(d,"WAVE",4) != 0 ) { 78 if ( qstrncmp(d,"WAVE",4) != 0 ) {
81 // skip 79 // skip
82//qDebug("skip %.4s RIFF chunk",d); 80//qDebug("skip %.4s RIFF chunk",d);
83 if ( chunk.size < 10000000 ) 81 if ( chunk.size < 10000000 )
84 (void)input.at(input.at()+chunk.size-4); 82 (void)input.at(input.at()+chunk.size-4);
85 } 83 }
86 } else if ( qstrncmp(chunk.id,"fmt ",4) == 0 ) { 84 } else if ( qstrncmp(chunk.id,"fmt ",4) == 0 ) {
87 if ( input.readBlock((char*)&chunkdata,sizeof(chunkdata)) != sizeof(chunkdata) ) 85 if ( input.readBlock((char*)&chunkdata,sizeof(chunkdata)) != sizeof(chunkdata) )
88 return 0; 86 return 0;
89#define WAVE_FORMAT_PCM 1 87#define WAVE_FORMAT_PCM 1
90 if ( chunkdata.formatTag != WAVE_FORMAT_PCM ) { 88 if ( chunkdata.formatTag != WAVE_FORMAT_PCM ) {
91 //qDebug("WAV file: UNSUPPORTED FORMAT %d",chunkdata.formatTag); 89 //qDebug("WAV file: UNSUPPORTED FORMAT %d",chunkdata.formatTag);
92 return 0; 90 return 0;
93 } 91 }
94 } else { 92 } else {
95//qDebug("skip %.4s chunk",chunk.id); 93//qDebug("skip %.4s chunk",chunk.id);
96 // ignored chunk 94 // ignored chunk
97 if ( chunk.size < 10000000 ) 95 if ( chunk.size < 10000000 )
98 (void)input.at(input.at()+chunk.size); 96 (void)input.at(input.at()+chunk.size);
99 } 97 }
100 } 98 }
101 99
102//qDebug("%dms",total); 100//qDebug("%dms",total);
103 return total; 101 return total;
104} 102}
105 103
106class SoundData : public QSound { 104class SoundData : public QSound {
107public: 105public:
108 SoundData ( const QString& name ) : 106 SoundData ( const QString& name ) :
109 QSound ( Resource::findSound ( name )), 107 QSound ( Resource::findSound ( name )),
110 filename ( Resource::findSound ( name )) 108 filename ( Resource::findSound ( name ))
111 { 109 {
112 loopsleft=0; 110 loopsleft=0;
113 ms = WAVsoundDuration(filename); 111 ms = WAVsoundDuration(filename);
114 } 112 }
115 113
116 void playLoop ( int loopcnt = -1 ) 114 void playLoop ( int loopcnt = -1 )
117 { 115 {
118 // needs server support 116 // needs server support
119 loopsleft = loopcnt; 117 loopsleft = loopcnt;
120 118
121 if ( ms ) 119 if ( ms )
122 startTimer ( ms > 50 ? ms-50 : 0 ); // 50 for latency 120 startTimer ( ms > 50 ? ms-50 : 0 ); // 50 for latency
123 play ( ); 121 play ( );
124 } 122 }
125 123
126 void timerEvent ( QTimerEvent *e ) 124 void timerEvent ( QTimerEvent *e )
127 { 125 {
128 if ( loopsleft >= 0 ) { 126 if ( loopsleft >= 0 ) {
129 if ( --loopsleft <= 0 ) { 127 if ( --loopsleft <= 0 ) {
130 killTimer ( e-> timerId ( )); 128 killTimer ( e-> timerId ( ));
131 loopsleft = 0; 129 loopsleft = 0;
132 return; 130 return;
133 } 131 }
134 } 132 }
135 play(); 133 play();
136 } 134 }
137 135
138 bool isFinished ( ) const 136 bool isFinished ( ) const
139 { 137 {
140 return ( loopsleft == 0 ); 138 return ( loopsleft == 0 );
141 } 139 }
142 140
143private: 141private:
144 QString filename; 142 QString filename;
145 int loopsleft; 143 int loopsleft;
146 int ms; 144 int ms;
147}; 145};
148 146
149#endif 147#endif
150 148
151/*! Opens a wave sound file \a name for playing 149/*! Opens a wave sound file \a name for playing
152 * Resource is used for finding the file 150 * Resource is used for finding the file
153 **/ 151 **/
154Sound::Sound(const QString& name) 152Sound::Sound(const QString& name)
155{ 153{
156#ifndef QT_NO_SOUND 154#ifndef QT_NO_SOUND
157 d = new SoundData(name); 155 d = new SoundData(name);
158#endif 156#endif
159} 157}
160 158
161/*! Destroys the sound */ 159/*! Destroys the sound */
162Sound::~Sound() 160Sound::~Sound()
163{ 161{
164#ifndef QT_NO_SOUND 162#ifndef QT_NO_SOUND
165 delete d; 163 delete d;
166#endif 164#endif
167} 165}
168 166
169/*! Play the sound once */ 167/*! Play the sound once */
170void Sound::play() 168void Sound::play()
171{ 169{
172#ifndef QT_NO_SOUND 170#ifndef QT_NO_SOUND
173 d->playLoop(1); 171 d->playLoop(1);
174#endif 172#endif
175} 173}
176 174
177/*! Play the sound, repeatedly until stop() is called */ 175/*! Play the sound, repeatedly until stop() is called */
178void Sound::playLoop() 176void Sound::playLoop()
179{ 177{
180#ifndef QT_NO_SOUND 178#ifndef QT_NO_SOUND
181 d->killTimers(); 179 d->killTimers();
182 d->playLoop(); 180 d->playLoop();
183#endif 181#endif
184} 182}
185 183
186/*! Do not repeat the sound after it finishes. This will end a playLoop() */ 184/*! Do not repeat the sound after it finishes. This will end a playLoop() */
187void Sound::stop() 185void Sound::stop()
188{ 186{
189#ifndef QT_NO_SOUND 187#ifndef QT_NO_SOUND
190 d->killTimers(); 188 d->killTimers();
191#endif 189#endif
192} 190}
193 191
194bool Sound::isFinished() const 192bool Sound::isFinished() const
195{ 193{
196#ifndef QT_NO_SOUND 194#ifndef QT_NO_SOUND
197 return d->isFinished(); 195 return d->isFinished();
198#else 196#else
199 return true; 197 return true;
200#endif 198#endif
201} 199}
202 200
203/*! Sounds the audible system alarm. This is used for applications such 201/*! Sounds the audible system alarm. This is used for applications such
204 as Calendar when it needs to alarm the user of an event. 202 as Calendar when it needs to alarm the user of an event.
205*/ 203*/
206void Sound::soundAlarm() 204void Sound::soundAlarm()
207{ 205{
208#ifndef QT_NO_COP 206#ifndef QT_NO_COP
209 QCopEnvelope( "QPE/TaskBar", "soundAlarm()" ); 207 QCopEnvelope( "QPE/TaskBar", "soundAlarm()" );
210#endif 208#endif
211} 209}
212 210
213 211
214/*! \class Sound 212/*! \class Sound
215 \brief The Sound class plays WAVE sound files and can invoke the audible alarm. 213 \brief The Sound class plays WAVE sound files and can invoke the audible alarm.
216 214
217 The Sound class is constructed with the .wav music file name. The Sound 215 The Sound class is constructed with the .wav music file name. The Sound
218 class retrieves the sound file from the shared Resource class. This class 216 class retrieves the sound file from the shared Resource class. This class
219 ties together QSound and the available sound resources. 217 ties together QSound and the available sound resources.
220 218
221 To sound an audible system alarm, call the static method soundAlarm() 219 To sound an audible system alarm, call the static method soundAlarm()
222 220
223 \ingroup qtopiaemb 221 \ingroup qtopiaemb
224*/ 222*/
diff --git a/library/storage.cpp b/library/storage.cpp
index d98139b..0ea465b 100644
--- a/library/storage.cpp
+++ b/library/storage.cpp
@@ -1,405 +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#include <qpe/custom.h>
25 24
26#include <qfile.h>
27#include <qtimer.h>
28#include <qcopchannel_qws.h> 25#include <qcopchannel_qws.h>
29 26
30#include <stdio.h> 27#include <stdio.h>
31 28
32#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 29#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
33#include <sys/vfs.h> 30#include <sys/vfs.h>
34#include <mntent.h> 31#include <mntent.h>
35#endif 32#endif
36 33
37#ifdef Q_OS_MACX 34#ifdef Q_OS_MACX
38# include <sys/param.h> 35# include <sys/param.h>
39# include <sys/ucred.h> 36# include <sys/ucred.h>
40# include <sys/mount.h> 37# include <sys/mount.h>
41# include <stdio.h> // For strerror() 38# include <stdio.h> // For strerror()
42# include <errno.h> 39# include <errno.h>
43#endif /* Q_OS_MACX */ 40#endif /* Q_OS_MACX */
44 41
45#include <qstringlist.h>
46 42
47// Shouldn't be here ! (eilers) 43// Shouldn't be here ! (eilers)
48// #include <sys/vfs.h> 44// #include <sys/vfs.h>
49// #include <mntent.h> 45// #include <mntent.h>
50 46
51 47
52static bool isCF(const QString& m) 48static bool isCF(const QString& m)
53{ 49{
54 50
55#ifndef Q_OS_MACX 51#ifndef Q_OS_MACX
56 FILE* f = fopen("/var/run/stab", "r"); 52 FILE* f = fopen("/var/run/stab", "r");
57 if (!f) f = fopen("/var/state/pcmcia/stab", "r"); 53 if (!f) f = fopen("/var/state/pcmcia/stab", "r");
58 if (!f) f = fopen("/var/lib/pcmcia/stab", "r"); 54 if (!f) f = fopen("/var/lib/pcmcia/stab", "r");
59 if ( f ) 55 if ( f )
60 { 56 {
61 char line[1024]; 57 char line[1024];
62 char devtype[80]; 58 char devtype[80];
63 char devname[80]; 59 char devname[80];
64 while ( fgets( line, 1024, f ) ) 60 while ( fgets( line, 1024, f ) )
65 { 61 {
66 // 0 ide ide-cs 0 hda 3 0 62 // 0 ide ide-cs 0 hda 3 0
67 if ( sscanf(line,"%*d %s %*s %*s %s", devtype, devname )==2 ) 63 if ( sscanf(line,"%*d %s %*s %*s %s", devtype, devname )==2 )
68 { 64 {
69 if ( QString(devtype) == "ide" && m.find(devname)>0 ) 65 if ( QString(devtype) == "ide" && m.find(devname)>0 )
70 { 66 {
71 fclose(f); 67 fclose(f);
72 return TRUE; 68 return TRUE;
73 } 69 }
74 } 70 }
75 } 71 }
76 fclose(f); 72 fclose(f);
77 } 73 }
78#endif /* Q_OS_MACX */ 74#endif /* Q_OS_MACX */
79 return FALSE; 75 return FALSE;
80} 76}
81 77
82/*! \class StorageInfo storage.h 78/*! \class StorageInfo storage.h
83 \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.
84 80
85 This class provides access to the mount information for the Linux 81 This class provides access to the mount information for the Linux
86 filesystem. Each mount point is represented by the FileSystem class. 82 filesystem. Each mount point is represented by the FileSystem class.
87 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
88 the update() method. Note that this will automatically be signaled 84 the update() method. Note that this will automatically be signaled
89 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.
90 86
91 \ingroup qtopiaemb 87 \ingroup qtopiaemb
92*/ 88*/
93 89
94/*! Constructor that determines the current mount points of the filesystem. 90/*! Constructor that determines the current mount points of the filesystem.
95 The standard \a parent parameters is passed on to QObject. 91 The standard \a parent parameters is passed on to QObject.
96 */ 92 */
97StorageInfo::StorageInfo( QObject *parent ) 93StorageInfo::StorageInfo( QObject *parent )
98 : QObject( parent ) 94 : QObject( parent )
99{ 95{
100 mFileSystems.setAutoDelete( TRUE ); 96 mFileSystems.setAutoDelete( TRUE );
101 channel = new QCopChannel( "QPE/Card", this ); 97 channel = new QCopChannel( "QPE/Card", this );
102 connect( channel, SIGNAL(received(const QCString &, const QByteArray &)), 98 connect( channel, SIGNAL(received(const QCString &, const QByteArray &)),
103 this, SLOT(cardMessage( const QCString &, const QByteArray &)) ); 99 this, SLOT(cardMessage( const QCString &, const QByteArray &)) );
104 update(); 100 update();
105} 101}
106 102
107/*! Returns the longest matching FileSystem that starts with the 103/*! Returns the longest matching FileSystem that starts with the
108 same prefix as \a filename as its mount point. 104 same prefix as \a filename as its mount point.
109*/ 105*/
110const FileSystem *StorageInfo::fileSystemOf( const QString &filename ) 106const FileSystem *StorageInfo::fileSystemOf( const QString &filename )
111{ 107{
112 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i) 108 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i)
113 { 109 {
114 if ( filename.startsWith( (*i)->path() ) ) 110 if ( filename.startsWith( (*i)->path() ) )
115 return (*i); 111 return (*i);
116 } 112 }
117 return 0; 113 return 0;
118} 114}
119 115
120 116
121void StorageInfo::cardMessage( const QCString& msg, const QByteArray& ) 117void StorageInfo::cardMessage( const QCString& msg, const QByteArray& )
122{ 118{
123 if ( msg == "mtabChanged()" ) 119 if ( msg == "mtabChanged()" )
124 update(); 120 update();
125} 121}
126 122
127 123
128/*! Updates the mount and free space available information for each mount 124/*! Updates the mount and free space available information for each mount
129 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
130 unmounted. 126 unmounted.
131*/ 127*/
132// cause of the lack of a d pointer we need 128// cause of the lack of a d pointer we need
133// to store informations in a config file :( 129// to store informations in a config file :(
134void StorageInfo::update() 130void StorageInfo::update()
135{ 131{
136 //qDebug("StorageInfo::updating"); 132 //qDebug("StorageInfo::updating");
137#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 133#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
138 struct mntent *me; 134 struct mntent *me;
139 FILE *mntfp = setmntent( "/etc/mtab", "r" ); 135 FILE *mntfp = setmntent( "/etc/mtab", "r" );
140 136
141 QStringList curdisks; 137 QStringList curdisks;
142 QStringList curopts; 138 QStringList curopts;
143 QStringList curfs; 139 QStringList curfs;
144 bool rebuild = FALSE; 140 bool rebuild = FALSE;
145 int n=0; 141 int n=0;
146 if ( mntfp ) 142 if ( mntfp )
147 { 143 {
148 while ( (me = getmntent( mntfp )) != 0 ) 144 while ( (me = getmntent( mntfp )) != 0 )
149 { 145 {
150 QString fs = me->mnt_fsname; 146 QString fs = me->mnt_fsname;
151 if ( fs.left(7)=="/dev/hd" || fs.left(7)=="/dev/sd" 147 if ( fs.left(7)=="/dev/hd" || fs.left(7)=="/dev/sd"
152 || fs.left(8)=="/dev/mtd" || fs.left(9) == "/dev/mmcd" 148 || fs.left(8)=="/dev/mtd" || fs.left(9) == "/dev/mmcd"
153 || fs.left( 14 ) == "/dev/mmc/part1" 149 || fs.left( 14 ) == "/dev/mmc/part1"
154 || fs.left(5)=="tmpfs" || fs.left(9)=="/dev/root" ) 150 || fs.left(5)=="tmpfs" || fs.left(9)=="/dev/root" )
155 { 151 {
156 n++; 152 n++;
157 curdisks.append(fs); 153 curdisks.append(fs);
158 curopts.append( me->mnt_opts ); 154 curopts.append( me->mnt_opts );
159 //qDebug("-->fs %s opts %s", fs.latin1(), me->mnt_opts ); 155 //qDebug("-->fs %s opts %s", fs.latin1(), me->mnt_opts );
160 curfs.append( me->mnt_dir ); 156 curfs.append( me->mnt_dir );
161 bool found = FALSE; 157 bool found = FALSE;
162 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i) 158 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i)
163 { 159 {
164 if ( (*i)->disk() == fs ) 160 if ( (*i)->disk() == fs )
165 { 161 {
166 found = TRUE; 162 found = TRUE;
167 break; 163 break;
168 } 164 }
169 } 165 }
170 if ( !found ) 166 if ( !found )
171 rebuild = TRUE; 167 rebuild = TRUE;
172 } 168 }
173 } 169 }
174 endmntent( mntfp ); 170 endmntent( mntfp );
175 } 171 }
176 if ( rebuild || n != (int)mFileSystems.count() ) 172 if ( rebuild || n != (int)mFileSystems.count() )
177 { 173 {
178 mFileSystems.clear(); 174 mFileSystems.clear();
179 QStringList::ConstIterator it=curdisks.begin(); 175 QStringList::ConstIterator it=curdisks.begin();
180 QStringList::ConstIterator fsit=curfs.begin(); 176 QStringList::ConstIterator fsit=curfs.begin();
181 QStringList::ConstIterator optsIt=curopts.begin(); 177 QStringList::ConstIterator optsIt=curopts.begin();
182 for (; it!=curdisks.end(); ++it, ++fsit, ++optsIt) 178 for (; it!=curdisks.end(); ++it, ++fsit, ++optsIt)
183 { 179 {
184 QString opts = *optsIt; 180 QString opts = *optsIt;
185 181
186 QString disk = *it; 182 QString disk = *it;
187 QString humanname; 183 QString humanname;
188 bool removable = FALSE; 184 bool removable = FALSE;
189 if ( isCF(disk) ) 185 if ( isCF(disk) )
190 { 186 {
191 humanname = tr("CF Card"); 187 humanname = tr("CF Card");
192 removable = TRUE; 188 removable = TRUE;
193 } 189 }
194 else if ( disk == "/dev/hda1" ) 190 else if ( disk == "/dev/hda1" )
195 { 191 {
196 humanname = tr("Hard Disk"); 192 humanname = tr("Hard Disk");
197 } 193 }
198 else if ( disk.left(9) == "/dev/mmcd" ) 194 else if ( disk.left(9) == "/dev/mmcd" )
199 { 195 {
200 humanname = tr("SD Card"); 196 humanname = tr("SD Card");
201 removable = TRUE; 197 removable = TRUE;
202 } 198 }
203 else if ( disk.left( 14 ) == "/dev/mmc/part1" ) 199 else if ( disk.left( 14 ) == "/dev/mmc/part1" )
204 { 200 {
205 humanname = tr("MMC Card"); 201 humanname = tr("MMC Card");
206 removable = TRUE; 202 removable = TRUE;
207 } 203 }
208 else if ( disk.left(7) == "/dev/hd" ) 204 else if ( disk.left(7) == "/dev/hd" )
209 humanname = tr("Hard Disk") + " " + disk; 205 humanname = tr("Hard Disk") + " " + disk;
210 else if ( disk.left(7) == "/dev/sd" ) 206 else if ( disk.left(7) == "/dev/sd" )
211 humanname = tr("SCSI Hard Disk") + " " + disk; 207 humanname = tr("SCSI Hard Disk") + " " + disk;
212 else if ( disk.left(14) == "/dev/mtdblock6" ) //openzaurus ramfs 208 else if ( disk.left(14) == "/dev/mtdblock6" ) //openzaurus ramfs
213 humanname = tr("Internal Memory"); 209 humanname = tr("Internal Memory");
214 else if ( disk == "/dev/mtdblock1" || humanname == "/dev/mtdblock/1" ) 210 else if ( disk == "/dev/mtdblock1" || humanname == "/dev/mtdblock/1" )
215 humanname = tr("Internal Storage"); 211 humanname = tr("Internal Storage");
216 else if ( disk.left(14) == "/dev/mtdblock/" ) 212 else if ( disk.left(14) == "/dev/mtdblock/" )
217 humanname = tr("Internal Storage") + " " + disk; 213 humanname = tr("Internal Storage") + " " + disk;
218 else if ( disk.left(13) == "/dev/mtdblock" ) 214 else if ( disk.left(13) == "/dev/mtdblock" )
219 humanname = tr("Internal Storage") + " " + disk; 215 humanname = tr("Internal Storage") + " " + disk;
220 else if ( disk.left(9) == "/dev/root" ) 216 else if ( disk.left(9) == "/dev/root" )
221 humanname = tr("Internal Storage") + " " + disk; 217 humanname = tr("Internal Storage") + " " + disk;
222 else if ( disk.left(5) == "tmpfs" ) //ipaqs /mnt/ramfs 218 else if ( disk.left(5) == "tmpfs" ) //ipaqs /mnt/ramfs
223 humanname = tr("Internal Memory"); 219 humanname = tr("Internal Memory");
224 FileSystem *fs = new FileSystem( disk, *fsit, humanname, removable, opts ); 220 FileSystem *fs = new FileSystem( disk, *fsit, humanname, removable, opts );
225 mFileSystems.append( fs ); 221 mFileSystems.append( fs );
226 } 222 }
227 emit disksChanged(); 223 emit disksChanged();
228 } 224 }
229 else 225 else
230 { 226 {
231 // just update them 227 // just update them
232 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i) 228 for (QListIterator<FileSystem> i(mFileSystems); i.current(); ++i)
233 i.current()->update(); 229 i.current()->update();
234 } 230 }
235#endif 231#endif
236} 232}
237 233
238bool deviceTab( const char *device) 234bool deviceTab( const char *device)
239{ 235{
240 QString name = device; 236 QString name = device;
241 bool hasDevice=false; 237 bool hasDevice=false;
242 238
243#ifdef Q_OS_MACX 239#ifdef Q_OS_MACX
244 // Darwin (MacOS X) 240 // Darwin (MacOS X)
245 struct statfs** mntbufp; 241 struct statfs** mntbufp;
246 int count = 0; 242 int count = 0;
247 if ( ( count = getmntinfo( mntbufp, MNT_WAIT ) ) == 0 ) 243 if ( ( count = getmntinfo( mntbufp, MNT_WAIT ) ) == 0 )
248 { 244 {
249 qWarning("deviceTab: Error in getmntinfo(): %s",strerror( errno ) ); 245 qWarning("deviceTab: Error in getmntinfo(): %s",strerror( errno ) );
250 hasDevice = false; 246 hasDevice = false;
251 } 247 }
252 for( int i = 0; i < count; i++ ) 248 for( int i = 0; i < count; i++ )
253 { 249 {
254 QString deviceName = mntbufp[i]->f_mntfromname; 250 QString deviceName = mntbufp[i]->f_mntfromname;
255 qDebug(deviceName); 251 qDebug(deviceName);
256 if( deviceName.left( name.length() ) == name ) 252 if( deviceName.left( name.length() ) == name )
257 hasDevice = true; 253 hasDevice = true;
258 } 254 }
259#else 255#else
260 // Linux 256 // Linux
261 struct mntent *me; 257 struct mntent *me;
262 FILE *mntfp = setmntent( "/etc/mtab", "r" ); 258 FILE *mntfp = setmntent( "/etc/mtab", "r" );
263 if ( mntfp ) 259 if ( mntfp )
264 { 260 {
265 while ( (me = getmntent( mntfp )) != 0 ) 261 while ( (me = getmntent( mntfp )) != 0 )
266 { 262 {
267 QString deviceName = me->mnt_fsname; 263 QString deviceName = me->mnt_fsname;
268 // qDebug(deviceName); 264 // qDebug(deviceName);
269 if( deviceName.left(name.length()) == name) 265 if( deviceName.left(name.length()) == name)
270 { 266 {
271 hasDevice = true; 267 hasDevice = true;
272 } 268 }
273 } 269 }
274 } 270 }
275 endmntent( mntfp ); 271 endmntent( mntfp );
276#endif /* Q_OS_MACX */ 272#endif /* Q_OS_MACX */
277 273
278 274
279 return hasDevice; 275 return hasDevice;
280} 276}
281 277
282/*! 278/*!
283 * @fn static bool StorageInfo::hasCf() 279 * @fn static bool StorageInfo::hasCf()
284 * @brief returns whether device has Cf mounted 280 * @brief returns whether device has Cf mounted
285 * 281 *
286 */ 282 */
287bool StorageInfo::hasCf() 283bool StorageInfo::hasCf()
288{ 284{
289 return deviceTab("/dev/hd"); 285 return deviceTab("/dev/hd");
290} 286}
291 287
292/*! 288/*!
293 * @fn static bool StorageInfo::hasSd() 289 * @fn static bool StorageInfo::hasSd()
294 * @brief returns whether device has SD mounted 290 * @brief returns whether device has SD mounted
295 * 291 *
296 */ 292 */
297bool StorageInfo::hasSd() 293bool StorageInfo::hasSd()
298{ 294{
299 return deviceTab("/dev/mmcd"); 295 return deviceTab("/dev/mmcd");
300} 296}
301 297
302/*! 298/*!
303 * @fn static bool StorageInfo::hasMmc() 299 * @fn static bool StorageInfo::hasMmc()
304 * @brief returns whether device has mmc mounted 300 * @brief returns whether device has mmc mounted
305 * 301 *
306 */ 302 */
307bool StorageInfo::hasMmc() 303bool StorageInfo::hasMmc()
308{ 304{
309 bool hasMmc=false; 305 bool hasMmc=false;
310 if( deviceTab("/dev/mmc/part")) 306 if( deviceTab("/dev/mmc/part"))
311 hasMmc=true; 307 hasMmc=true;
312 if( deviceTab("/dev/mmcd")) 308 if( deviceTab("/dev/mmcd"))
313 hasMmc=true; 309 hasMmc=true;
314 return hasMmc; 310 return hasMmc;
315} 311}
316 312
317/*! \fn const QList<FileSystem> &StorageInfo::fileSystems() const 313/*! \fn const QList<FileSystem> &StorageInfo::fileSystems() const
318 Returns a list of all available mounted file systems. 314 Returns a list of all available mounted file systems.
319 315
320 \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)
321*/ 317*/
322 318
323/*! \fn void StorageInfo::disksChanged() 319/*! \fn void StorageInfo::disksChanged()
324 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
325 a CF c 321 a CF c
326*/ 322*/
327//--------------------------------------------------------------------------- 323//---------------------------------------------------------------------------
328 324
329FileSystem::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 )
330 : 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 )
331{ 327{
332 update(); 328 update();
333} 329}
334 330
335void FileSystem::update() 331void FileSystem::update()
336{ 332{
337#if defined(_OS_LINUX_) || defined(Q_OS_LINUX) 333#if defined(_OS_LINUX_) || defined(Q_OS_LINUX)
338 struct statfs fs; 334 struct statfs fs;
339 if ( !statfs( fspath.latin1(), &fs ) ) 335 if ( !statfs( fspath.latin1(), &fs ) )
340 { 336 {
341 blkSize = fs.f_bsize; 337 blkSize = fs.f_bsize;
342 totalBlks = fs.f_blocks; 338 totalBlks = fs.f_blocks;
343 availBlks = fs.f_bavail; 339 availBlks = fs.f_bavail;
344 } 340 }
345 else 341 else
346 { 342 {
347 blkSize = 0; 343 blkSize = 0;
348 totalBlks = 0; 344 totalBlks = 0;
349 availBlks = 0; 345 availBlks = 0;
350 } 346 }
351#endif 347#endif
352} 348}
353 349
354/*! \class FileSystem storage.h 350/*! \class FileSystem storage.h
355 \brief The FileSystem class describes a single mount point. 351 \brief The FileSystem class describes a single mount point.
356 352
357 This class simply returns information about a mount point, including 353 This class simply returns information about a mount point, including
358 file system name, mount point, human readable name, size information 354 file system name, mount point, human readable name, size information
359 and mount options information. 355 and mount options information.
360 \ingroup qtopiaemb 356 \ingroup qtopiaemb
361 357
362 \sa StorageInfo 358 \sa StorageInfo
363*/ 359*/
364 360
365/*! \fn const QString &FileSystem::disk() const 361/*! \fn const QString &FileSystem::disk() const
366 Returns the file system name, such as /dev/hda3 362 Returns the file system name, such as /dev/hda3
367*/ 363*/
368 364
369/*! \fn const QString &FileSystem::path() const 365/*! \fn const QString &FileSystem::path() const
370 Returns the mount path, such as /home 366 Returns the mount path, such as /home
371*/ 367*/
372 368
373/*! \fn const QString &FileSystem::name() const 369/*! \fn const QString &FileSystem::name() const
374 Returns the translated, human readable name for the mount directory. 370 Returns the translated, human readable name for the mount directory.
375*/ 371*/
376 372
377/*! \fn const QString &FileSystem::options() const 373/*! \fn const QString &FileSystem::options() const
378 Returns the mount options 374 Returns the mount options
379*/ 375*/
380 376
381/*! \fn long FileSystem::blockSize() const 377/*! \fn long FileSystem::blockSize() const
382 Returns the size of each block on the file system. 378 Returns the size of each block on the file system.
383*/ 379*/
384 380
385/*! \fn long FileSystem::totalBlocks() const 381/*! \fn long FileSystem::totalBlocks() const
386 Returns the total number of blocks on the file system 382 Returns the total number of blocks on the file system
387*/ 383*/
388 384
389/*! \fn long FileSystem::availBlocks() const 385/*! \fn long FileSystem::availBlocks() const
390 Returns the number of available blocks on the file system 386 Returns the number of available blocks on the file system
391 */ 387 */
392 388
393/*! \fn bool FileSystem::isRemovable() const 389/*! \fn bool FileSystem::isRemovable() const
394 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
395 would be removable, but the internal memory wouldn't 391 would be removable, but the internal memory wouldn't
396*/ 392*/
397 393
398/*! \fn bool FileSystem::isWritable() const 394/*! \fn bool FileSystem::isWritable() const
399 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.
400 Returns FALSE if read-only, TRUE if read and write. 396 Returns FALSE if read-only, TRUE if read and write.
401*/ 397*/
402 398
403/*! \fn QStringList StorageInfo::fileSystemNames() const 399/*! \fn QStringList StorageInfo::fileSystemNames() const
404 Returns a list of filesystem names. 400 Returns a list of filesystem names.
405*/ 401*/
diff --git a/library/tzselect.cpp b/library/tzselect.cpp
index 4343eab..f28100b 100644
--- a/library/tzselect.cpp
+++ b/library/tzselect.cpp
@@ -1,303 +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 "global.h"
26#include "config.h" 25#include "config.h"
27#include <qtoolbutton.h> 26#include <qtoolbutton.h>
28#include <qfile.h> 27#include <qfile.h>
29#include <stdlib.h> 28#include <stdlib.h>
30 29
31#include <qcopchannel_qws.h> 30#include <qcopchannel_qws.h>
32#include <qpe/qpeapplication.h> 31#include <qpe/qpeapplication.h>
33#include <qmessagebox.h> 32#include <qmessagebox.h>
34 33
35/*! 34/*!
36 \class TimeZoneSelector 35 \class TimeZoneSelector
37 36
38 \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.
39 38
40 \ingroup qtopiaemb 39 \ingroup qtopiaemb
41*/ 40*/
42 41
43class TimeZoneSelectorPrivate 42class TimeZoneSelectorPrivate
44{ 43{
45public: 44public:
46 TimeZoneSelectorPrivate() : includeLocal(FALSE) {} 45 TimeZoneSelectorPrivate() : includeLocal(FALSE) {}
47 bool includeLocal; 46 bool includeLocal;
48}; 47};
49 48
50TZCombo::TZCombo( QWidget *p, const char* n ) 49TZCombo::TZCombo( QWidget *p, const char* n )
51 : QComboBox( p, n ) 50 : QComboBox( p, n )
52{ 51{
53 updateZones(); 52 updateZones();
54 // 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
55 QString tz = getenv("TZ"); 54 QString tz = getenv("TZ");
56 if (parent()->inherits("TimeZoneSelector")) { 55 if (parent()->inherits("TimeZoneSelector")) {
57 if ( ((TimeZoneSelector *)parent())->localIncluded() ) { 56 if ( ((TimeZoneSelector *)parent())->localIncluded() ) {
58 // overide to the 'local' type. 57 // overide to the 'local' type.
59 tz = "None"; 58 tz = "None";
60 } 59 }
61 } 60 }
62 if ( !tz.isNull() ) { 61 if ( !tz.isNull() ) {
63 int n = 0, 62 int n = 0,
64 index = 0; 63 index = 0;
65 for ( QStringList::Iterator it=identifiers.begin(); 64 for ( QStringList::Iterator it=identifiers.begin();
66 it!=identifiers.end(); ++it) { 65 it!=identifiers.end(); ++it) {
67 if ( *it == tz ) 66 if ( *it == tz )
68 index = n; 67 index = n;
69 n++; 68 n++;
70 } 69 }
71 setCurrentItem(index); 70 setCurrentItem(index);
72 } else { 71 } else {
73 setCurrentItem(0); 72 setCurrentItem(0);
74 } 73 }
75 74
76 75
77 76
78 // listen on QPE/System 77 // listen on QPE/System
79#if !defined(QT_NO_COP) 78#if !defined(QT_NO_COP)
80 QCopChannel *channel = new QCopChannel( "QPE/System", this ); 79 QCopChannel *channel = new QCopChannel( "QPE/System", this );
81 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), 80 connect( channel, SIGNAL(received(const QCString&, const QByteArray&)),
82 this, SLOT(handleSystemChannel(const QCString&, const QByteArray&)) ); 81 this, SLOT(handleSystemChannel(const QCString&, const QByteArray&)) );
83#endif 82#endif
84 83
85 84
86} 85}
87 86
88TZCombo::~TZCombo() 87TZCombo::~TZCombo()
89{ 88{
90} 89}
91 90
92void TZCombo::updateZones() 91void TZCombo::updateZones()
93{ 92{
94 QString cur = currentText(); 93 QString cur = currentText();
95 clear(); 94 clear();
96 identifiers.clear(); 95 identifiers.clear();
97 int curix=0; 96 int curix=0;
98 QString tz = getenv("TZ"); 97 QString tz = getenv("TZ");
99 bool tzFound = FALSE; 98 bool tzFound = FALSE;
100 Config cfg("CityTime"); 99 Config cfg("CityTime");
101 cfg.setGroup("TimeZones"); 100 cfg.setGroup("TimeZones");
102 int listIndex = 0; 101 int listIndex = 0;
103 if (parent()->inherits("TimeZoneSelector")) { 102 if (parent()->inherits("TimeZoneSelector")) {
104 if ( ((TimeZoneSelector *)parent())->localIncluded() ) { 103 if ( ((TimeZoneSelector *)parent())->localIncluded() ) {
105 // overide to the 'local' type. 104 // overide to the 'local' type.
106 identifiers.append( "None" ); 105 identifiers.append( "None" );
107 insertItem( tr("None") ); 106 insertItem( tr("None") );
108 if ( cur == tr("None")) 107 if ( cur == tr("None"))
109 curix = 0; 108 curix = 0;
110 listIndex++; 109 listIndex++;
111 } 110 }
112 } 111 }
113 int cfgIndex = 0; 112 int cfgIndex = 0;
114 while (1) { 113 while (1) {
115 QString zn = cfg.readEntry("Zone"+QString::number(cfgIndex), QString::null); 114 QString zn = cfg.readEntry("Zone"+QString::number(cfgIndex), QString::null);
116 if ( zn.isNull() ) 115 if ( zn.isNull() )
117 break; 116 break;
118 if ( zn == tz ) 117 if ( zn == tz )
119 tzFound = TRUE; 118 tzFound = TRUE;
120 QString nm = cfg.readEntry("ZoneName"+QString::number(cfgIndex)); 119 QString nm = cfg.readEntry("ZoneName"+QString::number(cfgIndex));
121 identifiers.append(zn); 120 identifiers.append(zn);
122 insertItem(nm); 121 insertItem(nm);
123 if ( nm == cur ) 122 if ( nm == cur )
124 curix = listIndex; 123 curix = listIndex;
125 ++cfgIndex; 124 ++cfgIndex;
126 ++listIndex; 125 ++listIndex;
127 } 126 }
128 if ( !listIndex ) { 127 if ( !listIndex ) {
129 QStringList list = timezoneDefaults(); 128 QStringList list = timezoneDefaults();
130 for ( QStringList::Iterator it = list.begin(); it!=list.end(); ++it ) { 129 for ( QStringList::Iterator it = list.begin(); it!=list.end(); ++it ) {
131 QString zn = *it; 130 QString zn = *it;
132 QString nm = *++it; 131 QString nm = *++it;
133 if ( zn == tz ) 132 if ( zn == tz )
134 tzFound = TRUE; 133 tzFound = TRUE;
135 if ( nm == cur ) 134 if ( nm == cur )
136 curix = listIndex; 135 curix = listIndex;
137 identifiers.append(zn); 136 identifiers.append(zn);
138 insertItem(nm); 137 insertItem(nm);
139 ++listIndex; 138 ++listIndex;
140 } 139 }
141 } 140 }
142 for (QStringList::Iterator it=extras.begin(); it!=extras.end(); ++it) { 141 for (QStringList::Iterator it=extras.begin(); it!=extras.end(); ++it) {
143 insertItem(*it); 142 insertItem(*it);
144 identifiers.append(*it); 143 identifiers.append(*it);
145 if ( *it == cur ) 144 if ( *it == cur )
146 curix = listIndex; 145 curix = listIndex;
147 ++listIndex; 146 ++listIndex;
148 } 147 }
149 if ( !tzFound && !tz.isEmpty()) { 148 if ( !tzFound && !tz.isEmpty()) {
150 int i = tz.find( '/' ); 149 int i = tz.find( '/' );
151 QString nm = tz.mid( i+1 ).replace(QRegExp("_"), " "); 150 QString nm = tz.mid( i+1 ).replace(QRegExp("_"), " ");
152 identifiers.append(tz); 151 identifiers.append(tz);
153 insertItem(nm); 152 insertItem(nm);
154 if ( nm == cur ) 153 if ( nm == cur )
155 curix = listIndex; 154 curix = listIndex;
156 ++listIndex; 155 ++listIndex;
157 } 156 }
158 setCurrentItem(curix); 157 setCurrentItem(curix);
159} 158}
160 159
161 160
162void TZCombo::keyPressEvent( QKeyEvent *e ) 161void TZCombo::keyPressEvent( QKeyEvent *e )
163{ 162{
164 // ### should popup() in Qt 3.0 (it's virtual there) 163 // ### should popup() in Qt 3.0 (it's virtual there)
165// updateZones(); 164// updateZones();
166 QComboBox::keyPressEvent(e); 165 QComboBox::keyPressEvent(e);
167} 166}
168 167
169void TZCombo::mousePressEvent(QMouseEvent*e) 168void TZCombo::mousePressEvent(QMouseEvent*e)
170{ 169{
171 // ### should popup() in Qt 3.0 (it's virtual there) 170 // ### should popup() in Qt 3.0 (it's virtual there)
172// updateZones(); 171// updateZones();
173 QComboBox::mousePressEvent(e); 172 QComboBox::mousePressEvent(e);
174} 173}
175 174
176QString TZCombo::currZone() const 175QString TZCombo::currZone() const
177{ 176{
178 return identifiers[currentItem()]; 177 return identifiers[currentItem()];
179} 178}
180 179
181void TZCombo::setCurrZone( const QString& id ) 180void TZCombo::setCurrZone( const QString& id )
182{ 181{
183 for (int i=0; i< count(); i++) { 182 for (int i=0; i< count(); i++) {
184 if ( identifiers[i] == id ) { 183 if ( identifiers[i] == id ) {
185 setCurrentItem(i); 184 setCurrentItem(i);
186 return; 185 return;
187} 186}
188 } 187 }
189 insertItem(id); 188 insertItem(id);
190 setCurrentItem( count() - 1); 189 setCurrentItem( count() - 1);
191 identifiers.append(id); 190 identifiers.append(id);
192 extras.append(id); 191 extras.append(id);
193} 192}
194 193
195 194
196 195
197void TZCombo::handleSystemChannel(const QCString&msg, const QByteArray&) 196void TZCombo::handleSystemChannel(const QCString&msg, const QByteArray&)
198{ 197{
199 if ( msg == "timeZoneListChange()" ) { 198 if ( msg == "timeZoneListChange()" ) {
200 updateZones(); 199 updateZones();
201 } 200 }
202} 201}
203 202
204/*! 203/*!
205 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
206 populated with the available timezones. 205 populated with the available timezones.
207*/ 206*/
208 207
209TimeZoneSelector::TimeZoneSelector(QWidget* p, const char* n) : 208TimeZoneSelector::TimeZoneSelector(QWidget* p, const char* n) :
210 QHBox(p,n) 209 QHBox(p,n)
211{ 210{
212 d = new TimeZoneSelectorPrivate(); 211 d = new TimeZoneSelectorPrivate();
213 // build the combobox before we do any updates... 212 // build the combobox before we do any updates...
214 cmbTz = new TZCombo( this, "timezone combo" ); 213 cmbTz = new TZCombo( this, "timezone combo" );
215 214
216 cmdTz = new QToolButton( this, "timezone button" ); 215 cmdTz = new QToolButton( this, "timezone button" );
217 cmdTz->setIconSet( Resource::loadIconSet( "citytime_icon" ) ); 216 cmdTz->setIconSet( Resource::loadIconSet( "citytime_icon" ) );
218 cmdTz->setMaximumSize( cmdTz->sizeHint() ); 217 cmdTz->setMaximumSize( cmdTz->sizeHint() );
219 218
220 // 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
221 // signal 220 // signal
222 QObject::connect( cmbTz, SIGNAL( activated( int ) ), 221 QObject::connect( cmbTz, SIGNAL( activated( int ) ),
223 this, SLOT( slotTzActive( int ) ) ); 222 this, SLOT( slotTzActive( int ) ) );
224 QObject::connect( cmdTz, SIGNAL( clicked() ), 223 QObject::connect( cmdTz, SIGNAL( clicked() ),
225 this, SLOT( slotExecute() ) ); 224 this, SLOT( slotExecute() ) );
226} 225}
227 226
228/*! 227/*!
229 Destroys a TimeZoneSelector. 228 Destroys a TimeZoneSelector.
230*/ 229*/
231TimeZoneSelector::~TimeZoneSelector() 230TimeZoneSelector::~TimeZoneSelector()
232{ 231{
233} 232}
234 233
235void TimeZoneSelector::setLocalIncluded(bool b) 234void TimeZoneSelector::setLocalIncluded(bool b)
236{ 235{
237 d->includeLocal = b; 236 d->includeLocal = b;
238 cmbTz->updateZones(); 237 cmbTz->updateZones();
239} 238}
240 239
241bool TimeZoneSelector::localIncluded() const 240bool TimeZoneSelector::localIncluded() const
242{ 241{
243 return d->includeLocal; 242 return d->includeLocal;
244} 243}
245 244
246/*! 245/*!
247 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.
248 \code Australia/Brisbane \endcode 247 \code Australia/Brisbane \endcode
249*/ 248*/
250QString TimeZoneSelector::currentZone() const 249QString TimeZoneSelector::currentZone() const
251{ 250{
252 return cmbTz->currZone(); 251 return cmbTz->currZone();
253} 252}
254 253
255/*! 254/*!
256 Sets the current timezone to \a id. 255 Sets the current timezone to \a id.
257*/ 256*/
258void TimeZoneSelector::setCurrentZone( const QString& id ) 257void TimeZoneSelector::setCurrentZone( const QString& id )
259{ 258{
260 cmbTz->setCurrZone( id ); 259 cmbTz->setCurrZone( id );
261} 260}
262/*! \fn void TimeZoneSelector::signalNewTz( const QString& id ) 261/*! \fn void TimeZoneSelector::signalNewTz( const QString& id )
263 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
264 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
265*/ 264*/
266 265
267 266
268void TimeZoneSelector::slotTzActive( int ) 267void TimeZoneSelector::slotTzActive( int )
269{ 268{
270 emit signalNewTz( cmbTz->currZone() ); 269 emit signalNewTz( cmbTz->currZone() );
271} 270}
272 271
273void TimeZoneSelector::slotExecute( void ) 272void TimeZoneSelector::slotExecute( void )
274{ 273{
275 // execute the world time application... 274 // execute the world time application...
276 if (QFile::exists(QPEApplication::qpeDir()+"bin/citytime")) 275 if (QFile::exists(QPEApplication::qpeDir()+"bin/citytime"))
277 Global::execute( "citytime" ); 276 Global::execute( "citytime" );
278 else 277 else
279 QMessageBox::warning(this,tr("citytime executable not found"), 278 QMessageBox::warning(this,tr("citytime executable not found"),
280 tr("In order to choose the time zones,\nplease install citytime.")); 279 tr("In order to choose the time zones,\nplease install citytime."));
281} 280}
282 281
283QStringList timezoneDefaults( void ) 282QStringList timezoneDefaults( void )
284{ 283{
285 QStringList tzs; 284 QStringList tzs;
286 // load up the list just like the file format (citytime.cpp) 285 // load up the list just like the file format (citytime.cpp)
287 tzs.append( "America/New_York" ); 286 tzs.append( "America/New_York" );
288 tzs.append( "New York" ); 287 tzs.append( "New York" );
289 tzs.append( "America/Los_Angeles" ); 288 tzs.append( "America/Los_Angeles" );
290 tzs.append( "Los Angeles" ); 289 tzs.append( "Los Angeles" );
291 tzs.append( "Australia/Brisbane" ); 290 tzs.append( "Australia/Brisbane" );
292 tzs.append( "Brisbane" ); 291 tzs.append( "Brisbane" );
293 tzs.append( "Europe/Berlin" ); 292 tzs.append( "Europe/Berlin" );
294 tzs.append( "Berlin" ); 293 tzs.append( "Berlin" );
295 tzs.append( "Asia/Tokyo" ); 294 tzs.append( "Asia/Tokyo" );
296 tzs.append( "Tokyo" ); 295 tzs.append( "Tokyo" );
297 tzs.append( "America/Denver" ); 296 tzs.append( "America/Denver" );
298 tzs.append( "Denver" ); 297 tzs.append( "Denver" );
299 298
300 return tzs; 299 return tzs;
301} 300}
302 301
303 302