summaryrefslogtreecommitdiffstats
path: root/qtsingleapplication/examples/loader/main.cpp
blob: 5078490766b6b4ec57b5e658ed4459bfcbacd8e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
// SPDX-License-Identifier: BSD-3-Clause

#include <qtsingleapplication.h>
#include <QFile>
#include <QMainWindow>
#include <QPrinter>
#include <QPainter>
#include <QTextEdit>
#include <QMdiArea>
#include <QTextStream>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow();

public slots:
    void handleMessage(const QString& message);

signals:
    void needToShow();

private:
    QMdiArea *workspace;
};

MainWindow::MainWindow()
{
    workspace = new QMdiArea(this);

    setCentralWidget(workspace);
}

void MainWindow::handleMessage(const QString& message)
{
    enum Action {
	Nothing,
	Open,
	Print
    } action;

    action = Nothing;
    QString filename = message;
    if (message.toLower().startsWith("/print ")) {
	filename = filename.mid(7);
	action = Print;
    } else if (!message.isEmpty()) {
	action = Open;
    }
    if (action == Nothing) {
        emit needToShow();
	return;
    }

    QFile file(filename);
    QString contents;
    if (file.open(QIODevice::ReadOnly))
        contents = file.readAll();
    else
        contents = "[[Error: Could not load file " + filename + "]]";

    QTextEdit *view = new QTextEdit;
    view->setPlainText(contents);

    switch(action) {
    case Print:
	{
	    QPrinter printer;
            view->print(&printer);
            delete view;
        }
	break;

    case Open:
	{
	    workspace->addSubWindow(view);
	    view->setWindowTitle(message);
	    view->show();
            emit needToShow();
	}
	break;
    default:
	break;
    };
}

#include "main.moc"

int main(int argc, char **argv)
{
    QtSingleApplication instance("File loader QtSingleApplication example", argc, argv);
    QString message;
    for (int a = 1; a < argc; ++a) {
	message += argv[a];
	if (a < argc-1)
	    message += " ";
    }

    if (instance.sendMessage(message))
	return 0;

    MainWindow mw;
    mw.handleMessage(message);
    mw.show();

    QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
		     &mw, SLOT(handleMessage(const QString&)));

    instance.setActivationWindow(&mw, false);
    QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow()));

    return instance.exec();
}