summaryrefslogtreecommitdiff
Unidiff
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--core/launcher/applauncher.cpp1
-rw-r--r--core/launcher/documentlist.cpp1
-rw-r--r--core/launcher/main.cpp2
-rw-r--r--core/launcher/qcopbridge.cpp1
-rw-r--r--core/launcher/screensaver.cpp20
-rw-r--r--core/launcher/server.cpp10
-rw-r--r--core/launcher/server.h4
-rw-r--r--core/launcher/serverapp.cpp9
-rw-r--r--core/launcher/serverapp.h10
-rw-r--r--core/launcher/transferserver.cpp1
-rw-r--r--core/launcher/wait.cpp1
-rw-r--r--core/launcher/wait.h4
12 files changed, 37 insertions, 27 deletions
diff --git a/core/launcher/applauncher.cpp b/core/launcher/applauncher.cpp
index efbf426..5a5517c 100644
--- a/core/launcher/applauncher.cpp
+++ b/core/launcher/applauncher.cpp
@@ -1,572 +1,573 @@
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 QTOPIA_INTERNAL_PRELOADACCESS 21#ifndef QTOPIA_INTERNAL_PRELOADACCESS
22#define QTOPIA_INTERNAL_PRELOADACCESS 22#define QTOPIA_INTERNAL_PRELOADACCESS
23#endif 23#endif
24#ifndef QTOPIA_INTERNAL_FILEOPERATIONS 24#ifndef QTOPIA_INTERNAL_FILEOPERATIONS
25#define QTOPIA_INTERNAL_FILEOPERATIONS 25#define QTOPIA_INTERNAL_FILEOPERATIONS
26#endif 26#endif
27#ifndef QTOPIA_PROGRAM_MONITOR 27#ifndef QTOPIA_PROGRAM_MONITOR
28#define QTOPIA_PROGRAM_MONITOR 28#define QTOPIA_PROGRAM_MONITOR
29#endif 29#endif
30#include <opie2/oglobal.h> 30#include <opie2/oglobal.h>
31 31
32#ifndef Q_OS_WIN32 32#ifndef Q_OS_WIN32
33#include <sys/stat.h> 33#include <sys/stat.h>
34#include <sys/wait.h> 34#include <sys/wait.h>
35#include <sys/file.h> 35#include <sys/file.h>
36#include <unistd.h> 36#include <unistd.h>
37#include <sys/time.h> 37#include <sys/time.h>
38#include <sys/resource.h> 38#include <sys/resource.h>
39#include <errno.h> 39#include <errno.h>
40#else 40#else
41#include <process.h> 41#include <process.h>
42#include <windows.h> 42#include <windows.h>
43#include <winbase.h> 43#include <winbase.h>
44#endif 44#endif
45 45
46#include <signal.h> 46#include <signal.h>
47#include <sys/types.h> 47#include <sys/types.h>
48#include <stdlib.h> 48#include <stdlib.h>
49 49
50#include <qtimer.h> 50#include <qtimer.h>
51#include <qwindowsystem_qws.h> 51#include <qwindowsystem_qws.h>
52#include <qmessagebox.h> 52#include <qmessagebox.h>
53#include <qfileinfo.h> 53#include <qfileinfo.h>
54 54
55#include <qtopia/qcopenvelope_qws.h> 55#include <qtopia/qcopenvelope_qws.h>
56#include <qtopia/qpeapplication.h> 56#include <qtopia/qpeapplication.h>
57 57
58#include "applauncher.h" 58#include "applauncher.h"
59#include "documentlist.h" 59#include "documentlist.h"
60 60
61using namespace Opie::Core;
61const int AppLauncher::RAISE_TIMEOUT_MS = 5000; 62const int AppLauncher::RAISE_TIMEOUT_MS = 5000;
62 63
63//--------------------------------------------------------------------------- 64//---------------------------------------------------------------------------
64 65
65static AppLauncher* appLauncherPtr; 66static AppLauncher* appLauncherPtr;
66 67
67const int appStopEventID = 1290; 68const int appStopEventID = 1290;
68 69
69class AppStoppedEvent : public QCustomEvent 70class AppStoppedEvent : public QCustomEvent
70{ 71{
71public: 72public:
72 AppStoppedEvent(int pid, int status) 73 AppStoppedEvent(int pid, int status)
73 : QCustomEvent( appStopEventID ), mPid(pid), mStatus(status) { } 74 : QCustomEvent( appStopEventID ), mPid(pid), mStatus(status) { }
74 75
75 int pid() { return mPid; } 76 int pid() { return mPid; }
76 int status() { return mStatus; } 77 int status() { return mStatus; }
77 78
78private: 79private:
79 int mPid, mStatus; 80 int mPid, mStatus;
80}; 81};
81 82
82AppLauncher::AppLauncher(QObject *parent, const char *name) 83AppLauncher::AppLauncher(QObject *parent, const char *name)
83 : QObject(parent, name), qlPid(0), qlReady(FALSE), 84 : QObject(parent, name), qlPid(0), qlReady(FALSE),
84 appKillerBox(0) 85 appKillerBox(0)
85{ 86{
86 connect(qwsServer, SIGNAL(newChannel(const QString&)), this, SLOT(newQcopChannel(const QString&))); 87 connect(qwsServer, SIGNAL(newChannel(const QString&)), this, SLOT(newQcopChannel(const QString&)));
87 connect(qwsServer, SIGNAL(removedChannel(const QString&)), this, SLOT(removedQcopChannel(const QString&))); 88 connect(qwsServer, SIGNAL(removedChannel(const QString&)), this, SLOT(removedQcopChannel(const QString&)));
88 QCopChannel* channel = new QCopChannel( "QPE/System", this ); 89 QCopChannel* channel = new QCopChannel( "QPE/System", this );
89 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), 90 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
90 this, SLOT(received(const QCString&,const QByteArray&)) ); 91 this, SLOT(received(const QCString&,const QByteArray&)) );
91 92
92 channel = new QCopChannel( "QPE/Server", this ); 93 channel = new QCopChannel( "QPE/Server", this );
93 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), 94 connect( channel, SIGNAL(received(const QCString&,const QByteArray&)),
94 this, SLOT(received(const QCString&,const QByteArray&)) ); 95 this, SLOT(received(const QCString&,const QByteArray&)) );
95 96
96#ifndef Q_OS_WIN32 97#ifndef Q_OS_WIN32
97 signal(SIGCHLD, signalHandler); 98 signal(SIGCHLD, signalHandler);
98#else 99#else
99 runningAppsProc.setAutoDelete( TRUE ); 100 runningAppsProc.setAutoDelete( TRUE );
100#endif 101#endif
101 QString tmp = qApp->argv()[0]; 102 QString tmp = qApp->argv()[0];
102 int pos = tmp.findRev('/'); 103 int pos = tmp.findRev('/');
103 if ( pos > -1 ) 104 if ( pos > -1 )
104 tmp = tmp.mid(++pos); 105 tmp = tmp.mid(++pos);
105 runningApps[::getpid()] = tmp; 106 runningApps[::getpid()] = tmp;
106 107
107 appLauncherPtr = this; 108 appLauncherPtr = this;
108 109
109 QTimer::singleShot( 1000, this, SLOT(createQuickLauncher()) ); 110 QTimer::singleShot( 1000, this, SLOT(createQuickLauncher()) );
110} 111}
111 112
112AppLauncher::~AppLauncher() 113AppLauncher::~AppLauncher()
113{ 114{
114 appLauncherPtr = 0; 115 appLauncherPtr = 0;
115#ifndef Q_OS_WIN32 116#ifndef Q_OS_WIN32
116 signal(SIGCHLD, SIG_DFL); 117 signal(SIGCHLD, SIG_DFL);
117#endif 118#endif
118 if ( qlPid ) { 119 if ( qlPid ) {
119 int status; 120 int status;
120 ::kill( qlPid, SIGTERM ); 121 ::kill( qlPid, SIGTERM );
121 waitpid( qlPid, &status, 0 ); 122 waitpid( qlPid, &status, 0 );
122 } 123 }
123} 124}
124 125
125/* We use the QCopChannel of the app as an indicator of when it has been launched 126/* We use the QCopChannel of the app as an indicator of when it has been launched
126 so that we can disable the busy indicators */ 127 so that we can disable the busy indicators */
127void AppLauncher::newQcopChannel(const QString& channelName) 128void AppLauncher::newQcopChannel(const QString& channelName)
128{ 129{
129// qDebug("channel %s added", channelName.data() ); 130// qDebug("channel %s added", channelName.data() );
130 QString prefix("QPE/Application/"); 131 QString prefix("QPE/Application/");
131 if (channelName.startsWith(prefix)) { 132 if (channelName.startsWith(prefix)) {
132 { 133 {
133 QCopEnvelope e("QPE/System", "newChannel(QString)"); 134 QCopEnvelope e("QPE/System", "newChannel(QString)");
134 e << channelName; 135 e << channelName;
135 } 136 }
136 QString appName = channelName.mid(prefix.length()); 137 QString appName = channelName.mid(prefix.length());
137 if ( appName != "quicklauncher" ) { 138 if ( appName != "quicklauncher" ) {
138 emit connected( appName ); 139 emit connected( appName );
139 QCopEnvelope e("QPE/System", "notBusy(QString)"); 140 QCopEnvelope e("QPE/System", "notBusy(QString)");
140 e << appName; 141 e << appName;
141 } 142 }
142 } else if (channelName.startsWith("QPE/QuickLauncher-")) { 143 } else if (channelName.startsWith("QPE/QuickLauncher-")) {
143 qDebug("Registered %s", channelName.latin1()); 144 qDebug("Registered %s", channelName.latin1());
144 int pid = channelName.mid(18).toInt(); 145 int pid = channelName.mid(18).toInt();
145 if (pid == qlPid) 146 if (pid == qlPid)
146 qlReady = TRUE; 147 qlReady = TRUE;
147 } 148 }
148} 149}
149 150
150void AppLauncher::removedQcopChannel(const QString& channelName) 151void AppLauncher::removedQcopChannel(const QString& channelName)
151{ 152{
152 if (channelName.startsWith("QPE/Application/")) { 153 if (channelName.startsWith("QPE/Application/")) {
153 QCopEnvelope e("QPE/System", "removedChannel(QString)"); 154 QCopEnvelope e("QPE/System", "removedChannel(QString)");
154 e << channelName; 155 e << channelName;
155 } 156 }
156} 157}
157 158
158void AppLauncher::received(const QCString& msg, const QByteArray& data) 159void AppLauncher::received(const QCString& msg, const QByteArray& data)
159{ 160{
160 QDataStream stream( data, IO_ReadOnly ); 161 QDataStream stream( data, IO_ReadOnly );
161 if ( msg == "execute(QString)" ) { 162 if ( msg == "execute(QString)" ) {
162 QString t; 163 QString t;
163 stream >> t; 164 stream >> t;
164 if ( !executeBuiltin( t, QString::null ) ) 165 if ( !executeBuiltin( t, QString::null ) )
165 execute(t, QString::null); 166 execute(t, QString::null);
166 } else if ( msg == "execute(QString,QString)" ) { 167 } else if ( msg == "execute(QString,QString)" ) {
167 QString t,d; 168 QString t,d;
168 stream >> t >> d; 169 stream >> t >> d;
169 if ( !executeBuiltin( t, d ) ) 170 if ( !executeBuiltin( t, d ) )
170 execute( t, d ); 171 execute( t, d );
171 } else if ( msg == "processQCop(QString)" ) { // from QPE/Server 172 } else if ( msg == "processQCop(QString)" ) { // from QPE/Server
172 QString t; 173 QString t;
173 stream >> t; 174 stream >> t;
174 if ( !executeBuiltin( t, QString::null ) ) 175 if ( !executeBuiltin( t, QString::null ) )
175 execute( t, QString::null, TRUE); 176 execute( t, QString::null, TRUE);
176 } else if ( msg == "raise(QString)" ) { 177 } else if ( msg == "raise(QString)" ) {
177 QString appName; 178 QString appName;
178 stream >> appName; 179 stream >> appName;
179 180
180 if ( !executeBuiltin( appName, QString::null ) ) { 181 if ( !executeBuiltin( appName, QString::null ) ) {
181 if ( !waitingHeartbeat.contains( appName ) && appKillerName != appName ) { 182 if ( !waitingHeartbeat.contains( appName ) && appKillerName != appName ) {
182 //qDebug( "Raising: %s", appName.latin1() ); 183 //qDebug( "Raising: %s", appName.latin1() );
183 QCString channel = "QPE/Application/"; 184 QCString channel = "QPE/Application/";
184 channel += appName.latin1(); 185 channel += appName.latin1();
185 186
186 // Need to lock it to avoid race conditions with QPEApplication::processQCopFile 187 // Need to lock it to avoid race conditions with QPEApplication::processQCopFile
187 QFile f("/tmp/qcop-msg-" + appName); 188 QFile f("/tmp/qcop-msg-" + appName);
188 if ( f.open(IO_WriteOnly | IO_Append) ) { 189 if ( f.open(IO_WriteOnly | IO_Append) ) {
189#ifndef Q_OS_WIN32 190#ifndef Q_OS_WIN32
190 flock(f.handle(), LOCK_EX); 191 flock(f.handle(), LOCK_EX);
191#endif 192#endif
192 QDataStream ds(&f); 193 QDataStream ds(&f);
193 QByteArray b; 194 QByteArray b;
194 QDataStream bstream(b, IO_WriteOnly); 195 QDataStream bstream(b, IO_WriteOnly);
195 ds << channel << QCString("raise()") << b; 196 ds << channel << QCString("raise()") << b;
196 f.flush(); 197 f.flush();
197#ifndef Q_OS_WIN32 198#ifndef Q_OS_WIN32
198 flock(f.handle(), LOCK_UN); 199 flock(f.handle(), LOCK_UN);
199#endif 200#endif
200 f.close(); 201 f.close();
201 } 202 }
202 bool alreadyRunning = isRunning( appName ); 203 bool alreadyRunning = isRunning( appName );
203 if ( execute(appName, QString::null) ) { 204 if ( execute(appName, QString::null) ) {
204 int id = startTimer(RAISE_TIMEOUT_MS + alreadyRunning?2000:0); 205 int id = startTimer(RAISE_TIMEOUT_MS + alreadyRunning?2000:0);
205 waitingHeartbeat.insert( appName, id ); 206 waitingHeartbeat.insert( appName, id );
206 } 207 }
207 } 208 }
208 } 209 }
209 } else if ( msg == "sendRunningApps()" ) { 210 } else if ( msg == "sendRunningApps()" ) {
210 QStringList apps; 211 QStringList apps;
211 QMap<int,QString>::Iterator it; 212 QMap<int,QString>::Iterator it;
212 for( it = runningApps.begin(); it != runningApps.end(); ++it ) 213 for( it = runningApps.begin(); it != runningApps.end(); ++it )
213 apps.append( *it ); 214 apps.append( *it );
214 QCopEnvelope e( "QPE/Desktop", "runningApps(QStringList)" ); 215 QCopEnvelope e( "QPE/Desktop", "runningApps(QStringList)" );
215 e << apps; 216 e << apps;
216 } else if ( msg == "appRaised(QString)" ) { 217 } else if ( msg == "appRaised(QString)" ) {
217 QString appName; 218 QString appName;
218 stream >> appName; 219 stream >> appName;
219 qDebug("Got a heartbeat from %s", appName.latin1()); 220 qDebug("Got a heartbeat from %s", appName.latin1());
220 QMap<QString,int>::Iterator it = waitingHeartbeat.find(appName); 221 QMap<QString,int>::Iterator it = waitingHeartbeat.find(appName);
221 if ( it != waitingHeartbeat.end() ) { 222 if ( it != waitingHeartbeat.end() ) {
222 killTimer( *it ); 223 killTimer( *it );
223 waitingHeartbeat.remove(it); 224 waitingHeartbeat.remove(it);
224 } 225 }
225 // Check to make sure we're not waiting on user input... 226 // Check to make sure we're not waiting on user input...
226 if ( appKillerBox && appName == appKillerName ) { 227 if ( appKillerBox && appName == appKillerName ) {
227 // If we are, we kill the dialog box, and the code waiting on the result 228 // If we are, we kill the dialog box, and the code waiting on the result
228 // will clean us up (basically the user said "no"). 229 // will clean us up (basically the user said "no").
229 delete appKillerBox; 230 delete appKillerBox;
230 appKillerBox = 0; 231 appKillerBox = 0;
231 appKillerName = QString::null; 232 appKillerName = QString::null;
232 } 233 }
233 } 234 }
234} 235}
235 236
236void AppLauncher::signalHandler(int) 237void AppLauncher::signalHandler(int)
237{ 238{
238#ifndef Q_OS_WIN32 239#ifndef Q_OS_WIN32
239 int status; 240 int status;
240 pid_t pid = waitpid(-1, &status, WNOHANG); 241 pid_t pid = waitpid(-1, &status, WNOHANG);
241/* if (pid == 0 || &status == 0 ) { 242/* if (pid == 0 || &status == 0 ) {
242 qDebug("hmm, could not get return value from signal"); 243 qDebug("hmm, could not get return value from signal");
243 } 244 }
244*/ 245*/
245 QApplication::postEvent(appLauncherPtr, new AppStoppedEvent(pid, status) ); 246 QApplication::postEvent(appLauncherPtr, new AppStoppedEvent(pid, status) );
246#else 247#else
247 qDebug("Unhandled signal see by AppLauncher::signalHandler(int)"); 248 qDebug("Unhandled signal see by AppLauncher::signalHandler(int)");
248#endif 249#endif
249} 250}
250 251
251bool AppLauncher::event(QEvent *e) 252bool AppLauncher::event(QEvent *e)
252{ 253{
253 if ( e->type() == appStopEventID ) { 254 if ( e->type() == appStopEventID ) {
254 AppStoppedEvent *ae = (AppStoppedEvent *) e; 255 AppStoppedEvent *ae = (AppStoppedEvent *) e;
255 sigStopped(ae->pid(), ae->status() ); 256 sigStopped(ae->pid(), ae->status() );
256 return TRUE; 257 return TRUE;
257 } 258 }
258 259
259 return QObject::event(e); 260 return QObject::event(e);
260} 261}
261 262
262void AppLauncher::timerEvent( QTimerEvent *e ) 263void AppLauncher::timerEvent( QTimerEvent *e )
263{ 264{
264 int id = e->timerId(); 265 int id = e->timerId();
265 QMap<QString,int>::Iterator it; 266 QMap<QString,int>::Iterator it;
266 for ( it = waitingHeartbeat.begin(); it != waitingHeartbeat.end(); ++it ) { 267 for ( it = waitingHeartbeat.begin(); it != waitingHeartbeat.end(); ++it ) {
267 if ( *it == id ) { 268 if ( *it == id ) {
268 if ( appKillerBox ) // we're already dealing with one 269 if ( appKillerBox ) // we're already dealing with one
269 return; 270 return;
270 271
271 appKillerName = it.key(); 272 appKillerName = it.key();
272 killTimer( id ); 273 killTimer( id );
273 waitingHeartbeat.remove( it ); 274 waitingHeartbeat.remove( it );
274 275
275 // qDebug("Checking in on %s", appKillerName.latin1()); 276 // qDebug("Checking in on %s", appKillerName.latin1());
276 277
277 // We store this incase the application responds while we're 278 // We store this incase the application responds while we're
278 // waiting for user input so we know not to delete ourselves. 279 // waiting for user input so we know not to delete ourselves.
279 appKillerBox = new QMessageBox(tr("Application Problem"), 280 appKillerBox = new QMessageBox(tr("Application Problem"),
280 tr("<p>%1 is not responding.</p>").arg(appKillerName) + 281 tr("<p>%1 is not responding.</p>").arg(appKillerName) +
281 tr("<p>Would you like to force the application to exit?</p>"), 282 tr("<p>Would you like to force the application to exit?</p>"),
282 QMessageBox::Warning, QMessageBox::Yes, 283 QMessageBox::Warning, QMessageBox::Yes,
283 QMessageBox::No | QMessageBox::Default, 284 QMessageBox::No | QMessageBox::Default,
284 QMessageBox::NoButton); 285 QMessageBox::NoButton);
285 if (appKillerBox->exec() == QMessageBox::Yes) { 286 if (appKillerBox->exec() == QMessageBox::Yes) {
286 // qDebug("Killing the app!!! Bwuhahahaha!"); 287 // qDebug("Killing the app!!! Bwuhahahaha!");
287 int pid = pidForName(appKillerName); 288 int pid = pidForName(appKillerName);
288 if ( pid > 0 ) 289 if ( pid > 0 )
289 kill( pid ); 290 kill( pid );
290 } 291 }
291 appKillerName = QString::null; 292 appKillerName = QString::null;
292 delete appKillerBox; 293 delete appKillerBox;
293 appKillerBox = 0; 294 appKillerBox = 0;
294 return; 295 return;
295 } 296 }
296 } 297 }
297 298
298 QObject::timerEvent( e ); 299 QObject::timerEvent( e );
299} 300}
300 301
301#ifndef Q_OS_WIN32 302#ifndef Q_OS_WIN32
302void AppLauncher::sigStopped(int sigPid, int sigStatus) 303void AppLauncher::sigStopped(int sigPid, int sigStatus)
303{ 304{
304 int exitStatus = 0; 305 int exitStatus = 0;
305 306
306 bool crashed = WIFSIGNALED(sigStatus); 307 bool crashed = WIFSIGNALED(sigStatus);
307 if ( !crashed ) { 308 if ( !crashed ) {
308 if ( WIFEXITED(sigStatus) ) 309 if ( WIFEXITED(sigStatus) )
309 exitStatus = WEXITSTATUS(sigStatus); 310 exitStatus = WEXITSTATUS(sigStatus);
310 } else { 311 } else {
311 exitStatus = WTERMSIG(sigStatus); 312 exitStatus = WTERMSIG(sigStatus);
312 } 313 }
313 314
314 QMap<int,QString>::Iterator it = runningApps.find( sigPid ); 315 QMap<int,QString>::Iterator it = runningApps.find( sigPid );
315 if ( it == runningApps.end() ) { 316 if ( it == runningApps.end() ) {
316 if ( sigPid == qlPid ) { 317 if ( sigPid == qlPid ) {
317 qDebug( "quicklauncher stopped" ); 318 qDebug( "quicklauncher stopped" );
318 qlPid = 0; 319 qlPid = 0;
319 qlReady = FALSE; 320 qlReady = FALSE;
320 QFile::remove("/tmp/qcop-msg-quicklauncher" ); 321 QFile::remove("/tmp/qcop-msg-quicklauncher" );
321 QTimer::singleShot( 2000, this, SLOT(createQuickLauncher()) ); 322 QTimer::singleShot( 2000, this, SLOT(createQuickLauncher()) );
322 } 323 }
323/* 324/*
324 if ( sigPid == -1 ) 325 if ( sigPid == -1 )
325 qDebug("non-qtopia application exited (disregarded)"); 326 qDebug("non-qtopia application exited (disregarded)");
326 else 327 else
327 qDebug("==== no pid matching %d in list, definite bug", sigPid); 328 qDebug("==== no pid matching %d in list, definite bug", sigPid);
328*/ 329*/
329 return; 330 return;
330 } 331 }
331 QString appName = *it; 332 QString appName = *it;
332 runningApps.remove(it); 333 runningApps.remove(it);
333 334
334 QMap<QString,int>::Iterator hbit = waitingHeartbeat.find(appName); 335 QMap<QString,int>::Iterator hbit = waitingHeartbeat.find(appName);
335 if ( hbit != waitingHeartbeat.end() ) { 336 if ( hbit != waitingHeartbeat.end() ) {
336 killTimer( *hbit ); 337 killTimer( *hbit );
337 waitingHeartbeat.remove( hbit ); 338 waitingHeartbeat.remove( hbit );
338 } 339 }
339 if ( appName == appKillerName ) { 340 if ( appName == appKillerName ) {
340 appKillerName = QString::null; 341 appKillerName = QString::null;
341 delete appKillerBox; 342 delete appKillerBox;
342 appKillerBox = 0; 343 appKillerBox = 0;
343 } 344 }
344 345
345 /* we must disable preload for an app that crashes as the system logic relies on preloaded apps 346 /* we must disable preload for an app that crashes as the system logic relies on preloaded apps
346 actually being loaded. If eg. the crash happened in the constructor, we can't automatically reload 347 actually being loaded. If eg. the crash happened in the constructor, we can't automatically reload
347 the app (withouth some timeout value for eg. 3 tries (which I think is a bad solution) 348 the app (withouth some timeout value for eg. 3 tries (which I think is a bad solution)
348 */ 349 */
349 bool preloadDisabled = FALSE; 350 bool preloadDisabled = FALSE;
350 if ( !DocumentList::appLnkSet ) return; 351 if ( !DocumentList::appLnkSet ) return;
351 const AppLnk* app = DocumentList::appLnkSet->findExec( appName ); 352 const AppLnk* app = DocumentList::appLnkSet->findExec( appName );
352 if ( !app ) return; // QCop messages processed to slow? 353 if ( !app ) return; // QCop messages processed to slow?
353 if ( crashed && app->isPreloaded() ) { 354 if ( crashed && app->isPreloaded() ) {
354 Config cfg("Launcher"); 355 Config cfg("Launcher");
355 cfg.setGroup("Preload"); 356 cfg.setGroup("Preload");
356 QStringList apps = cfg.readListEntry("Apps",','); 357 QStringList apps = cfg.readListEntry("Apps",',');
357 QString exe = app->exec(); 358 QString exe = app->exec();
358 apps.remove(exe); 359 apps.remove(exe);
359 cfg.writeEntry("Apps",apps,','); 360 cfg.writeEntry("Apps",apps,',');
360 preloadDisabled = TRUE; 361 preloadDisabled = TRUE;
361 } 362 }
362 363
363 // clean up 364 // clean up
364 if ( exitStatus ) { 365 if ( exitStatus ) {
365 QCopEnvelope e("QPE/System", "notBusy(QString)"); 366 QCopEnvelope e("QPE/System", "notBusy(QString)");
366 e << app->exec(); 367 e << app->exec();
367 } 368 }
368/* 369/*
369 // debug info 370 // debug info
370 for (it = runningApps.begin(); it != runningApps.end(); ++it) { 371 for (it = runningApps.begin(); it != runningApps.end(); ++it) {
371 qDebug("running according to internal list: %s, with pid %d", (*it).data(), it.key() ); 372 qDebug("running according to internal list: %s, with pid %d", (*it).data(), it.key() );
372 } 373 }
373*/ 374*/
374 375
375#ifdef QTOPIA_PROGRAM_MONITOR 376#ifdef QTOPIA_PROGRAM_MONITOR
376 if ( crashed ) { 377 if ( crashed ) {
377 QString sig; 378 QString sig;
378 switch( exitStatus ) { 379 switch( exitStatus ) {
379 case SIGABRT: sig = "SIGABRT"; break; 380 case SIGABRT: sig = "SIGABRT"; break;
380 case SIGALRM: sig = "SIGALRM"; break; 381 case SIGALRM: sig = "SIGALRM"; break;
381 case SIGBUS: sig = "SIGBUS"; break; 382 case SIGBUS: sig = "SIGBUS"; break;
382 case SIGFPE: sig = "SIGFPE"; break; 383 case SIGFPE: sig = "SIGFPE"; break;
383 case SIGHUP: sig = "SIGHUP"; break; 384 case SIGHUP: sig = "SIGHUP"; break;
384 case SIGILL: sig = "SIGILL"; break; 385 case SIGILL: sig = "SIGILL"; break;
385 case SIGKILL: sig = "SIGKILL"; break; 386 case SIGKILL: sig = "SIGKILL"; break;
386 case SIGPIPE: sig = "SIGPIPE"; break; 387 case SIGPIPE: sig = "SIGPIPE"; break;
387 case SIGQUIT: sig = "SIGQUIT"; break; 388 case SIGQUIT: sig = "SIGQUIT"; break;
388 case SIGSEGV: sig = "SIGSEGV"; break; 389 case SIGSEGV: sig = "SIGSEGV"; break;
389 case SIGTERM: sig = "SIGTERM"; break; 390 case SIGTERM: sig = "SIGTERM"; break;
390 case SIGTRAP: sig = "SIGTRAP"; break; 391 case SIGTRAP: sig = "SIGTRAP"; break;
391 default: sig = QString("Unkown %1").arg(exitStatus); 392 default: sig = QString("Unkown %1").arg(exitStatus);
392 } 393 }
393 if ( preloadDisabled ) 394 if ( preloadDisabled )
394 sig += tr("<qt><p>Fast loading has been disabled for this application. Tap and hold the application icon to reenable it.</qt>"); 395 sig += tr("<qt><p>Fast loading has been disabled for this application. Tap and hold the application icon to reenable it.</qt>");
395 396
396 QString str = tr("<qt><b>%1</b> was terminated due to signal code %2</qt>").arg( app->name() ).arg( sig ); 397 QString str = tr("<qt><b>%1</b> was terminated due to signal code %2</qt>").arg( app->name() ).arg( sig );
397 QMessageBox::information(0, tr("Application terminated"), str ); 398 QMessageBox::information(0, tr("Application terminated"), str );
398 } else { 399 } else {
399 if ( exitStatus == 255 ) { //could not find app (because global returns -1) 400 if ( exitStatus == 255 ) { //could not find app (because global returns -1)
400 QMessageBox::information(0, tr("Application not found"), tr("<qt>Could not locate application <b>%1</b></qt>").arg( app->exec() ) ); 401 QMessageBox::information(0, tr("Application not found"), tr("<qt>Could not locate application <b>%1</b></qt>").arg( app->exec() ) );
401 } else { 402 } else {
402 QFileInfo fi(QString::fromLatin1("/tmp/qcop-msg-") + appName); 403 QFileInfo fi(QString::fromLatin1("/tmp/qcop-msg-") + appName);
403 if ( fi.exists() && fi.size() ) { 404 if ( fi.exists() && fi.size() ) {
404 emit terminated(sigPid, appName); 405 emit terminated(sigPid, appName);
405 qWarning("Re executing obmitted for %s", appName.latin1() ); 406 qWarning("Re executing obmitted for %s", appName.latin1() );
406 // execute( appName, QString::null ); 407 // execute( appName, QString::null );
407 return; 408 return;
408 } 409 }
409 } 410 }
410 } 411 }
411 412
412#endif 413#endif
413 414
414 emit terminated(sigPid, appName); 415 emit terminated(sigPid, appName);
415} 416}
416#else 417#else
417void AppLauncher::sigStopped(int sigPid, int sigStatus) 418void AppLauncher::sigStopped(int sigPid, int sigStatus)
418{ 419{
419 qDebug("Unhandled signal : AppLauncher::sigStopped(int sigPid, int sigStatus)"); 420 qDebug("Unhandled signal : AppLauncher::sigStopped(int sigPid, int sigStatus)");
420} 421}
421#endif // Q_OS_WIN32 422#endif // Q_OS_WIN32
422 423
423bool AppLauncher::isRunning(const QString &app) 424bool AppLauncher::isRunning(const QString &app)
424{ 425{
425 for (QMap<int,QString>::ConstIterator it = runningApps.begin(); it != runningApps.end(); ++it) { 426 for (QMap<int,QString>::ConstIterator it = runningApps.begin(); it != runningApps.end(); ++it) {
426 if ( *it == app ) { 427 if ( *it == app ) {
427#ifdef Q_OS_UNIX 428#ifdef Q_OS_UNIX
428 pid_t t = ::__getpgid( it.key() ); 429 pid_t t = ::__getpgid( it.key() );
429 if ( t == -1 ) { 430 if ( t == -1 ) {
430 qDebug("appLauncher bug, %s believed running, but pid %d is not existing", app.data(), it.key() ); 431 qDebug("appLauncher bug, %s believed running, but pid %d is not existing", app.data(), it.key() );
431 runningApps.remove( it.key() ); 432 runningApps.remove( it.key() );
432 return FALSE; 433 return FALSE;
433 } 434 }
434#endif 435#endif
435 return TRUE; 436 return TRUE;
436 } 437 }
437 } 438 }
438 439
439 return FALSE; 440 return FALSE;
440} 441}
441 442
442bool AppLauncher::executeBuiltin(const QString &c, const QString &document) 443bool AppLauncher::executeBuiltin(const QString &c, const QString &document)
443{ 444{
444 Global::Command* builtin = OGlobal::builtinCommands(); 445 Global::Command* builtin = OGlobal::builtinCommands();
445 QGuardedPtr<QWidget> *running = OGlobal::builtinRunning(); 446 QGuardedPtr<QWidget> *running = OGlobal::builtinRunning();
446 447
447 // Attempt to execute the app using a builtin class for the app 448 // Attempt to execute the app using a builtin class for the app
448 if (builtin) { 449 if (builtin) {
449 for (int i = 0; builtin[i].file; i++) { 450 for (int i = 0; builtin[i].file; i++) {
450 if ( builtin[i].file == c ) { 451 if ( builtin[i].file == c ) {
451 if ( running[i] ) { 452 if ( running[i] ) {
452 if ( !document.isNull() && builtin[i].documentary ) 453 if ( !document.isNull() && builtin[i].documentary )
453 Global::setDocument(running[i], document); 454 Global::setDocument(running[i], document);
454 running[i]->raise(); 455 running[i]->raise();
455 running[i]->show(); 456 running[i]->show();
456 running[i]->setActiveWindow(); 457 running[i]->setActiveWindow();
457 } else { 458 } else {
458 running[i] = builtin[i].func( builtin[i].maximized ); 459 running[i] = builtin[i].func( builtin[i].maximized );
459 } 460 }
460#ifndef QT_NO_COP 461#ifndef QT_NO_COP
461 QCopEnvelope e("QPE/System", "notBusy(QString)" ); 462 QCopEnvelope e("QPE/System", "notBusy(QString)" );
462 e << c; // that was quick ;-) 463 e << c; // that was quick ;-)
463#endif 464#endif
464 return TRUE; 465 return TRUE;
465 } 466 }
466 } 467 }
467 } 468 }
468 469
469 // Convert the command line in to a list of arguments 470 // Convert the command line in to a list of arguments
470 QStringList list = QStringList::split(QRegExp(" *"),c); 471 QStringList list = QStringList::split(QRegExp(" *"),c);
471 QString ap=list[0]; 472 QString ap=list[0];
472 473
473 if ( ap == "suspend" ) { // No tr 474 if ( ap == "suspend" ) { // No tr
474 QWSServer::processKeyEvent( 0xffff, Qt::Key_F34, FALSE, TRUE, FALSE ); 475 QWSServer::processKeyEvent( 0xffff, Qt::Key_F34, FALSE, TRUE, FALSE );
475 return TRUE; 476 return TRUE;
476 } 477 }
477 478
478 return FALSE; 479 return FALSE;
479} 480}
480 481
481bool AppLauncher::execute(const QString &c, const QString &docParam, bool noRaise) 482bool AppLauncher::execute(const QString &c, const QString &docParam, bool noRaise)
482{ 483{
483 qWarning("AppLauncher::execute '%s' '%s'", (const char*) c, (const char*) docParam ); 484 qWarning("AppLauncher::execute '%s' '%s'", (const char*) c, (const char*) docParam );
484 // Convert the command line in to a list of arguments 485 // Convert the command line in to a list of arguments
485 QStringList list = QStringList::split(QRegExp(" *"),c); 486 QStringList list = QStringList::split(QRegExp(" *"),c);
486 QStringList arglist = QStringList::split(QRegExp(" *"),docParam); 487 QStringList arglist = QStringList::split(QRegExp(" *"),docParam);
487 for ( QStringList::Iterator it = arglist.begin(); it != arglist.end(); ++it ) 488 for ( QStringList::Iterator it = arglist.begin(); it != arglist.end(); ++it )
488 list.append( *it ); 489 list.append( *it );
489 490
490 QString appName = list[0]; 491 QString appName = list[0];
491 if ( isRunning(appName) ) { 492 if ( isRunning(appName) ) {
492 QCString channel = "QPE/Application/"; 493 QCString channel = "QPE/Application/";
493 channel += appName.latin1(); 494 channel += appName.latin1();
494 495
495 // Need to lock it to avoid race conditions with QPEApplication::processQCopFile 496 // Need to lock it to avoid race conditions with QPEApplication::processQCopFile
496 QFile f(QString::fromLatin1("/tmp/qcop-msg-") + appName); 497 QFile f(QString::fromLatin1("/tmp/qcop-msg-") + appName);
497 if ( !noRaise && f.open(IO_WriteOnly | IO_Append) ) { 498 if ( !noRaise && f.open(IO_WriteOnly | IO_Append) ) {
498#ifndef Q_OS_WIN32 499#ifndef Q_OS_WIN32
499 flock(f.handle(), LOCK_EX); 500 flock(f.handle(), LOCK_EX);
500#endif 501#endif
501 502
502 QDataStream ds(&f); 503 QDataStream ds(&f);
503 QByteArray b; 504 QByteArray b;
504 QDataStream bstream(b, IO_WriteOnly); 505 QDataStream bstream(b, IO_WriteOnly);
505 if ( !f.size() ) { 506 if ( !f.size() ) {
506 ds << channel << QCString("raise()") << b; 507 ds << channel << QCString("raise()") << b;
507 if ( !waitingHeartbeat.contains( appName ) && appKillerName != appName ) { 508 if ( !waitingHeartbeat.contains( appName ) && appKillerName != appName ) {
508 int id = startTimer(RAISE_TIMEOUT_MS); 509 int id = startTimer(RAISE_TIMEOUT_MS);
509 waitingHeartbeat.insert( appName, id ); 510 waitingHeartbeat.insert( appName, id );
510 } 511 }
511 } 512 }
512 if ( !docParam.isEmpty() ) { 513 if ( !docParam.isEmpty() ) {
513 bstream << docParam; 514 bstream << docParam;
514 ds << channel << QCString("setDocument(QString)") << b; 515 ds << channel << QCString("setDocument(QString)") << b;
515 } 516 }
516 517
517 f.flush(); 518 f.flush();
518#ifndef Q_OS_WIN32 519#ifndef Q_OS_WIN32
519 flock(f.handle(), LOCK_UN); 520 flock(f.handle(), LOCK_UN);
520#endif 521#endif
521 f.close(); 522 f.close();
522 } 523 }
523 if ( QCopChannel::isRegistered(channel) ) // avoid unnecessary warnings 524 if ( QCopChannel::isRegistered(channel) ) // avoid unnecessary warnings
524 QCopChannel::send(channel,"QPEProcessQCop()"); 525 QCopChannel::send(channel,"QPEProcessQCop()");
525 526
526 return TRUE; 527 return TRUE;
527 } 528 }
528 529
529#ifdef QT_NO_QWS_MULTIPROCESS 530#ifdef QT_NO_QWS_MULTIPROCESS
530 QMessageBox::warning( 0, tr("Error"), tr("<qt>Could not find the application %1</qt>").arg(c), 531 QMessageBox::warning( 0, tr("Error"), tr("<qt>Could not find the application %1</qt>").arg(c),
531 tr("OK"), 0, 0, 0, 1 ); 532 tr("OK"), 0, 0, 0, 1 );
532#else 533#else
533 534
534 QStrList slist; 535 QStrList slist;
535 unsigned j; 536 unsigned j;
536 for ( j = 0; j < list.count(); j++ ) 537 for ( j = 0; j < list.count(); j++ )
537 slist.append( list[j].utf8() ); 538 slist.append( list[j].utf8() );
538 539
539 const char **args = new const char *[slist.count() + 1]; 540 const char **args = new const char *[slist.count() + 1];
540 for ( j = 0; j < slist.count(); j++ ) 541 for ( j = 0; j < slist.count(); j++ )
541 args[j] = slist.at(j); 542 args[j] = slist.at(j);
542 args[j] = NULL; 543 args[j] = NULL;
543 544
544#ifndef Q_OS_WIN32 545#ifndef Q_OS_WIN32
545#ifdef Q_OS_MACX 546#ifdef Q_OS_MACX
546 if ( qlPid && qlReady && QFile::exists( QPEApplication::qpeDir()+"plugins/application/lib"+args[0] + ".dylib" ) ) { 547 if ( qlPid && qlReady && QFile::exists( QPEApplication::qpeDir()+"plugins/application/lib"+args[0] + ".dylib" ) ) {
547#else 548#else
548 if ( qlPid && qlReady && QFile::exists( QPEApplication::qpeDir()+"plugins/application/lib"+args[0] + ".so" ) ) { 549 if ( qlPid && qlReady && QFile::exists( QPEApplication::qpeDir()+"plugins/application/lib"+args[0] + ".so" ) ) {
549#endif /* Q_OS_MACX */ 550#endif /* Q_OS_MACX */
550 qDebug( "Quick launching: %s", args[0] ); 551 qDebug( "Quick launching: %s", args[0] );
551 if ( getuid() == 0 ) 552 if ( getuid() == 0 )
552 setpriority( PRIO_PROCESS, qlPid, 0 ); 553 setpriority( PRIO_PROCESS, qlPid, 0 );
553 QCString qlch("QPE/QuickLauncher-"); 554 QCString qlch("QPE/QuickLauncher-");
554 qlch += QString::number(qlPid); 555 qlch += QString::number(qlPid);
555 QCopEnvelope env( qlch, "execute(QStrList)" ); 556 QCopEnvelope env( qlch, "execute(QStrList)" );
556 env << slist; 557 env << slist;
557 runningApps[qlPid] = QString(args[0]); 558 runningApps[qlPid] = QString(args[0]);
558 emit launched(qlPid, QString(args[0])); 559 emit launched(qlPid, QString(args[0]));
559 QCopEnvelope e("QPE/System", "busy()"); 560 QCopEnvelope e("QPE/System", "busy()");
560 qlPid = 0; 561 qlPid = 0;
561 qlReady = FALSE; 562 qlReady = FALSE;
562 QTimer::singleShot( getuid() == 0 ? 800 : 1500, this, SLOT(createQuickLauncher()) ); 563 QTimer::singleShot( getuid() == 0 ? 800 : 1500, this, SLOT(createQuickLauncher()) );
563 } else { 564 } else {
564 int pid = ::vfork(); 565 int pid = ::vfork();
565 if ( !pid ) { 566 if ( !pid ) {
566 for ( int fd = 3; fd < 100; fd++ ) 567 for ( int fd = 3; fd < 100; fd++ )
567 ::close( fd ); 568 ::close( fd );
568 ::setpgid( ::getpid(), ::getppid() ); 569 ::setpgid( ::getpid(), ::getppid() );
569 // Try bindir first, so that foo/bar works too 570 // Try bindir first, so that foo/bar works too
570 ::execv( QPEApplication::qpeDir()+"bin/"+args[0], (char * const *)args ); 571 ::execv( QPEApplication::qpeDir()+"bin/"+args[0], (char * const *)args );
571 ::execvp( args[0], (char * const *)args ); 572 ::execvp( args[0], (char * const *)args );
572 _exit( -1 ); 573 _exit( -1 );
diff --git a/core/launcher/documentlist.cpp b/core/launcher/documentlist.cpp
index 63f853e..3e0a96c 100644
--- a/core/launcher/documentlist.cpp
+++ b/core/launcher/documentlist.cpp
@@ -1,561 +1,562 @@
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 "documentlist.h" 20#include "documentlist.h"
21#include "serverinterface.h" 21#include "serverinterface.h"
22#include "mediadlg.h" 22#include "mediadlg.h"
23 23
24#include <opie2/oglobal.h> 24#include <opie2/oglobal.h>
25 25
26#include <qtopia/config.h> 26#include <qtopia/config.h>
27#include <qtopia/mimetype.h> 27#include <qtopia/mimetype.h>
28#include <qtopia/resource.h> 28#include <qtopia/resource.h>
29#include <qtopia/private/categories.h> 29#include <qtopia/private/categories.h>
30#include <qtopia/qpeapplication.h> 30#include <qtopia/qpeapplication.h>
31#include <qtopia/applnk.h> 31#include <qtopia/applnk.h>
32#include <qtopia/storage.h> 32#include <qtopia/storage.h>
33#ifdef Q_WS_QWS 33#ifdef Q_WS_QWS
34#include <qtopia/qcopenvelope_qws.h> 34#include <qtopia/qcopenvelope_qws.h>
35#endif 35#endif
36 36
37#include <qtimer.h> 37#include <qtimer.h>
38#include <qfileinfo.h> 38#include <qfileinfo.h>
39#include <qtextstream.h> 39#include <qtextstream.h>
40#include <qfile.h> 40#include <qfile.h>
41#include <qdir.h> 41#include <qdir.h>
42#include <qpainter.h> 42#include <qpainter.h>
43#include <qimage.h> 43#include <qimage.h>
44#include <qcopchannel_qws.h> 44#include <qcopchannel_qws.h>
45#include <qlistview.h> 45#include <qlistview.h>
46#include <qlist.h> 46#include <qlist.h>
47#include <qpixmap.h> 47#include <qpixmap.h>
48 48
49 49
50using namespace Opie::Core;
50AppLnkSet *DocumentList::appLnkSet = 0; 51AppLnkSet *DocumentList::appLnkSet = 0;
51 52
52static const int MAX_SEARCH_DEPTH = 10; 53static const int MAX_SEARCH_DEPTH = 10;
53 54
54 55
55class DocumentListPrivate : public QObject { 56class DocumentListPrivate : public QObject {
56 Q_OBJECT 57 Q_OBJECT
57public: 58public:
58 DocumentListPrivate( ServerInterface *gui ); 59 DocumentListPrivate( ServerInterface *gui );
59 ~DocumentListPrivate(); 60 ~DocumentListPrivate();
60 61
61 void initialize(); 62 void initialize();
62 63
63 const QString nextFile(); 64 const QString nextFile();
64 const DocLnk *iterate(); 65 const DocLnk *iterate();
65 bool store( DocLnk* dl ); 66 bool store( DocLnk* dl );
66 void estimatedPercentScanned(); 67 void estimatedPercentScanned();
67 void appendDocpath(FileSystem*); 68 void appendDocpath(FileSystem*);
68 69
69 70
70 DocLnkSet dls; 71 DocLnkSet dls;
71 QDict<void> reference; 72 QDict<void> reference;
72 QDictIterator<void> *dit; 73 QDictIterator<void> *dit;
73 enum { Find, RemoveKnownFiles, MakeUnknownFiles, Done } state; 74 enum { Find, RemoveKnownFiles, MakeUnknownFiles, Done } state;
74 75
75 QStringList docPaths; 76 QStringList docPaths;
76 unsigned int docPathsSearched; 77 unsigned int docPathsSearched;
77 78
78 int searchDepth; 79 int searchDepth;
79 QDir *listDirs[MAX_SEARCH_DEPTH]; 80 QDir *listDirs[MAX_SEARCH_DEPTH];
80 const QFileInfoList *lists[MAX_SEARCH_DEPTH]; 81 const QFileInfoList *lists[MAX_SEARCH_DEPTH];
81 unsigned int listPositions[MAX_SEARCH_DEPTH]; 82 unsigned int listPositions[MAX_SEARCH_DEPTH];
82 83
83 StorageInfo *storage; 84 StorageInfo *storage;
84 85
85 int tid; 86 int tid;
86 87
87 ServerInterface *serverGui; 88 ServerInterface *serverGui;
88 89
89 bool needToSendAllDocLinks; 90 bool needToSendAllDocLinks;
90 bool sendAppLnks; 91 bool sendAppLnks;
91 bool sendDocLnks; 92 bool sendDocLnks;
92 bool scanDocs; 93 bool scanDocs;
93}; 94};
94 95
95 96
96/* 97/*
97 * scandocs will be read from Config 98 * scandocs will be read from Config
98 */ 99 */
99DocumentList::DocumentList( ServerInterface *serverGui, bool /*scanDocs*/, 100DocumentList::DocumentList( ServerInterface *serverGui, bool /*scanDocs*/,
100 QObject *parent, const char *name ) 101 QObject *parent, const char *name )
101 : QObject( parent, name ) 102 : QObject( parent, name )
102{ 103{
103 appLnkSet = new AppLnkSet( MimeType::appsFolderName() ); 104 appLnkSet = new AppLnkSet( MimeType::appsFolderName() );
104 d = new DocumentListPrivate( serverGui ); 105 d = new DocumentListPrivate( serverGui );
105 d->needToSendAllDocLinks = false; 106 d->needToSendAllDocLinks = false;
106 107
107 Config cfg( "Launcher" ); 108 Config cfg( "Launcher" );
108 cfg.setGroup( "DocTab" ); 109 cfg.setGroup( "DocTab" );
109 d->scanDocs = cfg.readBoolEntry( "Enable", true ); 110 d->scanDocs = cfg.readBoolEntry( "Enable", true );
110 qDebug( "DocumentList::DocumentList() : scanDocs = %d", d->scanDocs ); 111 qDebug( "DocumentList::DocumentList() : scanDocs = %d", d->scanDocs );
111 112
112 QTimer::singleShot( 10, this, SLOT( startInitialScan() ) ); 113 QTimer::singleShot( 10, this, SLOT( startInitialScan() ) );
113} 114}
114 115
115void DocumentList::startInitialScan() 116void DocumentList::startInitialScan()
116{ 117{
117 reloadAppLnks(); 118 reloadAppLnks();
118 reloadDocLnks(); 119 reloadDocLnks();
119} 120}
120 121
121DocumentList::~DocumentList() 122DocumentList::~DocumentList()
122{ 123{
123 delete appLnkSet; 124 delete appLnkSet;
124 delete d; 125 delete d;
125} 126}
126 127
127 128
128void DocumentList::add( const DocLnk& doc ) 129void DocumentList::add( const DocLnk& doc )
129{ 130{
130 if ( d->serverGui && QFile::exists( doc.file() ) ) 131 if ( d->serverGui && QFile::exists( doc.file() ) )
131 d->serverGui->documentAdded( doc ); 132 d->serverGui->documentAdded( doc );
132} 133}
133 134
134 135
135void DocumentList::start() 136void DocumentList::start()
136{ 137{
137 resume(); 138 resume();
138} 139}
139 140
140 141
141void DocumentList::pause() 142void DocumentList::pause()
142{ 143{
143 //qDebug("pause %i", d->tid); 144 //qDebug("pause %i", d->tid);
144 killTimer( d->tid ); 145 killTimer( d->tid );
145 d->tid = 0; 146 d->tid = 0;
146} 147}
147 148
148 149
149void DocumentList::resume() 150void DocumentList::resume()
150{ 151{
151 if ( d->tid == 0 ) { 152 if ( d->tid == 0 ) {
152 d->tid = startTimer( 20 ); 153 d->tid = startTimer( 20 );
153 //qDebug("resumed %i", d->tid); 154 //qDebug("resumed %i", d->tid);
154 } 155 }
155} 156}
156 157
157/* 158/*
158void DocumentList::resend() 159void DocumentList::resend()
159{ 160{
160 // Re-emits all the added items to the list (firstly letting everyone know to 161 // Re-emits all the added items to the list (firstly letting everyone know to
161 // clear what they have as it is being sent again) 162 // clear what they have as it is being sent again)
162 pause(); 163 pause();
163 emit allRemoved(); 164 emit allRemoved();
164 QTimer::singleShot( 5, this, SLOT( resendWorker() ) ); 165 QTimer::singleShot( 5, this, SLOT( resendWorker() ) );
165} 166}
166 167
167 168
168void DocumentList::resendWorker() 169void DocumentList::resendWorker()
169{ 170{
170 const QList<DocLnk> &list = d->dls.children(); 171 const QList<DocLnk> &list = d->dls.children();
171 for ( QListIterator<DocLnk> it( list ); it.current(); ++it ) 172 for ( QListIterator<DocLnk> it( list ); it.current(); ++it )
172 add( *(*it) ); 173 add( *(*it) );
173 resume(); 174 resume();
174} 175}
175*/ 176*/
176 177
177void DocumentList::rescan() 178void DocumentList::rescan()
178{ 179{
179 //qDebug("rescan"); 180 //qDebug("rescan");
180 pause(); 181 pause();
181 d->initialize(); 182 d->initialize();
182 resume(); 183 resume();
183} 184}
184 185
185 186
186void DocumentList::timerEvent( QTimerEvent *te ) 187void DocumentList::timerEvent( QTimerEvent *te )
187{ 188{
188 if ( te->timerId() == d->tid ) { 189 if ( te->timerId() == d->tid ) {
189 // Do 3 at a time 190 // Do 3 at a time
190 for (int i = 0; i < 3; i++ ) { 191 for (int i = 0; i < 3; i++ ) {
191 const DocLnk *lnk = d->iterate(); 192 const DocLnk *lnk = d->iterate();
192 if ( lnk ) { 193 if ( lnk ) {
193 add( *lnk ); 194 add( *lnk );
194 } else { 195 } else {
195 // stop when done 196 // stop when done
196 pause(); 197 pause();
197 if ( d->serverGui ) 198 if ( d->serverGui )
198 d->serverGui->documentScanningProgress( 100 ); 199 d->serverGui->documentScanningProgress( 100 );
199 if ( d->needToSendAllDocLinks ) 200 if ( d->needToSendAllDocLinks )
200 sendAllDocLinks(); 201 sendAllDocLinks();
201 break; 202 break;
202 } 203 }
203 } 204 }
204 } 205 }
205} 206}
206 207
207 208
208void DocumentList::reloadAppLnks() 209void DocumentList::reloadAppLnks()
209{ 210{
210 if ( d->sendAppLnks && d->serverGui ) { 211 if ( d->sendAppLnks && d->serverGui ) {
211 d->serverGui->applicationScanningProgress( 0 ); 212 d->serverGui->applicationScanningProgress( 0 );
212 d->serverGui->allApplicationsRemoved(); 213 d->serverGui->allApplicationsRemoved();
213 } 214 }
214 215
215 delete appLnkSet; 216 delete appLnkSet;
216 appLnkSet = new AppLnkSet( MimeType::appsFolderName() ); 217 appLnkSet = new AppLnkSet( MimeType::appsFolderName() );
217 218
218 if ( d->sendAppLnks && d->serverGui ) { 219 if ( d->sendAppLnks && d->serverGui ) {
219 static QStringList prevTypeList; 220 static QStringList prevTypeList;
220 QStringList types = appLnkSet->types(); 221 QStringList types = appLnkSet->types();
221 for ( QStringList::Iterator ittypes=types.begin(); ittypes!=types.end(); ++ittypes) { 222 for ( QStringList::Iterator ittypes=types.begin(); ittypes!=types.end(); ++ittypes) {
222 if ( !(*ittypes).isEmpty() ) { 223 if ( !(*ittypes).isEmpty() ) {
223 if ( !prevTypeList.contains(*ittypes) ) { 224 if ( !prevTypeList.contains(*ittypes) ) {
224 QString name = appLnkSet->typeName(*ittypes); 225 QString name = appLnkSet->typeName(*ittypes);
225 QPixmap pm = appLnkSet->typePixmap(*ittypes); 226 QPixmap pm = appLnkSet->typePixmap(*ittypes);
226 QPixmap bgPm = appLnkSet->typeBigPixmap(*ittypes); 227 QPixmap bgPm = appLnkSet->typeBigPixmap(*ittypes);
227 228
228 if (pm.isNull()) { 229 if (pm.isNull()) {
229 QImage img( Resource::loadImage( "UnknownDocument" ) ); 230 QImage img( Resource::loadImage( "UnknownDocument" ) );
230 pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); 231 pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() );
231 bgPm = img.smoothScale( AppLnk::bigIconSize(), AppLnk::bigIconSize() ); 232 bgPm = img.smoothScale( AppLnk::bigIconSize(), AppLnk::bigIconSize() );
232 } 233 }
233 234
234 //qDebug("adding type %s", (*ittypes).latin1()); 235 //qDebug("adding type %s", (*ittypes).latin1());
235 236
236 // ### our current launcher expects docs tab to be last 237 // ### our current launcher expects docs tab to be last
237 d->serverGui->typeAdded( *ittypes, name.isNull() ? (*ittypes) : name, pm, bgPm ); 238 d->serverGui->typeAdded( *ittypes, name.isNull() ? (*ittypes) : name, pm, bgPm );
238 } 239 }
239 prevTypeList.remove(*ittypes); 240 prevTypeList.remove(*ittypes);
240 } 241 }
241 } 242 }
242 for ( QStringList::Iterator ittypes=prevTypeList.begin(); ittypes!=prevTypeList.end(); ++ittypes) { 243 for ( QStringList::Iterator ittypes=prevTypeList.begin(); ittypes!=prevTypeList.end(); ++ittypes) {
243 //qDebug("removing type %s", (*ittypes).latin1()); 244 //qDebug("removing type %s", (*ittypes).latin1());
244 d->serverGui->typeRemoved(*ittypes); 245 d->serverGui->typeRemoved(*ittypes);
245 } 246 }
246 prevTypeList = types; 247 prevTypeList = types;
247 } 248 }
248 249
249 QListIterator<AppLnk> itapp( appLnkSet->children() ); 250 QListIterator<AppLnk> itapp( appLnkSet->children() );
250 AppLnk* l; 251 AppLnk* l;
251 while ( (l=itapp.current()) ) { 252 while ( (l=itapp.current()) ) {
252 ++itapp; 253 ++itapp;
253 if ( d->sendAppLnks && d->serverGui ) 254 if ( d->sendAppLnks && d->serverGui )
254 d->serverGui->applicationAdded( l->type(), *l ); 255 d->serverGui->applicationAdded( l->type(), *l );
255 } 256 }
256 257
257 if ( d->sendAppLnks && d->serverGui ) 258 if ( d->sendAppLnks && d->serverGui )
258 d->serverGui->applicationScanningProgress( 100 ); 259 d->serverGui->applicationScanningProgress( 100 );
259} 260}
260 261
261void DocumentList::reloadDocLnks() 262void DocumentList::reloadDocLnks()
262{ 263{
263 if ( !d->scanDocs ) 264 if ( !d->scanDocs )
264 return; 265 return;
265 266
266 if ( d->sendDocLnks && d->serverGui ) { 267 if ( d->sendDocLnks && d->serverGui ) {
267 d->serverGui->documentScanningProgress( 0 ); 268 d->serverGui->documentScanningProgress( 0 );
268 d->serverGui->allDocumentsRemoved(); 269 d->serverGui->allDocumentsRemoved();
269 } 270 }
270 271
271 rescan(); 272 rescan();
272} 273}
273 274
274void DocumentList::linkChanged( QString arg ) 275void DocumentList::linkChanged( QString arg )
275{ 276{
276 //qDebug( "linkchanged( %s )", arg.latin1() ); 277 //qDebug( "linkchanged( %s )", arg.latin1() );
277 278
278 if ( arg.isNull() || OGlobal::isAppLnkFileName( arg ) ) { 279 if ( arg.isNull() || OGlobal::isAppLnkFileName( arg ) ) {
279 reloadAppLnks(); 280 reloadAppLnks();
280 } else { 281 } else {
281 282
282 const QList<DocLnk> &list = d->dls.children(); 283 const QList<DocLnk> &list = d->dls.children();
283 QListIterator<DocLnk> it( list ); 284 QListIterator<DocLnk> it( list );
284 while ( it.current() ) { 285 while ( it.current() ) {
285 DocLnk *doc = it.current(); 286 DocLnk *doc = it.current();
286 ++it; 287 ++it;
287 if ( ( doc->linkFileKnown() && doc->linkFile() == arg ) 288 if ( ( doc->linkFileKnown() && doc->linkFile() == arg )
288 || ( doc->fileKnown() && doc->file() == arg ) ) { 289 || ( doc->fileKnown() && doc->file() == arg ) ) {
289 //qDebug( "found old link" ); 290 //qDebug( "found old link" );
290 DocLnk* dl = new DocLnk( arg ); 291 DocLnk* dl = new DocLnk( arg );
291 // add new one if it exists and matches the mimetype 292 // add new one if it exists and matches the mimetype
292 if ( d->store( dl ) ) { 293 if ( d->store( dl ) ) {
293 // Existing link has been changed, send old link ref and a ref 294 // Existing link has been changed, send old link ref and a ref
294 // to the new link 295 // to the new link
295 //qDebug( "change case" ); 296 //qDebug( "change case" );
296 if ( d->serverGui ) 297 if ( d->serverGui )
297 d->serverGui->documentChanged( *doc, *dl ); 298 d->serverGui->documentChanged( *doc, *dl );
298 299
299 } else { 300 } else {
300 // Link has been removed or doesn't match the mimetypes any more 301 // Link has been removed or doesn't match the mimetypes any more
301 // so we aren't interested in it, so take it away from the list 302 // so we aren't interested in it, so take it away from the list
302 //qDebug( "removal case" ); 303 //qDebug( "removal case" );
303 if ( d->serverGui ) 304 if ( d->serverGui )
304 d->serverGui->documentRemoved( *doc ); 305 d->serverGui->documentRemoved( *doc );
305 306
306 } 307 }
307 d->dls.remove( doc ); // remove old link from docLnkSet 308 d->dls.remove( doc ); // remove old link from docLnkSet
308 delete doc; 309 delete doc;
309 return; 310 return;
310 } 311 }
311 } 312 }
312 // Didn't find existing link, must be new 313 // Didn't find existing link, must be new
313 DocLnk* dl = new DocLnk( arg ); 314 DocLnk* dl = new DocLnk( arg );
314 if ( d->store( dl ) ) { 315 if ( d->store( dl ) ) {
315 // Add if it's a link we are interested in 316 // Add if it's a link we are interested in
316 //qDebug( "add case" ); 317 //qDebug( "add case" );
317 add( *dl ); 318 add( *dl );
318 } 319 }
319 320
320 } 321 }
321} 322}
322 323
323void DocumentList::restoreDone() 324void DocumentList::restoreDone()
324{ 325{
325 reloadAppLnks(); 326 reloadAppLnks();
326 reloadDocLnks(); 327 reloadDocLnks();
327} 328}
328 329
329void DocumentList::storageChanged() 330void DocumentList::storageChanged()
330{ 331{
331 // ### can implement better 332 // ### can implement better
332 reloadAppLnks(); 333 reloadAppLnks();
333 reloadDocLnks(); 334 reloadDocLnks();
334 // ### Optimization opportunity 335 // ### Optimization opportunity
335 // Could be a bit more intelligent and somehow work out which 336 // Could be a bit more intelligent and somehow work out which
336 // mtab entry has changed and then only scan that and add and remove 337 // mtab entry has changed and then only scan that and add and remove
337 // links appropriately. 338 // links appropriately.
338// rescan(); 339// rescan();
339} 340}
340 341
341void DocumentList::sendAllDocLinks() 342void DocumentList::sendAllDocLinks()
342{ 343{
343 if ( d->tid != 0 ) { 344 if ( d->tid != 0 ) {
344 // We are in the middle of scanning, set a flag so 345 // We are in the middle of scanning, set a flag so
345 // we do this when we finish our scanning 346 // we do this when we finish our scanning
346 d->needToSendAllDocLinks = true; 347 d->needToSendAllDocLinks = true;
347 return; 348 return;
348 } 349 }
349 350
350 QString contents; 351 QString contents;
351 Categories cats; 352 Categories cats;
352 for ( QListIterator<DocLnk> it( d->dls.children() ); it.current(); ++it ) { 353 for ( QListIterator<DocLnk> it( d->dls.children() ); it.current(); ++it ) {
353 DocLnk *doc = it.current(); 354 DocLnk *doc = it.current();
354 QFileInfo fi( doc->file() ); 355 QFileInfo fi( doc->file() );
355 if ( !fi.exists() ) 356 if ( !fi.exists() )
356 continue; 357 continue;
357 358
358 bool fake = !doc->linkFileKnown(); 359 bool fake = !doc->linkFileKnown();
359 if ( !fake ) { 360 if ( !fake ) {
360 QFile f( doc->linkFile() ); 361 QFile f( doc->linkFile() );
361 if ( f.open( IO_ReadOnly ) ) { 362 if ( f.open( IO_ReadOnly ) ) {
362 QTextStream ts( &f ); 363 QTextStream ts( &f );
363 ts.setEncoding( QTextStream::UnicodeUTF8 ); 364 ts.setEncoding( QTextStream::UnicodeUTF8 );
364 contents += ts.read(); 365 contents += ts.read();
365 f.close(); 366 f.close();
366 } else 367 } else
367 fake = TRUE; 368 fake = TRUE;
368 } 369 }
369 if (fake) { 370 if (fake) {
370 contents += "[Desktop Entry]\n"; // No tr 371 contents += "[Desktop Entry]\n"; // No tr
371 contents += "Categories = " + // No tr 372 contents += "Categories = " + // No tr
372 cats.labels("Document View",doc->categories()).join(";") + "\n"; // No tr 373 cats.labels("Document View",doc->categories()).join(";") + "\n"; // No tr
373 contents += "Name = "+doc->name()+"\n"; // No tr 374 contents += "Name = "+doc->name()+"\n"; // No tr
374 contents += "Type = "+doc->type()+"\n"; // No tr 375 contents += "Type = "+doc->type()+"\n"; // No tr
375 } 376 }
376 contents += "File = "+doc->file()+"\n"; // No tr // (resolves path) 377 contents += "File = "+doc->file()+"\n"; // No tr // (resolves path)
377 contents += QString("Size = %1\n").arg( fi.size() ); // No tr 378 contents += QString("Size = %1\n").arg( fi.size() ); // No tr
378 } 379 }
379 380
380 //qDebug( "sending length %d", contents.length() ); 381 //qDebug( "sending length %d", contents.length() );
381#ifndef QT_NO_COP 382#ifndef QT_NO_COP
382 QCopEnvelope e( "QPE/Desktop", "docLinks(QString)" ); 383 QCopEnvelope e( "QPE/Desktop", "docLinks(QString)" );
383 e << contents; 384 e << contents;
384#endif 385#endif
385 //qDebug( "================ \n\n%s\n\n===============", contents.latin1() ); 386 //qDebug( "================ \n\n%s\n\n===============", contents.latin1() );
386 387
387 d->needToSendAllDocLinks = false; 388 d->needToSendAllDocLinks = false;
388} 389}
389 390
390 391
391 392
392 393
393 394
394 395
395 396
396 397
397 398
398 399
399 400
400 401
401 402
402 403
403 404
404 405
405 406
406 407
407 408
408 409
409 410
410 411
411 412
412 413
413DocumentListPrivate::DocumentListPrivate( ServerInterface *gui ) 414DocumentListPrivate::DocumentListPrivate( ServerInterface *gui )
414{ 415{
415 storage = new StorageInfo( this ); 416 storage = new StorageInfo( this );
416 serverGui = gui; 417 serverGui = gui;
417 if ( serverGui ) { 418 if ( serverGui ) {
418 sendAppLnks = serverGui->requiresApplications(); 419 sendAppLnks = serverGui->requiresApplications();
419 sendDocLnks = serverGui->requiresDocuments(); 420 sendDocLnks = serverGui->requiresDocuments();
420 } else { 421 } else {
421 sendAppLnks = false; 422 sendAppLnks = false;
422 sendDocLnks = false; 423 sendDocLnks = false;
423 } 424 }
424 for ( int i = 0; i < MAX_SEARCH_DEPTH; i++ ) { 425 for ( int i = 0; i < MAX_SEARCH_DEPTH; i++ ) {
425 listDirs[i] = 0; 426 listDirs[i] = 0;
426 lists[i] = 0; 427 lists[i] = 0;
427 listPositions[i] = 0; 428 listPositions[i] = 0;
428 } 429 }
429 initialize(); 430 initialize();
430 tid = 0; 431 tid = 0;
431} 432}
432 433
433void DocumentListPrivate::appendDocpath(FileSystem*fs) 434void DocumentListPrivate::appendDocpath(FileSystem*fs)
434{ 435{
435 QDir defPath(fs->path()+"/Documents"); 436 QDir defPath(fs->path()+"/Documents");
436 QFileInfo f(fs->path()+"/.opiestorage.cf"); 437 QFileInfo f(fs->path()+"/.opiestorage.cf");
437 if (!f.exists()) { 438 if (!f.exists()) {
438 Mediadlg dlg(fs); 439 Mediadlg dlg(fs);
439 if (QDialog::Accepted != QPEApplication::execDialog( &dlg )) { 440 if (QDialog::Accepted != QPEApplication::execDialog( &dlg )) {
440 return; 441 return;
441 } 442 }
442 } 443 }
443 Config conf(f.filePath(), Config::File ); 444 Config conf(f.filePath(), Config::File );
444 conf.setGroup("main"); 445 conf.setGroup("main");
445 if (!conf.readBoolEntry("check",false)) { 446 if (!conf.readBoolEntry("check",false)) {
446 return; 447 return;
447 } 448 }
448 conf.setGroup("subdirs"); 449 conf.setGroup("subdirs");
449 bool read_all = conf.readBoolEntry("wholemedia",true); 450 bool read_all = conf.readBoolEntry("wholemedia",true);
450 if (read_all) { 451 if (read_all) {
451 docPaths+=fs->path(); 452 docPaths+=fs->path();
452 return; 453 return;
453 } 454 }
454 QStringList subDirs = conf.readListEntry("subdirs",':'); 455 QStringList subDirs = conf.readListEntry("subdirs",':');
455 if (subDirs.isEmpty()) { 456 if (subDirs.isEmpty()) {
456 if (defPath.exists()) { 457 if (defPath.exists()) {
457 docPaths+=defPath.path(); 458 docPaths+=defPath.path();
458 } 459 }
459 return; 460 return;
460 } 461 }
461 for (unsigned c = 0; c < subDirs.count();++c) { 462 for (unsigned c = 0; c < subDirs.count();++c) {
462 QDir docDir(QString(fs->path()+"/"+subDirs[c])); 463 QDir docDir(QString(fs->path()+"/"+subDirs[c]));
463 if (docDir.exists()) { 464 if (docDir.exists()) {
464 docPaths+=docDir.path(); 465 docPaths+=docDir.path();
465 } 466 }
466 } 467 }
467} 468}
468 469
469void DocumentListPrivate::initialize() 470void DocumentListPrivate::initialize()
470{ 471{
471 // Reset 472 // Reset
472 dls.clear(); 473 dls.clear();
473 docPaths.clear(); 474 docPaths.clear();
474 reference.clear(); 475 reference.clear();
475 476
476 QDir docDir( QPEApplication::documentDir() ); 477 QDir docDir( QPEApplication::documentDir() );
477 if ( docDir.exists() ) 478 if ( docDir.exists() )
478 docPaths += QPEApplication::documentDir(); 479 docPaths += QPEApplication::documentDir();
479 int i = 1; 480 int i = 1;
480 const QList<FileSystem> &fs = storage->fileSystems(); 481 const QList<FileSystem> &fs = storage->fileSystems();
481 QListIterator<FileSystem> it( fs ); 482 QListIterator<FileSystem> it( fs );
482 for ( ; it.current(); ++it ) { 483 for ( ; it.current(); ++it ) {
483 if ( (*it)->isRemovable() ) { 484 if ( (*it)->isRemovable() ) {
484 appendDocpath((*it)); 485 appendDocpath((*it));
485 ++i; 486 ++i;
486 } 487 }
487 } 488 }
488 489
489 for ( int i = 0; i < MAX_SEARCH_DEPTH; ++i ) { 490 for ( int i = 0; i < MAX_SEARCH_DEPTH; ++i ) {
490 if ( listDirs[i] ) { 491 if ( listDirs[i] ) {
491 delete listDirs[i]; 492 delete listDirs[i];
492 listDirs[i] = 0; 493 listDirs[i] = 0;
493 } 494 }
494 lists[i] = 0; 495 lists[i] = 0;
495 listPositions[i] = 0; 496 listPositions[i] = 0;
496 } 497 }
497 498
498 docPathsSearched = 0; 499 docPathsSearched = 0;
499 searchDepth = -1; 500 searchDepth = -1;
500 state = Find; 501 state = Find;
501 dit = 0; 502 dit = 0;
502} 503}
503 504
504 505
505DocumentListPrivate::~DocumentListPrivate() 506DocumentListPrivate::~DocumentListPrivate()
506{ 507{
507 for ( int i = 0; i < MAX_SEARCH_DEPTH; i++ ) 508 for ( int i = 0; i < MAX_SEARCH_DEPTH; i++ )
508 if ( listDirs[i] ) 509 if ( listDirs[i] )
509 delete listDirs[i]; 510 delete listDirs[i];
510 delete dit; 511 delete dit;
511} 512}
512 513
513 514
514void DocumentListPrivate::estimatedPercentScanned() 515void DocumentListPrivate::estimatedPercentScanned()
515{ 516{
516 double overallProgress = 0.0; 517 double overallProgress = 0.0;
517 double levelWeight = 75.0; 518 double levelWeight = 75.0;
518 519
519 int topCount = docPaths.count(); 520 int topCount = docPaths.count();
520 if ( topCount > 1 ) { 521 if ( topCount > 1 ) {
521 levelWeight = levelWeight / topCount; 522 levelWeight = levelWeight / topCount;
522 overallProgress += (docPathsSearched - 1) * levelWeight; 523 overallProgress += (docPathsSearched - 1) * levelWeight;
523 } 524 }
524 525
525 for ( int d = 0; d <= searchDepth; d++ ) { 526 for ( int d = 0; d <= searchDepth; d++ ) {
526 if ( listDirs[d] ) { 527 if ( listDirs[d] ) {
527 int items = lists[d]->count(); 528 int items = lists[d]->count();
528 if ( items > 1 ) { 529 if ( items > 1 ) {
529 levelWeight = levelWeight / items; 530 levelWeight = levelWeight / items;
530 // Take in to account "." and ".." 531 // Take in to account "." and ".."
531 overallProgress += (listPositions[d] - 3) * levelWeight; 532 overallProgress += (listPositions[d] - 3) * levelWeight;
532 } 533 }
533 } else { 534 } else {
534 break; 535 break;
535 } 536 }
536 } 537 }
537 538
538 // qDebug( "overallProgress: %f", overallProgress ); 539 // qDebug( "overallProgress: %f", overallProgress );
539 540
540 if ( serverGui ) 541 if ( serverGui )
541 serverGui->documentScanningProgress( (int)overallProgress ); 542 serverGui->documentScanningProgress( (int)overallProgress );
542} 543}
543 544
544 545
545const QString DocumentListPrivate::nextFile() 546const QString DocumentListPrivate::nextFile()
546{ 547{
547 while ( TRUE ) { 548 while ( TRUE ) {
548 while ( searchDepth < 0 ) { 549 while ( searchDepth < 0 ) {
549 // go to next base path 550 // go to next base path
550 if ( docPathsSearched >= docPaths.count() ) { 551 if ( docPathsSearched >= docPaths.count() ) {
551 // end of base paths 552 // end of base paths
552 return QString::null; 553 return QString::null;
553 } else { 554 } else {
554 QDir dir( docPaths[docPathsSearched] ); 555 QDir dir( docPaths[docPathsSearched] );
555 // qDebug("now using base path: %s", docPaths[docPathsSearched].latin1() ); 556 // qDebug("now using base path: %s", docPaths[docPathsSearched].latin1() );
556 docPathsSearched++; 557 docPathsSearched++;
557 if ( !dir.exists( ".Qtopia-ignore" ) ) { 558 if ( !dir.exists( ".Qtopia-ignore" ) ) {
558 listDirs[0] = new QDir( dir ); 559 listDirs[0] = new QDir( dir );
559 lists[0] = listDirs[0]->entryInfoList(); 560 lists[0] = listDirs[0]->entryInfoList();
560 listPositions[0] = 0; 561 listPositions[0] = 0;
561 searchDepth = 0; 562 searchDepth = 0;
diff --git a/core/launcher/main.cpp b/core/launcher/main.cpp
index c136bd9..3e7e0d2 100644
--- a/core/launcher/main.cpp
+++ b/core/launcher/main.cpp
@@ -1,352 +1,352 @@
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 QTOPIA_INTERNAL_FILEOPERATIONS 21#ifndef QTOPIA_INTERNAL_FILEOPERATIONS
22#define QTOPIA_INTERNAL_FILEOPERATIONS 22#define QTOPIA_INTERNAL_FILEOPERATIONS
23#endif 23#endif
24#include "server.h" 24#include "server.h"
25#include "serverapp.h" 25#include "serverapp.h"
26#include "stabmon.h" 26#include "stabmon.h"
27#include "firstuse.h" 27#include "firstuse.h"
28 28
29#include <opie2/oglobal.h> 29#include <opie2/oglobal.h>
30 30
31#include <qtopia/network.h> 31#include <qtopia/network.h>
32//#include <qtopia/custom.h> 32//#include <qtopia/custom.h>
33 33
34 34
35#include <qdir.h> 35#include <qdir.h>
36#ifdef QWS 36#ifdef QWS
37#include <qwindowsystem_qws.h> 37#include <qwindowsystem_qws.h>
38#include <qtopia/qcopenvelope_qws.h> 38#include <qtopia/qcopenvelope_qws.h>
39#endif 39#endif
40#include <qtopia/alarmserver.h> 40#include <qtopia/alarmserver.h>
41 41
42#include <stdlib.h> 42#include <stdlib.h>
43#include <stdio.h> 43#include <stdio.h>
44#include <signal.h> 44#include <signal.h>
45#ifndef Q_OS_WIN32 45#ifndef Q_OS_WIN32
46#include <unistd.h> 46#include <unistd.h>
47#else 47#else
48#include <process.h> 48#include <process.h>
49#endif 49#endif
50 50
51#include "calibrate.h" 51#include "calibrate.h"
52 52
53 53
54#ifdef QT_QWS_LOGIN 54#ifdef QT_QWS_LOGIN
55#include "../login/qdmdialogimpl.h" 55#include "../login/qdmdialogimpl.h"
56#endif 56#endif
57 57
58#ifdef Q_WS_QWS 58#ifdef Q_WS_QWS
59#include <qkeyboard_qws.h> 59#include <qkeyboard_qws.h>
60#endif 60#endif
61 61
62#include <qmessagebox.h> 62#include <qmessagebox.h>
63#include <opie2/odevice.h> 63#include <opie2/odevice.h>
64 64
65using namespace Opie; 65using namespace Opie::Core;
66 66
67 67
68static void cleanup() 68static void cleanup()
69{ 69{
70 QDir dir( "/tmp", "qcop-msg-*" ); 70 QDir dir( "/tmp", "qcop-msg-*" );
71 71
72 QStringList stale = dir.entryList(); 72 QStringList stale = dir.entryList();
73 QStringList::Iterator it; 73 QStringList::Iterator it;
74 for ( it = stale.begin(); it != stale.end(); ++it ) { 74 for ( it = stale.begin(); it != stale.end(); ++it ) {
75 dir.remove( *it ); 75 dir.remove( *it );
76 } 76 }
77} 77}
78 78
79static void refreshTimeZoneConfig() 79static void refreshTimeZoneConfig()
80{ 80{
81 /* ### FIXME timezone handling */ 81 /* ### FIXME timezone handling */
82#if 0 82#if 0
83 // We need to help WorldTime in setting up its configuration for 83 // We need to help WorldTime in setting up its configuration for
84 // the current translation 84 // the current translation
85 // BEGIN no tr 85 // BEGIN no tr
86 const char *defaultTz[] = { 86 const char *defaultTz[] = {
87 "America/New_York", 87 "America/New_York",
88 "America/Los_Angeles", 88 "America/Los_Angeles",
89 "Europe/Oslo", 89 "Europe/Oslo",
90 "Asia/Tokyo", 90 "Asia/Tokyo",
91 "Asia/Hong_Kong", 91 "Asia/Hong_Kong",
92 "Australia/Brisbane", 92 "Australia/Brisbane",
93 0 93 0
94 }; 94 };
95 // END no tr 95 // END no tr
96 96
97 TimeZone curZone; 97 TimeZone curZone;
98 QString zoneID; 98 QString zoneID;
99 int zoneIndex; 99 int zoneIndex;
100 Config cfg = Config( "WorldTime" ); 100 Config cfg = Config( "WorldTime" );
101 cfg.setGroup( "TimeZones" ); 101 cfg.setGroup( "TimeZones" );
102 if (!cfg.hasKey( "Zone0" )){ 102 if (!cfg.hasKey( "Zone0" )){
103 // We have no existing timezones use the defaults which are untranslated strings 103 // We have no existing timezones use the defaults which are untranslated strings
104 QString currTz = TimeZone::current().id(); 104 QString currTz = TimeZone::current().id();
105 QStringList zoneDefaults; 105 QStringList zoneDefaults;
106 zoneDefaults.append( currTz ); 106 zoneDefaults.append( currTz );
107 for ( int i = 0; defaultTz[i] && zoneDefaults.count() < 6; i++ ) { 107 for ( int i = 0; defaultTz[i] && zoneDefaults.count() < 6; i++ ) {
108 if ( defaultTz[i] != currTz ) 108 if ( defaultTz[i] != currTz )
109 zoneDefaults.append( defaultTz[i] ); 109 zoneDefaults.append( defaultTz[i] );
110 } 110 }
111 zoneIndex = 0; 111 zoneIndex = 0;
112 for (QStringList::Iterator it = zoneDefaults.begin(); it != zoneDefaults.end() ; ++it){ 112 for (QStringList::Iterator it = zoneDefaults.begin(); it != zoneDefaults.end() ; ++it){
113 cfg.writeEntry( "Zone" + QString::number( zoneIndex ) , *it); 113 cfg.writeEntry( "Zone" + QString::number( zoneIndex ) , *it);
114 zoneIndex++; 114 zoneIndex++;
115 } 115 }
116 } 116 }
117 // We have an existing list of timezones refresh the 117 // We have an existing list of timezones refresh the
118 // translations of TimeZone name 118 // translations of TimeZone name
119 zoneIndex = 0; 119 zoneIndex = 0;
120 while (cfg.hasKey( "Zone"+ QString::number( zoneIndex ))){ 120 while (cfg.hasKey( "Zone"+ QString::number( zoneIndex ))){
121 zoneID = cfg.readEntry( "Zone" + QString::number( zoneIndex )); 121 zoneID = cfg.readEntry( "Zone" + QString::number( zoneIndex ));
122 curZone = TimeZone( zoneID ); 122 curZone = TimeZone( zoneID );
123 if ( !curZone.isValid() ){ 123 if ( !curZone.isValid() ){
124 qDebug( "initEnvironment() Invalid TimeZone %s", zoneID.latin1() ); 124 qDebug( "initEnvironment() Invalid TimeZone %s", zoneID.latin1() );
125 break; 125 break;
126 } 126 }
127 cfg.writeEntry( "ZoneName" + QString::number( zoneIndex ), curZone.city() ); 127 cfg.writeEntry( "ZoneName" + QString::number( zoneIndex ), curZone.city() );
128 zoneIndex++; 128 zoneIndex++;
129 } 129 }
130#endif 130#endif
131} 131}
132 132
133void initEnvironment() 133void initEnvironment()
134{ 134{
135#ifdef Q_OS_WIN32 135#ifdef Q_OS_WIN32
136 // Config file requires HOME dir which uses QDir which needs the winver 136 // Config file requires HOME dir which uses QDir which needs the winver
137 qt_init_winver(); 137 qt_init_winver();
138#endif 138#endif
139 Config config("locale"); 139 Config config("locale");
140 config.setGroup( "Location" ); 140 config.setGroup( "Location" );
141 QString tz = config.readEntry( "Timezone", getenv("TZ") ).stripWhiteSpace(); 141 QString tz = config.readEntry( "Timezone", getenv("TZ") ).stripWhiteSpace();
142 142
143 // if not timezone set, pick New York 143 // if not timezone set, pick New York
144 if (tz.isNull() || tz.isEmpty()) 144 if (tz.isNull() || tz.isEmpty())
145 tz = "America/New_York"; 145 tz = "America/New_York";
146 146
147 setenv( "TZ", tz, 1 ); 147 setenv( "TZ", tz, 1 );
148 config.writeEntry( "Timezone", tz); 148 config.writeEntry( "Timezone", tz);
149 149
150 config.setGroup( "Language" ); 150 config.setGroup( "Language" );
151 QString lang = config.readEntry( "Language", getenv("LANG") ).stripWhiteSpace(); 151 QString lang = config.readEntry( "Language", getenv("LANG") ).stripWhiteSpace();
152 if( lang.isNull() || lang.isEmpty()) 152 if( lang.isNull() || lang.isEmpty())
153 lang = "en_US"; 153 lang = "en_US";
154 154
155 setenv( "LANG", lang, 1 ); 155 setenv( "LANG", lang, 1 );
156 config.writeEntry("Language", lang); 156 config.writeEntry("Language", lang);
157 config.write(); 157 config.write();
158 158
159#if 0 159#if 0
160 setenv( "QWS_SIZE", "240x320", 0 ); 160 setenv( "QWS_SIZE", "240x320", 0 );
161#endif 161#endif
162 162
163 163
164 164
165 QString env(getenv("QWS_DISPLAY")); 165 QString env(getenv("QWS_DISPLAY"));
166 if (env.contains("Transformed")) { 166 if (env.contains("Transformed")) {
167 int rot; 167 int rot;
168 // transformed driver default rotation is controlled by the hardware. 168 // transformed driver default rotation is controlled by the hardware.
169 Config config("qpe"); 169 Config config("qpe");
170 config.setGroup( "Rotation" ); 170 config.setGroup( "Rotation" );
171 if ( ( rot = config.readNumEntry( "Rot", -1 ) ) == -1 ) 171 if ( ( rot = config.readNumEntry( "Rot", -1 ) ) == -1 )
172 rot = ODevice::inst ( )-> rotation ( ) * 90; 172 rot = ODevice::inst ( )-> rotation ( ) * 90;
173 173
174 setenv("QWS_DISPLAY", QString("Transformed:Rot%1:0").arg(rot), 1); 174 setenv("QWS_DISPLAY", QString("Transformed:Rot%1:0").arg(rot), 1);
175 QPEApplication::defaultRotation ( ); /* to ensure deforient matches reality */ 175 QPEApplication::defaultRotation ( ); /* to ensure deforient matches reality */
176 } 176 }
177} 177}
178 178
179static void initKeyboard() 179static void initKeyboard()
180{ 180{
181 Config config("qpe"); 181 Config config("qpe");
182 182
183 config.setGroup( "Keyboard" ); 183 config.setGroup( "Keyboard" );
184 184
185 int ard = config.readNumEntry( "RepeatDelay" ); 185 int ard = config.readNumEntry( "RepeatDelay" );
186 int arp = config.readNumEntry( "RepeatPeriod" ); 186 int arp = config.readNumEntry( "RepeatPeriod" );
187 if ( ard > 0 && arp > 0 ) 187 if ( ard > 0 && arp > 0 )
188 qwsSetKeyboardAutoRepeat( ard, arp ); 188 qwsSetKeyboardAutoRepeat( ard, arp );
189 189
190 QString layout = config.readEntry( "Layout", "us101" ); 190 QString layout = config.readEntry( "Layout", "us101" );
191 Server::setKeyboardLayout( layout ); 191 Server::setKeyboardLayout( layout );
192} 192}
193 193
194static bool firstUse() 194static bool firstUse()
195{ 195{
196 bool needFirstUse = FALSE; 196 bool needFirstUse = FALSE;
197 if ( QWSServer::mouseHandler() && 197 if ( QWSServer::mouseHandler() &&
198 QWSServer::mouseHandler() ->inherits("QCalibratedMouseHandler") ) { 198 QWSServer::mouseHandler() ->inherits("QCalibratedMouseHandler") ) {
199 if ( !QFile::exists( "/etc/pointercal" ) ) 199 if ( !QFile::exists( "/etc/pointercal" ) )
200 needFirstUse = TRUE; 200 needFirstUse = TRUE;
201 } 201 }
202 202
203 { 203 {
204 Config config( "qpe" ); 204 Config config( "qpe" );
205 config.setGroup( "Startup" ); 205 config.setGroup( "Startup" );
206 needFirstUse |= config.readBoolEntry( "FirstUse", TRUE ); 206 needFirstUse |= config.readBoolEntry( "FirstUse", TRUE );
207 } 207 }
208 208
209 if ( !needFirstUse ) 209 if ( !needFirstUse )
210 return FALSE; 210 return FALSE;
211 211
212 FirstUse *fu = new FirstUse(); 212 FirstUse *fu = new FirstUse();
213 fu->exec(); 213 fu->exec();
214 bool rs = fu->restartNeeded(); 214 bool rs = fu->restartNeeded();
215 delete fu; 215 delete fu;
216 return rs; 216 return rs;
217} 217}
218 218
219int initApplication( int argc, char ** argv ) 219int initApplication( int argc, char ** argv )
220{ 220{
221 cleanup(); 221 cleanup();
222 222
223 223
224 initEnvironment(); 224 initEnvironment();
225 225
226 //Don't flicker at startup: 226 //Don't flicker at startup:
227#ifdef QWS 227#ifdef QWS
228 QWSServer::setDesktopBackground( QImage() ); 228 QWSServer::setDesktopBackground( QImage() );
229#endif 229#endif
230 ServerApplication a( argc, argv, QApplication::GuiServer ); 230 ServerApplication a( argc, argv, QApplication::GuiServer );
231 231
232 refreshTimeZoneConfig(); 232 refreshTimeZoneConfig();
233 233
234 initKeyboard(); 234 initKeyboard();
235 235
236 // Don't use first use under Windows 236 // Don't use first use under Windows
237 if ( firstUse() ) { 237 if ( firstUse() ) {
238 a.restart(); 238 a.restart();
239 return 0; 239 return 0;
240 } 240 }
241 241
242 ODevice::inst ( )-> setSoftSuspend ( true ); 242 ODevice::inst ( )-> setSoftSuspend ( true );
243 243
244 { 244 {
245 QCopEnvelope e("QPE/System", "setBacklight(int)" ); 245 QCopEnvelope e("QPE/System", "setBacklight(int)" );
246 e << -3; // Forced on 246 e << -3; // Forced on
247 } 247 }
248 248
249 AlarmServer::initialize(); 249 AlarmServer::initialize();
250 250
251 251
252 252
253 Server *s = new Server(); 253 Server *s = new Server();
254 254
255 (void)new SysFileMonitor(s); 255 (void)new SysFileMonitor(s);
256#ifdef QWS 256#ifdef QWS
257 Network::createServer(s); 257 Network::createServer(s);
258#endif 258#endif
259 259
260 s->show(); 260 s->show();
261 261
262 /* THE ARM rtc has problem holdings the time on reset */ 262 /* THE ARM rtc has problem holdings the time on reset */
263 if ( QDate::currentDate ( ). year ( ) < 2000 ) { 263 if ( QDate::currentDate ( ). year ( ) < 2000 ) {
264 if ( QMessageBox::information ( 0, ServerApplication::tr( "Information" ), ServerApplication::tr( "<p>The system date doesn't seem to be valid.\n(%1)</p><p>Do you want to correct the clock ?</p>" ). arg( TimeString::dateString ( QDate::currentDate ( ))), QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes ) { 264 if ( QMessageBox::information ( 0, ServerApplication::tr( "Information" ), ServerApplication::tr( "<p>The system date doesn't seem to be valid.\n(%1)</p><p>Do you want to correct the clock ?</p>" ). arg( TimeString::dateString ( QDate::currentDate ( ))), QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes ) {
265 QCopEnvelope e ( "QPE/Application/systemtime", "setDocument(QString)" ); 265 QCopEnvelope e ( "QPE/Application/systemtime", "setDocument(QString)" );
266 e << QString ( ); 266 e << QString ( );
267 } 267 }
268 } 268 }
269 269
270 int rv = a.exec(); 270 int rv = a.exec();
271 271
272 qDebug("exiting..."); 272 qDebug("exiting...");
273 delete s; 273 delete s;
274 274
275#ifndef Q_OS_MACX 275#ifndef Q_OS_MACX
276 ODevice::inst()->setSoftSuspend( false ); 276 ODevice::inst()->setSoftSuspend( false );
277#endif 277#endif
278 278
279 return rv; 279 return rv;
280} 280}
281 281
282static const char *pidfile_path = "/var/run/opie.pid"; 282static const char *pidfile_path = "/var/run/opie.pid";
283 283
284void create_pidfile ( ) 284void create_pidfile ( )
285{ 285{
286 FILE *f; 286 FILE *f;
287 287
288 if (( f = ::fopen ( pidfile_path, "w" ))) { 288 if (( f = ::fopen ( pidfile_path, "w" ))) {
289 ::fprintf ( f, "%d", getpid ( )); 289 ::fprintf ( f, "%d", getpid ( ));
290 ::fclose ( f ); 290 ::fclose ( f );
291 } 291 }
292} 292}
293 293
294void remove_pidfile ( ) 294void remove_pidfile ( )
295{ 295{
296 ::unlink ( pidfile_path ); 296 ::unlink ( pidfile_path );
297} 297}
298 298
299void handle_sigterm ( int /* sig */ ) 299void handle_sigterm ( int /* sig */ )
300{ 300{
301 if ( qApp ) 301 if ( qApp )
302 qApp-> quit ( ); 302 qApp-> quit ( );
303} 303}
304 304
305#ifndef Q_OS_WIN32 305#ifndef Q_OS_WIN32
306int main( int argc, char ** argv ) 306int main( int argc, char ** argv )
307{ 307{
308 308
309 ::signal ( SIGCHLD, SIG_IGN ); 309 ::signal ( SIGCHLD, SIG_IGN );
310 310
311 ::signal ( SIGTERM, handle_sigterm ); 311 ::signal ( SIGTERM, handle_sigterm );
312 ::signal ( SIGINT, handle_sigterm ); 312 ::signal ( SIGINT, handle_sigterm );
313 313
314 ::setsid ( ); 314 ::setsid ( );
315 ::setpgid ( 0, 0 ); 315 ::setpgid ( 0, 0 );
316 316
317 ::atexit ( remove_pidfile ); 317 ::atexit ( remove_pidfile );
318 create_pidfile ( ); 318 create_pidfile ( );
319 319
320 int retVal = initApplication( argc, argv ); 320 int retVal = initApplication( argc, argv );
321 321
322 // Have we been asked to restart? 322 // Have we been asked to restart?
323 if ( ServerApplication::doRestart ) { 323 if ( ServerApplication::doRestart ) {
324 for ( int fd = 3; fd < 100; fd++ ) 324 for ( int fd = 3; fd < 100; fd++ )
325 close( fd ); 325 close( fd );
326 326
327 execl( (QPEApplication::qpeDir()+"bin/qpe").latin1(), "qpe", 0 ); 327 execl( (QPEApplication::qpeDir()+"bin/qpe").latin1(), "qpe", 0 );
328 } 328 }
329 329
330 // Kill them. Kill them all. 330 // Kill them. Kill them all.
331 ::kill ( 0, SIGTERM ); 331 ::kill ( 0, SIGTERM );
332 ::sleep ( 1 ); 332 ::sleep ( 1 );
333 ::kill ( 0, SIGKILL ); 333 ::kill ( 0, SIGKILL );
334 334
335 return retVal; 335 return retVal;
336} 336}
337#else 337#else
338 338
339int main( int argc, char ** argv ) 339int main( int argc, char ** argv )
340{ 340{
341 int retVal = initApplication( argc, argv ); 341 int retVal = initApplication( argc, argv );
342 342
343 if ( DesktopApplication::doRestart ) { 343 if ( DesktopApplication::doRestart ) {
344 qDebug("Trying to restart"); 344 qDebug("Trying to restart");
345 execl( (QPEApplication::qpeDir()+"bin\\qpe").latin1(), "qpe", 0 ); 345 execl( (QPEApplication::qpeDir()+"bin\\qpe").latin1(), "qpe", 0 );
346 } 346 }
347 347
348 return retVal; 348 return retVal;
349} 349}
350 350
351#endif 351#endif
352 352
diff --git a/core/launcher/qcopbridge.cpp b/core/launcher/qcopbridge.cpp
index 53efba4..33df6c4 100644
--- a/core/launcher/qcopbridge.cpp
+++ b/core/launcher/qcopbridge.cpp
@@ -1,490 +1,491 @@
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 "qcopbridge.h" 21#include "qcopbridge.h"
22#include "transferserver.h" 22#include "transferserver.h"
23 23
24#include <opie2/oglobal.h> 24#include <opie2/oglobal.h>
25 25
26#ifdef Q_WS_QWS 26#ifdef Q_WS_QWS
27#include <qtopia/qcopenvelope_qws.h> 27#include <qtopia/qcopenvelope_qws.h>
28#endif 28#endif
29#include <qtopia/qpeapplication.h> 29#include <qtopia/qpeapplication.h>
30 30
31#include <qtopia/version.h> 31#include <qtopia/version.h>
32 32
33#include <qtextstream.h> 33#include <qtextstream.h>
34#include <qtimer.h> 34#include <qtimer.h>
35#ifdef Q_WS_QWS 35#ifdef Q_WS_QWS
36#include <qcopchannel_qws.h> 36#include <qcopchannel_qws.h>
37#endif 37#endif
38 38
39#ifndef _XOPEN_SOURCE 39#ifndef _XOPEN_SOURCE
40#define _XOPEN_SOURCE 40#define _XOPEN_SOURCE
41#endif 41#endif
42#ifndef Q_OS_WIN32 42#ifndef Q_OS_WIN32
43#include <pwd.h> 43#include <pwd.h>
44#include <unistd.h> 44#include <unistd.h>
45#include <sys/types.h> 45#include <sys/types.h>
46#endif 46#endif
47 47
48#if defined(_OS_LINUX_) 48#if defined(_OS_LINUX_)
49#include <shadow.h> 49#include <shadow.h>
50#endif 50#endif
51 51
52 52
53//#define INSECURE 53//#define INSECURE
54 54
55const int block_size = 51200; 55const int block_size = 51200;
56 56
57using namespace Opie::Core;
57QCopBridge::QCopBridge( Q_UINT16 port, QObject *parent, 58QCopBridge::QCopBridge( Q_UINT16 port, QObject *parent,
58 const char* name ) 59 const char* name )
59 : QServerSocket( port, 1, parent, name ), 60 : QServerSocket( port, 1, parent, name ),
60 desktopChannel( 0 ), 61 desktopChannel( 0 ),
61 cardChannel( 0 ) 62 cardChannel( 0 )
62{ 63{
63 if ( !ok() ) 64 if ( !ok() )
64 qWarning( "Failed to bind to port %d", port ); 65 qWarning( "Failed to bind to port %d", port );
65 else { 66 else {
66#ifndef QT_NO_COP 67#ifndef QT_NO_COP
67 desktopChannel = new QCopChannel( "QPE/Desktop", this ); 68 desktopChannel = new QCopChannel( "QPE/Desktop", this );
68 connect( desktopChannel, SIGNAL(received(const QCString&,const QByteArray&)), 69 connect( desktopChannel, SIGNAL(received(const QCString&,const QByteArray&)),
69 this, SLOT(desktopMessage(const QCString&,const QByteArray&)) ); 70 this, SLOT(desktopMessage(const QCString&,const QByteArray&)) );
70 cardChannel = new QCopChannel( "QPE/Card", this ); 71 cardChannel = new QCopChannel( "QPE/Card", this );
71 connect( cardChannel, SIGNAL(received(const QCString&,const QByteArray&)), 72 connect( cardChannel, SIGNAL(received(const QCString&,const QByteArray&)),
72 this, SLOT(desktopMessage(const QCString&,const QByteArray&)) ); 73 this, SLOT(desktopMessage(const QCString&,const QByteArray&)) );
73#endif 74#endif
74 } 75 }
75 sendSync = FALSE; 76 sendSync = FALSE;
76 openConnections.setAutoDelete( TRUE ); 77 openConnections.setAutoDelete( TRUE );
77 authorizeConnections(); 78 authorizeConnections();
78} 79}
79 80
80QCopBridge::~QCopBridge() 81QCopBridge::~QCopBridge()
81{ 82{
82#ifndef QT_NO_COP 83#ifndef QT_NO_COP
83 delete desktopChannel; 84 delete desktopChannel;
84#endif 85#endif
85} 86}
86 87
87void QCopBridge::authorizeConnections() 88void QCopBridge::authorizeConnections()
88{ 89{
89 Config cfg("Security"); 90 Config cfg("Security");
90 cfg.setGroup("SyncMode"); 91 cfg.setGroup("SyncMode");
91 m_mode = Mode(cfg.readNumEntry("Mode", Sharp )); 92 m_mode = Mode(cfg.readNumEntry("Mode", Sharp ));
92 QListIterator<QCopBridgePI> it(openConnections); 93 QListIterator<QCopBridgePI> it(openConnections);
93 while ( it.current() ) { 94 while ( it.current() ) {
94 if ( !it.current()->verifyAuthorised() ) { 95 if ( !it.current()->verifyAuthorised() ) {
95 disconnect ( it.current(), SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( closed(QCopBridgePI*) ) ); 96 disconnect ( it.current(), SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( closed(QCopBridgePI*) ) );
96 openConnections.removeRef( it.current() ); 97 openConnections.removeRef( it.current() );
97 } else 98 } else
98 ++it; 99 ++it;
99 } 100 }
100} 101}
101 102
102void QCopBridge::newConnection( int socket ) 103void QCopBridge::newConnection( int socket )
103{ 104{
104 QCopBridgePI *pi = new QCopBridgePI( socket, this ); 105 QCopBridgePI *pi = new QCopBridgePI( socket, this );
105 openConnections.append( pi ); 106 openConnections.append( pi );
106 connect ( pi, SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( closed(QCopBridgePI*) ) ); 107 connect ( pi, SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( closed(QCopBridgePI*) ) );
107 108
108 /* ### libqtopia merge FIXME */ 109 /* ### libqtopia merge FIXME */
109#if 0 110#if 0
110 QPEApplication::setTempScreenSaverMode( QPEApplication::DisableSuspend ); 111 QPEApplication::setTempScreenSaverMode( QPEApplication::DisableSuspend );
111#endif 112#endif
112#ifndef QT_NO_COP 113#ifndef QT_NO_COP
113 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend; 114 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend;
114#endif 115#endif
115 116
116 if ( sendSync ) { 117 if ( sendSync ) {
117 pi ->startSync(); 118 pi ->startSync();
118 sendSync = FALSE; 119 sendSync = FALSE;
119 } 120 }
120} 121}
121 122
122void QCopBridge::closed( QCopBridgePI *pi ) 123void QCopBridge::closed( QCopBridgePI *pi )
123{ 124{
124 emit connectionClosed( pi->peerAddress() ); 125 emit connectionClosed( pi->peerAddress() );
125 openConnections.removeRef( pi ); 126 openConnections.removeRef( pi );
126 if ( openConnections.count() == 0 ) { 127 if ( openConnections.count() == 0 ) {
127 /* ### FIXME libqtopia merge */ 128 /* ### FIXME libqtopia merge */
128#if 0 129#if 0
129 QPEApplication::setTempScreenSaverMode( QPEApplication::Enable ); 130 QPEApplication::setTempScreenSaverMode( QPEApplication::Enable );
130#endif 131#endif
131#ifndef QT_NO_COP 132#ifndef QT_NO_COP
132 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; 133 QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable;
133#endif 134#endif
134 } 135 }
135} 136}
136 137
137void QCopBridge::closeOpenConnections() 138void QCopBridge::closeOpenConnections()
138{ 139{
139 QCopBridgePI *pi; 140 QCopBridgePI *pi;
140 for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) 141 for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() )
141 pi->close(); 142 pi->close();
142} 143}
143 144
144 145
145void QCopBridge::desktopMessage( const QCString &command, const QByteArray &data ) 146void QCopBridge::desktopMessage( const QCString &command, const QByteArray &data )
146{ 147{
147 if ( command == "startSync()" ) { 148 if ( command == "startSync()" ) {
148 // we need to buffer it a bit 149 // we need to buffer it a bit
149 sendSync = TRUE; 150 sendSync = TRUE;
150 startTimer( 20000 ); 151 startTimer( 20000 );
151 } 152 }
152 153
153 if ( m_mode & Qtopia1_7 ) { 154 if ( m_mode & Qtopia1_7 ) {
154 // send the command to all open connections 155 // send the command to all open connections
155 QCopBridgePI *pi; 156 QCopBridgePI *pi;
156 for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) { 157 for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) {
157 pi->sendDesktopMessage( command, data ); 158 pi->sendDesktopMessage( command, data );
158 } 159 }
159 } 160 }
160 if ( ( m_mode & Sharp ) || (m_mode & IntelliSync) ) 161 if ( ( m_mode & Sharp ) || (m_mode & IntelliSync) )
161 sendDesktopMessageOld( command, data ); 162 sendDesktopMessageOld( command, data );
162} 163}
163 164
164#ifndef OPIE_NO_OLD_SYNC_CODE 165#ifndef OPIE_NO_OLD_SYNC_CODE
165/* 166/*
166 * Old compat mode 167 * Old compat mode
167 */ 168 */
168void QCopBridge::sendDesktopMessageOld( const QCString& command, const QByteArray& args) { 169void QCopBridge::sendDesktopMessageOld( const QCString& command, const QByteArray& args) {
169 command.stripWhiteSpace(); 170 command.stripWhiteSpace();
170 171
171 int paren = command.find( "(" ); 172 int paren = command.find( "(" );
172 if ( paren <= 0 ) { 173 if ( paren <= 0 ) {
173 qDebug("DesktopMessage: bad qcop syntax"); 174 qDebug("DesktopMessage: bad qcop syntax");
174 return; 175 return;
175 } 176 }
176 177
177 QString params = command.mid( paren + 1 ); 178 QString params = command.mid( paren + 1 );
178 if ( params[params.length()-1] != ')' ) { 179 if ( params[params.length()-1] != ')' ) {
179 qDebug("DesktopMessage: bad qcop syntax"); 180 qDebug("DesktopMessage: bad qcop syntax");
180 return; 181 return;
181 } 182 }
182 183
183 params.truncate( params.length()-1 ); 184 params.truncate( params.length()-1 );
184 185
185 QStringList paramList = QStringList::split( ",", params ); 186 QStringList paramList = QStringList::split( ",", params );
186 QString data; 187 QString data;
187 if ( paramList.count() ) { 188 if ( paramList.count() ) {
188 QDataStream stream( args, IO_ReadOnly ); 189 QDataStream stream( args, IO_ReadOnly );
189 for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) { 190 for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) {
190 QString str; 191 QString str;
191 if ( *it == "QString" ) { 192 if ( *it == "QString" ) {
192 stream >> str; 193 stream >> str;
193 } else if ( *it == "QCString" ) { 194 } else if ( *it == "QCString" ) {
194 QCString cstr; 195 QCString cstr;
195 stream >> cstr; 196 stream >> cstr;
196 str = QString::fromLocal8Bit( cstr ); 197 str = QString::fromLocal8Bit( cstr );
197 } else if ( *it == "int" ) { 198 } else if ( *it == "int" ) {
198 int i; 199 int i;
199 stream >> i; 200 stream >> i;
200 str = QString::number( i ); 201 str = QString::number( i );
201 } else if ( *it == "bool" ) { 202 } else if ( *it == "bool" ) {
202 int i; 203 int i;
203 stream >> i; 204 stream >> i;
204 str = QString::number( i ); 205 str = QString::number( i );
205 } else { 206 } else {
206 qDebug(" cannot route the argument type %s throught the qcop bridge", (*it).latin1() ); 207 qDebug(" cannot route the argument type %s throught the qcop bridge", (*it).latin1() );
207 return; 208 return;
208 } 209 }
209 QString estr; 210 QString estr;
210 for (int i=0; i<(int)str.length(); i++) { 211 for (int i=0; i<(int)str.length(); i++) {
211 QChar ch = str[i]; 212 QChar ch = str[i];
212 if ( ch.row() ) 213 if ( ch.row() )
213 goto quick; 214 goto quick;
214 switch (ch.cell()) { 215 switch (ch.cell()) {
215 case '&': 216 case '&':
216 estr.append( "&amp;" ); 217 estr.append( "&amp;" );
217 break; 218 break;
218 case ' ': 219 case ' ':
219 estr.append( "&0x20;" ); 220 estr.append( "&0x20;" );
220 break; 221 break;
221 case '\n': 222 case '\n':
222 estr.append( "&0x0d;" ); 223 estr.append( "&0x0d;" );
223 break; 224 break;
224 case '\r': 225 case '\r':
225 estr.append( "&0x0a;" ); 226 estr.append( "&0x0a;" );
226 break; 227 break;
227 default: quick: 228 default: quick:
228 estr.append(ch); 229 estr.append(ch);
229 } 230 }
230 } 231 }
231 data += " " + estr; 232 data += " " + estr;
232 } 233 }
233 } 234 }
234 QString sendCommand = QString(command.data()) + data; 235 QString sendCommand = QString(command.data()) + data;
235 236
236 237
237 // send the command to all open connections 238 // send the command to all open connections
238 QCopBridgePI *pi; 239 QCopBridgePI *pi;
239 for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) 240 for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() )
240 pi->sendDesktopMessage( sendCommand ); 241 pi->sendDesktopMessage( sendCommand );
241 242
242} 243}
243#endif 244#endif
244 245
245 246
246void QCopBridge::timerEvent( QTimerEvent * ) 247void QCopBridge::timerEvent( QTimerEvent * )
247{ 248{
248 sendSync = FALSE; 249 sendSync = FALSE;
249 killTimers(); 250 killTimers();
250} 251}
251 252
252 253
253QCopBridgePI::QCopBridgePI( int socket, QObject *parent, const char* name ) 254QCopBridgePI::QCopBridgePI( int socket, QObject *parent, const char* name )
254 : QSocket( parent, name ) 255 : QSocket( parent, name )
255{ 256{
256 setSocket( socket ); 257 setSocket( socket );
257 258
258 peerport = peerPort(); 259 peerport = peerPort();
259 peeraddress = peerAddress(); 260 peeraddress = peerAddress();
260 261
261#ifndef INSECURE 262#ifndef INSECURE
262 if ( !SyncAuthentication::isAuthorized(peeraddress) ) { 263 if ( !SyncAuthentication::isAuthorized(peeraddress) ) {
263 state = Forbidden; 264 state = Forbidden;
264 close(); 265 close();
265 } else 266 } else
266#endif 267#endif
267 { 268 {
268 state = Connected; 269 state = Connected;
269 connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); 270 connect( this, SIGNAL( readyRead() ), SLOT( read() ) );
270 QString intro="220 Qtopia "; 271 QString intro="220 Qtopia ";
271 intro += QPE_VERSION; intro += ";"; 272 intro += QPE_VERSION; intro += ";";
272 intro += "challenge="; intro += SyncAuthentication::serverId(); intro += ";"; // No tr 273 intro += "challenge="; intro += SyncAuthentication::serverId(); intro += ";"; // No tr
273 intro += "loginname="; intro += SyncAuthentication::loginName(); intro += ";"; 274 intro += "loginname="; intro += SyncAuthentication::loginName(); intro += ";";
274 intro += "displayname="; intro += SyncAuthentication::ownerName(); intro += ";"; 275 intro += "displayname="; intro += SyncAuthentication::ownerName(); intro += ";";
275 send( intro ); 276 send( intro );
276 state = Wait_USER; 277 state = Wait_USER;
277 } 278 }
278 sendSync = FALSE; 279 sendSync = FALSE;
279 connect( this, SIGNAL( connectionClosed() ), SLOT( myConnectionClosed() ) ); 280 connect( this, SIGNAL( connectionClosed() ), SLOT( myConnectionClosed() ) );
280 281
281 // idle timer to close connections when not used anymore 282 // idle timer to close connections when not used anymore
282 timer = new QTimer(this); 283 timer = new QTimer(this);
283 connect( timer, SIGNAL(timeout()), this, SLOT(myConnectionClosed()) ); 284 connect( timer, SIGNAL(timeout()), this, SLOT(myConnectionClosed()) );
284 timer->start( 300000, TRUE ); 285 timer->start( 300000, TRUE );
285} 286}
286 287
287 288
288QCopBridgePI::~QCopBridgePI() 289QCopBridgePI::~QCopBridgePI()
289{ 290{
290} 291}
291 292
292bool QCopBridgePI::verifyAuthorised() 293bool QCopBridgePI::verifyAuthorised()
293{ 294{
294 if ( !SyncAuthentication::isAuthorized(peerAddress()) ) { 295 if ( !SyncAuthentication::isAuthorized(peerAddress()) ) {
295 state = Forbidden; 296 state = Forbidden;
296 return FALSE; 297 return FALSE;
297 } 298 }
298 return TRUE; 299 return TRUE;
299} 300}
300 301
301void QCopBridgePI::myConnectionClosed() 302void QCopBridgePI::myConnectionClosed()
302{ 303{
303 emit connectionClosed( this ); 304 emit connectionClosed( this );
304} 305}
305 306
306void QCopBridgePI::sendDesktopMessage( const QString &msg ) 307void QCopBridgePI::sendDesktopMessage( const QString &msg )
307{ 308{
308 QString str = "CALL QPE/Desktop " + msg; // No tr 309 QString str = "CALL QPE/Desktop " + msg; // No tr
309 send ( str ); 310 send ( str );
310} 311}
311 312
312void QCopBridgePI::sendDesktopMessage( const QCString &msg, const QByteArray& data ) 313void QCopBridgePI::sendDesktopMessage( const QCString &msg, const QByteArray& data )
313{ 314{
314 if ( !isOpen() ) // eg. Forbidden 315 if ( !isOpen() ) // eg. Forbidden
315 return; 316 return;
316 317
317 const char hdr[]="CALLB QPE/Desktop "; 318 const char hdr[]="CALLB QPE/Desktop ";
318 writeBlock(hdr,sizeof(hdr)-1); 319 writeBlock(hdr,sizeof(hdr)-1);
319 writeBlock(msg,msg.length()); 320 writeBlock(msg,msg.length());
320 writeBlock(" ",1); 321 writeBlock(" ",1);
321 QByteArray b64 = OGlobal::encodeBase64(data); 322 QByteArray b64 = OGlobal::encodeBase64(data);
322 writeBlock(b64.data(),b64.size()); 323 writeBlock(b64.data(),b64.size());
323 writeBlock("\r\n",2); 324 writeBlock("\r\n",2);
324 325
325} 326}
326 327
327 328
328void QCopBridgePI::send( const QString& msg ) 329void QCopBridgePI::send( const QString& msg )
329{ 330{
330 if ( !isOpen() ) // eg. Forbidden 331 if ( !isOpen() ) // eg. Forbidden
331 return; 332 return;
332 QTextStream os( this ); 333 QTextStream os( this );
333 os << msg << endl; 334 os << msg << endl;
334 //qDebug( "sending qcop message: %s", msg.latin1() ); 335 //qDebug( "sending qcop message: %s", msg.latin1() );
335} 336}
336 337
337void QCopBridgePI::read() 338void QCopBridgePI::read()
338{ 339{
339 while ( canReadLine() ) { 340 while ( canReadLine() ) {
340 timer->start( 300000, TRUE ); 341 timer->start( 300000, TRUE );
341 process( readLine().stripWhiteSpace() ); 342 process( readLine().stripWhiteSpace() );
342 } 343 }
343} 344}
344 345
345void QCopBridgePI::process( const QString& message ) 346void QCopBridgePI::process( const QString& message )
346{ 347{
347 //qDebug( "Command: %s", message.latin1() ); 348 //qDebug( "Command: %s", message.latin1() );
348 349
349 // split message using "," as separator 350 // split message using "," as separator
350 QStringList msg = QStringList::split( " ", message ); 351 QStringList msg = QStringList::split( " ", message );
351 if ( msg.isEmpty() ) return; 352 if ( msg.isEmpty() ) return;
352 353
353 // command token 354 // command token
354 QString cmd = msg[0].upper(); 355 QString cmd = msg[0].upper();
355 356
356 // argument token 357 // argument token
357 QString arg; 358 QString arg;
358 if ( msg.count() >= 2 ) 359 if ( msg.count() >= 2 )
359 arg = msg[1]; 360 arg = msg[1];
360 361
361 // we always respond to QUIT, regardless of state 362 // we always respond to QUIT, regardless of state
362 if ( cmd == "QUIT" ) { 363 if ( cmd == "QUIT" ) {
363 send( "211 Have a nice day!" ); // No tr 364 send( "211 Have a nice day!" ); // No tr
364 close(); 365 close();
365 return; 366 return;
366 } 367 }
367 368
368 // connected to client 369 // connected to client
369 if ( Connected == state ) 370 if ( Connected == state )
370 return; 371 return;
371 372
372 // waiting for user name 373 // waiting for user name
373 if ( Wait_USER == state ) { 374 if ( Wait_USER == state ) {
374 375
375 if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) { 376 if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) {
376 send( "530 Please login with USER and PASS" ); // No tr 377 send( "530 Please login with USER and PASS" ); // No tr
377 return; 378 return;
378 } 379 }
379 send( "331 User name ok, need password" ); // No tr 380 send( "331 User name ok, need password" ); // No tr
380 state = Wait_PASS; 381 state = Wait_PASS;
381 return; 382 return;
382 } 383 }
383 384
384 // waiting for password 385 // waiting for password
385 if ( Wait_PASS == state ) { 386 if ( Wait_PASS == state ) {
386 387
387 if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) { 388 if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) {
388 send( "530 Please login with USER and PASS" ); // No tr 389 send( "530 Please login with USER and PASS" ); // No tr
389 return; 390 return;
390 } 391 }
391 send( "230 User logged in, proceed" ); // No tr 392 send( "230 User logged in, proceed" ); // No tr
392 state = Ready; 393 state = Ready;
393 if ( sendSync ) { 394 if ( sendSync ) {
394 sendDesktopMessage( "startSync()" ); 395 sendDesktopMessage( "startSync()" );
395 sendSync = FALSE; 396 sendSync = FALSE;
396 } 397 }
397 return; 398 return;
398 } 399 }
399 400
400 // noop (NOOP) 401 // noop (NOOP)
401 else if ( cmd == "NOOP" ) { 402 else if ( cmd == "NOOP" ) {
402 send( "200 Command okay" ); // No tr 403 send( "200 Command okay" ); // No tr
403 } 404 }
404 405
405 // call (CALL) 406 // call (CALL)
406 else if ( cmd == "CALL" ) { 407 else if ( cmd == "CALL" ) {
407 408
408 // example: call QPE/System execute(QString) addressbook 409 // example: call QPE/System execute(QString) addressbook
409 410
410 if ( msg.count() < 3 ) { 411 if ( msg.count() < 3 ) {
411 send( "500 Syntax error, command unrecognized" ); // No tr 412 send( "500 Syntax error, command unrecognized" ); // No tr
412 } 413 }
413 else { 414 else {
414 415
415 QString channel = msg[1]; 416 QString channel = msg[1];
416 QString command = msg[2]; 417 QString command = msg[2];
417 418
418 command.stripWhiteSpace(); 419 command.stripWhiteSpace();
419 420
420 int paren = command.find( "(" ); 421 int paren = command.find( "(" );
421 if ( paren <= 0 ) { 422 if ( paren <= 0 ) {
422 send( "500 Syntax error, command unrecognized" ); // No tr 423 send( "500 Syntax error, command unrecognized" ); // No tr
423 return; 424 return;
424 } 425 }
425 426
426 QString params = command.mid( paren + 1 ); 427 QString params = command.mid( paren + 1 );
427 if ( params[(int)params.length()-1] != ')' ) { 428 if ( params[(int)params.length()-1] != ')' ) {
428 send( "500 Syntax error, command unrecognized" ); // No tr 429 send( "500 Syntax error, command unrecognized" ); // No tr
429 return; 430 return;
430 } 431 }
431 432
432 params.truncate( params.length()-1 ); 433 params.truncate( params.length()-1 );
433 QByteArray buffer; 434 QByteArray buffer;
434 QDataStream ds( buffer, IO_WriteOnly ); 435 QDataStream ds( buffer, IO_WriteOnly );
435 436
436 int msgId = 3; 437 int msgId = 3;
437 438
438 QStringList paramList = QStringList::split( ",", params ); 439 QStringList paramList = QStringList::split( ",", params );
439 if ( paramList.count() > msg.count() - 3 ) { 440 if ( paramList.count() > msg.count() - 3 ) {
440 send( "500 Syntax error, command unrecognized" ); // No tr 441 send( "500 Syntax error, command unrecognized" ); // No tr
441 return; 442 return;
442 } 443 }
443 444
444 for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) { 445 for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) {
445 446
446 QString arg = msg[msgId]; 447 QString arg = msg[msgId];
447 arg.replace( QRegExp("&0x20;"), " " ); 448 arg.replace( QRegExp("&0x20;"), " " );
448 arg.replace( QRegExp("&amp;"), "&" ); 449 arg.replace( QRegExp("&amp;"), "&" );
449 arg.replace( QRegExp("&0x0d;"), "\n" ); 450 arg.replace( QRegExp("&0x0d;"), "\n" );
450 arg.replace( QRegExp("&0x0a;"), "\r" ); 451 arg.replace( QRegExp("&0x0a;"), "\r" );
451 if ( *it == "QString" ) 452 if ( *it == "QString" )
452 ds << arg; 453 ds << arg;
453 else if ( *it == "QCString" ) 454 else if ( *it == "QCString" )
454 ds << arg.local8Bit(); 455 ds << arg.local8Bit();
455 else if ( *it == "int" ) 456 else if ( *it == "int" )
456 ds << arg.toInt(); 457 ds << arg.toInt();
457 else if ( *it == "bool" ) 458 else if ( *it == "bool" )
458 ds << arg.toInt(); 459 ds << arg.toInt();
459 else { 460 else {
460 send( "500 Syntax error, command unrecognized" ); // No tr 461 send( "500 Syntax error, command unrecognized" ); // No tr
461 return; 462 return;
462 } 463 }
463 msgId++; 464 msgId++;
464 } 465 }
465 466
466#ifndef QT_NO_COP 467#ifndef QT_NO_COP
467 if ( !QCopChannel::isRegistered( channel.latin1() ) ) { 468 if ( !QCopChannel::isRegistered( channel.latin1() ) ) {
468 // send message back about it 469 // send message back about it
469 QString answer = "599 ChannelNotRegistered " + channel; 470 QString answer = "599 ChannelNotRegistered " + channel;
470 send( answer ); 471 send( answer );
471 return; 472 return;
472 } 473 }
473#endif 474#endif
474 475
475#ifndef QT_NO_COP 476#ifndef QT_NO_COP
476 if ( paramList.count() ) 477 if ( paramList.count() )
477 QCopChannel::send( channel.latin1(), command.latin1(), buffer ); 478 QCopChannel::send( channel.latin1(), command.latin1(), buffer );
478 else 479 else
479 QCopChannel::send( channel.latin1(), command.latin1() ); 480 QCopChannel::send( channel.latin1(), command.latin1() );
480 481
481 send( "200 Command okay" ); // No tr 482 send( "200 Command okay" ); // No tr
482#endif 483#endif
483 } 484 }
484 } 485 }
485 // not implemented 486 // not implemented
486 else 487 else
487 send( "502 Command not implemented" ); // No tr 488 send( "502 Command not implemented" ); // No tr
488} 489}
489 490
490 491
diff --git a/core/launcher/screensaver.cpp b/core/launcher/screensaver.cpp
index e544c61..6aaab3a 100644
--- a/core/launcher/screensaver.cpp
+++ b/core/launcher/screensaver.cpp
@@ -1,328 +1,328 @@
1 1
2#include "screensaver.h" 2#include "screensaver.h"
3 3
4#include <qpe/config.h> 4#include <qpe/config.h>
5#include <qpe/network.h> 5#include <qpe/network.h>
6 6
7#include <opie2/odevice.h> 7#include <opie2/odevice.h>
8 8
9 9
10using namespace Opie; 10using namespace Opie::Core;
11 11
12 12
13 13
14OpieScreenSaver::OpieScreenSaver ( ) 14OpieScreenSaver::OpieScreenSaver ( )
15 : QObject ( 0, "screensaver" ), QWSScreenSaver ( ) 15 : QObject ( 0, "screensaver" ), QWSScreenSaver ( )
16{ 16{
17 m_disable_suspend = 100; 17 m_disable_suspend = 100;
18 m_enable_dim = false; 18 m_enable_dim = false;
19 m_enable_lightoff = false; 19 m_enable_lightoff = false;
20 m_enable_suspend = false; 20 m_enable_suspend = false;
21 m_onlylcdoff = false; 21 m_onlylcdoff = false;
22 22
23 m_enable_dim_ac = false; 23 m_enable_dim_ac = false;
24 m_enable_lightoff_ac = false; 24 m_enable_lightoff_ac = false;
25 m_enable_suspend_ac = false; 25 m_enable_suspend_ac = false;
26 m_onlylcdoff_ac = false; 26 m_onlylcdoff_ac = false;
27 27
28 m_use_light_sensor = false; 28 m_use_light_sensor = false;
29 m_backlight_sensor = -1; 29 m_backlight_sensor = -1;
30 ::memset ( m_sensordata, 0xff, LS_Count * sizeof( m_sensordata [0] )); 30 ::memset ( m_sensordata, 0xff, LS_Count * sizeof( m_sensordata [0] ));
31 31
32 m_lcd_status = true; 32 m_lcd_status = true;
33 33
34 m_backlight_normal = -1; 34 m_backlight_normal = -1;
35 m_backlight_current = -1; 35 m_backlight_current = -1;
36 m_backlight_forcedoff = false; 36 m_backlight_forcedoff = false;
37 37
38 m_on_ac = false; 38 m_on_ac = false;
39 39
40 m_level = -1; 40 m_level = -1;
41 41
42 // Make sure the LCD is in fact on, (if opie was killed while the LCD is off it would still be off) 42 // Make sure the LCD is in fact on, (if opie was killed while the LCD is off it would still be off)
43 ODevice::inst ( )-> setDisplayStatus ( true ); 43 ODevice::inst ( )-> setDisplayStatus ( true );
44 setBacklight ( -1 ); 44 setBacklight ( -1 );
45} 45}
46 46
47 47
48/** 48/**
49 * Stops the screen saver 49 * Stops the screen saver
50 */ 50 */
51void OpieScreenSaver::restore() 51void OpieScreenSaver::restore()
52{ 52{
53 m_level = -1; 53 m_level = -1;
54 54
55 if ( !m_lcd_status ) { // We must have turned it off 55 if ( !m_lcd_status ) { // We must have turned it off
56 ODevice::inst ( ) -> setDisplayStatus ( true ); 56 ODevice::inst ( ) -> setDisplayStatus ( true );
57 m_lcd_status = true; 57 m_lcd_status = true;
58 } 58 }
59 59
60 setBacklightInternal ( -1 ); 60 setBacklightInternal ( -1 );
61} 61}
62 62
63 63
64/** 64/**
65 * Starts the screen saver 65 * Starts the screen saver
66 * 66 *
67 * @param level what level of screen saving should happen (0=lowest non-off, 1=off, 67 * @param level what level of screen saving should happen (0=lowest non-off, 1=off,
68 * 2=suspend whole machine) 68 * 2=suspend whole machine)
69 * @returns true on success 69 * @returns true on success
70 */ 70 */
71bool OpieScreenSaver::save( int level ) 71bool OpieScreenSaver::save( int level )
72{ 72{
73 m_level = level; 73 m_level = level;
74 74
75 switch ( level ) { 75 switch ( level ) {
76 case 0: 76 case 0:
77 if (( m_on_ac && m_enable_dim_ac ) || 77 if (( m_on_ac && m_enable_dim_ac ) ||
78 ( !m_on_ac && m_enable_dim )) { 78 ( !m_on_ac && m_enable_dim )) {
79 if (( m_disable_suspend > 0 ) && ( m_backlight_current > 1 ) && !m_use_light_sensor ) 79 if (( m_disable_suspend > 0 ) && ( m_backlight_current > 1 ) && !m_use_light_sensor )
80 setBacklightInternal ( 1 ); // lowest non-off 80 setBacklightInternal ( 1 ); // lowest non-off
81 } 81 }
82 return true; 82 return true;
83 break; 83 break;
84 84
85 case 1: 85 case 1:
86 if (( m_on_ac && m_enable_lightoff_ac ) || 86 if (( m_on_ac && m_enable_lightoff_ac ) ||
87 ( !m_on_ac && m_enable_lightoff )) { 87 ( !m_on_ac && m_enable_lightoff )) {
88 if ( m_disable_suspend > 1 ) 88 if ( m_disable_suspend > 1 )
89 setBacklightInternal ( 0 ); // off 89 setBacklightInternal ( 0 ); // off
90 } 90 }
91 return true; 91 return true;
92 break; 92 break;
93 93
94 case 2: 94 case 2:
95 if (( m_on_ac && !m_enable_suspend_ac ) || 95 if (( m_on_ac && !m_enable_suspend_ac ) ||
96 ( !m_on_ac && !m_enable_suspend )) { 96 ( !m_on_ac && !m_enable_suspend )) {
97 return true; 97 return true;
98 } 98 }
99 99
100 if (( m_on_ac && m_onlylcdoff_ac ) || 100 if (( m_on_ac && m_onlylcdoff_ac ) ||
101 ( !m_on_ac && m_onlylcdoff )) { 101 ( !m_on_ac && m_onlylcdoff )) {
102 ODevice::inst ( ) -> setDisplayStatus ( false ); 102 ODevice::inst ( ) -> setDisplayStatus ( false );
103 m_lcd_status = false; 103 m_lcd_status = false;
104 return true; 104 return true;
105 } 105 }
106 106
107 // We're going to suspend the whole machine 107 // We're going to suspend the whole machine
108 108
109 if (( m_disable_suspend > 2 ) && !Network::networkOnline ( )) { 109 if (( m_disable_suspend > 2 ) && !Network::networkOnline ( )) {
110 // TODO: why is this key F34 hard coded? -- schurig 110 // TODO: why is this key F34 hard coded? -- schurig
111 // Does this now only work an devices with a ODevice::filter? 111 // Does this now only work an devices with a ODevice::filter?
112 QWSServer::sendKeyEvent( 0xffff, Qt::Key_F34, FALSE, TRUE, FALSE ); 112 QWSServer::sendKeyEvent( 0xffff, Qt::Key_F34, FALSE, TRUE, FALSE );
113 return true; 113 return true;
114 } 114 }
115 115
116 break; 116 break;
117 } 117 }
118 return false; 118 return false;
119} 119}
120 120
121 121
122/** 122/**
123 * Set intervals in seconds for automatic dimming, light off and suspend 123 * Set intervals in seconds for automatic dimming, light off and suspend
124 * 124 *
125 * This function also sets the member variables m_m_enable_dim[_ac], 125 * This function also sets the member variables m_m_enable_dim[_ac],
126 * m_enable_lightoff[_ac], m_enable_suspend[_ac], m_onlylcdoff[_ac] 126 * m_enable_lightoff[_ac], m_enable_suspend[_ac], m_onlylcdoff[_ac]
127 * 127 *
128 * @param dim time in seconds to dim, -1 to read value from config file, 128 * @param dim time in seconds to dim, -1 to read value from config file,
129 * 0 to disable 129 * 0 to disable
130 * @param lightoff time in seconds to turn LCD backlight off, -1 to 130 * @param lightoff time in seconds to turn LCD backlight off, -1 to
131 * read value from config file, 0 to disable 131 * read value from config file, 0 to disable
132 * @param suspend time in seconds to do an APM suspend, -1 to 132 * @param suspend time in seconds to do an APM suspend, -1 to
133 * read value from config file, 0 to disable 133 * read value from config file, 0 to disable
134 */ 134 */
135void OpieScreenSaver::setIntervals ( int dim, int lightoff, int suspend ) 135void OpieScreenSaver::setIntervals ( int dim, int lightoff, int suspend )
136{ 136{
137 Config config ( "apm" ); 137 Config config ( "apm" );
138 config. setGroup ( m_on_ac ? "AC" : "Battery" ); 138 config. setGroup ( m_on_ac ? "AC" : "Battery" );
139 139
140 int v[ 4 ]; 140 int v[ 4 ];
141 if ( dim < 0 ) 141 if ( dim < 0 )
142 dim = config. readNumEntry ( "Dim", m_on_ac ? 60 : 30 ); 142 dim = config. readNumEntry ( "Dim", m_on_ac ? 60 : 30 );
143 if ( lightoff < 0 ) 143 if ( lightoff < 0 )
144 lightoff = config. readNumEntry ( "LightOff", m_on_ac ? 120 : 20 ); 144 lightoff = config. readNumEntry ( "LightOff", m_on_ac ? 120 : 20 );
145 if ( suspend < 0 ) 145 if ( suspend < 0 )
146 suspend = config. readNumEntry ( "Suspend", m_on_ac ? 0 : 60 ); 146 suspend = config. readNumEntry ( "Suspend", m_on_ac ? 0 : 60 );
147 147
148 if ( m_on_ac ) { 148 if ( m_on_ac ) {
149 m_enable_dim_ac = ( dim > 0 ); 149 m_enable_dim_ac = ( dim > 0 );
150 m_enable_lightoff_ac = ( lightoff > 0 ); 150 m_enable_lightoff_ac = ( lightoff > 0 );
151 m_enable_suspend_ac = ( suspend > 0 ); 151 m_enable_suspend_ac = ( suspend > 0 );
152 m_onlylcdoff_ac = config.readBoolEntry ( "LcdOffOnly", false ); 152 m_onlylcdoff_ac = config.readBoolEntry ( "LcdOffOnly", false );
153 } 153 }
154 else { 154 else {
155 m_enable_dim = ( dim > 0 ); 155 m_enable_dim = ( dim > 0 );
156 m_enable_lightoff = ( lightoff > 0 ); 156 m_enable_lightoff = ( lightoff > 0 );
157 m_enable_suspend = ( suspend > 0 ); 157 m_enable_suspend = ( suspend > 0 );
158 m_onlylcdoff = config.readBoolEntry ( "LcdOffOnly", false ); 158 m_onlylcdoff = config.readBoolEntry ( "LcdOffOnly", false );
159 } 159 }
160 160
161 //qDebug("screen saver intervals: %d %d %d", dim, lightoff, suspend); 161 //qDebug("screen saver intervals: %d %d %d", dim, lightoff, suspend);
162 162
163 v [ 0 ] = QMAX( 1000 * dim, 100 ); 163 v [ 0 ] = QMAX( 1000 * dim, 100 );
164 v [ 1 ] = QMAX( 1000 * lightoff, 100 ); 164 v [ 1 ] = QMAX( 1000 * lightoff, 100 );
165 v [ 2 ] = QMAX( 1000 * suspend, 100 ); 165 v [ 2 ] = QMAX( 1000 * suspend, 100 );
166 v [ 3 ] = 0; 166 v [ 3 ] = 0;
167 167
168 if ( !dim && !lightoff && !suspend ) 168 if ( !dim && !lightoff && !suspend )
169 QWSServer::setScreenSaverInterval( 0 ); 169 QWSServer::setScreenSaverInterval( 0 );
170 else 170 else
171 QWSServer::setScreenSaverIntervals( v ); 171 QWSServer::setScreenSaverIntervals( v );
172} 172}
173 173
174 174
175/** 175/**
176 * Set suspend time. Will read the dim and lcd-off times from the config file. 176 * Set suspend time. Will read the dim and lcd-off times from the config file.
177 * 177 *
178 * @param suspend time in seconds to go into APM suspend, -1 to 178 * @param suspend time in seconds to go into APM suspend, -1 to
179 * read value from config file, 0 to disable 179 * read value from config file, 0 to disable
180 */ 180 */
181void OpieScreenSaver::setInterval ( int interval ) 181void OpieScreenSaver::setInterval ( int interval )
182{ 182{
183 setIntervals ( -1, -1, interval ); 183 setIntervals ( -1, -1, interval );
184} 184}
185 185
186 186
187void OpieScreenSaver::setMode ( int mode ) 187void OpieScreenSaver::setMode ( int mode )
188{ 188{
189 if ( mode > m_disable_suspend ) 189 if ( mode > m_disable_suspend )
190 setInterval ( -1 ); 190 setInterval ( -1 );
191 m_disable_suspend = mode; 191 m_disable_suspend = mode;
192} 192}
193 193
194 194
195/** 195/**
196 * Set display brightness 196 * Set display brightness
197 * 197 *
198 * Get's default values for backlight, contrast and light sensor from config file. 198 * Get's default values for backlight, contrast and light sensor from config file.
199 * 199 *
200 * @param bright desired brighness (-1 to use automatic sensor data or value 200 * @param bright desired brighness (-1 to use automatic sensor data or value
201 * from config file, -2 to toggle backlight on and off, -3 to 201 * from config file, -2 to toggle backlight on and off, -3 to
202 * force backlight off) 202 * force backlight off)
203 */ 203 */
204void OpieScreenSaver::setBacklight ( int bright ) 204void OpieScreenSaver::setBacklight ( int bright )
205{ 205{
206 // Read from config 206 // Read from config
207 Config config ( "apm" ); 207 Config config ( "apm" );
208 config. setGroup ( m_on_ac ? "AC" : "Battery" ); 208 config. setGroup ( m_on_ac ? "AC" : "Battery" );
209 m_backlight_normal = config. readNumEntry ( "Brightness", m_on_ac ? 255 : 127 ); 209 m_backlight_normal = config. readNumEntry ( "Brightness", m_on_ac ? 255 : 127 );
210 int contrast = config. readNumEntry ( "Contrast", 127); 210 int contrast = config. readNumEntry ( "Contrast", 127);
211 m_use_light_sensor = config. readBoolEntry ( "LightSensor", false ); 211 m_use_light_sensor = config. readBoolEntry ( "LightSensor", false );
212 212
213 //qDebug ( "setBacklight: %d (norm: %d) (ls: %d)", bright, m_backlight_normal, m_use_light_sensor ? 1 : 0 ); 213 //qDebug ( "setBacklight: %d (norm: %d) (ls: %d)", bright, m_backlight_normal, m_use_light_sensor ? 1 : 0 );
214 214
215 killTimers ( ); 215 killTimers ( );
216 if (( bright < 0 ) && m_use_light_sensor ) { 216 if (( bright < 0 ) && m_use_light_sensor ) {
217 QStringList sl = config. readListEntry ( "LightSensorData", ';' ); 217 QStringList sl = config. readListEntry ( "LightSensorData", ';' );
218 218
219 m_sensordata [LS_SensorMin] = 40; 219 m_sensordata [LS_SensorMin] = 40;
220 m_sensordata [LS_SensorMax] = 215; 220 m_sensordata [LS_SensorMax] = 215;
221 m_sensordata [LS_LightMin] = 1; 221 m_sensordata [LS_LightMin] = 1;
222 m_sensordata [LS_LightMax] = 255; 222 m_sensordata [LS_LightMax] = 255;
223 m_sensordata [LS_Steps] = 12; 223 m_sensordata [LS_Steps] = 12;
224 m_sensordata [LS_Interval] = 2000; 224 m_sensordata [LS_Interval] = 2000;
225 225
226 for ( uint i = 0; i < LS_Count; i++ ) { 226 for ( uint i = 0; i < LS_Count; i++ ) {
227 if ( i < sl. count ( )) 227 if ( i < sl. count ( ))
228 m_sensordata [i] = sl [i]. toInt ( ); 228 m_sensordata [i] = sl [i]. toInt ( );
229 } 229 }
230 if ( m_sensordata [LS_Steps] < 2 ) // sanity check to avoid SIGFPE 230 if ( m_sensordata [LS_Steps] < 2 ) // sanity check to avoid SIGFPE
231 m_sensordata [LS_Steps] = 2; 231 m_sensordata [LS_Steps] = 2;
232 232
233 timerEvent ( 0 ); 233 timerEvent ( 0 );
234 startTimer ( m_sensordata [LS_Interval] ); 234 startTimer ( m_sensordata [LS_Interval] );
235 } 235 }
236 236
237 setBacklightInternal ( bright ); 237 setBacklightInternal ( bright );
238 ODevice::inst ( )-> setDisplayContrast(contrast); 238 ODevice::inst ( )-> setDisplayContrast(contrast);
239} 239}
240 240
241 241
242/** 242/**
243 * Internal brightness setting method 243 * Internal brightness setting method
244 * 244 *
245 * Get's default values for backlight and light sensor from config file. 245 * Get's default values for backlight and light sensor from config file.
246 * 246 *
247 * @param bright desired brighness (-1 to use automatic sensor data or value 247 * @param bright desired brighness (-1 to use automatic sensor data or value
248 * from config file, -2 to toggle backlight on and off, -3 to 248 * from config file, -2 to toggle backlight on and off, -3 to
249 * force backlight off) 249 * force backlight off)
250 */ 250 */
251void OpieScreenSaver::setBacklightInternal ( int bright ) 251void OpieScreenSaver::setBacklightInternal ( int bright )
252{ 252{
253 if ( bright == -3 ) { 253 if ( bright == -3 ) {
254 // Forced on 254 // Forced on
255 m_backlight_forcedoff = false; 255 m_backlight_forcedoff = false;
256 bright = -1; 256 bright = -1;
257 } 257 }
258 if ( m_backlight_forcedoff && bright != -2 ) 258 if ( m_backlight_forcedoff && bright != -2 )
259 return ; 259 return ;
260 if ( bright == -2 ) { 260 if ( bright == -2 ) {
261 // Toggle between off and on 261 // Toggle between off and on
262 bright = m_backlight_current ? 0 : -1; 262 bright = m_backlight_current ? 0 : -1;
263 m_backlight_forcedoff = !bright; 263 m_backlight_forcedoff = !bright;
264 } 264 }
265 if ( bright == -1 ) 265 if ( bright == -1 )
266 bright = m_use_light_sensor ? m_backlight_sensor : m_backlight_normal; 266 bright = m_use_light_sensor ? m_backlight_sensor : m_backlight_normal;
267 267
268 if ( bright != m_backlight_current ) { 268 if ( bright != m_backlight_current ) {
269 ODevice::inst ( )-> setDisplayBrightness ( bright ); 269 ODevice::inst ( )-> setDisplayBrightness ( bright );
270 m_backlight_current = bright; 270 m_backlight_current = bright;
271 } 271 }
272} 272}
273 273
274 274
275/** 275/**
276 * Timer event used for automatic setting the backlight according to a light sensor 276 * Timer event used for automatic setting the backlight according to a light sensor
277 * and to set the default brightness 277 * and to set the default brightness
278 */ 278 */
279void OpieScreenSaver::timerEvent ( QTimerEvent * ) 279void OpieScreenSaver::timerEvent ( QTimerEvent * )
280{ 280{
281 int s = ODevice::inst ( )-> readLightSensor ( ) * 256 / ODevice::inst ( )-> lightSensorResolution ( ); 281 int s = ODevice::inst ( )-> readLightSensor ( ) * 256 / ODevice::inst ( )-> lightSensorResolution ( );
282 282
283 if ( s < m_sensordata [LS_SensorMin] ) 283 if ( s < m_sensordata [LS_SensorMin] )
284 m_backlight_sensor = m_sensordata [LS_LightMax]; 284 m_backlight_sensor = m_sensordata [LS_LightMax];
285 else if ( s >= m_sensordata [LS_SensorMax] ) 285 else if ( s >= m_sensordata [LS_SensorMax] )
286 m_backlight_sensor = m_sensordata [LS_LightMin]; 286 m_backlight_sensor = m_sensordata [LS_LightMin];
287 else { 287 else {
288 int dx = m_sensordata [LS_SensorMax] - m_sensordata [LS_SensorMin]; 288 int dx = m_sensordata [LS_SensorMax] - m_sensordata [LS_SensorMin];
289 int dy = m_sensordata [LS_LightMax] - m_sensordata [LS_LightMin]; 289 int dy = m_sensordata [LS_LightMax] - m_sensordata [LS_LightMin];
290 290
291 int stepno = ( s - m_sensordata [LS_SensorMin] ) * m_sensordata [LS_Steps] / dx; // dx is never 0 291 int stepno = ( s - m_sensordata [LS_SensorMin] ) * m_sensordata [LS_Steps] / dx; // dx is never 0
292 292
293 m_backlight_sensor = m_sensordata [LS_LightMax] - dy * stepno / ( m_sensordata [LS_Steps] - 1 ); 293 m_backlight_sensor = m_sensordata [LS_LightMax] - dy * stepno / ( m_sensordata [LS_Steps] - 1 );
294 } 294 }
295 295
296 //qDebug ( "f(%d) = %d [%d - %d] -> [%d - %d] / %d", s, m_backlight_sensor, m_sensordata [LS_SensorMin], m_sensordata [LS_SensorMax], m_sensordata [LS_LightMin], m_sensordata [LS_LightMax], m_sensordata [LS_Steps] ); 296 //qDebug ( "f(%d) = %d [%d - %d] -> [%d - %d] / %d", s, m_backlight_sensor, m_sensordata [LS_SensorMin], m_sensordata [LS_SensorMax], m_sensordata [LS_LightMin], m_sensordata [LS_LightMax], m_sensordata [LS_Steps] );
297 297
298 if ( m_level <= 0 ) 298 if ( m_level <= 0 )
299 setBacklightInternal ( -1 ); 299 setBacklightInternal ( -1 );
300} 300}
301 301
302 302
303/** 303/**
304 * Like ODevice::setDisplayStatus(), but keep current state in m_lcd_status. 304 * Like ODevice::setDisplayStatus(), but keep current state in m_lcd_status.
305 */ 305 */
306void OpieScreenSaver::setDisplayState ( bool on ) 306void OpieScreenSaver::setDisplayState ( bool on )
307{ 307{
308 if ( m_lcd_status != on ) { 308 if ( m_lcd_status != on ) {
309 ODevice::inst ( ) -> setDisplayStatus ( on ); 309 ODevice::inst ( ) -> setDisplayStatus ( on );
310 m_lcd_status = on; 310 m_lcd_status = on;
311 } 311 }
312} 312}
313 313
314 314
315/** 315/**
316 * Set display to default ac/battery settings when power status changed. 316 * Set display to default ac/battery settings when power status changed.
317 */ 317 */
318void OpieScreenSaver::powerStatusChanged ( PowerStatus ps ) 318void OpieScreenSaver::powerStatusChanged ( PowerStatus ps )
319{ 319{
320 bool newonac = ( ps. acStatus ( ) == PowerStatus::Online ); 320 bool newonac = ( ps. acStatus ( ) == PowerStatus::Online );
321 321
322 if ( newonac != m_on_ac ) { 322 if ( newonac != m_on_ac ) {
323 m_on_ac = newonac; 323 m_on_ac = newonac;
324 setInterval ( -1 ); 324 setInterval ( -1 );
325 setBacklight ( -1 ); 325 setBacklight ( -1 );
326 restore ( ); 326 restore ( );
327 } 327 }
328} 328}
diff --git a/core/launcher/server.cpp b/core/launcher/server.cpp
index ea0b792..634082b 100644
--- a/core/launcher/server.cpp
+++ b/core/launcher/server.cpp
@@ -1,729 +1,729 @@
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 "server.h" 21#include "server.h"
22#include "serverapp.h" 22#include "serverapp.h"
23#include "startmenu.h" 23#include "startmenu.h"
24#include "launcher.h" 24#include "launcher.h"
25#include "transferserver.h" 25#include "transferserver.h"
26#include "qcopbridge.h" 26#include "qcopbridge.h"
27#include "irserver.h" 27#include "irserver.h"
28#include "packageslave.h" 28#include "packageslave.h"
29#include "calibrate.h" 29#include "calibrate.h"
30#include "qrsync.h" 30#include "qrsync.h"
31#include "syncdialog.h" 31#include "syncdialog.h"
32#include "shutdownimpl.h" 32#include "shutdownimpl.h"
33#include "applauncher.h" 33#include "applauncher.h"
34#if 0 34#if 0
35#include "suspendmonitor.h" 35#include "suspendmonitor.h"
36#endif 36#endif
37#include "documentlist.h" 37#include "documentlist.h"
38 38
39#include <qtopia/applnk.h> 39#include <qtopia/applnk.h>
40#include <qtopia/private/categories.h> 40#include <qtopia/private/categories.h>
41#include <qtopia/mimetype.h> 41#include <qtopia/mimetype.h>
42#include <qtopia/config.h> 42#include <qtopia/config.h>
43#include <qtopia/resource.h> 43#include <qtopia/resource.h>
44#include <qtopia/version.h> 44#include <qtopia/version.h>
45#include <qtopia/storage.h> 45#include <qtopia/storage.h>
46 46
47#include <qtopia/qcopenvelope_qws.h> 47#include <qtopia/qcopenvelope_qws.h>
48#include <qwindowsystem_qws.h> 48#include <qwindowsystem_qws.h>
49#include <qgfx_qws.h> 49#include <qgfx_qws.h>
50#include <qtopia/global.h> 50#include <qtopia/global.h>
51//#include <qtopia/custom.h> 51//#include <qtopia/custom.h>
52 52
53#include <opie2/odevicebutton.h> 53#include <opie2/odevicebutton.h>
54#include <opie2/odevice.h> 54#include <opie2/odevice.h>
55 55
56#include <unistd.h> 56#include <unistd.h>
57#include <qmainwindow.h> 57#include <qmainwindow.h>
58#include <qmessagebox.h> 58#include <qmessagebox.h>
59#include <qtimer.h> 59#include <qtimer.h>
60#include <qtextstream.h> 60#include <qtextstream.h>
61 61
62#include <stdlib.h> 62#include <stdlib.h>
63 63
64extern QRect qt_maxWindowRect; 64extern QRect qt_maxWindowRect;
65 65
66using namespace Opie;
67 66
67using namespace Opie::Core;
68static QWidget *calibrate(bool) 68static QWidget *calibrate(bool)
69{ 69{
70#ifdef Q_WS_QWS 70#ifdef Q_WS_QWS
71 Calibrate *c = new Calibrate; 71 Calibrate *c = new Calibrate;
72 c->show(); 72 c->show();
73 return c; 73 return c;
74#else 74#else
75 return 0; 75 return 0;
76#endif 76#endif
77} 77}
78 78
79#define FACTORY(T) \ 79#define FACTORY(T) \
80 static QWidget *new##T( bool maximized ) { \ 80 static QWidget *new##T( bool maximized ) { \
81 QWidget *w = new T( 0, 0, QWidget::WDestructiveClose | QWidget::WGroupLeader ); \ 81 QWidget *w = new T( 0, 0, QWidget::WDestructiveClose | QWidget::WGroupLeader ); \
82 if ( maximized ) { \ 82 if ( maximized ) { \
83 if ( qApp->desktop()->width() <= 350 ) { \ 83 if ( qApp->desktop()->width() <= 350 ) { \
84 w->showMaximized(); \ 84 w->showMaximized(); \
85 } else { \ 85 } else { \
86 w->resize( QSize( 300, 300 ) ); \ 86 w->resize( QSize( 300, 300 ) ); \
87 } \ 87 } \
88 } \ 88 } \
89 w->show(); \ 89 w->show(); \
90 return w; \ 90 return w; \
91 } 91 }
92 92
93 93
94#ifdef SINGLE_APP 94#ifdef SINGLE_APP
95#define APP(a,b,c,d) FACTORY(b) 95#define APP(a,b,c,d) FACTORY(b)
96#include "apps.h" 96#include "apps.h"
97#undef APP 97#undef APP
98#endif // SINGLE_APP 98#endif // SINGLE_APP
99 99
100static Global::Command builtins[] = { 100static Global::Command builtins[] = {
101 101
102#ifdef SINGLE_APP 102#ifdef SINGLE_APP
103#define APP(a,b,c,d) { a, new##b, c, d }, 103#define APP(a,b,c,d) { a, new##b, c, d },
104#include "apps.h" 104#include "apps.h"
105#undef APP 105#undef APP
106#endif 106#endif
107 107
108 /* FIXME defines need to be defined*/ 108 /* FIXME defines need to be defined*/
109#if !defined(OPIE_NO_BUILTIN_CALIBRATE) 109#if !defined(OPIE_NO_BUILTIN_CALIBRATE)
110 { "calibrate", calibrate, 1, 0 }, // No tr 110 { "calibrate", calibrate, 1, 0 }, // No tr
111#endif 111#endif
112#if !defined(OPIE_NO_BUILTIN_SHUTDOWN) 112#if !defined(OPIE_NO_BUILTIN_SHUTDOWN)
113 { "shutdown", Global::shutdown, 1, 0 }, // No tr 113 { "shutdown", Global::shutdown, 1, 0 }, // No tr
114 // { "run", run, 1, 0 }, // No tr 114 // { "run", run, 1, 0 }, // No tr
115#endif 115#endif
116 116
117 { 0, calibrate,0, 0 }, 117 { 0, calibrate,0, 0 },
118}; 118};
119 119
120 120
121//--------------------------------------------------------------------------- 121//---------------------------------------------------------------------------
122 122
123 123
124//=========================================================================== 124//===========================================================================
125 125
126Server::Server() : 126Server::Server() :
127 QWidget( 0, 0, WStyle_Tool | WStyle_Customize ), 127 QWidget( 0, 0, WStyle_Tool | WStyle_Customize ),
128 qcopBridge( 0 ), 128 qcopBridge( 0 ),
129 transferServer( 0 ), 129 transferServer( 0 ),
130 packageHandler( 0 ), 130 packageHandler( 0 ),
131 syncDialog( 0 ) 131 syncDialog( 0 )
132{ 132{
133 Global::setBuiltinCommands(builtins); 133 Global::setBuiltinCommands(builtins);
134 134
135 tid_xfer = 0; 135 tid_xfer = 0;
136 /* ### FIXME ### */ 136 /* ### FIXME ### */
137/* tid_today = startTimer(3600*2*1000);*/ 137/* tid_today = startTimer(3600*2*1000);*/
138 last_today_show = QDate::currentDate(); 138 last_today_show = QDate::currentDate();
139 139
140#if 0 140#if 0
141 tsmMonitor = new TempScreenSaverMode(); 141 tsmMonitor = new TempScreenSaverMode();
142 connect( tsmMonitor, SIGNAL(forceSuspend()), qApp, SIGNAL(power()) ); 142 connect( tsmMonitor, SIGNAL(forceSuspend()), qApp, SIGNAL(power()) );
143#endif 143#endif
144 144
145 serverGui = new Launcher; 145 serverGui = new Launcher;
146 serverGui->createGUI(); 146 serverGui->createGUI();
147 147
148 docList = new DocumentList( serverGui ); 148 docList = new DocumentList( serverGui );
149 appLauncher = new AppLauncher(this); 149 appLauncher = new AppLauncher(this);
150 connect(appLauncher, SIGNAL(launched(int,const QString&)), this, SLOT(applicationLaunched(int,const QString&)) ); 150 connect(appLauncher, SIGNAL(launched(int,const QString&)), this, SLOT(applicationLaunched(int,const QString&)) );
151 connect(appLauncher, SIGNAL(terminated(int,const QString&)), this, SLOT(applicationTerminated(int,const QString&)) ); 151 connect(appLauncher, SIGNAL(terminated(int,const QString&)), this, SLOT(applicationTerminated(int,const QString&)) );
152 connect(appLauncher, SIGNAL(connected(const QString&)), this, SLOT(applicationConnected(const QString&)) ); 152 connect(appLauncher, SIGNAL(connected(const QString&)), this, SLOT(applicationConnected(const QString&)) );
153 153
154 storage = new StorageInfo( this ); 154 storage = new StorageInfo( this );
155 connect( storage, SIGNAL(disksChanged()), this, SLOT(storageChanged()) ); 155 connect( storage, SIGNAL(disksChanged()), this, SLOT(storageChanged()) );
156 156
157 // start services 157 // start services
158 startTransferServer(); 158 startTransferServer();
159 (void) new IrServer( this ); 159 (void) new IrServer( this );
160 160
161 packageHandler = new PackageHandler( this ); 161 packageHandler = new PackageHandler( this );
162 connect(qApp, SIGNAL(activate(const Opie::ODeviceButton*,bool)), 162 connect(qApp, SIGNAL(activate(const Opie::Core::ODeviceButton*,bool)),
163 this,SLOT(activate(const Opie::ODeviceButton*,bool))); 163 this,SLOT(activate(const Opie::Core::ODeviceButton*,bool)));
164 164
165 setGeometry( -10, -10, 9, 9 ); 165 setGeometry( -10, -10, 9, 9 );
166 166
167 QCopChannel *channel = new QCopChannel("QPE/System", this); 167 QCopChannel *channel = new QCopChannel("QPE/System", this);
168 connect(channel, SIGNAL(received(const QCString&,const QByteArray&)), 168 connect(channel, SIGNAL(received(const QCString&,const QByteArray&)),
169 this, SLOT(systemMsg(const QCString&,const QByteArray&)) ); 169 this, SLOT(systemMsg(const QCString&,const QByteArray&)) );
170 170
171 QCopChannel *tbChannel = new QCopChannel( "QPE/TaskBar", this ); 171 QCopChannel *tbChannel = new QCopChannel( "QPE/TaskBar", this );
172 connect( tbChannel, SIGNAL(received(const QCString&,const QByteArray&)), 172 connect( tbChannel, SIGNAL(received(const QCString&,const QByteArray&)),
173 this, SLOT(receiveTaskBar(const QCString&,const QByteArray&)) ); 173 this, SLOT(receiveTaskBar(const QCString&,const QByteArray&)) );
174 174
175 connect( qApp, SIGNAL(prepareForRestart()), this, SLOT(terminateServers()) ); 175 connect( qApp, SIGNAL(prepareForRestart()), this, SLOT(terminateServers()) );
176 connect( qApp, SIGNAL(timeChanged()), this, SLOT(pokeTimeMonitors()) ); 176 connect( qApp, SIGNAL(timeChanged()), this, SLOT(pokeTimeMonitors()) );
177 177
178 preloadApps(); 178 preloadApps();
179} 179}
180 180
181void Server::show() 181void Server::show()
182{ 182{
183 ServerApplication::login(TRUE); 183 ServerApplication::login(TRUE);
184 QWidget::show(); 184 QWidget::show();
185} 185}
186 186
187Server::~Server() 187Server::~Server()
188{ 188{
189 serverGui->destroyGUI(); 189 serverGui->destroyGUI();
190 delete docList; 190 delete docList;
191 delete qcopBridge; 191 delete qcopBridge;
192 delete transferServer; 192 delete transferServer;
193 delete serverGui; 193 delete serverGui;
194#if 0 194#if 0
195 delete tsmMonitor; 195 delete tsmMonitor;
196#endif 196#endif
197} 197}
198 198
199static bool hasVisibleWindow(const QString& clientname, bool partial) 199static bool hasVisibleWindow(const QString& clientname, bool partial)
200{ 200{
201#ifdef QWS 201#ifdef QWS
202 const QList<QWSWindow> &list = qwsServer->clientWindows(); 202 const QList<QWSWindow> &list = qwsServer->clientWindows();
203 QWSWindow* w; 203 QWSWindow* w;
204 for (QListIterator<QWSWindow> it(list); (w=it.current()); ++it) { 204 for (QListIterator<QWSWindow> it(list); (w=it.current()); ++it) {
205 if ( w->client()->identity() == clientname ) { 205 if ( w->client()->identity() == clientname ) {
206 if ( partial && !w->isFullyObscured() ) 206 if ( partial && !w->isFullyObscured() )
207 return TRUE; 207 return TRUE;
208 if ( !partial && !w->isFullyObscured() && !w->isPartiallyObscured() ) { 208 if ( !partial && !w->isFullyObscured() && !w->isPartiallyObscured() ) {
209# if QT_VERSION < 0x030000 209# if QT_VERSION < 0x030000
210 QRect mwr = qt_screen->mapToDevice(qt_maxWindowRect, 210 QRect mwr = qt_screen->mapToDevice(qt_maxWindowRect,
211 QSize(qt_screen->width(),qt_screen->height()) ); 211 QSize(qt_screen->width(),qt_screen->height()) );
212# else 212# else
213 QRect mwr = qt_maxWindowRect; 213 QRect mwr = qt_maxWindowRect;
214# endif 214# endif
215 if ( mwr.contains(w->requested().boundingRect()) ) 215 if ( mwr.contains(w->requested().boundingRect()) )
216 return TRUE; 216 return TRUE;
217 } 217 }
218 } 218 }
219 } 219 }
220#endif 220#endif
221 return FALSE; 221 return FALSE;
222} 222}
223 223
224void Server::activate(const Opie::ODeviceButton* button, bool held) 224void Server::activate(const ODeviceButton* button, bool held)
225{ 225{
226 Global::terminateBuiltin("calibrate"); // No tr 226 Global::terminateBuiltin("calibrate"); // No tr
227 Opie::OQCopMessage om; 227 OQCopMessage om;
228 if ( held ) { 228 if ( held ) {
229 om = button->heldAction(); 229 om = button->heldAction();
230 } else { 230 } else {
231 om = button->pressedAction(); 231 om = button->pressedAction();
232 } 232 }
233 233
234 if ( om.channel() != "ignore" ) 234 if ( om.channel() != "ignore" )
235 om.send(); 235 om.send();
236 236
237 // A button with no action defined, will return a null ServiceRequest. Don't attempt 237 // A button with no action defined, will return a null ServiceRequest. Don't attempt
238 // to send/do anything with this as it will crash 238 // to send/do anything with this as it will crash
239 /* ### FIXME */ 239 /* ### FIXME */
240#if 0 240#if 0
241 if ( !sr.isNull() ) { 241 if ( !sr.isNull() ) {
242 QString app = sr.app(); 242 QString app = sr.app();
243 bool vis = hasVisibleWindow(app, app != "qpe"); 243 bool vis = hasVisibleWindow(app, app != "qpe");
244 if ( sr.message() == "raise()" && vis ) { 244 if ( sr.message() == "raise()" && vis ) {
245 sr.setMessage("nextView()"); 245 sr.setMessage("nextView()");
246 } else { 246 } else {
247 // "back door" 247 // "back door"
248 sr << (int)vis; 248 sr << (int)vis;
249 } 249 }
250 250
251 sr.send(); 251 sr.send();
252 } 252 }
253#endif 253#endif
254} 254}
255 255
256 256
257#ifdef Q_WS_QWS 257#ifdef Q_WS_QWS
258 258
259 259
260typedef struct KeyOverride { 260typedef struct KeyOverride {
261 ushort scan_code; 261 ushort scan_code;
262 QWSServer::KeyMap map; 262 QWSServer::KeyMap map;
263}; 263};
264 264
265 265
266static const KeyOverride jp109keys[] = { 266static const KeyOverride jp109keys[] = {
267 { 0x03, { Qt::Key_2, '2' , 0x22 , 0xffff } }, 267 { 0x03, { Qt::Key_2, '2' , 0x22 , 0xffff } },
268 { 0x07, { Qt::Key_6, '6' , '&' , 0xffff } }, 268 { 0x07, { Qt::Key_6, '6' , '&' , 0xffff } },
269 { 0x08, { Qt::Key_7, '7' , '\'' , 0xffff } }, 269 { 0x08, { Qt::Key_7, '7' , '\'' , 0xffff } },
270 { 0x09, { Qt::Key_8, '8' , '(' , 0xffff } }, 270 { 0x09, { Qt::Key_8, '8' , '(' , 0xffff } },
271 { 0x0a, { Qt::Key_9, '9' , ')' , 0xffff } }, 271 { 0x0a, { Qt::Key_9, '9' , ')' , 0xffff } },
272 { 0x0b, { Qt::Key_0, '0' , 0xffff , 0xffff } }, 272 { 0x0b, { Qt::Key_0, '0' , 0xffff , 0xffff } },
273 { 0x0c, { Qt::Key_Minus, '-' , '=' , 0xffff } }, 273 { 0x0c, { Qt::Key_Minus, '-' , '=' , 0xffff } },
274 { 0x0d, { Qt::Key_AsciiCircum,'^' , '~' , '^' - 64 } }, 274 { 0x0d, { Qt::Key_AsciiCircum,'^' , '~' , '^' - 64 } },
275 { 0x1a, { Qt::Key_At, '@' , '`' , 0xffff } }, 275 { 0x1a, { Qt::Key_At, '@' , '`' , 0xffff } },
276 { 0x1b, { Qt::Key_BraceLeft, '[' , '{' , '[' - 64 } }, 276 { 0x1b, { Qt::Key_BraceLeft, '[' , '{' , '[' - 64 } },
277 { 0x27, { Qt::Key_Semicolon, ';' , '+' , 0xffff } }, 277 { 0x27, { Qt::Key_Semicolon, ';' , '+' , 0xffff } },
278 { 0x28, { Qt::Key_Colon, ':' , '*' , 0xffff } }, 278 { 0x28, { Qt::Key_Colon, ':' , '*' , 0xffff } },
279 { 0x29, { Qt::Key_Zenkaku_Hankaku, 0xffff , 0xffff , 0xffff } }, 279 { 0x29, { Qt::Key_Zenkaku_Hankaku, 0xffff , 0xffff , 0xffff } },
280 { 0x2b, { Qt::Key_BraceRight, ']' , '}' , ']'-64 } }, 280 { 0x2b, { Qt::Key_BraceRight, ']' , '}' , ']'-64 } },
281 { 0x70, { Qt::Key_Hiragana_Katakana, 0xffff , 0xffff , 0xffff } }, 281 { 0x70, { Qt::Key_Hiragana_Katakana, 0xffff , 0xffff , 0xffff } },
282 { 0x73, { Qt::Key_Backslash, '\\' , '_' , 0xffff } }, 282 { 0x73, { Qt::Key_Backslash, '\\' , '_' , 0xffff } },
283 { 0x79, { Qt::Key_Henkan, 0xffff , 0xffff , 0xffff } }, 283 { 0x79, { Qt::Key_Henkan, 0xffff , 0xffff , 0xffff } },
284 { 0x7b, { Qt::Key_Muhenkan, 0xffff , 0xffff , 0xffff } }, 284 { 0x7b, { Qt::Key_Muhenkan, 0xffff , 0xffff , 0xffff } },
285 { 0x7d, { Qt::Key_yen, 0x00a5 , '|' , 0xffff } }, 285 { 0x7d, { Qt::Key_yen, 0x00a5 , '|' , 0xffff } },
286 { 0x00, { 0, 0xffff , 0xffff , 0xffff } } 286 { 0x00, { 0, 0xffff , 0xffff , 0xffff } }
287}; 287};
288 288
289bool Server::setKeyboardLayout( const QString &kb ) 289bool Server::setKeyboardLayout( const QString &kb )
290{ 290{
291 //quick demo version that can be extended 291 //quick demo version that can be extended
292 292
293 QIntDict<QWSServer::KeyMap> *om = 0; 293 QIntDict<QWSServer::KeyMap> *om = 0;
294 if ( kb == "us101" ) { // No tr 294 if ( kb == "us101" ) { // No tr
295 om = 0; 295 om = 0;
296 } else if ( kb == "jp109" ) { 296 } else if ( kb == "jp109" ) {
297 om = new QIntDict<QWSServer::KeyMap>(37); 297 om = new QIntDict<QWSServer::KeyMap>(37);
298 const KeyOverride *k = jp109keys; 298 const KeyOverride *k = jp109keys;
299 while ( k->scan_code ) { 299 while ( k->scan_code ) {
300 om->insert( k->scan_code, &k->map ); 300 om->insert( k->scan_code, &k->map );
301 k++; 301 k++;
302 } 302 }
303 } 303 }
304 QWSServer::setOverrideKeys( om ); 304 QWSServer::setOverrideKeys( om );
305 305
306 return TRUE; 306 return TRUE;
307} 307}
308 308
309#endif 309#endif
310 310
311void Server::systemMsg(const QCString &msg, const QByteArray &data) 311void Server::systemMsg(const QCString &msg, const QByteArray &data)
312{ 312{
313 QDataStream stream( data, IO_ReadOnly ); 313 QDataStream stream( data, IO_ReadOnly );
314 314
315 if ( msg == "securityChanged()" ) { 315 if ( msg == "securityChanged()" ) {
316 if ( transferServer ) 316 if ( transferServer )
317 transferServer->authorizeConnections(); 317 transferServer->authorizeConnections();
318 if ( qcopBridge ) 318 if ( qcopBridge )
319 qcopBridge->authorizeConnections(); 319 qcopBridge->authorizeConnections();
320 } 320 }
321 /* ### FIXME support TempScreenSaverMode */ 321 /* ### FIXME support TempScreenSaverMode */
322#if 0 322#if 0
323 else if ( msg == "setTempScreenSaverMode(int,int)" ) { 323 else if ( msg == "setTempScreenSaverMode(int,int)" ) {
324 int mode, pid; 324 int mode, pid;
325 stream >> mode >> pid; 325 stream >> mode >> pid;
326 tsmMonitor->setTempMode(mode, pid); 326 tsmMonitor->setTempMode(mode, pid);
327 } 327 }
328#endif 328#endif
329 else if ( msg == "linkChanged(QString)" ) { 329 else if ( msg == "linkChanged(QString)" ) {
330 QString link; 330 QString link;
331 stream >> link; 331 stream >> link;
332 qDebug( "desktop.cpp systemMsg -> linkchanged( %s )", link.latin1() ); 332 qDebug( "desktop.cpp systemMsg -> linkchanged( %s )", link.latin1() );
333 docList->linkChanged(link); 333 docList->linkChanged(link);
334 } else if ( msg == "serviceChanged(QString)" ) { 334 } else if ( msg == "serviceChanged(QString)" ) {
335 MimeType::updateApplications(); 335 MimeType::updateApplications();
336 } else if ( msg == "mkdir(QString)" ) { 336 } else if ( msg == "mkdir(QString)" ) {
337 QString dir; 337 QString dir;
338 stream >> dir; 338 stream >> dir;
339 if ( !dir.isEmpty() ) 339 if ( !dir.isEmpty() )
340 mkdir( dir ); 340 mkdir( dir );
341 } else if ( msg == "rdiffGenSig(QString,QString)" ) { 341 } else if ( msg == "rdiffGenSig(QString,QString)" ) {
342 QString baseFile, sigFile; 342 QString baseFile, sigFile;
343 stream >> baseFile >> sigFile; 343 stream >> baseFile >> sigFile;
344 QRsync::generateSignature( baseFile, sigFile ); 344 QRsync::generateSignature( baseFile, sigFile );
345 } else if ( msg == "rdiffGenDiff(QString,QString,QString)" ) { 345 } else if ( msg == "rdiffGenDiff(QString,QString,QString)" ) {
346 QString baseFile, sigFile, deltaFile; 346 QString baseFile, sigFile, deltaFile;
347 stream >> baseFile >> sigFile >> deltaFile; 347 stream >> baseFile >> sigFile >> deltaFile;
348 QRsync::generateDiff( baseFile, sigFile, deltaFile ); 348 QRsync::generateDiff( baseFile, sigFile, deltaFile );
349 } else if ( msg == "rdiffApplyPatch(QString,QString)" ) { 349 } else if ( msg == "rdiffApplyPatch(QString,QString)" ) {
350 QString baseFile, deltaFile; 350 QString baseFile, deltaFile;
351 stream >> baseFile >> deltaFile; 351 stream >> baseFile >> deltaFile;
352 if ( !QFile::exists( baseFile ) ) { 352 if ( !QFile::exists( baseFile ) ) {
353 QFile f( baseFile ); 353 QFile f( baseFile );
354 f.open( IO_WriteOnly ); 354 f.open( IO_WriteOnly );
355 f.close(); 355 f.close();
356 } 356 }
357 QRsync::applyDiff( baseFile, deltaFile ); 357 QRsync::applyDiff( baseFile, deltaFile );
358#ifndef QT_NO_COP 358#ifndef QT_NO_COP
359 QCopEnvelope e( "QPE/Desktop", "patchApplied(QString)" ); 359 QCopEnvelope e( "QPE/Desktop", "patchApplied(QString)" );
360 e << baseFile; 360 e << baseFile;
361#endif 361#endif
362 } else if ( msg == "rdiffCleanup()" ) { 362 } else if ( msg == "rdiffCleanup()" ) {
363 mkdir( "/tmp/rdiff" ); 363 mkdir( "/tmp/rdiff" );
364 QDir dir; 364 QDir dir;
365 dir.setPath( "/tmp/rdiff" ); 365 dir.setPath( "/tmp/rdiff" );
366 QStringList entries = dir.entryList(); 366 QStringList entries = dir.entryList();
367 for ( QStringList::Iterator it = entries.begin(); it != entries.end(); ++it ) 367 for ( QStringList::Iterator it = entries.begin(); it != entries.end(); ++it )
368 dir.remove( *it ); 368 dir.remove( *it );
369 } else if ( msg == "sendHandshakeInfo()" ) { 369 } else if ( msg == "sendHandshakeInfo()" ) {
370 QString home = getenv( "HOME" ); 370 QString home = getenv( "HOME" );
371#ifndef QT_NO_COP 371#ifndef QT_NO_COP
372 QCopEnvelope e( "QPE/Desktop", "handshakeInfo(QString,bool)" ); 372 QCopEnvelope e( "QPE/Desktop", "handshakeInfo(QString,bool)" );
373 e << home; 373 e << home;
374 int locked = (int) ServerApplication::screenLocked(); 374 int locked = (int) ServerApplication::screenLocked();
375 e << locked; 375 e << locked;
376#endif 376#endif
377 377
378 } 378 }
379 /* 379 /*
380 * QtopiaDesktop relies on the major number 380 * QtopiaDesktop relies on the major number
381 * to start with 1. We're at 0.9 381 * to start with 1. We're at 0.9
382 * so wee need to fake at least 1.4 to be able 382 * so wee need to fake at least 1.4 to be able
383 * to sync with QtopiaDesktop1.6 383 * to sync with QtopiaDesktop1.6
384 */ 384 */
385 else if ( msg == "sendVersionInfo()" ) { 385 else if ( msg == "sendVersionInfo()" ) {
386 QCopEnvelope e( "QPE/Desktop", "versionInfo(QString,QString)" ); 386 QCopEnvelope e( "QPE/Desktop", "versionInfo(QString,QString)" );
387 /* ### FIXME Architecture ### */ 387 /* ### FIXME Architecture ### */
388 e << QString::fromLatin1("1.7") << "Uncustomized Device"; 388 e << QString::fromLatin1("1.7") << "Uncustomized Device";
389 } else if ( msg == "sendCardInfo()" ) { 389 } else if ( msg == "sendCardInfo()" ) {
390#ifndef QT_NO_COP 390#ifndef QT_NO_COP
391 QCopEnvelope e( "QPE/Desktop", "cardInfo(QString)" ); 391 QCopEnvelope e( "QPE/Desktop", "cardInfo(QString)" );
392#endif 392#endif
393 storage->update(); 393 storage->update();
394 const QList<FileSystem> &fs = storage->fileSystems(); 394 const QList<FileSystem> &fs = storage->fileSystems();
395 QListIterator<FileSystem> it ( fs ); 395 QListIterator<FileSystem> it ( fs );
396 QString s; 396 QString s;
397 QString homeDir = getenv("HOME"); 397 QString homeDir = getenv("HOME");
398 QString homeFs, homeFsPath; 398 QString homeFs, homeFsPath;
399 for ( ; it.current(); ++it ) { 399 for ( ; it.current(); ++it ) {
400 int k4 = (*it)->blockSize()/256; 400 int k4 = (*it)->blockSize()/256;
401 if ( (*it)->isRemovable() ) { 401 if ( (*it)->isRemovable() ) {
402 s += (*it)->name() + "=" + (*it)->path() + "/Documents " // No tr 402 s += (*it)->name() + "=" + (*it)->path() + "/Documents " // No tr
403 + QString::number( (*it)->availBlocks() * k4/4 ) 403 + QString::number( (*it)->availBlocks() * k4/4 )
404 + "K " + (*it)->options() + ";"; 404 + "K " + (*it)->options() + ";";
405 } else if ( homeDir.contains( (*it)->path() ) && 405 } else if ( homeDir.contains( (*it)->path() ) &&
406 (*it)->path().length() > homeFsPath.length() ) { 406 (*it)->path().length() > homeFsPath.length() ) {
407 homeFsPath = (*it)->path(); 407 homeFsPath = (*it)->path();
408 homeFs = 408 homeFs =
409 (*it)->name() + "=" + homeDir + "/Documents " // No tr 409 (*it)->name() + "=" + homeDir + "/Documents " // No tr
410 + QString::number( (*it)->availBlocks() * k4/4 ) 410 + QString::number( (*it)->availBlocks() * k4/4 )
411 + "K " + (*it)->options() + ";"; 411 + "K " + (*it)->options() + ";";
412 } 412 }
413 } 413 }
414 if ( !homeFs.isEmpty() ) 414 if ( !homeFs.isEmpty() )
415 s += homeFs; 415 s += homeFs;
416 416
417#ifndef QT_NO_COP 417#ifndef QT_NO_COP
418 e << s; 418 e << s;
419#endif 419#endif
420 } else if ( msg == "sendSyncDate(QString)" ) { 420 } else if ( msg == "sendSyncDate(QString)" ) {
421 QString app; 421 QString app;
422 stream >> app; 422 stream >> app;
423 Config cfg( "qpe" ); 423 Config cfg( "qpe" );
424 cfg.setGroup("SyncDate"); 424 cfg.setGroup("SyncDate");
425#ifndef QT_NO_COP 425#ifndef QT_NO_COP
426 QCopEnvelope e( "QPE/Desktop", "syncDate(QString,QString)" ); 426 QCopEnvelope e( "QPE/Desktop", "syncDate(QString,QString)" );
427 e << app << cfg.readEntry( app ); 427 e << app << cfg.readEntry( app );
428#endif 428#endif
429 //qDebug("QPE/System sendSyncDate for %s: response %s", app.latin1(), 429 //qDebug("QPE/System sendSyncDate for %s: response %s", app.latin1(),
430 //cfg.readEntry( app ).latin1() ); 430 //cfg.readEntry( app ).latin1() );
431 } else if ( msg == "setSyncDate(QString,QString)" ) { 431 } else if ( msg == "setSyncDate(QString,QString)" ) {
432 QString app, date; 432 QString app, date;
433 stream >> app >> date; 433 stream >> app >> date;
434 Config cfg( "qpe" ); 434 Config cfg( "qpe" );
435 cfg.setGroup("SyncDate"); 435 cfg.setGroup("SyncDate");
436 cfg.writeEntry( app, date ); 436 cfg.writeEntry( app, date );
437 //qDebug("setSyncDate(QString,QString) %s %s", app.latin1(), date.latin1()); 437 //qDebug("setSyncDate(QString,QString) %s %s", app.latin1(), date.latin1());
438 } else if ( msg == "startSync(QString)" ) { 438 } else if ( msg == "startSync(QString)" ) {
439 QString what; 439 QString what;
440 stream >> what; 440 stream >> what;
441 delete syncDialog; 441 delete syncDialog;
442 syncDialog = new SyncDialog( this, what ); 442 syncDialog = new SyncDialog( this, what );
443 syncDialog->show(); 443 syncDialog->show();
444 connect( syncDialog, SIGNAL(cancel()), SLOT(cancelSync()) ); 444 connect( syncDialog, SIGNAL(cancel()), SLOT(cancelSync()) );
445 } else if ( msg == "stopSync()") { 445 } else if ( msg == "stopSync()") {
446 delete syncDialog; 446 delete syncDialog;
447 syncDialog = 0; 447 syncDialog = 0;
448 } else if (msg == "restoreDone(QString)") { 448 } else if (msg == "restoreDone(QString)") {
449 docList->restoreDone(); 449 docList->restoreDone();
450 } else if ( msg == "getAllDocLinks()" ) { 450 } else if ( msg == "getAllDocLinks()" ) {
451 docList->sendAllDocLinks(); 451 docList->sendAllDocLinks();
452 } 452 }
453#ifdef Q_WS_QWS 453#ifdef Q_WS_QWS
454 else if ( msg == "setMouseProto(QString)" ) { 454 else if ( msg == "setMouseProto(QString)" ) {
455 QString mice; 455 QString mice;
456 stream >> mice; 456 stream >> mice;
457 setenv("QWS_MOUSE_PROTO",mice.latin1(),1); 457 setenv("QWS_MOUSE_PROTO",mice.latin1(),1);
458 qwsServer->openMouse(); 458 qwsServer->openMouse();
459 } else if ( msg == "setKeyboard(QString)" ) { 459 } else if ( msg == "setKeyboard(QString)" ) {
460 QString kb; 460 QString kb;
461 stream >> kb; 461 stream >> kb;
462 setenv("QWS_KEYBOARD",kb.latin1(),1); 462 setenv("QWS_KEYBOARD",kb.latin1(),1);
463 qwsServer->openKeyboard(); 463 qwsServer->openKeyboard();
464 464
465 } else if ( msg == "setKeyboardAutoRepeat(int,int)" ) { 465 } else if ( msg == "setKeyboardAutoRepeat(int,int)" ) {
466 int delay, period; 466 int delay, period;
467 stream >> delay >> period; 467 stream >> delay >> period;
468 qwsSetKeyboardAutoRepeat( delay, period ); 468 qwsSetKeyboardAutoRepeat( delay, period );
469 Config cfg( "qpe" ); 469 Config cfg( "qpe" );
470 cfg.setGroup("Keyboard"); 470 cfg.setGroup("Keyboard");
471 cfg.writeEntry( "RepeatDelay", delay ); 471 cfg.writeEntry( "RepeatDelay", delay );
472 cfg.writeEntry( "RepeatPeriod", period ); 472 cfg.writeEntry( "RepeatPeriod", period );
473 } else if ( msg == "setKeyboardLayout(QString)" ) { 473 } else if ( msg == "setKeyboardLayout(QString)" ) {
474 QString kb; 474 QString kb;
475 stream >> kb; 475 stream >> kb;
476 setKeyboardLayout( kb ); 476 setKeyboardLayout( kb );
477 Config cfg( "qpe" ); 477 Config cfg( "qpe" );
478 cfg.setGroup("Keyboard"); 478 cfg.setGroup("Keyboard");
479 cfg.writeEntry( "Layout", kb ); 479 cfg.writeEntry( "Layout", kb );
480 } else if ( msg == "autoStart(QString)" ) { 480 } else if ( msg == "autoStart(QString)" ) {
481 QString appName; 481 QString appName;
482 stream >> appName; 482 stream >> appName;
483 Config cfg( "autostart" ); 483 Config cfg( "autostart" );
484 cfg.setGroup( "AutoStart" ); 484 cfg.setGroup( "AutoStart" );
485 if ( appName.compare("clear") == 0){ 485 if ( appName.compare("clear") == 0){
486 cfg.writeEntry("Apps", ""); 486 cfg.writeEntry("Apps", "");
487 } 487 }
488 } else if ( msg == "autoStart(QString,QString)" ) { 488 } else if ( msg == "autoStart(QString,QString)" ) {
489 QString modifier, appName; 489 QString modifier, appName;
490 stream >> modifier >> appName; 490 stream >> modifier >> appName;
491 Config cfg( "autostart" ); 491 Config cfg( "autostart" );
492 cfg.setGroup( "AutoStart" ); 492 cfg.setGroup( "AutoStart" );
493 if ( modifier.compare("add") == 0 ){ 493 if ( modifier.compare("add") == 0 ){
494 // only add if appname is entered 494 // only add if appname is entered
495 if (!appName.isEmpty()) { 495 if (!appName.isEmpty()) {
496 cfg.writeEntry("Apps", appName); 496 cfg.writeEntry("Apps", appName);
497 } 497 }
498 } else if (modifier.compare("remove") == 0 ) { 498 } else if (modifier.compare("remove") == 0 ) {
499 // need to change for multiple entries 499 // need to change for multiple entries
500 // actually remove is right now simular to clear, but in future there 500 // actually remove is right now simular to clear, but in future there
501 // should be multiple apps in autostart possible. 501 // should be multiple apps in autostart possible.
502 QString checkName; 502 QString checkName;
503 checkName = cfg.readEntry("Apps", ""); 503 checkName = cfg.readEntry("Apps", "");
504 if (checkName == appName) { 504 if (checkName == appName) {
505 cfg.writeEntry("Apps", ""); 505 cfg.writeEntry("Apps", "");
506 } 506 }
507 } 507 }
508 // case the autostart feature should be delayed 508 // case the autostart feature should be delayed
509 } else if ( msg == "autoStart(QString,QString,QString)") { 509 } else if ( msg == "autoStart(QString,QString,QString)") {
510 QString modifier, appName, delay; 510 QString modifier, appName, delay;
511 stream >> modifier >> appName >> delay; 511 stream >> modifier >> appName >> delay;
512 Config cfg( "autostart" ); 512 Config cfg( "autostart" );
513 513
514 cfg.setGroup( "AutoStart" ); 514 cfg.setGroup( "AutoStart" );
515 if ( modifier.compare("add") == 0 ){ 515 if ( modifier.compare("add") == 0 ){
516 // only add it appname is entered 516 // only add it appname is entered
517 if (!appName.isEmpty()) { 517 if (!appName.isEmpty()) {
518 cfg.writeEntry("Apps", appName); 518 cfg.writeEntry("Apps", appName);
519 cfg.writeEntry("Delay", delay); 519 cfg.writeEntry("Delay", delay);
520 } 520 }
521 } else { 521 } else {
522 } 522 }
523 } 523 }
524#endif 524#endif
525} 525}
526 526
527void Server::receiveTaskBar(const QCString &msg, const QByteArray &data) 527void Server::receiveTaskBar(const QCString &msg, const QByteArray &data)
528{ 528{
529 QDataStream stream( data, IO_ReadOnly ); 529 QDataStream stream( data, IO_ReadOnly );
530 530
531 if ( msg == "reloadApps()" ) { 531 if ( msg == "reloadApps()" ) {
532 docList->reloadAppLnks(); 532 docList->reloadAppLnks();
533 } else if ( msg == "soundAlarm()" ) { 533 } else if ( msg == "soundAlarm()" ) {
534 ServerApplication::soundAlarm(); 534 ServerApplication::soundAlarm();
535 } 535 }
536 else if ( msg == "setLed(int,bool)" ) { 536 else if ( msg == "setLed(int,bool)" ) {
537 int led, status; 537 int led, status;
538 stream >> led >> status; 538 stream >> led >> status;
539 539
540 QValueList <OLed> ll = ODevice::inst ( )-> ledList ( ); 540 QValueList <OLed> ll = ODevice::inst ( )-> ledList ( );
541 if ( ll. count ( )){ 541 if ( ll. count ( )){
542 OLed l = ll. contains ( Led_Mail ) ? Led_Mail : ll [0]; 542 OLed l = ll. contains ( Led_Mail ) ? Led_Mail : ll [0];
543 bool canblink = ODevice::inst ( )-> ledStateList ( l ). contains ( Led_BlinkSlow ); 543 bool canblink = ODevice::inst ( )-> ledStateList ( l ). contains ( Led_BlinkSlow );
544 544
545 ODevice::inst ( )-> setLedState ( l, status ? ( canblink ? Led_BlinkSlow : Led_On ) : Led_Off ); 545 ODevice::inst ( )-> setLedState ( l, status ? ( canblink ? Led_BlinkSlow : Led_On ) : Led_Off );
546 } 546 }
547 } 547 }
548} 548}
549 549
550void Server::cancelSync() 550void Server::cancelSync()
551{ 551{
552#ifndef QT_NO_COP 552#ifndef QT_NO_COP
553 QCopEnvelope e( "QPE/Desktop", "cancelSync()" ); 553 QCopEnvelope e( "QPE/Desktop", "cancelSync()" );
554#endif 554#endif
555 delete syncDialog; 555 delete syncDialog;
556 syncDialog = 0; 556 syncDialog = 0;
557} 557}
558 558
559bool Server::mkdir(const QString &localPath) 559bool Server::mkdir(const QString &localPath)
560{ 560{
561 QDir fullDir(localPath); 561 QDir fullDir(localPath);
562 if (fullDir.exists()) 562 if (fullDir.exists())
563 return true; 563 return true;
564 564
565 // at this point the directory doesn't exist 565 // at this point the directory doesn't exist
566 // go through the directory tree and start creating the direcotories 566 // go through the directory tree and start creating the direcotories
567 // that don't exist; if we can't create the directories, return false 567 // that don't exist; if we can't create the directories, return false
568 568
569 QString dirSeps = "/"; 569 QString dirSeps = "/";
570 int dirIndex = localPath.find(dirSeps); 570 int dirIndex = localPath.find(dirSeps);
571 QString checkedPath; 571 QString checkedPath;
572 572
573 // didn't find any seps; weird, use the cur dir instead 573 // didn't find any seps; weird, use the cur dir instead
574 if (dirIndex == -1) { 574 if (dirIndex == -1) {
575 //qDebug("No seperators found in path %s", localPath.latin1()); 575 //qDebug("No seperators found in path %s", localPath.latin1());
576 checkedPath = QDir::currentDirPath(); 576 checkedPath = QDir::currentDirPath();
577 } 577 }
578 578
579 while (checkedPath != localPath) { 579 while (checkedPath != localPath) {
580 // no more seperators found, use the local path 580 // no more seperators found, use the local path
581 if (dirIndex == -1) 581 if (dirIndex == -1)
582 checkedPath = localPath; 582 checkedPath = localPath;
583 else { 583 else {
584 // the next directory to check 584 // the next directory to check
585 checkedPath = localPath.left(dirIndex) + "/"; 585 checkedPath = localPath.left(dirIndex) + "/";
586 // advance the iterator; the next dir seperator 586 // advance the iterator; the next dir seperator
587 dirIndex = localPath.find(dirSeps, dirIndex+1); 587 dirIndex = localPath.find(dirSeps, dirIndex+1);
588 } 588 }
589 589
590 QDir checkDir(checkedPath); 590 QDir checkDir(checkedPath);
591 if (!checkDir.exists()) { 591 if (!checkDir.exists()) {
592 //qDebug("mkdir making dir %s", checkedPath.latin1()); 592 //qDebug("mkdir making dir %s", checkedPath.latin1());
593 593
594 if (!checkDir.mkdir(checkedPath)) { 594 if (!checkDir.mkdir(checkedPath)) {
595 qDebug("Unable to make directory %s", checkedPath.latin1()); 595 qDebug("Unable to make directory %s", checkedPath.latin1());
596 return FALSE; 596 return FALSE;
597 } 597 }
598 } 598 }
599 599
600 } 600 }
601 return TRUE; 601 return TRUE;
602} 602}
603 603
604void Server::styleChange( QStyle &s ) 604void Server::styleChange( QStyle &s )
605{ 605{
606 QWidget::styleChange( s ); 606 QWidget::styleChange( s );
607} 607}
608 608
609void Server::startTransferServer() 609void Server::startTransferServer()
610{ 610{
611 if ( !qcopBridge ) { 611 if ( !qcopBridge ) {
612 // start qcop bridge server 612 // start qcop bridge server
613 qcopBridge = new QCopBridge( 4243 ); 613 qcopBridge = new QCopBridge( 4243 );
614 if ( qcopBridge->ok() ) { 614 if ( qcopBridge->ok() ) {
615 // ... OK 615 // ... OK
616 connect( qcopBridge, SIGNAL(connectionClosed(const QHostAddress&)), 616 connect( qcopBridge, SIGNAL(connectionClosed(const QHostAddress&)),
617 this, SLOT(syncConnectionClosed(const QHostAddress&)) ); 617 this, SLOT(syncConnectionClosed(const QHostAddress&)) );
618 } else { 618 } else {
619 delete qcopBridge; 619 delete qcopBridge;
620 qcopBridge = 0; 620 qcopBridge = 0;
621 } 621 }
622 } 622 }
623 if ( !transferServer ) { 623 if ( !transferServer ) {
624 // start transfer server 624 // start transfer server
625 transferServer = new TransferServer( 4242 ); 625 transferServer = new TransferServer( 4242 );
626 if ( transferServer->ok() ) { 626 if ( transferServer->ok() ) {
627 // ... OK 627 // ... OK
628 } else { 628 } else {
629 delete transferServer; 629 delete transferServer;
630 transferServer = 0; 630 transferServer = 0;
631 } 631 }
632 } 632 }
633 if ( !transferServer || !qcopBridge ) 633 if ( !transferServer || !qcopBridge )
634 tid_xfer = startTimer( 2000 ); 634 tid_xfer = startTimer( 2000 );
635} 635}
636 636
637void Server::timerEvent( QTimerEvent *e ) 637void Server::timerEvent( QTimerEvent *e )
638{ 638{
639 if ( e->timerId() == tid_xfer ) { 639 if ( e->timerId() == tid_xfer ) {
640 killTimer( tid_xfer ); 640 killTimer( tid_xfer );
641 tid_xfer = 0; 641 tid_xfer = 0;
642 startTransferServer(); 642 startTransferServer();
643 } 643 }
644 /* ### FIXME today startin */ 644 /* ### FIXME today startin */
645#if 0 645#if 0
646 else if ( e->timerId() == tid_today ) { 646 else if ( e->timerId() == tid_today ) {
647 QDate today = QDate::currentDate(); 647 QDate today = QDate::currentDate();
648 if ( today != last_today_show ) { 648 if ( today != last_today_show ) {
649 last_today_show = today; 649 last_today_show = today;
650 Config cfg("today"); 650 Config cfg("today");
651 cfg.setGroup("Start"); 651 cfg.setGroup("Start");
652#ifndef QPE_DEFAULT_TODAY_MODE 652#ifndef QPE_DEFAULT_TODAY_MODE
653#define QPE_DEFAULT_TODAY_MODE "Never" 653#define QPE_DEFAULT_TODAY_MODE "Never"
654#endif 654#endif
655 if ( cfg.readEntry("Mode",QPE_DEFAULT_TODAY_MODE) == "Daily" ) { 655 if ( cfg.readEntry("Mode",QPE_DEFAULT_TODAY_MODE) == "Daily" ) {
656 QCopEnvelope env(Service::channel("today"),"raise()"); 656 QCopEnvelope env(Service::channel("today"),"raise()");
657 } 657 }
658 } 658 }
659 } 659 }
660#endif 660#endif
661} 661}
662 662
663void Server::terminateServers() 663void Server::terminateServers()
664{ 664{
665 delete transferServer; 665 delete transferServer;
666 delete qcopBridge; 666 delete qcopBridge;
667 transferServer = 0; 667 transferServer = 0;
668 qcopBridge = 0; 668 qcopBridge = 0;
669} 669}
670 670
671void Server::syncConnectionClosed( const QHostAddress & ) 671void Server::syncConnectionClosed( const QHostAddress & )
672{ 672{
673 qDebug( "Lost sync connection" ); 673 qDebug( "Lost sync connection" );
674 delete syncDialog; 674 delete syncDialog;
675 syncDialog = 0; 675 syncDialog = 0;
676} 676}
677 677
678void Server::pokeTimeMonitors() 678void Server::pokeTimeMonitors()
679{ 679{
680#if 0 680#if 0
681 // inform all TimeMonitors 681 // inform all TimeMonitors
682 QStrList tms = Service::channels("TimeMonitor"); 682 QStrList tms = Service::channels("TimeMonitor");
683 for (const char* ch = tms.first(); ch; ch=tms.next()) { 683 for (const char* ch = tms.first(); ch; ch=tms.next()) {
684 QString t = getenv("TZ"); 684 QString t = getenv("TZ");
685 QCopEnvelope e(ch, "timeChange(QString)"); 685 QCopEnvelope e(ch, "timeChange(QString)");
686 e << t; 686 e << t;
687 } 687 }
688#endif 688#endif
689} 689}
690 690
691void Server::applicationLaunched(int, const QString &app) 691void Server::applicationLaunched(int, const QString &app)
692{ 692{
693 serverGui->applicationStateChanged( app, ServerInterface::Launching ); 693 serverGui->applicationStateChanged( app, ServerInterface::Launching );
694} 694}
695 695
696void Server::applicationTerminated(int pid, const QString &app) 696void Server::applicationTerminated(int pid, const QString &app)
697{ 697{
698 serverGui->applicationStateChanged( app, ServerInterface::Terminated ); 698 serverGui->applicationStateChanged( app, ServerInterface::Terminated );
699#if 0 699#if 0
700 tsmMonitor->applicationTerminated( pid ); 700 tsmMonitor->applicationTerminated( pid );
701#endif 701#endif
702} 702}
703 703
704void Server::applicationConnected(const QString &app) 704void Server::applicationConnected(const QString &app)
705{ 705{
706 serverGui->applicationStateChanged( app, ServerInterface::Running ); 706 serverGui->applicationStateChanged( app, ServerInterface::Running );
707} 707}
708 708
709void Server::storageChanged() 709void Server::storageChanged()
710{ 710{
711 system( "qtopia-update-symlinks" ); 711 system( "qtopia-update-symlinks" );
712 serverGui->storageChanged( storage->fileSystems() ); 712 serverGui->storageChanged( storage->fileSystems() );
713 docList->storageChanged(); 713 docList->storageChanged();
714} 714}
715 715
716 716
717 717
718void Server::preloadApps() 718void Server::preloadApps()
719{ 719{
720 Config cfg("Launcher"); 720 Config cfg("Launcher");
721 cfg.setGroup("Preload"); 721 cfg.setGroup("Preload");
722 QStringList apps = cfg.readListEntry("Apps",','); 722 QStringList apps = cfg.readListEntry("Apps",',');
723 for (QStringList::ConstIterator it=apps.begin(); it!=apps.end(); ++it) { 723 for (QStringList::ConstIterator it=apps.begin(); it!=apps.end(); ++it) {
724#ifndef QT_NO_COP 724#ifndef QT_NO_COP
725 QCopEnvelope e("QPE/Application/"+(*it).local8Bit(), "enablePreload()"); 725 QCopEnvelope e("QPE/Application/"+(*it).local8Bit(), "enablePreload()");
726#endif 726#endif
727 } 727 }
728} 728}
729 729
diff --git a/core/launcher/server.h b/core/launcher/server.h
index 91bf883..1dc5e7e 100644
--- a/core/launcher/server.h
+++ b/core/launcher/server.h
@@ -1,97 +1,99 @@
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#ifndef DESKTOP_H 20#ifndef DESKTOP_H
21#define DESKTOP_H 21#define DESKTOP_H
22 22
23#include <qwidget.h> 23#include <qwidget.h>
24#include <qdatetime.h> 24#include <qdatetime.h>
25 25
26//#include "qcopbridge.h" 26//#include "qcopbridge.h"
27 27
28class QCopBridge; 28class QCopBridge;
29class QHostAddress; 29class QHostAddress;
30class TransferServer; 30class TransferServer;
31class PackageHandler; 31class PackageHandler;
32class ServiceRequest; 32class ServiceRequest;
33class TempScreenSaverMonitor; 33class TempScreenSaverMonitor;
34class AppLauncher; 34class AppLauncher;
35class AppLnkSet; 35class AppLnkSet;
36class StorageInfo; 36class StorageInfo;
37class SyncDialog; 37class SyncDialog;
38class DocumentList; 38class DocumentList;
39class ServerInterface; 39class ServerInterface;
40namespace Opie { 40namespace Opie {
41namespace Core {
41 class ODeviceButton; 42 class ODeviceButton;
42} 43}
44}
43 45
44class Server : public QWidget { 46class Server : public QWidget {
45 Q_OBJECT 47 Q_OBJECT
46public: 48public:
47 Server(); 49 Server();
48 ~Server(); 50 ~Server();
49 51
50 static bool mkdir(const QString &path); 52 static bool mkdir(const QString &path);
51 53
52 void show(); 54 void show();
53 55
54 static bool setKeyboardLayout( const QString &kb ); 56 static bool setKeyboardLayout( const QString &kb );
55 57
56public slots: 58public slots:
57 void systemMsg(const QCString &, const QByteArray &); 59 void systemMsg(const QCString &, const QByteArray &);
58 void receiveTaskBar(const QCString &msg, const QByteArray &data); 60 void receiveTaskBar(const QCString &msg, const QByteArray &data);
59 void terminateServers(); 61 void terminateServers();
60 void pokeTimeMonitors(); 62 void pokeTimeMonitors();
61 63
62private slots: 64private slots:
63 void activate(const Opie::ODeviceButton*,bool); 65 void activate(const Opie::Core::ODeviceButton*,bool);
64 void syncConnectionClosed( const QHostAddress & ); 66 void syncConnectionClosed( const QHostAddress & );
65 void applicationLaunched(int pid, const QString &app); 67 void applicationLaunched(int pid, const QString &app);
66 void applicationTerminated(int pid, const QString &app); 68 void applicationTerminated(int pid, const QString &app);
67 void applicationConnected(const QString &app); 69 void applicationConnected(const QString &app);
68 void storageChanged(); 70 void storageChanged();
69 void cancelSync(); 71 void cancelSync();
70 72
71protected: 73protected:
72 void styleChange( QStyle & ); 74 void styleChange( QStyle & );
73 void timerEvent( QTimerEvent *e ); 75 void timerEvent( QTimerEvent *e );
74 76
75private: 77private:
76 void layout(); 78 void layout();
77 void startTransferServer(); 79 void startTransferServer();
78 void preloadApps(); 80 void preloadApps();
79 81
80 QCopBridge *qcopBridge; 82 QCopBridge *qcopBridge;
81 TransferServer *transferServer; 83 TransferServer *transferServer;
82 PackageHandler *packageHandler; 84 PackageHandler *packageHandler;
83 QDate last_today_show; 85 QDate last_today_show;
84 int tid_xfer; 86 int tid_xfer;
85 /* ### FIXME two below### */ 87 /* ### FIXME two below### */
86// int tid_today; 88// int tid_today;
87// TempScreenSaverMonitor *tsmMonitor; 89// TempScreenSaverMonitor *tsmMonitor;
88 StorageInfo *storage; 90 StorageInfo *storage;
89 SyncDialog *syncDialog; 91 SyncDialog *syncDialog;
90 AppLauncher *appLauncher; 92 AppLauncher *appLauncher;
91 DocumentList *docList; 93 DocumentList *docList;
92 ServerInterface *serverGui; 94 ServerInterface *serverGui;
93}; 95};
94 96
95 97
96#endif // DESKTOP_H 98#endif // DESKTOP_H
97 99
diff --git a/core/launcher/serverapp.cpp b/core/launcher/serverapp.cpp
index d38dd97..e4e16f2 100644
--- a/core/launcher/serverapp.cpp
+++ b/core/launcher/serverapp.cpp
@@ -1,862 +1,863 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2003 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2003 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 "serverapp.h" 21#include "serverapp.h"
22 22
23#include <opie2/odevice.h> 23#include <opie2/odevice.h>
24 24
25#include <qtopia/password.h> 25#include <qtopia/password.h>
26#include <qtopia/config.h> 26#include <qtopia/config.h>
27#include <qtopia/power.h> 27#include <qtopia/power.h>
28 28
29#ifdef Q_WS_QWS 29#ifdef Q_WS_QWS
30#include <qtopia/qcopenvelope_qws.h> 30#include <qtopia/qcopenvelope_qws.h>
31#endif 31#endif
32#include <qtopia/global.h> 32#include <qtopia/global.h>
33//#include <qtopia/custom.h> 33//#include <qtopia/custom.h>
34 34
35#ifdef Q_WS_QWS 35#ifdef Q_WS_QWS
36#include <qgfx_qws.h> 36#include <qgfx_qws.h>
37#endif 37#endif
38#ifdef Q_OS_WIN32 38#ifdef Q_OS_WIN32
39#include <io.h> 39#include <io.h>
40#include <process.h> 40#include <process.h>
41#else 41#else
42#include <unistd.h> 42#include <unistd.h>
43#endif 43#endif
44#include <qmessagebox.h> 44#include <qmessagebox.h>
45#include <qtimer.h> 45#include <qtimer.h>
46#include <qpainter.h> 46#include <qpainter.h>
47#include <qfile.h> 47#include <qfile.h>
48#include <qpixmapcache.h> 48#include <qpixmapcache.h>
49 49
50#include <stdlib.h> 50#include <stdlib.h>
51#include "screensaver.h" 51#include "screensaver.h"
52 52
53static ServerApplication *serverApp = 0; 53static ServerApplication *serverApp = 0;
54static int loggedin=0; 54static int loggedin=0;
55 55
56using namespace Opie; 56using namespace Opie;
57 57
58using namespace Opie::Core;
58QCopKeyRegister::QCopKeyRegister() 59QCopKeyRegister::QCopKeyRegister()
59 : m_keyCode( 0 ) { 60 : m_keyCode( 0 ) {
60} 61}
61 62
62QCopKeyRegister::QCopKeyRegister( int k, const QCString& c, const QCString& m ) 63QCopKeyRegister::QCopKeyRegister( int k, const QCString& c, const QCString& m )
63 :m_keyCode( k ), m_channel( c ), m_message( m ) { 64 :m_keyCode( k ), m_channel( c ), m_message( m ) {
64} 65}
65 66
66int QCopKeyRegister::keyCode()const { 67int QCopKeyRegister::keyCode()const {
67 return m_keyCode; 68 return m_keyCode;
68} 69}
69 70
70QCString QCopKeyRegister::channel()const { 71QCString QCopKeyRegister::channel()const {
71 return m_channel; 72 return m_channel;
72} 73}
73 74
74QCString QCopKeyRegister::message()const { 75QCString QCopKeyRegister::message()const {
75 return m_message; 76 return m_message;
76} 77}
77 78
78bool QCopKeyRegister::send() { 79bool QCopKeyRegister::send() {
79 if (m_channel.isNull() ) 80 if (m_channel.isNull() )
80 return false; 81 return false;
81 82
82 QCopEnvelope( m_channel, m_message ); 83 QCopEnvelope( m_channel, m_message );
83 84
84 return true; 85 return true;
85} 86}
86 87
87//--------------------------------------------------------------------------- 88//---------------------------------------------------------------------------
88 89
89/* 90/*
90 Priority is number of alerts that are needed to pop up 91 Priority is number of alerts that are needed to pop up
91 alert. 92 alert.
92 */ 93 */
93class DesktopPowerAlerter : public QMessageBox 94class DesktopPowerAlerter : public QMessageBox
94{ 95{
95 Q_OBJECT 96 Q_OBJECT
96public: 97public:
97 DesktopPowerAlerter( QWidget *parent, const char *name = 0 ) 98 DesktopPowerAlerter( QWidget *parent, const char *name = 0 )
98 : QMessageBox( tr("Battery Status"), tr("Low Battery"), 99 : QMessageBox( tr("Battery Status"), tr("Low Battery"),
99 QMessageBox::Critical, 100 QMessageBox::Critical,
100 QMessageBox::Ok | QMessageBox::Default, 101 QMessageBox::Ok | QMessageBox::Default,
101 QMessageBox::NoButton, QMessageBox::NoButton, 102 QMessageBox::NoButton, QMessageBox::NoButton,
102 parent, name, FALSE ) 103 parent, name, FALSE )
103 { 104 {
104 currentPriority = INT_MAX; 105 currentPriority = INT_MAX;
105 alertCount = 0; 106 alertCount = 0;
106 } 107 }
107 108
108 void alert( const QString &text, int priority ); 109 void alert( const QString &text, int priority );
109 void hideEvent( QHideEvent * ); 110 void hideEvent( QHideEvent * );
110private: 111private:
111 int currentPriority; 112 int currentPriority;
112 int alertCount; 113 int alertCount;
113}; 114};
114 115
115void DesktopPowerAlerter::alert( const QString &text, int priority ) 116void DesktopPowerAlerter::alert( const QString &text, int priority )
116{ 117{
117 alertCount++; 118 alertCount++;
118 if ( alertCount < priority ) 119 if ( alertCount < priority )
119 return; 120 return;
120 if ( priority > currentPriority ) 121 if ( priority > currentPriority )
121 return; 122 return;
122 currentPriority = priority; 123 currentPriority = priority;
123 setText( text ); 124 setText( text );
124 show(); 125 show();
125} 126}
126 127
127 128
128void DesktopPowerAlerter::hideEvent( QHideEvent *e ) 129void DesktopPowerAlerter::hideEvent( QHideEvent *e )
129{ 130{
130 QMessageBox::hideEvent( e ); 131 QMessageBox::hideEvent( e );
131 alertCount = 0; 132 alertCount = 0;
132 currentPriority = INT_MAX; 133 currentPriority = INT_MAX;
133} 134}
134 135
135//--------------------------------------------------------------------------- 136//---------------------------------------------------------------------------
136 137
137KeyFilter::KeyFilter(QObject* parent) : QObject(parent), held_tid(0), heldButton(0) 138KeyFilter::KeyFilter(QObject* parent) : QObject(parent), held_tid(0), heldButton(0)
138{ 139{
139 /* We don't do this cause it would interfere with ODevice */ 140 /* We don't do this cause it would interfere with ODevice */
140#if 0 141#if 0
141 qwsServer->setKeyboardFilter(this); 142 qwsServer->setKeyboardFilter(this);
142#endif 143#endif
143} 144}
144 145
145void KeyFilter::timerEvent(QTimerEvent* e) 146void KeyFilter::timerEvent(QTimerEvent* e)
146{ 147{
147 if ( e->timerId() == held_tid ) { 148 if ( e->timerId() == held_tid ) {
148 killTimer(held_tid); 149 killTimer(held_tid);
149 // button held 150 // button held
150 if ( heldButton ) { 151 if ( heldButton ) {
151 emit activate(heldButton, TRUE); 152 emit activate(heldButton, TRUE);
152 heldButton = 0; 153 heldButton = 0;
153 } 154 }
154 held_tid = 0; 155 held_tid = 0;
155 } 156 }
156} 157}
157 158
158void KeyFilter::registerKey( const QCopKeyRegister& key ) { 159void KeyFilter::registerKey( const QCopKeyRegister& key ) {
159 m_keys.insert( key.keyCode(), key ); 160 m_keys.insert( key.keyCode(), key );
160} 161}
161 162
162void KeyFilter::unregisterKey( const QCopKeyRegister& key ) { 163void KeyFilter::unregisterKey( const QCopKeyRegister& key ) {
163 m_keys.remove( key.keyCode() ); 164 m_keys.remove( key.keyCode() );
164} 165}
165 166
166bool KeyFilter::keyRegistered( int key ) { 167bool KeyFilter::keyRegistered( int key ) {
167 /* 168 /*
168 * Check if we've a key registered 169 * Check if we've a key registered
169 */ 170 */
170 if ( !m_keys[key].send()) 171 if ( !m_keys[key].send())
171 return false; 172 return false;
172 else 173 else
173 return true; 174 return true;
174 175
175} 176}
176 177
177bool KeyFilter::checkButtonAction(bool db, int keycode, int press, int autoRepeat) 178bool KeyFilter::checkButtonAction(bool db, int keycode, int press, int autoRepeat)
178{ 179{
179 if ( !loggedin 180 if ( !loggedin
180 // Permitted keys 181 // Permitted keys
181 && keycode != Key_F34 // power 182 && keycode != Key_F34 // power
182 && keycode != Key_F30 // select 183 && keycode != Key_F30 // select
183 && keycode != Key_Enter 184 && keycode != Key_Enter
184 && keycode != Key_Return 185 && keycode != Key_Return
185 && keycode != Key_Space 186 && keycode != Key_Space
186 && keycode != Key_Left 187 && keycode != Key_Left
187 && keycode != Key_Right 188 && keycode != Key_Right
188 && keycode != Key_Up 189 && keycode != Key_Up
189 && keycode != Key_Down ) 190 && keycode != Key_Down )
190 return TRUE; 191 return TRUE;
191 192
192 /* check if it was registered */ 193 /* check if it was registered */
193 if (!db ) { 194 if (!db ) {
194 if (keycode != 0 &&press && !autoRepeat && keyRegistered(keycode) ) 195 if (keycode != 0 &&press && !autoRepeat && keyRegistered(keycode) )
195 return true; 196 return true;
196 }else { 197 }else {
197 198
198 199
199 // First check to see if DeviceButtonManager knows something about this button: 200 // First check to see if DeviceButtonManager knows something about this button:
200 const Opie::ODeviceButton* button = Opie::ODevice::inst()->buttonForKeycode(keycode); 201 const ODeviceButton* button = ODevice::inst()->buttonForKeycode(keycode);
201 if (button && !autoRepeat) { 202 if (button && !autoRepeat) {
202 if ( held_tid ) { 203 if ( held_tid ) {
203 killTimer(held_tid); 204 killTimer(held_tid);
204 held_tid = 0; 205 held_tid = 0;
205 } 206 }
206 if ( button->heldAction().isNull() ) { 207 if ( button->heldAction().isNull() ) {
207 if ( press ) 208 if ( press )
208 emit activate(button, FALSE); 209 emit activate(button, FALSE);
209 } else if ( press ) { 210 } else if ( press ) {
210 heldButton = button; 211 heldButton = button;
211 held_tid = startTimer( ODevice::inst ()->buttonHoldTime () ); 212 held_tid = startTimer( ODevice::inst ()->buttonHoldTime () );
212 } else if ( heldButton ) { 213 } else if ( heldButton ) {
213 heldButton = 0; 214 heldButton = 0;
214 emit activate(button, FALSE); 215 emit activate(button, FALSE);
215 } 216 }
216 QWSServer::screenSaverActivate(FALSE); 217 QWSServer::screenSaverActivate(FALSE);
217 return TRUE; 218 return TRUE;
218 } 219 }
219 return false; 220 return false;
220 } 221 }
221 if ( keycode == HardKey_Suspend ) { 222 if ( keycode == HardKey_Suspend ) {
222 if ( press ) emit power(); 223 if ( press ) emit power();
223 return TRUE; 224 return TRUE;
224 } 225 }
225 if ( keycode == HardKey_Backlight ) { 226 if ( keycode == HardKey_Backlight ) {
226 if ( press ) emit backlight(); 227 if ( press ) emit backlight();
227 return TRUE; 228 return TRUE;
228 } 229 }
229 if ( keycode == Key_F32 ) { 230 if ( keycode == Key_F32 ) {
230#ifndef QT_NO_COP 231#ifndef QT_NO_COP
231 if ( press ) QCopEnvelope e( "QPE/Desktop", "startSync()" ); 232 if ( press ) QCopEnvelope e( "QPE/Desktop", "startSync()" );
232#endif 233#endif
233 return TRUE; 234 return TRUE;
234 } 235 }
235 if ( keycode == Key_F31 ) { 236 if ( keycode == Key_F31 ) {
236 if ( press ) emit symbol(); 237 if ( press ) emit symbol();
237 QWSServer::screenSaverActivate(FALSE); 238 QWSServer::screenSaverActivate(FALSE);
238 return TRUE; 239 return TRUE;
239 } 240 }
240 241
241 if ( keycode == Key_NumLock ) 242 if ( keycode == Key_NumLock )
242 if ( press ) emit numLockStateToggle(); 243 if ( press ) emit numLockStateToggle();
243 244
244 if ( keycode == Key_CapsLock ) 245 if ( keycode == Key_CapsLock )
245 if ( press ) emit capsLockStateToggle(); 246 if ( press ) emit capsLockStateToggle();
246 247
247 if ( serverApp ) 248 if ( serverApp )
248 serverApp->keyClick(keycode,press,autoRepeat); 249 serverApp->keyClick(keycode,press,autoRepeat);
249 250
250 return FALSE; 251 return FALSE;
251} 252}
252 253
253enum MemState { MemUnknown, MemVeryLow, MemLow, MemNormal } memstate=MemUnknown; 254enum MemState { MemUnknown, MemVeryLow, MemLow, MemNormal } memstate=MemUnknown;
254 255
255#if defined(QPE_HAVE_MEMALERTER) 256#if defined(QPE_HAVE_MEMALERTER)
256QPE_MEMALERTER_IMPL 257QPE_MEMALERTER_IMPL
257#endif 258#endif
258 259
259 260
260 261
261//--------------------------------------------------------------------------- 262//---------------------------------------------------------------------------
262 263
263bool ServerApplication::doRestart = FALSE; 264bool ServerApplication::doRestart = FALSE;
264bool ServerApplication::allowRestart = TRUE; 265bool ServerApplication::allowRestart = TRUE;
265bool ServerApplication::ms_is_starting = TRUE; 266bool ServerApplication::ms_is_starting = TRUE;
266 267
267void ServerApplication::switchLCD( bool on ) { 268void ServerApplication::switchLCD( bool on ) {
268 if ( !qApp ) 269 if ( !qApp )
269 return; 270 return;
270 271
271 ServerApplication *dapp = ServerApplication::me() ; 272 ServerApplication *dapp = ServerApplication::me() ;
272 273
273 if ( !dapp-> m_screensaver ) 274 if ( !dapp-> m_screensaver )
274 return; 275 return;
275 276
276 if ( on ) { 277 if ( on ) {
277 dapp-> m_screensaver-> setDisplayState ( true ); 278 dapp-> m_screensaver-> setDisplayState ( true );
278 dapp-> m_screensaver-> setBacklight ( -3 ); 279 dapp-> m_screensaver-> setBacklight ( -3 );
279 }else 280 }else
280 dapp-> m_screensaver-> setDisplayState ( false ); 281 dapp-> m_screensaver-> setDisplayState ( false );
281 282
282 283
283} 284}
284 285
285ServerApplication::ServerApplication( int& argc, char **argv, Type t ) 286ServerApplication::ServerApplication( int& argc, char **argv, Type t )
286 : QPEApplication( argc, argv, t ) 287 : QPEApplication( argc, argv, t )
287{ 288{
288 ms_is_starting = true; 289 ms_is_starting = true;
289 290
290 // We know we'll have lots of cached pixmaps due to App/DocLnks 291 // We know we'll have lots of cached pixmaps due to App/DocLnks
291 QPixmapCache::setCacheLimit(512); 292 QPixmapCache::setCacheLimit(512);
292 293
293 m_ps = new PowerStatus; 294 m_ps = new PowerStatus;
294 m_ps_last = new PowerStatus; 295 m_ps_last = new PowerStatus;
295 pa = new DesktopPowerAlerter( 0 ); 296 pa = new DesktopPowerAlerter( 0 );
296 297
297 m_apm_timer = new QTimer( this ); 298 m_apm_timer = new QTimer( this );
298 connect(m_apm_timer, SIGNAL( timeout() ), 299 connect(m_apm_timer, SIGNAL( timeout() ),
299 this, SLOT( apmTimeout() ) ); 300 this, SLOT( apmTimeout() ) );
300 301
301 reloadPowerWarnSettings(); 302 reloadPowerWarnSettings();
302 303
303 QCopChannel *channel = new QCopChannel( "QPE/System", this ); 304 QCopChannel *channel = new QCopChannel( "QPE/System", this );
304 connect(channel, SIGNAL(received(const QCString&,const QByteArray&) ), 305 connect(channel, SIGNAL(received(const QCString&,const QByteArray&) ),
305 this, SLOT(systemMessage(const QCString&,const QByteArray&) ) ); 306 this, SLOT(systemMessage(const QCString&,const QByteArray&) ) );
306 307
307 channel = new QCopChannel("QPE/Launcher", this ); 308 channel = new QCopChannel("QPE/Launcher", this );
308 connect(channel, SIGNAL(received(const QCString&,const QByteArray&) ), 309 connect(channel, SIGNAL(received(const QCString&,const QByteArray&) ),
309 this, SLOT(launcherMessage(const QCString&,const QByteArray&) ) ); 310 this, SLOT(launcherMessage(const QCString&,const QByteArray&) ) );
310 311
311 m_screensaver = new OpieScreenSaver(); 312 m_screensaver = new OpieScreenSaver();
312 m_screensaver->setInterval( -1 ); 313 m_screensaver->setInterval( -1 );
313 QWSServer::setScreenSaver( m_screensaver ); 314 QWSServer::setScreenSaver( m_screensaver );
314 315
315 connect( qApp, SIGNAL( volumeChanged(bool) ), 316 connect( qApp, SIGNAL( volumeChanged(bool) ),
316 this, SLOT( rereadVolumes() ) ); 317 this, SLOT( rereadVolumes() ) );
317 318
318 319
319 /* ### PluginLoader libqtopia SafeMode */ 320 /* ### PluginLoader libqtopia SafeMode */
320#if 0 321#if 0
321 if ( PluginLoader::inSafeMode() ) 322 if ( PluginLoader::inSafeMode() )
322 QTimer::singleShot(500, this, SLOT(showSafeMode()) ); 323 QTimer::singleShot(500, this, SLOT(showSafeMode()) );
323 QTimer::singleShot(20*1000, this, SLOT(clearSafeMode()) ); 324 QTimer::singleShot(20*1000, this, SLOT(clearSafeMode()) );
324#endif 325#endif
325 326
326 kf = new KeyFilter(this); 327 kf = new KeyFilter(this);
327 328
328 connect( kf, SIGNAL(launch()), this, SIGNAL(launch()) ); 329 connect( kf, SIGNAL(launch()), this, SIGNAL(launch()) );
329 connect( kf, SIGNAL(power()), this, SIGNAL(power()) ); 330 connect( kf, SIGNAL(power()), this, SIGNAL(power()) );
330 connect( kf, SIGNAL(backlight()), this, SIGNAL(backlight()) ); 331 connect( kf, SIGNAL(backlight()), this, SIGNAL(backlight()) );
331 connect( kf, SIGNAL(symbol()), this, SIGNAL(symbol())); 332 connect( kf, SIGNAL(symbol()), this, SIGNAL(symbol()));
332 connect( kf, SIGNAL(numLockStateToggle()), this,SIGNAL(numLockStateToggle())); 333 connect( kf, SIGNAL(numLockStateToggle()), this,SIGNAL(numLockStateToggle()));
333 connect( kf, SIGNAL(capsLockStateToggle()), this,SIGNAL(capsLockStateToggle())); 334 connect( kf, SIGNAL(capsLockStateToggle()), this,SIGNAL(capsLockStateToggle()));
334 connect( kf, SIGNAL(activate(const Opie::ODeviceButton*,bool)), 335 connect( kf, SIGNAL(activate(const Opie::Core::ODeviceButton*,bool)),
335 this,SIGNAL(activate(const Opie::ODeviceButton*,bool))); 336 this,SIGNAL(activate(const Opie::Core::ODeviceButton*,bool)));
336 337
337 338
338 connect( kf, SIGNAL(backlight()), this, SLOT(toggleLight()) ); 339 connect( kf, SIGNAL(backlight()), this, SLOT(toggleLight()) );
339 340
340 connect( this, SIGNAL(power() ), 341 connect( this, SIGNAL(power() ),
341 SLOT(togglePower() ) ); 342 SLOT(togglePower() ) );
342 343
343 rereadVolumes(); 344 rereadVolumes();
344 345
345 serverApp = this; 346 serverApp = this;
346 347
347 apmTimeout(); 348 apmTimeout();
348 grabKeyboard(); 349 grabKeyboard();
349 350
350 /* make sure the event filter is installed */ 351 /* make sure the event filter is installed */
351 const Opie::ODeviceButton* but = Opie::ODevice::inst()->buttonForKeycode( -1 ); 352 const ODeviceButton* but = ODevice::inst()->buttonForKeycode( -1 );
352} 353}
353 354
354 355
355ServerApplication::~ServerApplication() 356ServerApplication::~ServerApplication()
356{ 357{
357 ungrabKeyboard(); 358 ungrabKeyboard();
358 359
359 360
360 delete pa; 361 delete pa;
361 delete m_ps; 362 delete m_ps;
362 delete m_ps_last; 363 delete m_ps_last;
363} 364}
364 365
365void ServerApplication::apmTimeout() { 366void ServerApplication::apmTimeout() {
366 serverApp-> checkMemory( ); // in case no events are generated 367 serverApp-> checkMemory( ); // in case no events are generated
367 *m_ps_last = *m_ps; 368 *m_ps_last = *m_ps;
368 *m_ps = PowerStatusManager::readStatus(); 369 *m_ps = PowerStatusManager::readStatus();
369 370
370 if ( m_ps->acStatus() != m_ps_last-> acStatus() ) 371 if ( m_ps->acStatus() != m_ps_last-> acStatus() )
371 m_screensaver-> powerStatusChanged( *m_ps ); 372 m_screensaver-> powerStatusChanged( *m_ps );
372 373
373 if ( m_ps->acStatus() == PowerStatus::Online ) { 374 if ( m_ps->acStatus() == PowerStatus::Online ) {
374 return; 375 return;
375 } 376 }
376 377
377 int bat = m_ps-> batteryPercentRemaining(); 378 int bat = m_ps-> batteryPercentRemaining();
378 379
379 if ( bat < m_ps_last-> batteryPercentRemaining() ) { 380 if ( bat < m_ps_last-> batteryPercentRemaining() ) {
380 if ( bat <= m_powerCritical ) { 381 if ( bat <= m_powerCritical ) {
381 QMessageBox battlow( 382 QMessageBox battlow(
382 tr("WARNING"), 383 tr("WARNING"),
383 tr("<p>The battery level is critical!" 384 tr("<p>The battery level is critical!"
384 "<p>Keep power off until AC is restored"), 385 "<p>Keep power off until AC is restored"),
385 QMessageBox::Warning, 386 QMessageBox::Warning,
386 QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 387 QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton,
387 0, QString::null, TRUE, WStyle_StaysOnTop); 388 0, QString::null, TRUE, WStyle_StaysOnTop);
388 battlow.setButtonText(QMessageBox::Cancel, tr("Ok")); 389 battlow.setButtonText(QMessageBox::Cancel, tr("Ok"));
389 battlow.exec(); 390 battlow.exec();
390 } else if ( bat <= m_powerVeryLow ) 391 } else if ( bat <= m_powerVeryLow )
391 pa->alert( tr( "The battery is running very low. "), 2 ); 392 pa->alert( tr( "The battery is running very low. "), 2 );
392 } 393 }
393 394
394 if ( m_ps-> backupBatteryStatus() == PowerStatus::VeryLow ) { 395 if ( m_ps-> backupBatteryStatus() == PowerStatus::VeryLow ) {
395 QMessageBox battlow( 396 QMessageBox battlow(
396 tr("WARNING"), 397 tr("WARNING"),
397 tr("<p>The Back-up battery is very low" 398 tr("<p>The Back-up battery is very low"
398 "<p>Please charge the back-up battery"), 399 "<p>Please charge the back-up battery"),
399 QMessageBox::Warning, 400 QMessageBox::Warning,
400 QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 401 QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton,
401 0, QString::null, TRUE, WStyle_StaysOnTop); 402 0, QString::null, TRUE, WStyle_StaysOnTop);
402 battlow.setButtonText(QMessageBox::Cancel, tr("Ok")); 403 battlow.setButtonText(QMessageBox::Cancel, tr("Ok"));
403 battlow.exec(); 404 battlow.exec();
404 } 405 }
405} 406}
406 407
407void ServerApplication::systemMessage( const QCString& msg, 408void ServerApplication::systemMessage( const QCString& msg,
408 const QByteArray& data ) { 409 const QByteArray& data ) {
409 QDataStream stream ( data, IO_ReadOnly ); 410 QDataStream stream ( data, IO_ReadOnly );
410 411
411 if ( msg == "setScreenSaverInterval(int)" ) { 412 if ( msg == "setScreenSaverInterval(int)" ) {
412 int time; 413 int time;
413 stream >> time; 414 stream >> time;
414 m_screensaver-> setInterval( time ); 415 m_screensaver-> setInterval( time );
415 } 416 }
416 else if ( msg == "setScreenSaverIntervals(int,int,int)" ) { 417 else if ( msg == "setScreenSaverIntervals(int,int,int)" ) {
417 int t1, t2, t3; 418 int t1, t2, t3;
418 stream >> t1 >> t2 >> t3; 419 stream >> t1 >> t2 >> t3;
419 m_screensaver-> setIntervals( t1, t2, t3 ); 420 m_screensaver-> setIntervals( t1, t2, t3 );
420 } 421 }
421 else if ( msg == "setBacklight(int)" ) { 422 else if ( msg == "setBacklight(int)" ) {
422 int bright; 423 int bright;
423 stream >> bright; 424 stream >> bright;
424 m_screensaver-> setBacklight( bright ); 425 m_screensaver-> setBacklight( bright );
425 } 426 }
426 else if ( msg == "setScreenSaverMode(int)" ) { 427 else if ( msg == "setScreenSaverMode(int)" ) {
427 int mode; 428 int mode;
428 stream >> mode; 429 stream >> mode;
429 m_screensaver-> setMode ( mode ); 430 m_screensaver-> setMode ( mode );
430 } 431 }
431 else if ( msg == "reloadPowerWarnSettings()" ) { 432 else if ( msg == "reloadPowerWarnSettings()" ) {
432 reloadPowerWarnSettings(); 433 reloadPowerWarnSettings();
433 } 434 }
434 else if ( msg == "setDisplayState(int)" ) { 435 else if ( msg == "setDisplayState(int)" ) {
435 int state; 436 int state;
436 stream >> state; 437 stream >> state;
437 m_screensaver-> setDisplayState ( state != 0 ); 438 m_screensaver-> setDisplayState ( state != 0 );
438 } 439 }
439 else if ( msg == "suspend()" ) { 440 else if ( msg == "suspend()" ) {
440 emit power(); 441 emit power();
441 } 442 }
442 else if ( msg == "sendBusinessCard()" ) { 443 else if ( msg == "sendBusinessCard()" ) {
443 QString card = ::getenv ( "HOME" ); 444 QString card = ::getenv ( "HOME" );
444 card += "/Applications/addressbook/businesscard.vcf"; 445 card += "/Applications/addressbook/businesscard.vcf";
445 446
446 if ( QFile::exists( card ) ) { 447 if ( QFile::exists( card ) ) {
447 QCopEnvelope e ( "QPE/Obex", "send(QString,QString,QString)" ); 448 QCopEnvelope e ( "QPE/Obex", "send(QString,QString,QString)" );
448 QString mimetype = "text/x-vCard"; 449 QString mimetype = "text/x-vCard";
449 e << tr( "business card" ) << card << mimetype; 450 e << tr( "business card" ) << card << mimetype;
450 } 451 }
451 } 452 }
452} 453}
453 454
454void ServerApplication::reloadPowerWarnSettings ( ) 455void ServerApplication::reloadPowerWarnSettings ( )
455{ 456{
456 Config cfg ( "apm" ); 457 Config cfg ( "apm" );
457 cfg. setGroup ( "Warnings" ); 458 cfg. setGroup ( "Warnings" );
458 459
459 int iv = cfg. readNumEntry ( "checkinterval", 10000 ); 460 int iv = cfg. readNumEntry ( "checkinterval", 10000 );
460 461
461 m_apm_timer-> stop ( ); 462 m_apm_timer-> stop ( );
462 if ( iv ) 463 if ( iv )
463 m_apm_timer-> start ( iv ); 464 m_apm_timer-> start ( iv );
464 465
465 m_powerVeryLow = cfg. readNumEntry ( "powerverylow", 10 ); 466 m_powerVeryLow = cfg. readNumEntry ( "powerverylow", 10 );
466 m_powerCritical = cfg. readNumEntry ( "powervcritical", 5 ); 467 m_powerCritical = cfg. readNumEntry ( "powervcritical", 5 );
467} 468}
468 469
469void ServerApplication::launcherMessage( const QCString & msg, const QByteArray & data ) 470void ServerApplication::launcherMessage( const QCString & msg, const QByteArray & data )
470{ 471{
471 QDataStream stream ( data, IO_ReadOnly ); 472 QDataStream stream ( data, IO_ReadOnly );
472 473
473 if ( msg == "deviceButton(int,int,int)" ) { 474 if ( msg == "deviceButton(int,int,int)" ) {
474 int keycode, press, autoRepeat; 475 int keycode, press, autoRepeat;
475 stream >> keycode >> press >> autoRepeat; 476 stream >> keycode >> press >> autoRepeat;
476 477
477 kf->checkButtonAction ( true, keycode, press, autoRepeat ); 478 kf->checkButtonAction ( true, keycode, press, autoRepeat );
478 } 479 }
479 else if ( msg == "keyRegister(int,QCString,QCString)" ) { 480 else if ( msg == "keyRegister(int,QCString,QCString)" ) {
480 int k; 481 int k;
481 QCString c, m; 482 QCString c, m;
482 stream >> k >> c >> m; 483 stream >> k >> c >> m;
483 484
484 kf -> registerKey( QCopKeyRegister(k, c, m) ); 485 kf -> registerKey( QCopKeyRegister(k, c, m) );
485 } 486 }
486} 487}
487 488
488 489
489bool ServerApplication::screenLocked() 490bool ServerApplication::screenLocked()
490{ 491{
491 return loggedin == 0; 492 return loggedin == 0;
492} 493}
493 494
494void ServerApplication::login(bool at_poweron) 495void ServerApplication::login(bool at_poweron)
495{ 496{
496 if ( !loggedin ) { 497 if ( !loggedin ) {
497 Global::terminateBuiltin("calibrate"); // No tr 498 Global::terminateBuiltin("calibrate"); // No tr
498 Password::authenticate(at_poweron); 499 Password::authenticate(at_poweron);
499 loggedin=1; 500 loggedin=1;
500#ifndef QT_NO_COP 501#ifndef QT_NO_COP
501 QCopEnvelope e( "QPE/Desktop", "unlocked()" ); 502 QCopEnvelope e( "QPE/Desktop", "unlocked()" );
502#endif 503#endif
503 } 504 }
504} 505}
505 506
506#if defined(QPE_HAVE_TOGGLELIGHT) 507#if defined(QPE_HAVE_TOGGLELIGHT)
507#include <qtopia/config.h> 508#include <qtopia/config.h>
508 509
509#include <sys/ioctl.h> 510#include <sys/ioctl.h>
510#include <sys/types.h> 511#include <sys/types.h>
511#include <fcntl.h> 512#include <fcntl.h>
512#include <unistd.h> 513#include <unistd.h>
513#include <errno.h> 514#include <errno.h>
514#include <linux/ioctl.h> 515#include <linux/ioctl.h>
515#include <time.h> 516#include <time.h>
516#endif 517#endif
517 518
518#if 0 519#if 0
519static bool blanked=FALSE; 520static bool blanked=FALSE;
520 521
521static void blankScreen() 522static void blankScreen()
522{ 523{
523#ifdef QWS 524#ifdef QWS
524 QWidget w(0, 0, Qt::WStyle_Customize | Qt::WStyle_NoBorder | Qt::WStyle_Tool | Qt::WStyle_StaysOnTop | Qt::WPaintUnclipped); 525 QWidget w(0, 0, Qt::WStyle_Customize | Qt::WStyle_NoBorder | Qt::WStyle_Tool | Qt::WStyle_StaysOnTop | Qt::WPaintUnclipped);
525 w.resize( qt_screen->width(), qt_screen->height() ); 526 w.resize( qt_screen->width(), qt_screen->height() );
526 w.move(0, 0); 527 w.move(0, 0);
527 528
528 QPainter p(&w); 529 QPainter p(&w);
529 p.fillRect(w.rect(), QBrush(QColor(255,255,255)) ); 530 p.fillRect(w.rect(), QBrush(QColor(255,255,255)) );
530 p.end(); 531 p.end();
531 w.repaint(); 532 w.repaint();
532 533
533 blanked = TRUE; 534 blanked = TRUE;
534#endif 535#endif
535} 536}
536 537
537static void darkScreen() 538static void darkScreen()
538{ 539{
539 /* ### Screen blanking ODevice */ 540 /* ### Screen blanking ODevice */
540#if 0 541#if 0
541 qpe_setBacklight(0); // force off 542 qpe_setBacklight(0); // force off
542#endif 543#endif
543} 544}
544#endif 545#endif
545 546
546namespace { 547namespace {
547 void execAutoStart(const QDateTime& suspendTime ) { 548 void execAutoStart(const QDateTime& suspendTime ) {
548 QString appName; 549 QString appName;
549 int delay; 550 int delay;
550 QDateTime now = QDateTime::currentDateTime(); 551 QDateTime now = QDateTime::currentDateTime();
551 552
552 Config cfg( "autostart" ); 553 Config cfg( "autostart" );
553 cfg.setGroup( "AutoStart" ); 554 cfg.setGroup( "AutoStart" );
554 appName = cfg.readEntry( "Apps", "" ); 555 appName = cfg.readEntry( "Apps", "" );
555 delay = cfg.readNumEntry( "Delay", 0 ); 556 delay = cfg.readNumEntry( "Delay", 0 );
556 557
557 // If the time between suspend and resume was longer then the 558 // If the time between suspend and resume was longer then the
558 // value saved as delay, start the app 559 // value saved as delay, start the app
559 if ( suspendTime.secsTo( now ) >= ( delay * 60 ) && !appName.isEmpty() ) { 560 if ( suspendTime.secsTo( now ) >= ( delay * 60 ) && !appName.isEmpty() ) {
560 QCopEnvelope e( "QPE/System", "execute(QString)" ); 561 QCopEnvelope e( "QPE/System", "execute(QString)" );
561 e << QString( appName ); 562 e << QString( appName );
562 } 563 }
563 } 564 }
564} 565}
565 566
566 567
567void ServerApplication::togglePower() 568void ServerApplication::togglePower()
568{ 569{
569 static bool excllock = false; 570 static bool excllock = false;
570 571
571 if ( excllock ) 572 if ( excllock )
572 return ; 573 return ;
573 574
574 excllock = true; 575 excllock = true;
575 576
576 bool wasloggedin = loggedin; 577 bool wasloggedin = loggedin;
577 loggedin = 0; 578 loggedin = 0;
578 m_suspendTime = QDateTime::currentDateTime(); 579 m_suspendTime = QDateTime::currentDateTime();
579 580
580#ifdef QWS 581#ifdef QWS
581 582
582 if ( Password::needToAuthenticate ( true ) && qt_screen ) { 583 if ( Password::needToAuthenticate ( true ) && qt_screen ) {
583 // Should use a big black window instead. 584 // Should use a big black window instead.
584 // But this would not show up fast enough 585 // But this would not show up fast enough
585 QGfx *g = qt_screen-> screenGfx ( ); 586 QGfx *g = qt_screen-> screenGfx ( );
586 g-> fillRect ( 0, 0, qt_screen-> width ( ), qt_screen-> height ( )); 587 g-> fillRect ( 0, 0, qt_screen-> width ( ), qt_screen-> height ( ));
587 delete g; 588 delete g;
588 } 589 }
589#endif 590#endif
590 591
591 ODevice::inst ( )-> suspend ( ); 592 ODevice::inst ( )-> suspend ( );
592 593
593 ServerApplication::switchLCD ( true ); // force LCD on without slow qcop call 594 ServerApplication::switchLCD ( true ); // force LCD on without slow qcop call
594 QWSServer::screenSaverActivate ( false ); 595 QWSServer::screenSaverActivate ( false );
595 596
596 { 597 {
597 QCopEnvelope( "QPE/Card", "mtabChanged()" ); // might have changed while asleep 598 QCopEnvelope( "QPE/Card", "mtabChanged()" ); // might have changed while asleep
598 } 599 }
599 600
600 if ( wasloggedin ) 601 if ( wasloggedin )
601 login ( true ); 602 login ( true );
602 603
603 execAutoStart(m_suspendTime); 604 execAutoStart(m_suspendTime);
604 //qcopBridge->closeOpenConnections(); 605 //qcopBridge->closeOpenConnections();
605 606
606 excllock = false; 607 excllock = false;
607} 608}
608 609
609void ServerApplication::toggleLight() 610void ServerApplication::toggleLight()
610{ 611{
611#ifndef QT_NO_COP 612#ifndef QT_NO_COP
612 QCopEnvelope e("QPE/System", "setBacklight(int)"); 613 QCopEnvelope e("QPE/System", "setBacklight(int)");
613 e << -2; // toggle 614 e << -2; // toggle
614#endif 615#endif
615} 616}
616 617
617 618
618/* 619/*
619 * We still listen to key events but handle them in 620 * We still listen to key events but handle them in
620 * a special class 621 * a special class
621 */ 622 */
622 623
623bool ServerApplication::eventFilter( QObject *o, QEvent *e) { 624bool ServerApplication::eventFilter( QObject *o, QEvent *e) {
624 if ( e->type() != QEvent::KeyPress && 625 if ( e->type() != QEvent::KeyPress &&
625 e->type() != QEvent::KeyRelease ) 626 e->type() != QEvent::KeyRelease )
626 return QPEApplication::eventFilter( o, e ); 627 return QPEApplication::eventFilter( o, e );
627 628
628 QKeyEvent *ke = static_cast<QKeyEvent*>( e ); 629 QKeyEvent *ke = static_cast<QKeyEvent*>( e );
629 if ( kf->checkButtonAction( true, ke->key(), 630 if ( kf->checkButtonAction( true, ke->key(),
630 e->type() == QEvent::KeyPress, 631 e->type() == QEvent::KeyPress,
631 ke-> isAutoRepeat() )) 632 ke-> isAutoRepeat() ))
632 return true; 633 return true;
633 634
634 return QPEApplication::eventFilter( o, e ); 635 return QPEApplication::eventFilter( o, e );
635 636
636} 637}
637 638
638#ifdef Q_WS_QWS 639#ifdef Q_WS_QWS
639bool ServerApplication::qwsEventFilter( QWSEvent *e ) 640bool ServerApplication::qwsEventFilter( QWSEvent *e )
640{ 641{
641 checkMemory(); 642 checkMemory();
642 643
643 if ( e->type == QWSEvent::Mouse ) { 644 if ( e->type == QWSEvent::Mouse ) {
644 QWSMouseEvent *me = (QWSMouseEvent *)e; 645 QWSMouseEvent *me = (QWSMouseEvent *)e;
645 static bool up = TRUE; 646 static bool up = TRUE;
646 if ( me->simpleData.state&LeftButton ) { 647 if ( me->simpleData.state&LeftButton ) {
647 if ( up ) { 648 if ( up ) {
648 up = FALSE; 649 up = FALSE;
649 screenClick(TRUE); 650 screenClick(TRUE);
650 } 651 }
651 } else if ( !up ) { 652 } else if ( !up ) {
652 up = TRUE; 653 up = TRUE;
653 screenClick(FALSE); 654 screenClick(FALSE);
654 } 655 }
655 }else if ( e->type == QWSEvent::Key ) { 656 }else if ( e->type == QWSEvent::Key ) {
656 QWSKeyEvent * ke = static_cast<QWSKeyEvent*>( e ); 657 QWSKeyEvent * ke = static_cast<QWSKeyEvent*>( e );
657 if ( kf->checkButtonAction( false, 658 if ( kf->checkButtonAction( false,
658 ke-> simpleData.keycode, 659 ke-> simpleData.keycode,
659 ke-> simpleData.is_press, 660 ke-> simpleData.is_press,
660 ke-> simpleData.is_auto_repeat ) ) 661 ke-> simpleData.is_auto_repeat ) )
661 return true; 662 return true;
662 } 663 }
663 664
664 return QPEApplication::qwsEventFilter( e ); 665 return QPEApplication::qwsEventFilter( e );
665} 666}
666#endif 667#endif
667 668
668 669
669/* ### FIXME libqtopia Plugin Safe Mode */ 670/* ### FIXME libqtopia Plugin Safe Mode */
670 671
671void ServerApplication::showSafeMode() 672void ServerApplication::showSafeMode()
672{ 673{
673#if 0 674#if 0
674 if ( QMessageBox::warning(0, tr("Safe Mode"), tr("<P>A system startup error occurred, " 675 if ( QMessageBox::warning(0, tr("Safe Mode"), tr("<P>A system startup error occurred, "
675 "and the system is now in Safe Mode. " 676 "and the system is now in Safe Mode. "
676 "Plugins are not loaded in Safe Mode. " 677 "Plugins are not loaded in Safe Mode. "
677 "You can use the Plugin Manager to " 678 "You can use the Plugin Manager to "
678 "disable plugins that cause system error."), tr("OK"), tr("Plugin Manager..."), 0) == 1 ) { 679 "disable plugins that cause system error."), tr("OK"), tr("Plugin Manager..."), 0) == 1 ) {
679 Global::execute( "pluginmanager" ); 680 Global::execute( "pluginmanager" );
680 } 681 }
681#endif 682#endif
682} 683}
683 684
684void ServerApplication::clearSafeMode() 685void ServerApplication::clearSafeMode()
685{ 686{
686#if 0 687#if 0
687 // If we've been running OK for a while then we won't bother going into 688 // If we've been running OK for a while then we won't bother going into
688 // safe mode immediately on the next crash. 689 // safe mode immediately on the next crash.
689 Config cfg( "PluginLoader" ); 690 Config cfg( "PluginLoader" );
690 cfg.setGroup( "Global" ); 691 cfg.setGroup( "Global" );
691 QString mode = cfg.readEntry( "Mode", "Normal" ); 692 QString mode = cfg.readEntry( "Mode", "Normal" );
692 if ( mode == "MaybeSafe" ) { 693 if ( mode == "MaybeSafe" ) {
693 cfg.writeEntry( "Mode", "Normal" ); 694 cfg.writeEntry( "Mode", "Normal" );
694 } 695 }
695#endif 696#endif
696} 697}
697 698
698 699
699void ServerApplication::shutdown() 700void ServerApplication::shutdown()
700{ 701{
701 if ( type() != GuiServer ) 702 if ( type() != GuiServer )
702 return; 703 return;
703 ShutdownImpl *sd = new ShutdownImpl( 0, 0, WDestructiveClose ); 704 ShutdownImpl *sd = new ShutdownImpl( 0, 0, WDestructiveClose );
704 connect( sd, SIGNAL(shutdown(ShutdownImpl::Type)), 705 connect( sd, SIGNAL(shutdown(ShutdownImpl::Type)),
705 this, SLOT(shutdown(ShutdownImpl::Type)) ); 706 this, SLOT(shutdown(ShutdownImpl::Type)) );
706 QPEApplication::showWidget( sd ); 707 QPEApplication::showWidget( sd );
707} 708}
708 709
709void ServerApplication::shutdown( ShutdownImpl::Type t ) 710void ServerApplication::shutdown( ShutdownImpl::Type t )
710{ 711{
711 char *opt = 0; 712 char *opt = 0;
712 713
713 switch ( t ) { 714 switch ( t ) {
714 case ShutdownImpl::ShutdownSystem: 715 case ShutdownImpl::ShutdownSystem:
715 opt = "-h"; 716 opt = "-h";
716 // fall through 717 // fall through
717 case ShutdownImpl::RebootSystem: 718 case ShutdownImpl::RebootSystem:
718 if ( opt == 0 ) 719 if ( opt == 0 )
719 opt = "-r"; 720 opt = "-r";
720 721
721 if ( execl( "/sbin/shutdown", "shutdown", opt, "now", ( void* ) 0) < 0 ) 722 if ( execl( "/sbin/shutdown", "shutdown", opt, "now", ( void* ) 0) < 0 )
722 perror("shutdown"); 723 perror("shutdown");
723 // ::syslog ( LOG_ERR, "Erroring execing shutdown\n" ); 724 // ::syslog ( LOG_ERR, "Erroring execing shutdown\n" );
724 725
725 break; 726 break;
726 case ShutdownImpl::RestartDesktop: 727 case ShutdownImpl::RestartDesktop:
727 restart(); 728 restart();
728 break; 729 break;
729 case ShutdownImpl::TerminateDesktop: 730 case ShutdownImpl::TerminateDesktop:
730 prepareForTermination( FALSE ); 731 prepareForTermination( FALSE );
731 732
732 // This is a workaround for a Qt bug 733 // This is a workaround for a Qt bug
733 // clipboard applet has to stop its poll timer, or Qt/E 734 // clipboard applet has to stop its poll timer, or Qt/E
734 // will hang on quit() right before it emits aboutToQuit() 735 // will hang on quit() right before it emits aboutToQuit()
735 emit aboutToQuit ( ); 736 emit aboutToQuit ( );
736 737
737 quit(); 738 quit();
738 break; 739 break;
739 } 740 }
740} 741}
741 742
742void ServerApplication::restart() 743void ServerApplication::restart()
743{ 744{
744 if ( allowRestart ) { 745 if ( allowRestart ) {
745 746
746 /* 747 /*
747 * Applets and restart is a problem. Some applets delete 748 * Applets and restart is a problem. Some applets delete
748 * their widgets even if ownership gets transfered to the 749 * their widgets even if ownership gets transfered to the
749 * parent (Systray ) but deleting the applet may be unsafe 750 * parent (Systray ) but deleting the applet may be unsafe
750 * as well ( double deletion ). Some have topLevel widgets 751 * as well ( double deletion ). Some have topLevel widgets
751 * and when we dlclose and then delete the widget we will 752 * and when we dlclose and then delete the widget we will
752 * crash and an crash during restart is not nice 753 * crash and an crash during restart is not nice
753 */ 754 */
754#ifdef ALL_APPLETS_ON_THIS_WORLD_ARE_FIXED 755#ifdef ALL_APPLETS_ON_THIS_WORLD_ARE_FIXED
755 /* same as above */ 756 /* same as above */
756 emit aboutToQuit(); 757 emit aboutToQuit();
757 prepareForTermination(TRUE); 758 prepareForTermination(TRUE);
758 doRestart = TRUE; 759 doRestart = TRUE;
759 quit(); 760 quit();
760#else 761#else
761 prepareForTermination( true ); 762 prepareForTermination( true );
762 for ( int fd = 3; fd < 100; fd++ ) 763 for ( int fd = 3; fd < 100; fd++ )
763 close( fd ); 764 close( fd );
764 execl( ( qpeDir() + "/bin/qpe" ).latin1(), "qpe", 0 ); 765 execl( ( qpeDir() + "/bin/qpe" ).latin1(), "qpe", 0 );
765 exit( 1 ); 766 exit( 1 );
766#endif 767#endif
767 } 768 }
768} 769}
769 770
770void ServerApplication::rereadVolumes() 771void ServerApplication::rereadVolumes()
771{ 772{
772 Config cfg( "qpe" ); 773 Config cfg( "qpe" );
773 cfg. setGroup ( "Volume" ); 774 cfg. setGroup ( "Volume" );
774 775
775 m_screentap_sound = cfg. readBoolEntry ( "TouchSound" ); 776 m_screentap_sound = cfg. readBoolEntry ( "TouchSound" );
776 m_keyclick_sound = cfg. readBoolEntry ( "KeySound" ); 777 m_keyclick_sound = cfg. readBoolEntry ( "KeySound" );
777 m_alarm_sound = cfg. readBoolEntry ( "AlarmSound" ); 778 m_alarm_sound = cfg. readBoolEntry ( "AlarmSound" );
778} 779}
779 780
780 781
781void ServerApplication::checkMemory() 782void ServerApplication::checkMemory()
782{ 783{
783#if defined(QPE_HAVE_MEMALERTER) 784#if defined(QPE_HAVE_MEMALERTER)
784 static bool ignoreNormal=TRUE; 785 static bool ignoreNormal=TRUE;
785 static bool existingMessage=FALSE; 786 static bool existingMessage=FALSE;
786 787
787 if(existingMessage) 788 if(existingMessage)
788 return; // don't show a second message while still on first 789 return; // don't show a second message while still on first
789 790
790 existingMessage = TRUE; 791 existingMessage = TRUE;
791 switch ( memstate ) { 792 switch ( memstate ) {
792 case MemUnknown: 793 case MemUnknown:
793 break; 794 break;
794 case MemLow: 795 case MemLow:
795 memstate = MemUnknown; 796 memstate = MemUnknown;
796 if ( !recoverMemory() ) { 797 if ( !recoverMemory() ) {
797 QMessageBox::warning( 0 , tr("Memory Status"), 798 QMessageBox::warning( 0 , tr("Memory Status"),
798 tr("Memory Low\nPlease save data.") ); 799 tr("Memory Low\nPlease save data.") );
799 ignoreNormal = FALSE; 800 ignoreNormal = FALSE;
800 } 801 }
801 break; 802 break;
802 case MemNormal: 803 case MemNormal:
803 memstate = MemUnknown; 804 memstate = MemUnknown;
804 if ( !ignoreNormal ) { 805 if ( !ignoreNormal ) {
805 ignoreNormal = TRUE; 806 ignoreNormal = TRUE;
806 QMessageBox::information ( 0 , tr("Memory Status"), 807 QMessageBox::information ( 0 , tr("Memory Status"),
807 "Memory OK" ); 808 "Memory OK" );
808 } 809 }
809 break; 810 break;
810 case MemVeryLow: 811 case MemVeryLow:
811 memstate = MemUnknown; 812 memstate = MemUnknown;
812 QMessageBox::critical( 0 , tr("Memory Status"), 813 QMessageBox::critical( 0 , tr("Memory Status"),
813 tr("Critical Memory Shortage\n" 814 tr("Critical Memory Shortage\n"
814 "Please end this application\n" 815 "Please end this application\n"
815 "immediately.") ); 816 "immediately.") );
816 recoverMemory(); 817 recoverMemory();
817 } 818 }
818 existingMessage = FALSE; 819 existingMessage = FALSE;
819#endif 820#endif
820} 821}
821 822
822bool ServerApplication::recoverMemory() 823bool ServerApplication::recoverMemory()
823{ 824{
824 return FALSE; 825 return FALSE;
825} 826}
826 827
827void ServerApplication::keyClick(int , bool press, bool ) 828void ServerApplication::keyClick(int , bool press, bool )
828{ 829{
829 if ( press && m_keyclick_sound ) 830 if ( press && m_keyclick_sound )
830 ODevice::inst() -> playKeySound(); 831 ODevice::inst() -> playKeySound();
831 832
832} 833}
833 834
834void ServerApplication::screenClick(bool press) 835void ServerApplication::screenClick(bool press)
835{ 836{
836 if ( press && m_screentap_sound ) 837 if ( press && m_screentap_sound )
837 ODevice::inst() -> playTouchSound(); 838 ODevice::inst() -> playTouchSound();
838} 839}
839 840
840void ServerApplication::soundAlarm() { 841void ServerApplication::soundAlarm() {
841 if ( me ()->m_alarm_sound ) 842 if ( me ()->m_alarm_sound )
842 ODevice::inst()->playAlarmSound(); 843 ODevice::inst()->playAlarmSound();
843} 844}
844 845
845ServerApplication *ServerApplication::me ( ) 846ServerApplication *ServerApplication::me ( )
846{ 847{
847 return static_cast<ServerApplication*>( qApp ); 848 return static_cast<ServerApplication*>( qApp );
848} 849}
849 850
850bool ServerApplication::isStarting() 851bool ServerApplication::isStarting()
851{ 852{
852 return ms_is_starting; 853 return ms_is_starting;
853} 854}
854 855
855int ServerApplication::exec() 856int ServerApplication::exec()
856{ 857{
857 ms_is_starting = true; 858 ms_is_starting = true;
858 qDebug("Serverapp - exec"); 859 qDebug("Serverapp - exec");
859 return QPEApplication::exec(); 860 return QPEApplication::exec();
860} 861}
861 862
862#include "serverapp.moc" 863#include "serverapp.moc"
diff --git a/core/launcher/serverapp.h b/core/launcher/serverapp.h
index 4d9f808..916d83c 100644
--- a/core/launcher/serverapp.h
+++ b/core/launcher/serverapp.h
@@ -1,169 +1,171 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2003 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2003 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 SERVERAPP_H 21#ifndef SERVERAPP_H
22#define SERVERAPP_H 22#define SERVERAPP_H
23 23
24#include <qtopia/qpeapplication.h> 24#include <qtopia/qpeapplication.h>
25 25
26#include <qwidget.h> 26#include <qwidget.h>
27#ifdef QWS 27#ifdef QWS
28#include <qwindowsystem_qws.h> 28#include <qwindowsystem_qws.h>
29#endif 29#endif
30 30
31#include "shutdownimpl.h" 31#include "shutdownimpl.h"
32 32
33class PowerStatus; 33class PowerStatus;
34class DesktopPowerAlerter; 34class DesktopPowerAlerter;
35 35
36class OpieScreenSaver; 36class OpieScreenSaver;
37namespace Opie { 37namespace Opie {
38namespace Core {
38 class ODeviceButton; 39 class ODeviceButton;
39} 40}
41}
40 42
41struct QCopKeyRegister { 43struct QCopKeyRegister {
42 QCopKeyRegister(); 44 QCopKeyRegister();
43 QCopKeyRegister( int k, const QCString&, const QCString& ); 45 QCopKeyRegister( int k, const QCString&, const QCString& );
44 int keyCode()const; 46 int keyCode()const;
45 QCString channel()const; 47 QCString channel()const;
46 QCString message()const; 48 QCString message()const;
47 inline bool send(); 49 inline bool send();
48 50
49private: 51private:
50 int m_keyCode; 52 int m_keyCode;
51 QCString m_channel, m_message; 53 QCString m_channel, m_message;
52}; 54};
53 55
54typedef QMap<int, QCopKeyRegister> KeyRegisterList; 56typedef QMap<int, QCopKeyRegister> KeyRegisterList;
55 57
56class KeyFilter : public QObject { 58class KeyFilter : public QObject {
57 Q_OBJECT 59 Q_OBJECT
58public: 60public:
59 KeyFilter(QObject* parent); 61 KeyFilter(QObject* parent);
60 void registerKey( const QCopKeyRegister& ); 62 void registerKey( const QCopKeyRegister& );
61 void unregisterKey( const QCopKeyRegister& ); 63 void unregisterKey( const QCopKeyRegister& );
62 bool checkButtonAction( bool, int, int, int ); 64 bool checkButtonAction( bool, int, int, int );
63 65
64 66
65 67
66protected: 68protected:
67 void timerEvent(QTimerEvent*); 69 void timerEvent(QTimerEvent*);
68 70
69signals: 71signals:
70 void launch(); 72 void launch();
71 void power(); 73 void power();
72 void backlight(); 74 void backlight();
73 void symbol(); 75 void symbol();
74 void numLockStateToggle(); 76 void numLockStateToggle();
75 void capsLockStateToggle(); 77 void capsLockStateToggle();
76 void activate(const Opie::ODeviceButton*,bool); 78 void activate(const Opie::Core::ODeviceButton*,bool);
77 79
78 80
79private: 81private:
80 bool keyRegistered( int key ); 82 bool keyRegistered( int key );
81 int held_tid; 83 int held_tid;
82 const Opie::ODeviceButton* heldButton; 84 const Opie::Core::ODeviceButton* heldButton;
83 KeyRegisterList m_keys; 85 KeyRegisterList m_keys;
84}; 86};
85 87
86class ServerApplication : public QPEApplication 88class ServerApplication : public QPEApplication
87{ 89{
88 Q_OBJECT 90 Q_OBJECT
89public: 91public:
90 ServerApplication( int& argc, char **argv, Type t ); 92 ServerApplication( int& argc, char **argv, Type t );
91 ~ServerApplication(); 93 ~ServerApplication();
92 94
93 static bool doRestart; 95 static bool doRestart;
94 static bool allowRestart; 96 static bool allowRestart;
95 static bool screenLocked(); 97 static bool screenLocked();
96 static void login(bool at_poweron); 98 static void login(bool at_poweron);
97 99
98 static bool isStarting(); 100 static bool isStarting();
99 101
100 static void switchLCD ( bool on ); // only for togglePower in Desktop 102 static void switchLCD ( bool on ); // only for togglePower in Desktop
101 static void soundAlarm(); // only because QCop soundAlarm() is defined in QPE/TaskBar 103 static void soundAlarm(); // only because QCop soundAlarm() is defined in QPE/TaskBar
102 104
103 void restart(); 105 void restart();
104 int exec(); 106 int exec();
105 107
106signals: 108signals:
107 void menu(); 109 void menu();
108 void home(); 110 void home();
109 void launch(); 111 void launch();
110 void power(); 112 void power();
111 void backlight(); 113 void backlight();
112 void symbol(); 114 void symbol();
113 void numLockStateToggle(); 115 void numLockStateToggle();
114 void capsLockStateToggle(); 116 void capsLockStateToggle();
115 void prepareForRestart(); 117 void prepareForRestart();
116 void activate(const Opie::ODeviceButton*,bool); 118 void activate(const Opie::Core::ODeviceButton*,bool);
117 119
118public slots: 120public slots:
119 virtual void systemMessage( const QCString& msg, const QByteArray& ); 121 virtual void systemMessage( const QCString& msg, const QByteArray& );
120 virtual void launcherMessage( const QCString& msg, const QByteArray& ); 122 virtual void launcherMessage( const QCString& msg, const QByteArray& );
121 void rereadVolumes(); 123 void rereadVolumes();
122 124
123protected: 125protected:
124 bool eventFilter( QObject*, QEvent* ); 126 bool eventFilter( QObject*, QEvent* );
125#ifdef Q_WS_QWS 127#ifdef Q_WS_QWS
126 bool qwsEventFilter( QWSEvent * ); 128 bool qwsEventFilter( QWSEvent * );
127#endif 129#endif
128 void shutdown(); 130 void shutdown();
129 void checkMemory(); 131 void checkMemory();
130 bool recoverMemory(); 132 bool recoverMemory();
131 void keyClick(int keycode, bool press, bool repeat); 133 void keyClick(int keycode, bool press, bool repeat);
132 void screenClick(bool press); 134 void screenClick(bool press);
133 135
134protected slots: 136protected slots:
135 void shutdown(ShutdownImpl::Type); 137 void shutdown(ShutdownImpl::Type);
136 void apmTimeout(); 138 void apmTimeout();
137 void showSafeMode(); 139 void showSafeMode();
138 void clearSafeMode(); 140 void clearSafeMode();
139 void togglePower(); 141 void togglePower();
140 void toggleLight(); 142 void toggleLight();
141 143
142private: 144private:
143 static ServerApplication *me (); 145 static ServerApplication *me ();
144 void reloadPowerWarnSettings(); 146 void reloadPowerWarnSettings();
145 KeyFilter *kf; 147 KeyFilter *kf;
146 148
147 149
148private: 150private:
149 DesktopPowerAlerter *pa; 151 DesktopPowerAlerter *pa;
150 PowerStatus *m_ps, *m_ps_last; 152 PowerStatus *m_ps, *m_ps_last;
151 OpieScreenSaver *m_screensaver; 153 OpieScreenSaver *m_screensaver;
152 QTimer *m_apm_timer; 154 QTimer *m_apm_timer;
153 QDateTime m_suspendTime; 155 QDateTime m_suspendTime;
154 int m_powerVeryLow; 156 int m_powerVeryLow;
155 int m_powerCritical; 157 int m_powerCritical;
156 int m_currentPowerLevel; 158 int m_currentPowerLevel;
157 159
158 bool m_keyclick_sound : 1; 160 bool m_keyclick_sound : 1;
159 bool m_screentap_sound : 1; 161 bool m_screentap_sound : 1;
160 bool m_alarm_sound : 1; 162 bool m_alarm_sound : 1;
161 static bool ms_is_starting; 163 static bool ms_is_starting;
162 164
163 165
164 friend class KeyFilter; 166 friend class KeyFilter;
165}; 167};
166 168
167 169
168#endif // SERVERAPP_H 170#endif // SERVERAPP_H
169 171
diff --git a/core/launcher/transferserver.cpp b/core/launcher/transferserver.cpp
index a5e20b2..e32cf41 100644
--- a/core/launcher/transferserver.cpp
+++ b/core/launcher/transferserver.cpp
@@ -1,573 +1,574 @@
1/********************************************************************** 1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. 2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3** 3**
4** This file is part of the Qtopia Environment. 4** This file is part of the Qtopia Environment.
5** 5**
6** 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 _XOPEN_SOURCE 20//#define _XOPEN_SOURCE
21 21
22#include <opie2/oglobal.h> 22#include <opie2/oglobal.h>
23 23
24#ifndef Q_OS_WIN32 24#ifndef Q_OS_WIN32
25#include <pwd.h> 25#include <pwd.h>
26#include <sys/types.h> 26#include <sys/types.h>
27#include <unistd.h> 27#include <unistd.h>
28#include <stdlib.h> 28#include <stdlib.h>
29#include <time.h> 29#include <time.h>
30 30
31#ifndef Q_OS_MACX 31#ifndef Q_OS_MACX
32#include <shadow.h> 32#include <shadow.h>
33#include <crypt.h> 33#include <crypt.h>
34#endif /* Q_OS_MACX */ 34#endif /* Q_OS_MACX */
35 35
36#else 36#else
37#include <stdlib.h> 37#include <stdlib.h>
38#include <time.h> 38#include <time.h>
39#endif 39#endif
40 40
41 41
42#if defined(_OS_LINUX_) 42#if defined(_OS_LINUX_)
43#include <shadow.h> 43#include <shadow.h>
44#endif 44#endif
45 45
46#include <qtextstream.h> 46#include <qtextstream.h>
47#include <qmessagebox.h> 47#include <qmessagebox.h>
48//#include <qtopia/qcopchannel_qws.h> 48//#include <qtopia/qcopchannel_qws.h>
49#include <qtopia/process.h> 49#include <qtopia/process.h>
50#include <qtopia/private/contact.h> 50#include <qtopia/private/contact.h>
51#include <qtopia/version.h> 51#include <qtopia/version.h>
52#ifdef Q_WS_QWS 52#ifdef Q_WS_QWS
53#include <qtopia/qcopenvelope_qws.h> 53#include <qtopia/qcopenvelope_qws.h>
54#endif 54#endif
55 55
56 56
57#include "transferserver.h" 57#include "transferserver.h"
58#include <qtopia/qprocess.h> 58#include <qtopia/qprocess.h>
59 59
60const int block_size = 51200; 60const int block_size = 51200;
61 61
62using namespace Opie::Core;
62TransferServer::TransferServer( Q_UINT16 port, QObject *parent, 63TransferServer::TransferServer( Q_UINT16 port, QObject *parent,
63 const char* name) 64 const char* name)
64 : QServerSocket( port, 1, parent, name ) 65 : QServerSocket( port, 1, parent, name )
65{ 66{
66 connections.setAutoDelete( TRUE ); 67 connections.setAutoDelete( TRUE );
67 if ( !ok() ) 68 if ( !ok() )
68 qWarning( "Failed to bind to port %d", port ); 69 qWarning( "Failed to bind to port %d", port );
69} 70}
70 71
71void TransferServer::authorizeConnections() 72void TransferServer::authorizeConnections()
72{ 73{
73 QListIterator<ServerPI> it(connections); 74 QListIterator<ServerPI> it(connections);
74 while ( it.current() ) { 75 while ( it.current() ) {
75 if ( !it.current()->verifyAuthorised() ) { 76 if ( !it.current()->verifyAuthorised() ) {
76 disconnect( it.current(), SIGNAL(connectionClosed(ServerPI*)), this, SLOT( closed(ServerPI*)) ); 77 disconnect( it.current(), SIGNAL(connectionClosed(ServerPI*)), this, SLOT( closed(ServerPI*)) );
77 connections.removeRef( it.current() ); 78 connections.removeRef( it.current() );
78 } else 79 } else
79 ++it; 80 ++it;
80 } 81 }
81} 82}
82 83
83void TransferServer::closed(ServerPI *item) 84void TransferServer::closed(ServerPI *item)
84{ 85{
85 connections.removeRef(item); 86 connections.removeRef(item);
86} 87}
87 88
88TransferServer::~TransferServer() 89TransferServer::~TransferServer()
89{ 90{
90} 91}
91 92
92void TransferServer::newConnection( int socket ) 93void TransferServer::newConnection( int socket )
93{ 94{
94 ServerPI *ptr = new ServerPI( socket, this ); 95 ServerPI *ptr = new ServerPI( socket, this );
95 connect( ptr, SIGNAL(connectionClosed(ServerPI*)), this, SLOT( closed(ServerPI*)) ); 96 connect( ptr, SIGNAL(connectionClosed(ServerPI*)), this, SLOT( closed(ServerPI*)) );
96 connections.append( ptr ); 97 connections.append( ptr );
97} 98}
98 99
99QString SyncAuthentication::serverId() 100QString SyncAuthentication::serverId()
100{ 101{
101 Config cfg("Security"); 102 Config cfg("Security");
102 cfg.setGroup("Sync"); 103 cfg.setGroup("Sync");
103 QString r = cfg.readEntry("serverid"); 104 QString r = cfg.readEntry("serverid");
104 105
105 if ( r.isEmpty() ) { 106 if ( r.isEmpty() ) {
106 r = OGlobal::generateUuid(); 107 r = OGlobal::generateUuid();
107 cfg.writeEntry("serverid", r ); 108 cfg.writeEntry("serverid", r );
108 } 109 }
109 return r; 110 return r;
110} 111}
111 112
112QString SyncAuthentication::ownerName() 113QString SyncAuthentication::ownerName()
113{ 114{
114 QString vfilename = Global::applicationFileName("addressbook", 115 QString vfilename = Global::applicationFileName("addressbook",
115 "businesscard.vcf"); 116 "businesscard.vcf");
116 if (QFile::exists(vfilename)) { 117 if (QFile::exists(vfilename)) {
117 Contact c; 118 Contact c;
118 c = Contact::readVCard( vfilename )[0]; 119 c = Contact::readVCard( vfilename )[0];
119 return c.fullName(); 120 return c.fullName();
120 } 121 }
121 122
122 return QString::null; 123 return QString::null;
123} 124}
124 125
125QString SyncAuthentication::loginName() 126QString SyncAuthentication::loginName()
126{ 127{
127 struct passwd *pw = 0L; 128 struct passwd *pw = 0L;
128#ifndef Q_OS_WIN32 129#ifndef Q_OS_WIN32
129 pw = getpwuid( geteuid() ); 130 pw = getpwuid( geteuid() );
130 return QString::fromLocal8Bit( pw->pw_name ); 131 return QString::fromLocal8Bit( pw->pw_name );
131#else 132#else
132 //### revise 133 //### revise
133 return QString(); 134 return QString();
134#endif 135#endif
135} 136}
136 137
137int SyncAuthentication::isAuthorized(QHostAddress peeraddress) 138int SyncAuthentication::isAuthorized(QHostAddress peeraddress)
138{ 139{
139 Config cfg("Security"); 140 Config cfg("Security");
140 cfg.setGroup("Sync"); 141 cfg.setGroup("Sync");
141 // QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0"); 142 // QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0");
142 uint auth_peer = cfg.readNumEntry("auth_peer", 0xc0a80100); 143 uint auth_peer = cfg.readNumEntry("auth_peer", 0xc0a80100);
143 144
144 // QHostAddress allowed; 145 // QHostAddress allowed;
145 // allowed.setAddress(allowedstr); 146 // allowed.setAddress(allowedstr);
146 // uint auth_peer = allowed.ip4Addr(); 147 // uint auth_peer = allowed.ip4Addr();
147 uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits", 24); 148 uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits", 24);
148 uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined 149 uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined
149 ? 0xffffffff : (((1 << auth_peer_bits) - 1) << (32 - auth_peer_bits)); 150 ? 0xffffffff : (((1 << auth_peer_bits) - 1) << (32 - auth_peer_bits));
150 151
151 return (peeraddress.ip4Addr() & mask) == auth_peer; 152 return (peeraddress.ip4Addr() & mask) == auth_peer;
152} 153}
153 154
154bool SyncAuthentication::checkUser( const QString& user ) 155bool SyncAuthentication::checkUser( const QString& user )
155{ 156{
156 if ( user.isEmpty() ) return FALSE; 157 if ( user.isEmpty() ) return FALSE;
157 QString euser = loginName(); 158 QString euser = loginName();
158 return user == euser; 159 return user == euser;
159} 160}
160 161
161bool SyncAuthentication::checkPassword( const QString& password ) 162bool SyncAuthentication::checkPassword( const QString& password )
162{ 163{
163#ifdef ALLOW_UNIX_USER_FTP 164#ifdef ALLOW_UNIX_USER_FTP
164 // First, check system password... 165 // First, check system password...
165 166
166 struct passwd *pw = 0; 167 struct passwd *pw = 0;
167 struct spwd *spw = 0; 168 struct spwd *spw = 0;
168 169
169 pw = getpwuid( geteuid() ); 170 pw = getpwuid( geteuid() );
170 spw = getspnam( pw->pw_name ); 171 spw = getspnam( pw->pw_name );
171 172
172 QString cpwd = QString::fromLocal8Bit( pw->pw_passwd ); 173 QString cpwd = QString::fromLocal8Bit( pw->pw_passwd );
173 if ( cpwd == "x" && spw ) 174 if ( cpwd == "x" && spw )
174 cpwd = QString::fromLocal8Bit( spw->sp_pwdp ); 175 cpwd = QString::fromLocal8Bit( spw->sp_pwdp );
175 176
176 // Note: some systems use more than crypt for passwords. 177 // Note: some systems use more than crypt for passwords.
177 QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) ); 178 QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) );
178 if ( cpwd == cpassword ) 179 if ( cpwd == cpassword )
179 return TRUE; 180 return TRUE;
180#endif 181#endif
181 182
182 static int lastdenial=0; 183 static int lastdenial=0;
183 static int denials=0; 184 static int denials=0;
184 int now = time(0); 185 int now = time(0);
185 186
186 Config cfg("Security"); 187 Config cfg("Security");
187 cfg.setGroup("SyncMode"); 188 cfg.setGroup("SyncMode");
188 int mode = cfg.readNumEntry("Mode", 0x02 ); 189 int mode = cfg.readNumEntry("Mode", 0x02 );
189 190
190 //No pass word needed if the user really needs it 191 //No pass word needed if the user really needs it
191 if (mode & 0x04) { 192 if (mode & 0x04) {
192 QMessageBox unauth( 193 QMessageBox unauth(
193 tr("Sync Connection"), 194 tr("Sync Connection"),
194 tr("<qt><p>An unauthorized system is requesting access to this device." 195 tr("<qt><p>An unauthorized system is requesting access to this device."
195 "<p>You chose IntelliSync so you may I allow or deny this connection.</qt>" ), 196 "<p>You chose IntelliSync so you may I allow or deny this connection.</qt>" ),
196 QMessageBox::Warning, 197 QMessageBox::Warning,
197 QMessageBox::Ok, QMessageBox::Cancel|QMessageBox::Default, QMessageBox::NoButton, 198 QMessageBox::Ok, QMessageBox::Cancel|QMessageBox::Default, QMessageBox::NoButton,
198 0, QString::null, TRUE, WStyle_StaysOnTop); 199 0, QString::null, TRUE, WStyle_StaysOnTop);
199 unauth.setButtonText(QMessageBox::Ok, tr("Allow" ) ); 200 unauth.setButtonText(QMessageBox::Ok, tr("Allow" ) );
200 unauth.setButtonText(QMessageBox::Cancel, tr("Deny")); 201 unauth.setButtonText(QMessageBox::Cancel, tr("Deny"));
201 switch( unauth.exec() ) { 202 switch( unauth.exec() ) {
202 case QMessageBox::Ok: 203 case QMessageBox::Ok:
203 return TRUE; 204 return TRUE;
204 break; 205 break;
205 case QMessageBox::Cancel: 206 case QMessageBox::Cancel:
206 default: 207 default:
207 denials++; 208 denials++;
208 lastdenial=now; 209 lastdenial=now;
209 return FALSE; 210 return FALSE;
210 } 211 }
211 } 212 }
212 213
213 // Detect old Qtopia Desktop (no password) and fail 214 // Detect old Qtopia Desktop (no password) and fail
214 if ( password.isEmpty() ) { 215 if ( password.isEmpty() ) {
215 if ( denials < 3 || now > lastdenial+600 ) { 216 if ( denials < 3 || now > lastdenial+600 ) {
216 QMessageBox unauth( 217 QMessageBox unauth(
217 tr("Sync Connection"), 218 tr("Sync Connection"),
218 tr("<p>An unauthorized system is requesting access to this device." 219 tr("<p>An unauthorized system is requesting access to this device."
219 "<p>If you are using a version of Qtopia Desktop older than 1.5.1, " 220 "<p>If you are using a version of Qtopia Desktop older than 1.5.1, "
220 "please upgrade or change the security setting to use IntelliSync." ), 221 "please upgrade or change the security setting to use IntelliSync." ),
221 QMessageBox::Warning, 222 QMessageBox::Warning,
222 QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 223 QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton,
223 0, QString::null, TRUE, WStyle_StaysOnTop); 224 0, QString::null, TRUE, WStyle_StaysOnTop);
224 unauth.setButtonText(QMessageBox::Cancel, tr("Deny")); 225 unauth.setButtonText(QMessageBox::Cancel, tr("Deny"));
225 unauth.exec(); 226 unauth.exec();
226 227
227 denials++; 228 denials++;
228 lastdenial=now; 229 lastdenial=now;
229 } 230 }
230 return FALSE; 231 return FALSE;
231 232
232 } 233 }
233 234
234 // Second, check sync password... 235 // Second, check sync password...
235 236
236 static int lock=0; 237 static int lock=0;
237 if ( lock ) return FALSE; 238 if ( lock ) return FALSE;
238 239
239 ++lock; 240 ++lock;
240 241
241 /* 242 /*
242 * we need to support old Sync software and QtopiaDesktop 243 * we need to support old Sync software and QtopiaDesktop
243 */ 244 */
244 if ( password.left(6) == "Qtopia" || password.left(6) == "rootme" ) { 245 if ( password.left(6) == "Qtopia" || password.left(6) == "rootme" ) {
245 Config cfg( "Security" ); 246 Config cfg( "Security" );
246 cfg.setGroup("Sync"); 247 cfg.setGroup("Sync");
247 QStringList pwds = cfg.readListEntry("Passwords",' '); 248 QStringList pwds = cfg.readListEntry("Passwords",' ');
248 for (QStringList::ConstIterator it=pwds.begin(); it!=pwds.end(); ++it) { 249 for (QStringList::ConstIterator it=pwds.begin(); it!=pwds.end(); ++it) {
249#ifndef Q_OS_WIN32 250#ifndef Q_OS_WIN32
250 QString cpassword = QString::fromLocal8Bit( 251 QString cpassword = QString::fromLocal8Bit(
251 crypt( password.mid(8).local8Bit(), (*it).left(2).latin1() ) ); 252 crypt( password.mid(8).local8Bit(), (*it).left(2).latin1() ) );
252#else 253#else
253 // ### revise 254 // ### revise
254 QString cpassword(""); 255 QString cpassword("");
255#endif 256#endif
256 if ( *it == cpassword ) { 257 if ( *it == cpassword ) {
257 lock--; 258 lock--;
258 return TRUE; 259 return TRUE;
259 } 260 }
260 } 261 }
261 262
262 // Unrecognized system. Be careful... 263 // Unrecognized system. Be careful...
263 QMessageBox unrecbox( 264 QMessageBox unrecbox(
264 tr("Sync Connection"), 265 tr("Sync Connection"),
265 tr("<p>An unrecognized system is requesting access to this device." 266 tr("<p>An unrecognized system is requesting access to this device."
266 "<p>If you have just initiated a Sync for the first time, this is normal."), 267 "<p>If you have just initiated a Sync for the first time, this is normal."),
267 QMessageBox::Warning, 268 QMessageBox::Warning,
268 QMessageBox::Cancel, QMessageBox::Yes, QMessageBox::NoButton, 269 QMessageBox::Cancel, QMessageBox::Yes, QMessageBox::NoButton,
269 0, QString::null, TRUE, WStyle_StaysOnTop); 270 0, QString::null, TRUE, WStyle_StaysOnTop);
270 unrecbox.setButtonText(QMessageBox::Cancel, tr("Deny")); 271 unrecbox.setButtonText(QMessageBox::Cancel, tr("Deny"));
271 unrecbox.setButtonText(QMessageBox::Yes, tr("Allow")); 272 unrecbox.setButtonText(QMessageBox::Yes, tr("Allow"));
272 273
273 if ( (denials > 2 && now < lastdenial+600) 274 if ( (denials > 2 && now < lastdenial+600)
274 || unrecbox.exec() != QMessageBox::Yes) 275 || unrecbox.exec() != QMessageBox::Yes)
275 { 276 {
276 denials++; 277 denials++;
277 lastdenial=now; 278 lastdenial=now;
278 lock--; 279 lock--;
279 return FALSE; 280 return FALSE;
280 } else { 281 } else {
281 const char salty[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/."; 282 const char salty[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
282 char salt[2]; 283 char salt[2];
283 salt[0]= salty[rand() % (sizeof(salty)-1)]; 284 salt[0]= salty[rand() % (sizeof(salty)-1)];
284 salt[1]= salty[rand() % (sizeof(salty)-1)]; 285 salt[1]= salty[rand() % (sizeof(salty)-1)];
285#ifndef Q_OS_WIN32 286#ifndef Q_OS_WIN32
286 QString cpassword = QString::fromLocal8Bit( 287 QString cpassword = QString::fromLocal8Bit(
287 crypt( password.mid(8).local8Bit(), salt ) ); 288 crypt( password.mid(8).local8Bit(), salt ) );
288#else 289#else
289 //### revise 290 //### revise
290 QString cpassword(""); 291 QString cpassword("");
291#endif 292#endif
292 denials=0; 293 denials=0;
293 pwds.prepend(cpassword); 294 pwds.prepend(cpassword);
294 cfg.writeEntry("Passwords",pwds,' '); 295 cfg.writeEntry("Passwords",pwds,' ');
295 lock--; 296 lock--;
296 return TRUE; 297 return TRUE;
297 } 298 }
298 } 299 }
299 lock--; 300 lock--;
300 301
301 return FALSE; 302 return FALSE;
302} 303}
303 304
304 305
305ServerPI::ServerPI( int socket, QObject *parent, const char* name ) 306ServerPI::ServerPI( int socket, QObject *parent, const char* name )
306 : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ), 307 : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ),
307 storFileSize(-1) 308 storFileSize(-1)
308{ 309{
309 state = Connected; 310 state = Connected;
310 311
311 setSocket( socket ); 312 setSocket( socket );
312 313
313 peerport = peerPort(); 314 peerport = peerPort();
314 peeraddress = peerAddress(); 315 peeraddress = peerAddress();
315 316
316#ifndef INSECURE 317#ifndef INSECURE
317 if ( !SyncAuthentication::isAuthorized(peeraddress) ) { 318 if ( !SyncAuthentication::isAuthorized(peeraddress) ) {
318 state = Forbidden; 319 state = Forbidden;
319 startTimer( 0 ); 320 startTimer( 0 );
320 } else 321 } else
321#endif 322#endif
322 { 323 {
323 connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); 324 connect( this, SIGNAL( readyRead() ), SLOT( read() ) );
324 connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); 325 connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) );
325 326
326 passiv = FALSE; 327 passiv = FALSE;
327 for( int i = 0; i < 4; i++ ) 328 for( int i = 0; i < 4; i++ )
328 wait[i] = FALSE; 329 wait[i] = FALSE;
329 330
330 send( "220 Qtopia " QPE_VERSION " FTP Server" ); // No tr 331 send( "220 Qtopia " QPE_VERSION " FTP Server" ); // No tr
331 state = Wait_USER; 332 state = Wait_USER;
332 333
333 dtp = new ServerDTP( this ); 334 dtp = new ServerDTP( this );
334 connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) ); 335 connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) );
335 connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) ); 336 connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) );
336 connect( dtp, SIGNAL( error(int) ), SLOT( dtpError(int) ) ); 337 connect( dtp, SIGNAL( error(int) ), SLOT( dtpError(int) ) );
337 338
338 339
339 directory = QDir::currentDirPath(); 340 directory = QDir::currentDirPath();
340 341
341 static int p = 1024; 342 static int p = 1024;
342 343
343 while ( !serversocket || !serversocket->ok() ) { 344 while ( !serversocket || !serversocket->ok() ) {
344 delete serversocket; 345 delete serversocket;
345 serversocket = new ServerSocket( ++p, this ); 346 serversocket = new ServerSocket( ++p, this );
346 } 347 }
347 connect( serversocket, SIGNAL( newIncomming(int) ), 348 connect( serversocket, SIGNAL( newIncomming(int) ),
348 SLOT( newConnection(int) ) ); 349 SLOT( newConnection(int) ) );
349 } 350 }
350} 351}
351 352
352ServerPI::~ServerPI() 353ServerPI::~ServerPI()
353{ 354{
354 close(); 355 close();
355 356
356 if ( dtp ) 357 if ( dtp )
357 dtp->close(); 358 dtp->close();
358 delete dtp; 359 delete dtp;
359 delete serversocket; 360 delete serversocket;
360} 361}
361 362
362bool ServerPI::verifyAuthorised() 363bool ServerPI::verifyAuthorised()
363{ 364{
364 if ( !SyncAuthentication::isAuthorized(peerAddress()) ) { 365 if ( !SyncAuthentication::isAuthorized(peerAddress()) ) {
365 state = Forbidden; 366 state = Forbidden;
366 return FALSE; 367 return FALSE;
367 } 368 }
368 return TRUE; 369 return TRUE;
369} 370}
370 371
371void ServerPI::connectionClosed() 372void ServerPI::connectionClosed()
372{ 373{
373 // qDebug( "Debug: Connection closed" ); 374 // qDebug( "Debug: Connection closed" );
374 emit connectionClosed(this); 375 emit connectionClosed(this);
375} 376}
376 377
377void ServerPI::send( const QString& msg ) 378void ServerPI::send( const QString& msg )
378{ 379{
379 QTextStream os( this ); 380 QTextStream os( this );
380 os << msg << endl; 381 os << msg << endl;
381 //qDebug( "Reply: %s", msg.latin1() ); 382 //qDebug( "Reply: %s", msg.latin1() );
382} 383}
383 384
384void ServerPI::read() 385void ServerPI::read()
385{ 386{
386 while ( canReadLine() ) 387 while ( canReadLine() )
387 process( readLine().stripWhiteSpace() ); 388 process( readLine().stripWhiteSpace() );
388} 389}
389 390
390bool ServerPI::checkReadFile( const QString& file ) 391bool ServerPI::checkReadFile( const QString& file )
391{ 392{
392 QString filename; 393 QString filename;
393 394
394 if ( file[0] != "/" ) 395 if ( file[0] != "/" )
395 filename = directory.path() + "/" + file; 396 filename = directory.path() + "/" + file;
396 else 397 else
397 filename = file; 398 filename = file;
398 399
399 QFileInfo fi( filename ); 400 QFileInfo fi( filename );
400 return ( fi.exists() && fi.isReadable() ); 401 return ( fi.exists() && fi.isReadable() );
401} 402}
402 403
403bool ServerPI::checkWriteFile( const QString& file ) 404bool ServerPI::checkWriteFile( const QString& file )
404{ 405{
405 QString filename; 406 QString filename;
406 407
407 if ( file[0] != "/" ) 408 if ( file[0] != "/" )
408 filename = directory.path() + "/" + file; 409 filename = directory.path() + "/" + file;
409 else 410 else
410 filename = file; 411 filename = file;
411 412
412 QFileInfo fi( filename ); 413 QFileInfo fi( filename );
413 414
414 if ( fi.exists() ) 415 if ( fi.exists() )
415 if ( !QFile( filename ).remove() ) 416 if ( !QFile( filename ).remove() )
416 return FALSE; 417 return FALSE;
417 return TRUE; 418 return TRUE;
418} 419}
419 420
420void ServerPI::process( const QString& message ) 421void ServerPI::process( const QString& message )
421{ 422{
422 //qDebug( "Command: %s", message.latin1() ); 423 //qDebug( "Command: %s", message.latin1() );
423 424
424 // split message using "," as separator 425 // split message using "," as separator
425 QStringList msg = QStringList::split( " ", message ); 426 QStringList msg = QStringList::split( " ", message );
426 if ( msg.isEmpty() ) return; 427 if ( msg.isEmpty() ) return;
427 428
428 // command token 429 // command token
429 QString cmd = msg[0].upper(); 430 QString cmd = msg[0].upper();
430 431
431 // argument token 432 // argument token
432 QString arg; 433 QString arg;
433 if ( msg.count() >= 2 ) 434 if ( msg.count() >= 2 )
434 arg = msg[1]; 435 arg = msg[1];
435 436
436 // full argument string 437 // full argument string
437 QString args; 438 QString args;
438 if ( msg.count() >= 2 ) { 439 if ( msg.count() >= 2 ) {
439 QStringList copy( msg ); 440 QStringList copy( msg );
440 // FIXME: for Qt3 441 // FIXME: for Qt3
441 // copy.pop_front() 442 // copy.pop_front()
442 copy.remove( copy.begin() ); 443 copy.remove( copy.begin() );
443 args = copy.join( " " ); 444 args = copy.join( " " );
444 } 445 }
445 446
446 //qDebug( "args: %s", args.latin1() ); 447 //qDebug( "args: %s", args.latin1() );
447 448
448 // we always respond to QUIT, regardless of state 449 // we always respond to QUIT, regardless of state
449 if ( cmd == "QUIT" ) { 450 if ( cmd == "QUIT" ) {
450 send( "211 Good bye!" ); // No tr 451 send( "211 Good bye!" ); // No tr
451 close(); 452 close();
452 return; 453 return;
453 } 454 }
454 455
455 // connected to client 456 // connected to client
456 if ( Connected == state ) 457 if ( Connected == state )
457 return; 458 return;
458 459
459 // waiting for user name 460 // waiting for user name
460 if ( Wait_USER == state ) { 461 if ( Wait_USER == state ) {
461 462
462 if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) { 463 if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) {
463 send( "530 Please login with USER and PASS" ); // No tr 464 send( "530 Please login with USER and PASS" ); // No tr
464 return; 465 return;
465 } 466 }
466 send( "331 User name ok, need password" ); // No tr 467 send( "331 User name ok, need password" ); // No tr
467 state = Wait_PASS; 468 state = Wait_PASS;
468 return; 469 return;
469 } 470 }
470 471
471 // waiting for password 472 // waiting for password
472 if ( Wait_PASS == state ) { 473 if ( Wait_PASS == state ) {
473 474
474 if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) { 475 if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) {
475 send( "530 Please login with USER and PASS" ); // No tr 476 send( "530 Please login with USER and PASS" ); // No tr
476 return; 477 return;
477 } 478 }
478 send( "230 User logged in, proceed" ); // No tr 479 send( "230 User logged in, proceed" ); // No tr
479 state = Ready; 480 state = Ready;
480 return; 481 return;
481 } 482 }
482 483
483 // ACCESS CONTROL COMMANDS 484 // ACCESS CONTROL COMMANDS
484 485
485 // Only an ALLO sent immediately before STOR is valid. 486 // Only an ALLO sent immediately before STOR is valid.
486 if ( cmd != "STOR" ) 487 if ( cmd != "STOR" )
487 storFileSize = -1; 488 storFileSize = -1;
488 489
489 // account (ACCT) 490 // account (ACCT)
490 if ( cmd == "ACCT" ) { 491 if ( cmd == "ACCT" ) {
491 // even wu-ftp does not support it 492 // even wu-ftp does not support it
492 send( "502 Command not implemented" ); // No tr 493 send( "502 Command not implemented" ); // No tr
493 } 494 }
494 495
495 // change working directory (CWD) 496 // change working directory (CWD)
496 else if ( cmd == "CWD" ) { 497 else if ( cmd == "CWD" ) {
497 498
498 if ( !args.isEmpty() ) { 499 if ( !args.isEmpty() ) {
499 if ( directory.cd( args, TRUE ) ) 500 if ( directory.cd( args, TRUE ) )
500 send( "250 Requested file action okay, completed" ); // No tr 501 send( "250 Requested file action okay, completed" ); // No tr
501 else 502 else
502 send( "550 Requested action not taken" ); // No tr 503 send( "550 Requested action not taken" ); // No tr
503 } 504 }
504 else 505 else
505 send( "500 Syntax error, command unrecognized" ); // No tr 506 send( "500 Syntax error, command unrecognized" ); // No tr
506 } 507 }
507 508
508 // change to parent directory (CDUP) 509 // change to parent directory (CDUP)
509 else if ( cmd == "CDUP" ) { 510 else if ( cmd == "CDUP" ) {
510 if ( directory.cdUp() ) 511 if ( directory.cdUp() )
511 send( "250 Requested file action okay, completed" ); // No tr 512 send( "250 Requested file action okay, completed" ); // No tr
512 else 513 else
513 send( "550 Requested action not taken" ); // No tr 514 send( "550 Requested action not taken" ); // No tr
514 } 515 }
515 516
516 // structure mount (SMNT) 517 // structure mount (SMNT)
517 else if ( cmd == "SMNT" ) { 518 else if ( cmd == "SMNT" ) {
518 // even wu-ftp does not support it 519 // even wu-ftp does not support it
519 send( "502 Command not implemented" ); // No tr 520 send( "502 Command not implemented" ); // No tr
520 } 521 }
521 522
522 // reinitialize (REIN) 523 // reinitialize (REIN)
523 else if ( cmd == "REIN" ) { 524 else if ( cmd == "REIN" ) {
524 // even wu-ftp does not support it 525 // even wu-ftp does not support it
525 send( "502 Command not implemented" ); // No tr 526 send( "502 Command not implemented" ); // No tr
526 } 527 }
527 528
528 529
529 // TRANSFER PARAMETER COMMANDS 530 // TRANSFER PARAMETER COMMANDS
530 531
531 532
532 // data port (PORT) 533 // data port (PORT)
533 else if ( cmd == "PORT" ) { 534 else if ( cmd == "PORT" ) {
534 if ( parsePort( arg ) ) 535 if ( parsePort( arg ) )
535 send( "200 Command okay" ); // No tr 536 send( "200 Command okay" ); // No tr
536 else 537 else
537 send( "500 Syntax error, command unrecognized" ); // No tr 538 send( "500 Syntax error, command unrecognized" ); // No tr
538 } 539 }
539 540
540 // passive (PASV) 541 // passive (PASV)
541 else if ( cmd == "PASV" ) { 542 else if ( cmd == "PASV" ) {
542 passiv = TRUE; 543 passiv = TRUE;
543 send( "227 Entering Passive Mode (" // No tr 544 send( "227 Entering Passive Mode (" // No tr
544 + address().toString().replace( QRegExp( "\\." ), "," ) + "," 545 + address().toString().replace( QRegExp( "\\." ), "," ) + ","
545 + QString::number( ( serversocket->port() ) >> 8 ) + "," 546 + QString::number( ( serversocket->port() ) >> 8 ) + ","
546 + QString::number( ( serversocket->port() ) & 0xFF ) +")" ); 547 + QString::number( ( serversocket->port() ) & 0xFF ) +")" );
547 } 548 }
548 549
549 // representation type (TYPE) 550 // representation type (TYPE)
550 else if ( cmd == "TYPE" ) { 551 else if ( cmd == "TYPE" ) {
551 if ( arg.upper() == "A" || arg.upper() == "I" ) 552 if ( arg.upper() == "A" || arg.upper() == "I" )
552 send( "200 Command okay" ); // No tr 553 send( "200 Command okay" ); // No tr
553 else 554 else
554 send( "504 Command not implemented for that parameter" ); // No tr 555 send( "504 Command not implemented for that parameter" ); // No tr
555 } 556 }
556 557
557 // file structure (STRU) 558 // file structure (STRU)
558 else if ( cmd == "STRU" ) { 559 else if ( cmd == "STRU" ) {
559 if ( arg.upper() == "F" ) 560 if ( arg.upper() == "F" )
560 send( "200 Command okay" ); // No tr 561 send( "200 Command okay" ); // No tr
561 else 562 else
562 send( "504 Command not implemented for that parameter" ); // No tr 563 send( "504 Command not implemented for that parameter" ); // No tr
563 } 564 }
564 565
565 // transfer mode (MODE) 566 // transfer mode (MODE)
566 else if ( cmd == "MODE" ) { 567 else if ( cmd == "MODE" ) {
567 if ( arg.upper() == "S" ) 568 if ( arg.upper() == "S" )
568 send( "200 Command okay" ); // No tr 569 send( "200 Command okay" ); // No tr
569 else 570 else
570 send( "504 Command not implemented for that parameter" ); // No tr 571 send( "504 Command not implemented for that parameter" ); // No tr
571 } 572 }
572 573
573 574
diff --git a/core/launcher/wait.cpp b/core/launcher/wait.cpp
index 4148e57..a5b329d 100644
--- a/core/launcher/wait.cpp
+++ b/core/launcher/wait.cpp
@@ -1,74 +1,75 @@
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 "wait.h" 21#include "wait.h"
22 22
23#include <qtopia/config.h> 23#include <qtopia/config.h>
24 24
25#include <opie2/owait.h> 25#include <opie2/owait.h>
26 26
27 27
28 28
29Wait *lastWaitObject = NULL; 29Wait *lastWaitObject = NULL;
30 30
31 31
32using namespace Opie::Ui;
32Wait::Wait( QWidget *parent ) : QWidget( parent ), 33Wait::Wait( QWidget *parent ) : QWidget( parent ),
33 pm( Resource::loadPixmap( "wait" ) ), waiting( FALSE ) 34 pm( Resource::loadPixmap( "wait" ) ), waiting( FALSE )
34{ 35{
35 setFixedSize( pm.size() ); 36 setFixedSize( pm.size() );
36 lastWaitObject = this; 37 lastWaitObject = this;
37 m_centralWait = new OWait( 0l ); 38 m_centralWait = new OWait( 0l );
38 m_centralWait->hide(); 39 m_centralWait->hide();
39 hide(); 40 hide();
40} 41}
41 42
42 43
43Wait *Wait::getWaitObject() 44Wait *Wait::getWaitObject()
44{ 45{
45 return lastWaitObject; 46 return lastWaitObject;
46} 47}
47 48
48 49
49void Wait::setWaiting( bool w ) 50void Wait::setWaiting( bool w )
50{ 51{
51 Config cfg ( "Launcher" ); 52 Config cfg ( "Launcher" );
52 cfg.setGroup("GUI"); 53 cfg.setGroup("GUI");
53 54
54 55
55 waiting = w; 56 waiting = w;
56 if ( w ) { 57 if ( w ) {
57 if ( cfg. readBoolEntry( "BigBusy" ) ) 58 if ( cfg. readBoolEntry( "BigBusy" ) )
58 m_centralWait->show(); 59 m_centralWait->show();
59 else 60 else
60 show(); 61 show();
61 }else{ 62 }else{
62 m_centralWait->hide(); 63 m_centralWait->hide();
63 hide(); 64 hide();
64 } 65 }
65} 66}
66 67
67 68
68void Wait::paintEvent( QPaintEvent * ) 69void Wait::paintEvent( QPaintEvent * )
69{ 70{
70 QPainter p( this ); 71 QPainter p( this );
71 p.drawPixmap( 0, 0, pm ); 72 p.drawPixmap( 0, 0, pm );
72} 73}
73 74
74 75
diff --git a/core/launcher/wait.h b/core/launcher/wait.h
index e7294d2..010fcc3 100644
--- a/core/launcher/wait.h
+++ b/core/launcher/wait.h
@@ -1,46 +1,46 @@
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 __WAIT_H__ 21#ifndef __WAIT_H__
22#define __WAIT_H__ 22#define __WAIT_H__
23 23
24#include <qtopia/resource.h> 24#include <qtopia/resource.h>
25 25
26#include <qwidget.h> 26#include <qwidget.h>
27#include <qpixmap.h> 27#include <qpixmap.h>
28#include <qpainter.h> 28#include <qpainter.h>
29 29
30class OWait; 30namespace Opie {namespace Ui {class OWait;}}
31class Wait : public QWidget 31class Wait : public QWidget
32{ 32{
33public: 33public:
34 Wait( QWidget *parent ); 34 Wait( QWidget *parent );
35 void setWaiting( bool w ); 35 void setWaiting( bool w );
36 void paintEvent( QPaintEvent * ); 36 void paintEvent( QPaintEvent * );
37 static Wait *getWaitObject(); 37 static Wait *getWaitObject();
38private: 38private:
39 QPixmap pm; 39 QPixmap pm;
40 bool waiting; 40 bool waiting;
41 OWait* m_centralWait; 41 Opie::Ui::OWait* m_centralWait;
42}; 42};
43 43
44 44
45#endif // __WAIT_H__ 45#endif // __WAIT_H__
46 46