summaryrefslogtreecommitdiff
path: root/core/launcher/serverapp.cpp
blob: 6edaa21b8017001cca4beaaaa07f8786aaad185b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/**********************************************************************
** Copyright (C) 2000-2003 Trolltech AS.  All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#include "serverapp.h"

#include <qtopia/password.h>
#include <qtopia/config.h>
#include <qtopia/power.h>
#include <qtopia/devicebuttonmanager.h>
#include <qtopia/pluginloader.h>

#ifdef Q_WS_QWS
#include <qtopia/qcopenvelope_qws.h>
#endif
#include <qtopia/global.h>
#include <qtopia/custom.h>

#ifdef Q_WS_QWS
#include <qgfx_qws.h>
#endif
#ifdef Q_OS_WIN32
#include <io.h>
#include <process.h>
#else
#include <unistd.h>
#endif
#include <qmessagebox.h>
#include <qtimer.h>
#include <qpainter.h>
#include <qfile.h>
#include <qpixmapcache.h>

#include <stdlib.h>

static ServerApplication *serverApp = 0;
static int loggedin=0;



/*  Apply light/power settings for current power source */
static void applyLightSettings(PowerStatus *p)
{
    int initbright, intervalDim, intervalLightOff, intervalSuspend;
    bool dim, lightoff, suspend;

    {
	Config config("qpe");
	bool defsus;
	if ( p->acStatus() == PowerStatus::Online ) {
	    config.setGroup("ExternalPower");
	    defsus = FALSE;
	} else {
	    config.setGroup("BatteryPower");
	    defsus = TRUE;
	}

	intervalDim = config.readNumEntry( "Interval_Dim", 20 );
	intervalLightOff = config.readNumEntry("Interval_LightOff", 30);
	intervalSuspend = config.readNumEntry("Interval", 240);
	initbright = config.readNumEntry("Brightness", 255);
	dim = config.readBoolEntry("Dim", TRUE);
	lightoff = config.readBoolEntry("LightOff", FALSE );
	suspend = config.readBoolEntry("Suspend", defsus );

	/*	For compability	*/
	config.setGroup("Screensaver");
	config.writeEntry( "Dim", dim );
	config.writeEntry( "LightOff", lightoff );
	config.writeEntry( "Suspend", suspend );
	config.writeEntry( "Interval_Dim", intervalDim );
	config.writeEntry( "Interval_LightOff", intervalLightOff );
	config.writeEntry( "Interval", intervalSuspend );
	config.writeEntry( "Brightness", initbright );
    }

    int i_dim =      (dim ? intervalDim : 0);
    int i_lightoff = (lightoff ? intervalLightOff : 0);
    int i_suspend =  (suspend ? intervalSuspend : 0);

#ifndef QT_NO_COP
    QCopEnvelope eB("QPE/System", "setBacklight(int)" );
    eB << initbright;

    QCopEnvelope e("QPE/System", "setScreenSaverIntervals(int,int,int)" );
    e << i_dim << i_lightoff << i_suspend;
#endif
}

//---------------------------------------------------------------------------

/*
  Priority is number of alerts that are needed to pop up
  alert.
 */
class DesktopPowerAlerter : public QMessageBox
{
    Q_OBJECT
public:
    DesktopPowerAlerter( QWidget *parent, const char *name = 0 )
	: QMessageBox( tr("Battery Status"), tr("Low Battery"),
		       QMessageBox::Critical,
		       QMessageBox::Ok | QMessageBox::Default,
		       QMessageBox::NoButton, QMessageBox::NoButton,
		       parent, name, FALSE )
    {
	currentPriority = INT_MAX;
	alertCount = 0;
    }

    void alert( const QString &text, int priority );
    void hideEvent( QHideEvent * );
private:
    int currentPriority;
    int alertCount;
};

void DesktopPowerAlerter::alert( const QString &text, int priority )
{
    alertCount++;
    if ( alertCount < priority )
	return;
    if ( priority > currentPriority )
	return;
    currentPriority = priority;
    setText( text );
    show();
}


void DesktopPowerAlerter::hideEvent( QHideEvent *e )
{
    QMessageBox::hideEvent( e );
    alertCount = 0;
    currentPriority = INT_MAX;
}

//---------------------------------------------------------------------------

KeyFilter::KeyFilter(QObject* parent) : QObject(parent), held_tid(0), heldButton(0)
{
    qwsServer->setKeyboardFilter(this);
}

void KeyFilter::timerEvent(QTimerEvent* e)
{
    if ( e->timerId() == held_tid ) {
	killTimer(held_tid);
	// button held
	if ( heldButton ) {
	    emit activate(heldButton, TRUE);
	    heldButton = 0;
	}
	held_tid = 0;
    }
}

bool KeyFilter::filter(int /*unicode*/, int keycode, int modifiers, bool press,
		  bool autoRepeat)
{
    if ( !loggedin
	    // Permitted keys
	    && keycode != Key_F34 // power
	    && keycode != Key_F30 // select
	    && keycode != Key_Enter
	    && keycode != Key_Return
	    && keycode != Key_Space
	    && keycode != Key_Left
	    && keycode != Key_Right
	    && keycode != Key_Up
	    && keycode != Key_Down )
	return TRUE;
    if ( !modifiers ) {
	if ( !((ServerApplication*)qApp)->keyboardGrabbed() ) {
	    // First check to see if DeviceButtonManager knows something about this button:
	    const DeviceButton* button = DeviceButtonManager::instance().buttonForKeycode(keycode);
	    if (button && !autoRepeat) {
		if ( held_tid ) {
		    killTimer(held_tid);
		    held_tid = 0;
		}
		if ( button->heldAction().isNull() ) {
		    if ( press )
			emit activate(button, FALSE);
		} else if ( press ) {
		    heldButton = button;
		    held_tid = startTimer(500);
		} else if ( heldButton ) {
		    heldButton = 0;
		    emit activate(button, FALSE);
		}
		QWSServer::screenSaverActivate(FALSE);
		return TRUE;
	    }
	}
	if ( keycode == Key_F34 ) {
	    if ( press ) emit power();
	    return TRUE;
	}
	if ( keycode == Key_F35 ) {
	    if ( press ) emit backlight();
	    return TRUE;
	}
	if ( keycode == Key_F32 ) {
#ifndef QT_NO_COP
	    if ( press ) QCopEnvelope e( "QPE/Desktop", "startSync()" );
#endif
	    return TRUE;
	}
	if ( keycode == Key_F31 ) {
	    if ( press ) emit symbol();
	    QWSServer::screenSaverActivate(FALSE);
	    return TRUE;
	}
    }
    if ( keycode == Key_NumLock ) {
	if ( press ) emit numLockStateToggle();
    }
    if ( keycode == Key_CapsLock ) {
	if ( press ) emit capsLockStateToggle();
    }
    if ( serverApp )
	serverApp->keyClick(keycode,press,autoRepeat);
    return FALSE;
}

enum MemState { MemUnknown, MemVeryLow, MemLow, MemNormal } memstate=MemUnknown;

#if defined(QPE_HAVE_MEMALERTER)
QPE_MEMALERTER_IMPL
#endif

#if defined(CUSTOM_SOUND_IMPL)
CUSTOM_SOUND_IMPL
#endif

//---------------------------------------------------------------------------

bool ServerApplication::doRestart = FALSE;
bool ServerApplication::allowRestart = TRUE;

ServerApplication::ServerApplication( int& argc, char **argv, Type t )
    : QPEApplication( argc, argv, t )
{
#ifdef CUSTOM_SOUND_INIT
    CUSTOM_SOUND_INIT;
#endif

#if defined(QPE_HAVE_MEMALERTER)
    initMemalerter();
#endif

    // We know we'll have lots of cached pixmaps due to App/DocLnks
    QPixmapCache::setCacheLimit(512);

    QTimer *timer = new QTimer( this );
    connect( timer, SIGNAL(timeout()), this, SLOT(psTimeout()) );
    timer->start( 10000 );
    ps = new PowerStatus;
    pa = new DesktopPowerAlerter( 0 );

    applyLightSettings(ps);

    if ( PluginLoader::inSafeMode() )
	QTimer::singleShot(500, this, SLOT(showSafeMode()) );
    QTimer::singleShot(20*1000, this, SLOT(clearSafeMode()) );

    KeyFilter* kf = new KeyFilter(this);

    connect( kf, SIGNAL(launch()), this, SIGNAL(launch()) );
    connect( kf, SIGNAL(power()), this, SIGNAL(power()) );
    connect( kf, SIGNAL(backlight()), this, SIGNAL(backlight()) );
    connect( kf, SIGNAL(symbol()), this, SIGNAL(symbol()));
    connect( kf, SIGNAL(numLockStateToggle()), this,SIGNAL(numLockStateToggle()));
    connect( kf, SIGNAL(capsLockStateToggle()), this,SIGNAL(capsLockStateToggle()));
    connect( kf, SIGNAL(activate(const DeviceButton*,bool)), this,SIGNAL(activate(const DeviceButton*,bool)));

    connect( kf, SIGNAL(power()), this, SLOT(togglePower()) );
    connect( kf, SIGNAL(backlight()), this, SLOT(toggleLight()) );

    connect( this, SIGNAL(volumeChanged(bool)), this, SLOT(rereadVolumes()) );
    rereadVolumes();

    serverApp = this;
}


ServerApplication::~ServerApplication()
{
    delete ps;
    delete pa;
}

bool ServerApplication::screenLocked()
{
    return loggedin == 0;
}

void ServerApplication::login(bool at_poweron)
{
    if ( !loggedin ) {
	Global::terminateBuiltin("calibrate"); // No tr
	Password::authenticate(at_poweron);
	loggedin=1;
#ifndef QT_NO_COP
	QCopEnvelope e( "QPE/Desktop", "unlocked()" );
#endif
    }
}

#if defined(QPE_HAVE_TOGGLELIGHT)
#include <qtopia/config.h>

#include <sys/ioctl.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <linux/ioctl.h>
#include <time.h>
#endif

static bool blanked=FALSE;

static void blankScreen()
{
#ifdef QWS
    QWidget w(0, 0, Qt::WStyle_Customize | Qt::WStyle_NoBorder | Qt::WStyle_Tool | Qt::WStyle_StaysOnTop | Qt::WPaintUnclipped);
    w.resize( qt_screen->width(), qt_screen->height() );
    w.move(0, 0);
    
    QPainter p(&w);
    p.fillRect(w.rect(), QBrush(QColor(255,255,255)) );
    p.end();
    w.repaint();

    blanked = TRUE;
#endif
}

static void darkScreen()
{
    qpe_setBacklight(0); // force off
}


void ServerApplication::togglePower()
{
    static int haveAPM = -1;
    if ( haveAPM < 0 ) {
	if ( QFile::exists( "/proc/apm" ) ) {
	    haveAPM = 1;
	} else {
	    haveAPM = 0;
	    qWarning( "Cannot suspend - no APM support in kernel" );
	}
    }
    
    if ( haveAPM ) {
	bool wasloggedin = loggedin;
	loggedin=0;
	if ( wasloggedin ) {
	    Config cfg( QPEApplication::qpeDir()+"/etc/Security.conf", Config::File);
	    cfg.setGroup("Passcode");
	    QString passcode = cfg.readEntry("passcode");
	    if ( !passcode.isEmpty() && cfg.readNumEntry("passcode_poweron",0) )
		blankScreen();
	}
	
	system("apm --suspend");
    
#ifndef QT_NO_COP
	QWSServer::screenSaverActivate( FALSE );
	{
	    QCopEnvelope("QPE/Card", "mtabChanged()" ); // might have changed while asleep
	    QCopEnvelope e("QPE/System", "setBacklight(int)");
	    e << -3; // Force on
	}
#endif
	if ( wasloggedin )
	    login(TRUE);
    } 
    
    //qcopBridge->closeOpenConnections();
    //qDebug("called togglePower()!!!!!!");
}

void ServerApplication::toggleLight()
{
#ifndef QT_NO_COP
    QCopEnvelope e("QPE/System", "setBacklight(int)");
    e << -2; // toggle
#endif
}


#ifdef Q_WS_QWS
bool ServerApplication::qwsEventFilter( QWSEvent *e )
{
    checkMemory();

    if ( e->type == QWSEvent::Mouse ) {
	QWSMouseEvent *me = (QWSMouseEvent *)e;
	static bool up = TRUE;
	if ( me->simpleData.state&LeftButton ) {
	    if ( up ) {
		up = FALSE;
		screenClick(TRUE);
	    }
	} else if ( !up ) {
	    up = TRUE;
	    screenClick(FALSE);
	}
    }

    return QPEApplication::qwsEventFilter( e );
}
#endif

void ServerApplication::psTimeout()
{
    checkMemory(); // in case no events are being generated

    PowerStatus::ACStatus oldStatus = ps->acStatus();

    *ps = PowerStatusManager::readStatus();

    if ( oldStatus != ps->acStatus() ) {
	// power source changed, read settings applying to current powersource
	applyLightSettings(ps);
    }


    if ( (ps->batteryStatus() == PowerStatus::VeryLow ) ) {
	pa->alert( tr( "Battery is running very low." ), 6 );
    }

    if (  ps->batteryStatus() == PowerStatus::Critical ) {
	pa->alert(  tr( "Battery level is critical!\n"
			"Please recharge the main battery!" ), 1 );
    }

    if (  ps->backupBatteryStatus() == PowerStatus::VeryLow ) {
	pa->alert( tr( "The Back-up battery is very low.\nPlease charge the back-up battery." ), 3 );
    }
}

void ServerApplication::showSafeMode()
{
    if ( QMessageBox::warning(0, tr("Safe Mode"), tr("<P>A system startup error occurred, "
		"and the system is now in Safe Mode. "
		"Plugins are not loaded in Safe Mode. "
		"You can use the Plugin Manager to "
		"disable plugins that cause system error."), tr("OK"), tr("Plugin Manager..."), 0) == 1 ) {
	Global::execute( "pluginmanager" );
    }
}

void ServerApplication::clearSafeMode()
{
    // If we've been running OK for a while then we won't bother going into
    // safe mode immediately on the next crash.
    Config cfg( "PluginLoader" );
    cfg.setGroup( "Global" );
    QString mode = cfg.readEntry( "Mode", "Normal" );
    if ( mode == "MaybeSafe" ) {
	cfg.writeEntry( "Mode", "Normal" );
    }
}

void ServerApplication::shutdown()
{
    if ( type() != GuiServer )
	return;
    ShutdownImpl *sd = new ShutdownImpl( 0, 0, WDestructiveClose );
    connect( sd, SIGNAL(shutdown(ShutdownImpl::Type)),
	     this, SLOT(shutdown(ShutdownImpl::Type)) );
    sd->showMaximized();
}

void ServerApplication::shutdown( ShutdownImpl::Type t )
{
    switch ( t ) {
	case ShutdownImpl::ShutdownSystem:
#ifndef Q_OS_WIN32
	    execlp("shutdown", "shutdown", "-h", "now", (void*)0); // No tr
#else
	    qDebug("ServerApplication::ShutdownSystem");      
	    prepareForTermination(FALSE);
	    quit();
#endif
	    break;

	case ShutdownImpl::RebootSystem:
#ifndef Q_OS_WIN32
	    execlp("shutdown", "shutdown", "-r", "now", (void*)0); // No tr
#else
	    qDebug("ServerApplication::RebootSystem");      
	    restart();
#endif
	    break;

	case ShutdownImpl::RestartDesktop:
	    restart();
	    break;

	case ShutdownImpl::TerminateDesktop:
	    prepareForTermination(FALSE);
	    quit();
	    break;
    }
}

void ServerApplication::restart()
{
    if ( allowRestart ) {
	prepareForTermination(TRUE);
	doRestart = TRUE;
	quit();
    }
}

void ServerApplication::rereadVolumes()
{
    Config cfg("Sound");
    cfg.setGroup("System");
    touchclick = cfg.readBoolEntry("Touch");
    keyclick = cfg.readBoolEntry("Key");
}


void ServerApplication::checkMemory()
{
#if defined(QPE_HAVE_MEMALERTER)
    static bool ignoreNormal=TRUE;
    static bool existingMessage=FALSE;

    if(existingMessage)
	return; // don't show a second message while still on first

    existingMessage = TRUE;
    switch ( memstate ) {
	case MemUnknown:
	    break;
	case MemLow:
	    memstate = MemUnknown;
	    if ( !recoverMemory() ) {
		QMessageBox::warning( 0 , tr("Memory Status"),
		    tr("Memory Low\nPlease save data.") );
		ignoreNormal = FALSE;
	    }
	    break;
	case MemNormal:
	    memstate = MemUnknown;
	    if ( !ignoreNormal ) {
		ignoreNormal = TRUE;
		QMessageBox::information ( 0 , tr("Memory Status"),
		    "Memory OK" );
	    }
	    break;
	case MemVeryLow:
	    memstate = MemUnknown;
	    QMessageBox::critical( 0 , tr("Memory Status"),
		tr("Critical Memory Shortage\n"
		"Please end this application\n"
		"immediately.") );
	    recoverMemory();
    }
    existingMessage = FALSE;
#endif
}

bool ServerApplication::recoverMemory()
{
    return FALSE;
}

void ServerApplication::keyClick(int keycode, bool press, bool repeat)
{
#ifdef CUSTOM_SOUND_KEYCLICK
    if ( keyclick )
	CUSTOM_SOUND_KEYCLICK(keycode,press,repeat);
#else
    Q_UNUSED( keycode );
    Q_UNUSED( press );
    Q_UNUSED( repeat );
#endif
}

void ServerApplication::screenClick(bool press)
{
#ifdef CUSTOM_SOUND_TOUCH
    if ( touchclick )
	CUSTOM_SOUND_TOUCH(press);
#else
    Q_UNUSED( press );
#endif
}


#include "serverapp.moc"