forked from dail8859/NotepadNext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotepadNextApplication.cpp
More file actions
528 lines (408 loc) · 17 KB
/
NotepadNextApplication.cpp
File metadata and controls
528 lines (408 loc) · 17 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
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
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#include "MainWindow.h"
#include "NotepadNextApplication.h"
#include "MarkerAppDecorator.h"
#include "RecentFilesListManager.h"
#include "EditorManager.h"
#include "LuaExtension.h"
#include "DebugManager.h"
#include "SessionManager.h"
#include "TranslationManager.h"
#include "ApplicationSettings.h"
#include "LuaState.h"
#include "lua.hpp"
#include "EditorConfigAppDecorator.h"
#include "ILexer.h"
#include "Lexilla.h"
#include <QCommandLineParser>
#include <QDirIterator>
#ifdef Q_OS_WIN
#include <Windows.h>
#endif
const SingleApplication::Options opts = SingleApplication::ExcludeAppPath | SingleApplication::ExcludeAppVersion | SingleApplication::SecondaryNotification;
void parseCommandLine(QCommandLineParser &parser, const QStringList &args)
{
parser.setApplicationDescription("Notepad Next");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("files", "Files to open.");
parser.addOptions({
{"translation", "Overrides the system default translation.", "translation"},
{"reset-settings", "Resets all application settings."},
{"n", "Places the cursor on the line number for the first file specified", "line number"},
{"workspace", "Opens the specified folder as a workspace", "workspace path"}
});
parser.process(args);
}
static QString toLocalFileName(const QString file)
{
QUrl fileUrl(file);
return fileUrl.isValid() && fileUrl.isLocalFile() ? fileUrl.toLocalFile() : file;
}
NotepadNextApplication::NotepadNextApplication(int &argc, char **argv)
: SingleApplication(argc, argv, true, opts)
{
#ifdef Q_OS_WIN
// Create a system-wide mutex so the installer can detect if it is running
CreateMutex(NULL, false, L"NotepadNextMutex");
#endif
parseCommandLine(parser, arguments());
DebugManager::manageDebugOutput();
DebugManager::pauseDebugOutput();
}
bool NotepadNextApplication::init()
{
qInfo(Q_FUNC_INFO);
#ifndef Q_OS_MACOS
setWindowIcon(QIcon(QStringLiteral(":/icons/NotepadNext.png")));
#endif
settings = new ApplicationSettings(this);
if (parser.isSet("reset-settings")) {
QFileInfo original(settings->fileName());
const QString backup = original.canonicalFilePath() + QStringLiteral(".backup");
qInfo("Resetting application settings");
qInfo("Backuping up %s to %s", qUtf8Printable(settings->fileName()), qUtf8Printable(backup));
QFile::remove(backup);
QFile::rename(settings->fileName(), backup);
settings->clear();
}
// Translation files are stored as a qresource
translationManager = new TranslationManager(this, QStringLiteral(":/i18n/"));
// The command line overrides the settings
if (!parser.value("translation").isEmpty()) {
translationManager->loadTranslation(parser.value("translation"));
}
else if (!settings->translation().isEmpty()){
translationManager->loadTranslation(settings->translation());
}
else {
translationManager->loadSystemDefaultTranslation();
}
// This connection isn't needed since the application can not appropriately retranslate the UI at runtime
//connect(settings, &ApplicationSettings::translationChanged, translationManager, &TranslationManager::loadTranslationByName);
luaState = new LuaState();
recentFilesListManager = new RecentFilesListManager(this);
editorManager = new EditorManager(settings, this);
sessionManager = new SessionManager(this);
connect(editorManager, &EditorManager::editorCreated, recentFilesListManager, [=](ScintillaNext *editor) {
if (editor->isFile()) {
recentFilesListManager->removeFile(editor->getFilePath());
}
});
connect(editorManager, &EditorManager::editorClosed, recentFilesListManager, [=](ScintillaNext *editor) {
if (editor->isFile()) {
recentFilesListManager->addFile(editor->getFilePath());
}
});
loadSettings();
connect(this, &NotepadNextApplication::aboutToQuit, this, &NotepadNextApplication::saveSettings);
EditorConfigAppDecorator *ecad = new EditorConfigAppDecorator(this);
ecad->setEnabled(true);
MarkerAppDecorator *mad = new MarkerAppDecorator(this);
mad->setEnabled(true);
luaState->setVariable("dark_mode", settings->effectiveDarkMode());
luaState->executeFile(":/scripts/init.lua");
LuaExtension::Instance().Initialise(luaState->L, Q_NULLPTR);
connect(settings, &ApplicationSettings::effectiveDarkModeChanged, this, &NotepadNextApplication::refreshEditorTheme);
createNewWindow();
connect(editorManager, &EditorManager::editorCreated, window, &MainWindow::addEditor);
// If the application is activated (e.g. user switching to another program and them back) the focus
// needs to be reset on whatever object previously had focus (e.g. the find dialog)
connect(this, &NotepadNextApplication::focusChanged, this, [&](QWidget *old, QWidget *now) {
Q_UNUSED(old);
if (now) {
currentlyFocusedWidget = now;
}
});
connect(this, &SingleApplication::instanceStarted, window, &MainWindow::bringWindowToForeground);
connect(this, &SingleApplication::receivedMessage, this, &NotepadNextApplication::receiveInfoFromSecondaryInstance, Qt::QueuedConnection);
connect(this, &NotepadNextApplication::applicationStateChanged, this, [&](Qt::ApplicationState state) {
if (state == Qt::ApplicationActive) {
// Make sure it is active...
// The application can be active without the main window being show e.g. if there is a
// message box that pops up before the main window
if (window->isActiveWindow()) {
window->focusIn();
}
if (!currentlyFocusedWidget.isNull()) {
currentlyFocusedWidget->activateWindow();
}
}
});
if (settings->restorePreviousSession()) {
qInfo("Restoring previous session");
sessionManager->loadSession(window);
}
openFiles(parser.positionalArguments());
if (parser.isSet("n") && parser.positionalArguments().length() > 0) {
QString firstFile = parser.positionalArguments()[0];
ScintillaNext *editor = editorManager->getEditorByFilePath(toLocalFileName(firstFile));
if (editor) {
int n = parser.value("n").toInt();
editor->gotoLine(n - 1);
}
}
// If the window does not have any editors (meaning the no files were
// specified on the command line) then create a new empty file
if (window->editorCount() == 0) {
window->newFile();
}
// Everything should be ready at this point
window->restoreWindowState();
// Check this after restoring the state, as the state contains the previous visibility state of the FAW dock
if (parser.isSet("workspace")) {
const QString dir = parser.value("workspace");
qInfo("Opening folder as workspace: %s", qUtf8Printable(dir));
window->setFolderAsWorkspacePath(dir);
}
window->show();
DebugManager::resumeDebugOutput();
return true;
}
SessionManager *NotepadNextApplication::getSessionManager() const
{
SessionManager::SessionFileTypes fileTypes;
if (settings->restorePreviousSession()) {
fileTypes |= SessionManager::SavedFile;
}
if (settings->restoreUnsavedFiles()) {
fileTypes |= SessionManager::UnsavedFile;
}
if (settings->restoreTempFiles()) {
fileTypes |= SessionManager::TempFile;
}
// Update the file types supported in case something has changed in the settings
sessionManager->setSessionFileTypes(fileTypes);
return sessionManager;
}
QString NotepadNextApplication::getFileDialogFilter() const
{
return getLuaState()->executeAndReturn<QString>("return DialogFilters()");
}
QString NotepadNextApplication::getFileDialogFilterForLanguage(const QString &language) const
{
getLuaState()->setVariable("langForFilter", language);
return getLuaState()->executeAndReturn<QString>("return FilterForLanguage(langForFilter)");
}
QStringList NotepadNextApplication::getLanguages() const
{
return getLuaState()->executeAndReturn<QStringList>(
R"(
local names = {}
for k in pairs(languages) do table.insert(names, k) end
table.sort(names, function (a, b) return string.lower(a) < string.lower(b) end)
return names
)");
}
void NotepadNextApplication::setEditorLanguage(ScintillaNext *editor, const QString &languageName) const
{
LuaExtension::Instance().setEditor(editor);
getLuaState()->setVariable("languageName", languageName);
const QString lexer = getLuaState()->executeAndReturn<QString>("return languages[languageName].lexer");
editor->languageName = languageName;
editor->languageSingleLineComment = getLuaState()->executeAndReturn<QString>("return languages[languageName].singleLineComment or \"\"").toUtf8();
auto lexerInstance = CreateLexer(lexer.toLatin1().constData());
editor->setILexer((sptr_t) lexerInstance);
editor->clearDocumentStyle(); // Remove all previous style information, setting the lexer does not guarantee styling information is cleared
// Not ideal this has to be manually emitted but it works since setILexer() is not widely used
emit editor->lexerChanged();
// Dynamic properties can be used to skip part of the default initialization. The value in the
// property doesn't currently matter, but may be used at a later point.
bool skipTabs = editor->QObject::property("nn_skip_usetabs").isValid();
bool skipTabWidth = editor->QObject::property("nn_skip_tabwidth").isValid();
getLuaState()->setVariable("skip_tabs", skipTabs);
getLuaState()->setVariable("skip_tabwidth", skipTabWidth);
getLuaState()->execute("SetLanguage(languageName)");
// Restore line number, brace match, and indent guide colors that the
// Lua-side styleClearAll wiped.
editorManager->applyEditorNamedStyles(editor);
}
QString NotepadNextApplication::detectLanguage(ScintillaNext *editor) const
{
qInfo(Q_FUNC_INFO);
QString language_name = QStringLiteral("Text");
if (editor->isFile()) {
language_name = detectLanguageFromExtension(editor->getFileInfo().suffix());
}
if (language_name == QStringLiteral("Text")) {
language_name = detectLanguageFromContents(editor);
}
return language_name;
}
QString NotepadNextApplication::detectLanguageFromExtension(const QString &extension) const
{
qInfo(Q_FUNC_INFO);
getLuaState()->setVariable("ext", extension);
return getLuaState()->executeAndReturn<QString>(R"(
for name, L in pairs(languages) do
if L.extensions then
for _, v in ipairs(L.extensions) do
if v == ext then
return name
end
end
end
end
return "Text"
)");
}
QString NotepadNextApplication::detectLanguageFromContents(ScintillaNext *editor) const
{
qInfo(Q_FUNC_INFO);
LuaExtension::Instance().setEditor(editor);
return getLuaState()->executeAndReturn<QString>(R"(
-- Grab a small chunk
if editor.Length > 0 then
editor:SetTargetRange(0, math.min(64, editor.Length))
return DetectLanguageFromContents(editor.TargetText)
end
return "Text"
)");
}
void NotepadNextApplication::sendInfoToPrimaryInstance()
{
qInfo(Q_FUNC_INFO);
QStringList argsToSend;
const QStringList positionalArguments = parser.positionalArguments();
// Any positional arguments need translated into an absolute file path relative to this instance
for (const QString &arg : arguments()) {
if (positionalArguments.contains(arg)) {
QFileInfo fileInfo(arg);
argsToSend.append(fileInfo.absoluteFilePath());
} else {
argsToSend.append(arg);
}
}
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);
stream << argsToSend;
const bool success = sendMessage(buffer);
if (!success) {
qWarning("sendMessage() unsuccessful");
}
}
void NotepadNextApplication::receiveInfoFromSecondaryInstance(quint32 instanceId, QByteArray message)
{
qInfo(Q_FUNC_INFO);
Q_UNUSED(instanceId)
QDataStream stream(&message, QIODevice::ReadOnly);
QStringList args;
stream >> args;
QCommandLineParser parser;
parseCommandLine(parser, args);
openFiles(parser.positionalArguments());
}
bool NotepadNextApplication::isRunningAsAdmin() const
{
static bool initialized = false;
static bool isAdmin = false;
if (!initialized) {
initialized = true;
#ifdef Q_OS_WIN
BOOL isMember;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
PSID administratorsGroupSid = NULL;
// Create a SID for the Administrators group
if (AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &administratorsGroupSid)) {
if (CheckTokenMembership(NULL, administratorsGroupSid, &isMember)) {
isAdmin = isMember;
}
FreeSid(administratorsGroupSid);
}
#endif
}
return isAdmin;
}
bool NotepadNextApplication::event(QEvent *event)
{
// Handle the QFileOpenEvent to open files on MacOS X.
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent*>(event);
qInfo("QFileOpenEvent %s", qUtf8Printable(fileOpenEvent->file()));
openFiles(QStringList() << fileOpenEvent->file());
return true;
}
return SingleApplication::event(event);
}
void NotepadNextApplication::openFiles(const QStringList &files)
{
qInfo(Q_FUNC_INFO);
for (const QString &file : files) {
window->openFile(toLocalFileName(file));
}
}
void NotepadNextApplication::loadSettings()
{
recentFilesListManager->setFileList(getSettings()->value("App/RecentFilesList").toStringList());
}
void NotepadNextApplication::saveSettings()
{
getSettings()->setValue("App/RecentFilesList", recentFilesListManager->fileList());
}
void NotepadNextApplication::saveSession()
{
// Iterate all the opened editors and add them to the recent file list
for (const auto &editor : window->editors()) {
if (editor->isFile()) {
recentFilesListManager->addFile(editor->getFilePath());
}
}
saveSettings();
getSessionManager()->saveSession(window);
}
MainWindow *NotepadNextApplication::createNewWindow()
{
Q_ASSERT(window == Q_NULLPTR);
window = new MainWindow(this);
// Keep Lua's editor reference up to date
connect(window, &MainWindow::editorActivated, this, [](ScintillaNext *editor) {
LuaExtension::Instance().setEditor(editor);
});
// TODO: this shouldn't be dependent on a MainWindow closing, but this works for now
// since the assumption is MainWindow::aboutToClose() infers the application is shutting
// down but the editors are still active.
connect(window, &MainWindow::aboutToClose, this, &NotepadNextApplication::saveSession);
// Timer to autosave the session
connect(&autoSaveTimer, &QTimer::timeout, this, &NotepadNextApplication::saveSession);
autoSaveTimer.start(60 * 1000);
return window;
}
QStringList NotepadNextApplication::debugInfo() const
{
QStringList info;
info.append(QStringLiteral("%1 v%2 %3").arg(applicationDisplayName(), applicationVersion(), APP_DISTRIBUTION));
info.append(QStringLiteral("Build Date/Time: %1 %2").arg(__DATE__, __TIME__));
info.append(QStringLiteral("Qt: %1").arg(qVersion()));
info.append(QStringLiteral("OS: %1").arg(QSysInfo::prettyProductName()));
info.append(QStringLiteral("Locale: %1").arg(QLocale::system().name()));
info.append(QStringLiteral("CPU: %1").arg(QSysInfo::currentCpuArchitecture()));
info.append(QStringLiteral("File Path: %1").arg(applicationFilePath()));
info.append(QStringLiteral("Arguments: %1").arg(arguments().join(' ')));
info.append(QStringLiteral("Config File: %1").arg(ApplicationSettings().fileName()));
return info;
}
void NotepadNextApplication::refreshEditorTheme()
{
getLuaState()->setVariable("dark_mode", settings->effectiveDarkMode());
getLuaState()->execute("UpdateTheme()");
for (auto &editor : editorManager->getEditors()) {
if (!editor->languageName.isEmpty())
setEditorLanguage(editor, editor->languageName);
}
}