forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSneedacityApp.cpp
2466 lines (2061 loc) · 76.4 KB
/
SneedacityApp.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
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
/**********************************************************************
Sneedacity: A Digital Audio Editor
SneedacityApp.cpp
Dominic Mazzoni
******************************************************************//**
\class SneedacityApp
\brief SneedacityApp is the 'main' class for Sneedacity
It handles initialization and termination by subclassing wxApp.
*//*******************************************************************/
#include "SneedacityApp.h"
#if 0
// This may be used to debug memory leaks.
// See: Visual Leak Detector @ http://vld.codeplex.com/
#include <vld.h>
#endif
#include <wx/setup.h> // for wxUSE_* macros
#include <wx/wxcrtvararg.h>
#include <wx/defs.h>
#include <wx/evtloop.h>
#include <wx/app.h>
#include <wx/bitmap.h>
#include <wx/docview.h>
#include <wx/event.h>
#include <wx/ipc.h>
#include <wx/window.h>
#include <wx/intl.h>
#include <wx/menu.h>
#include <wx/snglinst.h>
#include <wx/splash.h>
#include <wx/stdpaths.h>
#include <wx/sysopt.h>
#include <wx/fontmap.h>
#include <wx/fs_zip.h>
#include <wx/image.h>
#include <wx/dir.h>
#include <wx/file.h>
#include <wx/filename.h>
#ifdef __WXGTK__
#include <unistd.h>
#ifdef HAVE_GTK
#include <gtk/gtk.h>
#endif
#endif
// chmod, lstat, geteuid
#ifdef __UNIX__
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <stdio.h>
#endif
#if defined(__WXMSW__)
#include <wx/msw/registry.h> // for wxRegKey
#endif
#include "SneedacityLogger.h"
#include "AboutDialog.h"
#include "AColor.h"
#include "SneedacityFileConfig.h"
#include "AudioIO.h"
#include "Benchmark.h"
#include "Clipboard.h"
#include "CrashReport.h" // for HAS_CRASH_REPORT
#include "commands/CommandHandler.h"
#include "commands/AppCommandEvent.h"
#include "widgets/ASlider.h"
#include "FFmpeg.h"
//#include "LangChoice.h"
#include "Languages.h"
#include "Menus.h"
#include "PluginManager.h"
#include "Project.h"
#include "ProjectAudioIO.h"
#include "ProjectAudioManager.h"
#include "ProjectFileIO.h"
#include "ProjectFileManager.h"
#include "ProjectHistory.h"
#include "ProjectManager.h"
#include "ProjectSettings.h"
#include "ProjectWindow.h"
#include "Screenshot.h"
#include "Sequence.h"
#include "TempDirectory.h"
#include "Track.h"
#include "prefs/PrefsDialog.h"
#include "Theme.h"
#include "PlatformCompatibility.h"
#include "AutoRecoveryDialog.h"
#include "SplashDialog.h"
#include "FFT.h"
#include "widgets/SneedacityMessageBox.h"
#include "prefs/DirectoriesPrefs.h"
#include "prefs/GUIPrefs.h"
#include "tracks/ui/Scrubbing.h"
#include "widgets/FileConfig.h"
#include "widgets/FileHistory.h"
#ifdef EXPERIMENTAL_EASY_CHANGE_KEY_BINDINGS
#include "prefs/KeyConfigPrefs.h"
#endif
//temporarily commented out till it is added to all projects
//#include "Profiler.h"
#include "ModuleManager.h"
#include "import/Import.h"
#ifdef EXPERIMENTAL_SCOREALIGN
#include "effects/ScoreAlignDialog.h"
#endif
#if 0
#ifdef _DEBUG
#ifdef _MSC_VER
#undef THIS_FILE
static char*THIS_FILE= __FILE__;
#define new new(_NORMAL_BLOCK, THIS_FILE, __LINE__)
#endif
#endif
#endif
// DA: Logo for Splash Screen
#ifdef EXPERIMENTAL_DA
#include "../images/DarkSneedacityLogoWithName.xpm"
#else
#include "../images/SneedacityLogoWithName.xpm"
#endif
#include <thread>
////////////////////////////////////////////////////////////
/// Custom events
////////////////////////////////////////////////////////////
#if 0
#ifdef __WXGTK__
static void wxOnAssert(const wxChar *fileName, int lineNumber, const wxChar *msg)
{
if (msg)
wxPrintf("ASSERTION FAILED: %s\n%s: %d\n", (const char *)wxString(msg).mb_str(), (const char *)wxString(fileName).mb_str(), lineNumber);
else
wxPrintf("ASSERTION FAILED!\n%s: %d\n", (const char *)wxString(fileName).mb_str(), lineNumber);
// Force core dump
int *i = 0;
if (*i)
exit(1);
exit(0);
}
#endif
#endif
namespace {
void PopulatePreferences()
{
bool resetPrefs = false;
wxString langCode = gPrefs->Read(wxT("/Locale/Language"), wxEmptyString);
bool writeLang = false;
const wxFileName fn(
FileNames::ResourcesDir(),
wxT("FirstTime.ini"));
if (fn.FileExists()) // it will exist if the (win) installer put it there
{
const wxString fullPath{fn.GetFullPath()};
auto pIni =
SneedacityFileConfig::Create({}, {}, fullPath, {},
wxCONFIG_USE_LOCAL_FILE);
auto &ini = *pIni;
wxString lang;
if (ini.Read(wxT("/FromInno/Language"), &lang) && !lang.empty())
{
// Only change "langCode" if the language was actually specified in the ini file.
langCode = lang;
writeLang = true;
// Inno Setup doesn't allow special characters in the Name values, so "0" is used
// to represent the "@" character.
langCode.Replace(wxT("0"), wxT("@"));
}
ini.Read(wxT("/FromInno/ResetPrefs"), &resetPrefs, false);
bool gone = wxRemoveFile(fullPath); // remove FirstTime.ini
if (!gone)
{
SneedacityMessageBox(
XO("Failed to remove %s").Format(fullPath),
XO("Failed!"));
}
}
// Use the system default language if one wasn't specified or if the user selected System.
if (langCode.empty())
langCode =
Languages::GetSystemLanguageCode(FileNames::SneedacityPathList());
langCode = GUIPrefs::SetLang( langCode );
// User requested that the preferences be completely reset
if (resetPrefs)
{
// pop up a dialogue
auto prompt = XO(
"Reset Preferences?\n\nThis is a one-time question, after an 'install' where you asked to have the Preferences reset.");
int action = SneedacityMessageBox(
prompt,
XO("Reset Sneedacity Preferences"),
wxYES_NO, NULL);
if (action == wxYES) // reset
{
gPrefs->DeleteAll();
writeLang = true;
}
}
// Save the specified language
if (writeLang)
{
gPrefs->Write(wxT("/Locale/Language"), langCode);
}
// In AUdacity 2.1.0 support for the legacy 1.2.x preferences (depreciated since Sneedacity
// 1.3.1) is dropped. As a result we can drop the import flag
// first time this version of Sneedacity is run we try to migrate
// old preferences.
bool newPrefsInitialized = false;
gPrefs->Read(wxT("/NewPrefsInitialized"), &newPrefsInitialized, false);
if (newPrefsInitialized) {
gPrefs->DeleteEntry(wxT("/NewPrefsInitialized"), true); // take group as well if empty
}
// record the Prefs version for future checking (this has not been used for a very
// long time).
gPrefs->Write(wxT("/PrefsVersion"), wxString(wxT(SNEEDACITY_PREFS_VERSION_STRING)));
// Check if some prefs updates need to happen based on sneedacity version.
// Unfortunately we can't use the PrefsVersion prefs key because that resets things.
// In the future we may want to integrate that better.
// these are done on a case-by-case basis for now so they must be backwards compatible
// (meaning the changes won't mess sneedacity up if the user goes back to an earlier version)
int vMajor = gPrefs->Read(wxT("/Version/Major"), (long) 0);
int vMinor = gPrefs->Read(wxT("/Version/Minor"), (long) 0);
int vMicro = gPrefs->Read(wxT("/Version/Micro"), (long) 0);
gPrefs->SetVersionKeysInit(vMajor, vMinor, vMicro); // make a note of these initial values
// for use by ToolManager::ReadConfig()
// These integer version keys were introduced april 4 2011 for 1.3.13
// The device toolbar needs to be enabled due to removal of source selection features in
// the mixer toolbar.
if ((vMajor < 1) ||
(vMajor == 1 && vMinor < 3) ||
(vMajor == 1 && vMinor == 3 && vMicro < 13)) {
// Do a full reset of the Device Toolbar to get it on the screen.
if (gPrefs->Exists(wxT("/GUI/ToolBars/Device")))
gPrefs->DeleteGroup(wxT("/GUI/ToolBars/Device"));
// We keep the mixer toolbar prefs (shown/not shown)
// the width of the mixer toolbar may have shrunk, the prefs will keep the larger value
// if the user had a device that had more than one source.
if (gPrefs->Exists(wxT("/GUI/ToolBars/Mixer"))) {
// Use the default width
gPrefs->Write(wxT("/GUI/ToolBars/Mixer/W"), -1);
}
}
// In 2.1.0, the Meter toolbar was split and lengthened, but strange arrangements happen
// if upgrading due to the extra length. So, if a user is upgrading, use the pre-2.1.0
// lengths, but still use the NEW split versions.
if (gPrefs->Exists(wxT("/GUI/ToolBars/Meter")) &&
!gPrefs->Exists(wxT("/GUI/ToolBars/CombinedMeter"))) {
// Read in all of the existing values
long dock, order, show, x, y, w, h;
gPrefs->Read(wxT("/GUI/ToolBars/Meter/Dock"), &dock, -1);
gPrefs->Read(wxT("/GUI/ToolBars/Meter/Order"), &order, -1);
gPrefs->Read(wxT("/GUI/ToolBars/Meter/Show"), &show, -1);
gPrefs->Read(wxT("/GUI/ToolBars/Meter/X"), &x, -1);
gPrefs->Read(wxT("/GUI/ToolBars/Meter/Y"), &y, -1);
gPrefs->Read(wxT("/GUI/ToolBars/Meter/W"), &w, -1);
gPrefs->Read(wxT("/GUI/ToolBars/Meter/H"), &h, -1);
// "Order" must be adjusted since we're inserting two NEW toolbars
if (dock > 0) {
wxString oldPath = gPrefs->GetPath();
gPrefs->SetPath(wxT("/GUI/ToolBars"));
wxString bar;
long ndx = 0;
bool cont = gPrefs->GetFirstGroup(bar, ndx);
while (cont) {
long o;
if (gPrefs->Read(bar + wxT("/Order"), &o) && o >= order) {
gPrefs->Write(bar + wxT("/Order"), o + 2);
}
cont = gPrefs->GetNextGroup(bar, ndx);
}
gPrefs->SetPath(oldPath);
// And override the height
h = 27;
}
// Write the split meter bar values
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/Dock"), dock);
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/Order"), order);
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/Show"), show);
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/X"), -1);
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/Y"), -1);
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/W"), w);
gPrefs->Write(wxT("/GUI/ToolBars/RecordMeter/H"), h);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/Dock"), dock);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/Order"), order + 1);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/Show"), show);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/X"), -1);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/Y"), -1);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/W"), w);
gPrefs->Write(wxT("/GUI/ToolBars/PlayMeter/H"), h);
// And hide the old combined meter bar
gPrefs->Write(wxT("/GUI/ToolBars/Meter/Dock"), -1);
}
// Upgrading pre 2.2.0 configs we assume extended set of defaults.
if ((0<vMajor && vMajor < 2) ||
(vMajor == 2 && vMinor < 2))
{
gPrefs->Write(wxT("/GUI/Shortcuts/FullDefaults"),1);
}
// Upgrading pre 2.4.0 configs, the selection toolbar is now split.
if ((0<vMajor && vMajor < 2) ||
(vMajor == 2 && vMinor < 4))
{
gPrefs->Write(wxT("/GUI/Toolbars/Selection/W"),"");
gPrefs->Write(wxT("/GUI/Toolbars/SpectralSelection/W"),"");
gPrefs->Write(wxT("/GUI/Toolbars/Time/X"),-1);
gPrefs->Write(wxT("/GUI/Toolbars/Time/Y"),-1);
gPrefs->Write(wxT("/GUI/Toolbars/Time/H"),55);
gPrefs->Write(wxT("/GUI/Toolbars/Time/W"),251);
gPrefs->Write(wxT("/GUI/Toolbars/Time/DockV2"),2);
gPrefs->Write(wxT("/GUI/Toolbars/Time/Dock"),2);
gPrefs->Write(wxT("/GUI/Toolbars/Time/Path"),"0,1");
gPrefs->Write(wxT("/GUI/Toolbars/Time/Show"),1);
}
// write out the version numbers to the prefs file for future checking
gPrefs->Write(wxT("/Version/Major"), SNEEDACITY_VERSION);
gPrefs->Write(wxT("/Version/Minor"), SNEEDACITY_RELEASE);
gPrefs->Write(wxT("/Version/Micro"), SNEEDACITY_REVISION);
gPrefs->Flush();
}
}
static bool gInited = false;
static bool gIsQuitting = false;
static void QuitSneedacity(bool bForce)
{
// guard against recursion
if (gIsQuitting)
return;
gIsQuitting = true;
wxTheApp->SetExitOnFrameDelete(true);
// Try to close each open window. If the user hits Cancel
// in a Save Changes dialog, don't continue.
// BG: unless force is true
// BG: Are there any projects open?
//- if (!AllProjects{}.empty())
/*start+*/
if (AllProjects{}.empty())
{
#ifdef __WXMAC__
Clipboard::Get().Clear();
#endif
}
else
/*end+*/
{
if (AllProjects{}.size())
// PRL: Always did at least once before close might be vetoed
// though I don't know why that is important
ProjectManager::SaveWindowSize();
bool closedAll = AllProjects::Close( bForce );
if ( !closedAll )
{
gIsQuitting = false;
return;
}
}
ModuleManager::Get().Dispatch(AppQuiting);
#ifdef EXPERIMENTAL_SCOREALIGN
CloseScoreAlignDialog();
#endif
CloseScreenshotTools();
//print out profile if we have one by deleting it
//temporarily commented out till it is added to all projects
//DELETE Profiler::Instance();
// Save last log for diagnosis
auto logger = SneedacityLogger::Get();
if (logger)
{
wxFileName logFile(FileNames::DataDir(), wxT("lastlog.txt"));
logger->SaveLog(logFile.GetFullPath());
}
//remove our logger
std::unique_ptr<wxLog>{ wxLog::SetActiveTarget(NULL) }; // DELETE
if (bForce)
{
wxExit();
}
}
static void QuitSneedacity()
{
QuitSneedacity(false);
}
#if defined(__WXGTK__) && defined(HAVE_GTK)
///////////////////////////////////////////////////////////////////////////////
// Provide the ability to receive notification from the session manager
// when the user is logging out or shutting down.
//
// Most of this was taken from nsNativeAppSupportUnix.cpp from Mozilla.
///////////////////////////////////////////////////////////////////////////////
// TODO: May need updating. Is this code too obsolete (relying on Gnome2 so's) to be
// worth keeping anymore?
// CB suggests we use libSM directly ref:
// http://www.x.org/archive/X11R7.7/doc/libSM/SMlib.html#The_Save_Yourself_Callback
#include <dlfcn.h>
/* There is a conflict between the type names used in Glib >= 2.21 and those in
* wxGTK (http://trac.wxwidgets.org/ticket/10883)
* Happily we can avoid the hack, as we only need some of the headers, not
* the full GTK headers
*/
#include <glib-object.h>
typedef struct _GnomeProgram GnomeProgram;
typedef struct _GnomeModuleInfo GnomeModuleInfo;
typedef struct _GnomeClient GnomeClient;
typedef enum
{
GNOME_SAVE_GLOBAL,
GNOME_SAVE_LOCAL,
GNOME_SAVE_BOTH
} GnomeSaveStyle;
typedef enum
{
GNOME_INTERACT_NONE,
GNOME_INTERACT_ERRORS,
GNOME_INTERACT_ANY
} GnomeInteractStyle;
typedef enum
{
GNOME_DIALOG_ERROR,
GNOME_DIALOG_NORMAL
} GnomeDialogType;
typedef GnomeProgram * (*_gnome_program_init_fn)(const char *,
const char *,
const GnomeModuleInfo *,
int,
char **,
const char *,
...);
typedef const GnomeModuleInfo * (*_libgnomeui_module_info_get_fn)();
typedef GnomeClient * (*_gnome_master_client_fn)(void);
typedef void (*GnomeInteractFunction)(GnomeClient *,
gint,
GnomeDialogType,
gpointer);
typedef void (*_gnome_client_request_interaction_fn)(GnomeClient *,
GnomeDialogType,
GnomeInteractFunction,
gpointer);
typedef void (*_gnome_interaction_key_return_fn)(gint, gboolean);
static _gnome_client_request_interaction_fn gnome_client_request_interaction;
static _gnome_interaction_key_return_fn gnome_interaction_key_return;
static void interact_cb(GnomeClient * /* client */,
gint key,
GnomeDialogType /* type */,
gpointer /* data */)
{
wxCloseEvent e(wxEVT_QUERY_END_SESSION, wxID_ANY);
e.SetEventObject(&wxGetApp());
e.SetCanVeto(true);
wxGetApp().ProcessEvent(e);
gnome_interaction_key_return(key, e.GetVeto());
}
static gboolean save_yourself_cb(GnomeClient *client,
gint /* phase */,
GnomeSaveStyle /* style */,
gboolean shutdown,
GnomeInteractStyle interact,
gboolean /* fast */,
gpointer /* user_data */)
{
if (!shutdown || interact != GNOME_INTERACT_ANY) {
return TRUE;
}
if (AllProjects{}.empty()) {
return TRUE;
}
gnome_client_request_interaction(client,
GNOME_DIALOG_NORMAL,
interact_cb,
NULL);
return TRUE;
}
class GnomeShutdown
{
public:
GnomeShutdown()
{
mArgv[0].reset(strdup("Sneedacity"));
mGnomeui = dlopen("libgnomeui-2.so.0", RTLD_NOW);
if (!mGnomeui) {
return;
}
mGnome = dlopen("libgnome-2.so.0", RTLD_NOW);
if (!mGnome) {
return;
}
_gnome_program_init_fn gnome_program_init = (_gnome_program_init_fn)
dlsym(mGnome, "gnome_program_init");
_libgnomeui_module_info_get_fn libgnomeui_module_info_get = (_libgnomeui_module_info_get_fn)
dlsym(mGnomeui, "libgnomeui_module_info_get");
_gnome_master_client_fn gnome_master_client = (_gnome_master_client_fn)
dlsym(mGnomeui, "gnome_master_client");
gnome_client_request_interaction = (_gnome_client_request_interaction_fn)
dlsym(mGnomeui, "gnome_client_request_interaction");
gnome_interaction_key_return = (_gnome_interaction_key_return_fn)
dlsym(mGnomeui, "gnome_interaction_key_return");
if (!gnome_program_init || !libgnomeui_module_info_get) {
return;
}
gnome_program_init(mArgv[0].get(),
"1.0",
libgnomeui_module_info_get(),
1,
reinterpret_cast<char**>(mArgv),
NULL);
mClient = gnome_master_client();
if (mClient == NULL) {
return;
}
g_signal_connect(mClient, "save-yourself", G_CALLBACK(save_yourself_cb), NULL);
}
virtual ~GnomeShutdown()
{
// Do not dlclose() the libraries here lest you want segfaults...
}
private:
MallocString<> mArgv[1];
void *mGnomeui;
void *mGnome;
GnomeClient *mClient;
};
// This variable exists to call the constructor and
// connect a signal for the 'save-yourself' message.
GnomeShutdown GnomeShutdownInstance;
#endif
// Where drag/drop or "Open With" filenames get stored until
// the timer routine gets around to picking them up.
static wxArrayString ofqueue;
//
// DDE support for opening multiple files with one instance
// of Sneedacity.
//
#define IPC_APPL wxT("sneedacity")
#define IPC_TOPIC wxT("System")
class IPCConn final : public wxConnection
{
public:
IPCConn()
: wxConnection()
{
};
~IPCConn()
{
};
bool OnExec(const wxString & WXUNUSED(topic),
const wxString & data)
{
// Add the filename to the queue. It will be opened by
// the OnTimer() event when it is safe to do so.
ofqueue.push_back(data);
return true;
}
};
class IPCServ final : public wxServer
{
public:
IPCServ(const wxString & appl)
: wxServer()
{
Create(appl);
};
~IPCServ()
{
};
wxConnectionBase *OnAcceptConnection(const wxString & topic) override
{
if (topic != IPC_TOPIC) {
return NULL;
}
// Trust wxWidgets framework to DELETE it
return safenew IPCConn();
};
};
#if defined(__WXMAC__)
IMPLEMENT_APP_NO_MAIN(SneedacityApp)
IMPLEMENT_WX_THEME_SUPPORT
int main(int argc, char *argv[])
{
wxDISABLE_DEBUG_SUPPORT();
return wxEntry(argc, argv);
}
#elif defined(__WXGTK__) && defined(NDEBUG)
IMPLEMENT_APP_NO_MAIN(SneedacityApp)
IMPLEMENT_WX_THEME_SUPPORT
int main(int argc, char *argv[])
{
wxDISABLE_DEBUG_SUPPORT();
// Bug #1986 workaround - This doesn't actually reduce the number of
// messages, it simply hides them in Release builds. We'll probably
// never be able to get rid of the messages entirely, but we should
// look into what's causing them, so allow them to show in Debug
// builds.
stdout = freopen("/dev/null", "w", stdout);
stderr = freopen("/dev/null", "w", stderr);
return wxEntry(argc, argv);
}
#else
IMPLEMENT_APP(SneedacityApp)
#endif
#ifdef __WXMAC__
// in response of an open-document apple event
void SneedacityApp::MacOpenFile(const wxString &fileName)
{
ofqueue.push_back(fileName);
}
// in response of a print-document apple event
void SneedacityApp::MacPrintFile(const wxString &fileName)
{
ofqueue.push_back(fileName);
}
// in response of a open-application apple event
void SneedacityApp::MacNewFile()
{
if (!gInited)
return;
// This method should only be used on the Mac platform
// when no project windows are open.
if (AllProjects{}.empty())
(void) ProjectManager::New();
}
#endif //__WXMAC__
// IPC communication
#define ID_IPC_SERVER 6200
#define ID_IPC_SOCKET 6201
// we don't really care about the timer id, but set this value just in case we do in the future
#define kSneedacityAppTimerID 0
BEGIN_EVENT_TABLE(SneedacityApp, wxApp)
EVT_QUERY_END_SESSION(SneedacityApp::OnQueryEndSession)
EVT_END_SESSION(SneedacityApp::OnEndSession)
EVT_TIMER(kSneedacityAppTimerID, SneedacityApp::OnTimer)
#ifdef __WXMAC__
EVT_MENU(wxID_NEW, SneedacityApp::OnMenuNew)
EVT_MENU(wxID_OPEN, SneedacityApp::OnMenuOpen)
EVT_MENU(wxID_ABOUT, SneedacityApp::OnMenuAbout)
EVT_MENU(wxID_PREFERENCES, SneedacityApp::OnMenuPreferences)
#endif
// Associate the handler with the menu id on all operating systems, even
// if they don't have an application menu bar like in macOS, so that
// other parts of the program can send the application a shut-down
// event
EVT_MENU(wxID_EXIT, SneedacityApp::OnMenuExit)
#ifndef __WXMSW__
EVT_SOCKET(ID_IPC_SERVER, SneedacityApp::OnServerEvent)
EVT_SOCKET(ID_IPC_SOCKET, SneedacityApp::OnSocketEvent)
#endif
// Recent file event handlers.
EVT_MENU(FileHistory::ID_RECENT_CLEAR, SneedacityApp::OnMRUClear)
EVT_MENU_RANGE(FileHistory::ID_RECENT_FIRST, FileHistory::ID_RECENT_LAST,
SneedacityApp::OnMRUFile)
// Handle AppCommandEvents (usually from a script)
EVT_APP_COMMAND(wxID_ANY, SneedacityApp::OnReceiveCommand)
// Global ESC key handling
EVT_KEY_DOWN(SneedacityApp::OnKeyDown)
END_EVENT_TABLE()
// backend for OnMRUFile
// TODO: Would be nice to make this handle not opening a file with more panache.
// - Inform the user if DefaultOpenPath not set.
// - Switch focus to correct instance of project window, if already open.
bool SneedacityApp::MRUOpen(const FilePath &fullPathStr) {
// Most of the checks below are copied from ProjectManager::OpenFiles.
// - some rationalisation might be possible.
SneedacityProject *proj = GetActiveProject();
if (!fullPathStr.empty())
{
// verify that the file exists
if (wxFile::Exists(fullPathStr))
{
FileNames::UpdateDefaultPath(FileNames::Operation::Open, ::wxPathOnly(fullPathStr));
// Make sure it isn't already open.
// Test here even though SneedacityProject::OpenFile() also now checks, because
// that method does not return the bad result.
// That itself may be a FIXME.
if (ProjectFileManager::IsAlreadyOpen(fullPathStr))
return false;
( void ) ProjectManager::OpenProject( proj, fullPathStr,
true /* addtohistory */, false /* reuseNonemptyProject */ );
}
else {
// File doesn't exist - remove file from history
SneedacityMessageBox(
XO(
"%s could not be found.\n\nIt has been removed from the list of recent files.")
.Format(fullPathStr) );
return(false);
}
}
return(true);
}
bool SneedacityApp::SafeMRUOpen(const wxString &fullPathStr)
{
return GuardedCall< bool >( [&]{ return MRUOpen( fullPathStr ); } );
}
void SneedacityApp::OnMRUClear(wxCommandEvent& WXUNUSED(event))
{
FileHistory::Global().Clear();
}
//vvv Basically, anything from Recent Files is treated as a .aup3, until proven otherwise,
// then it tries to Import(). Very questionable handling, imo.
// Better, for example, to check the file type early on.
void SneedacityApp::OnMRUFile(wxCommandEvent& event) {
int n = event.GetId() - FileHistory::ID_RECENT_FIRST;
auto &history = FileHistory::Global();
const auto &fullPathStr = history[ n ];
// Try to open only if not already open.
// Test IsAlreadyOpen() here even though SneedacityProject::MRUOpen() also now checks,
// because we don't want to Remove() just because it already exists,
// and SneedacityApp::OnMacOpenFile() calls MRUOpen() directly.
// that method does not return the bad result.
// PRL: Don't call SafeMRUOpen
// -- if open fails for some exceptional reason of resource exhaustion that
// the user can correct, leave the file in history.
if (!ProjectFileManager::IsAlreadyOpen(fullPathStr) && !MRUOpen(fullPathStr))
history.Remove(n);
}
void SneedacityApp::OnTimer(wxTimerEvent& WXUNUSED(event))
{
// Filenames are queued when Sneedacity receives a few of the
// AppleEvent messages (via wxWidgets). So, open any that are
// in the queue and clean the queue.
if (gInited) {
if (ofqueue.size()) {
// Load each file on the queue
while (ofqueue.size()) {
wxString name;
name.swap(ofqueue[0]);
ofqueue.erase( ofqueue.begin() );
// Get the user's attention if no file name was specified
if (name.empty()) {
// Get the users attention
SneedacityProject *project = GetActiveProject();
if (project) {
auto &window = GetProjectFrame( *project );
window.Maximize();
window.Raise();
window.RequestUserAttention();
}
continue;
}
// TODO: Handle failures better.
// Some failures are OK, e.g. file not found, just would-be-nices to do better,
// so FAIL_MSG is more a case of an enhancement request than an actual problem.
// LL: In all but one case an appropriate message is already displayed. The
// instance that a message is NOT displayed is when a failure to write
// to the config file has occurred.
// PRL: Catch any exceptions, don't try this file again, continue to
// other files.
if (!SafeMRUOpen(name)) {
// Just log it. Assertion failure is not appropriate on valid
// defensive path against bad file data.
wxLogMessage(wxT("MRUOpen failed"));
}
}
}
}
}
#if defined(__WXMSW__)
#define WL(lang, sublang) (lang), (sublang),
#else
#define WL(lang,sublang)
#endif
#if wxCHECK_VERSION(3, 0, 1)
wxLanguageInfo userLangs[] =
{
// Bosnian is defined in wxWidgets already
// { wxLANGUAGE_USER_DEFINED, wxT("bs"), WL(0, SUBLANG_DEFAULT) wxT("Bosnian"), wxLayout_LeftToRight },
{ wxLANGUAGE_USER_DEFINED, wxT("eu"), WL(0, SUBLANG_DEFAULT) wxT("Basque"), wxLayout_LeftToRight },
};
#endif
void SneedacityApp::OnFatalException()
{
#if defined(HAS_CRASH_REPORT)
CrashReport::Generate(wxDebugReport::Context_Exception);
#endif
exit(-1);
}
#ifdef _MSC_VER
// If this is compiled with MSVC (Visual Studio)
#pragma warning( push )
#pragma warning( disable : 4702) // unreachable code warning.
#endif //_MSC_VER
bool SneedacityApp::OnExceptionInMainLoop()
{
// This function is invoked from catch blocks in the wxWidgets framework,
// and throw; without argument re-throws the exception being handled,
// letting us dispatch according to its type.
try { throw; }
catch ( SneedacityException &e ) {
(void)e;// Compiler food
// Here is the catch-all for our own exceptions
// Use CallAfter to delay this to the next pass of the event loop,
// rather than risk doing it inside stack unwinding.
auto pProject = ::GetActiveProject();
auto pException = std::current_exception();
CallAfter( [=] // Capture pException by value!
{
// Restore the state of the project to what it was before the
// failed operation
if (pProject) {
ProjectHistory::Get( *pProject ).RollbackState();
// Forget pending changes in the TrackList
TrackList::Get( *pProject ).ClearPendingTracks();
ProjectWindow::Get( *pProject ).RedrawProject();
}
// Give the user an alert
try { std::rethrow_exception( pException ); }
catch( SneedacityException &e )
{ e.DelayedHandlerAction(); }
} );
// Don't quit the program
return true;
}
catch ( ... ) {
// There was some other type of exception we don't know.
// Let the inherited function do throw; again and whatever else it does.
return wxApp::OnExceptionInMainLoop();
}
// Shouldn't ever reach this line
return false;
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif //_MSC_VER
SneedacityApp::SneedacityApp()
{
#if !defined(_DEBUG)
#if defined(HAS_CRASH_REPORT)
#if defined(wxUSE_ON_FATAL_EXCEPTION) && wxUSE_ON_FATAL_EXCEPTION
wxHandleFatalExceptions();
#endif
#endif
#endif