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

#include "mainwindow.h"
#include "configurationwidget.h"
#include "displaywidget.h"
#include "applicationmanager.h"
#include "phononmanager.h"
#include "widgetmanager.h"
#include "mobilitymanager.h"
#include "mobilitydata.h"
#include "qtsingleapplication.h"

#include "viewui.h"
#include "applicationui.h"
#include "contactsui.h"
#include "systeminfogenericui.h"
#include "systeminfonetworkui.h"
#include "systeminfostorageui.h"
#include "messagingui.h"
#include "sensorsui.h"
#include "organizerui.h"
#include "feedbackui.h"
#include "docgalleryui.h"
#include "cameraui.h"
#include "nfcui.h"
#include "inputscriptinterface.h"

#include <remotecontrolwidget/locationui.h>
#include <remotecontrolwidget/scriptui.h>
#include <remotecontrolwidget/scriptadapter.h>
#include <remotecontrolwidget/batterybutton.h>
#include <remotecontrolwidget/powerbutton.h>
#include <remotecontrolwidget/signalstrengthbutton.h>
#include <remotecontrolwidget/networkmodebutton.h>
#include <remotecontrolwidget/favoritescriptbutton.h>
#include <remotecontrolwidget/plugininterface.h>

#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtCore/QSettings>
#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtGui/QKeyEvent>
#include <QtGui/QLayout>
#include <QtGui/QGraphicsView>
#include <QtGui/QPixmap>
#include <QtGui/QPushButton>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QMessageBox>
#include <QtGui/QDesktopServices>
#include <QtCore/QPluginLoader>

#if defined(Q_WS_X11)
#include <private/qt_x11_p.h>
#include <QtGui/QX11Info>
#endif

// VERSION UPDATE
const VersionStruct simulatorVersion(1, 1, 0, 1);

// Increment this value if the scripts that come bundled with the Simulator
// have changed and the user should be asked whether he wants to copy them
// to his user script directory.
const int scriptVersion = 1;

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
    , view(0)
    , config(0)
    , applicationManager(0)
    , mDeviceItem(0)
    , debugWindow(0)
    , startupError(false)
{
    setWindowIcon(QIcon(":/ui/icons/hicolor/256x256/apps/Nokia-Simulator.png"));

    applicationManager = new ApplicationManager(this);
    if (applicationManager->simulatorAlreadyStarted()
        || !applicationManager->initializeFontDirectory()) {
        QTimer::singleShot(0, this, SLOT(close()));
        startupError = true;
        return;
    }
    applicationManager->setVersion(simulatorVersion);

    MobilityData *mobility = new MobilityData(this);
    mobilityServer = new MobilityServer(mobility, this);
    mobilityServer->setVersion(simulatorVersion);

    setWindowTitle(tr("Qt Simulator"));
#ifdef Q_OS_MAC
    // Sorry, widgets with translucent background are broken on MacOS X.
    // Wait until QTBUG-6831 is fixed.
#else
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(Qt::FramelessWindowHint);
    // set a mask, because kwin's compositor won't draw shadows under the window then
    setMask(QRect(0,0,4096,4096));
#endif
#ifdef Q_OS_WIN
    // Enable closing the simulator from the taskbar
    setWindowFlags(windowFlags() | Qt::WindowSystemMenuHint);
#endif

    scene = new QGraphicsScene(this);

    mDeviceItem = new DeviceItem;

    scene->addItem(mDeviceItem);

    view = new QGraphicsView(scene);
    view->setOptimizationFlag(QGraphicsView::DontSavePainterState);
    view->setRenderHint(QPainter::SmoothPixmapTransform);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // otherwise the graphics view won't be transparent
    view->viewport()->setAutoFillBackground(false);

    PhononManager* phononManager = new PhononManager(this);
    phononManager->setObjectName("PhononManager");
    applicationManager->setPhononManager(phononManager);

    WidgetManager *widgetManager = new WidgetManager(mDeviceItem->display(), this);
    applicationManager->setWidgetManager(widgetManager);

    connect(applicationManager, SIGNAL(applicationRegistered(Application*)), this, SLOT(activateWindow()));
    connect(applicationManager, SIGNAL(applicationUnRegistered(int)), widgetManager, SLOT(onApplicationUnregistered(int)));
    connect(applicationManager, SIGNAL(softkeyTextSizeChanged(double)), mDeviceItem, SLOT(setSymbianSoftKeyTextSize(double)));
    connect(widgetManager, SIGNAL(symbianSoftKeyTextChanged(int,QString)), mDeviceItem, SLOT(setSymbianSoftKeyText(int,QString)));
    connect(widgetManager, SIGNAL(maemoNavigationChanged(MaemoNavigationMode)), mDeviceItem, SLOT(setMaemoNavigationMode(MaemoNavigationMode)));
    connect(widgetManager, SIGNAL(topOrientationChanged(Qt::WidgetAttribute)), mDeviceItem, SLOT(updateOrientation(Qt::WidgetAttribute)));
    connect(mDeviceItem, SIGNAL(deviceChanged(QSize,DeviceData)), applicationManager, SLOT(updateDisplayInformation(QSize,DeviceData)));
    connect(mDeviceItem, SIGNAL(drag(QPoint)), this, SLOT(dragFromView(QPoint)));
    connect(mDeviceItem, SIGNAL(viewSizeRequired(QSize)), this, SLOT(setViewSize(QSize)));
    connect(mDeviceItem, SIGNAL(buttonPressed(Qt::Key, QString)), widgetManager, SLOT(sendKeyPress(Qt::Key, QString)));
    connect(mDeviceItem, SIGNAL(buttonReleased(Qt::Key)), widgetManager, SLOT(sendKeyRelease(Qt::Key)));
    connect(mDeviceItem, SIGNAL(closeWindowPressed()), widgetManager, SLOT(closeCurrentWindow()));
    connect(mDeviceItem, SIGNAL(symbianSoftKeyClicked(int)), widgetManager, SLOT(triggerSymbianSoftKeyAction(int)));
    connect(mDeviceItem, SIGNAL(offsetChanged(const QPoint &)), widgetManager, SLOT(changeOffset(const QPoint &)));
    connect(mDeviceItem, SIGNAL(deviceChanged(QSize,DeviceData)), widgetManager, SLOT(updateSymbianSoftKeys()));
    connect(mDeviceItem, SIGNAL(orientationChanged(Orientation)), mobility, SLOT(rotateDevice(Orientation)));
    connect(mobilityServer, SIGNAL(applicationConnected(int, VersionStruct)),
            applicationManager, SLOT(updateMobilityVersion(int, VersionStruct)));

    view->setFrameStyle(QFrame::NoFrame);
    view->setParent(this);

    // Setup debug window.
    debugWindow = new QWidget(this);
    debugWindow->setWindowFlags(Qt::Window);
    debugWindow->setWindowTitle(qApp->applicationName() + " " + simulatorVersion.toString());
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(applicationManager->logWidget());
    layout->addWidget(widgetManager->logWidget());
    debugWindow->setLayout(layout);

    // Setup configuration window.
    config = new ConfigurationWidget(this);
    config->setWindowFlags(Qt::Window);
    connect(mDeviceItem, SIGNAL(sizeChanged(const QSize &)), this, SLOT(setSizeToDevice(const QSize &)));
    connect(config, SIGNAL(closeMainWindow()), this, SLOT(close()));

    scriptAdapter = new ScriptAdapter(this);

    // build ui pages
    ViewUi *viewUi = new ViewUi(mDeviceItem, this);
    if (!viewUi->initializeDeviceList()) {
        QTimer::singleShot(0, this, SLOT(close()));
        startupError = true;
        return;
    }
    config->addPage(viewUi);
    connect(mDeviceItem, SIGNAL(orientationLocked(bool)), viewUi, SLOT(setOrientationLocked(bool)));

    ApplicationUi *applicationUi = new ApplicationUi(this);
    config->addPage(applicationUi);
    connect(applicationUi, SIGNAL(exitButtonClicked()), applicationManager, SLOT(killCurrentApplication()));
    connect(widgetManager, SIGNAL(topWidgetChanged(Widget *)), applicationUi, SLOT(updateMenuBarWidget(Widget *)));

    GenericSystemInfoUi *genericSystemInfoUi = new GenericSystemInfoUi(this);
    mobility->mSystemInfoGenericUi = genericSystemInfoUi;
    config->addPage(genericSystemInfoUi);

    StorageSystemInfoUi *storageSystemInfoUi = new StorageSystemInfoUi(this);
    mobility->mSystemInfoStorageUi = storageSystemInfoUi;
    config->addPage(storageSystemInfoUi);

    NetworkSystemInfoUi *networkSystemInfoUi = new NetworkSystemInfoUi(this);
    mobility->mSystemInfoNetworkUi = networkSystemInfoUi;
    config->addPage(networkSystemInfoUi);

    LocationUi *locationUi = new LocationUi(this);
    mobility->mLocationUi = locationUi;
    config->addPage(locationUi);

    config->addPage(new ContactsUi(mobility->mContacts, this));
    config->addPage(new MessagingUi(mobility, this));

    SensorsUi *sensorsUi = new SensorsUi(this);
    mobility->mSensorsUi = sensorsUi;
    config->addPage(sensorsUi);
    connect(mDeviceItem, SIGNAL(deviceChanged(bool)), sensorsUi, SLOT(updateDeviceDefaultOrientation(bool)));

    OrganizerUi *organizerUi = new OrganizerUi(mobility->mOrganizer, this);
    config->addPage(organizerUi);

    FeedbackUi *feedbackUi = new FeedbackUi(mobility->mFeedback, this);
    config->addPage(feedbackUi);

    DocGalleryUi *docgalleryUi = new DocGalleryUi(this);
    mobility->mDocGalleryUi = docgalleryUi;
    config->addPage(docgalleryUi);

    CameraUi *cameraUi = new CameraUi(this);
    mobility->mCameraUi = cameraUi;
    config->addPage(cameraUi);

    NfcUi *nfcUi = new NfcUi(this);
    mobility->mNfcUi = nfcUi;
    config->addPage(nfcUi);

    mTouchUi = new MultiPointTouchUi(this);
    mTouchUi->setGestureScriptPath(userResourcePath() + "/scripts/gestures");
    config->addPage(mTouchUi);
    connect(mTouchUi, SIGNAL(inputModeChanged(MultiPointTouchUi::InputMode)),
            widgetManager, SLOT(setMouseInputMode(MultiPointTouchUi::InputMode)));
    connect(this, SIGNAL(mouseInputModeChanged(MultiPointTouchUi::InputMode)),
            mTouchUi, SLOT(setInputMode(MultiPointTouchUi::InputMode)));
    connect(mTouchUi, SIGNAL(customGesturePathChanged(QString)),
            widgetManager, SLOT(setCurrentGesturePath(QString)));

    ScriptUi *scriptUi = new ScriptUi(scriptAdapter, this);
    FavoriteScriptButton *scriptButton = new FavoriteScriptButton(this);
    setupScriptDirectories(scriptUi, scriptButton);
    config->addPage(scriptUi);

    NetworkModeButton *networkModeButton = new NetworkModeButton(this);
    connect(networkModeButton, SIGNAL(networkModeChanged(NetworkModeButton::NetworkMode)),
            networkSystemInfoUi, SLOT(setCurrentNetworkMode(NetworkModeButton::NetworkMode)));
    connect(networkSystemInfoUi, SIGNAL(currentNetworkModeChanged(NetworkModeButton::NetworkMode)),
            networkModeButton, SLOT(setDisplayedNetworkMode(NetworkModeButton::NetworkMode)));
    config->addMenuButton(networkModeButton);

    SignalStrengthButton *signalStrengthButton = new SignalStrengthButton(this);
    connect(signalStrengthButton, SIGNAL(signalStrengthChanged(SignalStrengthButton::SignalStrength)),
            networkSystemInfoUi, SLOT(setCurrentNetworkSignalStrength(SignalStrengthButton::SignalStrength)));
    connect(networkSystemInfoUi, SIGNAL(currentNetworkSignalStrengthChanged(SignalStrengthButton::SignalStrength)),
            signalStrengthButton, SLOT(setDisplayedSignalStrength(SignalStrengthButton::SignalStrength)));
    config->addMenuButton(signalStrengthButton);

    BatteryButton *batteryButton = new BatteryButton(this);
    connect(batteryButton, SIGNAL(batteryLevelChanged(BatteryButton::BatteryLevel)),
            mobility->mSystemInfoGenericUi, SLOT(setCurrentBatteryLevel(BatteryButton::BatteryLevel)));
    connect(mobility->mSystemInfoGenericUi, SIGNAL(currentBatteryLevelChanged(BatteryButton::BatteryLevel)),
            batteryButton, SLOT(setDisplayedBatteryLevel(BatteryButton::BatteryLevel)));
    config->addMenuButton(batteryButton);

    PowerButton *powerButton = new PowerButton(this);
    connect(powerButton, SIGNAL(powerStateChanged(PowerButton::PowerState)),
            mobility->mSystemInfoGenericUi, SLOT(setCurrentPowerState(PowerButton::PowerState)));
    connect(mobility->mSystemInfoGenericUi, SIGNAL(currentPowerStateChanged(PowerButton::PowerState)),
            powerButton, SLOT(setDisplayedState(PowerButton::PowerState)));
    config->addMenuButton(powerButton);

    // scriptButton is created above
    connect(scriptButton, SIGNAL(scriptSelected(QString)),
            scriptAdapter, SLOT(run(QString)));
    config->addMenuButton(scriptButton);

    InputScriptInterface *inputScriptInterface = new InputScriptInterface(this, view->viewport());
    inputScriptInterface->setView(view);
    inputScriptInterface->setDisplay(deviceItem()->display());

    // register script interfaces
    scriptAdapter->addScriptInterface("simulator", viewUi->scriptInterface());
    scriptAdapter->addScriptInterface("sensors", sensorsUi->scriptInterface());
    scriptAdapter->addScriptInterface("location", locationUi->scriptInterface());
    scriptAdapter->addScriptInterface("sysinfo.generic", genericSystemInfoUi->scriptInterface());
    scriptAdapter->addScriptInterface("sysinfo.network", networkSystemInfoUi->scriptInterface());
    scriptAdapter->addScriptInterface("sysinfo.storage", storageSystemInfoUi->scriptInterface());
    scriptAdapter->addScriptInterface("camera", cameraUi->scriptInterface());
    scriptAdapter->addScriptInterface("input", inputScriptInterface);
    scriptAdapter->addScriptInterface("touch", widgetManager->scriptInterface());

    connect(viewUi, SIGNAL(deviceSelectionChanged(const DeviceData &)), SLOT(callDeviceScript(const DeviceData &)));
    connect(widgetManager, SIGNAL(gestureScriptRequested(QString)), scriptAdapter, SLOT(run(QString)));

    config->setWindowFlags(Qt::Tool);

    loadPlugins();

    // read settings
    QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
    mTouchUi->readSettings(settings);

    mobility->setInitialData();

    config->show();
    config->readSettings(settings);

    // Filter to show debug window on special key press.
    view->installEventFilter(this);
    view->setFocus();

    readSettings(settings);
    scriptAdapter->runAutostartScripts();
}

MainWindow::~MainWindow()
{
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == view)
    {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->key() == Qt::Key_F9
                && keyEvent->modifiers() & Qt::ControlModifier)
            {
                debugWindow->show();
            } else if (keyEvent->modifiers() & Qt::AltModifier) {
                if (keyEvent->key() == Qt::Key_1)
                    emit mouseInputModeChanged(MultiPointTouchUi::defaultMode);
                else if (keyEvent->key() == Qt::Key_2)
                    emit mouseInputModeChanged(MultiPointTouchUi::pinchMode);
                else if (keyEvent->key() == Qt::Key_3)
                    emit mouseInputModeChanged(MultiPointTouchUi::panMode);
                else if (keyEvent->key() == Qt::Key_4)
                    emit mouseInputModeChanged(MultiPointTouchUi::swipeMode);
                else if (keyEvent->key() == Qt::Key_5)
                    emit mouseInputModeChanged(MultiPointTouchUi::freeMode);
            }
        }
    }
    return false;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (applicationManager->hasApplications()) {
        event->ignore();
        applicationManager->killAllApplications();
        connect(applicationManager, SIGNAL(lastAppUnregistered()), this, SLOT(close()));
        return;
    }

    if (!startupError) {
        QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
        writeSettings(settings);
        config->writeSettings(settings);
        mTouchUi->writeSettings(settings);
    }
}

void MainWindow::setSizeToDevice(const QSize &size)
{
    QSize targetSize(size);

    // don't try to make windows bigger than allowed on X11
#ifdef Q_WS_X11
    QSize maxSize = QApplication::desktop()->availableGeometry(this).size();
    targetSize = targetSize.boundedTo(maxSize);
#endif
    setMaximumSize(targetSize);
    resize(targetSize);
}

void MainWindow::dragFromView(const QPoint &to)
{
#ifdef Q_WS_X11
    XEvent xev;
    xev.xclient.type = ClientMessage;
    xev.xclient.message_type = ATOM(_NET_WM_MOVERESIZE);
    xev.xclient.display = X11->display;
    xev.xclient.window = winId();
    xev.xclient.format = 32;
    xev.xclient.data.l[0] = to.x();
    xev.xclient.data.l[1] = to.y();
    // only moving (the "move via keyboard" value seems to impose less
    // movement restrictions)
    xev.xclient.data.l[2] = 10;
    xev.xclient.data.l[3] = Button1;
    xev.xclient.data.l[4] = 2; // user event
    XUngrabPointer(X11->display, X11->time);
    XSendEvent(X11->display, QX11Info::appRootWindow(x11Info().screen()), False,
               SubstructureRedirectMask | SubstructureNotifyMask, &xev);
#else
    move(to - view->pos());
#endif
}

void MainWindow::setViewSize(const QSize &size)
{
    QSize targetSize(size);

    // X11 seems to be unable to draw windows bigger than the available desktop geometry.
    // Therefore, we enable scroll bars there if the view is required to be bigger than that.
#ifdef Q_WS_X11
    QSize maxSize = QApplication::desktop()->availableGeometry(this).size();
    targetSize = targetSize.boundedTo(maxSize);
    // the first check is for whether we're rotating at the moment
    if (targetSize == this->size() || targetSize == size) {
        view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    } else {
        view->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    }

    // adjust the window mask, otherwise the window is transparent, but clickable
    setMask(QRect(QPoint(width() - targetSize.width(), height() - targetSize.height()) / 2, targetSize));
#endif

    // resize and center the view
    view->move(QPoint(width() - targetSize.width(), height() - targetSize.height()) / 2);
    view->resize(targetSize);

    view->setSceneRect(0, 0, size.width(), size.height());
    view->centerOn(size.width() / 2, size.height() / 2);
}

void MainWindow::writeSettings(QSettings &settings) const
{
    settings.beginGroup("MainWindow");
    settings.setValue("pos", pos());
    int deviceOrientation = static_cast<int>(mDeviceItem->deviceOrientation());
    settings.setValue("deviceOrientation", deviceOrientation);
    int screenOrientation = static_cast<int>(mDeviceItem->screenOrientation());
    settings.setValue("screenOrientation", screenOrientation);
    settings.endGroup();
}

void MainWindow::readSettings(QSettings &settings)
{
    settings.beginGroup("MainWindow");
    QPoint positionToSet;
    if (settings.contains("pos"))
        positionToSet = settings.value("pos").toPoint();
    else
        positionToSet = QPoint(config->geometry().right() + 50, config->geometry().top());
    const QRect geometry = QApplication::desktop()->availableGeometry(positionToSet);
    if (geometry.contains(positionToSet + QPoint(height() / 2, width() / 2)))
        move(positionToSet);
    Orientation deviceOrientation = topUp;
    Orientation screenOrientation = topUp;
    if (settings.contains("deviceOrientation")) {
        int orientationInt = settings.value("deviceOrientation").toInt();
        if (orientationInt != 0)
            deviceOrientation = static_cast<Orientation>(orientationInt);
    }
    if (settings.contains("screenOrientation")) {
        int orientationInt = settings.value("screenOrientation").toInt();
        if (orientationInt != 0)
            screenOrientation = static_cast<Orientation>(orientationInt);
    }
    mDeviceItem->setInitialRotation(deviceOrientation, screenOrientation);
    mDeviceItem->setMaemoNavigationMode(maemoClose);

    settings.endGroup();
}

static bool copyDirectoryContents(const QString& sourcePath, const QString& targetPath)
{
    if (!QFileInfo(sourcePath).isDir()) {
        qWarning() << QObject::tr("Source is not a directory: %1").arg(sourcePath);
        return false;
    }
    QFileInfo targetPathInfo(targetPath);
    if (!targetPathInfo.exists()) {
        if (!QDir().mkpath(targetPath)) {
            qWarning() << QObject::tr("Could not create target directory %1").arg(targetPath);
            return false;
        }
    } else if (!targetPathInfo.isDir()) {
        qWarning() << QObject::tr("Target is not a directory: %1").arg(targetPath);
        return false;
    }

    const QDir targetDir(targetPath);
    QDirIterator it(sourcePath, QDir::NoDotAndDotDot | QDir::AllEntries);
    while(it.hasNext()) {
        const QFileInfo i(it.next());
        if(i.isDir()) {
            if (!copyDirectoryContents(i.absoluteFilePath(), targetDir.absoluteFilePath(i.fileName())))
                return false;
        } else {
            QFile f(i.filePath());
            const QString target = targetDir.absoluteFilePath(i.fileName());
            QFile::remove(target);
            if(!f.copy(target)) {
                qWarning() << QObject::tr("Could not copy file from %1 to %2: %3").arg(f.fileName(), target, f.errorString());
                return false;
            }
        }
    }

    return true;
}

void MainWindow::setupScriptDirectories(ScriptUi *ui, FavoriteScriptButton *button)
{
    const QString resourcePath = userResourcePath();
    const QString scriptsPath = resourcePath + QLatin1String("/scripts");
    const QString builtinScripts = QCoreApplication::applicationDirPath() + QLatin1String("/scripts");

    QSettings settings;
    settings.beginGroup("Scripts");
    int installedScriptVersion = settings.value("version", 0).toInt();

    // copy initial scripts if directory does not exist yet or the script version is newer
    const QFileInfo fi(scriptsPath + QLatin1Char('/'));
    bool copy = !fi.exists();
    bool updateScriptVersion = false;
    if (!copy && installedScriptVersion < scriptVersion) {
        QMessageBox *copyQuestion = new QMessageBox;
        copyQuestion->setWindowTitle(tr("Copy new Simulator scripts?"));
        copyQuestion->setText(tr("New versions of the default scripts are available. Copy them into your user script directory?\n\n"
                                 "WARNING: If you have modified the default scripts, this will revert your changes.\n\n"
                                 "You can also update your scripts manually.\n"
                                 "Default scipt directory: %1\n"
                                 "User script directory: %2").arg(builtinScripts, scriptsPath));
        copyQuestion->setIcon(QMessageBox::Question);
        QPushButton *copyButton = copyQuestion->addButton(tr("Copy"), QMessageBox::AcceptRole);
        copyQuestion->addButton(tr("Ask again"), QMessageBox::DestructiveRole);
        QPushButton *dontButton = copyQuestion->addButton(tr("Do not copy"), QMessageBox::RejectRole);
        copyQuestion->exec();

        if (copyQuestion->clickedButton() == copyButton) {
            copy = updateScriptVersion = true;
        } else if (copyQuestion->clickedButton() == dontButton) {
            updateScriptVersion = true;
        }
    }
    if (copy) {
        if (!copyDirectoryContents(builtinScripts, scriptsPath)) {
            qWarning() << "Could not copy scripts to" << scriptsPath;
        }
    }
    if (updateScriptVersion) {
        settings.setValue("version", scriptVersion);
    }

    ui->setScriptDirectory(scriptsPath);
    button->setPath(scriptsPath + QLatin1String("/favorites"));
}

void MainWindow::handleMessage(const QString &message)
{
    if (message.startsWith(QLatin1String("runscript "))) {
        const QString filePath = message.mid(10);
        scriptAdapter->run(filePath);
    }
}

void MainWindow::callDeviceScript(const DeviceData &newDevice)
{
    QString deviceScript = QCoreApplication::applicationDirPath()
        + QString::fromUtf8("/scripts/devices/") + newDevice.name
        + QString::fromUtf8(".qs");

    if (!QFile::exists(deviceScript)) {
        deviceScript = deviceScript.replace(newDevice.name + QString::fromUtf8(".qs"),
            QString::fromUtf8("Default.qs"));
    }
    scriptAdapter->run(deviceScript);
}

void MainWindow::activateWindow()
{
    SharedTools::QtSingleApplication::instance()->activateWindow();
}

void MainWindow::changeEvent(QEvent* e)
{
    if (e->type() == QEvent::ActivationChange && isActiveWindow()) {
        config->raise();
        raise();
    }
}

QString MainWindow::userResourcePath() const
{
    // Create resource dir if it doesn't yet exist
    const QString urp = QDesktopServices::storageLocation(QDesktopServices::DataLocation);

    QFileInfo fi(urp + QLatin1Char('/'));
    if (!fi.exists()) {
        QDir dir;
        if (!dir.mkpath(urp))
            qWarning() << "could not create" << urp;
    }

    return urp;
}

void MainWindow::loadPlugins()
{
    // NOTE: static plugins are not supported

    QDir pluginsDir = QDir(qApp->applicationDirPath());

#if defined(Q_OS_WIN)
    if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
        pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
    if (pluginsDir.dirName() == "MacOS") {
        pluginsDir.cdUp();
        pluginsDir.cdUp();
        pluginsDir.cdUp();
    }
#endif
    pluginsDir.cd("plugins");
    pluginsDir.cd("simulator");

    foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
        QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = loader.instance();
        if (plugin) {
            PluginInterface *pi = qobject_cast<PluginInterface *>(plugin);
            if (pi) {
                foreach (ToolBoxPage *tbp, pi->pages(this)) {
                    config->addPage(tbp);

                    QString name = tbp->scriptInterfaceName();
                    QObject *obj = tbp->scriptInterface();
                    if ( obj && !name.isEmpty() )
                      scriptAdapter->addScriptInterface(name, obj);
                }
            }
        }
    }
}