panel.cpp 72.1 KB
Newer Older
1
#include <cmath>
2
#include <wx/dcbuffer.h>
Rafael Kitover's avatar
Rafael Kitover committed
3
#include <SDL_joystick.h>
4

Rafael Kitover's avatar
Rafael Kitover committed
5
#include "version.h"
6
#include "../common/ConfigManager.h"
7
8
#include "../common/Patch.h"
#include "../gb/gbPrinter.h"
9
10
11
#include "../gba/RTC.h"
#include "../gba/agbprint.h"
#include "../sdl/text.h"
12
#include "drawing.h"
13
#include "filters.h"
14
#include "wxvbam.h"
15
16
17
18
19
20

int emulating;

IMPLEMENT_DYNAMIC_CLASS(GameArea, wxPanel)

GameArea::GameArea()
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    : wxPanel()
    , loaded(IMAGE_UNKNOWN)
    , panel(NULL)
    , emusys(NULL)
    , basic_width(GBAWidth)
    , basic_height(GBAHeight)
    , fullscreen(false)
    , paused(false)
    , was_paused(false)
    , rewind_time(0)
    , do_rewind(false)
    , rewind_mem(0)
    , pointer_blanked(false)
    , mouse_active_time(0)
35
{
36
37
38
39
40
41
    SetSizer(new wxBoxSizer(wxVERTICAL));
    // all renderers prefer 32-bit
    // well, "simple" prefers 24-bit, but that's not available for filters
    systemColorDepth = 32;
    hq2x_init(32);
    Init_2xSaI(32);
42
43
}

44
void GameArea::LoadGame(const wxString& name)
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
    rom_scene_rls = wxT("-");
    rom_scene_rls_name = wxT("-");
    rom_name = wxT("");
    // fex just crashes if file does not exist and it's compressed,
    // so check first
    wxFileName fnfn(name);
    bool badfile = !fnfn.IsFileReadable();

    // if path was relative, look for it before giving up
    if (badfile && !fnfn.IsAbsolute()) {
        wxString rp = fnfn.GetPath();

        // can't really decide which dir to use, so try GBA first, then GB
        if (!wxGetApp().GetAbsolutePath(gopts.gba_rom_dir).empty()) {
            fnfn.SetPath(wxGetApp().GetAbsolutePath(gopts.gba_rom_dir) + wxT('/') + rp);
            badfile = !fnfn.IsFileReadable();
        }

        if (badfile && !wxGetApp().GetAbsolutePath(gopts.gb_rom_dir).empty()) {
            fnfn.SetPath(wxGetApp().GetAbsolutePath(gopts.gb_rom_dir) + wxT('/') + rp);
            badfile = !fnfn.IsFileReadable();
        }

        if (badfile && !wxGetApp().GetAbsolutePath(gopts.gbc_rom_dir).empty()) {
            fnfn.SetPath(wxGetApp().GetAbsolutePath(gopts.gbc_rom_dir) + wxT('/') + rp);
            badfile = !fnfn.IsFileReadable();
        }
    }

    // auto-conversion of wxCharBuffer to const char * seems broken
    // so save underlying wxCharBuffer (or create one of none is used)
    wxCharBuffer fnb(fnfn.GetFullPath().mb_fn_str());
    const char* fn = fnb.data();
    IMAGE_TYPE t = badfile ? IMAGE_UNKNOWN : utilFindType(fn);

    if (t == IMAGE_UNKNOWN) {
        wxString s;
        s.Printf(_("%s is not a valid ROM file"), name.c_str());
        wxMessageDialog dlg(GetParent(), s, _("Problem loading file"), wxOK | wxICON_ERROR);
        dlg.ShowModal();
        return;
    }

    {
        wxFileConfig* cfg = wxGetApp().cfg;

        if (!gopts.recent_freeze) {
            gopts.recent->AddFileToHistory(name);
            wxGetApp().frame->SetRecentAccels();
            cfg->SetPath(wxT("/Recent"));
            gopts.recent->Save(*cfg);
            cfg->SetPath(wxT("/"));
            cfg->Flush();
        }
    }

    UnloadGame();
    // strip extension from actual game file name
    // FIXME: save actual file name of archive so patches & cheats can
    // be loaded from archive
    // FIXME: if archive name does not match game name, prepend archive
    // name to uniquify game name
    loaded_game = fnfn;
    loaded_game.ClearExt();
    loaded_game.MakeAbsolute();
    // load patch, if enabled
    // note that it is difficult to load from archive due to
    // ../common/Patch.cpp depending on opening the file itself and doing
    // lots of seeking & such.  The only way would be to copy the patch
    // out to a temporary file and load it (and can't just use
    // AssignTempFileName because it needs correct extension)
    // too much trouble for now, though
    bool loadpatch = autoPatch;
    wxFileName pfn = loaded_game;
    int ovSaveType = 0;

    if (loadpatch) {
        // SetExt may strip something off by accident, so append to text instead
        // pfn.SetExt(wxT("ips")
        pfn.SetFullName(pfn.GetFullName() + wxT(".ips"));

        if (!pfn.IsFileReadable()) {
            pfn.SetExt(wxT("ups"));

            if (!pfn.IsFileReadable()) {
                pfn.SetExt(wxT("ppf"));
                loadpatch = pfn.IsFileReadable();
            }
        }
    }

    if (t == IMAGE_GB) {
        if (!gbLoadRom(fn)) {
            wxString s;
            s.Printf(_("Unable to load Game Boy ROM %s"), name.c_str());
            wxMessageDialog dlg(GetParent(), s, _("Problem loading file"), wxOK | wxICON_ERROR);
            dlg.ShowModal();
            return;
        }

        rom_size = gbRomSize;

        if (loadpatch) {
            int size = rom_size;
            // auto-conversion of wxCharBuffer to const char * seems broken
            // so save underlying wxCharBuffer (or create one of none is used)
            wxCharBuffer pfnb(pfn.GetFullPath().mb_fn_str());
            applyPatch(pfnb.data(), &gbRom, &size);

            if (size != rom_size)
                gbUpdateSizes();

            rom_size = size;
        }

        // start sound; this must happen before CPU stuff
        gb_effects_config.echo = (float)gopts.gb_echo / 100.0;
        gb_effects_config.stereo = (float)gopts.gb_stereo / 100.0;
        gbSoundSetDeclicking(gopts.gb_declick);
        soundInit();
        soundSetEnable(gopts.sound_en);
        gbSoundSetSampleRate(!gopts.sound_qual ? 48000 : 44100 / (1 << (gopts.sound_qual - 1)));
        soundSetVolume((float)gopts.sound_vol / 100.0);
169
170
        // this **MUST** be called **AFTER** setting sample rate because the core calls soundInit()
        soundSetThrottle(throttle);
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
        gbGetHardwareType();
        bool use_bios = false;
        // auto-conversion of wxCharBuffer to const char * seems broken
        // so save underlying wxCharBuffer (or create one of none is used)
        const char* fn = NULL;
        wxCharBuffer fnb;

        if (gbCgbMode) {
            use_bios = useBiosFileGBC;
            fnb = gopts.gbc_bios.mb_fn_str();
        } else {
            use_bios = useBiosFileGB;
            fnb = gopts.gb_bios.mb_fn_str();
        }

        fn = fnb.data();
        gbCPUInit(fn, use_bios);

        if (use_bios && !useBios) {
            wxLogError(_("Could not load BIOS %s"), (gbCgbMode ? gopts.gbc_bios : gopts.gb_bios).c_str());
            // could clear use flag & file name now, but better to force
            // user to do it
        }

        gbReset();

        if (gbBorderOn) {
            basic_width = gbBorderLineSkip = SGBWidth;
            basic_height = SGBHeight;
            gbBorderColumnSkip = (SGBWidth - GBWidth) / 2;
            gbBorderRowSkip = (SGBHeight - GBHeight) / 2;
        } else {
            basic_width = gbBorderLineSkip = GBWidth;
            basic_height = GBHeight;
            gbBorderColumnSkip = gbBorderRowSkip = 0;
        }

        emusys = &GBSystem;
    } else /* if(t == IMAGE_GBA) */
    {
        if (!(rom_size = CPULoadRom(fn))) {
            wxString s;
            s.Printf(_("Unable to load Game Boy Advance ROM %s"), name.c_str());
            wxMessageDialog dlg(GetParent(), s, _("Problem loading file"), wxOK | wxICON_ERROR);
            dlg.ShowModal();
            return;
        }

        rom_crc32 = crc32(0L, rom, rom_size);

        if (loadpatch) {
            // don't use real rom size or it might try to resize rom[]
            // instead, use known size of rom[]
            int size = 0x2000000;
            // auto-conversion of wxCharBuffer to const char * seems broken
            // so save underlying wxCharBuffer (or create one of none is used)
            wxCharBuffer pfnb(pfn.GetFullPath().mb_fn_str());
            applyPatch(pfnb.data(), &rom, &size);
            // that means we no longer really know rom_size either <sigh>
        }

        wxFileConfig* cfg = wxGetApp().overrides;
        wxString id = wxString((const char*)&rom[0xac], wxConvLibc, 4);

        if (cfg->HasGroup(id)) {
            cfg->SetPath(id);
            rtcEnable(cfg->Read(wxT("rtcEnabled"), rtcEnabled));
            int fsz = cfg->Read(wxT("flashSize"), (long)0);

            if (fsz != 0x10000 && fsz != 0x20000)
                fsz = 0x10000 << winFlashSize;

            flashSetSize(fsz);
            ovSaveType = cfg->Read(wxT("saveType"), cpuSaveType);

            if (ovSaveType < 0 || ovSaveType > 5)
                ovSaveType = 0;

            if (ovSaveType == 0)
                utilGBAFindSave(rom_size);
            else
                saveType = ovSaveType;

            mirroringEnable = cfg->Read(wxT("mirroringEnabled"), (long)1);
            cfg->SetPath(wxT("/"));
        } else {
            rtcEnable(rtcEnabled);
            flashSetSize(0x10000 << winFlashSize);

            if (cpuSaveType < 0 || cpuSaveType > 5)
                cpuSaveType = 0;

            if (cpuSaveType == 0)
                utilGBAFindSave(rom_size);
            else
                saveType = cpuSaveType;

            mirroringEnable = true;
        }

        doMirroring(mirroringEnable);
        // start sound; this must happen before CPU stuff
        gb_effects_config.echo = (float)gopts.gb_echo / 100.0;
        gb_effects_config.stereo = (float)gopts.gb_stereo / 100.0;
        gbSoundSetDeclicking(gopts.gb_declick);
        soundInit();
        soundSetEnable(gopts.sound_en);
        gbSoundSetSampleRate(!gopts.sound_qual ? 48000 : 44100 / (1 << (gopts.sound_qual - 1)));
        soundSetSampleRate(!gopts.sound_qual ? 48000 : 44100 / (1 << (gopts.sound_qual - 1)));
        soundSetVolume((float)gopts.sound_vol / 100.0);
281
282
        // this **MUST** be called **AFTER** setting sample rate because the core calls soundInit()
        soundSetThrottle(throttle);
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
        soundFiltering = (float)gopts.gba_sound_filter / 100.0f;
        CPUInit(gopts.gba_bios.mb_fn_str(), useBiosFileGBA);

        if (useBiosFileGBA && !useBios) {
            wxLogError(_("Could not load BIOS %s"), gopts.gba_bios.c_str());
            // could clear use flag & file name now, but better to force
            // user to do it
        }

        CPUReset();
        basic_width = GBAWidth;
        basic_height = GBAHeight;
        emusys = &GBASystem;
    }

    if (fullScreen)
        GameArea::ShowFullScreen(true);

    loaded = t;
    SetFrameTitle();
    SetFocus();
    AdjustSize(true);
    emulating = true;
    was_paused = true;
    MainFrame* mf = wxGetApp().frame;
    mf->SetJoystick();
    mf->cmd_enable &= ~(CMDEN_GB | CMDEN_GBA);
    mf->cmd_enable |= ONLOAD_CMDEN;
    mf->cmd_enable |= loaded == IMAGE_GB ? CMDEN_GB : (CMDEN_GBA | CMDEN_NGDB_GBA);
    mf->enable_menus();
313
#if (defined __WIN32__ || defined _WIN32)
Zach Bacon's avatar
Zach Bacon committed
314
#ifndef NO_LINK
315
    gbSerialFunction = gbStartLink;
316
#else
317
    gbSerialFunction = NULL;
Zach Bacon's avatar
Zach Bacon committed
318
#endif
319
#endif
320

321
322
323
    // probably only need to do this for GB carts
    if (winGbPrinterEnabled)
        gbSerialFunction = gbPrinterSend;
324

325
326
327
328
    // probably only need to do this for GBA carts
    agbPrintEnable(agbPrint);
    // set frame skip based on ROM type
    systemFrameSkip = frameSkip;
329

330
331
    if (systemFrameSkip < 0)
        systemFrameSkip = 0;
332

333
334
335
336
    // load battery and/or saved state
    recompute_dirs();
    mf->update_state_ts(true);
    bool did_autoload = gopts.autoload_state ? LoadState() : false;
337

338
339
    if (!did_autoload || skipSaveGameBattery) {
        wxString bname = loaded_game.GetFullName();
340
#ifndef NO_LINK
341
342
        // MakeInstanceFilename doesn't do wxString, so just add slave ID here
        int playerId = GetLinkPlayerId();
343

344
345
346
347
        if (playerId >= 0) {
            bname.append(wxT('-'));
            bname.append(wxChar(wxT('1') + playerId));
        }
348

349
#endif
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
        bname.append(wxT(".sav"));
        wxFileName bat(batdir, bname);
        fnb = bat.GetFullPath().mb_fn_str();

        if (emusys->emuReadBattery(fnb.data())) {
            wxString msg;
            msg.Printf(_("Loaded battery %s"), bat.GetFullPath().c_str());
            systemScreenMessage(msg);

            if (cpuSaveType == 0 && ovSaveType == 0 && t == IMAGE_GBA) {
                switch (bat.GetSize().GetValue()) {
                case 0x200:
                case 0x2000:
                    saveType = 1;
                    break;

                case 0x8000:
                    saveType = 2;
                    break;

                case 0x10000:
                    if (saveType == 1 || saveType == 2)
                        break;

                case 0x20000:
                    saveType = 3;
                    flashSetSize(bat.GetSize().GetValue());
                    break;

                default:
                    break;
                }

                SetSaveType(saveType);
            }
        }

        // forget old save writes
        systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
    }

    // do an immediate rewind save
    // even if loaded from state file: not smart enough yet to just
    // do a reset or load from state file when # rewinds == 0
    do_rewind = gopts.rewind_interval > 0;
    // FIXME: backup battery file (useful if game name conflict)
    cheats_dirty = (did_autoload && !skipSaveGameCheats) || (loaded == IMAGE_GB ? gbCheatNumber > 0 : cheatsNumber > 0);

    if (gopts.autoload_cheats && (!did_autoload || skipSaveGameCheats)) {
        wxFileName cfn = loaded_game;
        // SetExt may strip something off by accident, so append to text instead
        cfn.SetFullName(cfn.GetFullName() + wxT(".clt"));

        if (cfn.IsFileReadable()) {
            bool cld;

            if (loaded == IMAGE_GB)
                cld = gbCheatsLoadCheatList(cfn.GetFullPath().mb_fn_str());
            else
                cld = cheatsLoadCheatList(cfn.GetFullPath().mb_fn_str());

            if (cld) {
                systemScreenMessage(_("Loaded cheats"));
                cheats_dirty = false;
            }
        }
    }
417
418

#ifndef NO_LINK
419

420
421
422
423
    if (gopts.link_auto) {
        linkMode = mf->GetConfiguredLinkMode();
        BootLink(linkMode, gopts.link_host.mb_str(wxConvUTF8), linkTimeout, linkHacks, linkNumPlayers);
    }
424

425
#endif
426
427
428
429
}

void GameArea::SetFrameTitle()
{
430
    wxString tit = wxT("");
431

432
433
434
435
    if (loaded != IMAGE_UNKNOWN) {
        tit.append(loaded_game.GetFullName());
        tit.append(wxT(" - "));
    }
436

437
    tit.append(wxT("VisualBoyAdvance-M "));
438
#ifndef FINAL_BUILD
439
    tit.append(_(VERSION));
440
#endif
441
#ifndef NO_LINK
442
    int playerId = GetLinkPlayerId();
443

444
445
446
447
    if (playerId >= 0) {
        tit.append(_(" player "));
        tit.append(wxChar(wxT('1') + playerId));
    }
448

449
#endif
450
    wxGetApp().frame->SetTitle(tit);
451
452
453
454
}

void GameArea::recompute_dirs()
{
455
    batdir = gopts.battery_dir;
456

457
458
459
460
461
    if (!batdir.size()) {
        batdir = loaded_game.GetPathWithSep();
    } else {
        batdir = wxGetApp().GetAbsolutePath(gopts.battery_dir);
    }
462

463
    statedir = gopts.state_dir;
464

465
466
467
468
469
    if (!statedir.size()) {
        statedir = loaded_game.GetPathWithSep();
    } else {
        statedir = wxGetApp().GetAbsolutePath(gopts.state_dir);
    }
470

471
472
    if (!wxIsWritable(batdir))
        batdir = wxGetApp().GetConfigurationPath();
473

474
475
    if (!wxIsWritable(statedir))
        statedir = wxGetApp().GetConfigurationPath();
476
477
478
479
}

void GameArea::UnloadGame(bool destruct)
{
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
    if (!emulating)
        return;

    // last opportunity to autosave cheats
    if (gopts.autoload_cheats && cheats_dirty) {
        wxFileName cfn = loaded_game;
        // SetExt may strip something off by accident, so append to text instead
        cfn.SetFullName(cfn.GetFullName() + wxT(".clt"));

        if (loaded == IMAGE_GB) {
            if (!gbCheatNumber)
                wxRemoveFile(cfn.GetFullPath());
            else
                gbCheatsSaveCheatList(cfn.GetFullPath().mb_fn_str());
        } else {
            if (!cheatsNumber)
                wxRemoveFile(cfn.GetFullPath());
            else
                cheatsSaveCheatList(cfn.GetFullPath().mb_fn_str());
        }
    }

    // if timer was counting down for save, go ahead and save
    // this might not be safe, though..
    if (systemSaveUpdateCounter > SYSTEM_SAVE_NOT_UPDATED) {
        SaveBattery(destruct);
    }

    MainFrame* mf = wxGetApp().frame;
509
#ifndef NO_FFMPEG
510
511
    snd_rec.Stop();
    vid_rec.Stop();
512
#endif
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
    systemStopGameRecording();
    systemStopGamePlayback();
    debugger = false;
    remoteCleanUp();
    mf->cmd_enable |= CMDEN_NGDB_ANY;

    if (loaded == IMAGE_GB) {
        gbCleanUp();
        gbCheatRemoveAll();
    } else if (loaded == IMAGE_GBA) {
        CPUCleanUp();
        cheatsDeleteAll(false);
    }

    emulating = false;
    loaded = IMAGE_UNKNOWN;
    emusys = NULL;
    soundShutdown();

    if (destruct)
        return;

    // in destructor, panel should be auto-deleted by wx since all panels
    // are derived from a window attached as child to GameArea
    if (panel)
538
        panel->Destroy();
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556

    panel = NULL;

    // close any game-related viewer windows
    // in destructor, viewer windows are in process of being deleted anyway
    while (!mf->popups.empty())
        mf->popups.front()->Close(true);

    // remaining items are GUI updates that should not be needed in destructor
    SetFrameTitle();
    mf->cmd_enable &= UNLOAD_CMDEN_KEEP;
    mf->update_state_ts(true);
    mf->enable_menus();
    mf->SetJoystick();
    mf->ResetCheatSearch();

    if (rewind_mem)
        num_rewind_states = 0;
557
558
559
560
}

bool GameArea::LoadState()
{
561
    int slot = wxGetApp().frame->newest_state_slot();
562

563
564
    if (slot < 1)
        return false;
565

566
    return LoadState(slot);
567
568
569
570
}

bool GameArea::LoadState(int slot)
{
571
572
573
    wxString fname;
    fname.Printf(SAVESLOT_FMT, game_name().c_str(), slot);
    return LoadState(wxFileName(statedir, fname));
574
575
}

576
bool GameArea::LoadState(const wxFileName& fname)
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
    // FIXME: first save to backup state if not backup state
    bool ret = emusys->emuReadState(fname.GetFullPath().mb_fn_str());

    if (ret && num_rewind_states) {
        MainFrame* mf = wxGetApp().frame;
        mf->cmd_enable &= ~CMDEN_REWIND;
        mf->enable_menus();
        num_rewind_states = 0;
        // do an immediate rewind save
        // even if loaded from state file: not smart enough yet to just
        // do a reset or load from state file when # rewinds == 0
        do_rewind = true;
        rewind_time = gopts.rewind_interval * 6;
    }

    if (ret) {
        // forget old save writes
        systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
        // no point in blending after abrupt change
        InterframeCleanup();
        // frame rate calc should probably reset as well
        was_paused = true;
        // save state had a screen frame, so draw it
        systemDrawScreen();
    }

    wxString msg;
    msg.Printf(ret ? _("Loaded state %s") : _("Error loading state %s"),
        fname.GetFullPath().c_str());
    systemScreenMessage(msg);
    return ret;
609
610
611
612
}

bool GameArea::SaveState()
{
613
    return SaveState(wxGetApp().frame->oldest_state_slot());
614
615
616
617
}

bool GameArea::SaveState(int slot)
{
618
619
620
    wxString fname;
    fname.Printf(SAVESLOT_FMT, game_name().c_str(), slot);
    return SaveState(wxFileName(statedir, fname));
621
622
}

623
bool GameArea::SaveState(const wxFileName& fname)
624
{
625
626
627
628
629
630
631
632
    // FIXME: first copy to backup state if not backup state
    bool ret = emusys->emuWriteState(fname.GetFullPath().mb_fn_str());
    wxGetApp().frame->update_state_ts(true);
    wxString msg;
    msg.Printf(ret ? _("Saved state %s") : _("Error saving state %s"),
        fname.GetFullPath().c_str());
    systemScreenMessage(msg);
    return ret;
633
634
635
636
}

void GameArea::SaveBattery(bool quiet)
{
637
638
    // MakeInstanceFilename doesn't do wxString, so just add slave ID here
    wxString bname = game_name();
639
#ifndef NO_LINK
640
    int playerId = GetLinkPlayerId();
641

642
643
644
645
    if (playerId >= 0) {
        bname.append(wxT('-'));
        bname.append(wxChar(wxT('1') + playerId));
    }
646

647
#endif
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    bname.append(wxT(".sav"));
    wxFileName bat(batdir, bname);
    bat.Mkdir(0777, wxPATH_MKDIR_FULL);
    wxString fn = bat.GetFullPath();
    // auto-conversion of wxCharBuffer to const char * seems broken
    // so save underlying wxCharBuffer (or create one of none is used)
    wxCharBuffer fnb = fn.mb_fn_str();
    wxString msg;

    // FIXME: add option to support ring of backups
    // of course some games just write battery way too often for such
    // a thing to be useful
    if (emusys->emuWriteBattery(fnb.data()))
        msg.Printf(_("Wrote battery %s"), fn.c_str());
    else
        msg.Printf(_("Error writing battery %s"), fn.c_str());

    systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;

    if (!quiet)
        systemScreenMessage(msg);
669
670
671
672
}

void GameArea::AddBorder()
{
673
674
675
676
677
678
679
680
681
682
683
684
685
    if (basic_width != GBWidth)
        return;

    basic_width = SGBWidth;
    basic_height = SGBHeight;
    gbBorderLineSkip = SGBWidth;
    gbBorderColumnSkip = (SGBWidth - GBWidth) / 2;
    gbBorderRowSkip = (SGBHeight - GBHeight) / 2;
    AdjustSize(false);
    wxGetApp().frame->Fit();
    GetSizer()->Detach(panel->GetWindow());

    if (panel)
686
        panel->Destroy();
687
688

    panel = NULL;
689
690
691
692
}

void GameArea::DelBorder()
{
693
694
    if (basic_width != SGBWidth)
        return;
695

696
697
698
699
700
701
702
    basic_width = GBWidth;
    basic_height = GBHeight;
    gbBorderLineSkip = GBWidth;
    gbBorderColumnSkip = gbBorderRowSkip = 0;
    AdjustSize(false);
    wxGetApp().frame->Fit();
    GetSizer()->Detach(panel->GetWindow());
703

704
    if (panel)
705
        panel->Destroy();
706

707
    panel = NULL;
708
709
710
711
}

void GameArea::AdjustMinSize()
{
712
713
714
    wxWindow* frame           = wxGetApp().frame;
    double hidpi_scale_factor = HiDPIScaleFactor();

715
716
    // note: could safely set min size to 1x or less regardless of video_scale
    // but setting it to scaled size makes resizing to default easier
717
718
    wxSize sz((std::ceil(basic_width  * gopts.video_scale) / hidpi_scale_factor),
              (std::ceil(basic_height * gopts.video_scale) / hidpi_scale_factor));
719
720
721
    SetMinSize(sz);
#if wxCHECK_VERSION(2, 8, 8)
    sz = frame->ClientToWindowSize(sz);
722
#else
723
    sz += frame->GetSize() - frame->GetClientSize();
724
#endif
725
    frame->SetMinSize(sz);
726
727
728
729
}

void GameArea::LowerMinSize()
{
730
731
732
733
734
735
    wxWindow* frame           = wxGetApp().frame;
    double hidpi_scale_factor = HiDPIScaleFactor();

    wxSize sz(std::ceil(basic_width  / hidpi_scale_factor),
              std::ceil(basic_height / hidpi_scale_factor));

736
737
738
    SetMinSize(sz);
    // do not take decorations into account
    frame->SetMinSize(sz);
739
740
741
742
}

void GameArea::AdjustSize(bool force)
{
743
    AdjustMinSize();
744

745
746
    if (fullscreen)
        return;
747

748
749
750
    double hidpi_scale_factor = HiDPIScaleFactor();
    const wxSize newsz((std::ceil(basic_width  * gopts.video_scale) / hidpi_scale_factor),
                       (std::ceil(basic_height * gopts.video_scale) / hidpi_scale_factor));
751

752
    if (!force) {
753
        wxSize sz = GetClientSize();
754

755
756
757
        if (sz.GetWidth() >= newsz.GetWidth() && sz.GetHeight() >= newsz.GetHeight())
            return;
    }
758

759
760
761
    SetSize(newsz);
    GetParent()->SetClientSize(newsz);
    wxGetApp().frame->Fit();
762
763
764
765
}

void GameArea::ShowFullScreen(bool full)
{
766
767
768
769
770
771
772
773
    if (full == fullscreen) {
        // in case the tlw somehow lost its mind, force it to proper mode
        if (wxGetApp().frame->IsFullScreen() != fullscreen)
            wxGetApp().frame->ShowFullScreen(full);

        return;
    }

774
775
776
777
778
// on Mac maximize is native fullscreen, so ignore fullscreen requests
#ifdef __WXMAC__
    if (full && main_frame->IsMaximized()) return;
#endif

779
780
781
782
783
    fullscreen = full;

    // just in case screen mode is going to change, go ahead and preemptively
    // delete panel to be recreated immediately after resize
    if (panel) {
784
        panel->Destroy();
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
        panel = NULL;
    }

    // Windows does not restore old window size/pos
    // at least under Wine
    // so store them before entering fullscreen
    static bool cursz_valid = false;
    static wxSize cursz;
    static wxPoint curpos;
    MainFrame* tlw = wxGetApp().frame;
    int dno = wxDisplay::GetFromWindow(tlw);

    if (!full) {
        if (gopts.fs_mode.w && gopts.fs_mode.h) {
            wxDisplay d(dno);
            d.ChangeMode(wxDefaultVideoMode);
        }

        tlw->ShowFullScreen(false);

        if (!cursz_valid) {
            curpos = wxDefaultPosition;
            cursz = tlw->GetMinSize();
        }

        tlw->SetSize(cursz);
        tlw->SetPosition(curpos);
        AdjustMinSize();
    } else {
        // close all non-modal dialogs
        while (!tlw->popups.empty())
            tlw->popups.front()->Close();

818
819
820
821
        // Some kbd accels can send a menu open event without a close event,
        // this happens on Mac in HiDPI mode for the fullscreen toggle accel.
        main_frame->SetMenusOpened(false);

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
        // mouse stays blank whenever full-screen
        HidePointer();
        cursz_valid = true;
        cursz = tlw->GetSize();
        curpos = tlw->GetPosition();
        LowerMinSize();

        if (gopts.fs_mode.w && gopts.fs_mode.h) {
            // grglflargm
            // stupid wx does not do fullscreen properly when video mode is
            // changed under X11.   Since it does not use xrandr to switch, it
            // just changes the video mode without resizing the desktop.  It
            // still uses the original desktop size for fullscreen, though.
            // It also seems to stick the top-left corner wherever it pleases,
            // so I can't just resize the panel and expect it to show up.
            // ^(*&^^&!!!!  maybe just disable this code altogether on UNIX
            // most 3d cards are fine with full screen size, anyway.
            wxDisplay d(dno);

            if (!d.ChangeMode(gopts.fs_mode)) {
                wxLogInfo(_("Fullscreen mode %dx%d-%d@%d not supported; looking for another"),
                    gopts.fs_mode.w, gopts.fs_mode.h, gopts.fs_mode.bpp, gopts.fs_mode.refresh);
                // specifying a mode may not work with bpp/rate of 0
                // in particular, unix does Matches() in wrong direction
                wxArrayVideoModes vm = d.GetModes();
                int best_mode = -1;
                int i;

                for (i = 0; i < vm.size(); i++) {
                    if (vm[i].w != gopts.fs_mode.w || vm[i].h != gopts.fs_mode.h)
                        continue;

                    int bpp = vm[i].bpp;

                    if (gopts.fs_mode.bpp && bpp == gopts.fs_mode.bpp)
                        break;

                    if (!gopts.fs_mode.bpp && bpp == 32) {
                        gopts.fs_mode.bpp = 32;
                        break;
                    }

                    int bm_bpp = best_mode < 0 ? 0 : vm[i].bpp;

                    if (bpp == 32 && bm_bpp != 32)
                        best_mode = i;
                    else if (bpp == 24 && bm_bpp < 24)
                        best_mode = i;
                    else if (bpp == 16 && bm_bpp < 24 && bm_bpp != 16)
                        best_mode = i;
                    else if (!best_mode)
                        best_mode = i;
                }

                if (i == vm.size() && best_mode >= 0)
                    i = best_mode;

                if (i == vm.size()) {
                    wxLogWarning(_("Fullscreen mode %dx%d-%d@%d not supported"),
                        gopts.fs_mode.w, gopts.fs_mode.h, gopts.fs_mode.bpp, gopts.fs_mode.refresh);
                    gopts.fs_mode = wxVideoMode();

                    for (i = 0; i < vm.size(); i++)
                        wxLogInfo(_("Valid mode: %dx%d-%d@%d"), vm[i].w,
                            vm[i].h, vm[i].bpp,
                            vm[i].refresh);
                } else {
                    gopts.fs_mode.bpp = vm[i].bpp;
                    gopts.fs_mode.refresh = vm[i].refresh;
                }

                wxLogInfo(_("Chose mode %dx%d-%d@%d"),
                    gopts.fs_mode.w, gopts.fs_mode.h, gopts.fs_mode.bpp, gopts.fs_mode.refresh);

                if (!d.ChangeMode(gopts.fs_mode)) {
                    wxLogWarning(_("Failed to change mode to %dx%d-%d@%d"),
                        gopts.fs_mode.w, gopts.fs_mode.h, gopts.fs_mode.bpp, gopts.fs_mode.refresh);
                    gopts.fs_mode.w = 0;
                }
            }
        }

        tlw->ShowFullScreen(true);
    }
906
907
908
909
}

GameArea::~GameArea()
{
910
    UnloadGame(true);
911

912
913
    if (rewind_mem)
        free(rewind_mem);
914

915
916
917
918
919
920
    if (gopts.fs_mode.w && gopts.fs_mode.h && fullscreen) {
        MainFrame* tlw = wxGetApp().frame;
        int dno = wxDisplay::GetFromWindow(tlw);
        wxDisplay d(dno);
        d.ChangeMode(wxDefaultVideoMode);
    }
921
922
923
924
}

void GameArea::Pause()
{
925
926
    if (paused)
        return;
927

928
929
930
931
932
933
    // don't pause when linked
#ifndef NO_LINK
    if (GetLinkMode() != LINK_DISCONNECTED)
        return;
#endif

934
    paused = was_paused = true;
935

936
937
    if (loaded != IMAGE_UNKNOWN)
        soundPause();
938
939
940
941
}

void GameArea::Resume()
{
942
943
    if (!paused)
        return;
944

945
946
    paused = false;
    SetExtraStyle(GetExtraStyle() | wxWS_EX_PROCESS_IDLE);
947

948
949
    if (loaded != IMAGE_UNKNOWN)
        soundResume();
950

951
    SetFocus();
952
953
}

954
void GameArea::OnIdle(wxIdleEvent& event)
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
    wxString pl = wxGetApp().pending_load;

    if (pl.size()) {
        // sometimes this gets into a loop if LoadGame() called before
        // clearing pending_load.  weird.
        wxGetApp().pending_load = wxEmptyString;
        LoadGame(pl);
        MainFrame* mf = wxGetApp().frame;

        if (gdbBreakOnLoad)
            mf->GDBBreak();

        if (debugger && loaded != IMAGE_GBA) {
            wxLogError(_("Not a valid GBA cartridge"));
            UnloadGame();
        }
    }

    // stupid wx doesn't resize to screen size
    // forcing it this way just puts it in an infinite loop, though
    // with wx trying to resize/reposition to what it thinks is full screen
    // every time it detects a manual resize like this
    if (gopts.fs_mode.w && gopts.fs_mode.h && fullscreen) {
        wxSize sz = GetSize();

        if (sz.GetWidth() != gopts.fs_mode.w || sz.GetHeight() != gopts.fs_mode.h) {
            wxGetApp().frame->Move(0, 84);
            SetSize(gopts.fs_mode.w, gopts.fs_mode.h);
        }
    }
986

987
988
    if (!emusys)
        return;
989

990
991
992
993
994
    if (!panel) {
        switch (gopts.render_method) {
        case RND_SIMPLE:
            panel = new BasicDrawingPanel(this, basic_width, basic_height);
            break;
995
996
997
998
999
#ifdef __WXMAC__
        case RND_QUARTZ2D:
            panel = new Quartz2DDrawingPanel(this, basic_width, basic_height);
            break;
#endif
1000
#ifndef NO_OGL
1001
1002
1003
        case RND_OPENGL:
            panel = new GLDrawingPanel(this, basic_width, basic_height);
            break;
1004
1005
#endif
#ifdef __WXMSW__
1006
1007
1008
        case RND_DIRECT3D:
            panel = new DXDrawingPanel(this, basic_width, basic_height);
            break;
1009
#endif
1010
        }
1011

1012
        wxWindow* w = panel->GetWindow();
1013
1014
1015
1016
1017
1018
1019
1020
1021

        // set up event handlers
        // use both CHAR_HOOK and KEY_DOWN in case CHAR_HOOK does not work for whatever reason
        w->Connect(wxEVT_CHAR_HOOK,        wxKeyEventHandler(GameArea::OnKeyDown),         NULL, this);
        w->Connect(wxEVT_KEY_DOWN,         wxKeyEventHandler(GameArea::OnKeyDown),         NULL, this);
        w->Connect(wxEVT_KEY_UP,           wxKeyEventHandler(GameArea::OnKeyUp),           NULL, this);
        w->Connect(wxEVT_PAINT,            wxPaintEventHandler(GameArea::PaintEv),         NULL, this);
        w->Connect(wxEVT_ERASE_BACKGROUND, wxEraseEventHandler(GameArea::EraseBackground), NULL, this);
        w->Connect(wxEVT_SIZE,             wxSizeEventHandler(GameArea::OnSize),           NULL, this);
1022
        this->Connect(wxEVT_SIZE,          wxSizeEventHandler(GameArea::OnSize),           NULL, this);
1023

1024
1025
        w->SetBackgroundStyle(wxBG_STYLE_CUSTOM);
        w->SetSize(wxSize(basic_width, basic_height));
1026

1027
1028
1029
        if (maxScale)
            w->SetMaxSize(wxSize(basic_width * maxScale,
                basic_height * maxScale));
1030

1031
1032
1033
1034
        // if user changed Display/Scale config, this needs to run
        AdjustMinSize();
        AdjustSize(false);

1035
1036
        GetSizer()->Add(w, 1, gopts.retain_aspect ? (wxSHAPED | wxALIGN_CENTER) : wxEXPAND);
        Layout();
1037

1038
1039
        if (pointer_blanked)
            w->SetCursor(wxCursor(wxCURSOR_BLANK));
1040

1041
1042
        // set focus to panel
        w->SetFocus();
1043
    }
1044

1045
    if (!paused) {
1046
1047
        HidePointer();
        event.RequestMore();
1048

1049
1050
1051
        if (debugger) {
            was_paused = true;
            dbgMain();
1052

1053
1054
1055
1056
            if (!emulating) {
                emulating = true;
                UnloadGame();
            }
1057

1058
1059
            return;
        }
1060

1061
        emusys->emuMain(emusys->emuCount);
1062
#ifndef NO_LINK
1063

1064
1065
        if (loaded == IMAGE_GBA && GetLinkMode() != LINK_DISCONNECTED)
            CheckLinkConnection();
1066

1067
#endif
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
    } else {
        was_paused = true;

        if (paused)
            SetExtraStyle(GetExtraStyle() & ~wxWS_EX_PROCESS_IDLE);
    }

    if (do_rewind && emusys->emuWriteMemState) {
        if (!rewind_mem) {
            rewind_mem = (char*)malloc(NUM_REWINDS * REWIND_SIZE);
            num_rewind_states = next_rewind_state = 0;
        }

        if (!rewind_mem) {
            wxLogError(_("No memory for rewinding"));
            wxGetApp().frame->Close(true);
            return;
        }

        long resize;

        if (!emusys->emuWriteMemState(&rewind_mem[REWIND_SIZE * next_rewind_state],
                REWIND_SIZE, resize /* actual size */))
            // if you see a lot of these, maybe increase REWIND_SIZE
            wxLogInfo(_("Error writing rewind state"));
        else {
            if (!num_rewind_states) {
                MainFrame* mf = wxGetApp().frame;
                mf->cmd_enable |= CMDEN_REWIND;
                mf->enable_menus();
            }

            if (num_rewind_states < NUM_REWINDS)
                ++num_rewind_states;

            next_rewind_state = (next_rewind_state + 1) % NUM_REWINDS;
        }

        do_rewind = false;
    }
1108
1109
1110
1111
1112
1113
}

// Note: keys will get stuck if they are released while window has no focus
// can't really do anything about it, except scan for pressed keys on
// activate events.  Maybe later.

1114
1115
1116
1117
1118
static uint32_t bmask[NUM_KEYS] = {
    KEYM_UP, KEYM_DOWN, KEYM_LEFT, KEYM_RIGHT, KEYM_A, KEYM_B, KEYM_L, KEYM_R,
    KEYM_SELECT, KEYM_START, KEYM_MOTION_UP, KEYM_MOTION_DOWN, KEYM_MOTION_LEFT,
    KEYM_MOTION_RIGHT, KEYM_MOTION_IN, KEYM_MOTION_OUT, KEYM_AUTO_A, KEYM_AUTO_B, KEYM_SPEED, KEYM_CAPTURE,
    KEYM_GS
1119
1120
1121
1122
};

static wxJoyKeyBinding_v keys_pressed;

1123
static bool game_key_pressed()
1124
{
1125
1126
1127
1128
1129
1130
1131
1132
    bool game_key_pressed = false;

    for (int i = 0; i < 4; i++) {
        if (joypress[i] != 0) {
            game_key_pressed = true;
            break;
        }
    }
1133

1134
1135
1136
1137
1138
    return game_key_pressed;
}

static bool process_key_press(bool down, int key, int mod, int joy = 0)
{
Rafael Kitover's avatar
Rafael Kitover committed
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
    // modifier-only key releases do not set the modifier flag
    // so we set it here to match key release events to key press events
    switch (key) {
        case WXK_SHIFT:
            mod |= wxMOD_SHIFT;
            break;
        case WXK_ALT:
            mod |= wxMOD_ALT;
            break;
        case WXK_CONTROL:
            mod |= wxMOD_CONTROL;
            break;
1151
#ifdef __WXMAC__
Rafael Kitover's avatar
Rafael Kitover committed
1152
1153
1154
        case WXK_RAW_CONTROL:
            mod |= wxMOD_RAW_CONTROL;
            break;
1155
#endif
Rafael Kitover's avatar
Rafael Kitover committed
1156
1157
    }

1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
    // check if key is already pressed
    int kpno;

    for (kpno = 0; kpno < keys_pressed.size(); kpno++)
        if (keys_pressed[kpno].key == key && keys_pressed[kpno].mod == mod && keys_pressed[kpno].joy == joy)
            break;

    if (kpno < keys_pressed.size()) {
        // double press is noop
        if (down)
1168
            return game_key_pressed();
1169
1170
1171
1172
1173
1174

        // otherwise forget it
        keys_pressed.erase(keys_pressed.begin() + kpno);
    } else {
        // double release is noop
        if (!down)
1175
1176
            // we will just mark it processed so it is ignored, this is not entirely correct
            return true;
1177
1178
1179
1180
1181
1182
1183
1184

        // otherwise remember it
        // c++0x
        // keys_pressed.push_back({ key, mod, joy });
        wxJoyKeyBinding jb = { key, mod, joy };
        keys_pressed.push_back(jb);
    }

1185
    bool game_key_released = false;
1186

1187
1188
1189
1190
1191
1192
1193
    // find all game keys this is bound to
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < NUM_KEYS; j++) {
            wxJoyKeyBinding_v& b = gopts.joykey_bindings[i][j];

            for (int k = 0; k < b.size(); k++)
                if (b[k].key == key && b[k].mod == mod && b[k].joy == joy) {
1194
                    if (down) {
Rafael Kitover's avatar
Rafael Kitover committed
1195
                        // press button
1196
                        joypress[i] |= bmask[j];
1197
                    }
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
                    else {
                        // only release if no others pressed
                        int k2;

                        for (k2 = 0; k2 < b.size(); k2++) {
                            if (k == k2 || (b[k2].key == key && b[k2].mod == mod && b[k2].joy == joy))
                                continue;

                            for (kpno = 0; kpno < keys_pressed.size(); kpno++)
                                if (keys_pressed[kpno].key == b[k2].key && keys_pressed[kpno].mod == b[k2].mod && keys_pressed[kpno].joy == b[k2].joy)
                                    break;

                            if (kpno < keys_pressed.size())
                                break;
                        }

1214
                        if (k2 == b.size()) {
Rafael Kitover's avatar
Rafael Kitover committed
1215
                            // release button
1216
                            joypress[i] &= ~bmask[j];
1217
                            game_key_released = true;
1218
                        }
1219
1220
1221
1222
1223
                    }

                    break;
                }
        }
1224

1225
1226
1227
1228
1229
1230
    if (down) {
        return game_key_pressed();
    }
    else {
        return game_key_released;
    }
1231
1232
}

1233
1234
1235
1236
1237
1238
1239
1240
1241
static void draw_black_background(wxWindow* win) {
    wxClientDC dc(win);
    wxCoord w, h;
    dc.GetSize(&w, &h);
    dc.SetPen(*wxBLACK_PEN);
    dc.SetBrush(*wxBLACK_BRUSH);
    dc.DrawRectangle(0, 0, w, h);
}

1242
void GameArea::OnKeyDown(wxKeyEvent& ev)
1243
{
1244
1245
1246
1247
1248
1249
1250
1251
    if (process_key_press(true, ev.GetKeyCode(), ev.GetModifiers())) {
        ev.Skip(false);
        ev.StopPropagation();
        wxWakeUpIdle();
    }
    else {
        ev.Skip(true);
    }
1252
1253
}

1254
void GameArea::OnKeyUp(wxKeyEvent& ev)
1255
{
1256
1257
1258
1259
1260
1261
1262
1263
    if (process_key_press(false, ev.GetKeyCode(), ev.GetModifiers())) {
        ev.Skip(false);
        ev.StopPropagation();
        wxWakeUpIdle();
    }
    else {
        ev.Skip(true);
    }
1264
1265
}

1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
// these three are forwarded to the DrawingPanel instance
void GameArea::PaintEv(wxPaintEvent& ev)
{
    panel->PaintEv(ev);
}

void GameArea::EraseBackground(wxEraseEvent& ev)
{
    panel->EraseBackground(ev);
}

void GameArea::OnSize(wxSizeEvent& ev)
{
1279
1280
1281
    draw_black_background(this);
    if (panel)
        panel->OnSize(ev);
1282
1283
}

1284
void GameArea::OnSDLJoy(wxSDLJoyEvent& ev)
1285
{
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
    int key = ev.GetControlIndex();
    int mod = wxJoyKeyTextCtrl::DigitalButton(ev);
    int joy = ev.GetJoy() + 1;

    // mutually exclusive key types unpress their opposite
    if (mod == WXJB_AXIS_PLUS) {
        process_key_press(false, key, WXJB_AXIS_MINUS, joy);
        process_key_press(ev.GetControlValue() != 0, key, mod, joy);
    } else if (mod == WXJB_AXIS_MINUS) {
        process_key_press(false, key, WXJB_AXIS_PLUS, joy);
        process_key_press(ev.GetControlValue() != 0, key, mod, joy);
    } else if (mod >= WXJB_HAT_FIRST && mod <= WXJB_HAT_LAST) {
1298
1299
1300
1301
1302
        int value = ev.GetControlValue();
        process_key_press(value & SDL_HAT_UP, key, WXJB_HAT_N, joy);
        process_key_press(value & SDL_HAT_DOWN, key, WXJB_HAT_S, joy);
        process_key_press(value & SDL_HAT_RIGHT, key, WXJB_HAT_E, joy);
        process_key_press(value & SDL_HAT_LEFT, key, WXJB_HAT_W, joy);
1303
1304
    } else
        process_key_press(ev.GetControlValue() != 0, key, mod, joy);
1305
1306
1307
}

BEGIN_EVENT_TABLE(GameArea, wxPanel)
1308
1309
1310
1311
1312
EVT_IDLE(GameArea::OnIdle)
EVT_SDLJOY(GameArea::OnSDLJoy)
// FIXME: wxGTK does not generate motion events in MainFrame (not sure
// what to do about it)
EVT_MOUSE_EVENTS(GameArea::MouseEvent)
1313
1314
END_EVENT_TABLE()

1315
1316
DrawingPanelBase::DrawingPanelBase(int _width, int _height)
    : width(_width)
1317
1318
    , height(_height)
    , scale(1)
Su Yong's avatar
Su Yong committed
1319
    , did_init(false)
1320
1321
1322
1323
1324
    , todraw(0)
    , pixbuf1(0)
    , pixbuf2(0)
    , rpi(0)
    , nthreads(0)
1325
{
1326
    memset(delta, 0xff, sizeof(delta));
1327

1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
    if (gopts.filter == FF_PLUGIN) {
        do // do { } while(0) so break; exits entire block
        {
            // could've also just used goto & a label, I guess
            gopts.filter = FF_NONE; // preemptive in case of errors
            systemColorDepth = 32;

            if (gopts.filter_plugin.empty())
                break;

            wxFileName fpn(gopts.filter_plugin);
            fpn.MakeAbsolute(wxStandardPaths::Get().GetPluginsDir());

            if (!filt_plugin.Load(fpn.GetFullPath(), wxDL_VERBATIM | wxDL_NOW))
                break;

            RENDPLUG_GetInfo gi = (RENDPLUG_GetInfo)filt_plugin.GetSymbol(wxT("RenderPluginGetInfo"));

            if (!gi)
                break;

            // need to be able to write to _rpi to set Output() and Flags
            RENDER_PLUGIN_INFO* _rpi = gi();

            // FIXME: maybe < RPI_VERSION, assuming future vers. back compat?
            if (!_rpi || (_rpi->Flags & 0xff) != RPI_VERSION || !(_rpi->Flags & (RPI_555_SUPP | RPI_888_SUPP)))
                break;

            _rpi->Flags &= ~RPI_565_SUPP;

            if (_rpi->Flags & RPI_888_SUPP) {
                _rpi->Flags &= ~RPI_555_SUPP;
                // FIXME: should this be 32 or 24?  No docs or sample source
                systemColorDepth = 32;
            } else
                systemColorDepth = 16;

            if (!_rpi->Output)
                // note that in actual kega fusion plugins, rpi->Output is
                // unused (as is rpi->Handle)
                _rpi->Output = (RENDPLUG_Output)filt_plugin.GetSymbol(wxT("RenderPluginOutput"));

1370
            scale *= (_rpi->Flags & RPI_OUT_SCLMSK) >> RPI_OUT_SCLSH;
1371
1372
1373
1374
            rpi = _rpi;
            gopts.filter = FF_PLUGIN; // now that there is a valid plugin
        } while (0);
    } else {
1375
        scale *= builtin_ff_scale(gopts.filter);
1376
#define out_16 (systemColorDepth == 16)
1377
1378
        systemColorDepth = 32;
    }
1379

1380
1381
    // Intialize color tables
    if (systemColorDepth == 32) {
1382
#if wxBYTE_ORDER == wxLITTLE_ENDIAN
1383
1384
1385
1386
        systemRedShift = 3;
        systemGreenShift = 11;
        systemBlueShift = 19;
        RGB_LOW_BITS_MASK = 0x00010101;
1387
#else
1388
1389
1390
1391
        systemRedShift = 27;
        systemGreenShift = 19;
        systemBlueShift = 11;
        RGB_LOW_BITS_MASK = 0x01010100;
1392
#endif
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
    } else {
        // plugins expect RGB in native byte order
        systemRedShift = 10;
        systemGreenShift = 5;
        systemBlueShift = 0;
        RGB_LOW_BITS_MASK = 0x0421;
    }

    // FIXME: should be "true" for GBA carts if lcd mode selected
    // which means this needs to be re-run at pref change time
    utilUpdateSystemColorMaps(false);
1404
1405
}

1406
1407
DrawingPanel::DrawingPanel(wxWindow* parent, int _width, int _height)
    : DrawingPanelBase(_width, _height)
1408
    , wxPanel(parent, wxID_ANY, wxPoint(0, 0), parent->GetClientSize(),
1409
          wxFULL_REPAINT_ON_RESIZE | wxWANTS_CHARS)
1410
{
1411
}
1412

1413
1414
void DrawingPanelBase::DrawingPanelInit()
{
1415
1416
1417
    did_init = true;
}

1418
void DrawingPanelBase::PaintEv(wxPaintEvent& ev)
1419
{