1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
|
/*
Q Light Controller Plus
app.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QQuickItemGrabResult>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QtCore/qbuffer.h>
#include <QFontDatabase>
#include <QOpenGLContext>
#include <QPrintDialog>
#include <QApplication>
#include <QTranslator>
#include <QQmlContext>
#include <QQuickItem>
#include <QSettings>
#include <QKeyEvent>
#include <QPrinter>
#include <QPainter>
#include <QScreen>
#include <unistd.h>
#include "app.h"
#include "uimanager.h"
#include "simpledesk.h"
#include "showmanager.h"
#include "fixtureeditor.h"
#include "modelselector.h"
#include "videoprovider.h"
#include "importmanager.h"
#include "contextmanager.h"
#include "virtualconsole.h"
#include "fixturebrowser.h"
#include "fixturemanager.h"
#include "palettemanager.h"
#include "functionmanager.h"
#include "fixturegroupeditor.h"
#include "inputoutputmanager.h"
#include "tardis.h"
#include "networkmanager.h"
#include "qlcfixturedefcache.h"
#include "audioplugincache.h"
#include "rgbscriptscache.h"
#include "qlcconfig.h"
#include "qlcfile.h"
#define SETTINGS_WORKINGPATH "workspace/workingpath"
#define SETTINGS_RECENTFILE "workspace/recent"
#define KXMLQLCWorkspaceWindow "CurrentWindow"
#define MAX_RECENT_FILES 10
App::App()
: QQuickView()
, m_translator(nullptr)
, m_fixtureBrowser(nullptr)
, m_fixtureManager(nullptr)
, m_contextManager(nullptr)
, m_ioManager(nullptr)
, m_showManager(nullptr)
, m_simpleDesk(nullptr)
, m_videoProvider(nullptr)
, m_networkManager(nullptr)
, m_uiManager(nullptr)
, m_doc(nullptr)
, m_docLoaded(false)
, m_printItem(nullptr)
, m_fileName(QString())
, m_importManager(nullptr)
, m_fixtureEditor(nullptr)
{
QSettings settings;
updateRecentFilesList();
QVariant dir = settings.value(SETTINGS_WORKINGPATH);
if (dir.isValid() == true)
m_workingPath = dir.toString();
setAccessMask(defaultMask());
connect(this, &App::screenChanged, this, &App::slotScreenChanged);
connect(this, SIGNAL(closing(QQuickCloseEvent*)), this, SLOT(slotClosing()));
connect(this, &App::sceneGraphInitialized, this, &App::slotSceneGraphInitialized);
}
App::~App()
{
}
QString App::appName() const
{
return QString(APPNAME);
}
QString App::appVersion() const
{
return QString(APPVERSION);
}
void App::startup()
{
qmlRegisterUncreatableType<App>("org.qlcplus.classes", 1, 0, "App", "Can't create an App!");
qmlRegisterUncreatableType<Fixture>("org.qlcplus.classes", 1, 0, "Fixture", "Can't create a Fixture!");
qmlRegisterUncreatableType<Function>("org.qlcplus.classes", 1, 0, "QLCFunction", "Can't create a Function!");
qmlRegisterType<ModelSelector>("org.qlcplus.classes", 1, 0, "ModelSelector");
setTitle(APPNAME);
setIcon(QIcon(":/qlcplus.svg"));
if (QFontDatabase::addApplicationFont(":/RobotoCondensed-Regular.ttf") < 0)
qWarning() << "Roboto condensed cannot be loaded!";
if (QFontDatabase::addApplicationFont(":/RobotoMono-Regular.ttf") < 0)
qWarning() << "Roboto mono cannot be loaded!";
rootContext()->setContextProperty("qlcplus", this);
slotScreenChanged(screen());
initDoc();
m_uiManager = new UiManager(this, m_doc);
rootContext()->setContextProperty("uiManager", m_uiManager);
m_ioManager = new InputOutputManager(this, m_doc);
m_fixtureBrowser = new FixtureBrowser(this, m_doc);
m_fixtureManager = new FixtureManager(this, m_doc);
m_fixtureGroupEditor = new FixtureGroupEditor(this, m_doc, m_fixtureManager);
m_functionManager = new FunctionManager(this, m_doc);
m_simpleDesk = new SimpleDesk(this, m_doc, m_functionManager);
m_contextManager = new ContextManager(this, m_doc, m_fixtureManager, m_functionManager);
m_paletteManager = new PaletteManager(this, m_doc, m_contextManager);
m_virtualConsole = new VirtualConsole(this, m_doc, m_contextManager);
m_showManager = new ShowManager(this, m_doc);
m_networkManager = new NetworkManager(this, m_doc);
rootContext()->setContextProperty("networkManager", m_networkManager);
connect(m_networkManager, &NetworkManager::clientAccessRequest, this, &App::slotClientAccessRequest);
connect(m_networkManager, &NetworkManager::accessMaskChanged, this, &App::setAccessMask);
connect(m_networkManager, &NetworkManager::requestProjectLoad, this, &App::slotLoadDocFromMemory);
m_tardis = new Tardis(this, m_doc, m_networkManager, m_fixtureManager, m_functionManager,
m_contextManager, m_simpleDesk, m_showManager, m_virtualConsole);
rootContext()->setContextProperty("tardis", m_tardis);
m_contextManager->registerContext(m_virtualConsole);
m_contextManager->registerContext(m_simpleDesk);
m_contextManager->registerContext(m_showManager);
m_contextManager->registerContext(m_ioManager);
// register an uncreatable type just to use the enums in QML
qmlRegisterUncreatableType<ContextManager>("org.qlcplus.classes", 1, 0, "ContextManager", "Can't create a ContextManager!");
qmlRegisterUncreatableType<ShowManager>("org.qlcplus.classes", 1, 0, "ShowManager", "Can't create a ShowManager!");
qmlRegisterUncreatableType<NetworkManager>("org.qlcplus.classes", 1, 0, "NetworkManager", "Can't create a NetworkManager!");
qmlRegisterUncreatableType<SimpleDesk>("org.qlcplus.classes", 1, 0, "SimpleDesk", "Can't create a SimpleDesk!");
// Start up in non-modified state
m_doc->resetModified();
m_uiManager->initialize();
// and here we go !
setSource(QUrl("qrc:/MainView.qml"));
}
void App::toggleFullscreen()
{
static int wstate = windowState();
if (windowState() & Qt::WindowFullScreen)
{
if (wstate & Qt::WindowMaximized)
showMaximized();
else
showNormal();
wstate = windowState();
}
else
{
wstate = windowState();
showFullScreen();
}
}
void App::setLanguage(QString locale)
{
if (m_translator != nullptr)
{
QCoreApplication::removeTranslator(m_translator);
delete m_translator;
}
QString translationPath = QLCFile::systemDirectory(TRANSLATIONDIR).absolutePath();
if (locale.isEmpty() == true)
locale = QLocale::system().name();
QString file(QString("%1_%2").arg("qlcplus").arg(locale));
m_translator = new QTranslator(QCoreApplication::instance());
if (m_translator->load(file, translationPath) == true)
QCoreApplication::installTranslator(m_translator);
engine()->retranslate();
}
QString App::goboSystemPath() const
{
return QLCFile::systemDirectory(GOBODIR).absolutePath();
}
void App::show()
{
QScreen *currScreen = screen();
QRect rect(0, 0, 800, 600);
rect.moveTopLeft(currScreen->geometry().topLeft());
setGeometry(rect);
showMaximized();
}
qreal App::pixelDensity() const
{
return m_pixelDensity;
}
int App::accessMask() const
{
return m_accessMask;
}
bool App::is3DSupported() const
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
if (openglContext() == nullptr)
return false;
int glVersion = (openglContext()->format().majorVersion() * 10) + openglContext()->format().minorVersion();
return glVersion < 33 ? false : true;
#else
// TODO: Qt6
return true;
#endif
}
void App::aboutQt()
{
qApp->aboutQt();
}
void App::exit()
{
//destroy();
QApplication::quit();
}
void App::setAccessMask(int mask)
{
if (mask == m_accessMask)
return;
m_accessMask = mask;
emit accessMaskChanged(mask);
}
int App::defaultMask() const
{
return AC_FixtureEditing | AC_FunctionEditing | AC_InputOutput |
AC_ShowManager | AC_SimpleDesk | AC_VCControl | AC_VCEditing;
}
void App::keyPressEvent(QKeyEvent *e)
{
if (m_contextManager)
m_contextManager->handleKeyPress(e);
QQuickView::keyPressEvent(e);
}
void App::keyReleaseEvent(QKeyEvent *e)
{
if (m_contextManager)
m_contextManager->handleKeyRelease(e);
QQuickView::keyReleaseEvent(e);
}
bool App::event(QEvent *event)
{
if (event->type() == QEvent::Close)
{
if (m_doc->isModified())
{
QMetaObject::invokeMethod(rootObject(), "saveBeforeExit");
event->ignore();
return false;
}
}
return QQuickView::event(event);
}
void App::slotSceneGraphInitialized()
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
if (openglContext() == nullptr)
return;
qDebug() << "OpenGL version: " << openglContext()->format().majorVersion() << openglContext()->format().minorVersion();
#else
// TODO: Qt6
#endif
}
void App::slotScreenChanged(QScreen *screen)
{
bool isLandscape = (screen->orientation() == Qt::LandscapeOrientation ||
screen->orientation() == Qt::InvertedLandscapeOrientation) ? true : false;
qreal sSize = isLandscape ? screen->size().height() : screen->size().width();
m_pixelDensity = qMax(screen->physicalDotsPerInch() * 0.039370, sSize / 220.0);
qDebug() << "Screen changed to" << screen->name() << ", pixel density:" << m_pixelDensity
<< ", physical size:" << screen->physicalSize();
rootContext()->setContextProperty("screenPixelDensity", m_pixelDensity);
}
void App::slotClosing()
{
if (m_contextManager)
{
delete m_contextManager;
m_contextManager = nullptr;
}
}
void App::slotClientAccessRequest(QString name)
{
QMetaObject::invokeMethod(rootObject(), "openAccessRequest",
Q_ARG(QVariant, name));
}
void App::slotAccessMaskChanged(int mask)
{
setAccessMask(mask);
}
/*********************************************************************
* Doc
*********************************************************************/
Doc *App::doc()
{
return m_doc;
}
bool App::docLoaded()
{
return m_docLoaded;
}
bool App::docModified() const
{
return m_doc->isModified();
}
void App::initDoc()
{
Q_ASSERT(m_doc == nullptr);
m_doc = new Doc(this);
connect(m_doc, SIGNAL(modified(bool)), this, SIGNAL(docModifiedChanged()));
connect(m_doc->masterTimer(), SIGNAL(functionListChanged()),
this, SIGNAL(runningFunctionsCountChanged()));
/* Load user fixtures first so that they override system fixtures */
m_doc->fixtureDefCache()->load(QLCFixtureDefCache::userDefinitionDirectory());
m_doc->fixtureDefCache()->loadMap(QLCFixtureDefCache::systemDefinitionDirectory());
/* Load channel modifiers templates */
m_doc->modifiersCache()->load(QLCModifiersCache::systemTemplateDirectory(), true);
m_doc->modifiersCache()->load(QLCModifiersCache::userTemplateDirectory());
/* Load RGB scripts */
m_doc->rgbScriptsCache()->load(RGBScriptsCache::systemScriptsDirectory());
m_doc->rgbScriptsCache()->load(RGBScriptsCache::userScriptsDirectory());
/* Load plugins */
#if defined Q_OS_ANDROID
QString pluginsPath = QString("%1/../lib").arg(QDir::currentPath());
m_doc->ioPluginCache()->load(QDir(pluginsPath));
#else
m_doc->ioPluginCache()->load(IOPluginCache::systemPluginDirectory());
#endif
/* Load audio decoder plugins
* This doesn't use a AudioPluginCache::systemPluginDirectory() cause
* otherwise the qlcconfig.h creation should have been moved into the
* audio folder, which doesn't make much sense */
m_doc->audioPluginCache()->load(QLCFile::systemDirectory(AUDIOPLUGINDIR, KExtPlugin));
m_videoProvider = new VideoProvider(this, m_doc);
Q_ASSERT(m_doc->inputOutputMap() != nullptr);
/* Load input plugins & profiles */
m_doc->inputOutputMap()->loadProfiles(InputOutputMap::userProfileDirectory());
m_doc->inputOutputMap()->loadProfiles(InputOutputMap::systemProfileDirectory());
m_doc->inputOutputMap()->loadDefaults();
m_doc->inputOutputMap()->setBeatGeneratorType(InputOutputMap::Internal);
m_doc->inputOutputMap()->startUniverses();
m_doc->masterTimer()->start();
}
void App::clearDocument()
{
if (m_videoProvider)
{
delete m_videoProvider;
m_videoProvider = nullptr;
}
m_contextManager->resetFixtureSelection();
//m_simpleDesk->resetContents(); // TODO
m_showManager->resetContents();
m_virtualConsole->resetContents();
m_doc->masterTimer()->stop();
m_doc->clearContents();
m_tardis->resetHistory();
m_doc->inputOutputMap()->resetUniverses();
setFileName(QString());
m_doc->resetModified();
m_doc->inputOutputMap()->startUniverses();
m_doc->masterTimer()->start();
}
int App::runningFunctionsCount() const
{
return m_doc->masterTimer()->runningFunctions();
}
void App::stopAllFunctions()
{
// first, gracefully stop via Function Manager (if that's the case)
m_functionManager->setPreviewEnabled(false);
// then, brutally kill the rest (could be started from VC, etc)
m_doc->masterTimer()->stopAllFunctions();
}
void App::enableKioskMode()
{
// enable Virtual console only
setAccessMask(AC_VCControl);
}
void App::createKioskCloseButton(const QRect &rect)
{
Q_UNUSED(rect)
// TODO
}
/*********************************************************************
* Printer
*********************************************************************/
void App::printItem(QQuickItem *item)
{
if (item == nullptr)
return;
m_printItem = item;
m_printerImage = item->grabToImage();
connect(m_printerImage.data(), &QQuickItemGrabResult::ready, this, &App::slotItemReadyForPrinting);
}
void App::slotItemReadyForPrinting()
{
QPrinter printer;
QPrintDialog *dlg = new QPrintDialog(&printer);
if (dlg->exec() == QDialog::Accepted)
{
QRectF pageRect = printer.pageLayout().paintRect();
QSize imgSize = m_printerImage->image().size();
int totalHeight = imgSize.height();
int yOffset = 0;
qDebug() << "Page size:" << pageRect << ", image size:" << imgSize;
QPainter painter(&printer);
painter.setRenderHint(QPainter::Antialiasing, false);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
QImage img = m_printerImage->image();
int actualWidth = imgSize.width();
// if the grabbed image is larger than the page, fit it to the page width
if (pageRect.width() < imgSize.width())
{
img = m_printerImage->image().scaledToWidth(pageRect.width(), Qt::SmoothTransformation);
actualWidth = pageRect.width();
}
// handle multi-page printing
while (totalHeight > 0)
{
painter.drawImage(QPoint(0, 0), img, QRectF(0, yOffset, actualWidth, pageRect.height()));
yOffset += pageRect.height();
totalHeight -= pageRect.height();
if (totalHeight > 0)
printer.newPage();
}
painter.end();
}
m_printerImage.clear();
m_printItem->setProperty("isPrinting", false);
m_printItem = nullptr;
}
/*********************************************************************
* Load & Save
*********************************************************************/
void App::setFileName(const QString &fileName)
{
m_fileName = fileName;
}
QString App::fileName() const
{
return m_fileName;
}
void App::updateRecentFilesList(QString filename)
{
QSettings settings;
if (filename.isEmpty() == false)
{
m_recentFiles.removeAll(filename); // in case the string is already present, remove it...
m_recentFiles.prepend(filename); // and add it to the top
for (int i = 0; i < m_recentFiles.count(); i++)
{
settings.setValue(QString("%1%2").arg(SETTINGS_RECENTFILE).arg(i), m_recentFiles.at(i));
emit recentFilesChanged();
}
}
else
{
for (int i = 0; i < MAX_RECENT_FILES; i++)
{
QVariant recent = settings.value(QString("%1%2").arg(SETTINGS_RECENTFILE).arg(i));
if (recent.isValid() == true)
m_recentFiles.append(recent.toString());
}
}
}
QStringList App::recentFiles() const
{
return m_recentFiles;
}
QString App::workingPath() const
{
return m_workingPath;
}
void App::setWorkingPath(QString workingPath)
{
QString strippedPath = workingPath.replace("file://", "");
if (m_workingPath == strippedPath)
return;
m_workingPath = strippedPath;
QSettings settings;
settings.setValue(SETTINGS_WORKINGPATH, m_workingPath);
emit workingPathChanged(strippedPath);
}
bool App::newWorkspace()
{
clearDocument();
m_fixtureManager->slotDocLoaded();
m_functionManager->slotDocLoaded();
m_contextManager->resetContexts();
return true;
}
bool App::loadWorkspace(const QString &fileName)
{
m_contextManager->resetContexts();
/* Clear existing document data */
clearDocument();
m_docLoaded = false;
emit docLoadedChanged();
QString localFilename = fileName;
if (localFilename.startsWith("file:"))
localFilename = QUrl(fileName).toLocalFile();
if (loadXML(localFilename) == QFile::NoError)
{
setTitle(QString("%1 - %2").arg(APPNAME).arg(localFilename));
setFileName(localFilename);
m_docLoaded = true;
updateRecentFilesList(localFilename);
emit docLoadedChanged();
m_doc->resetModified();
m_videoProvider = new VideoProvider(this, m_doc);
m_contextManager->resetContexts();
// autostart Function if set
if (m_doc->startupFunction() != Function::invalidId())
{
Function *func = m_doc->function(m_doc->startupFunction());
if (func != nullptr)
{
qDebug() << Q_FUNC_INFO << "Starting startup function. (" << m_doc->startupFunction() << ")";
func->start(m_doc->masterTimer(), FunctionParent::master());
}
else
{
qWarning() << Q_FUNC_INFO << "Startup function does not exist, erasing. (" << m_doc->startupFunction() << ")";
m_doc->setStartupFunction(Function::invalidId());
}
}
m_doc->inputOutputMap()->startUniverses();
return true;
}
return false;
}
void App::slotLoadDocFromMemory(QByteArray &xmlData)
{
if (xmlData.isEmpty())
return;
/* Clear existing document data */
clearDocument();
QBuffer databuf;
databuf.setData(xmlData);
databuf.open(QIODevice::ReadOnly | QIODevice::Text);
//qDebug() << "Buffer data:" << databuf.data();
QXmlStreamReader doc(&databuf);
if (doc.hasError())
{
qWarning() << Q_FUNC_INFO << "Unable to read from XML in memory";
return;
}
while (!doc.atEnd())
{
if (doc.readNext() == QXmlStreamReader::DTD)
break;
}
if (doc.hasError())
{
qDebug() << "XML has errors:" << doc.errorString();
return;
}
if (doc.dtdName() == KXMLQLCWorkspace)
loadXML(doc, true, true);
else
qDebug() << "XML doesn't have a Workspace tag";
}
bool App::saveWorkspace(const QString &fileName)
{
QString localFilename = fileName;
if (localFilename.startsWith("file:"))
localFilename = QUrl(fileName).toLocalFile();
/* Always use the workspace suffix */
if (localFilename.right(4) != KExtWorkspace)
localFilename += KExtWorkspace;
/* Set the workspace path before saving the new XML. In this way local files
can be loaded even if the workspace file will be moved */
m_doc->setWorkspacePath(QFileInfo(localFilename).absolutePath());
if (saveXML(localFilename) == QFile::NoError)
{
setTitle(QString("%1 - %2").arg(APPNAME).arg(localFilename));
updateRecentFilesList(localFilename);
return true;
}
return false;
}
QFileDevice::FileError App::loadXML(const QString &fileName)
{
QFile::FileError retval = QFile::NoError;
if (fileName.isEmpty() == true)
return QFile::OpenError;
QXmlStreamReader *doc = QLCFile::getXMLReader(fileName);
if (doc == nullptr || doc->device() == nullptr || doc->hasError())
{
qWarning() << Q_FUNC_INFO << "Unable to read from" << fileName;
return QFile::ReadError;
}
while (!doc->atEnd())
{
if (doc->readNext() == QXmlStreamReader::DTD)
break;
}
if (doc->hasError())
{
QLCFile::releaseXMLReader(doc);
return QFile::ResourceError;
}
/* Set the workspace path before loading the new XML. In this way local files
can be loaded even if the workspace file has been moved */
m_doc->setWorkspacePath(QFileInfo(fileName).absolutePath());
if (doc->dtdName() == KXMLQLCWorkspace)
{
if (loadXML(*doc) == false)
{
retval = QFile::ReadError;
}
else
{
setFileName(fileName);
m_doc->resetModified();
retval = QFile::NoError;
}
}
else
{
retval = QFile::ReadError;
qWarning() << Q_FUNC_INFO << fileName << "is not a workspace file";
}
QLCFile::releaseXMLReader(doc);
return retval;
}
bool App::loadXML(QXmlStreamReader &doc, bool goToConsole, bool fromMemory)
{
if (doc.readNextStartElement() == false)
return false;
if (doc.name() != KXMLQLCWorkspace)
{
qWarning() << Q_FUNC_INFO << "Workspace node not found";
return false;
}
QString contextName = doc.attributes().value(KXMLQLCWorkspaceWindow).toString();
while (doc.readNextStartElement())
{
if (doc.name() == KXMLQLCEngine)
{
m_doc->loadXML(doc);
}
else if (doc.name() == KXMLQLCVirtualConsole)
{
m_virtualConsole->loadXML(doc);
}
#if 0
else if (doc.name() == KXMLQLCSimpleDesk)
{
SimpleDesk::instance()->loadXML(doc);
}
#endif
else if (doc.name() == KXMLQLCCreator)
{
/* Ignore creator information */
doc.skipCurrentElement();
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown Workspace tag:" << doc.name().toString();
doc.skipCurrentElement();
}
}
if (goToConsole == true || accessMask() == AC_VCControl)
// Force the active window to be Virtual Console
m_contextManager->switchToContext("VirtualConsole");
else
// Set the active window to what was saved in the workspace file
m_contextManager->switchToContext(contextName);
// Perform post-load operations
m_virtualConsole->postLoad();
if (m_doc->errorLog().isEmpty() == false &&
fromMemory == false)
{
// TODO: emit a signal to inform the QML UI to display an error message
/*
QMessageBox msg(QMessageBox::Warning, tr("Warning"),
tr("Some errors occurred while loading the project:") + "\n\n" + m_doc->errorLog(),
QMessageBox::Ok);
msg.exec();
*/
}
return true;
}
QFile::FileError App::saveXML(const QString& fileName)
{
QString tempFileName(fileName);
tempFileName += ".temp";
QFile file(tempFileName);
if (file.open(QIODevice::WriteOnly) == false)
return file.error();
QXmlStreamWriter doc(&file);
doc.setAutoFormatting(true);
doc.setAutoFormattingIndent(1);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
doc.setCodec("UTF-8");
#endif
doc.writeStartDocument();
doc.writeDTD(QString("<!DOCTYPE %1>").arg(KXMLQLCWorkspace));
doc.writeStartElement(KXMLQLCWorkspace);
doc.writeAttribute("xmlns", QString("%1%2").arg(KXMLQLCplusNamespace).arg(KXMLQLCWorkspace));
/* Currently active context */
doc.writeAttribute(KXMLQLCWorkspaceWindow, m_contextManager->currentContext());
/* Creator information */
doc.writeStartElement(KXMLQLCCreator);
doc.writeTextElement(KXMLQLCCreatorName, APPNAME);
doc.writeTextElement(KXMLQLCCreatorVersion, APPVERSION);
doc.writeTextElement(KXMLQLCCreatorAuthor, QLCFile::currentUserName());
doc.writeEndElement();
/* Write engine components to the XML document */
m_doc->saveXML(&doc);
/* Write virtual console to the XML document */
m_virtualConsole->saveXML(&doc);
/* Write Simple Desk to the XML document */
//SimpleDesk::instance()->saveXML(&doc);
doc.writeEndElement(); // close KXMLQLCWorkspace
/* End the document and close all the open elements */
doc.writeEndDocument();
file.close();
// Save to actual requested file name
QFile currFile(fileName);
if (currFile.exists() && !currFile.remove())
{
qWarning() << "Could not erase" << fileName;
return currFile.error();
}
if (!file.rename(fileName))
{
qWarning() << "Could not rename" << tempFileName << "to" << fileName;
return file.error();
}
/* Set the file name for the current Doc instance and
set it also in an unmodified state. */
setFileName(fileName);
m_doc->resetModified();
return QFile::NoError;
}
/*********************************************************************
* Import project
*********************************************************************/
bool App::loadImportWorkspace(const QString &fileName)
{
if (m_importManager != nullptr)
delete m_importManager;
m_importManager = new ImportManager(this, m_doc);
return m_importManager->loadWorkspace(fileName);
}
void App::cancelImport()
{
if (m_importManager != nullptr)
delete m_importManager;
m_importManager = nullptr;
}
void App::importFromWorkspace()
{
if (m_importManager == nullptr)
return;
m_importManager->apply();
m_paletteManager->updatePaletteList();
delete m_importManager;
m_importManager = nullptr;
}
/*********************************************************************
* Fixture editor
*********************************************************************/
void App::createFixture()
{
if (m_fixtureEditor == nullptr)
{
m_fixtureEditor = new FixtureEditor(this, m_doc);
QMetaObject::invokeMethod(rootObject(), "switchToContext",
Q_ARG(QVariant, "FXEDITOR"),
Q_ARG(QVariant, "qrc:/FixtureEditor.qml"));
}
m_fixtureEditor->createDefinition();
}
void App::loadFixture(QString fileName)
{
if (m_fixtureEditor == nullptr)
{
m_fixtureEditor = new FixtureEditor(this, m_doc);
QMetaObject::invokeMethod(rootObject(), "switchToContext",
Q_ARG(QVariant, "FXEDITOR"),
Q_ARG(QVariant, "qrc:/FixtureEditor.qml"));
}
m_fixtureEditor->loadDefinition(fileName);
}
void App::editFixture(QString manufacturer, QString model)
{
bool switchToEditor = false;
if (m_fixtureEditor == nullptr)
{
m_fixtureEditor = new FixtureEditor(this, m_doc);
switchToEditor = true;
}
if (m_fixtureEditor->editDefinition(manufacturer, model) == false)
{
delete m_fixtureEditor;
m_fixtureEditor = nullptr;
return;
}
if (switchToEditor)
{
QMetaObject::invokeMethod(rootObject(), "switchToContext",
Q_ARG(QVariant, "FXEDITOR"),
Q_ARG(QVariant, "qrc:/FixtureEditor.qml"));
}
}
void App::closeFixtureEditor()
{
if (m_fixtureEditor)
{
delete m_fixtureEditor;
m_fixtureEditor = nullptr;
}
// reload the QLC+ main view
//setSource(QUrl("qrc:/MainView.qml"));
QMetaObject::invokeMethod(rootObject(), "switchToContext",
Q_ARG(QVariant, "FIXANDFUNC"),
Q_ARG(QVariant, "qrc:/FixturesAndFunctions.qml"));
}
|