Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
217 lines (183 loc) · 7.4 KB
/
Copy pathmain.cpp
File metadata and controls
217 lines (183 loc) · 7.4 KB
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
#include <QApplication>
#include <QWebEngineView>
#include <QWebSocketServer>
#include <QWebSocket>
#include <QDebug>
#include <QWebEngineSettings>
#include <QDesktopServices>
#include <QWebEnginePage>
#include <QWebEngineProfile>
#include <QStandardPaths>
#include <QSettings>
#include <QCloseEvent>
#include <QMainWindow>
#include <QStackedWidget>
#include <QLabel>
#include <QTcpServer>
#include <QSharedMemory>
#include <QLocalServer>
#include <QLocalSocket>
#include <QMessageBox>
// own
#include "httpserver.h"
int findAvailablePort(int startPort, int range = 100) {
for (int port = startPort; port < startPort + range; ++port) {
QTcpServer server;
if (server.listen(QHostAddress::Any, port)) {
server.close();
// qDebug() << "Found available port:" << port;
return port;
}
}
// qWarning() << "Could not find an available port in range.";
return -1;
}
class CustomPage : public QWebEnginePage {
public:
CustomPage(QWebEngineProfile *profile, QObject *parent = nullptr)
: QWebEnginePage(profile, parent) {}
protected:
bool acceptNavigationRequest(const QUrl &url, NavigationType type, bool isMainFrame) override {
if ((url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("https")) && url.host() != QLatin1String("localhost")) {
//qDebug() << "External link clicked, opening in browser:" << url;
QDesktopServices::openUrl(url);
return false;
}
Q_UNUSED(type);
Q_UNUSED(isMainFrame);
return true;
}
};
class ClickableView : public QWebEngineView {
public:
ClickableView(QWidget *parent = nullptr) : QWebEngineView(parent) {
// Set up a persistent profile to store cache, cookies, etc.
QWebEngineProfile *profile = new QWebEngineProfile("AksharshalaTypingTutorProfile", this);
profile->setPersistentStoragePath(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/aksharshala-profile");
CustomPage *page = new CustomPage(profile, this);
setPage(page);
settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
settings()->setAttribute(QWebEngineSettings::JavascriptCanAccessClipboard, true);
settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
setContextMenuPolicy(Qt::NoContextMenu);
}
};
class MainWindow : public QMainWindow {
public:
MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
setWindowTitle("Aksharshala Typing Tutor");
resize(1150, 760);
m_stack = new QStackedWidget(this);
setCentralWidget(m_stack);
m_webView = new ClickableView(this);
m_stack->addWidget(m_webView);
m_errorLabel = new QLabel(this);
m_errorLabel->setAlignment(Qt::AlignCenter);
m_errorLabel->setStyleSheet("font-size: 16px; color: #444;");
m_stack->addWidget(m_errorLabel);
QSettings settings("Aksharshala", "Aksharshala");
if (settings.contains("geometry")) {
restoreGeometry(settings.value("geometry").toByteArray());
}
}
void showWebView(const QUrl& url) {
m_webView->setUrl(url);
m_stack->setCurrentWidget(m_webView);
}
void showError(const QString& message) {
m_errorLabel->setText(message);
m_stack->setCurrentWidget(m_errorLabel);
}
protected:
void closeEvent(QCloseEvent *event) override {
QSettings settings("Aksharshala", "Aksharshala");
settings.setValue("geometry", saveGeometry());
QMainWindow::closeEvent(event);
}
private:
QStackedWidget* m_stack;
ClickableView* m_webView;
QLabel* m_errorLabel;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
const QString uniqueKey = "AksharshalaTypingTutor_UniqueInstanceKey";
QSharedMemory sharedMemory(uniqueKey);
if (!sharedMemory.attach()) {
if (!sharedMemory.create(1, QSharedMemory::ReadWrite)) {
QMessageBox::critical(nullptr, "Application Error",
"Could not create shared memory segment.\n"
"Please try restarting your computer.");
// qCritical() << "Failed to create shared memory:" << sharedMemory.errorString();
return 1;
}
} else {
QLocalSocket socket;
socket.connectToServer(uniqueKey);
if (socket.waitForConnected(500)) {
// qWarning() << "Application is already running. Activating the existing window.";
socket.disconnectFromServer();
return 0;
} else {
// qWarning() << "Found a stale shared memory segment. Cleaning up...";
if (!sharedMemory.detach()) {
// qWarning() << "Could not detach from stale shared memory. It might be locked.";
}
if (!sharedMemory.create(1, QSharedMemory::ReadWrite)) {
QMessageBox::critical(nullptr, "Application Error",
"Could not clean up and re-create shared memory segment.\n"
"Please try restarting your computer.");
// qCritical() << "Failed to re-create shared memory after cleanup:" << sharedMemory.errorString();
return 1;
}
}
}
MainWindow mainWindow;
QLocalServer localServer;
QObject::connect(&localServer, &QLocalServer::newConnection, [&]() {
mainWindow.setWindowState((mainWindow.windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
mainWindow.raise();
mainWindow.activateWindow();
if (localServer.hasPendingConnections()) {
QLocalSocket *socket = localServer.nextPendingConnection();
socket->disconnectFromServer();
socket->deleteLater();
}
});
QLocalServer::removeServer(uniqueKey);
localServer.listen(uniqueKey);
// Server Initialization
const int httpPort = findAvailablePort(8093);
const int wsPort = findAvailablePort(9000);
bool serversOk = (httpPort != -1 && wsPort != -1);
AHttpServer httpServer;
QWebSocketServer wsServer("WebSocket Server", QWebSocketServer::NonSecureMode);
if (serversOk) {
if (!httpServer.listen(QHostAddress::Any, httpPort)) {
// qCritical() << "HTTP server failed to start.";
serversOk = false;
}
if (!wsServer.listen(QHostAddress::Any, wsPort)) {
// qCritical() << "WebSocket server failed to start.";
serversOk = false;
}
}
// Final UI State
if (serversOk) {
QObject::connect(&wsServer, &QWebSocketServer::newConnection, [&wsServer]() {
if (QWebSocket *socket = wsServer.nextPendingConnection()) {
QObject::connect(socket, &QWebSocket::textMessageReceived, [socket](const QString &message) {
socket->sendTextMessage("Echo: " + message);
});
QObject::connect(socket, &QWebSocket::disconnected, socket, &QObject::deleteLater);
}
});
mainWindow.showWebView(QUrl(QString("http://localhost:%1").arg(httpPort)));
} else {
mainWindow.showError("Error: Could not start required services.\n"
"Another application may be using the necessary ports.");
}
mainWindow.show();
int exitCode = app.exec();
return exitCode;
}