/
gui.cpp
731 lines (621 loc) · 20.8 KB
/
gui.cpp
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
// Aseprite
// Copyright (C) 2018-2021 Igara Studio S.A.
// Copyright (C) 2001-2018 David Capello
//
// This program is distributed under the terms of
// the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "app/app.h"
#include "app/app_menus.h"
#include "app/commands/cmd_open_file.h"
#include "app/commands/command.h"
#include "app/commands/commands.h"
#include "app/commands/params.h"
#include "app/console.h"
#include "app/crash/data_recovery.h"
#include "app/doc.h"
#include "app/ini_file.h"
#include "app/modules/editors.h"
#include "app/modules/gfx.h"
#include "app/modules/gui.h"
#include "app/modules/palettes.h"
#include "app/pref/preferences.h"
#include "app/tools/ink.h"
#include "app/tools/tool_box.h"
#include "app/ui/editor/editor.h"
#include "app/ui/keyboard_shortcuts.h"
#include "app/ui/main_menu_bar.h"
#include "app/ui/main_menu_bar.h"
#include "app/ui/main_window.h"
#include "app/ui/skin/skin_property.h"
#include "app/ui/skin/skin_theme.h"
#include "app/ui/status_bar.h"
#include "app/ui/toolbar.h"
#include "app/ui_context.h"
#include "app/util/open_batch.h"
#include "base/clamp.h"
#include "base/fs.h"
#include "base/memory.h"
#include "base/string.h"
#include "doc/sprite.h"
#include "os/error.h"
#include "os/surface.h"
#include "os/system.h"
#include "os/window.h"
#include "ui/intern.h"
#include "ui/ui.h"
#ifdef ENABLE_STEAM
#include "steam/steam.h"
#endif
#include <algorithm>
#include <list>
#include <vector>
#if defined(_DEBUG) && defined(ENABLE_DATA_RECOVERY)
#include "app/crash/data_recovery.h"
#include "app/modules/editors.h"
#endif
namespace app {
using namespace gfx;
using namespace ui;
using namespace app::skin;
static struct {
int width;
int height;
int scale;
} try_resolutions[] = { { 1024, 768, 2 },
{ 800, 600, 2 },
{ 640, 480, 2 },
{ 320, 240, 1 },
{ 320, 200, 1 },
{ 0, 0, 0 } };
//////////////////////////////////////////////////////////////////////
class CustomizedGuiManager : public ui::Manager
, public ui::LayoutIO {
public:
CustomizedGuiManager(const os::WindowRef& nativeWindow)
: ui::Manager(nativeWindow) {
}
protected:
bool onProcessMessage(Message* msg) override;
#if ENABLE_DEVMODE
bool onProcessDevModeKeyDown(KeyMessage* msg);
#endif
void onInitTheme(InitThemeEvent& ev) override;
LayoutIO* onGetLayoutIO() override { return this; }
void onNewDisplayConfiguration(Display* display) override;
// LayoutIO implementation
std::string loadLayout(Widget* widget) override;
void saveLayout(Widget* widget, const std::string& str) override;
};
static os::WindowRef main_window = nullptr;
static CustomizedGuiManager* manager = nullptr;
static Theme* gui_theme = nullptr;
static ui::Timer* defered_invalid_timer = nullptr;
static gfx::Region defered_invalid_region;
// Load & save graphics configuration
static void load_gui_config(int& w, int& h, bool& maximized,
std::string& windowLayout);
static void save_gui_config();
static bool create_main_window(bool gpuAccel,
bool& maximized,
std::string& lastError)
{
int w, h;
std::string windowLayout;
load_gui_config(w, h, maximized, windowLayout);
// Scale is equal to 0 when it's the first time the program is
// executed.
int scale = Preferences::instance().general.screenScale();
os::instance()->setGpuAcceleration(gpuAccel);
try {
if (w > 0 && h > 0) {
main_window = os::instance()->makeWindow(
w, h, (scale == 0 ? 2: base::clamp(scale, 1, 4)));
}
}
catch (const os::WindowCreationException& e) {
lastError = e.what();
}
if (!main_window) {
for (int c=0; try_resolutions[c].width; ++c) {
try {
main_window =
os::instance()->makeWindow(
try_resolutions[c].width,
try_resolutions[c].height,
(scale == 0 ? try_resolutions[c].scale: scale));
break;
}
catch (const os::WindowCreationException& e) {
lastError = e.what();
}
}
}
if (main_window) {
// Change the scale value only in the first run (this will be
// saved when the program is closed).
if (scale == 0)
Preferences::instance().general.screenScale(main_window->scale());
if (!windowLayout.empty()) {
main_window->setLayout(windowLayout);
if (main_window->isMinimized())
main_window->maximize();
}
}
return (main_window != nullptr);
}
// Initializes GUI.
int init_module_gui()
{
auto& pref = Preferences::instance();
bool maximized = false;
std::string lastError = "Unknown error";
bool gpuAccel = pref.general.gpuAcceleration();
if (!create_main_window(gpuAccel, maximized, lastError)) {
// If we've created the native window with hardware acceleration,
// now we try to do it without hardware acceleration.
if (gpuAccel &&
(int(os::instance()->capabilities()) &
int(os::Capabilities::GpuAccelerationSwitch)) == int(os::Capabilities::GpuAccelerationSwitch)) {
if (create_main_window(false, maximized, lastError)) {
// Disable hardware acceleration
pref.general.gpuAcceleration(false);
}
}
}
if (!main_window) {
os::error_message(
("Unable to create a user-interface window.\nDetails: "+lastError+"\n").c_str());
return -1;
}
// Create the default-manager
manager = new CustomizedGuiManager(main_window);
// Setup the GUI theme for all widgets
gui_theme = new SkinTheme;
ui::set_theme(gui_theme, pref.general.uiScale());
if (maximized)
main_window->maximize();
// Handle live resize too redraw the entire manager, dispatch the UI
// messages, and flip the window.
os::instance()->handleWindowResize =
[](os::Window* window) {
Display* display = manager->getDisplayFromNativeWindow(window);
if (!display)
display = manager->display();
ASSERT(display);
Message* msg = new Message(kResizeDisplayMessage);
msg->setDisplay(display);
msg->setRecipient(manager);
msg->setPropagateToChildren(false);
manager->enqueueMessage(msg);
manager->dispatchMessages();
};
// Set graphics options for next time
save_gui_config();
update_windows_color_profile_from_preferences();
return 0;
}
void exit_module_gui()
{
save_gui_config();
delete defered_invalid_timer;
delete manager;
// Now we can destroy theme
ui::set_theme(nullptr, ui::guiscale());
delete gui_theme;
// This should be the last unref() of the display to delete it.
main_window.reset();
}
void update_windows_color_profile_from_preferences()
{
auto system = os::instance();
gen::WindowColorProfile windowProfile;
if (Preferences::instance().color.manage())
windowProfile = Preferences::instance().color.windowProfile();
else
windowProfile = gen::WindowColorProfile::SRGB;
switch (windowProfile) {
case gen::WindowColorProfile::MONITOR:
system->setWindowsColorSpace(nullptr);
break;
case gen::WindowColorProfile::SRGB:
system->setWindowsColorSpace(
system->makeColorSpace(gfx::ColorSpace::MakeSRGB()));
break;
case gen::WindowColorProfile::SPECIFIC: {
std::string name =
Preferences::instance().color.windowProfileName();
std::vector<os::ColorSpaceRef> colorSpaces;
system->listColorSpaces(colorSpaces);
for (auto& cs : colorSpaces) {
auto gfxCs = cs->gfxColorSpace();
if (gfxCs->type() == gfx::ColorSpace::ICC &&
gfxCs->name() == name) {
system->setWindowsColorSpace(cs);
break;
}
}
break;
}
}
}
static void load_gui_config(int& w, int& h, bool& maximized,
std::string& windowLayout)
{
gfx::Size defSize = os::instance()->defaultNewWindowSize();
w = get_config_int("GfxMode", "Width", defSize.w);
h = get_config_int("GfxMode", "Height", defSize.h);
maximized = get_config_bool("GfxMode", "Maximized", false);
windowLayout = get_config_string("GfxMode", "WindowLayout", "");
ui::set_multiple_displays(Preferences::instance().experimental.multipleWindows());
}
static void save_gui_config()
{
os::Window* window = manager->display()->nativeWindow();
if (window) {
set_config_bool("GfxMode", "Maximized", window->isMaximized());
set_config_int("GfxMode", "Width", window->originalWidth());
set_config_int("GfxMode", "Height", window->originalHeight());
std::string windowLayout = window->getLayout();
if (!windowLayout.empty())
set_config_string("GfxMode", "WindowLayout", windowLayout.c_str());
}
}
void update_screen_for_document(const Doc* document)
{
// Without document.
if (!document) {
// Well, change to the default palette.
if (set_current_palette(NULL, false)) {
// If the palette changes, refresh the whole screen.
if (manager)
manager->invalidate();
}
}
// With a document.
else {
const_cast<Doc*>(document)->notifyGeneralUpdate();
// Update the tabs (maybe the modified status has been changed).
app_rebuild_documents_tabs();
}
}
void load_window_pos(Window* window, const char* section,
const bool limitMinSize)
{
Size desktopSize = ui::get_desktop_size();
// Default position
Rect origPos = window->bounds();
// Load configurated position
Rect pos = get_config_rect(section, "WindowPos", origPos);
if (limitMinSize) {
pos.w = base::clamp(pos.w, origPos.w, desktopSize.w);
pos.h = base::clamp(pos.h, origPos.h, desktopSize.h);
}
else {
pos.w = std::min(pos.w, desktopSize.w);
pos.h = std::min(pos.h, desktopSize.h);
}
pos.setOrigin(Point(base::clamp(pos.x, 0, desktopSize.w-pos.w),
base::clamp(pos.y, 0, desktopSize.h-pos.h)));
window->setBounds(pos);
if (get_multiple_displays()) {
Rect frame = get_config_rect(section, "WindowFrame", gfx::Rect());
if (!frame.isEmpty()) {
// TODO limit window area to current workspace / all available screen limits (?)
window->loadNativeFrame(frame);
}
}
else {
del_config_value(section, "WindowFrame");
}
}
void save_window_pos(Window* window, const char *section)
{
gfx::Rect rc;
if (!window->lastNativeFrame().isEmpty()) {
os::Window* mainNativeWindow = manager->display()->nativeWindow();
int scale = mainNativeWindow->scale();
rc = window->lastNativeFrame();
set_config_rect(section, "WindowFrame", rc);
rc.offset(-mainNativeWindow->frame().origin());
rc /= scale;
}
else {
rc = window->bounds();
}
set_config_rect(section, "WindowPos", rc);
}
// TODO Replace this with new theme styles
Widget* setup_mini_font(Widget* widget)
{
auto skinProp = get_skin_property(widget);
skinProp->setMiniFont();
return widget;
}
// TODO Replace this with new theme styles
Widget* setup_mini_look(Widget* widget)
{
auto skinProp = get_skin_property(widget);
skinProp->setLook(MiniLook);
return widget;
}
//////////////////////////////////////////////////////////////////////
// Button style (convert radio or check buttons and draw it like
// normal buttons)
void defer_invalid_rect(const gfx::Rect& rc)
{
if (!defered_invalid_timer)
defered_invalid_timer = new ui::Timer(250, manager);
defered_invalid_timer->stop();
defered_invalid_timer->start();
defered_invalid_region.createUnion(defered_invalid_region, gfx::Region(rc));
}
//////////////////////////////////////////////////////////////////////
// Manager event handler.
bool CustomizedGuiManager::onProcessMessage(Message* msg)
{
#ifdef ENABLE_STEAM
if (auto steamAPI = steam::SteamAPI::instance())
steamAPI->runCallbacks();
#endif
switch (msg->type()) {
case kCloseDisplayMessage:
// When the main display is closed...
if (msg->display() == this->display()) {
// Execute the "Exit" command.
Command* command = Commands::instance()->byId(CommandId::Exit());
UIContext::instance()->executeCommandFromMenuOrShortcut(command);
return true;
}
break;
case kDropFilesMessage:
// Files are processed only when the main window is the current
// window running.
//
// TODO could we send the files to each dialog?
if (getForegroundWindow() == App::instance()->mainWindow()) {
base::paths files = static_cast<DropFilesMessage*>(msg)->files();
UIContext* ctx = UIContext::instance();
OpenBatchOfFiles batch;
while (!files.empty()) {
auto fn = files.front();
files.erase(files.begin());
// If the document is already open, select it.
Doc* doc = ctx->documents().getByFileName(fn);
if (doc) {
DocView* docView = ctx->getFirstDocView(doc);
if (docView)
ctx->setActiveView(docView);
else {
ASSERT(false); // Must be some DocView available
}
}
// Load the file
else {
// Depending on the file type we will want to do different things:
std::string extension = base::string_to_lower(
base::get_file_extension(fn));
// Install the extension
if (extension == "aseprite-extension") {
Command* cmd = Commands::instance()->byId(CommandId::Options());
Params params;
params.set("installExtension", fn.c_str());
ctx->executeCommandFromMenuOrShortcut(cmd, params);
}
// Other extensions will be handled as an image/sprite
else {
batch.open(ctx, fn,
false); // Open all frames
// Remove all used file names from the "dropped files"
for (const auto& usedFn : batch.usedFiles()) {
auto it = std::find(files.begin(), files.end(), usedFn);
if (it != files.end())
files.erase(it);
}
}
}
}
}
break;
case kKeyDownMessage: {
#if ENABLE_DEVMODE
if (onProcessDevModeKeyDown(static_cast<KeyMessage*>(msg)))
return true;
#endif // ENABLE_DEVMODE
// Call base impl to check if there is a foreground window as
// top level that needs keys. (In this way we just do not
// process keyboard shortcuts for menus and tools).
if (Manager::onProcessMessage(msg))
return true;
KeyboardShortcuts* keys = KeyboardShortcuts::instance();
for (const KeyPtr& key : *keys) {
if (key->isPressed(msg, *keys)) {
// Cancel menu-bar loops (to close any popup menu)
App::instance()->mainWindow()->getMenuBar()->cancelMenuLoop();
switch (key->type()) {
case KeyType::Tool: {
tools::Tool* current_tool = App::instance()->activeTool();
tools::Tool* select_this_tool = key->tool();
tools::ToolBox* toolbox = App::instance()->toolBox();
std::vector<tools::Tool*> possibles;
// Collect all tools with the pressed keyboard-shortcut
for (tools::Tool* tool : *toolbox) {
const KeyPtr key = KeyboardShortcuts::instance()->tool(tool);
if (key && key->isPressed(msg, *keys))
possibles.push_back(tool);
}
if (possibles.size() >= 2) {
bool done = false;
for (size_t i=0; i<possibles.size(); ++i) {
if (possibles[i] != current_tool &&
ToolBar::instance()->isToolVisible(possibles[i])) {
select_this_tool = possibles[i];
done = true;
break;
}
}
if (!done) {
for (size_t i=0; i<possibles.size(); ++i) {
// If one of the possibilities is the current tool
if (possibles[i] == current_tool) {
// We select the next tool in the possibilities
select_this_tool = possibles[(i+1) % possibles.size()];
break;
}
}
}
}
ToolBar::instance()->selectTool(select_this_tool);
return true;
}
case KeyType::Command: {
Command* command = key->command();
// Commands are executed only when the main window is
// the current window running.
if (getForegroundWindow() == App::instance()->mainWindow()) {
// OK, so we can execute the command represented
// by the pressed-key in the message...
UIContext::instance()->executeCommandFromMenuOrShortcut(
command, key->params());
return true;
}
break;
}
case KeyType::Quicktool: {
// Do nothing, it is used in the editor through the
// KeyboardShortcuts::getCurrentQuicktool() function.
break;
}
}
break;
}
}
break;
}
case kTimerMessage:
if (static_cast<TimerMessage*>(msg)->timer() == defered_invalid_timer) {
invalidateRegion(defered_invalid_region);
defered_invalid_region.clear();
defered_invalid_timer->stop();
}
break;
}
return Manager::onProcessMessage(msg);
}
#if ENABLE_DEVMODE
bool CustomizedGuiManager::onProcessDevModeKeyDown(KeyMessage* msg)
{
// Ctrl+Shift+Q generates a crash (useful to test the anticrash feature)
if (msg->ctrlPressed() &&
msg->shiftPressed() &&
msg->scancode() == kKeyQ) {
int* p = nullptr;
*p = 0; // *Crash*
return true; // This line should not be executed anyway
}
// Ctrl+F1 switches screen/UI scaling
if (msg->ctrlPressed() &&
msg->scancode() == kKeyF1) {
try {
os::Window* window = display()->nativeWindow();
int screenScale = window->scale();
int uiScale = ui::guiscale();
if (msg->shiftPressed()) {
if (screenScale == 2 && uiScale == 1) {
screenScale = 1;
uiScale = 1;
}
else if (screenScale == 1 && uiScale == 1) {
screenScale = 1;
uiScale = 2;
}
else if (screenScale == 1 && uiScale == 2) {
screenScale = 2;
uiScale = 1;
}
}
else {
if (screenScale == 2 && uiScale == 1) {
screenScale = 1;
uiScale = 2;
}
else if (screenScale == 1 && uiScale == 2) {
screenScale = 1;
uiScale = 1;
}
else if (screenScale == 1 && uiScale == 1) {
screenScale = 2;
uiScale = 1;
}
}
if (uiScale != ui::guiscale()) {
ui::set_theme(ui::get_theme(), uiScale);
}
if (screenScale != window->scale()) {
updateAllDisplaysWithNewScale(screenScale);
}
}
catch (const std::exception& ex) {
Console::showException(ex);
}
return true;
}
#ifdef ENABLE_DATA_RECOVERY
// Ctrl+Shift+R recover active sprite from the backup store
if (msg->ctrlPressed() &&
msg->shiftPressed() &&
msg->scancode() == kKeyR &&
App::instance()->dataRecovery() &&
App::instance()->dataRecovery()->activeSession() &&
current_editor &&
current_editor->document()) {
Doc* doc = App::instance()
->dataRecovery()
->activeSession()
->restoreBackupById(current_editor->document()->id(), nullptr);
if (doc)
UIContext::instance()->documents().add(doc);
return true;
}
#endif // ENABLE_DATA_RECOVERY
return false;
}
#endif // ENABLE_DEVMODE
void CustomizedGuiManager::onInitTheme(InitThemeEvent& ev)
{
Manager::onInitTheme(ev);
// Update the theme on all menus
AppMenus::instance()->initTheme();
}
void CustomizedGuiManager::onNewDisplayConfiguration(Display* display)
{
Manager::onNewDisplayConfiguration(display);
// Only whne the main display/window is modified
if (display == this->display()) {
save_gui_config();
// TODO Should we provide a more generic way for all ui::Window to
// detect the os::Window (or UI Screen Scaling) change?
Console::notifyNewDisplayConfiguration();
}
}
std::string CustomizedGuiManager::loadLayout(Widget* widget)
{
if (widget->window() == nullptr)
return "";
std::string windowId = widget->window()->id();
std::string widgetId = widget->id();
return get_config_string(("layout:"+windowId).c_str(), widgetId.c_str(), "");
}
void CustomizedGuiManager::saveLayout(Widget* widget, const std::string& str)
{
if (widget->window() == NULL)
return;
std::string windowId = widget->window()->id();
std::string widgetId = widget->id();
set_config_string(("layout:"+windowId).c_str(),
widgetId.c_str(),
str.c_str());
}
} // namespace app