Subversion Repositories tpanel

Rev

Rev 465 | Rev 482 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
446 andreas 1
/*
2
 * Copyright (C) 2020 to 2024 by Andreas Theofilu <andreas@theosys.at>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
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 General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program; if not, write to the Free Software Foundation,
16
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
17
 */
18
 
19
/** @file tqtmain.cpp
20
 * @brief Implements the surface of the application.
21
 *
22
 * This file implements the callback functions of the suface. While the most
23
 * classes are drawing the elements, the methods here take the ready elements
24
 * and display them. This file makes the surface completely independent of
25
 * the rest of the application which makes it easy to change the surface by
26
 * any other technology.
27
 */
28
#include <QApplication>
29
#include <QGuiApplication>
30
#include <QByteArray>
31
#include <QCommandLineParser>
32
#include <QCommandLineOption>
33
#include <QLabel>
34
#include <QtWidgets>
35
#include <QStackedWidget>
36
#include <QMouseEvent>
37
#include <QMoveEvent>
38
#include <QTouchEvent>
39
#include <QPalette>
40
#include <QPixmap>
41
#include <QFont>
42
#include <QFontDatabase>
43
#include <QtMultimediaWidgets/QVideoWidget>
44
#include <QtMultimedia/QMediaPlayer>
45
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
46
#   include <QtMultimedia/QMediaPlaylist>
47
#else
48
#   include <QAudioOutput>
49
#   include <QMediaMetaData>
50
#endif
51
#include <QListWidget>
52
#include <QLayout>
53
#include <QSizePolicy>
54
#include <QUrl>
55
#include <QThread>
56
#ifdef Q_OS_IOS
57
#include <QtSensors/QOrientationSensor>
58
#endif
59
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
60
#   include <QSound>
61
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
62
#   include <QtSensors/QOrientationSensor>
63
#   include <qpa/qplatformscreen.h>
64
#endif
65
#else
66
#   include <QPlainTextEdit>
67
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
68
#   include <QGeoPositionInfoSource>
69
#   include <QtSensors/QOrientationReading>
70
#   include <QPermissions>
71
#endif
72
#endif
73
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && defined(Q_OS_ANDROID)
74
#include <QtAndroidExtras/QAndroidJniObject>
75
#include <QtAndroidExtras/QtAndroid>
76
#endif
77
#include <functional>
78
//#include <mutex>
79
#ifdef Q_OS_ANDROID
80
#include <android/log.h>
81
#endif
82
#include "tpagemanager.h"
83
#include "tqtmain.h"
84
#include "tconfig.h"
85
#if !defined(Q_OS_IOS) && !defined(Q_OS_ANDROID)
86
#include "tqtsettings.h"
87
#endif
88
#include "tqkeyboard.h"
89
#include "tqkeypad.h"
90
#include "tcolor.h"
91
#include "texcept.h"
92
#include "ttpinit.h"
93
#include "tqdownload.h"
94
#include "tqtphone.h"
95
#include "tqeditline.h"
96
#include "tqtinputline.h"
97
#include "tqmarquee.h"
98
#include "tqtwait.h"
99
#include "terror.h"
100
#include "tresources.h"
101
#include "tqscrollarea.h"
102
#include "tlock.h"
103
#ifdef Q_OS_IOS
104
#include "ios/QASettings.h"
105
#include "ios/tiosrotate.h"
106
#include "ios/tiosbattery.h"
107
#endif
108
#if TESTMODE == 1
109
#include "testmode.h"
110
#endif
111
 
112
#if __cplusplus < 201402L
113
#   error "This module requires at least C++14 standard!"
114
#else   // __cplusplus < 201402L
115
#   if __cplusplus < 201703L
116
#       include <experimental/filesystem>
117
namespace fs = std::experimental::filesystem;
118
#       warning "Support for C++14 and experimental filesystem will be removed in a future version!"
119
#   else    // __cplusplus < 201703L
120
#       include <filesystem>
121
#       ifdef __ANDROID__
122
namespace fs = std::__fs::filesystem;
123
#       else    // __ANDROID__
124
namespace fs = std::filesystem;
125
#       endif   // __ANDROID__
126
#   endif   // __cplusplus < 201703L
127
#endif  // __cplusplus < 201402L
128
 
129
 
130
extern amx::TAmxNet *gAmxNet;                   //!< Pointer to the class running the thread which handles the communication with the controller.
131
extern bool _restart_;                          //!< If this is set to true then the whole program will start over.
132
extern TPageManager *gPageManager;              //!< The pointer to the global defined main class.
133
static bool isRunning = false;                  //!< TRUE = the pageManager was started.
134
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
135
static double gScale = 1.0;                     //!< Global variable holding the scale factor.
136
static int gFullWidth = 0;                      //!< Global variable holding the width of the AMX screen. This is used to calculate the scale factor for the settings dialog.
137
std::atomic<double> mScaleFactorW{1.0};
138
std::atomic<double> mScaleFactorH{1.0};
139
int gScreenWidth{0};
140
int gScreenHeight{0};
141
bool isPortrait{false};
142
#endif
143
 
144
using std::bind;
145
using std::map;
146
using std::pair;
147
using std::string;
148
using std::vector;
149
 
150
static string _NO_OBJECT = "The global class TObject is not available!";
151
 
152
/**
153
 * @brief qtmain is used here as the entry point for the surface.
154
 *
155
 * The main entry function parses the command line parameters, if there were
156
 * any and sets the basic attributes. It creates the main window and starts the
157
 * application.
158
 *
159
 * @param argc      The number of command line arguments
160
 * @param argv      A pointer to a 2 dimensional array containing the command
161
 *                  line parameters.
162
 * @param pmanager  A pointer to the page manager class which is the main class
163
 *                  managing everything.
164
 *
165
 * @return If no errors occured it returns 0.
166
 */
167
int qtmain(int argc, char **argv, TPageManager *pmanager)
168
{
169
    DECL_TRACER("qtmain(int argc, char **argv, TPageManager *pmanager)");
170
 
171
    if (!pmanager)
172
    {
173
        MSG_ERROR("Fatal: No pointer to the page manager received!");
174
        return 1;
175
    }
176
 
177
    gPageManager = pmanager;
178
#ifdef __ANDROID__
179
    MSG_INFO("Android API version: " << __ANDROID_API__);
180
 
181
#if __ANDROID_API__ < 30
182
#warning "The Android API version is less than 30! Some functions may not work!"
183
#endif  // __ANDROID_API__
184
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
185
    QAndroidJniObject activity = QtAndroid::androidActivity();
186
    QAndroidJniObject::callStaticMethod<void>("org/qtproject/theosys/HideToolbar", "hide", "(Landroid/app/Activity;Z)V", activity.object(), true);
187
#else
188
    QJniObject activity = QNativeInterface::QAndroidApplication::context();
189
    QJniObject::callStaticMethod<void>("org/qtproject/theosys/HideToolbar", "hide", "(Landroid/app/Activity;Z)V", activity.object(), true);
190
#endif  // QT5_LINUX
191
#endif  // __ANDROID__
192
 
193
#if defined(Q_OS_ANDROID)
194
    QApplication::setAttribute(Qt::AA_ForceRasterWidgets);
195
//    QApplication::setAttribute(Qt::AA_Use96Dpi);
196
//    QApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
197
#endif
198
 
199
    QApplication app(argc, argv);
200
    // Set the orientation
201
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
202
    QScreen *screen = QGuiApplication::primaryScreen();
203
 
204
    if (!screen)
205
    {
206
        MSG_ERROR("Couldn't determine the primary screen!")
207
        return 1;
208
    }
209
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
210
    if (pmanager->getSettings()->isPortrait())  // portrait?
211
    {
212
        MSG_INFO("Orientation set to portrait mode.");
213
        screen->setOrientationUpdateMask(Qt::PortraitOrientation);
214
    }
215
    else
216
    {
217
        MSG_INFO("Orientation set to landscape mode.");
218
        screen->setOrientationUpdateMask(Qt::LandscapeOrientation);
219
    }
220
#endif  // QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
221
    double scale = 1.0;
222
    // Calculate the scale factor
223
    if (TConfig::getScale())
224
    {
225
        // Because we've no window here we can not know on which screen, if
226
        // there are more than one, the application will start. Because on a
227
        // mobile mostly no external screen is connected, we take always the
228
        // resolution of the first (built in) screen.
229
        // TODO: Find a way to get the screen the application will start and
230
        // take this screen to calculate the scale factor.
449 andreas 231
        QSize screenSize = screen->size();
446 andreas 232
        double width = 0.0;
233
        double height = 0.0;
449 andreas 234
        gScreenWidth = std::max(screenSize.width(), screenSize.height());
235
        gScreenHeight = std::min(screenSize.height(), screenSize.width());
446 andreas 236
 
449 andreas 237
        if (screenSize.width() > screenSize.height())
446 andreas 238
            isPortrait = false;
239
        else
240
            isPortrait = true;
241
 
242
        int minWidth = pmanager->getSettings()->getWidth();
243
        int minHeight = pmanager->getSettings()->getHeight();
244
 
245
        if (pmanager->getSettings()->isPortrait())  // portrait?
246
        {
247
            width = std::min(gScreenWidth, gScreenHeight);
248
            height = std::max(gScreenHeight, gScreenWidth);
249
        }
250
        else
251
        {
252
            width = std::max(gScreenWidth, gScreenHeight);
253
            height = std::min(gScreenHeight, gScreenWidth);
254
        }
255
 
256
        if (!TConfig::getToolbarSuppress() && TConfig::getToolbarForce())
257
            minWidth += 48;
258
 
259
        MSG_INFO("Dimension of AMX screen:" << minWidth << " x " << minHeight);
260
        MSG_INFO("Screen size: " << width << " x " << height);
261
        // The scale factor is always calculated in difference to the prefered
262
        // size of the original AMX panel.
263
        mScaleFactorW = width / (double)minWidth;
264
        mScaleFactorH = height / (double)minHeight;
265
        scale = std::min(mScaleFactorW, mScaleFactorH);
266
#ifdef __ANDROID__
449 andreas 267
        __android_log_print(ANDROID_LOG_DEBUG, "tpanel", "INF    ##, ???????????? scale: %f (Screen: %1.0fx%1.0f, Page: %dx%d)", scale, width, height, minWidth, minHeight);
446 andreas 268
#endif
269
        gScale = scale;     // The calculated scale factor
270
        gFullWidth = width;
271
        MSG_INFO("Calculated scale factor: " << scale);
272
        // This preprocessor variable allows the scaling to be done by the Skia
273
        // library, which is used to draw everything. In comparison to Qt this
274
        // library is a bit slower and sometimes does not honor the aspect ratio
275
        // correct. But in case there is another framework than Qt in use, this
276
        // could be necessary.
277
#ifdef _SCALE_SKIA_
278
        if (scale != 0.0)
279
        {
280
            pmanager->setScaleFactor(scale);
281
            MSG_INFO("Scale factor: " << scale);
282
        }
283
 
284
        if (scaleW != 0.0)
285
            pmanager->setScaleFactorWidth(scaleW);
286
 
287
        if (scaleH != 0.0)
288
            pmanager->setScaleFactorHeight(scaleH);
289
#endif  // _SCALE_SKIA_
290
    }
291
#endif  // defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
292
    // Initialize the application
293
    pmanager->setDPI(QGuiApplication::primaryScreen()->logicalDotsPerInch());
294
    QCoreApplication::setOrganizationName(TConfig::getProgName().c_str());
295
    QCoreApplication::setApplicationName("TPanel");
296
    QCoreApplication::setApplicationVersion(VERSION_STRING());
297
    QCommandLineParser parser;
298
    parser.setApplicationDescription(QCoreApplication::applicationName());
299
    parser.addHelpOption();
300
    parser.addVersionOption();
301
    parser.process(app);
302
 
303
    MainWindow mainWin;
304
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
305
#   ifndef _SCALE_SKIA_
306
    if (TConfig::getScale() && scale != 1.0)
307
        mainWin.setScaleFactor(scale);
308
#   endif   // _SCALE_SKIA_
309
#endif  // defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
310
    mainWin.setConfigFile(TConfig::getConfigPath() + "/" + TConfig::getConfigFileName());
311
    QPalette palette(mainWin.palette());
312
    palette.setColor(QPalette::Window, Qt::black);  // Keep the background black. Helps to save battery on OLED displays.
313
    mainWin.setPalette(palette);
314
    mainWin.grabGesture(Qt::PinchGesture);
315
    mainWin.grabGesture(Qt::SwipeGesture);
316
    mainWin.setOrientation(Qt::PrimaryOrientation);
317
//#ifdef Q_OS_IOS
318
 //   mainWin.setWindowFlag(Qt::MaximizeUsingFullscreenGeometryHint, true);
319
//#endif
320
 
321
    mainWin.show();
322
    return app.exec();
323
}
324
 
325
/**
326
 * @brief MainWindow::MainWindow constructor
327
 *
328
 * This method is the constructor for this class. It registers the callback
329
 * functions to the class TPageManager and starts the main run loop.
330
 *
331
 * Qt is used only to manage widgets to handle pages and subpages. A page as
332
 * well as a subpage may contain a background graphic and some elements. The
333
 * elements could be buttons, bargraphs and other objects. The underlying layer
334
 * draw every element as a ready graphic image and call a callback function to
335
 * let Qt display the graphic.
336
 * If there are some animations on a subpage defined, this is also handled by
337
 * Qt. Especialy sliding and fading.
338
 */
339
MainWindow::MainWindow()
461 andreas 340
    : mIntercom(this)
446 andreas 341
{
342
    DECL_TRACER("MainWindow::MainWindow()");
343
 
344
    TObject::setParent(this);
345
 
346
    if (!gPageManager)
347
    {
348
        EXCEPTFATALMSG("The class TPageManager was not initialized!");
349
    }
350
 
351
    mGestureFilter = new TQGestureFilter(this);
352
    connect(mGestureFilter, &TQGestureFilter::gestureEvent, this, &MainWindow::onGestureEvent);
353
    setAttribute(Qt::WA_AcceptTouchEvents, true);   // We accept touch events
354
    grabGesture(Qt::PinchGesture);                  // We use a pinch gesture to open the settings dialog
355
    grabGesture(Qt::SwipeGesture);                  // We support swiping also
356
 
357
#ifdef Q_OS_IOS                                     // Block autorotate on IOS
358
//    initGeoLocation();
359
    mIosRotate = new TIOSRotate;
360
//    mIosRotate->automaticRotation(false);           // FIXME: This doesn't work!
361
 
362
    if (!mSensor)
363
    {
364
        mSensor = new QOrientationSensor(this);
365
 
366
        if (mSensor)
367
        {
368
            mSensor->setAxesOrientationMode(QSensor::AutomaticOrientation);
369
 
370
            if (gPageManager && gPageManager->getSettings()->isPortrait())
371
                mSensor->setCurrentOrientation(Qt::PortraitOrientation);
372
            else
373
                mSensor->setCurrentOrientation(Qt::LandscapeOrientation);
374
        }
375
    }
376
#endif  // Q_OS_IOS
377
 
378
    // We create the central widget here to make sure the application
379
    // initializes correct. On mobiles the whole screen is used while on
380
    // desktops a window with the necessary size is created.
381
    QWidget *central = new QWidget;
382
    central->setObjectName("centralWidget");
383
    central->setBackgroundRole(QPalette::Window);
384
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
385
//    central->setAutoFillBackground(false);
386
    central->setFixedSize(gScreenWidth, gScreenHeight);
387
#endif  // defined(Q_OS_IOS) || defined(Q_OSANDROID)
388
    setCentralWidget(central);      // Here we set the central widget
389
    central->show();
390
    // This is a stacked widget used to hold all pages. With it we can also
391
    // simply manage the objects bound to a page.
392
    mCentralWidget = new QStackedWidget(central);
393
    mCentralWidget->setObjectName("stackedPageWidgets");
394
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
395
    MSG_DEBUG("Size will be set for " << (isPortrait ? "PORTRAIT" : "LANDSCAPE"));
396
 
397
    if (gPageManager && gPageManager->getSettings()->isLandscape())
398
    {
399
        if (!isPortrait)
400
            mCentralWidget->setFixedSize((mToolbar ? gScreenWidth - mToolbar->width() : gScreenWidth), gScreenHeight);
401
        else
402
            mCentralWidget->setFixedSize(gScreenWidth, gScreenHeight);
403
    }
404
    else
405
    {
406
        if (isPortrait)
407
            mCentralWidget->setFixedSize((mToolbar ? gScreenHeight - mToolbar->width() : gScreenHeight), gScreenWidth);
408
        else
409
            mCentralWidget->setFixedSize(gScreenHeight, gScreenWidth);
410
    }
411
#else
412
    QSize qs = menuBar()->sizeHint();
413
    QSize icSize =  iconSize();
414
    int lwidth = gPageManager->getSettings()->getWidth() + icSize.width() + 16;
415
    int lheight = gPageManager->getSettings()->getHeight() + qs.height();
416
    mCentralWidget->setFixedSize(gPageManager->getSettings()->getWidth(), gPageManager->getSettings()->getHeight());
417
#endif  // defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
418
 
419
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
420
    if (gPageManager->getSettings()->isPortrait())  // portrait?
421
    {
422
        MSG_INFO("Orientation set to portrait mode.");
423
        _setOrientation(O_PORTRAIT);
424
        mOrientation = Qt::PortraitOrientation;
425
    }
426
    else
427
    {
428
        MSG_INFO("Orientation set to landscape mode.");
429
        _setOrientation(O_LANDSCAPE);
430
        mOrientation = Qt::LandscapeOrientation;
431
    }
432
#else
433
    QRect rectMain = geometry();
434
    rectMain.setWidth(lwidth);
435
    rectMain.setHeight(lheight);
436
    setGeometry(rectMain);
437
    MSG_DEBUG("Height of main window:  " << rectMain.height());
438
    MSG_DEBUG("Height of panel screen: " << lheight);
439
    // If our first top pixel is not 0, maybe because of a menu, window
440
    // decorations or a toolbar, we must add this extra height to the
441
    // positions of widgets and mouse presses.
442
    int avHeight = rectMain.height() - gPageManager->getSettings()->getHeight();
443
    MSG_DEBUG("Difference in height:   " << avHeight);
444
    gPageManager->setFirstTopPixel(avHeight);
445
#endif
446
    setWindowIcon(QIcon(":images/icon.png"));
447
 
448
    // First we register all our surface callbacks to the underlying work
449
    // layer. All the graphics are drawn by the Skia library. The layer below
450
    // call the following functions to let Qt display the graphics on the
451
    // screen let it manage the widgets containing the graphics.
452
    gPageManager->registerCallbackDB(bind(&MainWindow::_displayButton, this,
453
                                       std::placeholders::_1,
454
                                       std::placeholders::_2,
455
                                       std::placeholders::_3,
456
                                       std::placeholders::_4,
457
                                       std::placeholders::_5,
458
                                       std::placeholders::_6,
459
                                       std::placeholders::_7,
460
                                       std::placeholders::_8,
461
                                       std::placeholders::_9,
462
                                       std::placeholders::_10));
463
 
464
    gPageManager->registerSetMarqueeText(bind(&MainWindow::_setMarqueeText, this, std::placeholders::_1));
465
 
466
    gPageManager->regDisplayViewButton(bind(&MainWindow::_displayViewButton, this,
467
                                          std::placeholders::_1,
468
                                          std::placeholders::_2,
469
                                          std::placeholders::_3,
470
                                          std::placeholders::_4,
471
                                          std::placeholders::_5,
472
                                          std::placeholders::_6,
473
                                          std::placeholders::_7,
474
                                          std::placeholders::_8,
475
                                          std::placeholders::_9,
476
                                          std::placeholders::_10));
477
 
478
    gPageManager->regAddViewButtonItems(bind(&MainWindow::_addViewButtonItems, this,
479
                                             std::placeholders::_1,
480
                                             std::placeholders::_2));
481
 
482
    gPageManager->regUpdateViewButton(bind(&MainWindow::_updateViewButton, this,
483
                                           std::placeholders::_1,
484
                                           std::placeholders::_2,
485
                                           std::placeholders::_3,
486
                                           std::placeholders::_4));
487
 
488
    gPageManager->regUpdateViewButtonItem(bind(&MainWindow::_updateViewButtonItem, this,
489
                                               std::placeholders::_1,
490
                                               std::placeholders::_2));
491
 
492
    gPageManager->regShowSubViewItem(bind(&MainWindow::_showViewButtonItem, this,
493
                                          std::placeholders::_1,
494
                                          std::placeholders::_2,
495
                                          std::placeholders::_3,
496
                                          std::placeholders::_4));
497
 
498
    gPageManager->regHideAllSubViewItems(bind(&MainWindow::_hideAllViewItems, this, std::placeholders::_1));
499
    gPageManager->regHideSubViewItem(bind(&MainWindow::_hideViewItem, this, std::placeholders::_1, std::placeholders::_2));
500
    gPageManager->regSetSubViewPadding(bind(&MainWindow::_setSubViewPadding, this, std::placeholders::_1, std::placeholders::_2));
501
 
502
    gPageManager->registerCallbackSP(bind(&MainWindow::_setPage, this,
503
                                         std::placeholders::_1,
504
                                         std::placeholders::_2,
505
                                         std::placeholders::_3));
506
 
507
    gPageManager->registerCallbackSSP(bind(&MainWindow::_setSubPage, this,
508
                                          std::placeholders::_1,
509
                                          std::placeholders::_2,
510
                                          std::placeholders::_3,
511
                                          std::placeholders::_4,
512
                                          std::placeholders::_5,
513
                                          std::placeholders::_6,
514
                                          std::placeholders::_7,
515
                                          std::placeholders::_8));
516
 
517
    gPageManager->registerCallbackSB(bind(&MainWindow::_setBackground, this,
518
                                         std::placeholders::_1,
519
                                         std::placeholders::_2,
520
                                         std::placeholders::_3,
521
                                         std::placeholders::_4,
522
#ifdef _OPAQUE_SKIA_
523
                                         std::placeholders::_5));
524
#else
525
                                         std::placeholders::_5,
526
                                         std::placeholders::_6));
527
#endif
528
    gPageManager->regCallDropPage(bind(&MainWindow::_dropPage, this, std::placeholders::_1));
529
    gPageManager->regCallDropSubPage(bind(&MainWindow::_dropSubPage, this, std::placeholders::_1, std::placeholders::_2));
530
    gPageManager->regCallPlayVideo(bind(&MainWindow::_playVideo, this,
531
                                       std::placeholders::_1,
532
                                       std::placeholders::_2,
533
                                       std::placeholders::_3,
534
                                       std::placeholders::_4,
535
                                       std::placeholders::_5,
536
                                       std::placeholders::_6,
537
                                       std::placeholders::_7,
538
                                       std::placeholders::_8,
539
                                       std::placeholders::_9));
540
    gPageManager->regCallInputText(bind(&MainWindow::_inputText, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
541
    gPageManager->regCallListBox(bind(&MainWindow::_listBox, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
542
    gPageManager->registerDropButton(bind(&MainWindow::_dropButton, this, std::placeholders::_1));
543
    gPageManager->regCallbackKeyboard(bind(&MainWindow::_showKeyboard, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
544
    gPageManager->regCallbackKeypad(bind(&MainWindow::_showKeypad, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
545
    gPageManager->regCallResetKeyboard(bind(&MainWindow::_resetKeyboard, this));
546
    gPageManager->regCallShowSetup(bind(&MainWindow::_showSetup, this));
547
    gPageManager->regCallbackResetSurface(bind(&MainWindow::_resetSurface, this));
548
    gPageManager->regCallbackShutdown(bind(&MainWindow::_shutdown, this));
549
    gPageManager->regCallbackPlaySound(bind(&MainWindow::_playSound, this, std::placeholders::_1));
550
    gPageManager->regCallbackStopSound(bind(&MainWindow::_stopSound, this));
551
    gPageManager->regCallbackMuteSound(bind(&MainWindow::_muteSound, this, std::placeholders::_1));
552
    gPageManager->regCallbackSetVolume(bind(&MainWindow::_setVolume, this, std::placeholders::_1));
553
    gPageManager->registerCBsetVisible(bind(&MainWindow::_setVisible, this, std::placeholders::_1, std::placeholders::_2));
554
    gPageManager->regSendVirtualKeys(bind(&MainWindow::_sendVirtualKeys, this, std::placeholders::_1));
555
    gPageManager->regShowPhoneDialog(bind(&MainWindow::_showPhoneDialog, this, std::placeholders::_1));
556
    gPageManager->regSetPhoneNumber(bind(&MainWindow::_setPhoneNumber, this, std::placeholders::_1));
557
    gPageManager->regSetPhoneStatus(bind(&MainWindow::_setPhoneStatus, this, std::placeholders::_1));
558
    gPageManager->regSetPhoneState(bind(&MainWindow::_setPhoneState, this, std::placeholders::_1, std::placeholders::_2));
559
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
560
    gPageManager->regOnOrientationChange(bind(&MainWindow::_orientationChanged, this, std::placeholders::_1));
561
    gPageManager->regOnSettingsChanged(bind(&MainWindow::_activateSettings, this, std::placeholders::_1,
562
                                            std::placeholders::_2,
563
                                            std::placeholders::_3,
564
                                            std::placeholders::_4,
565
                                            std::placeholders::_5,
566
                                            std::placeholders::_6));
567
#endif
568
    gPageManager->regRepaintWindows(bind(&MainWindow::_repaintWindows, this));
569
    gPageManager->regToFront(bind(&MainWindow::_toFront, this, std::placeholders::_1));
570
#if !defined (Q_OS_ANDROID) && !defined(Q_OS_IOS)
571
    gPageManager->regSetMainWindowSize(bind(&MainWindow::_setSizeMainWindow, this, std::placeholders::_1, std::placeholders::_2));
572
#endif
573
    gPageManager->regDownloadSurface(bind(&MainWindow::_downloadSurface, this, std::placeholders::_1, std::placeholders::_2));
574
    gPageManager->regDisplayMessage(bind(&MainWindow::_displayMessage, this, std::placeholders::_1, std::placeholders::_2));
575
    gPageManager->regAskPassword(bind(&MainWindow::_askPassword, this, std::placeholders::_1,
576
                                      std::placeholders::_2,
577
                                      std::placeholders::_3,
578
                                      std::placeholders::_4,
579
                                      std::placeholders::_5));
580
    gPageManager->regFileDialogFunction(bind(&MainWindow::_fileDialog, this,
581
                                             std::placeholders::_1,
582
                                             std::placeholders::_2,
583
                                             std::placeholders::_3,
584
                                             std::placeholders::_4));
585
    gPageManager->regStartWait(bind(&MainWindow::_startWait, this, std::placeholders::_1));
586
    gPageManager->regStopWait(bind(&MainWindow::_stopWait, this));
587
    gPageManager->regPageFinished(bind(&MainWindow::_pageFinished, this, std::placeholders::_1));
458 andreas 588
    gPageManager->regInitializeIntercom(bind(&MainWindow::_initializeIntercom, this, std::placeholders::_1));
589
    gPageManager->regIntercomStart(bind(&MainWindow::_intercomStart, this));
590
    gPageManager->regIntercomStop(bind(&MainWindow::_intercomStop, this));
591
    gPageManager->regIntercomSpkLevel(bind(&MainWindow::_intercomSpkLevel, this, std::placeholders::_1));
592
    gPageManager->regIntercomMicLevel(bind(&MainWindow::_intercomMicLevel, this, std::placeholders::_1));
593
    gPageManager->regIntercomMute(bind(&MainWindow::_intercomMicMute, this, std::placeholders::_1));
446 andreas 594
    gPageManager->deployCallbacks();
595
 
596
    createActions();        // Create the toolbar, if enabled by settings.
597
 
598
#ifndef QT_NO_SESSIONMANAGER
599
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
600
    QGuiApplication::setFallbackSessionManagementEnabled(false);
601
    connect(qApp, &QGuiApplication::commitDataRequest,
602
            this, &MainWindow::writeSettings);
603
#endif  // QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
604
#endif  // QT_NO_SESSIONMANAGER
605
 
606
    // Some types used to transport data from the layer below.
607
    qRegisterMetaType<size_t>("size_t");
608
    qRegisterMetaType<QByteArray>("QByteArray");
609
    qRegisterMetaType<ANIMATION_t>("ANIMATION_t");
610
    qRegisterMetaType<Button::TButton*>("Button::TButton*");
611
    qRegisterMetaType<std::string>("std::string");
612
    qRegisterMetaType<SUBVIEWLIST_T>("SUBVIEWLIST_T");
613
    qRegisterMetaType<PGSUBVIEWITEM_T>("PGSUBVIEWITEM_T");
614
    qRegisterMetaType<PGSUBVIEWITEM_T>("PGSUBVIEWITEM_T&");
615
    qRegisterMetaType<PGSUBVIEWATOM_T>("PGSUBVIEWATOM_T");
616
    qRegisterMetaType<TBitmap>("TBitmap");
458 andreas 617
    qRegisterMetaType<INTERCOM_t>("INTERCOM_t");
446 andreas 618
 
619
    // All the callback functions doesn't act directly. Instead they emit an
620
    // event. Then Qt decides whether the real function is started directly and
621
    // immediately or if the call is queued and called later in a thread. To
622
    // handle this we're "connecting" the real functions to some signals.
623
    try
624
    {
625
        connect(this, &MainWindow::sigDisplayButton, this, &MainWindow::displayButton);
626
        connect(this, &MainWindow::sigSetMarqueeText, this, &MainWindow::setMarqueeText);
627
        connect(this, &MainWindow::sigDisplayViewButton, this, &MainWindow::displayViewButton);
628
        connect(this, &MainWindow::sigAddViewButtonItems, this, &MainWindow::addViewButtonItems);
629
        connect(this, &MainWindow::sigShowViewButtonItem, this, &MainWindow::showViewButtonItem);
630
        connect(this, &MainWindow::sigUpdateViewButton, this, &MainWindow::updateViewButton);
631
        connect(this, &MainWindow::sigUpdateViewButtonItem, this, &MainWindow::updateViewButtonItem);
632
        connect(this, &MainWindow::sigSetPage, this, &MainWindow::setPage);
633
        connect(this, &MainWindow::sigSetSubPage, this, &MainWindow::setSubPage);
634
        connect(this, &MainWindow::sigSetBackground, this, &MainWindow::setBackground);
635
        connect(this, &MainWindow::sigDropPage, this, &MainWindow::dropPage);
636
        connect(this, &MainWindow::sigDropSubPage, this, &MainWindow::dropSubPage);
637
        connect(this, &MainWindow::sigPlayVideo, this, &MainWindow::playVideo);
638
        connect(this, &MainWindow::sigInputText, this, &MainWindow::inputText);
639
        connect(this, &MainWindow::sigListBox, this, &MainWindow::listBox);
640
        connect(this, &MainWindow::sigKeyboard, this, &MainWindow::showKeyboard);
641
        connect(this, &MainWindow::sigKeypad, this, &MainWindow::showKeypad);
642
        connect(this, &MainWindow::sigShowSetup, this, &MainWindow::showSetup);
643
        connect(this, &MainWindow::sigPlaySound, this, &MainWindow::playSound);
644
        connect(this, &MainWindow::sigSetVolume, this, &MainWindow::setVolume);
645
        connect(this, &MainWindow::sigDropButton, this, &MainWindow::dropButton);
646
        connect(this, &MainWindow::sigSetVisible, this, &MainWindow::SetVisible);
647
        connect(this, &MainWindow::sigSendVirtualKeys, this, &MainWindow::sendVirtualKeys);
648
        connect(this, &MainWindow::sigShowPhoneDialog, this, &MainWindow::showPhoneDialog);
649
        connect(this, &MainWindow::sigSetPhoneNumber, this, &MainWindow::setPhoneNumber);
650
        connect(this, &MainWindow::sigSetPhoneStatus, this, &MainWindow::setPhoneStatus);
651
        connect(this, &MainWindow::sigSetPhoneState, this, &MainWindow::setPhoneState);
652
        connect(this, &MainWindow::sigRepaintWindows, this, &MainWindow::repaintWindows);
653
        connect(this, &MainWindow::sigToFront, this, &MainWindow::toFront);
654
        connect(this, &MainWindow::sigOnProgressChanged, this, &MainWindow::onProgressChanged);
655
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
656
        connect(this, &MainWindow::sigSetSizeMainWindow, this, &MainWindow::setSizeMainWindow);
657
#endif
658
        connect(this, &MainWindow::sigDownloadSurface, this, &MainWindow::downloadSurface);
659
        connect(this, &MainWindow::sigDisplayMessage, this, &MainWindow::displayMessage);
660
        connect(this, &MainWindow::sigAskPassword, this, &MainWindow::askPassword);
661
        connect(this, &MainWindow::sigFileDialog, this, &MainWindow::fileDialog);
662
        connect(this, &MainWindow::sigStartWait, this, &MainWindow::startWait);
663
        connect(this, &MainWindow::sigStopWait, this, &MainWindow::stopWait);
664
        connect(this, &MainWindow::sigPageFinished, this, &MainWindow::pageFinished);
465 andreas 665
        connect(this, &MainWindow::sigInitializeIntercom, this, &MainWindow::initializeIntercom);
666
        connect(this, &MainWindow::sigIntercomStart, this, &MainWindow::intercomStart);
667
        connect(this, &MainWindow::sigIntercomStop, this, &MainWindow::intercomStop);
668
        connect(this, &MainWindow::sigIntercomSpkLevel, this, &MainWindow::intercomSpkLevel);
669
        connect(this, &MainWindow::sigIintercomMicLevel, this, &MainWindow::intercomMicLevel);
670
        connect(this, &MainWindow::sigIntercomMicMute, this, &MainWindow::intercomMicMute);
446 andreas 671
        connect(qApp, &QGuiApplication::applicationStateChanged, this, &MainWindow::onAppStateChanged);
672
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
673
        QScreen *screen = QGuiApplication::primaryScreen();
674
        connect(screen, &QScreen::orientationChanged, this, &MainWindow::onScreenOrientationChanged);
675
        connect(this, &MainWindow::sigActivateSettings, this, &MainWindow::activateSettings);
676
#endif
677
    }
678
    catch (std::exception& e)
679
    {
680
        MSG_ERROR("Connection error: " << e.what());
681
    }
682
    catch(...)
683
    {
684
        MSG_ERROR("Unexpected exception occured [MainWindow::MainWindow()]");
685
    }
686
 
687
    setUnifiedTitleAndToolBarOnMac(true);
688
#ifdef Q_OS_ANDROID
689
    // At least initialize the phone call listener
690
    if (gPageManager)
691
        gPageManager->initPhoneState();
692
 
693
    /*
694
     * In case this class was created not the first time, we initiate a small
695
     * thread to send the signal ApplicationActive to initiate the communication
696
     * with the controller again. This also starts the page manager thread
697
     * (TPageManager), which handles all elements of the surface.
698
     */
699
    if (_restart_ && gPageManager)
700
    {
701
        try
702
        {
703
            std::thread mThread = std::thread([=] { this->_signalState(Qt::ApplicationActive); });
704
            mThread.detach();   // We detach immediately to leave this method.
705
        }
706
        catch (std::exception& e)
707
        {
708
            MSG_ERROR("Error starting the thread to reinvoke communication!");
709
        }
710
        catch(...)
711
        {
712
            MSG_ERROR("Unexpected exception occured [MainWindow::MainWindow()]");
713
        }
714
    }
715
#endif
716
 
717
#ifdef Q_OS_IOS
718
    // To get the battery level periodicaly we setup a timer.
719
    if (!mIosBattery)
720
        mIosBattery = new TIOSBattery;
721
 
722
    mIosBattery->update();
723
 
724
    int left = mIosBattery->getBatteryLeft();
725
    int state = mIosBattery->getBatteryState();
726
    // At this point no buttons are registered and therefore the battery
727
    // state will not be visible. To have the state at the moment a button
728
    // is registered, we tell the page manager to store the values.
729
    gPageManager->setBattery(left, state);
730
    MSG_DEBUG("Battery state was set to " << left << "% and state " << state);
731
#endif  // Q_OS_IOS
732
 
733
    _restart_ = false;
734
}
735
 
736
MainWindow::~MainWindow()
737
{
738
    DECL_TRACER("MainWindow::~MainWindow()");
739
 
740
    killed = true;
741
    prg_stopped = true;
742
 
743
    disconnect(this, &MainWindow::sigDisplayButton, this, &MainWindow::displayButton);
744
    disconnect(this, &MainWindow::sigDisplayViewButton, this, &MainWindow::displayViewButton);
745
    disconnect(this, &MainWindow::sigAddViewButtonItems, this, &MainWindow::addViewButtonItems);
746
    disconnect(this, &MainWindow::sigSetPage, this, &MainWindow::setPage);
747
    disconnect(this, &MainWindow::sigSetSubPage, this, &MainWindow::setSubPage);
748
    disconnect(this, &MainWindow::sigSetBackground, this, &MainWindow::setBackground);
749
    disconnect(this, &MainWindow::sigDropPage, this, &MainWindow::dropPage);
750
    disconnect(this, &MainWindow::sigDropSubPage, this, &MainWindow::dropSubPage);
751
    disconnect(this, &MainWindow::sigPlayVideo, this, &MainWindow::playVideo);
752
    disconnect(this, &MainWindow::sigInputText, this, &MainWindow::inputText);
753
    disconnect(this, &MainWindow::sigListBox, this, &MainWindow::listBox);
754
    disconnect(this, &MainWindow::sigKeyboard, this, &MainWindow::showKeyboard);
755
    disconnect(this, &MainWindow::sigKeypad, this, &MainWindow::showKeypad);
756
    disconnect(this, &MainWindow::sigShowSetup, this, &MainWindow::showSetup);
757
    disconnect(this, &MainWindow::sigPlaySound, this, &MainWindow::playSound);
758
    disconnect(this, &MainWindow::sigDropButton, this, &MainWindow::dropButton);
759
    disconnect(this, &MainWindow::sigSetVisible, this, &MainWindow::SetVisible);
760
    disconnect(this, &MainWindow::sigSendVirtualKeys, this, &MainWindow::sendVirtualKeys);
761
    disconnect(this, &MainWindow::sigShowPhoneDialog, this, &MainWindow::showPhoneDialog);
762
    disconnect(this, &MainWindow::sigSetPhoneNumber, this, &MainWindow::setPhoneNumber);
763
    disconnect(this, &MainWindow::sigSetPhoneStatus, this, &MainWindow::setPhoneStatus);
764
    disconnect(this, &MainWindow::sigSetPhoneState, this, &MainWindow::setPhoneState);
765
    disconnect(this, &MainWindow::sigRepaintWindows, this, &MainWindow::repaintWindows);
766
    disconnect(this, &MainWindow::sigToFront, this, &MainWindow::toFront);
767
    disconnect(this, &MainWindow::sigOnProgressChanged, this, &MainWindow::onProgressChanged);
768
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
769
    disconnect(this, &MainWindow::sigSetSizeMainWindow, this, &MainWindow::setSizeMainWindow);
770
#endif
771
    disconnect(this, &MainWindow::sigDownloadSurface, this, &MainWindow::downloadSurface);
772
    disconnect(this, &MainWindow::sigDisplayMessage, this, &MainWindow::displayMessage);
773
    disconnect(this, &MainWindow::sigFileDialog, this, &MainWindow::fileDialog);
774
    disconnect(this, &MainWindow::sigStartWait, this, &MainWindow::startWait);
775
    disconnect(this, &MainWindow::sigStopWait, this, &MainWindow::stopWait);
776
    disconnect(this, &MainWindow::sigPageFinished, this, &MainWindow::pageFinished);
777
    disconnect(qApp, &QGuiApplication::applicationStateChanged, this, &MainWindow::onAppStateChanged);
778
 
779
#ifdef Q_OS_IOS
780
    if (mSource)
781
    {
782
        delete mSource;
783
        mSource = nullptr;
784
    }
785
#endif
786
    if (mMediaPlayer)
787
    {
788
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
789
        delete mAudioOutput;
790
#endif
791
        delete mMediaPlayer;
792
    }
793
 
794
    if (gAmxNet && !gAmxNet->isStopped())
795
        gAmxNet->stop();
796
 
797
    if (mToolbar)
798
    {
799
        removeToolBar(mToolbar);
800
        mToolbar = nullptr;
801
    }
802
 
803
    isRunning = false;
804
#ifdef Q_OS_IOS
805
    if (mIosRotate)
806
        mIosRotate->automaticRotation(true);
807
 
808
    if (mIosBattery)
809
    {
810
        delete mIosBattery;
811
        mIosBattery = nullptr;
812
    }
813
 
814
    if (mIosRotate)
815
        delete mIosRotate;
816
#endif
817
 
818
    if (mGestureFilter)
819
    {
820
        disconnect(mGestureFilter, &TQGestureFilter::gestureEvent, this, &MainWindow::onGestureEvent);
821
        delete mGestureFilter;
822
    }
823
}
824
 
825
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
826
/**
827
 * @brief Small thread to invoke the initialization on an Android device.
828
 *
829
 * On Android devices the signal ApplicationActive is not send if the class
830
 * \p MainWindow is destroyed and recreated. Therefore we need this little
831
 * helper to send the signal when the class is initialized.
832
 *
833
 * @param state     This defines the signal to send.
834
 */
835
void MainWindow::_signalState(Qt::ApplicationState state)
836
{
837
    DECL_TRACER("MainWindow::_signalState(Qt::ApplicationState state)");
838
 
839
    std::this_thread::sleep_for(std::chrono::seconds(1));   // Wait a second
840
    onAppStateChanged(state);
841
}
842
 
843
void MainWindow::_orientationChanged(int orientation)
844
{
845
    DECL_TRACER("MainWindow::_orientationChanged(int orientation)");
846
 
847
    if (gPageManager && gPageManager->getSettings()->isPortrait())  // portrait?
848
    {
849
        if (orientation == O_REVERSE_PORTRAIT && mOrientation != Qt::InvertedPortraitOrientation)
850
        {
851
            _setOrientation((J_ORIENTATION)orientation);
852
            mOrientation = Qt::InvertedPortraitOrientation;
853
        }
854
        else if (orientation == O_PORTRAIT && mOrientation != Qt::PortraitOrientation)
855
        {
856
            _setOrientation((J_ORIENTATION)orientation);
857
            mOrientation = Qt::PortraitOrientation;
858
        }
859
    }
860
    else
861
    {
862
        if (orientation == O_REVERSE_LANDSCAPE && mOrientation != Qt::InvertedLandscapeOrientation)
863
        {
864
            _setOrientation((J_ORIENTATION)orientation);
865
            mOrientation = Qt::InvertedLandscapeOrientation;
866
        }
867
        else if (orientation == O_LANDSCAPE && mOrientation != Qt::LandscapeOrientation)
868
        {
869
            _setOrientation((J_ORIENTATION)orientation);
870
            mOrientation = Qt::LandscapeOrientation;
871
        }
872
    }
873
}
874
 
875
void MainWindow::_activateSettings(const std::string& oldNetlinx, int oldPort, int oldChannelID, const std::string& oldSurface, bool oldToolbarSuppress, bool oldToolbarForce)
876
{
877
    DECL_TRACER("MainWindow::_activateSettings(const std::string& oldNetlinx, int oldPort, int oldChannelID, const std::string& oldSurface, bool oldToolbarSuppress, bool oldToolbarForce)");
878
 
879
    if (!mHasFocus)
880
        return;
881
 
882
    emit sigActivateSettings(oldNetlinx, oldPort, oldChannelID, oldSurface, oldToolbarSuppress, oldToolbarForce);
883
}
884
 
885
/**
886
 * @brief MainWindow::activateSettings
887
 * This method activates some urgent settings. It is called on Android and IOS
888
 * after the setup dialog was closed. The method expects some values taken
889
 * immediately before the setup dialog was started. If takes some actions like
890
 * downloading a surface when the setting for it changed or removes the
891
 * toolbar on the right if the user reuqsted it.
892
 *
893
 * @param oldNetlinx        The IP or name of the Netlinx
894
 * @param oldPort           The network port number used to connect to Netlinx
895
 * @param oldChannelID      The channel ID TPanel uses to identify against the
896
 *                          Netlinx.
897
 * @param oldSurface        The name of theprevious TP4 file.
898
 * @param oldToolbarSuppress    State of toolbar suppress switch
899
 * @param oldToolbarForce   The state of toolbar force switch
900
 */
901
void MainWindow::activateSettings(const std::string& oldNetlinx, int oldPort, int oldChannelID, const std::string& oldSurface, bool oldToolbarSuppress, bool oldToolbarForce)
902
{
903
    DECL_TRACER("MainWindow::activateSettings(const std::string& oldNetlinx, int oldPort, int oldChannelID, const std::string& oldSurface, bool oldToolbarSuppress, bool oldToolbarForce)");
904
 
905
#ifdef Q_OS_IOS
906
    TConfig cf(TConfig::getConfigPath() + "/" + TConfig::getConfigFileName());
907
#endif
908
    bool rebootAnyway = false;
909
    bool doDownload = false;
910
    string newSurface = TConfig::getFtpSurface();
911
 
912
    if (!TConfig::getToolbarSuppress() && oldToolbarForce != TConfig::getToolbarForce())
913
    {
914
        QMessageBox msgBox(this);
915
        msgBox.setText("The change for the visibility of the toolbar will be active on the next start of TPanel!");
916
        msgBox.exec();
917
    }
918
    else if (oldToolbarSuppress != TConfig::getToolbarSuppress() && TConfig::getToolbarSuppress())
919
    {
920
        if (mToolbar)
921
        {
922
            mToolbar->close();
923
            delete mToolbar;
924
            mToolbar = nullptr;
925
        }
926
    }
927
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
928
    if (newSurface != oldSurface || TTPInit::haveSystemMarker())
929
#else
930
    time_t dlTime = TConfig::getFtpDownloadTime();
931
    time_t actTime = time(NULL);
932
 
933
    if (newSurface != oldSurface || dlTime == 0 || dlTime < (actTime - 60))
934
#endif
935
    {
936
        MSG_DEBUG("Surface should be downloaded (Old: " << oldSurface << ", New: " << newSurface << ")");
937
 
938
        QMessageBox msgBox(this);
939
        msgBox.setText(QString("Should the surface <b>") + newSurface.c_str() + "</b> be installed?");
940
        msgBox.addButton(QMessageBox::Yes);
941
        msgBox.addButton(QMessageBox::No);
942
        int ret = msgBox.exec();
943
 
944
        if (ret == QMessageBox::Yes)
945
        {
946
            doDownload = true;
947
            TTPInit tpinit;
948
            std::vector<TTPInit::FILELIST_t> mFileList;
949
            // Get the list of TP4 files from NetLinx, if there are any.
950
            TQtWait waitBox(this, string("Please wait while I'm looking at the disc of Netlinx (") + TConfig::getController().c_str() + ") for TP4 files ...");
951
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
952
            waitBox.setScaleFactor(mScaleFactor);
953
            waitBox.doResize();
954
            waitBox.start();
955
#endif
956
            tpinit.setPath(TConfig::getProjectPath());
957
            tpinit.regCallbackProcessEvents(bind(&MainWindow::runEvents, this));
958
            tpinit.regCallbackProgressBar(bind(&MainWindow::_onProgressChanged, this, std::placeholders::_1));
959
            mFileList = tpinit.getFileList(".tp4");
960
            bool found = false;
961
 
962
            if (mFileList.size() > 0)
963
            {
964
                vector<TTPInit::FILELIST_t>::iterator iter;
965
 
966
                for (iter = mFileList.begin(); iter != mFileList.end(); ++iter)
967
                {
968
                    if (iter->fname == newSurface)
969
                    {
970
                        tpinit.setFileSize(iter->size);
971
                        found = true;
972
                        break;
973
                    }
974
                }
975
            }
976
 
977
            waitBox.end();
978
 
979
            if (found)
980
            {
981
                string msg = "Loading file <b>" + newSurface + "</b>.";
982
                MSG_DEBUG("Download of surface " << newSurface << " was forced!");
983
 
984
                downloadBar(msg, this);
985
 
986
                if (tpinit.loadSurfaceFromController(true))
987
                    rebootAnyway = true;
988
 
989
                mDownloadBar->close();
990
                mBusy = false;
991
            }
992
            else
993
            {
994
                MSG_PROTOCOL("The surface " << newSurface << " does not exist on NetLinx or the NetLinx " << TConfig::getController() << " was not found!");
995
                displayMessage("The surface " + newSurface + " does not exist on NetLinx or the NetLinx " + TConfig::getController() + " was not found!", "Information");
996
            }
997
        }
998
    }
999
 
1000
    if (doDownload &&
1001
        (TConfig::getController() != oldNetlinx ||
1002
        TConfig::getChannel() != oldChannelID ||
1003
        TConfig::getPort() != oldPort || rebootAnyway))
1004
    {
1005
        // Start over by exiting this class
1006
        MSG_INFO("Program will start over!");
1007
        _restart_ = true;
1008
        prg_stopped = true;
1009
        killed = true;
1010
 
1011
        if (gAmxNet)
1012
            gAmxNet->stop();
1013
 
1014
        close();
1015
    }
1016
#ifdef Q_OS_ANDROID
1017
    else
1018
    {
1019
        TConfig cf(TConfig::getConfigPath() + "/" + TConfig::getConfigFileName());
1020
    }
1021
#endif
1022
}
1023
 
1024
/**
1025
 * @brief MainWindow::_freezeWorkaround: A workaround for the screen freeze.
1026
 * On Mobiles the screen sometimes stay frozen after the application state
1027
 * changes to ACTIVE or some yet unidentified things happened.
1028
 * The workaround produces a faked geometry change which makes the Qt framework
1029
 * to reattach to the screen.
1030
 * There may be situations where this workaround could trigger a repaint of all
1031
 * objects on the screen but then the surface is still frozen. At the moment of
1032
 * writing this comment I have no workaround or even an explanation for this.
1033
 */
1034
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1035
/**
1036
 * @brief MainWindow::_freezeWorkaround
1037
 * This hack was made from Thomas Andersen. You'll find it at:
1038
 * https://bugreports.qt.io/browse/QTBUG-76142
1039
 */
1040
void MainWindow::_freezeWorkaround()
1041
{
1042
    DECL_TRACER("MainWindow::_freezeWorkaround()");
1043
 
1044
    QScreen* scr = QGuiApplication::screens().first();
1045
    QPlatformScreen* l_pScr = scr->handle(); /*QAndroidPlatformScreen*/
1046
    QRect l_geomHackAdjustedRect = l_pScr->availableGeometry();
1047
    QRect l_geomHackRect = l_geomHackAdjustedRect;
1048
    l_geomHackAdjustedRect.adjust(0, 0, 0, 5);
1049
    QMetaObject::invokeMethod(dynamic_cast<QObject*>(l_pScr), "setAvailableGeometry", Qt::DirectConnection, Q_ARG( const QRect &, l_geomHackAdjustedRect ));
1050
    QMetaObject::invokeMethod(dynamic_cast<QObject*>(l_pScr), "setAvailableGeometry", Qt::QueuedConnection, Q_ARG( const QRect &, l_geomHackRect ));
1051
}
1052
#endif  // QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1053
#endif  // Q_OS_ANDROID || Q_OS_IOS
1054
 
1055
void MainWindow::_repaintWindows()
1056
{
1057
    DECL_TRACER("MainWindow::_repaintWindows()");
1058
 
1059
    if (mHasFocus)
1060
        emit sigRepaintWindows();
1061
}
1062
 
1063
void MainWindow::_toFront(ulong handle)
1064
{
1065
    DECL_TRACER("MainWindow::_toFront(ulong handle)");
1066
 
1067
    if (mHasFocus)
1068
        emit sigToFront(handle);
1069
}
1070
 
1071
void MainWindow::_downloadSurface(const string &file, size_t size)
1072
{
1073
    DECL_TRACER("MainWindow::_downloadSurface(const string &file, size_t size)");
1074
 
1075
    if (mHasFocus)
1076
        emit sigDownloadSurface(file, size);
1077
}
1078
 
1079
void MainWindow::_startWait(const string& text)
1080
{
1081
    DECL_TRACER("MainWindow::_startWait(const string& text)");
1082
 
1083
    emit sigStartWait(text);
1084
}
1085
 
1086
void MainWindow::_stopWait()
1087
{
1088
    DECL_TRACER("MainWindow::_stopWait()");
1089
 
1090
    emit sigStopWait();
1091
}
1092
 
1093
void MainWindow::_pageFinished(uint handle)
1094
{
1095
    DECL_TRACER("MainWindow::_pageFinished(uint handle)");
1096
 
1097
    emit sigPageFinished(handle);
1098
}
1099
 
1100
/**
1101
 * @brief MainWindow::closeEvent called when the application receives an exit event.
1102
 *
1103
 * If the user clicks on the exit icon or on the menu point _Exit_ this method
1104
 * is called. It makes sure everything is written to the configuration file
1105
 * and accepts the evernt.
1106
 *
1107
 * @param event The exit event
1108
 */
1109
void MainWindow::closeEvent(QCloseEvent *event)
1110
{
1111
    DECL_TRACER("MainWindow::closeEvent(QCloseEvent *event)");
1112
#ifdef __ANDROID__
1113
    __android_log_print(ANDROID_LOG_DEBUG,"tpanel","Close event; settingsChanged=%s", (settingsChanged ? "true":"false"));
1114
#endif
1115
    if (settingsChanged)
1116
    {
1117
        writeSettings();
1118
        event->accept();
1119
    }
1120
    else
1121
    {
1122
        prg_stopped = true;
1123
        killed = true;
1124
        MSG_INFO("Program will stop!");
1125
#ifdef __ANDROID__
1126
        if (gPageManager)
1127
            gPageManager->stopNetworkState();
1128
#endif
1129
        event->accept();
1130
    }
1131
}
1132
 
1133
/**
1134
 * @brief MainWindow::event Looks for a gesture
1135
 * @param event The event occured
1136
 * @return TRUE if event was accepted
1137
 */
1138
bool MainWindow::event(QEvent* event)
1139
{
1140
    if (event->type() == QEvent::Gesture)
1141
        return gestureEvent(static_cast<QGestureEvent*>(event));
1142
 
1143
    return QMainWindow::event(event);
1144
}
1145
 
1146
/**
1147
 * @brief MainWindow::gestureEvent handles a pinch event
1148
 * If a pinch event occured where the scale factor increased, the settings
1149
 * dialog is called. This exists for devices, where the left toolbox is not
1150
 * visible.
1151
 * @param event The guesture occured
1152
 * @return FALSE
1153
 */
1154
bool MainWindow::gestureEvent(QGestureEvent* event)
1155
{
1156
    DECL_TRACER("MainWindow::gestureEvent(QGestureEvent* event)");
1157
 
1158
    if (QGesture *pinch = event->gesture(Qt::PinchGesture))
1159
    {
1160
        QPinchGesture *pg = static_cast<QPinchGesture *>(pinch);
1161
#ifdef QT_DEBUG
1162
        string gs;
1163
 
1164
        switch(pg->state())
1165
        {
1166
            case Qt::NoGesture:         gs.assign("no gesture"); break;
1167
            case Qt::GestureStarted:    gs.assign("gesture started"); break;
1168
            case Qt::GestureUpdated:    gs.assign("gesture updated"); break;
1169
            case Qt::GestureFinished:   gs.assign("gesture finished"); break;
1170
            case Qt::GestureCanceled:   gs.assign("gesture canceled"); break;
1171
        }
1172
 
1173
        MSG_DEBUG("PinchGesture state " << gs << " detected");
1174
#endif
1175
        if (pg->state() == Qt::GestureFinished)
1176
        {
1177
            MSG_DEBUG("total scale: " << pg->totalScaleFactor() << ", scale: " << pg->scaleFactor() << ", last scale: " << pg->lastScaleFactor());
1178
 
1179
            if (pg->totalScaleFactor() > pg->scaleFactor())
1180
                settings();
1181
 
1182
            return true;
1183
        }
1184
    }
1185
    else if (QGesture *swipe = event->gesture(Qt::SwipeGesture))
1186
    {
1187
        if (!gPageManager)
1188
            return false;
1189
 
1190
        QSwipeGesture *sw = static_cast<QSwipeGesture *>(swipe);
1191
        MSG_DEBUG("Swipe gesture detected.");
1192
 
1193
        if (sw->state() == Qt::GestureFinished)
1194
        {
1195
            if (sw->horizontalDirection() == QSwipeGesture::Left)
1196
                gPageManager->onSwipeEvent(TPageManager::SW_LEFT);
1197
            else if (sw->horizontalDirection() == QSwipeGesture::Right)
1198
                gPageManager->onSwipeEvent(TPageManager::SW_RIGHT);
1199
            else if (sw->verticalDirection() == QSwipeGesture::Up)
1200
                gPageManager->onSwipeEvent(TPageManager::SW_UP);
1201
            else if (sw->verticalDirection() == QSwipeGesture::Down)
1202
                gPageManager->onSwipeEvent(TPageManager::SW_DOWN);
1203
 
1204
            return true;
1205
        }
1206
    }
1207
 
1208
    return false;
1209
}
1210
 
1211
/**
1212
 * @brief MainWindow::mousePressEvent catches the event Qt::LeftButton.
1213
 *
1214
 * If the user presses the left mouse button somewhere in the main window, this
1215
 * method is triggered. It retrieves the position of the mouse pointer and
1216
 * sends it to the page manager TPageManager.
1217
 *
1218
 * @param event The event
1219
 */
1220
void MainWindow::mousePressEvent(QMouseEvent* event)
1221
{
1222
    DECL_TRACER("MainWindow::mousePressEvent(QMouseEvent* event)");
1223
 
1224
    if (!gPageManager)
1225
        return;
1226
 
1227
    if(event->button() == Qt::LeftButton)
1228
    {
1229
        int nx = 0, ny = 0;
1230
#ifdef Q_OS_IOS
1231
        if (mHaveNotchPortrait && gPageManager->getSettings()->isPortrait())
1232
        {
1233
            nx = mNotchPortrait.left();
1234
            ny = mNotchPortrait.top();
1235
        }
1236
        else if (mHaveNotchLandscape && gPageManager->getSettings()->isLandscape())
1237
        {
1238
            nx = mNotchLandscape.left();
1239
            ny = mNotchLandscape.top();
1240
        }
1241
        else
1242
        {
1243
            MSG_WARNING("Have no notch distances!");
1244
        }
1245
#endif
1246
        int x = static_cast<int>(event->position().x()) - nx;
1247
        int y = static_cast<int>(event->position().y()) - ny;
1248
        MSG_DEBUG("Mouse press coordinates: x: " << event->position().x() << ", y: " << event->position().y() << " [new x: " << x << ", y: " << y << " -- \"notch\" nx: " << nx << ", ny: " << ny << "]");
1249
 
1250
        mLastPressX = x;
1251
        mLastPressY = y;
1252
/*
1253
        QWidget *w = childAt(event->x(), event->y());
1254
 
1255
        if (w)
1256
        {
1257
            MSG_DEBUG("Object " << w->objectName().toStdString() << " is under mouse cursor.");
1258
            QObject *par = w->parent();
1259
 
1260
            if (par)
1261
            {
1262
                MSG_DEBUG("The parent is " << par->objectName().toStdString());
1263
 
1264
                if (par->objectName().startsWith("Item_"))
1265
                {
1266
                    QObject *ppar = par->parent();
1267
 
1268
                    if (ppar)
1269
                    {
1270
                        MSG_DEBUG("The pparent is " << ppar->objectName().toStdString());
1271
 
1272
                        if (ppar->objectName().startsWith("View_"))
1273
                        {
1274
                            QMouseEvent *mev = new QMouseEvent(event->type(), event->localPos(), event->globalPos(), event->button(), event->buttons(), event->modifiers());
1275
                            QApplication::postEvent(ppar, mev);
1276
                            return;
1277
                        }
1278
                    }
1279
                }
1280
            }
1281
        }
1282
*/
449 andreas 1283
        if (isScaled())
446 andreas 1284
        {
1285
            x = static_cast<int>(static_cast<double>(x) / mScaleFactor);
1286
            y = static_cast<int>(static_cast<double>(y) / mScaleFactor);
1287
        }
1288
 
1289
        gPageManager->mouseEvent(x, y, true);
1290
        mTouchStart = std::chrono::steady_clock::now();
1291
        mTouchX = mLastPressX;
1292
        mTouchY = mLastPressY;
1293
        event->accept();
1294
    }
1295
    else if (event->button() == Qt::MiddleButton)
1296
    {
1297
        event->accept();
1298
        settings();
1299
    }
1300
    else
1301
        QMainWindow::mousePressEvent(event);
1302
}
1303
 
1304
/**
1305
 * @brief MainWindow::mouseReleaseEvent catches the event Qt::LeftButton.
1306
 *
1307
 * If the user releases the left mouse button somewhere in the main window, this
1308
 * method is triggered. It retrieves the position of the mouse pointer and
1309
 * sends it to the page manager TPageManager.
1310
 *
1311
 * @param event The event
1312
 */
1313
void MainWindow::mouseReleaseEvent(QMouseEvent* event)
1314
{
1315
    DECL_TRACER("MainWindow::mouseReleaseEvent(QMouseEvent* event)");
1316
 
1317
    if (!gPageManager)
1318
        return;
1319
 
1320
    if(event->button() == Qt::LeftButton)
1321
    {
1322
        int nx = 0, ny = 0;
1323
#ifdef Q_OS_IOS
1324
        if (mHaveNotchPortrait && gPageManager->getSettings()->isPortrait())
1325
        {
1326
            nx = mNotchPortrait.left();
1327
            ny = mNotchPortrait.top();
1328
        }
1329
        else if (mHaveNotchLandscape && gPageManager->getSettings()->isLandscape())
1330
        {
1331
            nx = mNotchLandscape.left();
1332
            ny = mNotchLandscape.top();
1333
        }
1334
#endif
1335
        int x = ((mLastPressX >= 0) ? mLastPressX : (static_cast<int>(event->position().x()) - nx));
1336
        int y = ((mLastPressY >= 0) ? mLastPressY : (static_cast<int>(event->position().y()) - ny));
1337
        MSG_DEBUG("Mouse press coordinates: x: " << event->position().x() << ", y: " << event->position().y());
1338
        mLastPressX = mLastPressY = -1;
1339
/*
1340
        QWidget *w = childAt(event->x(), event->y());
1341
 
1342
        if (w)
1343
        {
1344
            MSG_DEBUG("Object " << w->objectName().toStdString() << " is under mouse cursor.");
1345
            QObject *par = w->parent();
1346
 
1347
            if (par)
1348
            {
1349
                MSG_DEBUG("The parent is " << par->objectName().toStdString());
1350
 
1351
                if (par->objectName().startsWith("Item_"))
1352
                {
1353
                    QObject *ppar = par->parent();
1354
 
1355
                    if (ppar)
1356
                    {
1357
                        MSG_DEBUG("The pparent is " << ppar->objectName().toStdString());
1358
 
1359
                        if (ppar->objectName().startsWith("View_"))
1360
                        {
1361
                            QMouseEvent *mev = new QMouseEvent(event->type(), event->localPos(), event->globalPos(), event->button(), event->buttons(), event->modifiers());
1362
                            QApplication::postEvent(ppar, mev);
1363
                            return;
1364
                        }
1365
                    }
1366
                }
1367
            }
1368
        }
1369
*/
449 andreas 1370
        if (isScaled())
446 andreas 1371
        {
1372
            x = static_cast<int>(static_cast<double>(x) / mScaleFactor);
1373
            y = static_cast<int>(static_cast<double>(y) / mScaleFactor);
1374
        }
1375
 
1376
        gPageManager->mouseEvent(x, y, false);
1377
        std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
1378
        std::chrono::nanoseconds difftime = end - mTouchStart;
1379
        std::chrono::milliseconds msecs = std::chrono::duration_cast<std::chrono::milliseconds>(difftime);
1380
 
1381
        if (msecs.count() < 100)    // 1/10 of a second
1382
        {
1383
            MSG_DEBUG("Time was too short: " << msecs.count());
1384
            event->accept();
1385
            return;
1386
        }
1387
 
1388
        x = static_cast<int>(event->position().x());
1389
        y = static_cast<int>(event->position().y());
449 andreas 1390
        int width = scale(gPageManager->getSettings()->getWidth());
1391
        int height = scale(gPageManager->getSettings()->getHeight());
446 andreas 1392
        MSG_DEBUG("Coordinates: x1=" << mTouchX << ", y1=" << mTouchY << ", x2=" << x << ", y2=" << y << ", width=" << width << ", height=" << height);
1393
 
1394
        if (mTouchX < x && (x - mTouchX) > (width / 3))
1395
            gPageManager->onSwipeEvent(TPageManager::SW_RIGHT);
1396
        else if (x < mTouchX && (mTouchX - x) > (width / 3))
1397
            gPageManager->onSwipeEvent(TPageManager::SW_LEFT);
1398
        else if (mTouchY < y && (y - mTouchY) > (height / 3))
1399
            gPageManager->onSwipeEvent(TPageManager::SW_DOWN);
1400
        else if (y < mTouchY && (mTouchY - y) > (height / 3))
1401
            gPageManager->onSwipeEvent(TPageManager::SW_UP);
1402
 
1403
        event->accept();
1404
    }
1405
    else
1406
        QMainWindow::mouseReleaseEvent(event);
1407
}
1408
 
1409
void MainWindow::mouseMoveEvent(QMouseEvent* event)
1410
{
1411
    DECL_TRACER("MainWindow::mouseMoveEvent(QMouseEvent* event)");
1412
 
1413
    if (!gPageManager)
1414
        return;
1415
 
1416
    QWidget *w = childAt(event->position().x(), event->position().y());
1417
 
1418
    if (w)
1419
    {
1420
        MSG_DEBUG("Object " << w->objectName().toStdString() << " is under mouse cursor.");
1421
 
1422
        gPageManager->mouseMoveEvent(event->position().x(), event->position().y());
1423
        mLastPressX = event->position().x();
1424
        mLastPressY = event->position().y();
1425
    }
1426
/*        QObject *par = w->parent();
1427
 
1428
        if (par)
1429
        {
1430
            MSG_DEBUG("The parent is " << par->objectName().toStdString());
1431
 
1432
            if (par->objectName().startsWith("Item_"))
1433
            {
1434
                QObject *ppar = par->parent();
1435
 
1436
                if (ppar)
1437
                {
1438
                    MSG_DEBUG("The pparent is " << ppar->objectName().toStdString());
1439
 
1440
                    if (ppar->objectName().startsWith("View_"))
1441
                    {
1442
                        QMouseEvent *mev = new QMouseEvent(event->type(), event->localPos(), event->globalPos(), event->button(), event->buttons(), event->modifiers());
1443
                        QApplication::postEvent(ppar, mev);
1444
                        return;
1445
                    }
1446
                }
1447
            }
1448
        }
1449
    }
1450
*/
1451
}
1452
 
1453
void MainWindow::keyPressEvent(QKeyEvent *event)
1454
{
1455
    DECL_TRACER("MainWindow::keyPressEvent(QKeyEvent *event)");
1456
 
1457
    if (event && event->key() == Qt::Key_Back && !mToolbar)
1458
    {
1459
        QMessageBox msgBox(this);
1460
        msgBox.setText("Select what to do next:");
1461
        msgBox.addButton("Quit", QMessageBox::AcceptRole);
1462
        msgBox.addButton("Setup", QMessageBox::RejectRole);
1463
        msgBox.addButton("Cancel", QMessageBox::ResetRole);
1464
        int ret = msgBox.exec();
1465
 
1466
        if (ret == QMessageBox::Accepted)   // This is correct! QT seems to change here the buttons.
1467
        {
1468
            showSetup();
1469
            event->accept();
1470
            return;
1471
        }
1472
        else if (ret == QMessageBox::Rejected)  // This is correct! QT seems to change here the buttons.
1473
        {
1474
            event->accept();
1475
            close();
1476
        }
1477
    }
1478
    else
1479
        QMainWindow::keyPressEvent(event);
1480
}
1481
 
1482
void MainWindow::keyReleaseEvent(QKeyEvent *event)
1483
{
1484
    DECL_TRACER("MainWindow::keyReleaseEvent(QKeyEvent *event)");
1485
 
1486
    QMainWindow::keyReleaseEvent(event);
1487
}
1488
 
1489
/**
1490
 * @brief MainWindow::onScreenOrientationChanged sets invers or normal orientation.
1491
 * This method sets according to the actual set orientation the invers
1492
 * orientations or switches back to normal orientation.
1493
 * For example: When the orientation is set to portrait and the device is turned
1494
 * to top down, then the orientation is set to invers portrait.
1495
 * @param ori   The detected orientation
1496
 */
1497
void MainWindow::onScreenOrientationChanged(Qt::ScreenOrientation ori)
1498
{
1499
    DECL_TRACER("MainWindow::onScreenOrientationChanged(int ori)");
1500
#if defined(QT_DEBUG) && (defined(Q_OS_IOS) || defined(Q_OS_ANDROID))
1501
    MSG_DEBUG("Orientation changed to " << orientationToString(ori) << " (mOrientation: " << orientationToString(mOrientation) << ")");
1502
#endif
1503
    if (!gPageManager)
1504
        return;
1505
 
1506
    if (gPageManager->getSettings()->isPortrait())
1507
    {
1508
#ifdef Q_OS_IOS
1509
        if (!mHaveNotchPortrait)
1510
            setNotch();
1511
#endif
1512
        if (ori == Qt::PortraitOrientation || ori == Qt::InvertedPortraitOrientation)
1513
        {
1514
#ifdef Q_OS_IOS
1515
            if (mSensor)
1516
                mSensor->setCurrentOrientation(ori);
1517
#endif
1518
            if (mOrientation == ori)
1519
                return;
1520
 
1521
            mOrientation = ori;
1522
        }
1523
        else if (mOrientation != Qt::PortraitOrientation && mOrientation != Qt::InvertedPortraitOrientation)
1524
            mOrientation = Qt::PortraitOrientation;
1525
    }
1526
    else
1527
    {
1528
#ifdef Q_OS_IOS
1529
        if (!mHaveNotchLandscape)
1530
            setNotch();
1531
#endif
1532
        if (ori == Qt::LandscapeOrientation || ori == Qt::InvertedLandscapeOrientation)
1533
        {
1534
#ifdef Q_OS_IOS
1535
            if (mSensor)
1536
                mSensor->setCurrentOrientation(ori);
1537
#endif
1538
            if (mOrientation == ori)
1539
                return;
1540
 
1541
            mOrientation = ori;
1542
        }
1543
        else if (mOrientation != Qt::LandscapeOrientation && mOrientation != Qt::InvertedLandscapeOrientation)
1544
            mOrientation = Qt::LandscapeOrientation;
1545
    }
1546
 
1547
    J_ORIENTATION jori = O_UNDEFINED;
1548
 
1549
    switch(mOrientation)
1550
    {
1551
        case Qt::LandscapeOrientation:          jori = O_LANDSCAPE; break;
1552
        case Qt::InvertedLandscapeOrientation:  jori = O_REVERSE_LANDSCAPE; break;
1553
        case Qt::PortraitOrientation:           jori = O_PORTRAIT; break;
1554
        case Qt::InvertedPortraitOrientation:   jori = O_REVERSE_PORTRAIT; break;
1555
        default:
1556
            return;
1557
    }
1558
 
1559
    _setOrientation(jori);
1560
#ifdef Q_OS_IOS
1561
    setNotch();
1562
#endif
1563
}
1564
#ifdef Q_OS_IOS
1565
/**
1566
 * @brief MainWindow::onPositionUpdated
1567
 * This method is a callback function for the Qt framework. It is called
1568
 * whenever the geo position changes. The position information is never really
1569
 * used and is implemented only to keep the application on IOS running in the
1570
 * background.
1571
 *
1572
 * @param update    A structure containing the geo position information.
1573
 */
1574
 
1575
void MainWindow::onPositionUpdated(const QGeoPositionInfo &update)
1576
{
1577
    DECL_TRACER("MainWindow::onPositionUpdated(const QGeoPositionInfo &update)");
1578
 
1579
    QGeoCoordinate coord = update.coordinate();
1580
    MSG_DEBUG("Geo location: " << coord.toString().toStdString());
1581
}
1582
 
1583
void MainWindow::onErrorOccurred(QGeoPositionInfoSource::Error positioningError)
1584
{
1585
    DECL_TRACER("MainWindow::onErrorOccurred(QGeoPositionInfoSource::Error positioningError)");
1586
 
1587
    switch(positioningError)
1588
    {
1589
        case QGeoPositionInfoSource::AccessError:
1590
            MSG_ERROR("The connection setup to the remote positioning backend failed because the application lacked the required privileges.");
1591
            mGeoHavePermission = false;
1592
        break;
1593
 
1594
        case QGeoPositionInfoSource::ClosedError:   MSG_ERROR("The remote positioning backend closed the connection, which happens for example in case the user is switching location services to off. As soon as the location service is re-enabled regular updates will resume."); break;
1595
        case QGeoPositionInfoSource::UnknownSourceError: MSG_ERROR("An unidentified error occurred."); break;
1596
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1597
        case QGeoPositionInfoSource::UpdateTimeoutError: MSG_ERROR("Current position could not be retrieved within the specified timeout."); break;
1598
#endif
1599
        default:
1600
            return;
1601
    }
1602
}
1603
#endif  // Q_OS_IOS
1604
/**
1605
 * @brief Displays or hides a phone dialog window.
1606
 * This method creates and displays a phone dialog window containing everything
1607
 * a simple phone needs. Depending on the parameter \p state the dialog is
1608
 * created or an existing dialog is closed.
1609
 * @param state     If TRUE the dialog is created or if it is not visible
1610
 * brought to front and is made visible.
1611
 * If this is FALSE an existing dialog window is destroid and disappears. If
1612
 * the window didn't exist nothing happens.
1613
 */
1614
void MainWindow::showPhoneDialog(bool state)
1615
{
1616
    DECL_TRACER("MainWindow::showPhoneDialog(bool state)");
1617
 
1618
    if (mPhoneDialog)
1619
    {
1620
        if (!state)
1621
        {
1622
            mPhoneDialog->close();
1623
            delete mPhoneDialog;
1624
            mPhoneDialog = nullptr;
1625
            return;
1626
        }
1627
 
1628
        if (!mPhoneDialog->isVisible())
1629
            mPhoneDialog->setVisible(true);
1630
 
1631
        return;
1632
    }
1633
 
1634
    if (!state)
1635
        return;
1636
 
1637
    mPhoneDialog = new TQtPhone(this);
1638
#if defined(Q_OS_ANDROID)
1639
    // On mobile devices we set the scale factor always because otherwise the
1640
    // dialog will be unusable.
1641
    mPhoneDialog->setScaleFactor(gScale);
1642
    mPhoneDialog->doResize();
1643
#endif
1644
    mPhoneDialog->open();
1645
}
1646
 
1647
/**
1648
 * Displays a phone number (can also be an URL) on a label in the phone dialog
1649
 * window.
1650
 * @param number    The string contains the phone number to display.
1651
 */
1652
void MainWindow::setPhoneNumber(const std::string& number)
1653
{
1654
    DECL_TRACER("MainWindow::setPhoneNumber(const std::string& number)");
1655
 
1656
    if (!mPhoneDialog)
1657
        return;
1658
 
1659
    mPhoneDialog->setPhoneNumber(number);
1660
}
1661
 
1662
/**
1663
 * Displays a message in the status line on the bottom of the phone dialog
1664
 * window.
1665
 * @param msg   The string conaining a message.
1666
 */
1667
void MainWindow::setPhoneStatus(const std::string& msg)
1668
{
1669
    DECL_TRACER("MainWindow::setPhoneStatus(const std::string& msg)");
1670
 
1671
    if (!mPhoneDialog)
1672
        return;
1673
 
1674
    mPhoneDialog->setPhoneStatus(msg);
1675
}
1676
 
1677
void MainWindow::setPhoneState(int state, int id)
1678
{
1679
    DECL_TRACER("MainWindow::setPhoneState(int state)");
1680
 
1681
    if (mPhoneDialog)
1682
        mPhoneDialog->setPhoneState(state, id);
1683
}
1684
 
1685
/**
1686
 * @brief MainWindow::createActions creates the toolbar on the right side.
1687
 */
1688
void MainWindow::createActions()
1689
{
1690
    DECL_TRACER("MainWindow::createActions()");
1691
 
1692
    // If the toolbar should not be visible at all we return here immediately.
1693
    if (TConfig::getToolbarSuppress())
1694
        return;
1695
 
1696
    // Add a mToolbar (on the right side)
1697
    mToolbar = new QToolBar(this);
1698
    QPalette palette(mToolbar->palette());
1699
    palette.setColor(QPalette::Window, QColorConstants::Svg::honeydew);
1700
    mToolbar->setPalette(palette);
1701
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
1702
    mToolbar->setAllowedAreas(Qt::RightToolBarArea);
1703
    mToolbar->setFloatable(false);
1704
    mToolbar->setMovable(false);
1705
#if defined(Q_OS_ANDROID) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1706
    if (isScaled())
1707
    {
1708
        int width = (int)((double)gPageManager->getSettings()->getWidth() * gScale);
1709
        int tbWidth = (int)(48.0 * gScale);
1710
        int icWidth = (int)(40.0 * gScale);
1711
 
1712
        if ((gFullWidth - width) < tbWidth && !TConfig::getToolbarForce())
1713
        {
1714
            delete mToolbar;
1715
            mToolbar = nullptr;
1716
            return;
1717
        }
1718
 
1719
        MSG_DEBUG("Icon size: " << icWidth << "x" << icWidth << ", Toolbar width: " << tbWidth);
1720
        QSize iSize(icWidth, icWidth);
1721
        mToolbar->setIconSize(iSize);
1722
    }
1723
#endif  // QT_VERSION
1724
#if (defined(Q_OS_ANDROID) || defined(Q_OS_IOS)) && QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1725
    if (isScaled())
1726
    {
1727
        int panwidth = (int)((double)gPageManager->getSettings()->getWidth() * gScale);
1728
        int toolwidth = mToolbar->width();
1729
 
1730
        if ((gFullWidth - panwidth) < toolwidth && !TConfig::getToolbarForce())
1731
        {
1732
            delete mToolbar;
1733
            mToolbar = nullptr;
1734
            return;
1735
        }
1736
    }
1737
#endif
1738
#else
1739
    mToolbar->setFloatable(true);
1740
    mToolbar->setMovable(true);
1741
    mToolbar->setAllowedAreas(Qt::RightToolBarArea | Qt::BottomToolBarArea);
1742
#endif  // defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
1743
    QAction *arrowUpAct = new QAction(QIcon(":/images/arrow_up.png"), tr("Up"), this);
1744
    connect(arrowUpAct, &QAction::triggered, this, &MainWindow::arrowUp);
1745
    mToolbar->addAction(arrowUpAct);
1746
 
1747
    QAction *arrowLeftAct = new QAction(QIcon(":/images/arrow_left.png"), tr("Left"), this);
1748
    connect(arrowLeftAct, &QAction::triggered, this, &MainWindow::arrowLeft);
1749
    mToolbar->addAction(arrowLeftAct);
1750
 
1751
    QAction *arrowRightAct = new QAction(QIcon(":/images/arrow_right.png"), tr("Right"), this);
1752
    connect(arrowRightAct, &QAction::triggered, this, &MainWindow::arrowRight);
1753
    mToolbar->addAction(arrowRightAct);
1754
 
1755
    QAction *arrowDownAct = new QAction(QIcon(":/images/arrow_down.png"), tr("Down"), this);
1756
    connect(arrowDownAct, &QAction::triggered, this, &MainWindow::arrowDown);
1757
    mToolbar->addAction(arrowDownAct);
1758
 
1759
    QAction *selectOkAct = new QAction(QIcon(":/images/ok.png"), tr("Ok"), this);
1760
    connect(selectOkAct, &QAction::triggered, this, &MainWindow::selectOk);
1761
    mToolbar->addAction(selectOkAct);
1762
 
1763
    mToolbar->addSeparator();
1764
 
1765
    QToolButton *btVolUp = new QToolButton(this);
1766
    btVolUp->setIcon(QIcon(":/images/vol_up.png"));
1767
    connect(btVolUp, &QToolButton::pressed, this, &MainWindow::volumeUpPressed);
1768
    connect(btVolUp, &QToolButton::released, this, &MainWindow::volumeUpReleased);
1769
    mToolbar->addWidget(btVolUp);
1770
 
1771
    QToolButton *btVolDown = new QToolButton(this);
1772
    btVolDown->setIcon(QIcon(":/images/vol_down.png"));
1773
    connect(btVolDown, &QToolButton::pressed, this, &MainWindow::volumeDownPressed);
1774
    connect(btVolDown, &QToolButton::released, this, &MainWindow::volumeDownReleased);
1775
    mToolbar->addWidget(btVolDown);
1776
/*
1777
    QAction *volMute = new QAction(QIcon(":/images/vol_mute.png"), tr("X"), this);
1778
    connect(volMute, &QAction::triggered, this, &MainWindow::volumeMute);
1779
    mToolbar->addAction(volMute);
1780
*/
1781
    mToolbar->addSeparator();
1782
    const QIcon settingsIcon = QIcon::fromTheme("settings-configure", QIcon(":/images/settings.png"));
1783
    QAction *settingsAct = new QAction(settingsIcon, tr("&Settings..."), this);
1784
    settingsAct->setStatusTip(tr("Change the settings"));
1785
    connect(settingsAct, &QAction::triggered, this, &MainWindow::settings);
1786
    mToolbar->addAction(settingsAct);
1787
 
1788
    const QIcon aboutIcon = QIcon::fromTheme("help-about", QIcon(":/images/info.png"));
1789
    QAction *aboutAct = new QAction(aboutIcon, tr("&About..."), this);
1790
    aboutAct->setShortcuts(QKeySequence::Open);
1791
    aboutAct->setStatusTip(tr("About this program"));
1792
    connect(aboutAct, &QAction::triggered, this, &MainWindow::about);
1793
    mToolbar->addAction(aboutAct);
1794
 
1795
    const QIcon exitIcon = QIcon::fromTheme("application-exit", QIcon(":/images/off.png"));
1796
    QAction *exitAct = mToolbar->addAction(exitIcon, tr("E&xit"), this, &QWidget::close);
1797
    exitAct->setShortcuts(QKeySequence::Quit);
1798
    exitAct->setStatusTip(tr("Exit the application"));
1799
 
1800
    addToolBar(Qt::RightToolBarArea, mToolbar);
1801
}
1802
 
1803
/**
1804
 * @brief MainWindow::settings initiates the configuration dialog.
1805
 */
1806
void MainWindow::settings()
1807
{
1808
    DECL_TRACER("MainWindow::settings()");
1809
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
1810
#ifdef Q_OS_ANDROID
1811
    if (gPageManager)
1812
    {
1813
        gPageManager->showSetup();
1814
        return;
1815
    }
1816
    else    // This "else" should never be executed!
1817
        displayMessage("<b>Fatal error</b>: An internal mandatory class was not initialized!<br>Unable to show setup dialog!", "Fatal error");
1818
#else
1819
    mIOSSettingsActive = true;
1820
    QASettings::openSettings();
1821
#endif
1822
#else
1823
    // Save some old values to decide whether to start over or not.
1824
    string oldHost = TConfig::getController();
1825
    int oldPort = TConfig::getPort();
1826
    int oldChannelID = TConfig::getChannel();
1827
    string oldSurface = TConfig::getFtpSurface();
1828
    bool oldToolbar = TConfig::getToolbarForce();
1829
    bool oldToolbarSuppress = TConfig::getToolbarSuppress();
1830
    // Initialize and open the settings dialog.
1831
    TQtSettings *dlg_settings = new TQtSettings(this);
1832
    int ret = dlg_settings->exec();
1833
    bool rebootAnyway = false;
1834
 
1835
    if ((ret && dlg_settings->hasChanged()) || (ret && dlg_settings->downloadForce()))
1836
    {
1837
        writeSettings();
1838
 
1839
        if (!TConfig::getToolbarSuppress() && oldToolbar != TConfig::getToolbarForce())
1840
        {
1841
            QMessageBox msgBox(this);
1842
            msgBox.setText("The change for the visibility of the toolbar will be active on the next start of TPanel!");
1843
            msgBox.exec();
1844
        }
1845
        else if (oldToolbarSuppress != TConfig::getToolbarSuppress() && TConfig::getToolbarSuppress())
1846
        {
1847
            if (mToolbar)
1848
            {
1849
                mToolbar->close();
1850
                delete mToolbar;
1851
                mToolbar = nullptr;
1852
            }
1853
        }
1854
 
1855
        if (TConfig::getFtpSurface() != oldSurface || dlg_settings->downloadForce())
1856
        {
1857
            bool dlYes = true;
1858
 
1859
            MSG_DEBUG("Surface should be downloaded (Old: " << oldSurface << ", New: " << TConfig::getFtpSurface() << ")");
1860
 
1861
            if (!dlg_settings->downloadForce())
1862
            {
1863
                QMessageBox msgBox(this);
1864
                msgBox.setText(QString("Should the surface <b>") + TConfig::getFtpSurface().c_str() + "</b> be installed?");
1865
                msgBox.addButton(QMessageBox::Yes);
1866
                msgBox.addButton(QMessageBox::No);
1867
                int ret = msgBox.exec();
1868
 
1869
                if (ret == QMessageBox::No)
1870
                    dlYes = false;
1871
            }
1872
 
1873
            if (dlYes)
1874
            {
1875
                TTPInit tpinit;
1876
                tpinit.regCallbackProcessEvents(bind(&MainWindow::runEvents, this));
1877
                tpinit.regCallbackProgressBar(bind(&MainWindow::_onProgressChanged, this, std::placeholders::_1));
1878
                tpinit.setPath(TConfig::getProjectPath());
1879
                tpinit.setFileSize(static_cast<off64_t>(dlg_settings->getSelectedFtpFileSize()));
1880
                string msg = "Loading file <b>" + TConfig::getFtpSurface() + "</b>.";
1881
                MSG_DEBUG("Download of surface " << TConfig::getFtpSurface() << " was forced!");
1882
 
1883
                downloadBar(msg, this);
1884
 
1885
                if (tpinit.loadSurfaceFromController(true))
1886
                    rebootAnyway = true;
1887
 
1888
                mDownloadBar->close();
1889
                mBusy = false;
1890
            }
1891
            else
1892
            {
1893
                MSG_DEBUG("No change of surface. Old surface " << oldSurface << " was saved again.");
1894
                TConfig::saveFtpSurface(oldSurface);
1895
                writeSettings();
1896
            }
1897
        }
1898
 
1899
        if (TConfig::getController() != oldHost ||
1900
            TConfig::getChannel() != oldChannelID ||
1901
            TConfig::getPort() != oldPort || rebootAnyway)
1902
        {
1903
            // Start over by exiting this class
1904
            MSG_INFO("Program will start over!");
1905
            _restart_ = true;
1906
            prg_stopped = true;
1907
            killed = true;
1908
 
1909
            if (gAmxNet)
1910
                gAmxNet->stop();
1911
 
1912
            close();
1913
        }
1914
    }
1915
    else if (!ret && dlg_settings->hasChanged())
1916
    {
1917
        TConfig cf(TConfig::getConfigPath() + "/" + TConfig::getConfigFileName());
1918
    }
1919
 
1920
    delete dlg_settings;
1921
#endif  // defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
1922
}
1923
 
1924
/**
1925
 * @brief MainWindow::writeSettings Writes the settings into the configuration file.
1926
 */
1927
void MainWindow::writeSettings()
1928
{
1929
    DECL_TRACER("MainWindow::writeSettings()");
1930
 
1931
    TConfig::saveSettings();
1932
    MSG_INFO("Wrote settings.");
1933
}
1934
 
1935
/**
1936
 * @brief MainWindow::about displays the _about_ dialog.
1937
 */
1938
void MainWindow::about()
1939
{
1940
    DECL_TRACER("MainWindow::about()");
1941
 
1942
#ifdef Q_OS_IOS
1943
    // On IOS the explicit about dialog is shown over the whole screen with
1944
    // the text in a small stripe on the left. This looks ugly and therefor
1945
    // we construct our own about dialog.
1946
    std::string msg = "About TPanel\n\n";
1947
    msg.append("Simulation of an AMX G4 panel\n");
1948
    msg.append("Version v").append(VERSION_STRING()).append("\n");
1949
    msg.append("(C) Copyright 2020 to 2023 by Andreas Theofilu (andreas@theosys.at)\n");
1950
 
1951
    QMessageBox about(this);
1952
    about.addButton(QMessageBox::Ok);
1953
    about.setWindowTitle(tr("About TPanel"));
1954
    about.setIconPixmap(QPixmap(":images/icon.png"));
1955
    about.setTextFormat(Qt::PlainText);
1956
    about.setText(tr(msg.c_str()));
1957
    about.setInformativeText(tr("This program is under the terms of GPL version 3!"));
1958
    about.exec();
1959
#else
1960
    std::string msg = "Simulation of an AMX G4 panel\n";
1961
    msg.append("Version v").append(VERSION_STRING()).append("\n");
1962
    msg.append("(C) Copyright 2020 to 2023 by Andreas Theofilu <andreas@theosys.at>\n");
1963
    msg.append("This program is under the terms of GPL version 3!");
1964
    QMessageBox::about(this, tr("About TPanel"), tr(msg.c_str()));
1965
#endif
1966
}
1967
 
1968
void MainWindow::arrowUp()
1969
{
1970
    DECL_TRACER("MainWindow::arrowUp()");
1971
 
1972
    extButtons_t btType = EXT_CURSOR_UP;
1973
 
1974
    if (TConfig::getPanelType().find("Android") != string::npos)
1975
        btType = EXT_GESTURE_UP;
1976
 
1977
    gPageManager->externalButton(btType, true);
1978
    gPageManager->externalButton(btType, false);
1979
}
1980
 
1981
void MainWindow::arrowLeft()
1982
{
1983
    DECL_TRACER("MainWindow::arrowLeft()");
1984
    extButtons_t btType = EXT_CURSOR_LEFT;
1985
 
1986
    if (TConfig::getPanelType().find("Android") != string::npos)
1987
        btType = EXT_GESTURE_LEFT;
1988
 
1989
    gPageManager->externalButton(btType, true);
1990
    gPageManager->externalButton(btType, false);
1991
}
1992
 
1993
void MainWindow::arrowRight()
1994
{
1995
    DECL_TRACER("MainWindow::arrowRight()");
1996
    extButtons_t btType = EXT_CURSOR_RIGHT;
1997
 
1998
    if (TConfig::getPanelType().find("Android") != string::npos)
1999
        btType = EXT_GESTURE_RIGHT;
2000
 
2001
    gPageManager->externalButton(btType, true);
2002
    gPageManager->externalButton(btType, false);
2003
}
2004
 
2005
void MainWindow::arrowDown()
2006
{
2007
    DECL_TRACER("MainWindow::arrowDown()");
2008
    extButtons_t btType = EXT_CURSOR_DOWN;
2009
 
2010
    if (TConfig::getPanelType().find("Android") != string::npos)
2011
        btType = EXT_GESTURE_DOWN;
2012
 
2013
    gPageManager->externalButton(btType, true);
2014
    gPageManager->externalButton(btType, false);
2015
}
2016
 
2017
void MainWindow::selectOk()
2018
{
2019
    DECL_TRACER("MainWindow::selectOk()");
2020
    extButtons_t btType = EXT_CURSOR_SELECT;
2021
 
2022
    if (TConfig::getPanelType().find("Android") != string::npos)
2023
        btType = EXT_GESTURE_DOUBLE_PRESS;
2024
 
2025
    gPageManager->externalButton(btType, true);
2026
    gPageManager->externalButton(btType, false);
2027
}
2028
 
2029
void MainWindow::volumeUpPressed()
2030
{
2031
    DECL_TRACER("MainWindow::volumeUpPressed()");
2032
    extButtons_t btType = EXT_CURSOR_ROTATE_RIGHT;
2033
 
2034
    if (TConfig::getPanelType().find("Android") != string::npos)
2035
        btType = EXT_GESTURE_ROTATE_RIGHT;
2036
 
2037
    gPageManager->externalButton(btType, true);
2038
}
2039
 
2040
void MainWindow::volumeUpReleased()
2041
{
2042
    DECL_TRACER("MainWindow::volumeUpReleased()");
2043
    extButtons_t btType = EXT_CURSOR_ROTATE_RIGHT;
2044
 
2045
    if (TConfig::getPanelType().find("Android") != string::npos)
2046
        btType = EXT_GESTURE_ROTATE_RIGHT;
2047
 
2048
    gPageManager->externalButton(btType, false);
2049
}
2050
 
2051
void MainWindow::volumeDownPressed()
2052
{
2053
    DECL_TRACER("MainWindow::volumeDownPressed()");
2054
    extButtons_t btType = EXT_CURSOR_ROTATE_LEFT;
2055
 
2056
    if (TConfig::getPanelType().find("Android") != string::npos)
2057
        btType = EXT_GESTURE_ROTATE_LEFT;
2058
 
2059
    gPageManager->externalButton(btType, true);
2060
}
2061
 
2062
void MainWindow::volumeDownReleased()
2063
{
2064
    DECL_TRACER("MainWindow::volumeDownReleased()");
2065
    extButtons_t btType = EXT_CURSOR_ROTATE_LEFT;
2066
 
2067
    if (TConfig::getPanelType().find("Android") != string::npos)
2068
        btType = EXT_GESTURE_ROTATE_LEFT;
2069
 
2070
    gPageManager->externalButton(btType, false);
2071
}
2072
/*
2073
void MainWindow::volumeMute()
2074
{
2075
    DECL_TRACER("MainWindow::volumeMute()");
2076
    gPageManager->externalButton(EXT_GENERAL, true);
2077
    gPageManager->externalButton(EXT_GENERAL, false);
2078
}
2079
*/
2080
 
2081
void MainWindow::animationInFinished()
2082
{
2083
    DECL_TRACER("MainWindow::animationInFinished()");
2084
 
2085
    if (mAnimObjects.empty())
2086
    {
2087
#if TESTMODE == 1
2088
        setScreenDone();
2089
#endif
2090
        return;
2091
    }
2092
 
2093
//    TLOCKER(anim_mutex);
2094
    map<ulong, OBJECT_t *>::iterator iter;
2095
 
2096
    for (iter = mAnimObjects.begin(); iter != mAnimObjects.end(); ++iter)
2097
    {
2098
        if (!iter->second->animation)
2099
            continue;
2100
 
2101
        if (!iter->second->invalid && iter->second->type == OBJ_SUBPAGE && iter->second->animation->state() == QAbstractAnimation::Stopped)
2102
        {
2103
            if (iter->second->object.widget)
2104
            {
2105
                iter->second->object.widget->lower();
2106
                iter->second->object.widget->show();
2107
                iter->second->object.widget->raise();
2108
            }
2109
 
2110
            disconnect(iter->second->animation, &QPropertyAnimation::finished, this, &MainWindow::animationInFinished);
2111
            delete iter->second->animation;
2112
            iter->second->animation = nullptr;
2113
        }
2114
    }
2115
 
2116
    // Delete all empty/finished animations
2117
    bool repeat = false;
2118
 
2119
    do
2120
    {
2121
        repeat = false;
2122
 
2123
        for (iter = mAnimObjects.begin(); iter != mAnimObjects.end(); ++iter)
2124
        {
2125
            if (!iter->second->remove && !iter->second->animation)
2126
            {
2127
                mAnimObjects.erase(iter);
2128
                repeat = true;
2129
                break;
2130
            }
2131
        }
2132
    }
2133
    while (repeat);
2134
#if TESTMODE == 1
2135
    __success = true;
2136
    setScreenDone();
2137
#endif
2138
}
2139
 
2140
void MainWindow::animationFinished()
2141
{
2142
    DECL_TRACER("MainWindow::animationFinished()");
2143
 
2144
    if (mAnimObjects.empty())
2145
    {
2146
#if TESTMODE == 1
2147
        setScreenDone();
2148
#endif
2149
        return;
2150
    }
2151
 
2152
//    TLOCKER(anim_mutex);
2153
    map<ulong, OBJECT_t *>::iterator iter;
2154
 
2155
    for (iter = mAnimObjects.begin(); iter != mAnimObjects.end(); ++iter)
2156
    {
2157
        OBJECT_t *obj = findObject(iter->first);
2158
 
2159
        if (obj && obj->remove && obj->animation && obj->animation->state() == QAbstractAnimation::Stopped)
2160
        {
2161
            MSG_DEBUG("Invalidating object " << handleToString(iter->first));
2162
            disconnect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationFinished);
2163
            delete obj->animation;
2164
            obj->animation = nullptr;
2165
            invalidateAllSubObjects(iter->first);
2166
            invalidateObject(iter->first);
2167
 
2168
            if (obj->type == OBJ_SUBPAGE && obj->object.widget)
2169
                obj->object.widget->hide();
2170
        }
2171
    }
2172
    // Delete all empty/finished animations
2173
    bool repeat = false;
2174
 
2175
    do
2176
    {
2177
        repeat = false;
2178
 
2179
        for (iter = mAnimObjects.begin(); iter != mAnimObjects.end(); ++iter)
2180
        {
2181
            if (iter->second->remove && !iter->second->animation)
2182
            {
2183
                mAnimObjects.erase(iter);
2184
                repeat = true;
2185
                break;
2186
            }
2187
        }
2188
    }
2189
    while (repeat);
2190
#if TESTMODE == 1
2191
    __success = true;
2192
    setScreenDone();
2193
#endif
2194
}
2195
 
2196
void MainWindow::repaintWindows()
2197
{
2198
    DECL_TRACER("MainWindow::repaintWindows()");
2199
 
2200
    if (mWasInactive)
2201
    {
2202
        MSG_INFO("Refreshing of visible popups will be requested.");
2203
        mDoRepaint = true;
2204
    }
2205
}
2206
 
2207
void MainWindow::toFront(ulong handle)
2208
{
2209
    DECL_TRACER("MainWindow::toFront(ulong handle)");
2210
 
2211
    TObject::OBJECT_t *obj = findObject(handle);
2212
 
2213
    if (!obj)
2214
    {
2215
        MSG_WARNING("Object with " << handleToString(handle) << " not found!");
2216
#if TESTMODE == 1
2217
        setScreenDone();
2218
#endif
2219
        return;
2220
    }
2221
 
2222
    if (obj->type == TObject::OBJ_SUBPAGE && obj->object.widget)
2223
        obj->object.widget->raise();
2224
#if TESTMODE == 1
2225
    __success = true;
2226
    setScreenDone();
2227
#endif
2228
}
2229
 
2230
void MainWindow::downloadSurface(const string &file, size_t size)
2231
{
2232
    DECL_TRACER("MainWindow::downloadSurface(const string &file, size_t size)");
2233
 
2234
    if (mBusy)
2235
        return;
2236
 
2237
    QMessageBox msgBox(this);
2238
    msgBox.setText(QString("Should the surface <b>") + file.c_str() + "</b> be installed?<br><i><u>Hint</u>: This will also save all current made settings.</i>");
2239
    msgBox.addButton(QMessageBox::Yes);
2240
    msgBox.addButton(QMessageBox::No);
2241
    int ret = msgBox.exec();
2242
 
2243
    if (ret == QMessageBox::Yes)
2244
    {
2245
        TTPInit tpinit;
2246
        tpinit.regCallbackProcessEvents(bind(&MainWindow::runEvents, this));
2247
        tpinit.regCallbackProgressBar(bind(&MainWindow::_onProgressChanged, this, std::placeholders::_1));
2248
        tpinit.setPath(TConfig::getProjectPath());
2249
 
2250
        if (size)
2251
            tpinit.setFileSize(static_cast<off64_t>(size));
2252
        else
2253
        {
2254
            size = static_cast<size_t>(tpinit.getFileSize(file));
2255
 
2256
            if (!size)
2257
            {
2258
                displayMessage("File <b>" + file + "</b> either doesn't exist on " + TConfig::getController() + " or the NetLinx is not reachable!", "Error");
2259
                return;
2260
            }
2261
 
2262
            tpinit.setFileSize(static_cast<off64_t>(size));
2263
        }
2264
 
2265
        string msg = "Loading file <b>" + file + "</b>.";
2266
 
2267
        downloadBar(msg, this);
2268
        bool reboot = false;
2269
 
2270
        if (tpinit.loadSurfaceFromController(true))
2271
            reboot = true;
2272
        else
2273
            displayMessage("Error downloading file <b>" + file + "</b>!", "Error");
2274
 
2275
        mDownloadBar->close();
2276
        TConfig::setTemporary(true);
2277
        TConfig::saveSettings();
2278
 
2279
        if (reboot)
2280
        {
2281
            // Start over by exiting this class
2282
            MSG_INFO("Program will start over!");
2283
            _restart_ = true;
2284
            prg_stopped = true;
2285
            killed = true;
2286
 
2287
            if (gAmxNet)
2288
                gAmxNet->stop();
2289
 
2290
            close();
2291
        }
2292
    }
2293
 
2294
    mBusy = false;
2295
}
2296
 
2297
void MainWindow::displayMessage(const string &msg, const string &title)
2298
{
2299
    DECL_TRACER("MainWindow::displayMessage(const string &msg, const string &title)");
2300
 
2301
    QMessageBox msgBox(this);
2302
    msgBox.setText(msg.c_str());
2303
 
2304
    if (!title.empty())
2305
        msgBox.setWindowTitle(title.c_str());
2306
 
2307
    msgBox.setWindowModality(Qt::WindowModality::ApplicationModal);
2308
    msgBox.addButton(QMessageBox::Ok);
2309
    msgBox.exec();
2310
}
2311
 
2312
void MainWindow::askPassword(ulong handle, const string msg, const string& title, int x, int y)
2313
{
2314
    DECL_TRACER("MainWindow::askPassword(const string msg, const string& title, int x, int y)");
2315
 
2316
    TQtInputLine *inputLine = new TQtInputLine(this);
2317
    inputLine->setMessage(msg);
2318
    inputLine->setWindowTitle(title.c_str());
2319
    inputLine->setWindowModality(Qt::WindowModality::ApplicationModal);
2320
    inputLine->setPassword(true);
2321
    int bt = inputLine->exec();
2322
 
2323
    if (bt == QDialog::Rejected)
2324
    {
2325
        if (gPageManager)
2326
            gPageManager->callSetPassword(handle, "", x, y);
2327
 
2328
        delete inputLine;
2329
        return;
2330
    }
2331
 
2332
    if (gPageManager)
2333
        gPageManager->callSetPassword(handle, inputLine->getText(), x, y);
2334
 
2335
    delete inputLine;
2336
}
2337
 
2338
void MainWindow::fileDialog(ulong handle, const string &path, const std::string& extension, const std::string& suffix)
2339
{
2340
    DECL_TRACER("MainWindow::fileDialog(ulong handle, const string &path, const std::string& extension, const std::string& suffix)");
2341
 
2342
    std::string pt = path;
2343
 
2344
    if (fs::exists(path) && fs::is_regular_file(path))
2345
    {
2346
        size_t pos = pt.find_last_of("/");
2347
 
2348
        if (pos != std::string::npos)
2349
            pt = pt.substr(0, pos);
2350
        else
2351
        {
2352
            char hv0[4096];
2353
            getcwd(hv0, sizeof(hv0));
2354
            pt = hv0;
2355
        }
2356
    }
2357
 
2358
    QString actPath(pt.c_str());
2359
    QFileDialog fdialog(this, tr("File"), actPath, tr(extension.c_str()));
2360
    fdialog.setAcceptMode(QFileDialog::AcceptSave);
2361
 
2362
    if (!suffix.empty())
2363
        fdialog.setDefaultSuffix(suffix.c_str());
2364
 
2365
    fdialog.setOption(QFileDialog::DontConfirmOverwrite);
2366
    QString fname;
2367
 
2368
    if (fdialog.exec())
2369
    {
2370
        QDir dir = fdialog.directory();
2371
        QStringList list = fdialog.selectedFiles();
2372
 
2373
        if (list.size() > 0)
2374
            fname = dir.absoluteFilePath(list.at(0));
2375
        else
2376
            return;
2377
    }
2378
    else
2379
        return;
2380
 
2381
#ifdef Q_OS_ANDROID
2382
    // In case of Android we get some kind of URL instead of a clear
2383
    // path. Because of this we must call some Java API functions to find the
2384
    // real path.
2385
    QString fileName = fname;
2386
 
2387
    if (fileName.contains("content://"))
2388
    {
2389
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
2390
        QAndroidJniObject uri = QAndroidJniObject::callStaticObjectMethod(
2391
            "android/net/Uri", "parse", "(Ljava/lang/String;)Landroid/net/Uri;",
2392
            QAndroidJniObject::fromString(fileName).object<jstring>());
2393
 
2394
        fileName = QAndroidJniObject::callStaticObjectMethod(
2395
            "org/qtproject/theosys/UriToPath", "getFileName",
2396
            "(Landroid/net/Uri;Landroid/content/Context;)Ljava/lang/String;",
2397
            uri.object(), QtAndroid::androidContext().object()).toString();
2398
#else   // QT5_LINUX
2399
        // For QT6 the API has slightly changed. Especialy the class name to
2400
        // call Java objects.
2401
        QJniObject uri = QJniObject::callStaticObjectMethod(
2402
            "android/net/Uri", "parse", "(Ljava/lang/String;)Landroid/net/Uri;",
2403
            QJniObject::fromString(fileName).object<jstring>());
2404
 
2405
        fileName = QJniObject::callStaticObjectMethod(
2406
            "org/qtproject/theosys/UriToPath", "getFileName",
2407
            "(Landroid/net/Uri;Landroid/content/Context;)Ljava/lang/String;",
2408
            uri.object(), QNativeInterface::QAndroidApplication::context()).toString();
2409
#endif  // QT5_LINUX
2410
        if (fileName.length() > 0)
2411
            fname = fileName;
2412
    }
2413
    else
2414
    {
2415
        MSG_WARNING("Not an Uri? (" << fname.toStdString() << ")");
2416
    }
2417
#endif  // Q_OS_ANDROID
2418
 
2419
    if (gPageManager)
2420
        gPageManager->setTextToButton(handle, fname.toStdString(), true);
2421
}
2422
 
2423
void MainWindow::onTListCallbackCurrentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
2424
{
2425
    DECL_TRACER("MainWindow::onTListCallbackCurrentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)");
2426
 
2427
    if (!current || current == previous)
2428
        return;
2429
 
2430
    QListWidget *w = current->listWidget();
2431
    TObject::OBJECT_t *objWindow = findFirstWindow();
2432
 
2433
    while(objWindow)
2434
    {
2435
        TObject::OBJECT_t *objItem = findFirstChild(objWindow->handle);
2436
 
2437
        while (objItem)
2438
        {
2439
            if (objItem->type == TObject::OBJ_LIST && objItem->object.list == w)
2440
            {
2441
                int row = objItem->object.list->currentRow();
2442
                gPageManager->setSelectedRow(objItem->handle, row + 1, current->text().toStdString());
2443
                return;
2444
            }
2445
 
2446
            objItem = findNextChild(objItem->handle);
2447
        }
2448
 
2449
        objWindow = findNextWindow(objWindow);
2450
    }
2451
}
2452
 
2453
void MainWindow::onProgressChanged(int percent)
2454
{
2455
    DECL_TRACER("MainWindow::onProgressChanged(int percent)");
2456
 
2457
    if (!mDownloadBar || !mBusy)
2458
        return;
2459
 
2460
    mDownloadBar->setProgress(percent);
2461
}
2462
 
2463
void MainWindow::startWait(const string& text)
2464
{
2465
    DECL_TRACER("MainWindow::startWait(const string& text)");
2466
 
2467
    if (mWaitBox)
2468
    {
2469
        mWaitBox->setText(text);
2470
        return;
2471
    }
2472
 
2473
    mWaitBox = new TQtWait(this, text);
2474
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
2475
    mWaitBox->setScaleFactor(mScaleFactor);
2476
    mWaitBox->doResize();
2477
    mWaitBox->start();
2478
#endif
2479
}
2480
 
2481
void MainWindow::stopWait()
2482
{
2483
    DECL_TRACER("MainWindow::stopWait()");
2484
 
2485
    if (!mWaitBox)
2486
        return;
2487
 
2488
    mWaitBox->end();
2489
    delete mWaitBox;
2490
    mWaitBox = nullptr;
2491
}
2492
 
2493
void MainWindow::pageFinished(ulong handle)
2494
{
2495
    DECL_TRACER("MainWindow::pageFinished(uint handle)");
2496
 
2497
    TObject::OBJECT_t *obj = findObject(handle);
2498
 
2499
    if (obj)
2500
    {
2501
        if (obj->type == TObject::OBJ_SUBPAGE && (obj->animate.showEffect == SE_NONE || obj->animate.showTime <= 0) && obj->object.widget)
2502
        {
2503
            if (!obj->object.widget->isEnabled())
2504
                obj->object.widget->setEnabled(true);
2505
 
2506
            obj->object.widget->show();
2507
            obj->object.widget->lower();
2508
            obj->object.widget->raise();
2509
        }
2510
 
2511
        if (obj->type == TObject::OBJ_SUBPAGE && obj->animate.showEffect != SE_NONE && obj->object.widget)
2512
        {
2513
            if (startAnimation(obj, obj->animate))
2514
                return;
2515
        }
2516
 
2517
        if ((obj->type == TObject::OBJ_PAGE || obj->type == TObject::OBJ_SUBPAGE) && obj->object.widget)
2518
        {
2519
            QObjectList list = obj->object.widget->children();
2520
            QObjectList::Iterator iter;
2521
 
2522
            for (iter = list.begin(); iter != list.end(); ++iter)
2523
            {
2524
                QObject *o = *iter;
2525
                ulong child = extractHandle(o->objectName().toStdString());
2526
                OBJECT_t *obj = nullptr;
2527
 
2528
                if (child && (obj = findObject(child)) != nullptr)
2529
                {
2530
                    if (obj->invalid && obj->type != OBJ_SUBPAGE)
2531
                        obj->invalid = false;
2532
 
2533
                    if (obj->remove)
2534
                        obj->remove = false;
2535
 
2536
                    switch (obj->type)
2537
                    {
2538
                        case OBJ_PAGE:
2539
                        case OBJ_SUBPAGE:
2540
                            if (obj->object.widget && !obj->invalid && obj->object.widget->isHidden())
2541
                            {
2542
                                if (!obj->object.widget->isEnabled())
2543
                                    obj->object.widget->setEnabled(true);
2544
 
2545
                                obj->object.widget->show();
2546
                                obj->object.widget->lower();
2547
                                obj->object.widget->raise();
2548
                            }
2549
                        break;
2550
 
2551
                        case OBJ_BUTTON:
2552
                            if (obj->object.label && obj->object.label->isHidden())
2553
                                obj->object.label->show();
2554
                        break;
2555
 
2556
                        case OBJ_MARQUEE:
2557
                            if (obj->object.marquee && obj->object.marquee->isHidden())
2558
                                obj->object.marquee->show();
2559
                        break;
2560
 
2561
                        case OBJ_INPUT:
2562
                        case OBJ_TEXT:
2563
                            if (obj->object.plaintext && obj->object.plaintext->isHidden())
2564
                                obj->object.plaintext->show();
2565
                        break;
2566
 
2567
                        case OBJ_LIST:
2568
                            if (obj->object.list && obj->object.list->isHidden())
2569
                                obj->object.list->show();
2570
                        break;
2571
 
2572
                        case OBJ_SUBVIEW:
2573
                            if (obj->object.area && obj->object.area->isHidden())
2574
                            {
2575
                                obj->object.area->lower();
2576
                                obj->object.area->show();
2577
                                obj->object.area->raise();
2578
                            }
2579
                        break;
2580
 
2581
                        case OBJ_VIDEO:
2582
                            if (obj->object.vwidget && obj->object.vwidget->isHidden())
2583
                                obj->object.vwidget->show();
2584
                        break;
2585
 
2586
                        default:
2587
                            MSG_WARNING("Object " << handleToString(child) << " is an invalid type!");
2588
                    }
2589
                }
2590
                else
2591
                {
2592
                    QString obName = o->objectName();
2593
 
2594
                    if (obName.startsWith("Label_"))
2595
                    {
2596
                        QLabel *l = dynamic_cast<QLabel *>(o);
2597
 
2598
                        if (l->isHidden())
2599
                            l->show();
2600
                    }
2601
                }
2602
            }
2603
        }
2604
 
2605
        if (obj->type == OBJ_SUBVIEW && obj->object.area)
2606
            obj->object.area->show();
2607
#if TESTMODE == 1
2608
        __success = true;
2609
#endif
2610
    }
2611
#ifdef QT_DEBUG
2612
    else
2613
    {
2614
        MSG_WARNING("Object " << handleToString(handle) << " not found!");
2615
    }
2616
#endif
2617
#if TESTMODE == 1
2618
    setScreenDone();
2619
#endif
2620
}
2621
 
2622
/**
2623
 * @brief MainWindow::appStateChanged - Is called whenever the state of the app changes.
2624
 * This callback method is called whenever the state of the application
2625
 * changes. This is mostly usefull on mobile devices. Whenever the main window
2626
 * looses the focus (screen closed, application is put into background, ...)
2627
 * this method is called and updates a flag. If the application is not able
2628
 * to draw to the screen (suspended) all events are cached. At the moment the
2629
 * application becomes active, all queued messages are applied.
2630
 * @param state     The new state of the application.
2631
 */
2632
void MainWindow::onAppStateChanged(Qt::ApplicationState state)
2633
{
2634
    DECL_TRACER("MainWindow::onAppStateChanged(Qt::ApplicationState state)");
2635
 
2636
    switch (state)
2637
    {
2638
        case Qt::ApplicationSuspended:              // Should not occure on a normal desktop
2639
            MSG_INFO("Switched to mode SUSPEND");
2640
            mHasFocus = false;
2641
#ifdef Q_OS_ANDROID
2642
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
2643
            QAndroidJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "pauseOrientationListener", "()V");
2644
#else
2645
            QJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "pauseOrientationListener", "()V");
2646
#endif
2647
#endif
2648
        break;
2649
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)      // On a normal desktop we can ignore this signals
2650
        case Qt::ApplicationInactive:
2651
            MSG_INFO("Switched to mode INACTIVE");
2652
            mHasFocus = false;
2653
            mWasInactive = true;
2654
#ifdef Q_OS_ANDROID
2655
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
2656
            QAndroidJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "pauseOrientationListener", "()V");
2657
#else
2658
            QJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "pauseOrientationListener", "()V");
2659
#endif
2660
#endif
2661
        break;
2662
 
2663
        case Qt::ApplicationHidden:
2664
            MSG_INFO("Switched to mode HIDDEN");
2665
            mHasFocus = false;
2666
#ifdef Q_OS_ANDROID
2667
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
2668
            QAndroidJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "pauseOrientationListener", "()V");
2669
#else
2670
            QJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "pauseOrientationListener", "()V");
2671
#endif
2672
#endif
2673
        break;
2674
#endif
2675
        case Qt::ApplicationActive:
2676
            MSG_INFO("Switched to mode ACTIVE");
2677
            mHasFocus = true;
2678
#ifdef Q_OS_IOS
2679
            initGeoLocation();
2680
#endif
2681
            if (!isRunning && gPageManager)
2682
            {
2683
                // Start the core application
2684
                gPageManager->startUp();
2685
                gPageManager->run();
2686
                isRunning = true;
2687
                mWasInactive = false;
2688
#ifdef Q_OS_IOS
2689
                // To get the battery level periodicaly we setup a timer.
2690
                if (!mIosBattery)
2691
                    mIosBattery = new TIOSBattery;
2692
 
2693
                mIosBattery->update();
2694
 
2695
                int left = mIosBattery->getBatteryLeft();
2696
                int stat = mIosBattery->getBatteryState();
2697
                MSG_DEBUG("iOS battery state: " << left << "%, State: " << stat);
2698
                // At this point no buttons are registered and therefore the battery
2699
                // state will not be visible. To have the state at the moment a button
2700
                // is registered, we tell the page manager to store the values.
2701
                gPageManager->setBattery(left, stat);
2702
                gPageManager->informBatteryStatus(left, stat);
2703
 
2704
                if (mSensor)
2705
                {
2706
                    if (mIosRotate && mOrientation == Qt::PrimaryOrientation) // Unknown?
2707
                    {
2708
                        switch(mIosRotate->getCurrentOrientation())
2709
                        {
2710
                            case O_PORTRAIT:            mOrientation = Qt::PortraitOrientation; break;
2711
                            case O_REVERSE_PORTRAIT:    mOrientation = Qt::InvertedPortraitOrientation; break;
2712
                            case O_REVERSE_LANDSCAPE:   mOrientation = Qt::InvertedLandscapeOrientation; break;
2713
                            case O_LANDSCAPE:           mOrientation = Qt::LandscapeOrientation; break;
2714
                        }
2715
                    }
2716
#if defined(QT_DEBUG) && (defined(Q_OS_IOS) || defined(Q_OS_ANDROID))
2717
                    MSG_DEBUG("Orientation after activate: " << orientationToString(mOrientation));
2718
#endif
2719
                    if (gPageManager && mIosRotate)
2720
                    {
2721
                        if (gPageManager->getSettings()->isPortrait() && mOrientation != Qt::PortraitOrientation)
2722
                        {
2723
                            mIosRotate->rotate(O_PORTRAIT);
2724
                            mOrientation = Qt::PortraitOrientation;
2725
                        }
2726
                        else if (mOrientation != Qt::LandscapeOrientation)
2727
                        {
2728
                            mIosRotate->rotate(O_LANDSCAPE);
2729
                            mOrientation = Qt::LandscapeOrientation;
2730
                        }
2731
                    }
2732
 
2733
                    setNotch();
2734
                }
2735
#endif
2736
            }
2737
            else
2738
            {
2739
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && defined(Q_OS_ANDROID)
2740
                _freezeWorkaround();
2741
#endif
2742
                if (mDoRepaint || mWasInactive)
2743
                    repaintObjects();
2744
 
2745
                mDoRepaint = false;
2746
                mWasInactive = false;
2747
            }
2748
#ifdef Q_OS_ANDROID
2749
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
2750
            QAndroidJniObject activity = QtAndroid::androidActivity();
2751
            QAndroidJniObject::callStaticMethod<void>("org/qtproject/theosys/HideToolbar", "hide", "(Landroid/app/Activity;Z)V", activity.object(), true);
2752
            QAndroidJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "resumeOrientationListener", "()V");
2753
#else
2754
            QJniObject activity = QNativeInterface::QAndroidApplication::context();
2755
//            QJniObject::callStaticMethod<void>("org/qtproject/theosys/HideToolbar", "hide", "(Landroid/app/Activity;Z)V", activity.object(), true);
2756
            QJniObject::callStaticMethod<void>("org/qtproject/theosys/Orientation", "resumeOrientationListener", "()V");
2757
#endif
2758
#endif
2759
#ifdef Q_OS_IOS
2760
            // We do this to make sure the battery state is up to date after the
2761
            // screen was reactivated.
2762
            int left = mIosBattery->getBatteryLeft();
2763
            int stat = mIosBattery->getBatteryState();
2764
            gPageManager->informBatteryStatus(left, stat);
2765
 
2766
            if (mIOSSettingsActive)
2767
            {
2768
                mIOSSettingsActive = false;
2769
                MSG_DEBUG("Activating settings");
2770
                activateSettings(QASettings::getOldNetlinx(),
2771
                                  QASettings::getOldPort(),
2772
                                  QASettings::getOoldChannelID(),
2773
                                  QASettings::getOldSurface(),
2774
                                  QASettings::getOldToolbarSuppress(),
2775
                                  QASettings::getOldToolbarForce());
2776
            }
2777
#endif
2778
#if TESTMODE == 1
2779
            if (_gTestMode)
2780
                _gTestMode->run();
2781
 
2782
            _run_test_ready = true;
2783
#endif
2784
        break;
2785
#if not defined(Q_OS_IOS) && not defined(Q_OS_ANDROID)
2786
        default:
2787
            mHasFocus = true;
2788
#endif
2789
    }
2790
#if defined(Q_OS_ANDROID)
2791
    if (mHasFocus && gPageManager)
2792
    {
2793
        gPageManager->initNetworkState();
2794
        gPageManager->initBatteryState();
2795
    }
2796
    else if (gPageManager)
2797
    {
2798
        gPageManager->stopNetworkState();
2799
        gPageManager->stopBatteryState();
2800
    }
2801
#endif
2802
}
2803
 
2804
void MainWindow::_shutdown()
2805
{
2806
    DECL_TRACER("MainWindow::_shutdown()")
2807
 
2808
    close();
2809
}
2810
 
2811
/******************* Signal handling *************************/
2812
 
2813
void MainWindow::_resetSurface()
2814
{
2815
    DECL_TRACER("MainWindow::_resetSurface()");
2816
 
2817
    // Start over by exiting this class
2818
    MSG_INFO("Program will start over!");
2819
    _restart_ = true;
2820
    prg_stopped = true;
2821
    killed = true;
2822
 
2823
    if (gAmxNet)
2824
        gAmxNet->stop();
2825
 
2826
    close();
2827
}
2828
 
2829
void MainWindow::_displayButton(ulong handle, ulong parent, TBitmap buffer, int width, int height, int left, int top, bool passthrough, int marqtype, int marq)
2830
{
2831
    DECL_TRACER("MainWindow::_displayButton(ulong handle, ulong parent, TBitmap buffer, int width, int height, int left, int top, bool passthrough, int marqtype, int marq)");
2832
 
2833
    if (prg_stopped)
2834
        return;
2835
 
2836
    if (!mHasFocus)
2837
    {
2838
        markDirty(handle);
2839
        return;
2840
    }
2841
 
2842
    emit sigDisplayButton(handle, parent, buffer, width, height, left, top, passthrough, marqtype, marq);
2843
}
2844
 
2845
void MainWindow::_setMarqueeText(Button::TButton* button)
2846
{
2847
    DECL_TRACER("MainWindow::_setMarqueeText(Button::TButton* button)");
2848
 
2849
    if (prg_stopped)
2850
        return;
2851
 
2852
    emit sigSetMarqueeText(button);
2853
}
2854
 
2855
void MainWindow::_displayViewButton(ulong handle, ulong parent, bool vertical, TBitmap buffer, int width, int height, int left, int top, int space, TColor::COLOR_T fillColor)
2856
{
2857
    DECL_TRACER("MainWindow::_displayViewButton(ulong handle, ulong parent, TBitmap buffer, int width, int height, int left, int top)");
2858
 
2859
    if (prg_stopped)
2860
        return;
2861
 
2862
    if (!mHasFocus)
2863
    {
2864
        markDirty(handle);
2865
        return;
2866
    }
2867
 
2868
    emit sigDisplayViewButton(handle, parent, vertical, buffer, width, height, left, top, space, fillColor);
2869
}
2870
 
2871
void MainWindow::_addViewButtonItems(ulong parent, vector<PGSUBVIEWITEM_T> items)
2872
{
2873
    DECL_TRACER("MainWindow::_addViewButtonItems(ulong parent, vector<PGSUBVIEWITEM_T> items)");
2874
 
2875
    if (prg_stopped)
2876
        return;
2877
 
2878
    emit sigAddViewButtonItems(parent, items);
2879
}
2880
 
2881
void MainWindow::_updateViewButton(ulong handle, ulong parent, TBitmap buffer, TColor::COLOR_T fillColor)
2882
{
2883
    DECL_TRACER("MainWindow::_updateViewButton(ulong handle, ulong parent, TBitmap buffer, TColor::COLOR_T fillColor)");
2884
 
2885
    if (prg_stopped || !mHasFocus)
2886
        return;
2887
 
2888
    if (!mHasFocus)
2889
    {
2890
        markDirty(handle);
2891
        return;
2892
    }
2893
 
2894
    emit sigUpdateViewButton(handle, parent, buffer, fillColor);
2895
}
2896
 
2897
void MainWindow::_updateViewButtonItem(PGSUBVIEWITEM_T& item, ulong parent)
2898
{
2899
    DECL_TRACER("MainWindow::_updateViewButtonItem(PGSUBVIEWITEM_T& item, ulong parent)");
2900
 
2901
    if (prg_stopped || !mHasFocus)
2902
        return;
2903
 
2904
    emit sigUpdateViewButtonItem(item, parent);
2905
}
2906
 
2907
void MainWindow::_showViewButtonItem(ulong handle, ulong parent, int position, int timer)
2908
{
2909
    DECL_TRACER("MainWindow::_showViewButtonItem(ulong handle, ulong parent, int position, int timer)");
2910
 
2911
    if (prg_stopped)
2912
        return;
2913
 
2914
    if (!mHasFocus)
2915
    {
2916
        markDirty(handle);
2917
        return;
2918
    }
2919
 
2920
    emit sigShowViewButtonItem(handle, parent, position, timer);
2921
}
2922
 
2923
void MainWindow::_hideAllViewItems(ulong handle)
2924
{
2925
    DECL_TRACER("MainWindow::_hideAllViewItems(ulong handle)");
2926
 
2927
    if (prg_stopped || !mHasFocus)
2928
        return;
2929
 
2930
    emit sigHideAllViewItems(handle);
2931
}
2932
 
2933
void MainWindow::_toggleViewButtonItem(ulong handle, ulong parent, int position, int timer)
2934
{
2935
    DECL_TRACER("MainWindow::_toggleViewButtonItem(ulong handle, ulong parent, int position, int timer)");
2936
 
2937
    if (prg_stopped)
2938
        return;
2939
 
2940
    if (!mHasFocus)
2941
    {
2942
        markDirty(handle);
2943
        return;
2944
    }
2945
 
2946
    emit sigToggleViewButtonItem(handle, parent, position, timer);
2947
}
2948
 
2949
void MainWindow::_hideViewItem(ulong handle, ulong parent)
2950
{
2951
    DECL_TRACER("MainWindow::_hideViewItem(ulong handle, ulong parent)");
2952
 
2953
    if (prg_stopped || !mHasFocus)
2954
        return;
2955
 
2956
    emit sigHideViewItem(handle, parent);
2957
}
2958
 
2959
void MainWindow::_setVisible(ulong handle, bool state)
2960
{
2961
    DECL_TRACER("MainWindow::_setVisible(ulong handle, bool state)");
2962
 
2963
    if (prg_stopped || !mHasFocus)
2964
        return;
2965
 
2966
    emit sigSetVisible(handle, state);
2967
}
2968
 
2969
void MainWindow::_setSubViewPadding(ulong handle, int padding)
2970
{
2971
    DECL_TRACER("MainWindow::_setSubViewPadding(ulong handle, int padding)");
2972
 
2973
    if (prg_stopped || !mHasFocus)
2974
        return;
2975
 
2976
    emit sigSetSubViewPadding(handle, padding);
2977
}
2978
 
2979
void MainWindow::_setPage(ulong handle, int width, int height)
2980
{
2981
    DECL_TRACER("MainWindow::_setPage(ulong handle, int width, int height)");
2982
 
2983
    if (prg_stopped || !mHasFocus)
2984
        return;
2985
 
2986
    emit sigSetPage(handle, width, height);
2987
}
2988
 
2989
void MainWindow::_setSubPage(ulong handle, ulong parent, int left, int top, int width, int height, ANIMATION_t animate, bool modal)
2990
{
2991
    DECL_TRACER("MainWindow::_setSubPage(ulong handle, ulong parent, int left, int top, int width, int height, ANIMATION_t animate, bool modal)");
2992
 
2993
    if (prg_stopped || !mHasFocus)
2994
        return;
2995
 
2996
    emit sigSetSubPage(handle, parent, left, top, width, height, animate, modal);
2997
}
2998
 
2999
#ifdef _OPAQUE_SKIA_
3000
void MainWindow::_setBackground(ulong handle, TBitmap image, int width, int height, ulong color)
3001
#else
3002
void MainWindow::_setBackground(ulong handle, TBitmap image, int width, int height, ulong color, int opacity)
3003
#endif
3004
{
3005
    DECL_TRACER("MainWindow::_setBackground(ulong handle, TBitmap image, int width, int height, ulong color [, int opacity])");
3006
 
3007
    if (prg_stopped)
3008
        return;
3009
 
3010
    if (!mHasFocus)
3011
    {
3012
        markDirty(handle);
3013
        return;
3014
    }
3015
 
3016
#ifdef _OPAQUE_SKIA_
3017
    emit sigSetBackground(handle, image, width, height, color);
3018
#else
3019
    emit sigSetBackground(handle, image, width, height, color, opacity);
3020
#endif
3021
}
3022
 
3023
void MainWindow::_dropPage(ulong handle)
3024
{
3025
    DECL_TRACER("MainWindow::_dropPage(ulong handle)");
3026
 
3027
    if (!mHasFocus)
3028
        return;
3029
 
3030
    doReleaseButton();
3031
 
3032
    if (!mHasFocus)
3033
    {
3034
        markDroped(handle);
3035
        return;
3036
    }
3037
 
3038
    emit sigDropPage(handle);
3039
}
3040
 
3041
void MainWindow::_dropSubPage(ulong handle, ulong parent)
3042
{
3043
    DECL_TRACER("MainWindow::_dropSubPage(ulong handle, ulong parent)");
3044
 
3045
    if (!mHasFocus)
3046
        return;
3047
 
3048
    doReleaseButton();
3049
 
3050
    if (!mHasFocus)
3051
    {
3052
        markDroped(handle);
3053
        return;
3054
    }
3055
 
3056
    emit sigDropSubPage(handle, parent);
3057
}
3058
 
3059
void MainWindow::_dropButton(ulong handle)
3060
{
3061
    DECL_TRACER("MainWindow::_dropButton(ulong handle)");
3062
 
3063
    if (!mHasFocus)
3064
    {
3065
        markDroped(handle);
3066
        return;
3067
    }
3068
 
3069
    emit sigDropButton(handle);
3070
}
3071
 
3072
void MainWindow::_playVideo(ulong handle, ulong parent, int left, int top, int width, int height, const string& url, const string& user, const string& pw)
3073
{
3074
    DECL_TRACER("MainWindow::_playVideo(ulong handle, const string& url)");
3075
 
3076
    if (prg_stopped || !mHasFocus)
3077
        return;
3078
 
3079
    emit sigPlayVideo(handle, parent, left, top, width, height, url, user, pw);
3080
}
3081
 
3082
void MainWindow::_inputText(Button::TButton *button, Button::BITMAP_t& bm, int frame)
3083
{
3084
    DECL_TRACER("MainWindow::_inputText(Button::TButton *button, Button::BITMAP_t& bm, int frame)");
3085
 
3086
    if (prg_stopped || !button || !mHasFocus)
3087
        return;
3088
 
3089
    QByteArray buf;
3090
 
3091
    if (bm.buffer && bm.rowBytes > 0)
3092
    {
3093
        size_t size = static_cast<size_t>(bm.width) * static_cast<size_t>(bm.height) * static_cast<size_t>(bm.rowBytes / static_cast<size_t>(bm.width));
3094
        buf.insert(0, (const char *)bm.buffer, static_cast<qsizetype>(size));
3095
    }
3096
 
3097
    emit sigInputText(button, buf, bm.width, bm.height, frame, bm.rowBytes);
3098
}
3099
 
3100
void MainWindow::_listBox(Button::TButton *button, Button::BITMAP_t& bm, int frame)
3101
{
3102
    DECL_TRACER("MainWindow::_listBox(Button::TButton& button, Button::BITMAP_t& bm, int frame)");
3103
 
3104
    if (prg_stopped || !mHasFocus)
3105
        return;
3106
 
3107
    QByteArray buf;
3108
 
3109
    if (bm.buffer && bm.rowBytes > 0)
3110
    {
3111
        size_t size = static_cast<size_t>(bm.width) * static_cast<size_t>(bm.height) * static_cast<size_t>(bm.rowBytes / static_cast<size_t>(bm.width));
3112
        buf.insert(0, (const char *)bm.buffer, static_cast<qsizetype>(size));
3113
    }
3114
 
3115
    emit sigListBox(button, buf, bm.width, bm.height, frame, bm.rowBytes);
3116
}
3117
 
3118
void MainWindow::_showKeyboard(const std::string& init, const std::string& prompt, bool priv)
3119
{
3120
    DECL_TRACER("MainWindow::_showKeyboard(std::string &init, std::string &prompt, bool priv)");
3121
 
3122
    if (prg_stopped || !mHasFocus)
3123
        return;
3124
 
3125
    doReleaseButton();
3126
    emit sigKeyboard(init, prompt, priv);
3127
}
3128
 
3129
void MainWindow::_showKeypad(const std::string& init, const std::string& prompt, bool priv)
3130
{
3131
    DECL_TRACER("MainWindow::_showKeypad(std::string &init, std::string &prompt, bool priv)");
3132
 
3133
    if (prg_stopped || !mHasFocus)
3134
        return;
3135
 
3136
    doReleaseButton();
3137
    emit sigKeypad(init, prompt, priv);
3138
}
3139
 
3140
void MainWindow::_resetKeyboard()
3141
{
3142
    DECL_TRACER("MainWindow::_resetKeyboard()");
3143
 
3144
    if (mHasFocus)
3145
        emit sigResetKeyboard();
3146
}
3147
 
3148
void MainWindow::_showSetup()
3149
{
3150
    DECL_TRACER("MainWindow::_showSetup()");
3151
 
3152
    if (mHasFocus)
3153
        emit sigShowSetup();
3154
}
3155
 
3156
void MainWindow::_playSound(const string& file)
3157
{
3158
    DECL_TRACER("MainWindow::_playSound(const string& file)");
3159
 
3160
    if (mHasFocus)
3161
        emit sigPlaySound(file);
3162
}
3163
 
3164
void MainWindow::_stopSound()
3165
{
3166
    DECL_TRACER("MainWindow::_stopSound()");
3167
 
3168
    if (mHasFocus)
3169
        emit sigStopSound();
3170
}
3171
 
3172
void MainWindow::_muteSound(bool state)
3173
{
3174
    DECL_TRACER("MainWindow::_muteSound(bool state)");
3175
 
3176
    if (mHasFocus)
3177
        emit sigMuteSound(state);
3178
}
3179
 
3180
void MainWindow::_setVolume(int volume)
3181
{
3182
    DECL_TRACER("MainWindow::_setVolume(int volume)");
3183
 
3184
    if (mHasFocus)
3185
        emit sigSetVolume(volume);
3186
}
3187
 
3188
void MainWindow::_setOrientation(J_ORIENTATION ori)
3189
{
3190
#ifdef Q_OS_ANDROID
3191
    DECL_TRACER("MainWindow::_setOriantation(J_ORIENTATION ori)");
3192
 
3193
    if (ori == O_FACE_UP || ori == O_FACE_DOWN)
3194
        return;
3195
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
3196
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
3197
#else
3198
    QJniObject activity = QJniObject::callStaticObjectMethod("org/qtproject/qt/android/QtNative", "activity", "()Landroid/app/Activity;");
3199
#endif
3200
    if ( activity.isValid() )
3201
    {
3202
        activity.callMethod<void>
3203
                ("setRequestedOrientation"  // method name
3204
                 , "(I)V"                   // signature
3205
                 , ori);
3206
 
3207
        switch(ori)
3208
        {
3209
            case O_LANDSCAPE:           mOrientation = Qt::LandscapeOrientation; break;
3210
            case O_PORTRAIT:            mOrientation = Qt::PortraitOrientation; break;
3211
            case O_REVERSE_LANDSCAPE:   mOrientation = Qt::InvertedLandscapeOrientation; break;
3212
            case O_REVERSE_PORTRAIT:    mOrientation = Qt::InvertedPortraitOrientation; break;
3213
            default:
3214
                MSG_WARNING("Orientation is undefined!");
3215
                mOrientation = Qt::PrimaryOrientation;
3216
        }
3217
    }
3218
#elif defined(Q_OS_IOS)
3219
    if (mIosRotate)
3220
    {
3221
        mIosRotate->rotate(ori);
3222
#ifdef QT_DEBUG
3223
        string msg;
3224
 
3225
        switch(ori)
3226
        {
3227
            case O_LANDSCAPE:           msg = "LANDSCAPE"; break;
3228
            case O_PORTRAIT:            msg = "PORTRAIT"; break;
3229
            case O_REVERSE_PORTRAIT:    msg = "INVERTED PORTRAIT"; break;
3230
            case O_REVERSE_LANDSCAPE:   msg = "INVERTED LANDSCAPE"; break;
3231
            default:
3232
                msg = "unknown";
3233
        }
3234
 
3235
        MSG_DEBUG("Rotated to " << msg);
3236
#endif
3237
    }
3238
#else
3239
    Q_UNUSED(ori);
3240
#endif
3241
}
3242
 
3243
void MainWindow::_sendVirtualKeys(const string& str)
3244
{
3245
    DECL_TRACER("MainWindow::_sendVirtualKeys(const string& str)");
3246
 
3247
    if (mHasFocus)
3248
        emit sigSendVirtualKeys(str);
3249
}
3250
 
3251
void MainWindow::_showPhoneDialog(bool state)
3252
{
3253
    DECL_TRACER("MainWindow::_showPhoneDialog(bool state)");
3254
 
3255
    if (mHasFocus)
3256
        emit sigShowPhoneDialog(state);
3257
}
3258
 
3259
void MainWindow::_setPhoneNumber(const std::string& number)
3260
{
3261
    DECL_TRACER("MainWindow::_setPhoneNumber(const std::string& number)");
3262
 
3263
    if (mHasFocus)
3264
        emit sigSetPhoneNumber(number);
3265
}
3266
 
3267
void MainWindow::_setPhoneStatus(const std::string& msg)
3268
{
3269
    DECL_TRACER("MainWindow::_setPhoneStatus(const std::string& msg)");
3270
 
3271
    if (mHasFocus)
3272
        emit sigSetPhoneStatus(msg);
3273
}
3274
 
3275
void MainWindow::_setPhoneState(int state, int id)
3276
{
3277
    DECL_TRACER("MainWindow::_setPhoneState(int state, int id)");
3278
 
3279
    if (mHasFocus)
3280
        emit sigSetPhoneState(state, id);
3281
}
3282
 
3283
void MainWindow::_onProgressChanged(int percent)
3284
{
3285
    DECL_TRACER("MainWindow::_onProgressChanged(int percent)");
3286
 
3287
    if (mHasFocus)
3288
        emit sigOnProgressChanged(percent);
3289
}
3290
 
3291
void MainWindow::_displayMessage(const string &msg, const string &title)
3292
{
3293
    DECL_TRACER("MainWindow::_displayMessage(const string &msg, const string &title)");
3294
 
3295
    if (mHasFocus)
3296
        emit sigDisplayMessage(msg, title);
3297
}
3298
 
3299
void MainWindow::_askPassword(ulong handle, const string& msg, const string& title, int x, int y)
3300
{
3301
    DECL_TRACER("MainWindow::_askPassword(ulong handle, const string& msg, const string& title, int x int y)");
3302
 
3303
    if (mHasFocus)
3304
        emit sigAskPassword(handle, msg, title, x, y);
3305
}
3306
 
3307
void MainWindow::_fileDialog(ulong handle, const string &path, const std::string& extension, const std::string& suffix)
3308
{
3309
    DECL_TRACER("MainWindow::_fileDialog(ulong handle, const string &path, const std::string& extension, const std::string& suffix)");
3310
 
3311
    if (!handle || path.empty())
3312
    {
3313
        MSG_WARNING("Invalid parameter handle or no path!");
3314
        return;
3315
    }
3316
 
3317
    emit sigFileDialog(handle, path, extension, suffix);
3318
}
3319
 
3320
void MainWindow::_setSizeMainWindow(int width, int height)
3321
{
3322
#if !defined (Q_OS_ANDROID) && !defined(Q_OS_IOS)
3323
    DECL_TRACER("MainWindow::_setSizeMainWindow(int width, int height)");
3324
 
3325
    emit sigSetSizeMainWindow(width, height);
3326
#else
3327
    Q_UNUSED(width);
3328
    Q_UNUSED(height);
3329
#endif
3330
}
3331
 
3332
void MainWindow::_listViewArea(ulong handle, ulong parent, Button::TButton& button, SUBVIEWLIST_T& list)
3333
{
3334
    DECL_TRACER("MainWindow::_listViewArea(ulong handle, ulong parent, Button::TButton *button, SUBVIEWLIST_T& list)");
3335
 
3336
    if (!handle || !parent || list.id <= 0)
3337
    {
3338
        MSG_WARNING("Invalid parameters for scroll area!");
3339
        return;
3340
    }
3341
 
3342
    if (!mHasFocus)
3343
    {
3344
        markDirty(handle);
3345
        return;
3346
    }
3347
 
3348
    emit sigListViewArea(handle, parent, button, list);
3349
}
3350
 
458 andreas 3351
void MainWindow::_initializeIntercom(INTERCOM_t ic)
3352
{
3353
    DECL_TRACER("MainWindow::_initializeIntercom(INTERCOM_t ic)");
3354
 
3355
    emit sigInitializeIntercom(ic);
3356
}
3357
 
3358
void MainWindow::_intercomStart()
3359
{
3360
    DECL_TRACER("MainWindow::_intercomStart()");
3361
 
3362
    emit sigIntercomStart();
3363
}
3364
 
3365
void MainWindow::_intercomStop()
3366
{
3367
    DECL_TRACER("MainWindow::_intercomStop()");
3368
 
3369
    emit sigIntercomStop();
3370
}
3371
 
3372
void MainWindow::_intercomSpkLevel(int level)
3373
{
3374
    DECL_TRACER("MainWindow::_intercomSpkLevel(int level)");
3375
 
3376
    emit sigIntercomSpkLevel(level);
3377
}
3378
 
3379
void MainWindow::_intercomMicLevel(int level)
3380
{
3381
    DECL_TRACER("MainWindow::_intercomMicLevel(int level)");
3382
 
3383
    emit sigIintercomMicLevel(level);
3384
}
3385
 
3386
void MainWindow::_intercomMicMute(bool mute)
3387
{
3388
    DECL_TRACER("MainWindow::_intercomMicMute(bool mute)");
3389
 
3390
    emit sigIntercomMicMute(mute);
3391
}
3392
 
446 andreas 3393
void MainWindow::doReleaseButton()
3394
{
3395
    DECL_TRACER("MainWindow::doReleaseButton()");
3396
 
3397
    if (mLastPressX >= 0 && mLastPressY >= 0 && gPageManager)
3398
    {
3399
        MSG_DEBUG("Sending outstanding mouse release event for coordinates x" << mLastPressX << ", y" << mLastPressY);
3400
        int x = mLastPressX;
3401
        int y = mLastPressY;
3402
 
3403
        if (isScaled())
3404
        {
3405
            x = static_cast<int>(static_cast<double>(x) / mScaleFactor);
3406
            y = static_cast<int>(static_cast<double>(y) / mScaleFactor);
3407
        }
3408
 
3409
        gPageManager->mouseEvent(x, y, false);
3410
        mLastPressX = mLastPressY = -1;
3411
    }
3412
}
3413
 
3414
/**
3415
 * @brief MainWindow::repaintObjects
3416
 * If the application was suspended, which is only on mobile devices possible,
3417
 * the surface can't be drawn. If there was a change on a visible object it
3418
 * was marked "dirty". This methos searches for all dirty marked objects and
3419
 * asks the TPageManager to resend the last drawn graphic of the object. If the
3420
 * object was a page or subpage, the whole page or subpage is redrawn. Otherwise
3421
 * only the changed object.
3422
 */
3423
void MainWindow::repaintObjects()
3424
{
3425
    DECL_TRACER("MainWindow::repaintObjects()");
3426
 
3427
    if (mRunRedraw)
3428
        return;
3429
 
3430
    std::thread thr = std::thread([=] {
3431
        mRunRedraw = true;
3432
        TObject::OBJECT_t *obj = getFirstDirty();
3433
 
3434
        while (obj)
3435
        {
3436
            if (!obj->remove && !obj->invalid && obj->dirty)
3437
            {
3438
                MSG_PROTOCOL("Refreshing widget " << handleToString (obj->handle));
3439
 
3440
                if (gPageManager)
3441
                    gPageManager->redrawObject(obj->handle);
3442
 
3443
                obj->dirty = false;
3444
            }
3445
 
3446
            obj = getNextDirty(obj);
3447
        }
3448
 
3449
        mRunRedraw = false;
3450
    });
3451
 
3452
    thr.detach();
3453
}
3454
 
3455
void MainWindow::refresh(ulong handle)
3456
{
3457
    DECL_TRACER("MainWindow::refresh(ulong handle)");
3458
 
3459
    if (!handle)
3460
        return;
3461
 
3462
    OBJECT_t *obj = findFirstChild(handle);
3463
 
3464
    while (obj)
3465
    {
3466
        MSG_DEBUG("Object " << handleToString(obj->handle) << " of type " << objectToString(obj->type) << ". Invalid: " << (obj->invalid ? "YES" : "NO") << ", Pointer: " << (obj->object.widget ? "YES" : "NO"));
3467
 
3468
        if (obj->type == OBJ_SUBVIEW && !obj->invalid && obj->object.area)
3469
        {
3470
            obj->object.area->setHidden(true);
3471
            obj->object.area->setHidden(false);
3472
            obj->object.area->setEnabled(true);
3473
            MSG_DEBUG("Subview refreshed");
3474
        }
3475
        else if (obj->type == OBJ_LIST && !obj->invalid && obj->object.list)
3476
        {
3477
            if (!obj->object.list->isEnabled())
3478
                obj->object.list->setEnabled(true);
3479
        }
3480
        else if (obj->type == OBJ_BUTTON && !obj->invalid && obj->object.label)
3481
        {
3482
            if (!obj->object.label->isEnabled())
3483
                obj->object.label->setEnabled(true);
3484
        }
3485
        else if (obj->type == OBJ_MARQUEE && !obj->invalid && obj->object.marquee)
3486
        {
3487
            if (!obj->object.marquee->isEnabled())
3488
                obj->object.marquee->setEnabled(true);
3489
        }
3490
        else if ((obj->type == OBJ_SUBPAGE || obj->type == OBJ_PAGE) && !obj->invalid && obj->object.widget)
3491
        {
3492
            if (!obj->object.widget->isEnabled())
3493
                obj->object.widget->setEnabled(true);
3494
        }
3495
 
3496
        obj = findNextChild(obj->handle);
3497
    }
3498
}
3499
 
3500
void MainWindow::markDirty(ulong handle)
3501
{
3502
    DECL_TRACER("MainWindow::markDirty(ulong handle)");
3503
 
3504
    OBJECT_t *obj = findObject(handle);
3505
 
3506
    if (!obj)
3507
        return;
3508
 
3509
    MSG_DEBUG("Object " << handleToString(handle) << " marked dirty.");
3510
    obj->dirty = true;
3511
}
3512
 
3513
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
3514
int MainWindow::calcVolume(int value)
3515
#else
3516
double MainWindow::calcVolume(int value)
3517
#endif
3518
{
3519
    DECL_TRACER("MainWindow::calcVolume(int value)");
3520
 
3521
    // volumeSliderValue is in the range [0..100]
3522
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
3523
    qreal linearVolume = QAudio::convertVolume(value / qreal(100.0),
3524
                                               QAudio::LogarithmicVolumeScale,
3525
                                               QAudio::LinearVolumeScale);
3526
 
3527
    return qRound(linearVolume * 100);
3528
#else
3529
    return static_cast<double>(value) / 100.0;
3530
#endif
3531
}
3532
 
3533
QFont MainWindow::loadFont(int number, const FONT_T& f, const FONT_STYLE style)
3534
{
3535
    DECL_TRACER("MainWindow::loadFont(int number, const FONT_t& f, const FONT_STYLE style)");
3536
 
3537
    QString path;
3538
    string prjPath = TConfig::getProjectPath();
3539
 
3540
    if (number < 32)    // System font?
3541
    {
3542
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
3543
        path.append(prjPath).append("/__system/graphics/fonts/").append(f.file);
3544
#else
3545
        path.append(prjPath.c_str()).append("/__system/graphics/fonts/").append(f.file.c_str());
3546
#endif
3547
 
3548
        if (!fs::is_regular_file(path.toStdString()))
3549
        {
3550
            MSG_WARNING("Seem to miss system fonts ...");
3551
            path.clear();
3552
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
3553
            path.append(prjPath).append("/fonts/").append(f.file);
3554
#else
3555
            path.append(prjPath.c_str()).append("/fonts/").append(f.file.c_str());
3556
#endif
3557
        }
3558
    }
3559
    else
3560
    {
3561
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
3562
        path.append(prjPath).append("/fonts/").append(f.file);
3563
#else
3564
        path.append(prjPath.c_str()).append("/fonts/").append(f.file.c_str());
3565
#endif
3566
        if (!fs::exists(path.toStdString()))
3567
        {
3568
            string pth = prjPath + "/__system/fonts/" + f.file;
3569
 
3570
            if (fs::exists(pth))
3571
            {
3572
#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
3573
                path.assign(pth);
3574
#else
3575
                path = pth.c_str();
3576
#endif
3577
            }
3578
        }
3579
    }
3580
 
3581
    const QStringList ffamilies = QFontDatabase::families();
3582
    bool haveFont = false;
3583
    QString fname = QString::fromStdString(f.name);
3584
 
3585
    for (const QString &family : ffamilies)
3586
    {
3587
        if (family == fname)
3588
        {
3589
            haveFont = true;
3590
            break;
3591
        }
3592
    }
3593
 
3594
    // Scale the font size
3595
    int pix = f.size;
3596
 
3597
    if (mScaleFactor > 0.0 && mScaleFactor != 1.0)
3598
        pix = static_cast<int>(static_cast<double>(f.size) / mScaleFactor);
3599
 
3600
    QString qstyle;
3601
    QFont font;
3602
 
3603
    switch (style)
3604
    {
3605
#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
3606
        case FONT_BOLD:         qstyle.assign("Bold"); break;
3607
        case FONT_ITALIC:       qstyle.assign("Italic"); break;
3608
        case FONT_BOLD_ITALIC:  qstyle.assign("Bold Italic"); break;
3609
 
3610
        default:
3611
            qstyle.assign("Normal");
3612
#else
3613
        case FONT_BOLD:         qstyle = "Bold"; break;
3614
        case FONT_ITALIC:       qstyle = "Italic"; break;
3615
        case FONT_BOLD_ITALIC:  qstyle = "Bold Italic"; break;
3616
 
3617
        default:
3618
            qstyle = "Normal";
3619
#endif
3620
    }
3621
 
3622
    if (!haveFont)  // Did we found the font?
3623
    {               // No, then load it
3624
        QFontDatabase::addApplicationFont(path);
3625
        font = QFontDatabase::font(fname, qstyle, pix);
3626
        MSG_DEBUG("Font \"" << path.toStdString() << "\" was loaded");
3627
    }
3628
    else
3629
    {
3630
        font.setFamily(fname);
3631
        font.setPointSize(pix);
3632
        font.setStyleName(qstyle);
3633
    }
3634
 
3635
    string family = font.family().toStdString();
3636
 
3637
    if (!font.exactMatch() && (family != f.name || font.styleName() != qstyle || font.pointSize() != pix))
3638
    {
3639
        MSG_WARNING("Using font "
3640
                    << family << "|" << font.styleName().toStdString() << "|" << font.pointSize()
3641
                    << " but requested font "
3642
                    << f.name << "|" << qstyle.toStdString() << "|" << pix << "!");
3643
    }
3644
    else
3645
    {
3646
        MSG_DEBUG("Font was set to " << f.name << "|" << qstyle.toStdString() << "|" << pix << "! " << (font.exactMatch() ? "[original]" : "[replacement]"));
3647
    }
3648
 
3649
    return font;
3650
}
3651
 
3652
/**
3653
 * @brief MainWindow::convertMask
3654
 * Converts the AMX mask for input lines into Qt mask sympols for input lines.
3655
 *
3656
 * @param mask  A string containing the AMX mask symbols.
3657
 *
3658
 * @return The converted mask string for Qt input lines.
3659
 */
3660
string MainWindow::convertMask(const string& mask)
3661
{
3662
    DECL_TRACER("MainWindow::convertMask(const string& mask)");
3663
 
3664
    string qMask;
3665
 
3666
    for (size_t i = 0; i < mask.length(); ++i)
3667
    {
3668
        switch (mask[i])
3669
        {
3670
            case '0': qMask += "9"; break;
3671
            case '9': qMask += "0"; break;
3672
            case 'A': qMask += "N"; break;
3673
            case 'a': qMask += "n"; break;
3674
            case 'L': qMask += "X"; break;
3675
            case '?': qMask += "x"; break;
3676
            case '&': qMask += "A"; break;
3677
            case 'C': qMask += "a"; break;
3678
            case '^': qMask += ";"; break;
3679
 
3680
            default:
3681
                qMask += mask[i];
3682
        }
3683
    }
3684
 
3685
    return qMask;
3686
}
3687
 
3688
#ifdef Q_OS_ANDROID
3689
void MainWindow::hideAndroidBars()
3690
{
3691
    DECL_TRACER("MainWindow::hideAndroidBars()");
3692
}
3693
#endif
3694
#ifdef Q_OS_IOS
3695
void MainWindow::setNotch()
3696
{
3697
    DECL_TRACER("MainWindow::setNotch()");
3698
 
3699
    Qt::ScreenOrientation so = getRealOrientation();
3700
 
3701
    if (so == Qt::PrimaryOrientation)
3702
        return;
3703
 
3704
    QMargins margins;
3705
 
3706
    if (mHaveNotchPortrait && (so == Qt::PortraitOrientation || so == Qt::InvertedPortraitOrientation))
3707
        margins = mNotchPortrait;
3708
    else if (mHaveNotchLandscape && (so == Qt::LandscapeOrientation || so == Qt::InvertedLandscapeOrientation))
3709
        margins = mNotchLandscape;
3710
    else
3711
    {
3712
        margins = QASettings::getNotchSize();
3713
 
3714
        if (gPageManager && gPageManager->getSettings()->isPortrait())
3715
        {
3716
            if (so == Qt::LandscapeOrientation)
3717
            {
3718
                int left = margins.left();
3719
                int top = margins.top();
3720
                margins.setTop(margins.right());
3721
                margins.setLeft(top);
3722
                margins.setRight(margins.bottom());
3723
                margins.setBottom(left);
3724
            }
3725
            else if (so == Qt::InvertedLandscapeOrientation)
3726
            {
3727
                int right = margins.right();
3728
                int top = margins.top();
3729
                margins.setTop(margins.left());
3730
                margins.setLeft(top);
3731
                margins.setRight(margins.bottom());
3732
                margins.setBottom(right);
3733
            }
3734
        }
3735
        else if (gPageManager && gPageManager->getSettings()->isLandscape())
3736
        {
3737
            if (so == Qt::PortraitOrientation)
3738
            {
3739
                int top = margins.top();
3740
                int right = margins.right();
3741
                margins.setTop(margins.left());
3742
                margins.setLeft(top);
3743
                margins.setRight(margins.bottom());
3744
                margins.setBottom(right);
3745
            }
3746
            else if (so == Qt::InvertedPortraitOrientation)
3747
            {
3748
                int top = margins.top();
3749
                int left = margins.left();
3750
                margins.setTop(margins.right());
3751
                margins.setLeft(margins.bottom());
3752
                margins.setRight(top);
3753
                margins.setBottom(left);
3754
            }
3755
        }
3756
    }
3757
#if defined(QT_DEBUG) && (defined(Q_OS_IOS) || defined(Q_OS_ANDROID))
3758
    MSG_DEBUG("Notch top: " << margins.top() << ", bottom: " << margins.bottom() << ", left: " << margins.left() << ", right: " << margins.right() << ", Orientation real: " << orientationToString(so) << ", estimated: " << orientationToString(mOrientation));
3759
#endif
3760
    if (gPageManager)
3761
    {
3762
        // If the real orientation "so" differs from "mOrientation" then
3763
        // "mOrientation" contains the wanted orientation and not the real one!
3764
        if (gPageManager->getSettings()->isPortrait() &&
3765
            (mOrientation == Qt::PortraitOrientation || mOrientation == Qt::InvertedPortraitOrientation))
3766
        {
3767
            mNotchPortrait = margins;
3768
            mHaveNotchPortrait = true;
3769
        }
3770
        else if (gPageManager->getSettings()->isLandscape() &&
3771
            (mOrientation == Qt::LandscapeOrientation || mOrientation == Qt::InvertedLandscapeOrientation))
3772
        {
3773
            mNotchLandscape = margins;
3774
            mHaveNotchLandscape = true;
3775
        }
3776
    }
3777
}
3778
 
3779
/**
3780
 * @brief MainWindow::initGeoLocation
3781
 * This method is only used on IOS to let the application run in the background.
3782
 * It is necessary because it is the only way to let an application run in
3783
 * the background.
3784
 * The method initializes the geo position module of Qt. If the app doesn't
3785
 * have the permissions to retrieve the geo positions, it will not run in the
3786
 * background. It stops at the moment the app is not in front or the display is
3787
 * closed. This makes it stop communicate with the NetLinx and looses the
3788
 * network connection. When the app gets the focus again, it must reconnect to
3789
 * the NetLinx.
3790
 */
3791
void MainWindow::initGeoLocation()
3792
{
3793
    DECL_TRACER("MainWindow::initGeoLocation()");
3794
 
3795
    if (mSource && mGeoHavePermission)
3796
        return;
3797
 
3798
    if (!mSource)
3799
    {
3800
        mGeoHavePermission = true;
3801
        mSource = QGeoPositionInfoSource::createDefaultSource(this);
3802
 
3803
        if (!mSource)
3804
        {
3805
            MSG_WARNING("Error creating geo positioning source!");
3806
            mGeoHavePermission = false;
3807
            return;
3808
        }
3809
 
3810
        mSource->setPreferredPositioningMethods(QGeoPositionInfoSource::AllPositioningMethods);
3811
        mSource->setUpdateInterval(800);    // milli seconds
3812
        // Connecting some callbacks to the class
3813
        connect(mSource, &QGeoPositionInfoSource::positionUpdated, this, &MainWindow::onPositionUpdated);
3814
        connect(mSource, &QGeoPositionInfoSource::errorOccurred, this, &MainWindow::onErrorOccurred);
3815
#ifdef Q_OS_IOS
3816
        QLocationPermission perm;
3817
        perm.setAccuracy(QLocationPermission::Approximate);
3818
        perm.setAvailability(QLocationPermission::Always);
3819
        mGeoHavePermission = false;
3820
 
3821
        switch (qApp->checkPermission(perm))
3822
        {
3823
            case Qt::PermissionStatus::Undetermined:
3824
                qApp->requestPermission(perm, [this] (const QPermission& permission)
3825
                {
3826
                    if (permission.status() == Qt::PermissionStatus::Granted)
3827
                    {
3828
                        mGeoHavePermission = true;
3829
                        mSource->startUpdates();
3830
                    }
3831
                    else
3832
                        onErrorOccurred(QGeoPositionInfoSource::AccessError);
3833
                });
3834
            break;
3835
 
3836
            case Qt::PermissionStatus::Denied:
3837
                MSG_WARNING("Location permission is denied");
3838
                onErrorOccurred(QGeoPositionInfoSource::AccessError);
3839
            break;
3840
 
3841
            case Qt::PermissionStatus::Granted:
3842
                mSource->startUpdates();
3843
                mGeoHavePermission = true;
3844
            break;
3845
        }
3846
#endif
3847
    }
3848
}
3849
 
3850
Qt::ScreenOrientation MainWindow::getRealOrientation()
3851
{
3852
    DECL_TRACER("MainWindow::getRealOrientation()");
3853
 
3854
    QScreen *screen = QGuiApplication::primaryScreen();
3855
 
3856
    if (!screen)
3857
    {
3858
        MSG_ERROR("Couldn't determine the primary screen!")
3859
        return Qt::PrimaryOrientation;
3860
    }
3861
 
3862
    QRect rect = screen->availableGeometry();
3863
 
3864
    if (rect.width() > rect.height())
3865
        return Qt::LandscapeOrientation;
3866
 
3867
    return Qt::PortraitOrientation;
3868
}
3869
#endif  // Q_OS_IOS
3870
#if defined(QT_DEBUG) && (defined(Q_OS_IOS) || defined(Q_OS_ANDROID))
3871
string MainWindow::orientationToString(Qt::ScreenOrientation ori)
3872
{
3873
    string sori;
3874
 
3875
    switch(ori)
3876
    {
3877
        case Qt::PortraitOrientation:           sori = "PORTRAIT"; break;
3878
        case Qt::InvertedPortraitOrientation:   sori = "INVERTED PORTRAIT"; break;
3879
        case Qt::LandscapeOrientation:          sori = "LANDSCAPE"; break;
3880
        case Qt::InvertedLandscapeOrientation:  sori = "INVERTED LANDSCAPE"; break;
3881
        default:
3882
            sori = "Unknown: ";
3883
            sori.append(intToString(ori));
3884
    }
3885
 
3886
    return sori;
3887
}
3888
#endif
3889
 
3890
/******************* Draw elements *************************/
3891
 
3892
/**
3893
 * @brief Displays an image.
3894
 * The method is a callback function and is called whenever an image should be
3895
 * displayed. It defines a label, set it to the (scaled) \b width and \b height
3896
 * and moves it to the (scaled) position \b left and \b top.
3897
 *
3898
 * @param handle    The unique handle of the object
3899
 * @param parent    The unique handle of the parent object.
3900
 * @param buffer    A byte array containing the image.
3901
 * @param width     The width of the object
3902
 * @param height    The height of the object
3903
 * @param pixline   The number of pixels in one line of the image.
3904
 * @param left      The prosition from the left.
3905
 * @param top       The position from the top.
3906
 * @param marqtype  The type of marquee line
3907
 * @param marq      Enabled/disabled marquee
3908
 */
3909
void MainWindow::displayButton(ulong handle, ulong parent, TBitmap buffer, int width, int height, int left, int top, bool passthrough, int marqtype, int marq)
3910
{
3911
    DECL_TRACER("MainWindow::displayButton(ulong handle, TBitmap buffer, size_t size, int width, int height, int left, int top, bool passthrough, int marqtype, int marq)");
3912
 
3913
    TObject::OBJECT_t *obj = findObject(handle);
3914
    TObject::OBJECT_t *par = findObject(parent);
3915
    MSG_TRACE("Processing button " << handleToString(handle) << " from parent " << handleToString(parent));
3916
 
3917
    if (!par)
3918
    {
3919
        if (TStreamError::checkFilter(HLOG_DEBUG))
3920
            MSG_WARNING("Button " << handleToString(handle) << " has no parent (" << handleToString(parent) << ")! Ignoring it.");
3921
#if TESTMODE == 1
3922
        setScreenDone();
3923
#endif
3924
        return;
3925
    }
3926
 
3927
    if (par->animation && !par->aniDirection)
3928
    {
3929
        if (par->animation->state() == QAbstractAnimation::Running)
3930
        {
3931
            MSG_WARNING("Object " << handleToString(parent) << " is busy with an animation!");
3932
            par->animation->stop();
3933
        }
3934
        else
3935
        {
3936
            MSG_WARNING("Object " << handleToString(parent) << " has not finished the animation!");
3937
        }
3938
 
3939
#if TESTMODE == 1
3940
        setScreenDone();
3941
#endif
3942
        return;
3943
    }
3944
    else if (par->remove)
3945
    {
3946
        MSG_WARNING("Object " << handleToString(parent) << " is marked for remove. Will not draw image!");
3947
#if TESTMODE == 1
3948
        setScreenDone();
3949
#endif
3950
        return;
3951
    }
3952
 
3953
    if (!obj)
3954
    {
3955
        if (!par->object.widget)
3956
        {
3957
            MSG_ERROR("Object " << handleToString(parent) << " has no valid widget!");
3958
#if TESTMODE == 1
3959
            setScreenDone();
3960
#endif
3961
            return;
3962
        }
3963
 
3964
        MSG_DEBUG("Adding new object " << handleToString(handle) << " ...");
3965
        OBJECT_t nobj;
3966
 
3967
        if (marqtype > 0 && marq)
3968
            nobj.type = OBJ_MARQUEE;
3969
        else
3970
            nobj.type = OBJ_BUTTON;
3971
 
3972
        nobj.handle = handle;
3973
 
449 andreas 3974
        nobj.width = scale(width);
3975
        nobj.height = scale(height);
3976
        nobj.left = scale(left);
3977
        nobj.top = scale(top);
446 andreas 3978
 
3979
        if (nobj.type == OBJ_MARQUEE)
3980
        {
3981
            nobj.object.marquee = new TQMarquee(par->object.widget, 1, static_cast<TQMarquee::MQ_TYPES>(marqtype));
3982
            nobj.object.marquee->setObjectName(QString("Marquee_") + handleToString(handle).c_str());
3983
 
3984
            if (mGestureFilter)
3985
            {
3986
                nobj.object.marquee->installEventFilter(mGestureFilter);
3987
                nobj.object.marquee->grabGesture(Qt::PinchGesture);
3988
                nobj.object.marquee->grabGesture(Qt::SwipeGesture);
3989
            }
3990
 
3991
            nobj.object.marquee->setGeometry(nobj.left, nobj.top, nobj.width, nobj.height);
3992
 
3993
            if (passthrough)
3994
                nobj.object.marquee->setAttribute(Qt::WA_TransparentForMouseEvents);
3995
        }
3996
        else
3997
        {
3998
            nobj.object.label = new QLabel(par->object.widget);
3999
            nobj.object.label->setObjectName(QString("Label_") + handleToString(handle).c_str());
4000
 
4001
            if (mGestureFilter)
4002
            {
4003
                nobj.object.label->installEventFilter(mGestureFilter);
4004
                nobj.object.label->grabGesture(Qt::PinchGesture);
4005
                nobj.object.label->grabGesture(Qt::SwipeGesture);
4006
            }
4007
 
4008
            nobj.object.label->setGeometry(nobj.left, nobj.top, nobj.width, nobj.height);
4009
 
4010
            if (passthrough)
4011
                nobj.object.label->setAttribute(Qt::WA_TransparentForMouseEvents);
4012
        }
4013
 
4014
        if (!addObject(nobj))
4015
        {
4016
            MSG_ERROR("Unable to add the new object " << handleToString(handle) << "!");
4017
#if TESTMODE == 1
4018
            setScreenDone();
4019
#endif
4020
            return;
4021
        }
4022
 
4023
        obj = findObject(handle);
4024
    }
4025
    else
4026
    {
4027
        MSG_DEBUG("Object " << handleToString(handle) << " of type " << TObject::objectToString(obj->type) << " found!");
4028
 
4029
        if (passthrough && obj->object.label)   // Because it's a union we can test on any of the pointer types
4030
        {
4031
            if (obj->type == OBJ_BUTTON)
4032
                obj->object.label->setAttribute(Qt::WA_TransparentForMouseEvents);
4033
            else if (obj->type == OBJ_MARQUEE)
4034
                obj->object.marquee->setAttribute(Qt::WA_TransparentForMouseEvents);
4035
        }
4036
 
4037
        if (!enableObject(handle))
4038
        {
4039
            MSG_ERROR("Object " << handleToString(handle) << " of type " << objectToString(obj->type) << " couldn't be enabled!");
4040
#if TESTMODE == 1
4041
            setScreenDone();
4042
#endif
4043
            return;
4044
        }
4045
 
4046
        // In case the dimensions or position has changed we calculate the
4047
        // position and size again.
449 andreas 4048
        int wt = scale(width);
4049
        int ht = scale(height);
4050
        int lt = scale(left);
4051
        int tp = scale(top);
446 andreas 4052
 
4053
        if (obj->type != OBJ_INPUT && (wt != obj->width || ht != obj->height || lt != obj->left || tp != obj->top))
4054
        {
4055
            MSG_DEBUG("Scaled button with new size: lt: " << obj->left << ", tp: " << obj->top << ", wt: " << obj->width << ", ht: " << obj->height);
4056
 
4057
            if (obj->type == OBJ_MARQUEE)
4058
                obj->object.marquee->setGeometry(lt, tp, wt, ht);
4059
            else
4060
                obj->object.label->setGeometry(lt, tp, wt, ht);
4061
 
4062
            obj->left = lt;
4063
            obj->top = tp;
4064
            obj->width = wt;
4065
            obj->height = ht;
4066
        }
4067
    }
4068
 
4069
    if (obj->type != OBJ_INPUT)
4070
    {
4071
        try
4072
        {
4073
            if (buffer.getSize() > 0 && buffer.getPixline() > 0)
4074
            {
4075
                MSG_DEBUG("Setting image for " << handleToString(handle) << " ...");
4076
                QPixmap pixmap = scaleImage(static_cast<unsigned char *>(buffer.getBitmap()), buffer.getWidth(), buffer.getHeight(), buffer.getPixline());
4077
 
4078
                if (obj->type == OBJ_MARQUEE && obj->object.marquee)
4079
                {
4080
                    obj->object.marquee->setBackground(pixmap);
4081
#if TESTMODE == 1
4082
                    __success = true;
4083
#endif
4084
                }
4085
                else if (obj->object.label)
4086
                {
4087
                    obj->object.label->setPixmap(pixmap);
4088
#if TESTMODE == 1
4089
                    __success = true;
4090
#endif
4091
                }
4092
                else
4093
                {
4094
                    MSG_WARNING("Object " << handleToString(handle) << " does not exist any more!");
4095
                }
4096
            }
4097
        }
4098
        catch(std::exception& e)
4099
        {
4100
            MSG_ERROR("Error drawing button " << handleToString(handle) << ": " << e.what());
4101
        }
4102
        catch(...)
4103
        {
4104
            MSG_ERROR("Unexpected exception occured [MainWindow::displayButton()]");
4105
        }
4106
    }
4107
#if TESTMODE == 1
4108
    setScreenDone();
4109
#endif
4110
}
4111
 
4112
void MainWindow::setMarqueeText(Button::TButton* button)
4113
{
4114
    DECL_TRACER("MainWindow::setMarqueeText(Button::TButton* button)");
4115
 
4116
    ulong handle = button->getHandle();
4117
    TObject::OBJECT_t *obj = findObject(handle);
4118
 
4119
    if (!obj)
4120
    {
4121
        MSG_WARNING("No object " << handleToString(handle) << " found!");
4122
        return;
4123
    }
4124
 
4125
    if (obj->type != OBJ_MARQUEE || !obj->object.marquee)
4126
    {
4127
        MSG_WARNING("Object " << handleToString(handle) << " is not a Marquee type or does not exist!");
4128
        return;
4129
    }
4130
 
4131
    TQMarquee *marquee = obj->object.marquee;
479 andreas 4132
    Button::ORIENTATION to = static_cast<Button::ORIENTATION>(button->getTextJustification(nullptr, nullptr, button->getActiveInstance()));
446 andreas 4133
 
4134
    switch(to)
4135
    {
4136
        case Button::ORI_TOP_LEFT:          marquee->setAlignment(Qt::AlignTop | Qt::AlignLeft); break;
4137
        case Button::ORI_TOP_MIDDLE:        marquee->setAlignment(Qt::AlignTop | Qt::AlignHCenter); break;
4138
        case Button::ORI_TOP_RIGHT:         marquee->setAlignment(Qt::AlignTop | Qt::AlignRight); break;
4139
 
4140
        case Button::ORI_CENTER_LEFT:       marquee->setAlignment(Qt::AlignHCenter | Qt::AlignLeft); break;
4141
        case Button::ORI_CENTER_MIDDLE:     marquee->setAlignment(Qt::AlignCenter); break;
4142
        case Button::ORI_CENTER_RIGHT:      marquee->setAlignment(Qt::AlignHCenter | Qt::AlignRight); break;
4143
 
4144
        case Button::ORI_BOTTOM_LEFT:       marquee->setAlignment(Qt::AlignBottom | Qt::AlignLeft); break;
4145
        case Button::ORI_BOTTOM_MIDDLE:     marquee->setAlignment(Qt::AlignBottom | Qt::AlignHCenter); break;
4146
        case Button::ORI_BOTTOM_RIGHT:      marquee->setAlignment(Qt::AlignBottom | Qt::AlignRight); break;
4147
 
4148
        default:
4149
            marquee->setAlignment(Qt::AlignCenter);
4150
    }
4151
 
4152
    marquee->setText(button->getText().c_str());
4153
    marquee->setSpeed(button->getMarqueeSpeed(button->getActiveInstance()));
4154
    int frameSize = scale(button->getBorderSize(button->getBorderStyle(button->getActiveInstance())));
4155
    marquee->setFrame(frameSize, frameSize, frameSize, frameSize);
4156
    QFont font = loadFont(button->getFontIndex(button->getActiveInstance()), button->getFont(), button->getFontStyle());
4157
    marquee->setFont(font);
4158
}
4159
 
4160
void MainWindow::displayViewButton(ulong handle, ulong parent, bool vertical, TBitmap buffer, int width, int height, int left, int top, int space, TColor::COLOR_T fillColor)
4161
{
4162
    DECL_TRACER("MainWindow::displayViewButton(ulong handle, TBitmap buffer, size_t size, int width, int height, int left, int top)");
4163
 
4164
    TObject::OBJECT_t *obj = findObject(handle);
4165
    TObject::OBJECT_t *par = findObject(parent);
4166
    MSG_TRACE("Processing button " << handleToString(handle) << " from parent " << handleToString(parent));
4167
 
4168
    if (!par)
4169
    {
4170
        if (TStreamError::checkFilter(HLOG_DEBUG))
4171
            MSG_WARNING("Button " << handleToString(handle) << " has no parent (" << handleToString(parent) << ")! Ignoring it.");
4172
 
4173
#if TESTMODE == 1
4174
        setScreenDone();
4175
#endif
4176
        return;
4177
    }
4178
 
4179
    if (par->animation && !par->aniDirection)
4180
    {
4181
        if (par->animation->state() == QAbstractAnimation::Running)
4182
        {
4183
            MSG_WARNING("Object " << handleToString(parent) << " is busy with an animation!");
4184
            par->animation->stop();
4185
        }
4186
        else
4187
        {
4188
            MSG_WARNING("Object " << handleToString(parent) << " has not finished the animation!");
4189
        }
4190
 
4191
#if TESTMODE == 1
4192
        setScreenDone();
4193
#endif
4194
        return;
4195
    }
4196
    else if (par->remove)
4197
    {
4198
        MSG_WARNING("Object " << handleToString(parent) << " is marked for remove. Will not draw image!");
4199
#if TESTMODE == 1
4200
        setScreenDone();
4201
#endif
4202
        return;
4203
    }
4204
 
4205
    if (!obj)
4206
    {
4207
        if (!par->object.widget)
4208
        {
4209
#if TESTMODE == 1
4210
            MSG_ERROR("Object " << handleToString(parent) << " has no valid object!");
4211
#endif
4212
            return;
4213
        }
4214
 
4215
        MSG_DEBUG("Adding new object " << handleToString(handle) << " ...");
4216
        OBJECT_t nobj;
4217
 
4218
        nobj.type = OBJ_SUBVIEW;
4219
        nobj.handle = handle;
4220
 
4221
        nobj.width = scale(width);
4222
        nobj.height = scale(height);
4223
        nobj.left = scale(left);
4224
        nobj.top = scale(top);
4225
 
4226
        nobj.object.area = new TQScrollArea(par->object.widget, nobj.width, nobj.height, vertical);
4227
        nobj.object.area->setObjectName(QString("View_") + handleToString(handle).c_str());
4228
        nobj.object.area->setScaleFactor(mScaleFactor);
4229
        nobj.object.area->setSpace(space);
4230
        nobj.object.area->move(nobj.left, nobj.top);
4231
        nobj.connected = true;
4232
        connect(nobj.object.area, &TQScrollArea::objectClicked, this, &MainWindow::onSubViewItemClicked);
4233
 
4234
        if (!addObject(nobj))
4235
        {
4236
            MSG_ERROR("Couldn't add the object " << handleToString(handle) << "!");
4237
#if TESTMODE == 1
4238
            setScreenDone();
4239
#endif
4240
            return;
4241
        }
4242
 
4243
        obj = findObject(handle);
4244
    }
4245
    else if (obj->type != OBJ_SUBVIEW)
4246
    {
4247
        MSG_ERROR("Object " << handleToString(handle) << " is of wrong type " << objectToString(obj->type) << "!");
4248
#if TESTMODE == 1
4249
        setScreenDone();
4250
#endif
4251
        return;
4252
    }
4253
    else
4254
    {
4255
        MSG_DEBUG("Object " << handleToString(handle) << " of type " << TObject::objectToString(obj->type) << " found!");
4256
 
4257
        if (obj->object.area && !obj->connected)
4258
            reconnectArea(obj->object.area);
4259
    }
4260
 
4261
    try
4262
    {
4263
        // Set background color
4264
        if (obj->object.area)
4265
        {
4266
            QColor color;
4267
 
4268
            if (fillColor.alpha == 0)
4269
                color = Qt::transparent;
4270
            else
4271
                color = qRgba(fillColor.red, fillColor.green, fillColor.blue, fillColor.alpha);
4272
 
4273
            obj->object.area->setBackGroundColor(color);
4274
        }
4275
 
4276
        if (buffer.getSize() > 0 && buffer.getPixline() > 0)
4277
        {
4278
            MSG_DEBUG("Setting image for " << handleToString(handle) << " ...");
4279
            QPixmap pixmap = scaleImage(static_cast<unsigned char *>(buffer.getBitmap()), buffer.getWidth(), buffer.getHeight(), buffer.getPixline());
4280
 
4281
            if (pixmap.isNull())
4282
            {
4283
                MSG_ERROR("Unable to create a pixmap out of an image!");
4284
#if TESTMODE == 1
4285
                setScreenDone();
4286
#endif
4287
                return;
4288
            }
4289
 
4290
            if (obj->object.area)
4291
            {
4292
                obj->object.area->setBackgroundImage(pixmap);
4293
            }
4294
            else
4295
            {
4296
                MSG_WARNING("Object " << handleToString(handle) << " does not exist any more!");
4297
            }
4298
        }
4299
    }
4300
    catch(std::exception& e)
4301
    {
4302
        MSG_ERROR("Error drawing button " << handleToString(handle) << ": " << e.what());
4303
    }
4304
    catch(...)
4305
    {
4306
        MSG_ERROR("Unexpected exception occured [MainWindow::displayViewButton()]");
4307
    }
4308
}
4309
 
4310
void MainWindow::addViewButtonItems(ulong parent, vector<PGSUBVIEWITEM_T> items)
4311
{
4312
    DECL_TRACER("MainWindow::addViewButtonItems(ulong parent, vector<PGSUBVIEWITEM_T> items)");
4313
 
4314
    if (items.empty())
4315
        return;
4316
 
4317
    OBJECT_t *par = findObject(parent);
4318
 
4319
    if (!par || par->type != OBJ_SUBVIEW || !par->object.area)
4320
    {
4321
        MSG_ERROR("No object with handle " << handleToString(parent) << " found or object is not a subview list!");
4322
        return;
4323
    }
4324
 
4325
    if (par->invalid)
4326
    {
4327
        if (!enableObject(parent))
4328
        {
4329
            MSG_ERROR("Object " << handleToString(parent) << " of type " << objectToString(par->type) << " couldn't be enabled!");
4330
#if TESTMODE == 1
4331
            setScreenDone();
4332
#endif
4333
            return;
4334
        }
4335
    }
4336
 
4337
    if (!items.empty())
4338
    {
4339
        par->object.area->setScrollbar(items[0].scrollbar);
4340
        par->object.area->setScrollbarOffset(items[0].scrollbarOffset);
4341
        par->object.area->setAnchor(items[0].position);
4342
    }
4343
 
4344
    par->object.area->addItems(items);
4345
}
4346
 
4347
void MainWindow::updateViewButton(ulong handle, ulong parent, TBitmap buffer, TColor::COLOR_T fillColor)
4348
{
4349
    DECL_TRACER("MainWindow::updateViewButton(ulong handle, ulong parent, TBitmap buffer, TColor::COLOR_T fillColor)");
4350
 
4351
    OBJECT_t *par = findObject(parent);
4352
 
4353
    if (!par || par->type != OBJ_SUBVIEW || !par->object.area)
4354
    {
4355
        MSG_ERROR("No object with handle " << handleToString(parent) << " found for update or object is not a subview list!");
4356
#if TESTMODE == 1
4357
        setScreenDone();
4358
#endif
4359
        return;
4360
    }
4361
 
4362
    PGSUBVIEWITEM_T item;
4363
    item.handle = handle;
4364
    item.parent = parent;
4365
    item.image = buffer;
4366
    item.bgcolor = fillColor;
4367
    par->object.area->updateItem(item);
4368
}
4369
 
4370
void MainWindow::updateViewButtonItem(PGSUBVIEWITEM_T& item, ulong parent)
4371
{
4372
    DECL_TRACER("MainWindow::updateViewButtonItem(PGSUBVIEWITEM_T& item, ulong parent)");
4373
 
4374
    OBJECT_t *par = findObject(parent);
4375
 
4376
    if (!par || par->type != OBJ_SUBVIEW || !par->object.area)
4377
    {
4378
        MSG_ERROR("No object with handle " << handleToString(parent) << " found for update or object is not a subview list!");
4379
#if TESTMODE == 1
4380
        setScreenDone();
4381
#endif
4382
        return;
4383
    }
4384
 
4385
    par->object.area->updateItem(item);
4386
}
4387
 
4388
void MainWindow::showViewButtonItem(ulong handle, ulong parent, int position, int timer)
4389
{
4390
    DECL_TRACER("MainWindow::showViewButtonItem(ulong handle, ulong parent, int position, int timer)");
4391
 
4392
    Q_UNUSED(timer);
4393
 
4394
    OBJECT_t *par = findObject(parent);
4395
 
4396
    if (!par || par->type != OBJ_SUBVIEW || !par->object.area)
4397
    {
4398
        MSG_ERROR("No object with handle " << handleToString(parent) << " found for update or object is not a subview list!");
4399
#if TESTMODE == 1
4400
        setScreenDone();
4401
#endif
4402
        return;
4403
    }
4404
 
4405
    par->object.area->showItem(handle, position);
4406
}
4407
 
4408
void MainWindow::toggleViewButtonItem(ulong handle, ulong parent, int position, int timer)
4409
{
4410
    DECL_TRACER("MainWindow::toggleViewButtonItem(ulong handle, ulong parent, int position, int timer)");
4411
 
4412
    Q_UNUSED(timer);
4413
 
4414
    OBJECT_t *par = findObject(parent);
4415
 
4416
    if (!par || par->type != OBJ_SUBVIEW || !par->object.area)
4417
    {
4418
        MSG_ERROR("No object with handle " << handleToString(parent) << " found for update or object is not a subview list!");
4419
#if TESTMODE == 1
4420
        setScreenDone();
4421
#endif
4422
        return;
4423
    }
4424
 
4425
    par->object.area->showItem(handle, position);
4426
}
4427
 
4428
void MainWindow::hideAllViewItems(ulong handle)
4429
{
4430
    DECL_TRACER("MainWindow::hideAllViewItems(ulong handle)");
4431
 
4432
    OBJECT_t *obj = findObject(handle);
4433
 
4434
    if (!obj || obj->type != OBJ_SUBVIEW || !obj->object.area)
4435
    {
4436
#if TESTMODE == 1
4437
        setScreenDone();
4438
#endif
4439
        return;
4440
    }
4441
 
4442
    obj->object.area->hideAllItems();
4443
}
4444
 
4445
void MainWindow::hideViewItem(ulong handle, ulong parent)
4446
{
4447
    DECL_TRACER("MainWindow::hideViewItem(ulong handle, ulong parent)");
4448
 
4449
    OBJECT_t *obj = findObject(parent);
4450
 
4451
    if (!obj || obj->type != OBJ_SUBVIEW || !obj->object.area)
4452
    {
4453
#if TESTMODE == 1
4454
        setScreenDone();
4455
#endif
4456
        return;
4457
    }
4458
 
4459
    obj->object.area->hideItem(handle);
4460
}
4461
 
4462
void MainWindow::SetVisible(ulong handle, bool state)
4463
{
4464
    DECL_TRACER("MainWindow::SetVisible(ulong handle, bool state)");
4465
 
4466
    OBJECT_t *obj = findObject(handle);
4467
 
4468
    if (!obj)
4469
    {
4470
        MSG_ERROR("Object " << handleToString(handle) << " not found!");
4471
#if TESTMODE == 1
4472
        setScreenDone();
4473
#endif
4474
        return;
4475
    }
4476
 
4477
    if (obj->type == OBJ_BUTTON && obj->object.label)
4478
    {
4479
        obj->object.label->setVisible(state);
4480
        obj->invalid = false;
4481
        obj->remove = false;
4482
    }
4483
    else if (obj->type == OBJ_MARQUEE && obj->object.marquee)
4484
    {
4485
        obj->object.marquee->setVisible(state);
4486
        obj->invalid = false;
4487
        obj->remove = false;
4488
    }
4489
    else if (obj->type == OBJ_SUBVIEW && obj->object.area)
4490
    {
4491
        obj->object.area->setVisible(state);
4492
        obj->invalid = false;
4493
        obj->remove = false;
4494
    }
4495
    else
4496
    {
4497
        MSG_DEBUG("Ignoring non button object " << handleToString(handle));
4498
    }
4499
}
4500
 
4501
void MainWindow::setSubViewPadding(ulong handle, int padding)
4502
{
4503
    DECL_TRACER("MainWindow::setSubViewPadding(ulong handle, int padding)");
4504
 
4505
    OBJECT_t *obj = findObject(handle);
4506
 
4507
    if (!obj)
4508
    {
4509
        MSG_ERROR("Object " << handleToString(handle) << " not found!");
4510
#if TESTMODE == 1
4511
        setScreenDone();
4512
#endif
4513
        return;
4514
    }
4515
 
4516
    if (obj->type != OBJ_SUBVIEW || !obj->object.area)
4517
    {
4518
#if TESTMODE == 1
4519
        setScreenDone();
4520
#endif
4521
        return;
4522
    }
4523
 
4524
    obj->object.area->setSpace(padding);
4525
}
4526
 
4527
/**
4528
 * @brief Prepares a new object.
4529
 * The method first checks whether there exists a background widget or not. If
4530
 * not it creates a background widget with a black background. On Android this
4531
 * image is the size of the whole screen while on a desktop it is only the size
4532
 * of a page plus the task bar, if any.
4533
 * If the background image (centralWidget()) already exists, it set's only the
4534
 * credentials of the object.
4535
 * It makes sure that all child objects of the central widget are destroyed.
4536
 *
4537
 * @param handle    The handle of the new widget
4538
 * @param width     The original width of the page
4539
 * @param heoght    The original height of the page
4540
 */
4541
void MainWindow::setPage(ulong handle, int width, int height)
4542
{
4543
    DECL_TRACER("MainWindow::setPage(ulong handle, int width, int height)");
4544
 
4545
    if (handle == mActualPageHandle)
4546
    {
4547
#if TESTMODE == 1
4548
        setScreenDone();
4549
#endif
4550
        return;
4551
    }
4552
 
4553
//    TLOCKER(draw_mutex);
4554
    QWidget *wBackground = centralWidget();
4555
 
4556
    if (!wBackground)
4557
    {
4558
        MSG_ERROR("No central widget!");
4559
#if TESTMODE == 1
4560
        setScreenDone();
4561
#endif
4562
        return;
4563
    }
4564
 
4565
    if (!mCentralWidget)
4566
    {
4567
        MSG_ERROR("Stack for pages not initialized!");
4568
#if TESTMODE == 1
4569
        setScreenDone();
4570
#endif
4571
        return;
4572
    }
4573
 
4574
    // The following should be true only for the first time this method is called.
4575
    if (!mCentralInitialized)
4576
    {
4577
        QSize qs = menuBar()->sizeHint();
4578
 
449 andreas 4579
        setMinimumSize(scale(width), scale(height) + qs.height());
446 andreas 4580
        mCentralInitialized = true;
4581
    }
4582
 
4583
    OBJECT_t *obj = findObject(handle);
4584
 
4585
    if (!obj)
4586
    {
4587
        MSG_DEBUG("Adding new object " << handleToString(handle));
4588
        OBJECT_t nobj;
4589
 
4590
        nobj.handle = handle;
4591
        nobj.type = OBJ_PAGE;
4592
        nobj.object.widget = nullptr;
449 andreas 4593
        nobj.height = scale(height);
4594
        nobj.width = scale(width);
446 andreas 4595
 
4596
        if (!addObject(nobj))
4597
        {
4598
            MSG_ERROR("Error crating an object for handle " << handleToString(handle));
4599
#if TESTMODE == 1
4600
            setScreenDone();
4601
#endif
4602
            return;
4603
        }
4604
 
4605
        obj = findObject(handle);
4606
    }
4607
    else
4608
    {
4609
        if (obj->type != OBJ_PAGE)
4610
        {
4611
            MSG_WARNING("Object " << handleToString(handle) << " is not a page! Will not reuse it as a page.");
4612
#if TESTMODE == 1
4613
            setScreenDone();
4614
#endif
4615
            return;
4616
        }
4617
 
4618
        if (obj->object.widget && obj->object.widget->isHidden() && mCentralWidget->indexOf(obj->object.widget) >= 0)
4619
            obj->object.widget->setParent(wBackground);
4620
 
4621
        obj->invalid = false;
4622
        obj->remove = false;
4623
        MSG_DEBUG("Hidden object " << handleToString(handle) << " was reactivated.");
4624
    }
4625
 
4626
    if (!obj->object.widget)
4627
    {
4628
        obj->object.widget = new QWidget;
4629
        obj->object.widget->setObjectName(QString("Page_") + handleToString(handle).c_str());
4630
 
4631
        if (mGestureFilter)
4632
        {
4633
            obj->object.widget->installEventFilter(mGestureFilter);
4634
            obj->object.widget->grabGesture(Qt::PinchGesture);
4635
            obj->object.widget->grabGesture(Qt::SwipeGesture);
4636
        }
4637
 
4638
        obj->object.widget->setAutoFillBackground(true);
4639
        obj->invalid = false;
4640
        obj->object.widget->move(0, 0);
4641
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
4642
        obj->object.widget->setFixedSize(obj->width, obj->height);
4643
#else
4644
        obj->object.widget->setGeometry(geometry());
4645
#endif
4646
        mCentralWidget->addWidget(obj->object.widget);
4647
    }
4648
 
4649
    mActualPageHandle = handle;
4650
    MSG_PROTOCOL("Current page: " << handleToString(handle));
4651
}
4652
 
4653
void MainWindow::setSubPage(ulong handle, ulong parent, int left, int top, int width, int height, ANIMATION_t animate, bool modal)
4654
{
4655
    DECL_TRACER("MainWindow::setSubPage(ulong handle, ulong parent, int left, int top, int width, int height, ANIMATION_t animate, bool modal)");
4656
 
4657
    Q_UNUSED(height);
4658
    Q_UNUSED(modal);
4659
    OBJECT_t *par = findObject(parent);
4660
 
4661
    if (!par || par->type != OBJ_PAGE)
4662
    {
4663
        if (!par)
4664
        {
4665
            MSG_ERROR("Subpage " << handleToString(handle) << " has no parent! Ignoring it.");
4666
        }
4667
        else
4668
        {
4669
            MSG_ERROR("Subpage " << handleToString(handle) << " has invalid parent " << handleToString(parent) << " which is no page! Ignoring it.");
4670
        }
4671
#if TESTMODE == 1
4672
        setScreenDone();
4673
#endif
4674
        return;
4675
    }
4676
 
4677
    if (!par->object.widget)
4678
    {
4679
        MSG_ERROR("Parent page " << handleToString(parent) << " has no widget defined!");
4680
#if TESTMODE == 1
4681
        setScreenDone();
4682
#endif
4683
        return;
4684
    }
4685
 
4686
    if (mCentralWidget && mCentralWidget->currentWidget() != par->object.widget)
4687
    {
4688
        MSG_WARNING("The parent page " << handleToString(parent) << " is not the current page " << handleToString(handle) << "!");
4689
#if TESTMODE == 1
4690
        setScreenDone();
4691
#endif
4692
        return;
4693
    }
4694
 
4695
    OBJECT_t *obj = findObject(handle);
4696
    OBJECT_t nobj;
4697
    bool shouldAdd = false;
4698
 
4699
    if (obj && obj->type != OBJ_SUBPAGE)
4700
    {
4701
        MSG_WARNING("Object " << handleToString(handle) << " exists but is not a subpage! Refusing to create a new page with this handle.");
4702
#if TESTMODE == 1
4703
        setScreenDone();
4704
#endif
4705
        return;
4706
    }
4707
    else if (!obj)
4708
    {
4709
        obj = &nobj;
4710
        shouldAdd = true;
4711
    }
4712
    else
4713
    {
4714
        obj->invalid = false;
4715
        obj->remove = false;
4716
    }
4717
 
449 andreas 4718
    int scLeft = scale(left);
4719
    int scTop = scale(top);
4720
    int scWidth = scale(width);
4721
    int scHeight = scale(height);
446 andreas 4722
 
4723
    obj->type = OBJ_SUBPAGE;
4724
    obj->handle = handle;
4725
 
4726
    if (!obj->object.widget)
4727
    {
4728
        obj->object.widget = new QWidget(par->object.widget);
4729
        obj->object.widget->setObjectName(QString("Subpage_%1").arg(handleToString(handle).c_str()));
4730
/*
4731
        if (modal)
4732
        {
4733
            obj->object.widget->setWindowModality(Qt::WindowModal);
4734
            MSG_TRACE("Subpage " << handleToString(handle) << " is a modal page");
4735
        }
4736
*/
4737
    }
4738
    else
4739
        obj->object.widget->setParent(par->object.widget);
4740
 
4741
    obj->object.widget->setAutoFillBackground(true);
4742
    obj->object.widget->move(scLeft, scTop);
4743
    obj->object.widget->setFixedSize(scWidth, scHeight);
4744
    obj->left = scLeft;
4745
    obj->top = scTop;
4746
    obj->width = scWidth;
4747
    obj->height = scHeight;
4748
    obj->invalid = false;
4749
    obj->remove = false;
4750
    // filter move event
4751
    if (mGestureFilter)
4752
    {
4753
        obj->object.widget->installEventFilter(mGestureFilter);
4754
        obj->object.widget->grabGesture(Qt::PinchGesture);
4755
        obj->object.widget->grabGesture(Qt::SwipeGesture);
4756
    }
4757
 
4758
    obj->aniDirection = true;
4759
    obj->animate = animate;
4760
 
4761
    if (shouldAdd)
4762
    {
4763
        if (!addObject(nobj))
4764
        {
4765
            MSG_ERROR("Couldn't add the object " << handleToString(handle) << "!");
4766
            nobj.object.widget->close();
4767
#if TESTMODE == 1
4768
            setScreenDone();
4769
#endif
4770
        }
4771
    }
4772
}
4773
 
4774
#ifdef _OPAQUE_SKIA_
4775
void MainWindow::setBackground(ulong handle, TBitmap image, int width, int height, ulong color)
4776
#else
4777
void MainWindow::setBackground(ulong handle, TBitmap image, int width, int height, ulong color, int opacity)
4778
#endif
4779
{
4780
    DECL_TRACER("MainWindow::setBackground(ulong handle, TBitmap image, ulong color [, int opacity])");
4781
 
4782
    Q_UNUSED(height);
4783
 
4784
    if (!mCentralWidget)
4785
    {
4786
        MSG_ERROR("The internal page stack is not initialized!");
4787
#if TESTMODE == 1
4788
        setScreenDone();
4789
#endif
4790
        return;
4791
    }
4792
 
4793
    OBJECT_t *obj = findObject(handle);
4794
 
4795
    if (!obj || obj->remove)
4796
    {
4797
#ifdef QT_DEBUG
4798
        if (obj)
4799
        {
4800
            MSG_WARNING("No object " << handleToString(handle) << " found! (Flag remove: " << (obj->remove ? "TRUE" : "FALSE") << ")");
4801
        }
4802
        else
4803
        {
4804
            MSG_WARNING("No object " << handleToString(handle) << " found!");
4805
        }
4806
#else
4807
        MSG_WARNING("No object " << handleToString(handle) << " found!");
4808
#endif
4809
#if TESTMODE == 1
4810
        setScreenDone();
4811
#endif
4812
        return;
4813
    }
4814
    else if (obj->invalid)
4815
    {
4816
        if (!enableObject(handle))
4817
        {
4818
            MSG_ERROR("Object " << handleToString(handle) << " of type " << objectToString(obj->type) << " couldn't be anabled!");
4819
#if TESTMODE == 1
4820
            setScreenDone();
4821
#endif
4822
            return;
4823
        }
4824
    }
4825
 
4826
    if (obj->type != OBJ_SUBPAGE && obj->type != OBJ_BUTTON && obj->type != OBJ_PAGE)
4827
    {
4828
        MSG_ERROR("Method does not support object type " << objectToString(obj->type) << " for object " << handleToString(handle) << "!");
4829
#if TESTMODE == 1
4830
        setScreenDone();
4831
#endif
4832
        return;
4833
    }
4834
 
4835
    MSG_DEBUG("Object " << handleToString(handle) << " of type " << objectToString(obj->type) << " found!");
4836
 
4837
    if (obj->type == OBJ_BUTTON || obj->type == OBJ_SUBPAGE)
4838
    {
4839
        MSG_DEBUG("Processing object " << objectToString(obj->type));
4840
 
4841
        if ((obj->type == OBJ_BUTTON || obj->type == OBJ_MARQUEE) && !obj->object.label)
4842
        {
4843
            MSG_ERROR("The label of the object " << handleToString(handle) << " was not initialized!");
4844
#if TESTMODE == 1
4845
            setScreenDone();
4846
#endif
4847
            return;
4848
        }
4849
        else if (obj->type == OBJ_SUBPAGE && !obj->object.widget)
4850
        {
4851
            MSG_ERROR("The widget of the object " << handleToString(handle) << " was not initialized!");
4852
#if TESTMODE == 1
4853
            setScreenDone();
4854
#endif
4855
            return;
4856
        }
4857
 
4858
        QPixmap pix(obj->width, obj->height);
4859
 
4860
        if (TColor::getAlpha(color) == 0)
4861
            pix.fill(Qt::transparent);
4862
        else
4863
            pix.fill(QColor::fromRgba(qRgba(TColor::getRed(color),TColor::getGreen(color),TColor::getBlue(color),TColor::getAlpha(color))));
4864
 
4865
        if (image.isValid() > 0)
4866
        {
4867
            MSG_DEBUG("Setting image of size " << image.getSize() << " (" << image.getWidth() << " x " << image.getHeight() << ")");
4868
            QImage img(image.getBitmap(), image.getWidth(), image.getHeight(), image.getPixline(), QImage::Format_ARGB32);
4869
 
449 andreas 4870
            if (isScaled())
446 andreas 4871
            {
4872
                QSize size(obj->width, obj->height);
4873
                pix.convertFromImage(img.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
4874
            }
4875
            else
4876
                pix.convertFromImage(img);
4877
        }
4878
 
4879
        if (obj->type == OBJ_BUTTON)
4880
            obj->object.label->setPixmap(pix);
4881
        else if (obj->type == OBJ_MARQUEE)
4882
            obj->object.marquee->setBackground(pix);
4883
        else
4884
        {
4885
            MSG_DEBUG("Setting image as background for subpage " << handleToString(handle));
4886
            QPalette palette(obj->object.widget->palette());
4887
#ifndef _OPAQUE_SKIA_
4888
            qreal oo;
4889
 
4890
            if (opacity < 0)
4891
                oo = 0.0;
4892
            else if (opacity > 255)
4893
                oo = 1.0;
4894
            else
4895
                oo = 1.0 / 255.0 * (qreal)opacity;
4896
 
4897
            if (oo < 1.0)
4898
            {
4899
                QPixmap image(pix.size());      //Image with given size and format.
4900
                image.fill(Qt::transparent);    //fills with transparent
4901
                QPainter p(&image);
4902
                p.setOpacity(oo);               // set opacity from 0.0 to 1.0, where 0.0 is fully transparent and 1.0 is fully opaque.
4903
                p.drawPixmap(0, 0, pix);        // given pixmap into the paint device.
4904
                p.end();
4905
                palette.setBrush(QPalette::Window, QBrush(image));
4906
                MSG_DEBUG("Opacity was set to " << oo);
4907
            }
4908
            else
4909
                palette.setBrush(QPalette::Window, QBrush(pix));
4910
#else
4911
            palette.setBrush(QPalette::Window, QBrush(pix));
4912
#endif
4913
            obj->object.widget->setPalette(palette);
4914
        }
4915
    }
4916
    else if (obj->type == TObject::OBJ_PAGE)
4917
    {
4918
        MSG_DEBUG("Processing object of type PAGE ...");
4919
        QWidget *central = obj->object.widget;
4920
 
4921
        if (!central)
4922
        {
4923
            MSG_ERROR("There is no page widget initialized for page " << handleToString(handle));
4924
#if TESTMODE == 1
4925
            setScreenDone();
4926
#endif
4927
            displayMessage("Can't set a background without an active page!", "Internal error");
4928
            return;
4929
        }
4930
 
4931
        QWidget *current = mCentralWidget->currentWidget();
4932
        int index = -1;
4933
 
4934
        if (current && central != current)
4935
        {
4936
            if ((index = mCentralWidget->indexOf(central)) < 0)
4937
            {
4938
                QString obName = QString("Page_%1").arg(handleToString(handle).c_str());
4939
 
4940
                for (int i = 0; i < mCentralWidget->count(); ++i)
4941
                {
4942
                    QWidget *w = mCentralWidget->widget(i);
4943
                    MSG_DEBUG("Checking widget " << w->objectName().toStdString());
4944
 
4945
                    if (w->objectName() == obName)
4946
                    {
4947
                        index = i;
4948
                        break;
4949
                    }
4950
                }
4951
 
4952
                if (index < 0)
4953
                {
4954
                    MSG_WARNING("Missing page " << handleToString(handle) << " on stack! Will add it to the stack.");
4955
                    index = mCentralWidget->addWidget(central);
4956
                    MSG_DEBUG("Number pages on stack: " << mCentralWidget->count());
4957
                    QRect geomMain = geometry();
4958
                    QRect geomCent = mCentralWidget->geometry();
4959
                    MSG_DEBUG("Geometry MainWindow: left: " << geomMain.left() << ", right: " << geomMain.right() << ", top: " << geomMain.top() << ", bottom: " << geomMain.bottom());
4960
                    MSG_DEBUG("Geometry CentWindow: left: " << geomCent.left() << ", right: " << geomCent.right() << ", top: " << geomCent.top() << ", bottom: " << geomCent.bottom());
4961
                }
4962
            }
4963
        }
4964
        else
4965
            index = mCentralWidget->indexOf(central);
4966
 
4967
        QPixmap pix(obj->width, obj->height);
4968
        QColor backgroundColor;
4969
 
4970
        if (TColor::getAlpha(color) == 0)
4971
            backgroundColor = Qt::transparent;
4972
        else
4973
            backgroundColor = QColor::fromRgba(qRgba(TColor::getRed(color),TColor::getGreen(color),TColor::getBlue(color),TColor::getAlpha(color)));
4974
 
4975
        pix.fill(backgroundColor);
4976
        MSG_DEBUG("Filled background of size " << pix.width() << "x" << pix.height() << " with color #" << std::setfill('0') << std::setw(8) << std::hex << color);
4977
 
4978
        if (width > 0 && image.isValid())
4979
        {
4980
            QImage img(image.getBitmap(), image.getWidth(), image.getHeight(), image.getPixline(), QImage::Format_ARGB32);
4981
            bool valid = false;
4982
 
4983
            if (!img.isNull())
4984
            {
4985
                if (isScaled())
4986
                {
4987
                    QImage bgImage = img.scaled(obj->width, obj->height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
4988
                    valid = pix.convertFromImage(bgImage);
4989
                    MSG_DEBUG("Scaled image from " << width << "x" << height << " to " << obj->width << "x" << obj->height);
4990
                }
4991
                else
4992
                {
4993
                    valid = pix.convertFromImage(img);
4994
                    MSG_DEBUG("Converted image to pixmap.");
4995
                }
4996
            }
4997
 
4998
            if (!valid || pix.isNull())
4999
            {
5000
                if (pix.isNull())
5001
                    pix = QPixmap(obj->width, obj->height);
5002
 
5003
                pix.fill(backgroundColor);
5004
                MSG_WARNING("Error converting an image! Size raw data: " << image.getSize() << ", Width: " << image.getWidth() << ", Height: " << image.getHeight() << ", Bytes per row: " << image.getPixline());
5005
            }
5006
        }
5007
 
5008
        QPalette palette(central->palette());
5009
        palette.setBrush(QPalette::Window, QBrush(pix));
5010
        central->setPalette(palette);
5011
 
5012
        if (index >= 0)
5013
            mCentralWidget->setCurrentIndex(index);
5014
        else if (mCentralWidget)
5015
        {
5016
            index = mCentralWidget->addWidget(central);
5017
            mCentralWidget->setCurrentIndex(index);
5018
            MSG_DEBUG("Page widget " << handleToString(handle) << " was added at index " << index);
5019
        }
5020
 
5021
        MSG_DEBUG("Background set");
5022
    }
5023
}
5024
 
5025
void MainWindow::disconnectArea(TQScrollArea* area)
5026
{
5027
    DECL_TRACER("MainWindow::disconnectArea(TQScrollArea* area)");
5028
 
5029
    if (!area)
5030
        return;
5031
 
5032
    disconnect(area, &TQScrollArea::objectClicked, this, &MainWindow::onSubViewItemClicked);
5033
}
5034
 
5035
void MainWindow::disconnectList(QListWidget* list)
5036
{
5037
    DECL_TRACER("MainWindow::disconnectList(QListWidget* list)");
5038
 
5039
    if (!list)
5040
        return;
5041
 
5042
    disconnect(list, &QListWidget::currentItemChanged, this, &MainWindow::onTListCallbackCurrentItemChanged);
5043
}
5044
 
5045
void MainWindow::reconnectArea(TQScrollArea * area)
5046
{
5047
    DECL_TRACER("MainWindow::reconnectArea(TQScrollArea * area)");
5048
 
5049
    if (!area)
5050
        return;
5051
 
5052
    connect(area, &TQScrollArea::objectClicked, this, &MainWindow::onSubViewItemClicked);
5053
}
5054
 
5055
void MainWindow::reconnectList(QListWidget *list)
5056
{
5057
    DECL_TRACER("MainWindow::reconnectList(QListWidget *list)");
5058
 
5059
    if (!list)
5060
        return;
5061
 
5062
    connect(list, &QListWidget::currentItemChanged, this, &MainWindow::onTListCallbackCurrentItemChanged);
5063
}
5064
 
5065
/**
5066
 * @brief MainWindow::dropPage - Marks a page invalid
5067
 * This method marks a page and all the object on the page as invalid. They are
5068
 * not deleted. Instead the page, a QWidget representing a page, is set hidden.
5069
 * With it all childs of the QWidget are also hidden. So the page can be
5070
 * displayed later when it is used again.
5071
 *
5072
 * @param handle    The handle of the page.
5073
 */
5074
void MainWindow::dropPage(ulong handle)
5075
{
5076
//    TLOCKER(draw_mutex);
5077
    DECL_TRACER("MainWindow::dropPage(ulong handle)");
5078
 
5079
    MSG_PROTOCOL("Dropping page " << handleToString(handle));
5080
 
5081
    OBJECT_t *obj = findObject(handle);
5082
 
5083
    if (!obj)
5084
    {
5085
        MSG_WARNING("Object " << handleToString(handle) << " (Page) does not exist. Ignoring!");
5086
#if TESTMODE == 1
5087
        setScreenDone();
5088
#endif
5089
        return;
5090
    }
5091
 
5092
    if (obj->type != OBJ_PAGE)
5093
    {
5094
        MSG_WARNING("Object " << handleToString(handle) << " is not a page!");
5095
#if TESTMODE == 1
5096
        setScreenDone();
5097
#endif
5098
        return;
5099
    }
5100
 
5101
    MSG_DEBUG("Dropping page " << handleToString(handle));
5102
    invalidateAllSubObjects(handle);
5103
 
5104
    if (obj->object.widget)
5105
    {
5106
        obj->object.widget->setHidden(true);
5107
#if TESTMODE == 1
5108
        __success = true;
5109
#endif
5110
    }
5111
#if TESTMODE == 1
5112
    setScreenDone();
5113
#endif
5114
}
5115
 
5116
void MainWindow::dropSubPage(ulong handle, ulong parent)
5117
{
5118
    DECL_TRACER("MainWindow::dropSubPage(ulong handle, ulong parent)");
5119
 
5120
    OBJECT_t *obj = findObject(handle);
5121
    OBJECT_t *par = findObject(parent);
5122
 
5123
    if (!obj)
5124
    {
5125
        MSG_WARNING("Object " << handleToString(handle) << " (SubPage) does not exist. Ignoring!");
5126
#if TESTMODE == 1
5127
        setScreenDone();
5128
#endif
5129
        return;
5130
    }
5131
 
5132
    if (!par)
5133
    {
5134
        MSG_DEBUG("Parent object " << handleToString(parent) << " not found!");
5135
#if TESTMODE == 1
5136
        setScreenDone();
5137
#endif
5138
        return;
5139
    }
5140
 
5141
    if (obj->type != OBJ_SUBPAGE)
5142
    {
5143
        MSG_WARNING("Object " << handleToString(handle) << " is not a SubPage!");
5144
#if TESTMODE == 1
5145
        setScreenDone();
5146
#endif
5147
        return;
5148
    }
5149
 
5150
    QWidget *w = par->object.widget->findChild<QWidget *>(QString("Subpage_%1").arg(handleToString(handle).c_str()));
5151
 
5152
    if (!w)
5153
    {
5154
        MSG_DEBUG("Parent object " << handleToString(parent) << " has no child " << handleToString(handle) << "!");
5155
        obj->object.widget = nullptr;
5156
        obj->remove = true;
5157
        obj->invalid = true;
5158
#if TESTMODE == 1
5159
        setScreenDone();
5160
#endif
5161
        return;
5162
    }
5163
 
5164
    MSG_DEBUG("Dropping subpage " << handleToString(handle));
5165
    invalidateAllSubObjects(handle);
5166
    obj->aniDirection = false;
5167
    bool ret = startAnimation(obj, obj->animate, false);
5168
 
5169
    if (obj->animate.hideEffect == SE_NONE || !ret || !mLastObject)
5170
    {
5171
        obj->invalid = true;
5172
        obj->remove = false;
5173
 
5174
        if (obj->object.widget)
5175
        {
5176
            obj->object.widget->hide();
5177
#if TESTMODE == 1
5178
            __success = true;
5179
#endif
5180
        }
5181
    }
5182
#if TESTMODE == 1
5183
    setScreenDone();
5184
#endif
5185
}
5186
 
5187
void MainWindow::dropButton(ulong handle)
5188
{
5189
//    TLOCKER(draw_mutex);
5190
    DECL_TRACER("MainWindow::dropButton(ulong handle)");
5191
 
5192
    OBJECT_t *obj = findObject(handle);
5193
 
5194
    if (!obj)
5195
    {
5196
        MSG_WARNING("Object " << handleToString(handle) << " does not exist. Ignoring!");
5197
        return;
5198
    }
5199
 
5200
    if (obj->type == OBJ_PAGE || obj->type == OBJ_SUBPAGE)
5201
        return;
5202
 
5203
    invalidateObject(handle);
5204
}
5205
 
5206
void MainWindow::setSizeMainWindow(int width, int height)
5207
{
5208
#if !defined (Q_OS_ANDROID) && !defined(Q_OS_IOS)
5209
    DECL_TRACER("MainWindow::setSizeMainWindow(int width, int height)");
5210
 
5211
    QRect geo = geometry();
5212
    setGeometry(geo.x(), geo.y(), width, height + menuBar()->height());
5213
#else
5214
    Q_UNUSED(width);
5215
    Q_UNUSED(height);
5216
#endif
5217
}
5218
 
5219
void MainWindow::playVideo(ulong handle, ulong parent, int left, int top, int width, int height, const string& url, const string& user, const string& pw)
5220
{
5221
//    TLOCKER(draw_mutex);
5222
    DECL_TRACER("MainWindow::playVideo(ulong handle, const string& url, const string& user, const string& pw))");
5223
 
5224
    TObject::OBJECT_t *obj = findObject(handle);
5225
    TObject::OBJECT_t *par = findObject(parent);
5226
    MSG_TRACE("Processing button " << handleToString(handle) << " from parent " << handleToString(parent));
5227
 
5228
    if (!par)
5229
    {
5230
        MSG_WARNING("Button has no parent! Ignoring it.");
5231
        return;
5232
    }
5233
 
5234
    if (!obj)
5235
    {
5236
        MSG_DEBUG("Adding new video object ...");
5237
        OBJECT_t nobj;
5238
 
5239
        nobj.type = TObject::OBJ_VIDEO;
5240
        nobj.handle = handle;
449 andreas 5241
        nobj.width = scale(width);
5242
        nobj.height = scale(height);
5243
        nobj.left = scale(left);
5244
        nobj.top = scale(top);
446 andreas 5245
 
5246
        nobj.object.vwidget = new QVideoWidget(par->object.widget);
5247
        nobj.object.vwidget->installEventFilter(this);
5248
 
5249
        if (!addObject(nobj))
5250
        {
5251
            MSG_ERROR("Error creating a video object!");
5252
            return;
5253
        }
5254
 
5255
        obj = findObject(handle);
5256
    }
5257
    else
5258
        MSG_DEBUG("Object " << handleToString(handle) << " of type " << objectToString(obj->type) << " found!");
5259
 
5260
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5261
    QMediaPlaylist *playlist = new QMediaPlaylist;
5262
#endif
5263
    QUrl qurl(url.c_str());
5264
 
5265
    if (!user.empty())
5266
        qurl.setUserName(user.c_str());
5267
 
5268
    if (!pw.empty())
5269
        qurl.setPassword(pw.c_str());
5270
 
5271
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5272
    playlist->addMedia(qurl);
5273
#endif
5274
    obj->player = new QMediaPlayer;
5275
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5276
    obj->player->setPlaylist(playlist);
5277
#else
5278
    obj->player->setSource(qurl);
5279
#endif
5280
    obj->player->setVideoOutput(obj->object.vwidget);
5281
 
5282
    obj->object.vwidget->show();
5283
    obj->player->play();
5284
}
5285
 
5286
void MainWindow::inputText(Button::TButton *button, QByteArray buf, int width, int height, int frame, size_t pixline)
5287
{
5288
    DECL_TRACER("MainWindow::inputText(Button::TButton& button, QByteArray buf, int width, int height, int frame, size_t pixline)");
5289
 
5290
    if (!button)
5291
    {
5292
        MSG_WARNING("Method was called with no button!");
5293
        return;
5294
    }
5295
 
5296
    ulong handle = button->getHandle();
5297
    ulong parent = button->getParent();
5298
    TObject::OBJECT_t *obj = findObject(handle);
5299
    TObject::OBJECT_t *par = findObject(parent);
5300
    MSG_TRACE("Processing button " << handleToString(handle) << " from parent " << handleToString(parent) << " with frame width " << frame);
5301
 
5302
    if (!par)
5303
    {
5304
        MSG_WARNING("Button has no parent! Ignoring it.");
5305
        return;
5306
    }
5307
 
5308
    int instance = button->getActiveInstance();
5309
    MSG_DEBUG("Instance: " << instance);
5310
 
5311
    if (!obj)
5312
    {
5313
        MSG_DEBUG("Adding new input object ...");
5314
        OBJECT_t nobj;
5315
 
5316
        nobj.type = TObject::OBJ_INPUT;
5317
        nobj.handle = handle;
449 andreas 5318
        nobj.width = scale(width);
5319
        nobj.height = scale(height);
5320
        nobj.left = scale(button->getLeftPosition());
5321
        nobj.top = scale(button->getTopPosition());
446 andreas 5322
 
5323
        string text = button->getText(0);
5324
        string placeholder = button->getText(1);
5325
        string mask = button->getInputMask();
5326
 
5327
        if (button->isMultiLine())
5328
            text = ReplaceString(text, "|", "\n");
5329
 
5330
        nobj.object.plaintext = new TQEditLine(text, par->object.widget, button->isMultiLine());
5331
        nobj.object.plaintext->setObjectName(string("EditLine_") + handleToString(handle));
5332
        nobj.object.plaintext->setHandle(handle);
5333
        nobj.object.plaintext->move(nobj.left, nobj.top);
5334
        nobj.object.plaintext->setFixedSize(nobj.width, nobj.height);
5335
        nobj.object.plaintext->setPadding(frame, frame, frame, frame);
5336
        nobj.object.plaintext->setPasswordChar(button->getPasswordChar());
5337
        nobj.wid = nobj.object.plaintext->winId();
5338
 
5339
        if (!placeholder.empty())
5340
            nobj.object.plaintext->setPlaceholderText(placeholder);
5341
 
5342
        bool sys = false;
5343
 
5344
        if (button->getAddressPort() == 0 || button->getChannelPort() == 0)
5345
        {
5346
            int ch = 0;
5347
 
5348
            if (button->getAddressPort() == 0 && button->getAddressChannel() > 0)
5349
                ch = button->getAddressChannel();
5350
            else if (button->getChannelPort() == 0 && button->getChannelNumber() > 0)
5351
                ch = button->getChannelNumber();
5352
 
5353
            switch(ch)
5354
            {
5355
                case SYSTEM_ITEM_SIPPORT:
5356
                case SYSTEM_ITEM_NETLINX_PORT:
5357
                    nobj.object.plaintext->setInputMask("000000");
5358
                    nobj.object.plaintext->setNumericInput();
5359
                    sys = true;
5360
                break;
5361
 
5362
                case SYSTEM_ITEM_NETLINX_CHANNEL:
5363
                    nobj.object.plaintext->setInputMask("99999");
5364
                    nobj.object.plaintext->setNumericInput();
5365
                    sys = true;
5366
                break;
5367
            }
5368
 
5369
            if (sys)
5370
                MSG_TRACE("System button " << ch << " detected.");
5371
        }
5372
 
5373
        if (!sys && !mask.empty())
5374
            nobj.object.plaintext->setInputMask(convertMask(mask));
5375
 
5376
        if (!buf.size() || pixline == 0)
5377
        {
5378
            MSG_ERROR("No image!");
5379
            TError::setError();
5380
            return;
5381
        }
5382
 
5383
        MSG_DEBUG("Background image size: " << width << " x " << height << ", rowBytes: " << pixline);
5384
        QPixmap pix(width, height);
5385
        QImage img((uchar *)buf.data(), width, height, QImage::Format_ARGB32);
5386
 
449 andreas 5387
        if (isScaled())
446 andreas 5388
            pix.convertFromImage(img.scaled(scale(width), scale(height), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
5389
        else
5390
            pix.convertFromImage(img);
5391
 
5392
        nobj.object.plaintext->setBackgroundPixmap(pix);
5393
        // Load the font
5394
        QFont font = loadFont(button->getFontIndex(button->getActiveInstance()), button->getFont(), button->getFontStyle());
5395
        QPalette palette(this->palette());
5396
        TColor::COLOR_T textColor = TColor::getAMXColor(button->getTextColor(instance));
5397
        TColor::COLOR_T fillColor = TColor::getAMXColor(button->getFillColor(instance));
5398
        QColor txcolor(QColor::fromRgba(qRgba(textColor.red, textColor.green, textColor.blue, textColor.alpha)));
5399
        QColor cfcolor(QColor::fromRgba(qRgba(fillColor.red, fillColor.green, fillColor.blue, fillColor.alpha)));
5400
        palette.setColor(QPalette::Window, cfcolor);
5401
        palette.setColor(QPalette::Base, cfcolor);
5402
        palette.setColor(QPalette::Text, txcolor);
5403
 
5404
        nobj.object.plaintext->setFont(font);
5405
        nobj.object.plaintext->setPalette(palette);
5406
        nobj.object.plaintext->setTextColor(txcolor);
5407
 
5408
        if (!addObject(nobj))
5409
        {
5410
            MSG_ERROR("Error creating an input object!");
5411
            return;
5412
        }
5413
 
5414
        connect(nobj.object.plaintext, &TQEditLine::inputChanged, this, &MainWindow::onInputChanged);
5415
        connect(nobj.object.plaintext, &TQEditLine::cursorPositionChanged, this, &MainWindow::onCursorChanged);
5416
        connect(nobj.object.plaintext, &TQEditLine::focusChanged, this, &MainWindow::onFocusChanged);
5417
    }
5418
    else
5419
    {
5420
        MSG_DEBUG("Object " << handleToString(handle) << " of type " << objectToString(obj->type) << " found!");
5421
 
5422
        string text = button->getText(0);
5423
        string placeholder = button->getText(1);
5424
        string mask = button->getInputMask();
5425
        MSG_DEBUG("Setting text: \"" << text << "\" with mask: \"" << mask << "\"");
5426
 
5427
        if (!placeholder.empty())
5428
            obj->object.plaintext->setPlaceholderText(placeholder);
5429
 
5430
        if (button->isMultiLine())
5431
            text = ReplaceString(text, "|", "\n");
5432
 
5433
        obj->object.plaintext->setText(text);
5434
 
5435
        if (!mask.empty())
5436
            obj->object.plaintext->setInputMask(convertMask(mask));
5437
 
5438
        QPixmap pix(obj->width, obj->height);
5439
        QImage img((uchar *)buf.data(), width, height, QImage::Format_ARGB32);
5440
 
5441
        if (isScaled())
5442
            pix.convertFromImage(img.scaled(obj->width, obj->height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
5443
        else
5444
            pix.convertFromImage(img);
5445
 
5446
//        obj->object.plaintext->setBgPixmap(pix);
5447
        obj->object.plaintext->setBackgroundPixmap(pix);
5448
        QPalette palette(this->palette());
5449
        TColor::COLOR_T textColor = TColor::getAMXColor(button->getTextColor(instance));
5450
        TColor::COLOR_T fillColor = TColor::getAMXColor(button->getFillColor(instance));
5451
        QColor txcolor(QColor::fromRgba(qRgba(textColor.red, textColor.green, textColor.blue, textColor.alpha)));
5452
        QColor cfcolor(QColor::fromRgba(qRgba(fillColor.red, fillColor.green, fillColor.blue, fillColor.alpha)));
5453
        palette.setColor(QPalette::Window, cfcolor);
5454
        palette.setColor(QPalette::Base, cfcolor);
5455
        palette.setColor(QPalette::Text, txcolor);
5456
//        palette.setBrush(QPalette::Window, QBrush(pix));
5457
 
5458
        obj->object.plaintext->setPalette(palette);
5459
        obj->object.plaintext->setTextColor(txcolor);
5460
    }
5461
}
5462
 
5463
void MainWindow::listBox(Button::TButton *button, QByteArray buffer, int width, int height, int frame, size_t pixline)
5464
{
5465
    DECL_TRACER("MainWindow::listBox(Button::TButton& button, QByteArray buffer, int width, int height, int frame, size_t pixline)");
5466
 
5467
    ulong handle = button->getHandle();
5468
    ulong parent = button->getParent();
5469
    TObject::OBJECT_t *obj = findObject(handle);
5470
    TObject::OBJECT_t *par = findObject(parent);
5471
    MSG_TRACE("Processing list " << handleToString(handle) << " from parent " << handleToString(parent) << " with frame width " << frame);
5472
 
5473
    if (!par)
5474
    {
5475
        MSG_WARNING("List has no parent! Ignoring it.");
5476
        return;
5477
    }
5478
 
5479
    if (!obj)
5480
    {
5481
        MSG_DEBUG("Adding new list object ...");
5482
        OBJECT_t nobj;
5483
 
5484
        nobj.type = TObject::OBJ_LIST;
5485
        nobj.handle = handle;
5486
        nobj.rows = button->getListNumRows();
5487
        nobj.cols = button->getListNumCols();
449 andreas 5488
        nobj.width = scale(width);
5489
        nobj.height = scale(height);
5490
        nobj.left = scale(button->getLeftPosition());
5491
        nobj.top = scale(button->getTopPosition());
446 andreas 5492
 
5493
        vector<string> listContent = button->getListContent();
5494
 
5495
        if (par->type == TObject::OBJ_PAGE)
5496
            nobj.object.list = new QListWidget(par->object.widget ? par->object.widget : centralWidget());
5497
        else
5498
            nobj.object.list = new QListWidget(par->object.widget);
5499
 
5500
        nobj.object.list->move(nobj.left, nobj.top);
5501
        nobj.object.list->setFixedSize(nobj.width, nobj.height);
5502
        connect(nobj.object.list, &QListWidget::currentItemChanged, this, &MainWindow::onTListCallbackCurrentItemChanged);
5503
 
5504
        if (!buffer.size() || pixline == 0)
5505
        {
5506
            MSG_ERROR("No image!");
5507
            TError::setError();
5508
            return;
5509
        }
5510
 
5511
        MSG_DEBUG("Background image size: " << width << " x " << height << ", rowBytes: " << pixline);
5512
        QPixmap pix(width, height);
5513
        QImage img((uchar *)buffer.data(), width, height, QImage::Format_ARGB32);
5514
 
449 andreas 5515
        if (isScaled())
446 andreas 5516
            pix.convertFromImage(img.scaled(scale(width), scale(height), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
5517
        else
5518
            pix.convertFromImage(img);
5519
 
5520
        // Load the font
5521
        FONT_T font = button->getFont();
5522
        vector<string> fontList = TFont::getFontPathList();
5523
        vector<string>::iterator iter;
5524
        string ffile;
5525
 
5526
        for (iter = fontList.begin(); iter != fontList.end(); ++iter)
5527
        {
5528
            TValidateFile vf;
5529
 
5530
            if (!vf.isValidFile(*iter + "/" + font.file))
5531
                continue;
5532
 
5533
            ffile = *iter + "/" + font.file;
5534
            break;
5535
        }
5536
 
5537
        if (ffile.empty())
5538
        {
5539
            MSG_ERROR("Font " << font.file << " doesn't exists!");
5540
            return;
5541
        }
5542
 
5543
        if (QFontDatabase::addApplicationFont(ffile.c_str()) == -1)
5544
        {
5545
            MSG_ERROR("Font " << ffile << " could not be loaded!");
5546
            TError::setError();
5547
            return;
5548
        }
5549
 
5550
        QFont ft;
5551
        ft.setFamily(font.name.c_str());
449 andreas 5552
        ft.setPointSize(font.size);
446 andreas 5553
 
5554
        MSG_DEBUG("Using font \"" << font.name << "\" with size " << font.size << "pt.");
5555
 
5556
        switch (button->getFontStyle())
5557
        {
5558
            case FONT_BOLD:     ft.setBold(true); break;
5559
            case FONT_ITALIC:   ft.setItalic(true); break;
5560
            case FONT_BOLD_ITALIC:
5561
                ft.setBold(true);
5562
                ft.setItalic(true);
5563
            break;
5564
 
5565
            default:
5566
                ft.setBold(false);
5567
                ft.setItalic(false);
5568
        }
5569
 
5570
        QPalette palette;
5571
        TColor::COLOR_T textColor = TColor::getAMXColor(button->getTextColor());
5572
        TColor::COLOR_T fillColor = TColor::getAMXColor(button->getFillColor());
5573
        QColor txcolor(QColor::fromRgba(qRgba(textColor.red, textColor.green, textColor.blue, textColor.alpha)));
5574
        QColor cfcolor(QColor::fromRgba(qRgba(fillColor.red, fillColor.green, fillColor.blue, fillColor.alpha)));
5575
        palette.setColor(QPalette::Base, cfcolor);
5576
        palette.setColor(QPalette::Text, txcolor);
5577
//        pix.save("frame.png");
5578
        palette.setBrush(QPalette::Base, QBrush(pix));
5579
 
5580
        nobj.object.list->setFont(ft);
5581
        nobj.object.list->setPalette(palette);
5582
        // Add content
5583
        if (!listContent.empty())
5584
        {
5585
            vector<string>::iterator iter;
5586
 
5587
            if (nobj.object.list->count() > 0)
5588
                nobj.object.list->clear();
5589
 
5590
            MSG_DEBUG("Adding " << listContent.size() << " entries to list.");
5591
            string selected = gPageManager->getSelectedItem(handle);
5592
            int index = 0;
5593
 
5594
            for (iter = listContent.begin(); iter != listContent.end(); ++iter)
5595
            {
5596
                nobj.object.list->addItem(iter->c_str());
5597
 
5598
                if (selected == *iter)
5599
                    nobj.object.list->setCurrentRow(index);
5600
 
5601
                index++;
5602
            }
5603
        }
5604
        else
5605
            MSG_DEBUG("No items for list!");
5606
 
5607
//        nobj.object.list->show();
5608
 
5609
        if (!addObject(nobj))
5610
        {
5611
            MSG_ERROR("Error creating a list object!");
5612
            return;
5613
        }
5614
    }
5615
    else
5616
    {
5617
        MSG_DEBUG("Object " << handleToString(handle) << " of type " << objectToString(obj->type) << " found!");
5618
        enableObject(handle);
5619
    }
5620
}
5621
 
5622
void MainWindow::showKeyboard(const std::string& init, const std::string& prompt, bool priv)
5623
{
5624
    DECL_TRACER("MainWindow::showKeyboard(std::string &init, std::string &prompt, bool priv)");
5625
 
5626
    if (mKeyboard)
5627
        return;
5628
 
5629
    mQKeyboard = new TQKeyboard(init, prompt, this);
5630
    mKeyboard = true;
5631
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
5632
    mQKeyboard->setScaleFactor(mScaleFactor);
5633
#endif
5634
    mQKeyboard->setPrivate(priv);
5635
    mQKeyboard->doResize();
5636
    mQKeyboard->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
5637
    int ret = mQKeyboard->exec();
5638
    string text = "KEYB-";
5639
 
5640
    if (ret == QDialog::Accepted)
5641
        text.append(mQKeyboard->getText());
5642
    else
5643
        text = "KEYB-ABORT";
5644
 
5645
    if (gPageManager)
5646
        gPageManager->sendKeyboard(text);
5647
 
5648
    delete mQKeyboard;
5649
    mQKeyboard = nullptr;
5650
    mKeyboard = false;
5651
}
5652
 
5653
void MainWindow::showKeypad(const std::string& init, const std::string& prompt, bool priv)
5654
{
5655
    DECL_TRACER("MainWindow::showKeypad(std::string& init, std::string& prompt, bool priv)");
5656
 
5657
    if (mKeypad)
5658
        return;
5659
 
5660
    mQKeypad = new TQKeypad(init, prompt, this);
5661
    mKeypad = true;
5662
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
5663
    mQKeypad->setScaleFactor(mScaleFactor);
5664
#endif
5665
    mQKeypad->setPrivate(priv);
5666
    mQKeypad->setMaxLength(50);     // Standard maximum length
5667
    mQKeypad->doResize();
5668
    mQKeypad->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
5669
    int ret = mQKeypad->exec();
5670
 
5671
    if (ret == QDialog::Accepted)
5672
    {
5673
        string text = "KEYP-";
5674
        text.append(mQKeypad->getText());
5675
 
5676
        if (gPageManager)
5677
            gPageManager->sendKeypad(text);
5678
    }
5679
    else
5680
    {
5681
        string text = "KEYP-ABORT";
5682
 
5683
        if (gPageManager)
5684
            gPageManager->sendKeypad(text);
5685
    }
5686
 
5687
    delete mQKeypad;
5688
    mQKeypad = nullptr;
5689
    mKeypad = false;
5690
}
5691
 
5692
void MainWindow::resetKeyboard()
5693
{
5694
    DECL_TRACER("MainWindow::resetKeyboard()");
5695
 
5696
    if (mQKeyboard)
5697
        mQKeyboard->reject();
5698
 
5699
    if (mQKeypad)
5700
        mQKeypad->reject();
5701
}
5702
 
5703
void MainWindow::sendVirtualKeys(const string& str)
5704
{
5705
    DECL_TRACER("MainWindow::sendVirtualKeys(const string& str)");
5706
 
5707
    if (mKeyboard && mQKeyboard)
5708
        mQKeyboard->setString(str);
5709
    else if (mKeypad && mQKeypad)
5710
        mQKeypad->setString(str);
5711
}
5712
 
5713
void MainWindow::showSetup()
5714
{
5715
    DECL_TRACER("MainWindow::showSetup()");
5716
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
5717
    settings();
5718
#else
5719
#ifndef Q_OS_IOS
5720
    if (gPageManager)
5721
        gPageManager->showSetup();
5722
#else
5723
    mIOSSettingsActive = true;
5724
    QASettings::openSettings();
5725
#endif  // Q_OS_IOS
5726
#endif  // !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
5727
}
5728
 
5729
void MainWindow::playSound(const string& file)
5730
{
5731
    DECL_TRACER("MainWindow::playSound(const string& file)");
5732
 
5733
    MSG_DEBUG("Playing file " << file);
5734
 
5735
    if (TConfig::getMuteState())
5736
    {
5737
#if TESTMODE == 1
5738
        __success = true;
5739
        setAllDone();
5740
#endif
5741
        return;
5742
    }
5743
 
5744
    if (!mMediaPlayer)
5745
    {
5746
        mMediaPlayer = new QMediaPlayer;
5747
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
5748
        mAudioOutput = new QAudioOutput;
5749
        mMediaPlayer->setAudioOutput(mAudioOutput);
5750
#endif
5751
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
5752
        connect(mMediaPlayer, &QMediaPlayer::playingChanged, this, &MainWindow::onPlayingChanged);
5753
#endif
5754
        connect(mMediaPlayer, &QMediaPlayer::mediaStatusChanged, this, &MainWindow::onMediaStatusChanged);
5755
        connect(mMediaPlayer, &QMediaPlayer::errorOccurred, this, &MainWindow::onPlayerError);
5756
    }
5757
 
5758
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5759
    mMediaPlayer->setMedia(QUrl::fromLocalFile(file.c_str()));
5760
    mMediaPlayer->setVolume(calcVolume(TConfig::getSystemVolume()));
5761
 
5762
    if (mMediaPlayer->state() != QMediaPlayer::StoppedState)
5763
        mMediaPlayer->stop();
5764
#else   // QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5765
    mMediaPlayer->setSource(QUrl::fromLocalFile(file.c_str()));
5766
    mAudioOutput->setVolume(static_cast<float>(calcVolume(TConfig::getSystemVolume())));
5767
 
5768
    if (!mMediaPlayer->isAvailable())
5769
    {
5770
        MSG_WARNING("No audio modul found!");
5771
#if TESTMODE == 1
5772
        setAllDone();
5773
#endif
5774
        return;
5775
    }
5776
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
5777
    if (mMediaPlayer->isPlaying())
5778
        mMediaPlayer->setPosition(0);
5779
//        mMediaPlayer->stop();
5780
#else
5781
    if (mMediaPlayer->playbackState() != QMediaPlayer::StoppedState)
5782
        mMediaPlayer->stop();
5783
 
5784
    mMediaPlayer->setPosition(0);
5785
#endif  // #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
5786
 
5787
#endif  // QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5788
    mMediaPlayer->play();
5789
#if TESTMODE == 1
5790
    if (mMediaPlayer->error() != QMediaPlayer::NoError)
5791
    {
5792
        MSG_ERROR("Error playing \"" << file << "\": " << mMediaPlayer->errorString().toStdString());
5793
    }
5794
    else
5795
        __success = true;
5796
 
5797
    setAllDone();
5798
#endif
5799
}
5800
 
5801
void MainWindow::stopSound()
5802
{
5803
    DECL_TRACER("MainWindow::stopSound()");
5804
 
5805
    if (mMediaPlayer)
5806
        mMediaPlayer->stop();
5807
}
5808
 
5809
void MainWindow::muteSound(bool state)
5810
{
5811
    DECL_TRACER("MainWindow::muteSound(bool state)");
5812
 
5813
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5814
    if (mMediaPlayer)
5815
        mMediaPlayer->setMuted(state);
5816
#else
5817
    if (mAudioOutput)
5818
        mAudioOutput->setMuted(state);
5819
#endif
5820
#if TESTMODE == 1
5821
    __success = true;
5822
    setAllDone();
5823
#endif
5824
}
5825
 
5826
void MainWindow::setVolume(int volume)
5827
{
5828
    DECL_TRACER("MainWindow::setVolume(int volume)");
5829
 
5830
    if (!mMediaPlayer)
5831
    {
5832
#if TESTMODE == 1
5833
        setAllDone();
5834
#endif
5835
        return;
5836
    }
5837
 
5838
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5839
    mMediaPlayer->setVolume(calcVolume(volume));
5840
#else   // QT_VERSION
5841
    if (!mMediaPlayer || !mAudioOutput)
5842
    {
5843
#if TESTMODE == 1
5844
        setAllDone();
5845
#endif  // TESTMODE
5846
        return;
5847
    }
5848
 
5849
    mAudioOutput->setVolume(static_cast<float>(calcVolume(volume)));
5850
#if TESTMODE == 1
5851
    __success = true;
5852
    setAllDone();
5853
#endif  // TESTMODE
5854
#endif  // QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5855
}
5856
 
5857
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
5858
void MainWindow::onPlayingChanged(bool playing)
5859
{
5860
    DECL_TRACER("MainWindow::onPlayingChanged(bool playing)");
5861
 
5862
    // If playing stopped for whatever reason, we rewind the track
5863
    if (!playing && mMediaPlayer)
5864
    {
5865
        mMediaPlayer->setPosition(0);
5866
        MSG_DEBUG("Track was rewound.");
5867
    }
5868
}
5869
#endif
5870
 
5871
void MainWindow::onMediaStatusChanged(QMediaPlayer::MediaStatus status)
5872
{
5873
    DECL_TRACER("MainWindow::onMediaStatusChanged(QMediaPlayer::MediaStatus status)");
5874
 
5875
    switch(status)
5876
    {
461 andreas 5877
        case QMediaPlayer::NoMedia:         MSG_WARNING("There is no current media."); break;
446 andreas 5878
        case QMediaPlayer::LoadingMedia:    MSG_INFO("The current media is being loaded."); break;
5879
        case QMediaPlayer::LoadedMedia:     MSG_INFO("The current media has been loaded."); break;
5880
        case QMediaPlayer::StalledMedia:    MSG_WARNING("Playback of the current media has stalled due to insufficient buffering or some other temporary interruption."); break;
5881
        case QMediaPlayer::BufferingMedia:  MSG_INFO("The player is buffering data but has enough data buffered for playback to continue for the immediate future."); break;
5882
        case QMediaPlayer::BufferedMedia:   MSG_INFO("The player has fully buffered the current media."); break;
5883
        case QMediaPlayer::EndOfMedia:      MSG_INFO("Playback has reached the end of the current media."); break;
5884
        case QMediaPlayer::InvalidMedia:    MSG_WARNING("The current media cannot be played.");
5885
    }
5886
}
5887
 
5888
void MainWindow::onPlayerError(QMediaPlayer::Error error, const QString &errorString)
5889
{
5890
    DECL_TRACER("MainWindow::onPlayerError(QMediaPlayer::Error error, const QString &errorString)");
5891
 
5892
    if (error == QMediaPlayer::NoError)
5893
        return;
5894
 
5895
    MSG_ERROR("Media player error (" << error << "): " << errorString.toStdString());
5896
}
458 andreas 5897
 
5898
void MainWindow::initializeIntercom(INTERCOM_t ic)
5899
{
5900
    DECL_TRACER("MainWindow::initializeIntercom(INTERCOM_t ic)");
5901
 
5902
    mIntercom.setIntercom(ic);
5903
}
5904
 
5905
void MainWindow::intercomStart()
5906
{
5907
    DECL_TRACER("MainWindow::intercomStart()");
5908
 
5909
    mIntercom.start();
5910
}
5911
 
5912
void MainWindow::intercomStop()
5913
{
5914
    DECL_TRACER("MainWindow::intercomStop()");
5915
 
5916
    mIntercom.stop();
5917
}
5918
 
5919
void MainWindow::intercomMicLevel(int level)
5920
{
5921
    DECL_TRACER("MainWindow::intercomMicLevel(int level)");
5922
 
461 andreas 5923
    mIntercom.setMicrophoneLevel(level);
458 andreas 5924
}
5925
 
5926
void MainWindow::intercomSpkLevel(int level)
5927
{
5928
    DECL_TRACER("MainWindow::intercomSpkLevel(int level)");
5929
 
5930
    mIntercom.setSpeakerLevel(level);
5931
}
5932
 
5933
void MainWindow::intercomMicMute(bool mute)
5934
{
5935
    DECL_TRACER("MainWindow::intercomMicMute(bool mute)");
5936
 
5937
    mIntercom.setMute(mute);
5938
}
5939
 
446 andreas 5940
/*
5941
void MainWindow::playShowList()
5942
{
5943
    DECL_TRACER("MainWindow::playShowList()");
5944
 
5945
    _EMIT_TYPE_t etype = getNextType();
5946
 
5947
    while (etype != ET_NONE)
5948
    {
5949
        ulong handle = 0;
5950
        ulong parent = 0;
5951
        int left = 0;
5952
        int top = 0;
5953
        int width = 0;
5954
        int height = 0;
5955
        int frame = 0;
5956
        TBitmap image;
5957
        ulong color = 0;
5958
        int space{0};
5959
        bool vertical = false;
5960
        TColor::COLOR_T fillColor;
5961
        bool pth = false;
5962
#ifndef _OPAQUE_SKIA_
5963
        int opacity = 255;
5964
#endif
5965
        ANIMATION_t animate;
5966
        std::string url;
5967
        std::string user;
5968
        std::string pw;
5969
        Button::TButton *button;
5970
        Button::BITMAP_t bm;
5971
 
5972
        switch(etype)
5973
        {
5974
            case ET_BACKGROUND:
5975
#ifdef _OPAQUE_SKIA_
5976
                if (getBackground(&handle, &image, &width, &height, &color))
5977
#else
5978
                if (getBackground(&handle, &image, &width, &height, &color, &opacity))
5979
#endif
5980
                {
5981
                    MSG_PROTOCOL("Replay: BACKGROUND of object " << handleToString(handle));
5982
#ifdef _OPAQUE_SKIA_
5983
                    emit sigSetBackground(handle, image, width, height, color);
5984
#else
5985
                    emit sigSetBackground(handle, image, width, height, color, opacity);
5986
#endif
5987
                }
5988
            break;
5989
 
5990
            case ET_BUTTON:
5991
                if (getButton(&handle, &parent, &image, &left, &top, &width, &height, &pth))
5992
                {
5993
                    MSG_PROTOCOL("Replay: BUTTON object " << handleToString(handle));
5994
                    emit sigDisplayButton(handle, parent, image, width, height, left, top, pth);
5995
                }
5996
            break;
5997
 
5998
            case ET_INTEXT:
5999
                if (getInText(&handle, &button, &bm, &frame))
6000
                {
6001
                    QByteArray buf;
6002
 
6003
                    if (bm.buffer && bm.rowBytes > 0)
6004
                    {
6005
                        size_t s = (size_t)bm.width * (size_t)bm.height * (size_t)(bm.rowBytes / bm.width);
6006
                        buf.insert(0, (const char *)bm.buffer, s);
6007
                    }
6008
 
6009
                    MSG_PROTOCOL("Replay: INTEXT object " << handleToString(handle));
6010
                    emit sigInputText(button, buf, bm.width, bm.height, (int)bm.rowBytes, frame);
6011
                }
6012
            break;
6013
 
6014
            case ET_PAGE:
6015
                if (getPage(&handle, &width, &height))
6016
                {
6017
                    MSG_PROTOCOL("Replay: PAGE object " << handleToString(handle));
6018
 
6019
                    if (isDeleted())
6020
                        emit sigDropPage(handle);
6021
                    else
6022
                        emit sigSetPage(handle, width, height);
6023
                }
6024
            break;
6025
 
6026
            case ET_SUBPAGE:
6027
                if (getSubPage(&handle, &parent, &left, &top, &width, &height, &animate))
6028
                {
6029
                    MSG_PROTOCOL("Replay: SUBPAGE object " << handleToString(handle));
6030
 
6031
                    if (isDeleted())
6032
                        emit sigDropSubPage(handle, parent);
6033
                    else
6034
                        emit sigSetSubPage(handle, parent, left, top, width, height, animate);
6035
                }
6036
            break;
6037
 
6038
            case ET_SUBVIEW:
6039
                if (getViewButton(&handle, &parent, &vertical, &image, &left, &top, &width, &height, &space, &fillColor))
6040
                {
6041
                    MSG_PROTOCOL("Replay: SUBVIEW object " << handleToString(handle));
6042
                    emit sigDisplayViewButton(handle, parent, vertical, image, width, height, left, top, space, fillColor);
6043
                }
6044
            break;
6045
 
6046
            case ET_VIDEO:
6047
                if (getVideo(&handle, &parent, &left, &top, &width, &height, &url, &user, &pw))
6048
                {
6049
                    MSG_PROTOCOL("Replay: VIDEO object " << handleToString(handle));
6050
                    emit sigPlayVideo(handle, parent, left, top, width, height, url, user, pw);
6051
                }
6052
            break;
6053
 
6054
            default:
6055
                MSG_WARNING("Type " << etype << " is currently not supported!");
6056
        }
6057
 
6058
        dropType(etype);
6059
        etype = getNextType();
6060
    }
6061
}
6062
*/
6063
 
6064
int MainWindow::scale(int value)
6065
{
6066
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
6067
    double s = gScale;
6068
#else
6069
    double s = mScaleFactor;
6070
#endif
6071
    if (value <= 0 || s == 1.0 || s < 0.0)
6072
        return value;
6073
 
6074
    return static_cast<int>(static_cast<double>(value) * s);
6075
}
6076
 
6077
bool MainWindow::isScaled()
6078
{
6079
    DECL_TRACER("MainWindow::isScaled()");
6080
 
6081
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
6082
    double s = gScale;
6083
#else
6084
    double s = mScaleFactor;
6085
#endif
6086
    if (s > 0.0 && s != 1.0 && gPageManager && TConfig::getScale())
6087
        return true;
6088
 
6089
    return false;
6090
}
6091
 
6092
bool MainWindow::startAnimation(TObject::OBJECT_t* obj, ANIMATION_t& ani, bool in)
6093
{
6094
    DECL_TRACER("MainWindow::startAnimation(OBJECT_t* obj, ANIMATION_t& ani)");
6095
 
6096
    if (!obj)
6097
    {
6098
        MSG_ERROR("Got no object to start the animation!");
6099
        return false;
6100
    }
6101
 
6102
//    TLOCKER(anim_mutex);
6103
    int scLeft = obj->left;
6104
    int scTop = obj->top;
6105
    int scWidth = obj->width;
6106
    int scHeight = obj->height;
6107
    int duration = (in ? ani.showTime : ani.hideTime);
6108
    SHOWEFFECT_t effect = (in ? ani.showEffect : ani.hideEffect);
6109
    mLastObject = nullptr;
6110
 
6111
    if (effect == SE_NONE || duration <= 0 || (obj->type != OBJ_SUBPAGE && obj->type != OBJ_PAGE))
6112
        return false;
6113
 
6114
    if (!obj->object.widget)
6115
    {
6116
        MSG_WARNING("Object " << handleToString(obj->handle) << " has no widget defined! Ignoring fade effect.");
6117
#if TESTMODE == 1
6118
        setScreenDone();
6119
#endif
6120
        return false;
6121
    }
6122
 
6123
    if (effect == SE_FADE)
6124
    {
6125
        MSG_DEBUG("Fading object " << handleToString(obj->handle) << (in ? " IN" : " OUT"));
6126
        QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(obj->object.widget);
6127
 
6128
        if (effect)
6129
        {
6130
            obj->object.widget->setGraphicsEffect(effect);
6131
            obj->animation = new QPropertyAnimation(effect, "opacity");
6132
        }
6133
    }
6134
    else
6135
    {
6136
        MSG_DEBUG("Moving object " << handleToString(obj->handle) << (in ? " IN" : " OUT"));
6137
        obj->animation = new QPropertyAnimation(obj->object.widget);
6138
        obj->animation->setTargetObject(obj->object.widget);
6139
    }
6140
 
6141
    obj->animation->setDuration(duration * 100);    // convert 10th of seconds into milliseconds
6142
    MSG_DEBUG("Processing animation effect " << effect << " with a duration of " << obj->animation->duration() << "ms");
6143
 
6144
    switch(effect)
6145
    {
6146
        case SE_SLIDE_BOTTOM_FADE:
6147
        case SE_SLIDE_BOTTOM:
6148
            obj->animation->setPropertyName("geometry");
6149
 
6150
            if (in)
6151
            {
6152
                obj->animation->setStartValue(QRect(scLeft, scTop + (scHeight * 2), scWidth, scHeight));
6153
                obj->animation->setEndValue(QRect(scLeft, scTop, scWidth, scHeight));
6154
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationInFinished);
6155
                obj->object.widget->show();
6156
            }
6157
            else
6158
            {
6159
                obj->animation->setStartValue(QRect(scLeft, scTop, scWidth, scHeight));
6160
                obj->animation->setEndValue(QRect(scLeft, scTop + (scHeight * 2), scWidth, scHeight));
6161
                obj->remove = true;
6162
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationFinished);
6163
            }
6164
 
6165
            mLastObject = obj;
6166
            mAnimObjects.insert(pair<ulong, OBJECT_t *>(obj->handle, obj));
6167
            obj->animation->start();
6168
            MSG_DEBUG("Animation SLIDE BOTTOM started.");
6169
        break;
6170
 
6171
        case SE_SLIDE_LEFT_FADE:
6172
        case SE_SLIDE_LEFT:
6173
            obj->animation->setPropertyName("geometry");
6174
 
6175
            if (in)
6176
            {
6177
                obj->animation->setStartValue(QRect(scLeft - scWidth, scTop, scWidth, scHeight));
6178
                obj->animation->setEndValue(QRect(scLeft, scTop, scWidth, scHeight));
6179
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationInFinished);
6180
                obj->object.widget->show();
6181
            }
6182
            else
6183
            {
6184
                obj->animation->setStartValue(QRect(scLeft, scTop, scWidth, scHeight));
6185
                obj->animation->setEndValue(QRect(scLeft - scWidth, scTop, scWidth, scHeight));
6186
                obj->remove = true;
6187
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationFinished);
6188
            }
6189
 
6190
            mLastObject = obj;
6191
            mAnimObjects.insert(pair<ulong, OBJECT_t *>(obj->handle, obj));
6192
            obj->animation->start();
6193
        break;
6194
 
6195
        case SE_SLIDE_RIGHT_FADE:
6196
        case SE_SLIDE_RIGHT:
6197
            obj->animation->setPropertyName("geometry");
6198
 
6199
            if (in)
6200
            {
6201
                obj->animation->setStartValue(QRect(scLeft + scWidth, scTop, scWidth, scHeight));
6202
                obj->animation->setEndValue(QRect(scLeft, scTop, scWidth, scHeight));
6203
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationInFinished);
6204
                obj->object.widget->show();
6205
            }
6206
            else
6207
            {
6208
                obj->animation->setStartValue(QRect(scLeft, scTop, scWidth, scHeight));
6209
                obj->animation->setEndValue(QRect(scLeft + scWidth, scTop, scWidth, scHeight));
6210
                obj->remove = true;
6211
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationFinished);
6212
            }
6213
 
6214
            mLastObject = obj;
6215
            mAnimObjects.insert(pair<ulong, OBJECT_t *>(obj->handle, obj));
6216
            obj->animation->start();
6217
        break;
6218
 
6219
        case SE_SLIDE_TOP_FADE:
6220
        case SE_SLIDE_TOP:
6221
            obj->animation->setPropertyName("geometry");
6222
 
6223
            if (in)
6224
            {
6225
                obj->animation->setStartValue(QRect(scLeft, scTop - scHeight, scWidth, scHeight));
6226
                obj->animation->setEndValue(QRect(scLeft, scTop, scWidth, scHeight));
6227
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationInFinished);
6228
                obj->object.widget->show();
6229
            }
6230
            else
6231
            {
6232
                obj->animation->setStartValue(QRect(scLeft, scTop, scWidth, scHeight));
6233
                obj->animation->setEndValue(QRect(scLeft, scTop - scHeight, scWidth, scHeight));
6234
                obj->remove = true;
6235
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationFinished);
6236
            }
6237
 
6238
            mLastObject = obj;
6239
            mAnimObjects.insert(pair<ulong, OBJECT_t *>(obj->handle, obj));
6240
            obj->animation->start();
6241
        break;
6242
 
6243
        case SE_FADE:
6244
            if (in)
6245
            {
6246
                if (obj->object.widget)
6247
                {
6248
                    obj->object.widget->setWindowOpacity(0.0);
6249
                    obj->object.widget->show();
6250
                }
6251
 
6252
                obj->animation->setStartValue(0.0);
6253
                obj->animation->setEndValue(1.0);
6254
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationInFinished);
6255
                obj->object.widget->show();
6256
            }
6257
            else
6258
            {
6259
                obj->animation->setStartValue(1.0);
6260
                obj->animation->setEndValue(0.0);
6261
                obj->remove = true;
6262
                connect(obj->animation, &QPropertyAnimation::finished, this, &MainWindow::animationFinished);
6263
            }
6264
 
6265
            mLastObject = obj;
6266
            mAnimObjects.insert(pair<ulong, OBJECT_t *>(obj->handle, obj));
6267
            obj->animation->setEasingCurve(QEasingCurve::Linear);
6268
            obj->animation->start();
6269
        break;
6270
 
6271
        default:
6272
            MSG_WARNING("Subpage effect " << ani.showEffect << " is not supported.");
6273
            delete obj->animation;
6274
            obj->animation = nullptr;
6275
            return false;
6276
    }
6277
 
6278
    return true;
6279
}
6280
 
6281
void MainWindow::downloadBar(const string &msg, QWidget *parent)
6282
{
6283
    DECL_TRACER("void MainWindow::downloadBar(const string &msg, QWidget *parent)");
6284
 
6285
    if (mBusy)
6286
        return;
6287
 
6288
    mBusy = true;
6289
    mDownloadBar = new TqDownload(msg, parent);
6290
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
6291
    mDownloadBar->setScaleFactor(gScale);
6292
    mDownloadBar->doResize();
6293
#endif
6294
    mDownloadBar->show();
6295
}
6296
 
6297
void MainWindow::runEvents()
6298
{
6299
    DECL_TRACER("MainWindow::runEvents()");
6300
 
6301
    QApplication::processEvents();
6302
}
6303
 
6304
void MainWindow::onSubViewItemClicked(ulong handle, bool pressed)
6305
{
6306
    DECL_TRACER("MainWindow::onSubViewItemClicked(ulong handle)");
6307
 
6308
    if (!handle)
6309
        return;
6310
 
6311
    // Create a thread and call the base program function.
6312
    // We create a thread to not interrupt the QT framework longer then
6313
    // necessary.
6314
    if (gPageManager)
6315
        gPageManager->mouseEvent(handle, pressed);
6316
}
6317
 
6318
void MainWindow::onInputChanged(ulong handle, string& text)
6319
{
6320
    DECL_TRACER("MainWindow::onInputChanged(ulong handle, string& text)");
6321
 
6322
    try
6323
    {
6324
        std::thread thr = std::thread([=] {
6325
            if (gPageManager)
6326
                gPageManager->inputButtonFinished(handle, text);
6327
        });
6328
 
6329
        thr.detach();
6330
    }
6331
    catch (std::exception& e)
6332
    {
6333
        MSG_ERROR("Error starting a thread to handle input line finish: " << e.what());
6334
    }
6335
}
6336
 
6337
void MainWindow::onFocusChanged(ulong handle, bool in)
6338
{
6339
    DECL_TRACER("MainWindow::onFocusChanged(ulong handle, bool in)");
6340
 
6341
    try
6342
    {
6343
        std::thread thr = std::thread([=] {
6344
            if (gPageManager)
6345
                gPageManager->inputFocusChanged(handle, in);
6346
        });
6347
 
6348
        thr.detach();
6349
    }
6350
    catch (std::exception& e)
6351
    {
6352
        MSG_ERROR("Error starting a thread to handle input line finish: " << e.what());
6353
    }
6354
}
6355
 
6356
void MainWindow::onCursorChanged(ulong handle, int oldPos, int newPos)
6357
{
6358
    DECL_TRACER("MainWindow::onCursorChanged(ulong handle, int oldPos, int newPos)");
6359
 
6360
    try
6361
    {
6362
        std::thread thr = std::thread([=] {
6363
            if (gPageManager)
6364
                gPageManager->inputCursorPositionChanged(handle, oldPos, newPos);
6365
        });
6366
 
6367
        thr.detach();
6368
    }
6369
    catch (std::exception& e)
6370
    {
6371
        MSG_ERROR("Error starting a thread to handle input line finish: " << e.what());
6372
    }
6373
}
6374
 
6375
void MainWindow::onGestureEvent(QObject *obj, QGestureEvent *event)
6376
{
6377
    DECL_TRACER("MainWindow::onGestureEvent(QObject *obj, QGestureEvent *event)");
6378
 
6379
    Q_UNUSED(obj);
6380
    gestureEvent(event);
6381
}
6382
 
6383
QPixmap MainWindow::scaleImage(QPixmap& pix)
6384
{
6385
    DECL_TRACER("MainWindow::scaleImage(QPixmap& pix)");
6386
 
6387
    int width = scale(pix.width());
6388
    int height = scale(pix.height());
6389
 
6390
    return pix.scaled(width, height);
6391
}
6392
 
6393
QPixmap MainWindow::scaleImage(unsigned char* buffer, int width, int height, int pixline)
6394
{
6395
    DECL_TRACER("MainWindow::scaleImage(unsigned char* buffer, int width, int height, int pixline)");
6396
 
6397
    if (!buffer || width < 1 || height < 1 || pixline < (width * 4))
6398
    {
6399
        MSG_ERROR("Invalid image for scaling!");
6400
        return QPixmap();
6401
    }
6402
 
6403
    QImage img(buffer, width, height, pixline, QImage::Format_ARGB32);  // Original size
6404
 
6405
    if (img.isNull() || !img.valid(width-1, height-1))
6406
    {
6407
        MSG_ERROR("Unable to create a valid image!");
6408
        return QPixmap();
6409
    }
6410
 
6411
    QSize size(scale(width), scale(height));
6412
    QPixmap pixmap;
6413
    bool ret = false;
6414
 
6415
    if (isScaled())
6416
        ret = pixmap.convertFromImage(img.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); // Scaled size
6417
    else
6418
        ret = pixmap.convertFromImage(img);
6419
 
6420
    if (!ret || pixmap.isNull())
6421
    {
6422
        MSG_ERROR("Unable to create a pixmap out of an image!");
6423
    }
6424
 
6425
    return pixmap;
6426
}
6427
 
6428
#ifndef QT_NO_SESSIONMANAGER
6429
void MainWindow::commitData(QSessionManager &manager)
6430
{
6431
    if (manager.allowsInteraction())
6432
    {
6433
        if (!settingsChanged)
6434
            manager.cancel();
6435
    }
6436
    else
6437
    {
6438
        if (settingsChanged)
6439
            writeSettings();
6440
    }
6441
}
6442
#endif