securitydialogs/Autolock/src/Autolock.cpp
branchRCL_3
changeset 50 03674e5abf46
parent 49 09b1ac925e3f
child 54 94da73d93b58
equal deleted inserted replaced
49:09b1ac925e3f 50:03674e5abf46
     1 /*
       
     2  * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     3  * All rights reserved.
       
     4  *
       
     5  * This program is free software: you can redistribute it and/or modify
       
     6  * it under the terms of the GNU Lesser General Public License as published by
       
     7  * the Free Software Foundation, version 2.1 of the License.
       
     8  * 
       
     9  * This program is distributed in the hope that it will be useful,
       
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    12  * GNU Lesser General Public License for more details.
       
    13  *
       
    14  * You should have received a copy of the GNU Lesser General Public License
       
    15  * along with this program.  If not, 
       
    16  * see "http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html/".
       
    17  *
       
    18  * Description:
       
    19  *
       
    20  */
       
    21 
       
    22 #include <QCoreApplication>
       
    23 #include <QKeyEvent>
       
    24 #include <QEvent>
       
    25 #include <QTimer>
       
    26 #include <QMessageBox>
       
    27 #include <QSymbianEvent>
       
    28 #include <QMainWindow>
       
    29 #include <qvaluespacesubscriber.h>
       
    30 #include <qvaluespacepublisher.h>
       
    31 
       
    32 QTM_USE_NAMESPACE
       
    33 
       
    34 #include <HbIndicator>
       
    35 #include <hbdevicemessagebox.h>
       
    36 
       
    37 #include <lockappclientserver.h>
       
    38 
       
    39 #include "Autolock.h"
       
    40 #include <xqserviceutil.h>
       
    41 #include "autolockuseractivityservice.h"
       
    42 #include <settingsinternalcrkeys.h>     // CenRep keys
       
    43 #include <w32std.h>
       
    44 #include <eikenv.h>
       
    45 #include <aknsoundsystem.h>
       
    46 
       
    47 #include <secuisecuritysettings.h>
       
    48 #include <secui.h>
       
    49 #include <secuisecurityhandler.h>
       
    50 #include <etelmm.h>
       
    51 #include <rmmcustomapi.h>
       
    52 #include <keylockpolicyapi.h>
       
    53 #include <qvaluespacesubscriber.h>
       
    54 
       
    55 #include <hwrmlightdomaincrkeys.h>
       
    56 #include <ProfileEngineSDKCRKeys.h>
       
    57 #include <e32property.h>
       
    58 #include <coreapplicationuisdomainpskeys.h>
       
    59 #include "../PubSub/securityuisprivatepskeys.h"
       
    60 #include <avkondomainpskeys.h>
       
    61 #include <hwrmdomainpskeys.h>
       
    62 #include <ctsydomainpskeys.h>
       
    63 
       
    64 #include <hbdevicedialog.h>
       
    65 #include <power_save_display_mode.h>
       
    66 
       
    67 const TInt KPhoneIndex(0);
       
    68 const TInt KTriesToConnectServer(2);
       
    69 const TInt KTimeBeforeRetryingServerConnection(50000);
       
    70 #define ESecUiTypeLock                  0x00100000
       
    71 _LIT( KMmTsyModuleName, "PhoneTsy");
       
    72 
       
    73 // Constant definitions to control screensaver view types
       
    74 static const char *KSnsrViewTypeKey = "view_type";
       
    75 enum TSnsrViewType
       
    76     {
       
    77     ESnsrViewTypeInitial = 0, // default initial state, depends on the configuration
       
    78     ESnsrViewTypeActive,
       
    79     ESnsrViewTypeStandby,
       
    80     ESnsrViewTypeDisabled,
       
    81     };
       
    82 static const char *KSnsrCmdUnlock = "unlock";
       
    83 static const char *KSnsrCmdSwitchLights = "switch_lights";
       
    84 static const char *KSnsrCmdSwitchLowPower = "switch_low_power";
       
    85 
       
    86 Autolock::Autolock(QWidget *parent, Qt::WFlags f) :
       
    87     QWidget(parent, f), mService(NULL)
       
    88     {
       
    89     RDEBUG("start autolock", 0);
       
    90 
       
    91     // The very first thing is to define the properties, so that others can use them.
       
    92     TSecurityPolicy readPolicy(ECapabilityReadDeviceData);
       
    93     TSecurityPolicy writePolicy(ECapabilityWriteDeviceData);
       
    94     TInt ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, RProperty::EInt, readPolicy, writePolicy);
       
    95     RDEBUG("defined KSecurityUIsSecUIOriginatedQuery", ret);
       
    96     ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsQueryRequestCancel, RProperty::EInt, readPolicy, writePolicy);
       
    97     RDEBUG("defined KSecurityUIsQueryRequestCancel", ret);
       
    98     _LIT_SECURITY_POLICY_PASS( KReadPolicy);
       
    99     _LIT_SECURITY_POLICY_C1(KWritePolicy, ECapabilityWriteDeviceData);
       
   100     ret = RProperty::Define(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, RProperty::EInt, KReadPolicy, KWritePolicy);
       
   101     RDEBUG("defined KCoreAppUIsAutolockStatus", ret);
       
   102 
       
   103     // This is important: we set the status through a property
       
   104     TInt autolockState;
       
   105     ret = RProperty::Get(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, autolockState);
       
   106     RDEBUG("Get KCoreAppUIsAutolockStatus", ret);
       
   107     RDEBUG("autolockState", autolockState);
       
   108     if (autolockState == EAutolockStatusUninitialized)
       
   109         {
       
   110         autolockState = EAutolockOff; // not-initialized means taht the unlock-query hasn't been displayed. Therefore the device should not stay locked.
       
   111         }
       
   112     ret = RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, autolockState); // this might re-set it. That's not bad. It will re-notify all listeners.
       
   113     RDEBUG("Set KCoreAppUIsAutolockStatus", ret);
       
   114 
       
   115     ret = RProperty::Define(KPSUidAvkonDomain, KAknKeyguardStatus, RProperty::EInt, TSecurityPolicy(TSecurityPolicy::EAlwaysPass), KWritePolicy);
       
   116     RDEBUG("defined KAknKeyguardStatus", ret);
       
   117 
       
   118     ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsLockInitiatorUID, RProperty::EInt, TSecurityPolicy(TSecurityPolicy::EAlwaysPass), writePolicy);
       
   119     RDEBUG("defined KSecurityUIsLockInitiatorUID", ret);
       
   120 
       
   121     ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsLockInitiatorTimeHigh, RProperty::EInt, readPolicy, writePolicy);
       
   122     RDEBUG("defined KSecurityUIsLockInitiatorTimeHigh", ret);
       
   123     ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsLockInitiatorTimeLow, RProperty::EInt, readPolicy, writePolicy);
       
   124     RDEBUG("defined KSecurityUIsLockInitiatorTimeLow", ret);
       
   125 
       
   126     ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsLights, RProperty::EInt, TSecurityPolicy(TSecurityPolicy::EAlwaysPass), TSecurityPolicy(TSecurityPolicy::EAlwaysPass));
       
   127     RDEBUG("defined KAknKeyguardStatus", ret);
       
   128 
       
   129     ret = RProperty::Define(KPSUidSecurityUIs, KSecurityUIsDismissDialog, RProperty::EInt, TSecurityPolicy(TSecurityPolicy::EAlwaysPass), TSecurityPolicy(
       
   130             TSecurityPolicy::EAlwaysPass));
       
   131     RDEBUG("defined KSecurityUIsDismissDialog", ret);
       
   132 
       
   133     mService = new AutolockService(this);
       
   134 
       
   135     /* Adjust the palette */
       
   136 #if defined(Q_WS_S60)
       
   137     // this is defined.
       
   138     RDEBUG( "Q_WS_S60", 1 );
       
   139     QPalette p = qApp->palette();
       
   140     QColor color(192,192,192);
       
   141     QColor bg(201,250,250);
       
   142     p.setColor(QPalette::Highlight, color.lighter(200));
       
   143     p.setColor(QPalette::Text, Qt::black);
       
   144     p.setColor(QPalette::Base, bg);
       
   145     p.setColor(QPalette::WindowText, Qt::black);
       
   146     p.setColor(QPalette::Window, bg);
       
   147     p.setColor(QPalette::ButtonText, Qt::black);
       
   148     p.setColor(QPalette::Button, color.lighter(150));
       
   149     p.setColor(QPalette::Link, QColor(240,40,40));
       
   150 
       
   151     qApp->setPalette(p);
       
   152 #endif
       
   153 
       
   154     RDEBUG("connect", 1);
       
   155 
       
   156 #if defined(Q_WS_X11) || defined(Q_WS_WIN)
       
   157     setFixedSize(QSize(360,640)); // nHD
       
   158 #elif defined(Q_WS_S60)
       
   159     // this doesn't work well
       
   160     // showMaximized();
       
   161     showFullScreen();
       
   162 #endif
       
   163 
       
   164     serviceKeyguard = new AutolockUserActivityService();
       
   165     serviceDevicelock = new AutolockUserActivityService();
       
   166 
       
   167     TInt lockValue = 0;
       
   168     TInt lightsTimeout = 0;
       
   169     CRepository* repository = NULL;
       
   170     TInt cRresult = 0;
       
   171     iLockCodeQueryInDisplay = EFalse;
       
   172     Q_UNUSED(cRresult);
       
   173 
       
   174 		iProcessingEvent = -1;
       
   175     iLockStatusPrev = ELockNotActive;
       
   176     iLockStatus = ELockNotActive;
       
   177     QT_TRAP_THROWING(repository = CRepository::NewL(KCRUidSecuritySettings));
       
   178     cRresult = repository->Get(KSettingsAutolockStatus, lockValue);
       
   179     RDEBUG("KSettingsAutolockStatus", KSettingsAutolockStatus);
       
   180     RDEBUG("cRresult", cRresult);
       
   181     RDEBUG("lockValue", lockValue);
       
   182     iLockStatus = lockValue;
       
   183     // the settings says to lock
       
   184     delete repository;
       
   185 
       
   186     adjustInactivityTimers(0);
       
   187 
       
   188     QT_TRAP_THROWING(repository = CRepository::NewL(KCRUidProfileEngine));
       
   189     cRresult = repository->Get(KProEngActiveProfile, lightsTimeout);
       
   190     // this value is not used for now
       
   191     delete repository;
       
   192 
       
   193     QT_TRAP_THROWING(repository = CRepository::NewL(KCRUidLightSettings));
       
   194     cRresult = repository->Get(KDisplayLightsTimeout, lightsTimeout);
       
   195     // this value is not used for now
       
   196     delete repository;
       
   197 
       
   198     // subscribe to settings changes
       
   199     subscriberKSettingsAutolockStatus = new QValueSpaceSubscriber("/KCRUidSecuritySettings/KSettingsAutolockStatus", this);
       
   200     connect(subscriberKSettingsAutolockStatus, SIGNAL(contentsChanged()), this, SLOT(subscriberKSettingsAutolockStatusChanged()));
       
   201     subscriberKSettingsAutoLockTime = new QValueSpaceSubscriber("/KCRUidSecuritySettings/KSettingsAutoLockTime", this);
       
   202     connect(subscriberKSettingsAutoLockTime, SIGNAL(contentsChanged()), this, SLOT(subscriberKSettingsAutoLockTimeChanged()));
       
   203     subscriberKSettingsAutomaticKeyguardTime = new QValueSpaceSubscriber("/KCRUidSecuritySettings/KSettingsAutomaticKeyguardTime", this);
       
   204     connect(subscriberKSettingsAutomaticKeyguardTime, SIGNAL(contentsChanged()), this, SLOT(subscriberKSettingsAutomaticKeyguardTimeChanged()));
       
   205     subscriberKDisplayLightsTimeout = new QValueSpaceSubscriber("/KCRUidLightSettings/KDisplayLightsTimeout", this);
       
   206     connect(subscriberKDisplayLightsTimeout, SIGNAL(contentsChanged()), this, SLOT(subscriberKDisplayLightsTimeoutChanged()));
       
   207     subscriberKProEngActiveProfile = new QValueSpaceSubscriber("/KCRUidProfileEngine/KProEngActiveProfile", this);
       
   208     connect(subscriberKProEngActiveProfile, SIGNAL(contentsChanged()), this, SLOT(subscriberKProEngActiveProfileChanged()));
       
   209 
       
   210     subscriberKSecurityUIsDismissDialog = new QValueSpaceSubscriber("/KPSUidSecurityUIs/KSecurityUIsDismissDialog", this);
       
   211     connect(subscriberKSecurityUIsDismissDialog, SIGNAL(contentsChanged()), this, SLOT(subscriberKSecurityUIsDismissDialogChanged()));
       
   212 
       
   213     // subscribe to environment changes
       
   214     subscriberKHWRMGripStatus = new QValueSpaceSubscriber("/KPSUidHWRM/KHWRMGripStatus");
       
   215     connect(subscriberKHWRMGripStatus, SIGNAL(contentsChanged()), this, SLOT(subscriberKHWRMGripStatusChanged()));
       
   216 
       
   217     subscriberKAknKeyguardStatus = new QValueSpaceSubscriber("/KPSUidAvkonDomain/KAknKeyguardStatus");
       
   218     connect(subscriberKAknKeyguardStatus, SIGNAL(contentsChanged()), this, SLOT(subscriberKAknKeyguardStatusChanged()));
       
   219 
       
   220     subscriberKCoreAppUIsAutolockStatus = new QValueSpaceSubscriber("/KPSUidCoreApplicationUIs/KCoreAppUIsAutolockStatus");
       
   221     connect(subscriberKCoreAppUIsAutolockStatus, SIGNAL(contentsChanged()), this, SLOT(subscriberKCoreAppUIsAutolockStatusChanged()));
       
   222 
       
   223     subscriberKCTsyCallState = new QValueSpaceSubscriber("/KPSUidCtsyCallInformation/KCTsyCallState");
       
   224     connect(subscriberKCTsyCallState, SIGNAL(contentsChanged()), this, SLOT(subscriberKCTsyCallStateChanged()));
       
   225 
       
   226     // inactivity
       
   227     connect(serviceKeyguard, SIGNAL(active()), this, SLOT(activeKeyguard()));
       
   228     connect(serviceKeyguard, SIGNAL(notActive()), this, SLOT(notActiveKeyguard()));
       
   229     connect(serviceDevicelock, SIGNAL(active()), this, SLOT(activeDevicelock()));
       
   230     connect(serviceDevicelock, SIGNAL(notActive()), this, SLOT(notActiveDevicelock()));
       
   231 
       
   232     RWindowGroup& groupWin = CEikonEnv::Static()->RootWin();
       
   233     RDEBUG("got groupWin", 1);
       
   234     // if I want to release, I should do:   mKeyCaptureHandle = env->RootWin().CaptureKey(EKeyBackspace, 0, 0);
       
   235     mEKeyDeviceFCaptureHandle = groupWin.CaptureKey(EKeyDeviceF, 0, 0);
       
   236     RDEBUG("mEKeyDeviceFCaptureHandle", mEKeyDeviceFCaptureHandle);
       
   237     mEKeyBellCaptureHandle = groupWin.CaptureKey(EKeyBell, 0, 0);
       
   238     RDEBUG("mEKeyBellCaptureHandle", mEKeyBellCaptureHandle);
       
   239     RDEBUG("got mKeyCaptureHandle", 1);
       
   240 
       
   241     iSecQueryUiCreated = -1;
       
   242     iDeviceDialogCreated = EDeviceDialogUninitialized;
       
   243     RDEBUG("new iDeviceDialogCreated", iDeviceDialogCreated);
       
   244     iDeviceDialog = NULL;
       
   245     // for now, always starts unlocked. This is correct because if locked, the unlock-query (from starter) is on top
       
   246     // TryChangeStatus(iLockStatus);
       
   247     TryChangeStatus( ELockNotActive);
       
   248     lower();
       
   249     hide();
       
   250 
       
   251     iDeviceDialog = new HbDeviceDialog(HbDeviceDialog::NoFlags, this);
       
   252     connect(iDeviceDialog, SIGNAL(dataReceived(QVariantMap)), SLOT(handleMessageFromScreensaver(QVariantMap)));
       
   253     connect(iDeviceDialog, SIGNAL(deviceDialogClosed()), SLOT(handleScreensaverClosed()));
       
   254 
       
   255     // screensaver standby mode timer
       
   256     mScreensaverModeTimer = new QTimer(this);
       
   257     mScreensaverModeTimer->setInterval(5 * 1000); // milliseconds, TODO: read from cenrep
       
   258     connect(mScreensaverModeTimer, SIGNAL(timeout()), SLOT(switchScreensaverToPowerSaveMode()));
       
   259     // screensaver AMOLED low power mode support
       
   260     mScreensaverPowerSave = CPowerSaveDisplayMode::NewL();
       
   261     mScreensaverPowerSavePixelBuffer = HBufC16::NewL(360 * 640);
       
   262     mScreensaverPowerSavePixelBuffer->Des().Fill(0);
       
   263     }
       
   264 
       
   265 Autolock::~Autolock()
       
   266     {
       
   267     RDEBUG("0", 0);
       
   268     delete mService;
       
   269     delete mScreensaverPowerSave;
       
   270     delete mScreensaverPowerSavePixelBuffer;
       
   271     RDEBUG("1", 1);
       
   272     }
       
   273 
       
   274 void Autolock::adjustInactivityTimers(int aReason)
       
   275     {
       
   276     RDEBUG("aReason", aReason);
       
   277     TInt keyguardTime = 0;
       
   278     TInt lockTime = 0;
       
   279     CRepository* repository = NULL;
       
   280     TInt cRresult = 0;
       
   281     Q_UNUSED(cRresult);
       
   282 
       
   283     QT_TRAP_THROWING(repository = CRepository::NewL(KCRUidSecuritySettings));
       
   284     cRresult = repository->Get(KSettingsAutomaticKeyguardTime, keyguardTime); // in seconds
       
   285     RDEBUG("KSettingsAutomaticKeyguardTime", KSettingsAutomaticKeyguardTime);
       
   286     RDEBUG("cRresult", cRresult);
       
   287     RDEBUG("keyguardTime", keyguardTime);
       
   288     if (keyguardTime > 0 && keyguardTime < 1000)
       
   289         {
       
   290         serviceKeyguard->setInactivityPeriod(keyguardTime);
       
   291         }
       
   292     else
       
   293         {
       
   294         serviceKeyguard->setInactivityPeriod(12 * 31 * 24 * 60 * 60);
       
   295         }
       
   296 
       
   297     cRresult = repository->Get(KSettingsAutoLockTime, lockTime); // in minutes, handled internally as seconds
       
   298     lockTime *= 60;
       
   299     RDEBUG("KSettingsAutoLockTime", KSettingsAutoLockTime);
       
   300     RDEBUG("cRresult", cRresult);
       
   301     RDEBUG("lockTime", lockTime);
       
   302     if (lockTime == 65535 * 60) // Special setting "lock at same time as keyguard" at CpDeviceLockPluginView::GetAutoLockIndex which uses this magic number
       
   303         lockTime = keyguardTime - 2; // lock 2 seconds before before, to avoid keyguard->devicelock sequence
       
   304     if (lockTime > 60 && lockTime < 24 * 60 * 60) // lock timer can't be bigger than 1 day
       
   305         {
       
   306         serviceDevicelock->setInactivityPeriod(lockTime);
       
   307         }
       
   308     else
       
   309         {
       
   310         serviceDevicelock->setInactivityPeriod(12 * 31 * 24 * 60 * 60); // 0x1ea6e00
       
   311         }
       
   312 
       
   313     delete repository;
       
   314     }
       
   315 void Autolock::quit()
       
   316     {
       
   317     RDEBUG("0", 0);
       
   318     qApp->quit();
       
   319     }
       
   320 
       
   321 int Autolock::AskValidSecCode(int aReason)
       
   322     {
       
   323     RDEBUG("aReason", aReason);
       
   324     RMobilePhone iPhone; // NULL in emulator
       
   325 
       
   326 #ifdef __WINS__1
       
   327     return KErrNone;
       
   328 #endif
       
   329 
       
   330     TInt err(KErrGeneral);
       
   331     Q_UNUSED(err);
       
   332     TBool validCode(EFalse);
       
   333     TInt thisTry(0);
       
   334     RTelServer iTelServer;
       
   335 
       
   336     err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLights, ESecurityUIsLightsQueryOnRequest);
       
   337     RDEBUG("KSecurityUIsLights err", err);
       
   338 
       
   339     RMmCustomAPI iCustomPhone;
       
   340     while ((err = iTelServer.Connect()) != KErrNone && (thisTry++) <= KTriesToConnectServer)
       
   341         {
       
   342         User::After( KTimeBeforeRetryingServerConnection);
       
   343         }
       
   344     err = iTelServer.LoadPhoneModule(KMmTsyModuleName);
       
   345     RTelServer::TPhoneInfo PhoneInfo;
       
   346     RDEBUG("LoadPhoneModule err", err);
       
   347     err = iTelServer.SetExtendedErrorGranularity(RTelServer::EErrorExtended);
       
   348     RDEBUG("SetExtendedErrorGranularity err", err);
       
   349     err = iTelServer.GetPhoneInfo(KPhoneIndex, PhoneInfo);
       
   350     RDEBUG("GetPhoneInfo err", err);
       
   351     err = iPhone.Open(iTelServer, PhoneInfo.iName);
       
   352     RDEBUG("Open err", err);
       
   353     err = iCustomPhone.Open(iPhone);
       
   354     RDEBUG("Open2 err", err);
       
   355 
       
   356     RDEBUG("CSecurityHandler", 0);
       
   357     CSecurityHandler* handler = new (ELeave) CSecurityHandler(iPhone);
       
   358     if (aReason == ELockAppDisableDevicelock)
       
   359         {
       
   360         RDEBUG("calling AskSecCodeInAutoLockL", 0);
       
   361         iLockCodeQueryInDisplay = ETrue;
       
   362         QT_TRAP_THROWING(validCode = handler->AskSecCodeInAutoLockL()); // this returns true/false
       
   363         iLockCodeQueryInDisplay = EFalse;
       
   364         // TODO should this also do iPhone.SetLockSetting(status, lockType, lockChange); ???
       
   365         }
       
   366     else if (aReason == ELockAppEnableDevicelock)
       
   367         {
       
   368         // check whether code is really needed
       
   369         RMobilePhone::TMobilePhoneLock lockType = RMobilePhone::ELockPhoneDevice;
       
   370         RMobilePhone::TMobilePhoneLockInfoV1 lockInfo;
       
   371         RMobilePhone::TMobilePhoneLockInfoV1Pckg lockInfoPkg(lockInfo);
       
   372         RMobilePhone::TMobilePhoneLockSetting lockChange(RMobilePhone::ELockSetDisabled);
       
   373         TRequestStatus status = KRequestPending;
       
   374         TInt ret = KErrNone;
       
   375         RDEBUG("GetLockInfo", 0);
       
   376         iPhone.GetLockInfo(status, lockType, lockInfoPkg);
       
   377         RDEBUG("WaitForRequest", 0);
       
   378         User::WaitForRequest(status);
       
   379         ret = status.Int();
       
   380         RDEBUG("WaitForRequest ret", ret);
       
   381 #ifdef __WINS__
       
   382         if (ret == KErrTimedOut)
       
   383             {
       
   384             ret = KErrNone;
       
   385             lockInfo.iSetting = RMobilePhone::ELockSetDisabled; // ask password only if there's no timeout.
       
   386             }
       
   387 #endif
       
   388         if (ret == KErrNone)
       
   389             {
       
   390             RDEBUG("lockInfo.iSetting", lockInfo.iSetting);
       
   391             RDEBUG("RMobilePhone::ELockSetDisabled",
       
   392                     RMobilePhone::ELockSetDisabled);
       
   393             if (lockInfo.iSetting == RMobilePhone::ELockSetDisabled) // ask password only if there's no timeout
       
   394                 {
       
   395                 lockChange = RMobilePhone::ELockSetEnabled;
       
   396                 RDEBUG("SetLockSetting lockChange", lockChange);
       
   397 #define OLD_METHODx
       
   398 #ifdef OLD_METHOD
       
   399                 status = KRequestPending;
       
   400                 RDEBUG( "SetLockSetting", 0 );
       
   401                 iPhone.SetLockSetting(status, lockType, lockChange); // ask for PassPhraseRequiredL
       
   402                 RDEBUG( "WaitForRequestL", 0 );
       
   403                 User::WaitForRequest( status ); // TODO this waits 33 seconds in WINS and returns ffffffdf = KErrTimedOut
       
   404                 ret = status.Int();
       
   405                 RDEBUG( "WaitForRequestL ret", ret );
       
   406 #else
       
   407                 RDEBUG("! OLD_METHOD", 0);
       
   408                 CWait *iWait = NULL;
       
   409                 QT_TRAP_THROWING(iWait = CWait::NewL());
       
   410                 iWait->SetRequestType(EMobilePhoneSetLockSetting);
       
   411                 iPhone.SetLockSetting(iWait->iStatus, lockType, lockChange); // ask for PassPhraseRequiredL
       
   412                 RDEBUG("WaitForRequestL", 0);
       
   413                 QT_TRAP_THROWING(ret = iWait->WaitForRequestL());
       
   414                 RDEBUG("WaitForRequestL ret", ret);
       
   415                 if (iWait)
       
   416                     {
       
   417                     RDEBUG("IsActive", 0);
       
   418                     if (iWait->IsActive())
       
   419                         {
       
   420                         RDEBUG("CancelAsyncRequest", 0);
       
   421                         iPhone.CancelAsyncRequest(iWait->GetRequestType());
       
   422                         RDEBUG("cancelled", 0);
       
   423                         }
       
   424                     }
       
   425                 delete iWait;
       
   426 #endif
       
   427 
       
   428                 RDEBUG("WaitForRequestL ret", ret);
       
   429 #ifdef __WINS__
       
   430                 if (ret == KErrTimedOut)
       
   431                     ret = KErrNone;
       
   432 #endif
       
   433                 if (ret == KErrNone)
       
   434                     validCode = 1;
       
   435                 else
       
   436                     validCode = 0;
       
   437                 }
       
   438             else
       
   439                 {
       
   440                 RDEBUG("RMobilePhone::ELockSetEnabled", RMobilePhone::ELockSetEnabled);
       
   441                 RDEBUG("lockInfo.iSetting = RMobilePhone::ELockSetEnabled", RMobilePhone::ELockSetEnabled);
       
   442                 validCode = 0x20;
       
   443                 }
       
   444             }
       
   445         else
       
   446             {
       
   447             RDEBUG("Error: ret", ret);
       
   448             validCode = 0x21;
       
   449             }
       
   450 
       
   451         /* Alternative way to ask for password
       
   452          RMobilePhone::TMobilePhoneSecurityEvent iEvent;
       
   453          TInt result = KErrNone;
       
   454          iEvent = RMobilePhone::EPhonePasswordRequired;
       
   455          RDEBUG( "calling HandleEventL", 0 );
       
   456          handler->HandleEventL(iEvent, result); // this is supposed to wait
       
   457          validCode = false;
       
   458          if(result)
       
   459          validCode = true;
       
   460          RDEBUG( "result", result );
       
   461          */
       
   462         }
       
   463     RDEBUG("validCode", validCode);
       
   464     if (validCode > 0)
       
   465         return KErrNone;
       
   466 
       
   467     // no valid code -> switch off the lights
       
   468     err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLights, ESecurityUIsLightsLockOffRequest);
       
   469     RDEBUG("KSecurityUIsLights err", err);
       
   470     return KErrCancel;
       
   471     }
       
   472 
       
   473 void Autolock::handleAnswerDelivered()
       
   474     {
       
   475     RDEBUG("0", 0);
       
   476     // quit();
       
   477 
       
   478     }
       
   479 
       
   480 void Autolock::setLabelNumber(QString label, QString number)
       
   481     {
       
   482     RDEBUG("0", 0);
       
   483     }
       
   484 
       
   485 void Autolock::DebugRequest(int aReason)
       
   486     {
       
   487     switch (aReason)
       
   488         {
       
   489         case ELockAppEnableKeyguard:
       
   490             RDEBUG("ELockAppEnableKeyguard", aReason)
       
   491             ;
       
   492             break;
       
   493         case ELockAppDisableKeyguard:
       
   494             RDEBUG("ELockAppDisableKeyguard", aReason)
       
   495             ;
       
   496             break;
       
   497         case ELockAppEnableDevicelock:
       
   498             RDEBUG("ELockAppEnableDevicelock", aReason)
       
   499             ;
       
   500             break;
       
   501         case ELockAppDisableDevicelock:
       
   502             RDEBUG("ELockAppDisableDevicelock", aReason)
       
   503             ;
       
   504             break;
       
   505         case ELockAppOfferKeyguard:
       
   506             RDEBUG("ELockAppOfferKeyguard", aReason)
       
   507             ;
       
   508             break;
       
   509         case ELockAppOfferDevicelock:
       
   510             RDEBUG("ELockAppOfferDevicelock", aReason)
       
   511             ;
       
   512             break;
       
   513         case ELockAppShowKeysLockedNote:
       
   514             RDEBUG("ELockAppShowKeysLockedNote", aReason)
       
   515             ;
       
   516             break;
       
   517         default:
       
   518             RDEBUG("default", aReason)
       
   519             ;
       
   520             break;
       
   521         }
       
   522     }
       
   523 void Autolock::DebugStatus(int aReason)
       
   524     {
       
   525     switch (aReason)
       
   526         {
       
   527         case ELockNotActive:
       
   528             RDEBUG("ELockNotActive", aReason)
       
   529             ;
       
   530             break;
       
   531         case EKeyguardActive:
       
   532             RDEBUG("EKeyguardActive", aReason)
       
   533             ;
       
   534             break;
       
   535         case EDevicelockActive:
       
   536             RDEBUG("EDevicelockActive", aReason)
       
   537             ;
       
   538             break;
       
   539         default:
       
   540             RDEBUG("default", aReason)
       
   541             ;
       
   542             break;
       
   543         }
       
   544     }
       
   545 void Autolock::DebugError(int aReason)
       
   546     {
       
   547     switch (aReason)
       
   548         {
       
   549         case KErrNone:
       
   550             RDEBUG("KErrNone", aReason)
       
   551             ;
       
   552             break;
       
   553         case KErrPermissionDenied: // caller doesn't have enough capabilities
       
   554             RDEBUG("KErrPermissionDenied", aReason)
       
   555             ;
       
   556             break;
       
   557         case KErrAlreadyExists: // this particular lock is already enabled
       
   558             RDEBUG("KErrAlreadyExists", aReason)
       
   559             ;
       
   560             break;
       
   561         case KErrInUse: // the dialog is already shown
       
   562             RDEBUG("KErrInUse", aReason)
       
   563             ;
       
   564             break;
       
   565         default:
       
   566             RDEBUG("default", aReason)
       
   567             ;
       
   568             break;
       
   569         }
       
   570     }
       
   571 
       
   572 int Autolock::CheckIfLegal(int aReason)
       
   573     {
       
   574     RDEBUG("aReason", aReason);
       
   575     // check whether a dialog is already displayed. This is to prevent timeout-lock and timeout-keyguard activated on top of a PIN query, in particular at boot-up (TODO check for Starter)
       
   576     TInt secUiOriginatedQuery(ESecurityUIsSecUIOriginatedUninitialized);
       
   577     TInt err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
       
   578     RDEBUG("err", err);
       
   579     RDEBUG("secUiOriginatedQuery", secUiOriginatedQuery);
       
   580     switch (aReason)
       
   581         {
       
   582         case ELockAppEnableKeyguard:
       
   583             {
       
   584             RDEBUG("ELockAppEnableKeyguard iLockStatus", iLockStatus);
       
   585             if (secUiOriginatedQuery != ESecurityUIsSecUIOriginatedUninitialized)
       
   586                 return KErrInUse; // PIN on top. Don't keyguard
       
   587             switch (iLockStatus)
       
   588                 {
       
   589                 case ELockNotActive:
       
   590                     if (!CKeyLockPolicyApi::KeyguardAllowed())
       
   591                         return KErrPermissionDenied;
       
   592                     else
       
   593                         return KErrNone;
       
   594                 case EKeyguardActive:
       
   595                     return KErrAlreadyExists;
       
   596                 case EDevicelockActive:
       
   597                     return KErrPermissionDenied;
       
   598                 }
       
   599             }
       
   600             break;
       
   601         case ELockAppDisableKeyguard:
       
   602             {
       
   603             RDEBUG("ELockAppDisableKeyguard iLockStatus", iLockStatus);
       
   604             // no matter whether PIN is displayed
       
   605             switch (iLockStatus)
       
   606                 {
       
   607                 case ELockNotActive:
       
   608                     return KErrAlreadyExists;
       
   609                 case EKeyguardActive:
       
   610                     return KErrNone;
       
   611                 case EDevicelockActive:
       
   612                     return KErrPermissionDenied;
       
   613                 }
       
   614             }
       
   615             break;
       
   616         case ELockAppEnableDevicelock:
       
   617             {
       
   618             RDEBUG("ELockAppEnableDevicelock iLockStatus", iLockStatus);
       
   619             if (secUiOriginatedQuery != ESecurityUIsSecUIOriginatedUninitialized && secUiOriginatedQuery != ESecurityUIsSystemLockOriginated)
       
   620                 return KErrInUse; // PIN on top. Don't devicelock
       
   621             switch (iLockStatus)
       
   622                 {
       
   623                 case ELockNotActive:
       
   624                     return KErrNone;
       
   625                 case EKeyguardActive:
       
   626                     return KErrNone;
       
   627                 case EDevicelockActive:
       
   628                     return KErrAlreadyExists;
       
   629                 }
       
   630             }
       
   631             break;
       
   632         case ELockAppDisableDevicelock:
       
   633             {
       
   634             RDEBUG("ELockAppDisableDevicelock iLockStatus", iLockStatus);
       
   635             if (iLockCodeQueryInDisplay)
       
   636                 {
       
   637                 // PIN on top and trying to display unlock-code. This is valid
       
   638                 return KErrAlreadyExists;
       
   639                 }
       
   640             switch (iLockStatus)
       
   641                 {
       
   642                 case ELockNotActive:
       
   643                     return KErrAlreadyExists;
       
   644                 case EKeyguardActive:
       
   645                     return KErrPermissionDenied;
       
   646                 case EDevicelockActive:
       
   647                     return KErrNone;
       
   648                 }
       
   649             }
       
   650             break;
       
   651         case ELockAppOfferKeyguard:
       
   652             {
       
   653             RDEBUG("ELockAppOfferKeyguard iLockStatus", iLockStatus);
       
   654             if (secUiOriginatedQuery != ESecurityUIsSecUIOriginatedUninitialized && secUiOriginatedQuery != ESecurityUIsSystemLockOriginated)
       
   655                 return KErrInUse; // PIN on top. Don't offer
       
   656             switch (iLockStatus)
       
   657                 {
       
   658                 case ELockNotActive:
       
   659                     return KErrNone;
       
   660                 case EKeyguardActive:
       
   661                     return KErrPermissionDenied;
       
   662                 case EDevicelockActive:
       
   663                     return KErrPermissionDenied;
       
   664                 }
       
   665             }
       
   666             break;
       
   667         case ELockAppOfferDevicelock:
       
   668             {
       
   669             RDEBUG("ELockAppOfferDevicelock iLockStatus", iLockStatus);
       
   670             if (secUiOriginatedQuery != ESecurityUIsSecUIOriginatedUninitialized && secUiOriginatedQuery != ESecurityUIsSystemLockOriginated)
       
   671                 return KErrInUse; // PIN on top. Don't offer
       
   672             switch (iLockStatus)
       
   673                 {
       
   674                 case ELockNotActive:
       
   675                     return KErrNone;
       
   676                 case EKeyguardActive:
       
   677                     return KErrNone;
       
   678                 case EDevicelockActive:
       
   679                     return KErrAlreadyExists;
       
   680                 }
       
   681             }
       
   682             break;
       
   683         case ELockAppShowKeysLockedNote:
       
   684             {
       
   685             RDEBUG("ELockAppShowKeysLockedNote iLockStatus", iLockStatus);
       
   686             if (secUiOriginatedQuery != ESecurityUIsSecUIOriginatedUninitialized && secUiOriginatedQuery != ESecurityUIsSystemLockOriginated)
       
   687                 return KErrInUse; // PIN on top. Don't display
       
   688             switch (iLockStatus)
       
   689                 {
       
   690                 case ELockNotActive:
       
   691                     return KErrPermissionDenied;
       
   692                 case EKeyguardActive:
       
   693                     return KErrNone;
       
   694                 case EDevicelockActive: // TODO confirm this. CMMKeyBearer::ReceivedKeyEvent expects KErrNone if keypad is locked
       
   695                     return KErrPermissionDenied;
       
   696                 }
       
   697             }
       
   698             break;
       
   699         default:
       
   700             {
       
   701             RDEBUG("default iLockStatus", iLockStatus);
       
   702             return KErrPermissionDenied;
       
   703             }
       
   704             // break;
       
   705         } // switch
       
   706     return KErrPermissionDenied;
       
   707     }
       
   708 
       
   709 int Autolock::publishStatus(int aReason)
       
   710     {
       
   711     RDEBUG("aReason", aReason);
       
   712     Q_UNUSED(aReason);
       
   713     TInt err = KErrNone;
       
   714     Q_UNUSED(err);
       
   715     // can't use include file because it's private file. However it gives permissions
       
   716     const TUid KCRUidCoreApplicationUIsSysAp =
       
   717         {
       
   718         0x101F8765
       
   719         };
       
   720     const TUint32 KSysApKeyguardActive = 0x00000001;
       
   721     CRepository* repositoryDevicelock = NULL;
       
   722     CRepository* repositoryKeyguard = NULL;
       
   723     QT_TRAP_THROWING(repositoryDevicelock = CRepository::NewL(KCRUidSecuritySettings));
       
   724     QT_TRAP_THROWING(repositoryKeyguard = CRepository::NewL(KCRUidCoreApplicationUIsSysAp));
       
   725     TInt cRresult = KErrNone;
       
   726     Q_UNUSED(cRresult);
       
   727     if (1 == 1) // this is a quick way to disable this functionality, for testing
       
   728         {
       
   729         RDEBUG("publishing", aReason);
       
   730         if (aReason == ELockNotActive)
       
   731             {
       
   732             err = RProperty::Set(KPSUidAvkonDomain, KAknKeyguardStatus, EKeyguardNotActive);
       
   733             RDEBUG("err", err);
       
   734             err = RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOff);
       
   735             RDEBUG("err", err);
       
   736             err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLights, ESecurityUIsLightsLockOnRequest); // lights are required
       
   737             RDEBUG("KSecurityUIsLights err", err);
       
   738 
       
   739             // cRresult = repositoryDevicelock->Set(KSettingsAutolockStatus, 0);    // the settings remains. Only ISA changes, as well as the P&S
       
   740             cRresult = repositoryKeyguard->Set(KSysApKeyguardActive, 0);
       
   741             RDEBUG("cRresult", cRresult);
       
   742             }
       
   743         if (1 == 1) // this is a quick way to disable this functionality, for testing
       
   744             {
       
   745             if (aReason == EKeyguardActive)
       
   746                 {
       
   747                 err = RProperty::Set(KPSUidAvkonDomain, KAknKeyguardStatus, EKeyguardLocked);
       
   748                 RDEBUG("KAknKeyguardStatus err", err);
       
   749                 err = RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EAutolockOff);
       
   750                 RDEBUG("KCoreAppUIsAutolockStatus err", err);
       
   751                 err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLights, ESecurityUIsLightsLockOffRequest); // same for keyguard and devicelock
       
   752                 RDEBUG("KSecurityUIsLights err", err);
       
   753                 // cRresult = repositoryDevicelock->Set(KSettingsAutolockStatus, 0);
       
   754                 cRresult = repositoryKeyguard->Set(KSysApKeyguardActive, 1);
       
   755                 RDEBUG("cRresult", cRresult);
       
   756                 }
       
   757             else if (aReason >= EDevicelockActive)
       
   758                 {
       
   759                 err = RProperty::Set(KPSUidAvkonDomain, KAknKeyguardStatus, EKeyguardAutolockEmulation); // Other candidates might be: EKeyguardLocked and EKeyguardNotActive
       
   760                 RDEBUG("KAknKeyguardStatus err", err);
       
   761                 err = RProperty::Set(KPSUidCoreApplicationUIs, KCoreAppUIsAutolockStatus, EManualLocked);
       
   762                 RDEBUG("KCoreAppUIsAutolockStatus err", err);
       
   763                 err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLights, ESecurityUIsLightsLockOffRequest);
       
   764                 RDEBUG(" KSecurityUIsLights err", err);
       
   765                 // cRresult = repositoryDevicelock->Set(KSettingsAutolockStatus, 1);
       
   766                 cRresult = repositoryKeyguard->Set(KSysApKeyguardActive, 0); // keyguard disabled, so that user can type and DeviceF can be captured
       
   767                 RDEBUG("cRresult", cRresult);
       
   768                 }
       
   769             }
       
   770         }
       
   771     delete repositoryDevicelock;
       
   772     delete repositoryKeyguard;
       
   773     // this is the real point where everything is done.
       
   774     iLockStatusPrev = iLockStatus;
       
   775     iLockStatus = aReason;
       
   776     RDEBUG("setting iLockStatus", iLockStatus);
       
   777     return KErrNone;
       
   778     }
       
   779 /********************/
       
   780 int Autolock::showNoteIfRequested(int aReason)
       
   781     {
       
   782     RDEBUG("aReason", aReason);
       
   783     // The notes are displayed. This is useful only for the API withNote, and ELockAppShowKeysLockedNote
       
   784     // However, it has some inconvenients:
       
   785     // - the screensaver already displays/hides
       
   786     // - the notes are shown behing the icon because they have lower priorities
       
   787     // - they are annoying
       
   788     // TODO translate
       
   789     if (aReason == ELockNotActive)
       
   790         {
       
   791         if (iShowKeyguardNote == 1)
       
   792             {
       
   793             HbDeviceMessageBox::information("Keyguard deactivated");
       
   794             }
       
   795         }
       
   796     else if (aReason == EKeyguardActive)
       
   797         {
       
   798         if (iShowKeyguardNote == 1)
       
   799             {
       
   800             HbDeviceMessageBox::information("Keyguard activated");
       
   801             // this already waits a bit because the lock-icon takes some time to display. So the note is visible before the lock-icon.
       
   802             }
       
   803         }
       
   804     else if (aReason >= EDevicelockActive) // this doesn't happen, but we are prepared nevertheless
       
   805         {
       
   806         if (iShowKeyguardNote == 1)
       
   807             {
       
   808             HbDeviceMessageBox::information("Devicelock activated");
       
   809             }
       
   810         }
       
   811     return KErrNone;
       
   812     }
       
   813 /***********************/
       
   814 int Autolock::TryChangeStatus(int aReason)
       
   815     {
       
   816     RDEBUG("aReason", aReason);
       
   817     int ret = aReason;
       
   818     int errorInProcess = KErrNone;
       
   819     DebugRequest(ret);
       
   820 
       
   821     // this will cancel any previous dialog, i.e. PIN query, or any previous code-request.
       
   822     // not sure about the screensaver, but nevertheless will be cancelled when the status is changed.
       
   823     TInt err = KErrNone;
       
   824     Q_UNUSED(err);
       
   825     RDEBUG("Not setting KSecurityUIsDismissDialog ESecurityUIsDismissDialogOn", ESecurityUIsDismissDialogOn);
       
   826     //// err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsDismissDialog, ESecurityUIsDismissDialogOn);
       
   827     RDEBUG("err", err);
       
   828     switch (ret)
       
   829         {
       
   830         case ELockAppEnableKeyguard: // 1
       
   831             {
       
   832             errorInProcess = CheckIfLegal(ret);
       
   833             DebugError(errorInProcess);
       
   834             if (errorInProcess == KErrNone)
       
   835                 {
       
   836                 showNoteIfRequested( EKeyguardActive);
       
   837                 setLabelIcon(EKeyguardActive);
       
   838                 updateIndicator(EKeyguardActive);
       
   839                 publishStatus(EKeyguardActive);
       
   840                 setLockDialog(aReason, 1);
       
   841                 }
       
   842             }
       
   843             break;
       
   844         case ELockAppDisableKeyguard: // 2
       
   845             {
       
   846             errorInProcess = CheckIfLegal(ret);
       
   847             DebugError(errorInProcess);
       
   848             if (errorInProcess == KErrNone)
       
   849                 {
       
   850                 showNoteIfRequested( ELockNotActive);
       
   851                 setLabelIcon(ELockNotActive);
       
   852                 updateIndicator(ELockNotActive);
       
   853                 publishStatus(ELockNotActive);
       
   854                 setLockDialog(aReason, 0);
       
   855                 }
       
   856             }
       
   857             break;
       
   858         case ELockAppEnableDevicelock: // 3
       
   859             {
       
   860             errorInProcess = CheckIfLegal(ret);
       
   861             DebugError(errorInProcess);
       
   862             if (errorInProcess == KErrNone)
       
   863                 {
       
   864                 if (!callerHasECapabilityWriteDeviceData) // check permissions for calling process, because doesn't AskValidSecCode
       
   865                     errorInProcess = KErrPermissionDenied;
       
   866                 DebugError(errorInProcess);
       
   867                 }
       
   868             if (errorInProcess == KErrNone)
       
   869                 {
       
   870                 updateIndicator( EDevicelockActive);
       
   871                 publishStatus(EDevicelockActive);
       
   872                 setLabelIcon(EDevicelockActive);
       
   873                 setLockDialog(aReason, 1);
       
   874                 }
       
   875             // aParam1 is aReason : EDevicelockManual, EDevicelockRemote
       
   876             // this never shows a note
       
   877             }
       
   878             break;
       
   879         case ELockAppDisableDevicelock: // 4
       
   880             {
       
   881             errorInProcess = CheckIfLegal(ret);
       
   882             DebugError(errorInProcess);
       
   883             if (errorInProcess == KErrNone)
       
   884                 {
       
   885                 if (!callerHasECapabilityWriteDeviceData) // check permissions for calling process, because doesn't AskValidSecCode
       
   886                     errorInProcess = KErrPermissionDenied;
       
   887                 DebugError(errorInProcess);
       
   888                 }
       
   889             if (errorInProcess == KErrNone)
       
   890                 {
       
   891                 setLockDialog(aReason, 0); // hide temporarilly because HbDeviceMessageBox doesn't get in top of the Lock-icon. Thus, dismiss it.
       
   892                 // do I need to enable touch? it seems to work without it
       
   893                 // in any case, lights are needed
       
   894                 err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLights, ESecurityUIsLightsQueryOnRequest);
       
   895                 RDEBUG("calling HbDeviceMessageBox::question", 0);
       
   896                 bool value = true;
       
   897                 // not sure whether this question is really needed. The UI doesn't say anything, so I remove it for now.
       
   898                 // HbDeviceMessageBox::question("Disable Lock?");   // this doesn't block other events, so after return everything might be messed up.
       
   899                 RDEBUG("value", value);
       
   900                 if (!value)
       
   901                     errorInProcess = KErrCancel;
       
   902                 }
       
   903             if (errorInProcess == KErrNone)
       
   904                 {
       
   905                 setLockDialog(aReason, 0); // hide temporarilly because AskValidSecCode doesn't get in top of the Lock-icon. Thus, dismiss it.
       
   906                 RDEBUG("calling AskValidSecCode", 0);
       
   907                 errorInProcess = AskValidSecCode(ELockAppDisableDevicelock);
       
   908                 RDEBUG("errorInProcess", errorInProcess);
       
   909                 }
       
   910             if (errorInProcess == KErrNone)
       
   911                 {
       
   912                 setLabelIcon( ELockNotActive);
       
   913                 updateIndicator(ELockNotActive);
       
   914                 setLockDialog(aReason, 0);
       
   915                 publishStatus(ELockNotActive);
       
   916                 }
       
   917             if (errorInProcess != KErrNone)
       
   918                 { // re-lock. For example, if password is wrong
       
   919                 if (iLockStatus >= EDevicelockActive) // this skips the case "unlocking although it wasn't locked"
       
   920                     setLockDialog(ELockAppEnableDevicelock, 1);
       
   921                 }
       
   922             // this never shows a note
       
   923             }
       
   924             break;
       
   925         case ELockAppOfferKeyguard: // 5
       
   926             {
       
   927             errorInProcess = CheckIfLegal(ret);
       
   928             DebugError(errorInProcess);
       
   929             if (errorInProcess == KErrNone)
       
   930                 {
       
   931                 // no need to dismiss screensaver, because it's not active
       
   932                 // what about any PIN-query, i.e. from settings ? In this case, the query will show after the PIN query is finished. somehow this is good because PIN is more important
       
   933                 bool value = HbDeviceMessageBox::question("Enable Keyguard?"); // this doesn't block other events, so after return everything might be messed up.
       
   934                 // what about a nice icon?
       
   935                 RDEBUG("value", value);
       
   936                 if (!value)
       
   937                     errorInProcess = KErrCancel;
       
   938                 }
       
   939             if (errorInProcess == KErrNone)
       
   940                 {
       
   941                 errorInProcess = TryChangeStatus(ELockAppEnableKeyguard);
       
   942                 }
       
   943             // this never shows a note
       
   944             }
       
   945             break;
       
   946         case ELockAppOfferDevicelock: // 6
       
   947             {
       
   948             errorInProcess = CheckIfLegal(ret);
       
   949             DebugError(errorInProcess);
       
   950             if (errorInProcess == KErrNone)
       
   951                 {
       
   952                 setLockDialog(aReason, 0); // hide temporarilly because AskValidSecCode doesn't get in top of the Lock-icon. Thus, dismiss it.
       
   953                 errorInProcess = AskValidSecCode(ELockAppEnableDevicelock);
       
   954                 }
       
   955             if (errorInProcess == KErrNone)
       
   956                 {
       
   957                 RDEBUG("ELockAppOfferDevicelock calling ELockAppEnableDevicelock", ELockAppEnableDevicelock);
       
   958                 errorInProcess = TryChangeStatus(ELockAppEnableDevicelock);
       
   959                 }
       
   960             // this never shows a note. Perhaps ELockAppEnableDevicelock does.
       
   961             }
       
   962             break;
       
   963         case ELockAppShowKeysLockedNote: // 7
       
   964             {
       
   965             errorInProcess = CheckIfLegal(ret); // it will not be legal if the keyguard is not enabled and the devicelock is not enabled.
       
   966             DebugError(errorInProcess);
       
   967             if (errorInProcess == KErrNone)
       
   968                 {
       
   969                 iShowKeyguardNote = 1; // this is not sent as parameter, so we need to fake it: ON
       
   970                 showNoteIfRequested( EKeyguardActive);
       
   971                 }
       
   972             }
       
   973             break;
       
   974         default:
       
   975             {
       
   976             RDEBUG("default", ret);
       
   977             errorInProcess = KErrNotSupported;
       
   978             }
       
   979             break;
       
   980 
       
   981         }
       
   982     return errorInProcess;
       
   983     }
       
   984 /**************************/
       
   985 int Autolock::setLockDialog(int aReason, int status)
       
   986     {
       
   987     RDEBUG("aReason", aReason);
       
   988     RDEBUG("status", status);
       
   989     RDEBUG("iDeviceDialogCreated", iDeviceDialogCreated);
       
   990     TInt secUiOriginatedQuery(ESecurityUIsSecUIOriginatedUninitialized);
       
   991     TInt err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, secUiOriginatedQuery);
       
   992     RDEBUG("err", err);
       
   993     RDEBUG("secUiOriginatedQuery", secUiOriginatedQuery);
       
   994 
       
   995     RWindowGroup& groupWin = CEikonEnv::Static()->RootWin();
       
   996 
       
   997     if (status == 0) // hide
       
   998         {
       
   999         // aReason is not important here, but let's check nevertheless
       
  1000         RDEBUG("ReleaseContext", R_AVKON_DEFAULT_SKEY_LIST);
       
  1001         static_cast<CAknAppUi*>(CEikonEnv::Static()->EikAppUi())->KeySounds()->ReleaseContext();
       
  1002         RDEBUG("PopContext", 0x90);
       
  1003         static_cast<CAknAppUi*>(CEikonEnv::Static()->EikAppUi())->KeySounds()->PopContext();
       
  1004         RDEBUG("ReleaseContext done", 0x92);
       
  1005 
       
  1006         if (aReason != ELockAppDisableKeyguard && aReason != ELockAppDisableDevicelock)
       
  1007             {
       
  1008             RDEBUG("!!!!****!!!!! error. status=0 but aReason", aReason);
       
  1009             }
       
  1010         // secUiOriginatedQuery should be ESecurityUIsSystemLockOriginated . If not, this is not correctly setting it
       
  1011         if (iDeviceDialogCreated >= EDeviceDialogCreated)
       
  1012             {
       
  1013             iDeviceDialogCreated = EDeviceDialogDestroyed;
       
  1014             RDEBUG("new iDeviceDialogCreated", iDeviceDialogCreated);
       
  1015 
       
  1016             RDEBUG("calling switchScreensaverMode", ESnsrViewTypeDisabled);
       
  1017             switchScreensaverMode( ESnsrViewTypeDisabled);
       
  1018 
       
  1019             disconnect(iDeviceDialog, SIGNAL(dataReceived(QVariantMap)), this, SLOT(handleMessageFromScreensaver(QVariantMap)));
       
  1020             disconnect(iDeviceDialog, SIGNAL(deviceDialogClosed()), this, SLOT(handleScreensaverClosed()));
       
  1021             RDEBUG("signal disconnected", err);
       
  1022             // TODO this crashes for EDeviceDialogScreenSaver
       
  1023             err = iDeviceDialog->cancel();
       
  1024             RDEBUG("cancel (bool: 1= wellCancelled) err", err);
       
  1025             err = iDeviceDialog->error();
       
  1026             RDEBUG("err", err);
       
  1027             RDEBUG("calling iDeviceDialog->waitForClosed()", 0);
       
  1028             err = iDeviceDialog->waitForClosed();
       
  1029             RDEBUG("cancel (bool: 1= well waitForClosed) err", err);
       
  1030             err = iDeviceDialog->error();
       
  1031             RDEBUG("err", err);
       
  1032 
       
  1033             TInt err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSecUIOriginatedUninitialized);
       
  1034             RDEBUG("reset KSecurityUIsSecUIOriginatedQuery. err", err);
       
  1035             // Cancel power key and application key capturing
       
  1036             groupWin.CancelCaptureKey(mPowerKeyCaptureHandle);
       
  1037             groupWin.CancelCaptureKey(mApplicationKeyCaptureHandle);
       
  1038             groupWin.CancelCaptureLongKey(mApplicationLongKeyCaptureHandle);
       
  1039             RDEBUG("done CancelCaptureKey", 1);
       
  1040             if (mEKeyYesCaptureHandle)
       
  1041                 {
       
  1042                 RDEBUG("mEKeyYesCaptureHandle", mEKeyYesCaptureHandle);
       
  1043                 groupWin.CancelCaptureKey(mEKeyYesCaptureHandle);
       
  1044                 mEKeyYesCaptureHandle = NULL;
       
  1045                 }
       
  1046             if (mEKeyNoCaptureHandle)
       
  1047                 {
       
  1048                 RDEBUG("mEKeyNoCaptureHandle", mEKeyNoCaptureHandle);
       
  1049                 groupWin.CancelCaptureKey(mEKeyNoCaptureHandle);
       
  1050                 mEKeyNoCaptureHandle = NULL;
       
  1051                 }
       
  1052 
       
  1053             RDEBUG("deleting iDeviceDialog", 0);
       
  1054             delete iDeviceDialog;
       
  1055             RDEBUG("deleted iDeviceDialog", 1);
       
  1056             iDeviceDialog = NULL;
       
  1057             }
       
  1058         }
       
  1059     else if (status == 1) // show
       
  1060         {
       
  1061         RDEBUG("PushContextL", R_AVKON_DEFAULT_SKEY_LIST);
       
  1062         static_cast<CAknAppUi*>(CEikonEnv::Static()->EikAppUi())->KeySounds()->PushContextL(R_AVKON_SILENT_SKEY_LIST);
       
  1063         RDEBUG("BringToForeground", 0x90);
       
  1064         static_cast<CAknAppUi*>(CEikonEnv::Static()->EikAppUi())->KeySounds()->BringToForeground();
       
  1065         RDEBUG("LockContext", 0x91);
       
  1066         static_cast<CAknAppUi*>(CEikonEnv::Static()->EikAppUi())->KeySounds()->LockContext();
       
  1067         RDEBUG("PushContextL Done", 0x92);
       
  1068 
       
  1069         // secUiOriginatedQuery should be ESecurityUIsSecUIOriginatedUninitialized . If not, the validation is not correctly filtering it
       
  1070         QVariantMap params;
       
  1071         TBool err;
       
  1072 #define ESecUiTypeDeviceLock        0x00100000
       
  1073 #define ESecUiTypeKeyguard          0x00200000
       
  1074 
       
  1075         if (aReason == ELockAppEnableKeyguard)
       
  1076             params.insert("type", ESecUiTypeKeyguard);
       
  1077         else if (aReason == ELockAppEnableDevicelock)
       
  1078             params.insert("type", ESecUiTypeDeviceLock);
       
  1079         else
       
  1080             {
       
  1081             RDEBUG("error. status=1 but aReason", aReason);
       
  1082             }
       
  1083         // no need for title. Icon should be explicit enough
       
  1084         // params.insert("title", "Locked");
       
  1085         if (iDeviceDialogCreated < EDeviceDialogCreated)
       
  1086             {
       
  1087             if (iDeviceDialog != NULL)
       
  1088                 {
       
  1089                 RDEBUG("!!!!!!*********!!!!!!!! error: iDeviceDialog != NULL", 0);
       
  1090                 }
       
  1091             RDEBUG("creating iDeviceDialog", 0);
       
  1092             iDeviceDialog = new HbDeviceDialog(HbDeviceDialog::NoFlags, this);
       
  1093             // in theory this is needed only for screensaver, not for LockIcon. But it doesn't harm
       
  1094             connect(iDeviceDialog, SIGNAL(dataReceived(QVariantMap)), SLOT(handleMessageFromScreensaver(QVariantMap)));
       
  1095             connect(iDeviceDialog, SIGNAL(deviceDialogClosed()), SLOT(handleScreensaverClosed()));
       
  1096             iDeviceDialogCreated = EDeviceDialogCreated;
       
  1097             RDEBUG("new iDeviceDialogCreated", iDeviceDialogCreated);
       
  1098             }
       
  1099         else
       
  1100             {
       
  1101             RDEBUG("raising iDeviceDialog", 0);
       
  1102             // confirm that dialog is present
       
  1103             err = iDeviceDialog->error();
       
  1104             RDEBUG("err", err);
       
  1105             iDeviceDialogCreated = EDeviceDialogRaised;
       
  1106             RDEBUG("new iDeviceDialogCreated", iDeviceDialogCreated);
       
  1107             }
       
  1108         const QString KScreensaverDeviceDialog("com.nokia.screensaver.snsrdevicedialogplugin/1.0");
       
  1109         RDEBUG("pre show", aReason);
       
  1110         bool launchSuccesful = iDeviceDialog->show(KScreensaverDeviceDialog, params); // and continue processing
       
  1111         RDEBUG("post show. bool launchSuccesful", launchSuccesful);
       
  1112         err = iDeviceDialog->error();
       
  1113         RDEBUG("iDeviceDialog->error", err);
       
  1114         if (launchSuccesful) // TODO && !error ???
       
  1115             {
       
  1116             iDeviceDialogCreated = EDeviceDialogScreenSaver;
       
  1117             RDEBUG("new iDeviceDialogCreated", iDeviceDialogCreated);
       
  1118             // TODO this is needed if creating dialog for first time? switchScreensaverToActiveMode(); // this is needed in case the dialog was existing.
       
  1119             // Start standy mode timer. The initial state may already be the standby
       
  1120             // mode but setting screensaver again to standby doesn't hurt.
       
  1121             mScreensaverModeTimer->start();
       
  1122             }
       
  1123         else // some err. Usually 3 (not existing)
       
  1124             {
       
  1125             // screensaver has failed. Probably because it's not installed. Then, try the standard lock-icon
       
  1126             iDeviceDialogCreated = EDeviceDialogLockIcon;
       
  1127             RDEBUG("new iDeviceDialogCreated", iDeviceDialogCreated);
       
  1128             const QString KSecQueryUiDeviceDialog("com.nokia.secuinotificationdialog/1.0");
       
  1129             err = iDeviceDialog->show(KSecQueryUiDeviceDialog, params); // and continue processing
       
  1130             RDEBUG("post show. err", err);
       
  1131             }
       
  1132         err = iDeviceDialog->error();
       
  1133         RDEBUG("err", err);
       
  1134         // This won't be needed when screensaver is in place, as the dialogs will be different, and therefore both can be present
       
  1135         // Somehow this should be handled by Orbit, but unfortunatelly they don't allow the same dialog twice
       
  1136         err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsSecUIOriginatedQuery, ESecurityUIsSecUIOriginatedUninitialized); // this could also be ESecurityUIsSystemLockOriginated
       
  1137         RDEBUG("err", err);
       
  1138         // Capture power and application keys while screen saver is open. Also works for LockIcon
       
  1139         mPowerKeyCaptureHandle = groupWin.CaptureKey(EKeyDevice2, 0, 0);
       
  1140         mApplicationKeyCaptureHandle = groupWin.CaptureKey(EKeyApplication0, 0, 0);
       
  1141         mApplicationLongKeyCaptureHandle = groupWin.CaptureLongKey(EKeyApplication0, EKeyApplication0, 0, 0, 0, ELongCaptureShortEventImmediately | ELongCaptureRepeatEvents);
       
  1142         mEKeyYesCaptureHandle = groupWin.CaptureKey(EKeyYes, 0, 0);
       
  1143         mEKeyNoCaptureHandle = groupWin.CaptureKey(EKeyNo, 0, 0);
       
  1144         RDEBUG("keys captured", err);
       
  1145         }
       
  1146     else
       
  1147         {
       
  1148         RDEBUG("unknown status", status);
       
  1149         return KErrNotSupported;
       
  1150         }
       
  1151     return KErrNone;
       
  1152     }
       
  1153 
       
  1154 void Autolock::setLabelIcon(int aReason)
       
  1155     {
       
  1156     RDEBUG("aReason", aReason);
       
  1157 
       
  1158     if (aReason == ELockNotActive)
       
  1159         {
       
  1160         // setLockDialog(aReason, 0); // This is done already at TryChangeStatus
       
  1161         lower();
       
  1162         hide();
       
  1163         }
       
  1164     else if (aReason == EKeyguardActive)
       
  1165         {
       
  1166         // setLockDialog(aReason, 1); // This is done already at TryChangeStatus
       
  1167         // this shows the Autolock Application. not needed
       
  1168         }
       
  1169     else if (aReason == EDevicelockActive)
       
  1170         {
       
  1171         }
       
  1172     else
       
  1173         {
       
  1174         RDEBUG("error: aReason", aReason);
       
  1175         }
       
  1176     }
       
  1177 
       
  1178 int Autolock::updateIndicator(int aReason)
       
  1179     {
       
  1180     RDEBUG("aReason", aReason);
       
  1181     QList<QVariant> list;
       
  1182     list.insert(0, 1);
       
  1183     list.insert(1, "dummy");
       
  1184     list.insert(2, 2);
       
  1185 
       
  1186     HbIndicator indicator;
       
  1187     bool success;
       
  1188     if (aReason == ELockNotActive)
       
  1189         success = indicator.deactivate("com.nokia.hb.indicator.autolock.autolock_8/1.0"); // maybe it's already deactivated. Not a problem
       
  1190     else if (aReason == EKeyguardActive)
       
  1191         success = indicator.activate("com.nokia.hb.indicator.autolock.autolock_8/1.0");
       
  1192     else if (aReason == EDevicelockActive)
       
  1193         success = indicator.activate("com.nokia.hb.indicator.autolock.autolock_8/1.0"); // same. We have just 1 indicator
       
  1194     else
       
  1195         success = 0;
       
  1196     RDEBUG("success", success);
       
  1197     return success;
       
  1198     }
       
  1199 
       
  1200 void Autolock::activeKeyguard()
       
  1201     {
       
  1202     // activity while keyguarded. Nothing to do
       
  1203     RDEBUG("0", 0);
       
  1204     }
       
  1205 
       
  1206 void Autolock::notActiveKeyguard()
       
  1207     {
       
  1208     // inactivity. Keyguard should be activated
       
  1209     RDEBUG("0", 0);
       
  1210     int ret = KErrNone;
       
  1211     DebugStatus( iLockStatus);
       
  1212     if (iLockStatus == ELockNotActive) // not possible if it's keyguarded, or locked
       
  1213         {
       
  1214         TInt callState = EPSCTsyCallStateNone;
       
  1215         int err = RProperty::Get(KPSUidCtsyCallInformation, KCTsyCallState, callState);
       
  1216         RDEBUG("err", err);
       
  1217         RDEBUG("callState", callState);
       
  1218         // if there's an active call, don't auto-keyguard (manual is still possible)
       
  1219         if (callState <= EPSCTsyCallStateNone)
       
  1220             {
       
  1221             ret = TryChangeStatus(ELockAppEnableKeyguard);
       
  1222             RDEBUG("ret", ret);
       
  1223             }
       
  1224         else
       
  1225             {
       
  1226             RDEBUG("not ELockAppEnableKeyguard because callState", callState);
       
  1227             }
       
  1228         }
       
  1229     else
       
  1230         {
       
  1231         // restart screensaver. The scenario is: keyguard->screensaver->CriticalNote->lightsOn . Therefore we need lightsOff
       
  1232         // this is done when keyguard can't be enabled because it's already enabled
       
  1233         // Note that this happens only once, so it's fine to show the screensaver in full light.
       
  1234         if (ret == KErrAlreadyExists)
       
  1235             switchScreensaverMode( ESnsrViewTypeInitial);
       
  1236         }
       
  1237     RDEBUG("ret", ret);
       
  1238     }
       
  1239 /* Some activity detected while the deviceLock is enabled */
       
  1240 void Autolock::activeDevicelock()
       
  1241     {
       
  1242     // nothing to do
       
  1243     RDEBUG("0", 0);
       
  1244     }
       
  1245 
       
  1246 void Autolock::notActiveDevicelock()
       
  1247     {
       
  1248     // inactivity. Devicelock should be activated
       
  1249     RDEBUG("0", 0);
       
  1250     int ret = KErrNone;
       
  1251     Q_UNUSED(ret);
       
  1252     DebugStatus( iLockStatus);
       
  1253     if (iLockStatus == ELockNotActive || iLockStatus == EKeyguardActive) // not possible if it's locked
       
  1254         {
       
  1255         // this is independent of the call status
       
  1256         ret = TryChangeStatus(ELockAppEnableDevicelock);
       
  1257         }
       
  1258     RDEBUG("ret", ret);
       
  1259 
       
  1260     }
       
  1261 
       
  1262 void Autolock::switchScreensaverMode(int mode)
       
  1263     {
       
  1264     RDEBUG("mode", mode);
       
  1265     if (iDeviceDialog)
       
  1266         {
       
  1267         // maybe this can be used to tell the dialog to dismiss itself?
       
  1268         RDEBUG("got iDeviceDialog. iDeviceDialogCreated", iDeviceDialogCreated);
       
  1269         QVariantMap params;
       
  1270         // this is for LockIcon. Doesn't harm screensaver
       
  1271         // need to send again so that the existing dialog still knows what is its type
       
  1272         if (iLockStatus == EKeyguardActive)
       
  1273             params.insert("type", ESecUiTypeKeyguard);
       
  1274         else if (iLockStatus >= EDevicelockActive)
       
  1275             params.insert("type", ESecUiTypeDeviceLock);
       
  1276 
       
  1277         // this is for screensaver. Doesn't harm LockIcon
       
  1278         params.insert(KSnsrViewTypeKey, mode);
       
  1279         iDeviceDialog->update(params);
       
  1280 
       
  1281         if (mScreensaverModeTimer)
       
  1282             {
       
  1283             if (mode == ESnsrViewTypeStandby || mode == ESnsrViewTypeDisabled)
       
  1284                 {
       
  1285                 RDEBUG("stop mScreensaverModeTimer", 0);
       
  1286                 mScreensaverModeTimer->stop();
       
  1287                 }
       
  1288             else
       
  1289             		{
       
  1290                 RDEBUG("start mScreensaverModeTimer", 0);
       
  1291             		mScreensaverModeTimer->start();
       
  1292             		}
       
  1293             }
       
  1294         }
       
  1295     RDEBUG("1", 1);
       
  1296     }
       
  1297 
       
  1298 void Autolock::switchScreensaverToPowerSaveMode()
       
  1299     {
       
  1300     RDEBUG("0", 0);
       
  1301     switchScreensaverMode( ESnsrViewTypeStandby);
       
  1302     RDEBUG("1", 1);
       
  1303     }
       
  1304 
       
  1305 void Autolock::handleMessageFromScreensaver(const QVariantMap &data)
       
  1306     {
       
  1307     RDEBUG("0", 0);
       
  1308     RDEBUG("iLockStatus", iLockStatus);
       
  1309     QVariantMap::const_iterator it = data.find(KSnsrCmdUnlock);
       
  1310     if (it != data.end() && iLockStatus != ELockNotActive)
       
  1311         {
       
  1312         RDEBUG("calling handleLockSwitch", 0);
       
  1313         handleLockSwitch();
       
  1314         }
       
  1315 
       
  1316     it = data.find(KSnsrCmdSwitchLights);
       
  1317     if (it != data.end())
       
  1318         {
       
  1319         int lightStatus = it.value().toInt();
       
  1320         RDEBUG("switching screen lights . lightStatus", lightStatus);
       
  1321         int err = RProperty::Set(KPSUidCoreApplicationUIs, KLightsSSForcedLightsOn, lightStatus);
       
  1322         RDEBUG("err", err);
       
  1323         }
       
  1324 
       
  1325     it = data.find(KSnsrCmdSwitchLowPower);
       
  1326     if (it != data.end())
       
  1327         {
       
  1328         QVariantList lowPowerLimits = it.value().toList();
       
  1329         if (lowPowerLimits.count() == 2)
       
  1330             {
       
  1331             // switch on screen power save mode when start and end lines are given
       
  1332             int startRow = lowPowerLimits.at(0).toInt();
       
  1333             int endRow = lowPowerLimits.at(1).toInt();
       
  1334             // TODO: The pixel buffer passed to CPowerSaveDisplayMode is supposed to
       
  1335             // contain the pixels shown in the active area of the screen. Currently, we
       
  1336             // pass a buffer filled with 0s, and this works fine on the reference
       
  1337             // hardware. However, according to display driver people, this doesn't
       
  1338             // work if the display component of the device doesn't have internal memory
       
  1339             // which may be the case in some of our target devices.
       
  1340             TUint16 *ptr = const_cast<TUint16 *> (mScreensaverPowerSavePixelBuffer->Ptr());
       
  1341             RDEBUG("switching screen power save on, number of visible rows", endRow-startRow);
       
  1342             int err = mScreensaverPowerSave->Set(startRow, endRow, ptr);
       
  1343             RDEBUG("err", err);
       
  1344             }
       
  1345         else
       
  1346             {
       
  1347             // any other case is interpreted as an order to switch off the power save and
       
  1348             // return to the normal mode
       
  1349             RDEBUG("switching screen power save off 0", 0);
       
  1350             int err = mScreensaverPowerSave->Exit();
       
  1351             RDEBUG("err", err);
       
  1352             }
       
  1353         }
       
  1354     }
       
  1355 
       
  1356 void Autolock::handleScreensaverClosed()
       
  1357     {
       
  1358     RDEBUG("0", 0);
       
  1359     int err(0);
       
  1360     // Screensaver (usually) cannot send anymore any commands when
       
  1361     // it's being closed. Thus, we need to ensure here that screen has lights and
       
  1362     // full-power mode once screensaver is closed.
       
  1363     if (mScreensaverPowerSave)
       
  1364         {
       
  1365         RDEBUG("switching screen power save off", 0);
       
  1366         err = mScreensaverPowerSave->Exit();
       
  1367         RDEBUG("error=", err);
       
  1368         }
       
  1369     RDEBUG("switching screen lights on", 1);
       
  1370     err = RProperty::Set(KPSUidCoreApplicationUIs, KLightsSSForcedLightsOn, 30);
       
  1371     RDEBUG("err", err);
       
  1372     }
       
  1373 
       
  1374 // some key is pressed
       
  1375 // TODO perhaps need a way to stop switch-key while asking unlock-code?
       
  1376 // Not clear what to do here. dismiss query? 
       
  1377 bool Autolock::event(QEvent *ev)
       
  1378     {
       
  1379     if (ev)
       
  1380         {
       
  1381         int isSwitchKey = 0;
       
  1382         if (ev->type() == QEvent::KeyPress)
       
  1383             {
       
  1384             QKeyEvent *keyEvent = static_cast<QKeyEvent *> (ev);
       
  1385             RDEBUG("KeyPress", keyEvent->key());
       
  1386             RDEBUG("KeyPress nativeScanCode", keyEvent->nativeScanCode());
       
  1387             RDEBUG("EStdKeyDeviceF", EStdKeyDeviceF);
       
  1388             RDEBUG("EKeyDeviceF", EKeyDeviceF);
       
  1389             RDEBUG("keyEvent->isAutoRepeat()", keyEvent->isAutoRepeat());
       
  1390             // note that the key was EKeyApplication0 and EKeyDevice2
       
  1391             // yes=0xc4 app=0xb4 no=0xa6
       
  1392             if (keyEvent->nativeScanCode() == EStdKeyApplication0 || keyEvent->nativeScanCode() == EStdKeyDevice2 || keyEvent->nativeScanCode() == EStdKeyYes
       
  1393                     || keyEvent->nativeScanCode() == EStdKeyNo)
       
  1394                 {
       
  1395                 // switch to active screensaver if application key or power key pressed while screensaver active
       
  1396                 // This key can be repeated, so that the screensaver remains as long as key is pushed
       
  1397                 // TODO what happens when holding Power key ?
       
  1398                 switchScreensaverMode( ESnsrViewTypeActive);
       
  1399                 }
       
  1400             else if (!keyEvent->isAutoRepeat())
       
  1401                 {
       
  1402                 if (keyEvent->key() == EKeyInsert)
       
  1403                     {
       
  1404                     // on WINS, this is handled with the "Ins" key in the numeric keypad
       
  1405                     RDEBUG("EKeyInsert", EKeyInsert);
       
  1406                     // only reacts on release, not on press
       
  1407                     isSwitchKey = 1;
       
  1408                     }
       
  1409                 else if (keyEvent->key() == EKeyDeviceF)
       
  1410                     {
       
  1411                     // this never seem to happen. Nevertheless we are not doing anything
       
  1412                     RDEBUG("EKeyDeviceF", EKeyDeviceF);
       
  1413                     }
       
  1414                 else if (keyEvent->nativeScanCode() == EStdKeyDeviceF)
       
  1415                     {
       
  1416                     RDEBUG("got EStdKeyDeviceF", EStdKeyDeviceF);
       
  1417                     isSwitchKey = 1;
       
  1418                     }
       
  1419                 else if (keyEvent->nativeScanCode() == EKeyBell) // this might be sent by others, i.e. PCFW
       
  1420                     {
       
  1421                     RDEBUG("got EKeyBell", EKeyBell);
       
  1422                     isSwitchKey = 1;
       
  1423                     }
       
  1424                 else if (keyEvent->key() == 0x1ffffff)
       
  1425                     {
       
  1426                     RDEBUG("0x1ffffff", 0x1ffffff); // some unknown key is received. Nothing to do
       
  1427                     }
       
  1428                 }
       
  1429             }
       
  1430         else if (ev->type() == QEvent::KeyRelease)
       
  1431             {
       
  1432             QKeyEvent *keyEvent = static_cast<QKeyEvent *> (ev);
       
  1433             RDEBUG("KeyRelease", keyEvent->key());
       
  1434             RDEBUG("KeyRelease native", keyEvent->nativeScanCode());
       
  1435             if (keyEvent->nativeScanCode() == EStdKeyDeviceF && !keyEvent->isAutoRepeat())
       
  1436                 {
       
  1437                 RDEBUG("released EStdKeyDeviceF", 1);
       
  1438                 // isSwitchKey=1; this should happen is   pressed  was not processed (hint: if it is/was in background)
       
  1439                 }
       
  1440             }
       
  1441         RDEBUG("isSwitchKey", isSwitchKey);
       
  1442         if (isSwitchKey)
       
  1443             {
       
  1444             handleLockSwitch();
       
  1445             RDEBUG("0", 0);
       
  1446             } // isSwitchKey
       
  1447         } // ev
       
  1448     // Process if not done before. For example, redraw or quit
       
  1449     TBool widgetEventSuccesful = QWidget::event(ev);
       
  1450     RDEBUG("9", 9);
       
  1451     return widgetEventSuccesful;
       
  1452     }
       
  1453 
       
  1454 int Autolock::handleLockSwitch()
       
  1455     {
       
  1456     RDEBUG("0", 0);
       
  1457     int ret = KErrNone;
       
  1458    	RDEBUG("iProcessingEvent", iProcessingEvent);
       
  1459    	// iProcessingEvent is used to avoid concurrent processing, i.e. 2 side-switch presses; because it needs time to create (and dismiss) the dialog
       
  1460    	// However this disallows keyguard during unlock-quey.
       
  1461    	if(iProcessingEvent < 1)
       
  1462    		{
       
  1463 	    iProcessingEvent = 1;
       
  1464 	    Q_UNUSED(ret);
       
  1465 	    DebugStatus( iLockStatus);
       
  1466 	    if (iLockStatus == ELockNotActive)
       
  1467 	        {
       
  1468 	        iShowKeyguardNote = 0; // no note on enable keyguard
       
  1469 	        callerHasECapabilityWriteDeviceData = 1;
       
  1470 	        ret = TryChangeStatus(ELockAppEnableKeyguard); // this should not ask confirmation
       
  1471 	        }
       
  1472 	    else if (iLockStatus == EKeyguardActive)
       
  1473 	        {
       
  1474 	        iShowKeyguardNote = 0; // no note on disable keyguard
       
  1475 	        callerHasECapabilityWriteDeviceData = 1;
       
  1476 	        ret = TryChangeStatus(ELockAppDisableKeyguard);
       
  1477 	        }
       
  1478 	    else if (iLockStatus == EDevicelockActive)
       
  1479 	        {
       
  1480 	        callerHasECapabilityWriteDeviceData = 1;
       
  1481 	        ret = TryChangeStatus(ELockAppDisableDevicelock);
       
  1482 	        }
       
  1483 	    else
       
  1484 	        {
       
  1485 	        RDEBUG("unknown iLockStatus", iLockStatus);
       
  1486 	        }
       
  1487     	iProcessingEvent = 0;
       
  1488 	    }
       
  1489     RDEBUG("ret", ret);
       
  1490     return ret;
       
  1491     }
       
  1492 
       
  1493 bool Autolock::eventFilter(QObject *o, QEvent *ev)
       
  1494     {
       
  1495     // this never happens
       
  1496     RDEBUG("0", 0);
       
  1497     return QWidget::eventFilter(o, ev);
       
  1498     }
       
  1499 // some setting changed
       
  1500 void Autolock::subscriberKSettingsAutolockStatusChanged()
       
  1501     {
       
  1502     RDEBUG("0", 0);
       
  1503     QVariant v = subscriberKSettingsAutolockStatus->value("/KCRUidSecuritySettings/KSettingsAutolockStatus");
       
  1504     adjustInactivityTimers( KSettingsAutolockStatus);
       
  1505     }
       
  1506 void Autolock::subscriberKSettingsAutoLockTimeChanged()
       
  1507     {
       
  1508     RDEBUG("0", 0);
       
  1509     QVariant v = subscriberKSettingsAutoLockTime->value("/KCRUidSecuritySettings/KSettingsAutoLockTime");
       
  1510     adjustInactivityTimers( KSettingsAutoLockTime);
       
  1511     }
       
  1512 void Autolock::subscriberKSettingsAutomaticKeyguardTimeChanged()
       
  1513     {
       
  1514     RDEBUG("0", 0);
       
  1515     QVariant v = subscriberKSettingsAutomaticKeyguardTime->value("/KCRUidSecuritySettings/KSettingsAutomaticKeyguardTime");
       
  1516     adjustInactivityTimers( KSettingsAutoLockTime);
       
  1517     }
       
  1518 void Autolock::subscriberKDisplayLightsTimeoutChanged()
       
  1519     {
       
  1520     RDEBUG("0", 0);
       
  1521     QVariant v = subscriberKDisplayLightsTimeout->value("/KCRUidLightSettings/KDisplayLightsTimeout");
       
  1522     // nothing to do
       
  1523     }
       
  1524 void Autolock::subscriberKProEngActiveProfileChanged()
       
  1525     {
       
  1526     RDEBUG("0", 0);
       
  1527     QVariant v = subscriberKProEngActiveProfile->value("/KCRUidProfileEngine/KProEngActiveProfile");
       
  1528     // nothing to do
       
  1529     }
       
  1530 // some environment changed
       
  1531 void Autolock::subscriberKAknKeyguardStatusChanged()
       
  1532     {
       
  1533     RDEBUG("Error only Autolock should be able to change it", 0);
       
  1534     }
       
  1535 void Autolock::subscriberKCoreAppUIsAutolockStatusChanged()
       
  1536     {
       
  1537     RDEBUG("Error only Autolock should be able to change it", 0);
       
  1538     }
       
  1539 void Autolock::subscriberKHWRMGripStatusChanged()
       
  1540     {
       
  1541     TInt ret = KErrNone;
       
  1542     Q_UNUSED(ret);
       
  1543     RDEBUG("0", 0);
       
  1544     TInt aGripStatus;
       
  1545     TInt err = RProperty::Get(KPSUidHWRM, KHWRMGripStatus, aGripStatus);
       
  1546     RDEBUG("err", err);
       
  1547     RDEBUG("value", aGripStatus);
       
  1548     if (aGripStatus == EPSHWRMGripOpen)
       
  1549         {
       
  1550         if (iLockStatus == EKeyguardActive)
       
  1551             {
       
  1552             iShowKeyguardNote = 0; // no note on disable keyguard
       
  1553             callerHasECapabilityWriteDeviceData = 1;
       
  1554             ret = TryChangeStatus(ELockAppDisableKeyguard);
       
  1555             }
       
  1556         else if (iLockStatus == EDevicelockActive)
       
  1557             {
       
  1558             callerHasECapabilityWriteDeviceData = 1;
       
  1559             ret = TryChangeStatus(ELockAppDisableDevicelock);
       
  1560             }
       
  1561         }
       
  1562     else if (aGripStatus == EPSHWRMGripClosed)
       
  1563         {
       
  1564         if (iLockStatus == ELockNotActive)
       
  1565             {
       
  1566             iShowKeyguardNote = 0; // no note on enable keyguard
       
  1567             callerHasECapabilityWriteDeviceData = 1;
       
  1568             ret = TryChangeStatus(ELockAppEnableKeyguard);
       
  1569             }
       
  1570         }
       
  1571     RDEBUG("ret", ret);
       
  1572     }
       
  1573 /**************/
       
  1574 void Autolock::subscriberKCTsyCallStateChanged()
       
  1575     {
       
  1576     RDEBUG("0", 0);
       
  1577     TInt aCallStatus;
       
  1578     TInt err = RProperty::Get(KPSUidCtsyCallInformation, KCTsyCallState, aCallStatus);
       
  1579     RDEBUG("err", err);
       
  1580     RDEBUG("aCallStatus", aCallStatus);
       
  1581     RWindowGroup& groupWin = CEikonEnv::Static()->RootWin();
       
  1582     if (aCallStatus == EPSCTsyCallStateUninitialized || aCallStatus == EPSCTsyCallStateNone)
       
  1583         {
       
  1584         RDEBUG("call is inactive", aCallStatus);
       
  1585         RDEBUG("iLockStatus", iLockStatus);
       
  1586         if (iLockStatus == EKeyguardActive || iLockStatus == EDevicelockActive)
       
  1587             {
       
  1588             if (!mEKeyYesCaptureHandle)
       
  1589                 mEKeyYesCaptureHandle = groupWin.CaptureKey(EKeyYes, 0, 0);
       
  1590             if (!mEKeyNoCaptureHandle)
       
  1591                 mEKeyNoCaptureHandle = groupWin.CaptureKey(EKeyNo, 0, 0);
       
  1592             }
       
  1593         }
       
  1594     else
       
  1595         {
       
  1596         RDEBUG("call is active", aCallStatus);
       
  1597         // Telephone should be on top, but nevertheless we give End/Send to them
       
  1598         // This should be done only if locked, but it doesn't harm
       
  1599         if (mEKeyYesCaptureHandle)
       
  1600             {
       
  1601             RDEBUG("mEKeyYesCaptureHandle", mEKeyYesCaptureHandle);
       
  1602             groupWin.CancelCaptureKey(mEKeyYesCaptureHandle);
       
  1603             mEKeyYesCaptureHandle = NULL;
       
  1604             }
       
  1605         if (mEKeyNoCaptureHandle)
       
  1606             {
       
  1607             RDEBUG("mEKeyNoCaptureHandle", mEKeyNoCaptureHandle);
       
  1608             groupWin.CancelCaptureKey(mEKeyNoCaptureHandle);
       
  1609             mEKeyNoCaptureHandle = NULL;
       
  1610             }
       
  1611         }
       
  1612     RDEBUG("9", 9);
       
  1613     }
       
  1614 // SecUiNotificationDialog::subscriberKSecurityUIsDismissDialogChanged()
       
  1615 // A way for Autolock to dismiss any possible PIN dialog
       
  1616 // ----------------------------------------------------------------------------
       
  1617 //
       
  1618 void Autolock::subscriberKSecurityUIsDismissDialogChanged()
       
  1619     {
       
  1620     RDEBUG("0", 0);
       
  1621     TInt aDismissDialog = ESecurityUIsDismissDialogUninitialized;
       
  1622     TInt err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsDismissDialog, aDismissDialog);
       
  1623     RDEBUG("err", err);
       
  1624     RDEBUG("aDismissDialog", aDismissDialog);
       
  1625     }
       
  1626 // ----------AutolockService---------------
       
  1627 
       
  1628 AutolockService::AutolockService(Autolock* parent) :
       
  1629     XQServiceProvider(QLatin1String("com.nokia.services.Autolock.Autolock"), parent), mAutolock(parent), mAsyncReqId(-1), mAsyncAnswer(false)
       
  1630     {
       
  1631     RDEBUG("0", 0);
       
  1632     publishAll();
       
  1633     connect(this, SIGNAL(returnValueDelivered()), parent, SLOT(handleAnswerDelivered()));
       
  1634     }
       
  1635 
       
  1636 AutolockService::~AutolockService()
       
  1637     {
       
  1638     RDEBUG("0", 0);
       
  1639     }
       
  1640 
       
  1641 void AutolockService::complete(QString number)
       
  1642     {
       
  1643     RDEBUG("0", 0);
       
  1644     if (mAsyncReqId == -1)
       
  1645         return;
       
  1646     completeRequest(mAsyncReqId, number.toInt());
       
  1647     }
       
  1648 
       
  1649 // got API request from lockaccessextension
       
  1650 int AutolockService::service(const QString& number, const QString& aParam1, const QString& aParam2)
       
  1651     {
       
  1652     RDEBUG("0", 0);
       
  1653     TInt err = KErrNone;
       
  1654     RDEBUG("number", number.toInt());
       
  1655     RDEBUG("aParam1", aParam1.toInt());
       
  1656     RDEBUG("aParam2", aParam2.toInt());
       
  1657     mAsyncAnswer = false;
       
  1658     XQRequestInfo info = requestInfo();
       
  1659     QSet<int> caps = info.clientCapabilities();
       
  1660 
       
  1661     mAutolock->callerHasECapabilityWriteDeviceData = 0;
       
  1662     if (caps.contains(ECapabilityWriteDeviceData))
       
  1663         {
       
  1664         RDEBUG("callerHasECapabilityWriteDeviceData",
       
  1665                 ECapabilityWriteDeviceData);
       
  1666         mAutolock->callerHasECapabilityWriteDeviceData = 1;
       
  1667         }
       
  1668 
       
  1669     QString label = "Autolock::service:\n";
       
  1670     label += QString("number=%1\n").arg(number);
       
  1671 
       
  1672     mNumber = number;
       
  1673     mAutolock->setLabelNumber(label, number);
       
  1674     int ret = 0;
       
  1675     ret = number.toInt();
       
  1676 
       
  1677     mAutolock->mParam1 = aParam1.toInt();
       
  1678     mAutolock->iShowKeyguardNote = aParam1.toInt();
       
  1679     mAutolock->mParam2 = aParam2.toInt();
       
  1680     TTime myTime;
       
  1681     myTime.HomeTime();
       
  1682     TInt myTimeHigh = 0;
       
  1683     TInt myTimeLow = 0;
       
  1684     err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsLockInitiatorTimeHigh, myTimeHigh);
       
  1685     RDEBUG("err", err);
       
  1686     RDEBUG("myTimeHigh", myTimeHigh);
       
  1687     err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsLockInitiatorTimeLow, myTimeLow);
       
  1688     RDEBUG("err", err);
       
  1689     RDEBUG("myTimeLow", myTimeLow);
       
  1690 
       
  1691     myTimeHigh = I64HIGH( myTime.Int64() );
       
  1692     myTimeLow = I64LOW( myTime.Int64() );
       
  1693     RDEBUG("myTimeHigh", myTimeHigh);
       
  1694     RDEBUG("myTimeLow", myTimeLow);
       
  1695     err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLockInitiatorTimeHigh, myTimeHigh);
       
  1696     err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLockInitiatorTimeLow, myTimeLow);
       
  1697 
       
  1698     ret = mAutolock->TryChangeStatus(ret);
       
  1699     RDEBUG("ret", ret);
       
  1700 
       
  1701     TInt myInitiatorUID = 0;
       
  1702     err = RProperty::Get(KPSUidSecurityUIs, KSecurityUIsLockInitiatorUID, myInitiatorUID);
       
  1703     RDEBUG("ret", ret);
       
  1704     RDEBUG("myInitiatorUID", myInitiatorUID);
       
  1705     myInitiatorUID = info.clientSecureId();
       
  1706     err = RProperty::Set(KPSUidSecurityUIs, KSecurityUIsLockInitiatorUID, myInitiatorUID);
       
  1707     RDEBUG("ret", ret);
       
  1708     RDEBUG("myInitiatorUID", myInitiatorUID);
       
  1709 
       
  1710     return ret;
       
  1711     }
       
  1712 
       
  1713 void AutolockService::handleClientDisconnect()
       
  1714     {
       
  1715     RDEBUG("0", 0);
       
  1716     // Just quit service application if client ends
       
  1717     mAsyncAnswer = false;
       
  1718     RDEBUG("0", 0);
       
  1719     // mAutolock->quit();
       
  1720     }
       
  1721 
       
  1722 /****************/
       
  1723 CWait* CWait::NewL()
       
  1724     {
       
  1725     CWait* self = new (ELeave) CWait();
       
  1726     CleanupStack::PushL(self);
       
  1727     self->ConstructL();
       
  1728     CleanupStack::Pop();
       
  1729     return self;
       
  1730     }
       
  1731 void CWait::ConstructL()
       
  1732     {
       
  1733     CActiveScheduler::Add(this);
       
  1734     }
       
  1735 CWait::CWait() :
       
  1736     CActive(0)
       
  1737     {
       
  1738     }
       
  1739 CWait::~CWait()
       
  1740     {
       
  1741     Cancel();
       
  1742     }
       
  1743 TInt CWait::WaitForRequestL()
       
  1744     {
       
  1745     SetActive();
       
  1746     iWait.Start();
       
  1747     return iStatus.Int();
       
  1748     }
       
  1749 void CWait::RunL()
       
  1750     {
       
  1751     if (iWait.IsStarted())
       
  1752         iWait.AsyncStop();
       
  1753     }
       
  1754 void CWait::DoCancel()
       
  1755     {
       
  1756     if (iWait.IsStarted())
       
  1757         iWait.AsyncStop();
       
  1758     }
       
  1759 void CWait::SetRequestType(TInt aRequestType)
       
  1760     {
       
  1761     iRequestType = aRequestType;
       
  1762     }
       
  1763 TInt CWait::GetRequestType()
       
  1764     {
       
  1765     return iRequestType;
       
  1766     }
       
  1767